Onboarding guide
15. Common UI Framework (MudBlazor components, theme, base pages)
What this chapter covers. MMCA.Common.UI is the Blazor presentation package, and it is one of
the two layers (with Grpc) allowed to reference Shared only: its single ProjectReference is
MMCA.Common.Shared (MMCA.Common.UI/MMCA.Common.UI.csproj:42), and every other dependency is a
NuGet package (MudBlazor, Polly, the SignalR client, Scrutor, QRCoder, FeatureManagement,
System.IdentityModel.Tokens.Jwt, MMCA.Common.UI.csproj:19-37). It touches no Application, Domain
or Infrastructure type, which is exactly what lets it compile into a Blazor WebAssembly bundle and
into a .NET MAUI hybrid head (see primer §1). What it ships is the
set of reusable parts every consumer UI assembles pages from: a server-paged data-grid list-page
base class, the brand MudBlazor theme, a Result-returning typed HTTP service base for
talking to the WebAPI, the authentication and token-refresh
boundary, list-page state preservation across navigation, vendor-neutral toast and dialog
facades, a pluggable UI-module contract, an end-to-end localization pipeline, drop-in role
and user administration screens, a turnkey notification inbox / push / live-channel feature, and
opt-in two-factor, offline write queue and in-app diagnostics features.
A second, thinner package MMCA.Common.UI.Web sits above it and holds the pieces that need an ASP.NET
pipeline (server-side token storage, the Blazor Content-Security-Policy provider, the
trusted-caller header an SSR host stamps on its gateway calls, and the host's own edge rate limiter
and ceiling on open circuits, plus an opt-in same-origin API proxy that keeps every token out of script, and the service worker that makes a host an installable web app). The per-app and per-module Razor pages in the consumer apps
(chapter 21) derive from and consume these primitives, and the same
components render across Blazor Server, WebAssembly and MAUI with no per-platform reimplementation.
[Rubric §18, UI Architecture & Component Design] assesses component reuse, separation of
presentation from data access, and whether there is a coherent composition model; nearly every type
in this group exists so a consumer page is composed rather than hand-rolled, which is the shape
ADR-067 records.
The data-access boundary: a Result contract over one named HttpClient. A page never touches
HttpClient, and it never catches an exception to learn what the server said. It depends on
IEntityService<TEntityDTO, TIdentifierType>
(MMCA.Common.UI/Common/Interfaces/IEntityService.cs:20), whose seven CRUD members every one return
a Result or Result<T>
(IEntityService.cs:25-66), and it gets its behavior from the abstract
EntityServiceBase<TEntityDTO, TIdentifierType>
(MMCA.Common.UI/Services/Api/EntityServiceBase.cs:35), which derives in turn from
AuthenticatedServiceBase
(MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:17). That base owns the cross-cutting concerns
of an outbound call. First, a Polly retry policy: 3 retries with exponential backoff (0.5s, 1s, 2s)
plus up to 250 ms of random jitter so a fleet of clients does not re-converge on the same instant
(AuthenticatedServiceBase.cs:25-41, :356-364, :412-413), over a deliberate retryable set rather than "any
5xx", since 501 and 505 are permanent verdicts and are excluded while 408 and 429 are explicit
invitations to come back (AuthenticatedServiceBase.cs:259-292). A 429 that names a Retry-After is waited out for exactly that long instead of the backoff, and is not retried at all when it asks for more than HttpResilienceDefaults.MaxRetryAfterWait, since the rate-limit window will not reset within any wait worth holding the user for (:34-37, :269-271, :280-283, :367-385). A POST or PATCH is replayed only
when its request carried an Idempotency-Key, because re-sending a write the server cannot dedupe
could apply it twice (:285-288, :294-318); a transport failure on such a write is retried only when it failed before the request was sent (name resolution, the TCP connect, the TLS handshake), which AuthDelegatingHandler records on the exception because the exception arm of the policy sees no request (:320-352). The policy's onRetry disposes each
superseded response, because Polly hands the caller only the final outcome and an undisposed 5xx
leaks its content buffer and holds its connection out of the pool under exactly the sustained failure
the retries exist to survive (AuthenticatedServiceBase.cs:391-398, :415-419). Second, a helper that creates a
"APIClient" HttpClient from IHttpClientFactory and stamps the JWT Bearer token onto it from
ITokenStorageService, swallowing the InvalidOperationException that JS
interop throws during SSR prerender (AuthenticatedServiceBase.cs:67-83, :91-94); a sibling
CreateClientWithToken builds a client around an explicitly supplied token so a request the API
answered 401 can be replayed with one acquired straight from ITokenRefresher
rather than resending the token the server just rejected (AuthenticatedServiceBase.cs:130-145).
The same policy object is reachable without inheritance: IdempotentReadRetry
(MMCA.Common.UI/Services/Api/IdempotentReadRetry.cs:18) hands anonymous lookup services the exact
instance the base exposes to its subclasses, so the two paths cannot drift, and its only entry point
is a GET because re-sending is safe only for an idempotent read (IdempotentReadRetry.cs:9-16, :24,
:35-44, AuthenticatedServiceBase.cs:48-52). Its read-side sibling PagedReadAll
(MMCA.Common.UI/Services/Api/PagedReadAll.cs:18) exists because a single read truncates silently at
the API's page-size maximum: it pages a /paged endpoint in stable id order with a PageSize of 500
until the server's reported total is reached, hands back the first failure unchanged, and stops after
40 pages (20,000 rows) whatever the server claims (PagedReadAll.cs:12-18, :22, :28, :43-46,
:57-90).
Retry and idempotency are coupled on purpose: NewIdempotencyKey()
(AuthenticatedServiceBase.cs:65) is generated once per logical write and set as a default header
on the single client that serves every attempt (EntityServiceBase.cs:152-159, :323-334), so a
retried create dedupes on the server instead of producing a duplicate row (the server half is
IdempotencyHeaders and
IdempotentAttribute,
ADR-017). Creates and updates
both carry a key, and deletes carry none (EntityServiceBase.cs:16, :199-208). Updates also carry
a precondition: ConcurrencyTagOf renders a DTO's RowVersion as a weak entity tag when the DTO
implements IConcurrencyAware, and that tag
travels as the If-Match header on the same per-operation client, so every retry states the same
precondition instead of a later attempt succeeding against a version the user never saw
(EntityServiceBase.cs:163-196, :336-345,
ADR-035). The two travel
together on purpose: a PUT whose first attempt landed and only lost its response is replayed by the
server's idempotency filter as the stored 204, instead of being re-run against the version it just
replaced and answered with a 412 telling the user someone else changed the item
(EntityServiceBase.cs:175-184, :338-343). Responses come back
in the same PagedCollectionResult<T> /
CollectionResult<T> envelopes the API
returns, and both SendRequestAsync overloads read the response through
ProblemDetailsResultReader
(EntityServiceBase.cs:271, :286, :301, :314), so a 404 arrives as an
ErrorType.NotFound failure, a rejection as
Validation, a 500 as Unexpected, each carrying the server's own text. What the reader cannot
convert is the absence of a response, and that is
HttpResultExecutor's job
(MMCA.Common.UI/Services/Api/HttpResultExecutor.cs:35): it wraps each call, turns a refused connection,
a broken stream or an unreadable body into Http.TransportFailure and a client-side timeout into
Http.Timeout (HttpResultExecutor.cs:38, :41, :135-136), and rethrows an
OperationCanceledException only when the caller's own token asked for it, because a page owns
its cancellation and must not have a disposed component reported back as an error to render
(HttpResultExecutor.cs:69-75, :104-110). Many-to-many join endpoints, which have POST and DELETE but no
standalone reads, get their own thinner base, ChildEntityServiceBase
(MMCA.Common.UI/Services/Api/ChildEntityServiceBase.cs:18), whose DeleteByIdAsync reports a missing
join row as a NotFound failure so "nothing to remove" stays distinguishable from "the remove
failed" (ChildEntityServiceBase.cs:66-83). The page-side half of the same transport is
ResultUiExtensions
(MMCA.Common.UI/Common/ResultUiExtensions.cs:75): TryGetValue unwraps inside a conditional the way
Dictionary.TryGetValue does, branching on IsFailure rather than on a null so a failed
(Items, TotalItems) tuple is not read as a success (ResultUiExtensions.cs:87-103), and the
rendering helpers look every message up as a resource key with pass-through, de-duplicate ordinally,
and order most severe first so a real 403 or 500 leads and an incidental validation line never buries it
(ResultUiExtensions.cs:36-38, :142-145). [Rubric §3, Clean Architecture] and [Rubric §9, API & Contract Design]: the UI binds to a DTO contract and an interface, never to server internals, and the wire
envelope is uniform across every entity. [Rubric §29, Resilience] is the retry, jitter, idempotency
and precondition set. The contract itself is recorded in
ADR-094, and the retirement
of the old exception-throwing UI deviation in
ADR-013.
The list page: DataGridListPageBase<TDto>. This is the most concept-dense type in the group and
the centerpiece of the compose-do-not-repeat thesis. Every list screen in every consumer app derives
from DataGridListPageBase<TDto>
(MMCA.Common.UI/Pages/Common/DataGridListPageBase.cs:24), a ComponentBase that encapsulates what
would otherwise be copy-pasted onto each page: server-side paging against MudDataGrid<T>,
CancellationTokenSource lifecycle, loading state, filter and sort extraction from MudBlazor's
GridState<T>, error surfacing through the toast facade, a LoadFailed flag so a failed fetch
renders an inline retry instead of a misleading "no records" empty state
(DataGridListPageBase.cs:54, set at :922 and :943), viewport-driven mobile versus desktop
rendering (it implements IBrowserViewportObserver and flips IsMobile through
BreakpointConstants at the 960 px sidebar-collapse boundary,
DataGridListPageBase.cs:24, :339, and
MMCA.Common.UI/Common/BreakpointConstants.cs:16-17; until the first viewport notification arrives
IsLayoutKnown stays false, and the base exposes it through the internal
IListLayoutSource, MMCA.Common.UI/Components/Lists/IListLayoutSource.cs:9,
DataGridListPageBase.cs:87, :90, which
ListPageShell<TItem> reads off its ServerData callback's target when the
page passes no IsLayoutKnown of its own, so every list page wired through the shell holds back both
layouts until it knows which to render, without a markup change,
MMCA.Common.UI/Components/Lists/ListPageShell.razor.cs:84, :167, IListLayoutSource.cs:3-8), a persisted dense-density toggle
(DataGridListPageBase.cs:106), and a careful IAsyncDisposable/IDisposable teardown. The fetch
path is Result-shaped end to end: a failed page toasts through
NotifyOnFailure(Toast, Localizer) and returns an empty grid rather than throwing
(DataGridListPageBase.cs:942-943). It also solves a Blazor render-mode problem: grid data captured
during SSR prerender is persisted through PersistentComponentState as a private
PersistedGridState record (DataGridListPageBase.cs:1372), restored in
OnInitialized (:203) and re-registered for persisting with an explicit
RenderMode.InteractiveAuto, because a page that inherits its render mode from <Routes> gives the
framework nothing to associate the callback with (DataGridListPageBase.cs:215-225,
ADR-056). A
PrerenderFetchTimeoutMs of 5000 caps how long prerender may block on a cold backend before falling
back to an empty grid the first interactive fetch refills (DataGridListPageBase.cs:112, applied at
:991). That fetch links the timeout to the page's own lifetime token, read through
ComponentLifetimeExtensions.LifetimeToken
(DataGridListPageBase.cs:987-988, MMCA.Common.UI/Common/ComponentLifetimeExtensions.cs:18, :26):
reading Token off a disposed CancellationTokenSource throws ObjectDisposedException, so a load
that resumed after the user navigated away would crash the circuit, whereas the extension returns an
already-cancelled token and the work stops through its ordinary cancellation path
(ComponentLifetimeExtensions.cs:3-11, :28-41). LatestLoadGuard and DetailPageBase read their
tokens the same way (LatestLoadGuard.cs:58, DetailPageBase.cs:38), and
LifetimeTokenConventionTestsBase pins the rule in each repo (ComponentLifetimeExtensions.cs:13-14). [Rubric §23, Front-End Performance & Rendering] assesses render efficiency and avoided
round-trips; this persist-and-restore dance is that concern made concrete. Around the base sit three
smaller helpers that are deliberately not members of it, so a page composing its own layout can
still use them: ListPageActions
(MMCA.Common.UI/Pages/Common/ListPageActions.cs:14) holds the mobile-versus-desktop reload dispatch
and the confirm-delete-reload flow every organizer list page repeats (:25-38, :56);
LatestLoadGuard (MMCA.Common.UI/Common/LatestLoadGuard.cs:38) gives each load
a generation and a token and cancels the previous one, which is what keeps a routed detail component
(reused by Blazor across route-parameter changes) from rendering entity 100's late answer after the
user has navigated to 101 (LatestLoadGuard.cs:50-59, :67); and
OfflineFirstPageSnapshot<TItem>
(MMCA.Common.UI/Pages/Common/OfflineFirstPageSnapshot.cs:30) records the first page of a list into
ILocalCacheStore as a private
CachedPage record (:39) and serves it back only when the device reports itself
offline, the store is available and the request is page 1, so the live path is untouched
(OfflineFirstPageSnapshot.cs:43, :49, :67). The single-aggregate counterpart of the list base
is DetailPageBase
(MMCA.Common.UI/Pages/Common/DetailPageBase.cs:28), an abstract ComponentBase that owns what
every detail page loaded by route id otherwise repeats: a page-scoped PageToken that cancels
in-flight work when the page goes away (:38), a LatestLoadGuard for route-driven reloads (:45),
and the inline edit lifecycle, where BeginEdit and EndEdit both reset IsDirty so the flag an
unsaved-changes guard reads can never be left set behind a closed editor (:98-101, :120-131,
rationale at :17-21). The load reports where it stands through the DetailLoadState enum (MMCA.Common.UI/Components/PageState/DetailLoadState.cs:8): BeginLoad supersedes the load in flight and puts the page back in Loading, and CompleteLoad records Loaded on success, NotFound for a not-found failure and Failed for any other, or leaves the state alone when a newer load has superseded it (DetailPageBase.cs:52, :59-64, :78-95). The two failure states are separate on purpose: a load that failed on venue Wi-Fi is the common case, and telling the reader the record is missing tells them not to try again (DetailLoadState.cs:3-7, :16-20). A derived page keeps only its load, its edit-model copy and its save, and
releases its own disposables in a Dispose(bool) override that calls the base last (:24-25,
:138-153). [Rubric §22, Responsive & Cross-Browser] is named by BreakpointConstants and exercised by
MobileInfiniteScrollList<TItem>
(MMCA.Common.UI/Components/Lists/MobileInfiniteScrollList.razor.cs:20), the mobile card list whose
IntersectionObserver sentinel, 500-item MaxRenderedItems cap (:52) and generation-guarded
supersession of in-flight fetches keep a long list bounded; a page that wants infinite scroll without
giving up its own card markup renders InfiniteScrollSentinel alone
(MMCA.Common.UI/Components/Lists/InfiniteScrollSentinel.razor.cs:21), which owns just the observer and is
disposed by the renderer the moment the host stops rendering it (:6-20). Both delegate the JS half to
the internal InfiniteScrollObserver<TOwner>
(MMCA.Common.UI/Components/Lists/InfiniteScrollObserver.cs:17, created at
MobileInfiniteScrollList.razor.cs:115 and InfiniteScrollSentinel.razor.cs:59): one
infinite-scroll.js module imported single-flight through LazyJsModule, since Blazor does not
serialize OnAfterRenderAsync and an unguarded ??= would import twice and leak the overwritten
instance, and one IntersectionObserver that calls the owner's OnSentinelVisible. Every call is best
effort, so a torn-down circuit or a call the browser refuses leaves the list at the pages already
loaded rather than escaping the owner's render (InfiniteScrollObserver.cs:7-13, :20-27,
:62-69), and an owner disposed while the import is still in flight releases the late module instead
of attaching an observer nobody would detach (:46-54).
State preservation across navigation. Paging, sort, filters and density live in the URL query
string as the source of truth, encoded and decoded by
ListPageQueryStateService under deliberately short reserved keys (p,
ps, mp, s, sd, d, q, f:<name>) with defaults omitted so a pristine list page has a clean
URL (MMCA.Common.UI/Services/ListPageQueryStateService.cs:15-43), so deep links and browser
back/forward replay correctly. The noisier scroll offset lives in
ListPageStateService
(MMCA.Common.UI/Services/ListPageStateService.cs:71), a per-circuit scoped service whose
synchronous dictionary is the fast path and whose HydrateFromSessionAsync
(ListPageStateService.cs:103) / PersistToSessionAsync (:138) mirror entries through
sessionStorage via a nav-interop.js module (:65) so state survives circuit teardown, forceLoad
navigation and the SSR to WASM transition. Every JS path there is defensively caught (prerender,
disconnected circuit, Safari private mode) so storage can never break the page. The immutable
ListPageState record (ListPageStateService.cs:9) carries page, page size, mobile
page, scroll, sort, density and a page-specific filter dictionary, and is updated with with
expressions. [Rubric §19, State Management & Data Flow] assesses a deliberate, scoped state model rather than ambient globals: these are
registered Scoped, so each circuit gets its own instance
(MMCA.Common.UI/DependencyInjection.cs:225-226). [Rubric §25, Navigation & Information Architecture] covers the route catalogue (RoutePaths
(MMCA.Common.UI/Common/RoutePaths.cs:7), NavItem with its role, claim, permission,
section and group facets plus resource-key titles resolved per circuit
(MMCA.Common.UI/Common/NavItem.cs:20), and the NavSection enum whose declaration
order is the sidebar order, MMCA.Common.UI/Common/NavSection.cs:7-17) and the open-redirect guard
ReturnUrlProtector, which accepts only same-origin relative paths beginning
with a single forward slash and rejects protocol-relative forms, backslashes, control characters and
anything that does not parse as a relative URI, replacing each with a fallback
(MMCA.Common.UI/Services/Navigation/ReturnUrlProtector.cs:18-60).
Authentication, the host-polymorphic token refresh, and the devices page. Client-side auth is
contracted by IAuthUIService
(MMCA.Common.UI/Services/Auth/IAuthUIService.cs:17), whose members are Result-returning like the
entity services, and implemented by AuthUIService
(MMCA.Common.UI/Services/Auth/AuthUIService.cs:49), which calls the WebAPI auth/* endpoints,
persists tokens through ITokenStorageService, pushes auth-state changes
through JwtAuthenticationStateProvider so AuthorizeView reacts
immediately, and coordinates push-registration through the device-capability contract
IPushRegistrationService
(AuthUIService.cs:49). Two named codes make its local-only failures legible rather than null:
Auth.TokenStorageUnavailable when the sign-in succeeded but JS interop could not persist the tokens,
and Auth.MissingAccessToken when a 2xx carried no usable token, which means the response shape
drifted (AuthUIService.cs:57, :63). The provider round trip is bound to the client that started
it: OAuthFlowStateStore
(MMCA.Common.UI/Services/Auth/OAuth/OAuthFlowStateStore.cs:20) mints a 32-character random hex value
before the challenge and persists it to device-local storage under auth.oauth-flow as a private
PendingAttempt record, optionally carrying the flow's code verifier, inside a
private PendingAttempts list that keeps at most five live attempts so two tabs or
a retry click each keep their own (:23, :25-29, :101-105, :172, :174). It reads the list
back after writing and throws before the redirect when the store accepted the write without keeping
it (storage full, blocked or private mode), so the page can explain instead of the completion failing
silently one redirect later (:51-55, :107-114). A completion is accepted only when its returned
state matches a live attempt younger than the 10-minute lifetime; only that attempt is removed, so a
stray or forged completion is refused without consuming another tab's attempt, an absent state is
refused, and one value is redeemable exactly once (:35, :119-156, :160-163). The reason that
matters is stated on the type: the completion code is a bearer value, so without a binding an attacker
can complete the provider flow with their own account and hand the victim the completion link, signing
the victim's app in as the attacker (OAuthFlowStateStore.cs:8-16). A host with no durable storage at
all reports IsEnforced false and fails closed: no attempt can be started and every completion is
refused, because nothing can be written across the redirect (:39-44, :96-99, :134-139). Alongside login, register, OAuth exchange, logout, refresh and
change-password, it carries the self-service reset pair (IAuthUIService.cs:60, :67,
ADR-091) and the
multi-device session pair: GetSessionsAsync lists the caller's live refresh sessions newest first
and RevokeSessionAsync ends one of them (IAuthUIService.cs:75, :84,
ADR-097). Those two are
rendered by the framework-owned Sessions page
(MMCA.Common.UI/Pages/Auth/Sessions.razor.cs:29), reachable at /profile/sessions
(RoutePaths.cs:16), which deliberately offers two revoke paths: a per-row sign-out that ends one
other device's session, and a page-level sign-out-everywhere that also ends the caller's own and is
therefore followed by the local logout and a redirect. The current device's row carries no button at
all, since revoking it from here would leave the app signed in on a dead session until the access
token expired (Sessions.razor.cs:15-27, the guard at :125). The page-level path is
RevokeAllSessionsAsync, which signs out locally only once the server confirmed the revoke
(IAuthUIService.cs:94), run through SignOutNavigator
(MMCA.Common.UI/Services/Navigation/SignOutNavigator.cs:30, call at Sessions.razor.cs:246). That
scoped service (MMCA.Common.UI/DependencyInjection.cs:199) exists because a sign-out followed by a
forced navigation races: the auth flip re-renders an [Authorize] page into RedirectToLogin, whose
own forced navigation to the login page reaches the browser first and the caller's destination is
lost (SignOutNavigator.cs:7-14). It sets IsSigningOut for the round trip, which RedirectToLogin
reads to stand down (:36, MMCA.Common.UI/Components/Auth/RedirectToLogin.razor:12), then issues
the one forced navigation to a destination sanitized through ReturnUrlProtector (:69-73); the
claim is never released on success, since the forced load discards the scope, while a failed or
throwing sign-out releases it and navigates nowhere (:15-22, :56-62, :79-89). MainLayout,
NavMenu, BiometricGate, TermsAcceptanceGate and the two-factor account page sign out the same
way (MMCA.Common.UI/Layout/MainLayout.razor:218, MMCA.Common.UI/Layout/NavMenu.razor.cs:70,
MMCA.Common.UI/Components/Capabilities/BiometricGate.razor.cs:270,
MMCA.Common.UI/Components/Legal/TermsAcceptanceGate.razor.cs:237,
MMCA.Common.UI/Pages/Auth/TwoFactor/TwoFactorAccount.razor.cs:319). One busy flag disables every button while any revoke is in flight, so a
second click cannot race the list rebuild (Sessions.razor.cs:55-59). Each row is labelled through
UserAgentSummary
(MMCA.Common.UI/Services/Auth/Devices/UserAgentSummary.cs:21), which extracts a browser and a
platform from the raw header with the most specific token winning (every Chromium browser also says
"Chrome", and Chrome and Edge both say "Safari", UserAgentSummary.cs:22-40, :85-93) and keeps the
two parts separate until a resource format joins them, because composing "Chrome on Windows" in
code would hard-code English word order (UserAgentSummary.cs:15-18, :118-124). Its Describe
reads a native app header before the browser tokens, since an app's WebView also says "Chrome/"
(:95-114). That header is built by AppUserAgent
(MMCA.Common.UI/Services/Auth/Devices/AppUserAgent.cs:10), whose Build produces a value such as
AtlDevCon/1.9.2 (Android 15; MmcaApp) around the MmcaApp marker (:7, :13, :29-49): the app
name and version are folded to RFC 9110 tokens and the platform and OS to header-comment text, so a
display name with accents, spaces or parentheses cannot break the header, and MAUI's WinUI and
MacCatalyst head names become Windows and macOS (:55-65, :67-77, :110-112); the MAUI head
stamps it from MauiAppUserAgentHandler
(MMCA.Common.UI.Maui/Services/MauiAppUserAgentHandler.cs:21). The same label serves an
administrator: UserSessionsTable
(MMCA.Common.UI/Components/Auth/UserSessionsTable.razor.cs:21) is a read-only table of one
account's live sessions (device, IP address, signed in, expires) with no sign-out and no row marked as
the current device, because an administrator is never on the viewed user's device, and it renders the
instants on the viewer's clock through ViewerTimeZone exactly as the page does (:11-20, :42-49,
:69-74).
Email confirmation
(ADR-116) ships the same
way, as a framework page over a framework client. IEmailConfirmationUIService
(MMCA.Common.UI/Services/Auth/IEmailConfirmationUIService.cs:22) is a separate interface rather than
two new IAuthUIService members, so a consumer's own IAuthUIService implementation keeps compiling
(MMCA.Common.UI/DependencyInjection.cs:201-203). Its two anonymous, Result-returning calls redeem a
link's single-use token and ask for a fresh link, the latter answering success on any well-formed
request because the endpoint returns 202 whether or not the address holds an account
(IEmailConfirmationUIService.cs:28, :30-38). The in-box
EmailConfirmationUIService
(MMCA.Common.UI/Services/Auth/EmailConfirmationUIService.cs:22) is deliberately not built on the
entity-service bases: the token is single-use and the resend spends a per-address request budget, so
a retried POST could only spend either one twice. It takes the "APIClient" straight from the factory,
posts exactly once and reads the answer through ProblemDetailsResultReader inside
HttpResultExecutor (EmailConfirmationUIService.cs:13-21, :35-48). The anonymous
ConfirmEmail page (MMCA.Common.UI/Pages/Auth/ConfirmEmail.razor.cs:46, routed at
/confirm-email, ConfirmEmail.razor:1) reads the email and token from the URI fragment, which
a browser never sends to a server, so the live token stays out of ingress logs, request telemetry
and Referer headers; the locationHashTake interop call also scrubs it from the address bar and
history, with query-string parameters honored as a fallback (ConfirmEmail.razor.cs:17-22, :139).
A link carrying both values is redeemed once on the first interactive render, a link missing either
lands on manual entry without posting a request that can only be refused, and a refused token keeps
the form with the API's own message and a resend button (:25-30, :108-128). What the page shows
is the private three-value ConfirmationState enum, Working, Form and
Confirmed (ConfirmEmail.razor.cs:50-60).
The refresh is the interesting part: one ITokenRefresher abstraction
(MMCA.Common.UI/Services/Auth/Tokens/ITokenRefresher.cs:17) has two implementations picked per host,
SameOriginProxyTokenRefresher for the browser (the refresh token
lives in an HttpOnly cookie and rotation happens server-side behind a same-origin
/auth/session/token proxy, so JS never sees it) and
DirectApiTokenRefresher for MAUI (the refresh token sits in OS
SecureStorage and is exchanged directly against auth/refresh). Storage is host-polymorphic in the
same way: WasmTokenStorageService holds the access token in memory only
and single-flights its re-acquisition behind a lock, since an unguarded ??= lets two callers each
start a hydrate and the later one overwrite the other's token
(MMCA.Common.UI/Services/Auth/Tokens/WasmTokenStorageService.cs:27, :36, :40), while
ServerTokenStorageService reads the HttpOnly cookie through
CookieTokenReader during a real page request (SSR
prerender) and switches to the in-memory token on the interactive circuit, whose HttpContext is not null but is the stale request that opened the hub connection: once the scoped instance has set, cleared or hydrated a token memory is the source of truth, and before that a hub connection request answers from its cookie only while that token is fresh
(MMCA.Common.UI.Web/Services/ServerTokenStorageService.cs:48, :10-17, :28-40,
ADR-022). The same AddCommonServerTokenStorage() also puts
BrowserOriginHandler
(MMCA.Common.UI.Web/Services/BrowserOriginHandler.cs:32) on the server-side "APIClient"
(MMCA.Common.UI.Web/DependencyInjection.cs:40, :47-48): a Blazor Server host calls the API on the
visitor's behalf, and without it every visitor would share the host's own address and send no
user-agent, so the registration rate limit and the session's recorded IP and device would key on the
host. It forwards X-Forwarded-For from the request's RemoteIpAddress, which has already been
through this host's forwarded-headers middleware rather than copied from whatever the client sent,
plus the browser's User-Agent, replacing any value already present and sending nothing when no
request is in scope (BrowserOriginHandler.cs:5-29, :47-52, :57-68). A third
contract, ISecureTokenStore
(MMCA.Common.UI/Services/Auth/Tokens/ISecureTokenStore.cs:16), is raw persistence with no freshness
semantics, and it exists to keep the MAUI graph acyclic: storage depends on the refresher, the
refresher depends on the raw store, and there is no loop (ISecureTokenStore.cs:5-14). A refresher can also say why it came back
empty. ITokenRefresher answers null both for "there is no session" and for a transient failure, so
the optional ISessionAwareTokenRefresher
(MMCA.Common.UI/Services/Auth/Tokens/ISessionAwareTokenRefresher.cs:12) adds
TryAcquireAccessTokenAsync, which returns a TokenAcquisition
(MMCA.Common.UI/Services/Auth/Tokens/TokenAcquisition.cs:9): NoSession for the endpoint's 401,
Unavailable for a 429 or 5xx, a dropped connection, missing JS interop or a cancelled call, and
Acquired(token) otherwise (ISessionAwareTokenRefresher.cs:17, TokenAcquisition.cs:3-8, :18,
:21, :35). Storage that remembers a "no session" answer for an anonymous grace period starts the
grace only on the definitive kind, so one 429 cannot sign a signed-in user out for the whole window,
and a refresher that does not implement the interface keeps the old reading of null as "no session"
(ISessionAwareTokenRefresher.cs:3-11). The two browser storages also act on that definitive answer. A session can end on the server without this client signing out (revoked from another device with "Sign out everywhere", or the account deleted), so ISessionAwareTokenStorage (MMCA.Common.UI/Services/Auth/Tokens/ISessionAwareTokenStorage.cs:12) adds a SessionEnded event, raised once with the stored token already cleared when a refresh answers "no session" for a session the storage held, and never for a transient failure (ISessionAwareTokenStorage.cs:3-11, :14-18). WasmTokenStorageService and ServerTokenStorageService both implement it (WasmTokenStorageService.cs:29, :58, :191-196; ServerTokenStorageService.cs:87, :249), and JwtAuthenticationStateProvider subscribes in its constructor, then forgets the list pages' persisted search and filters and signs the shell out, so the app no longer stays signed in behind a run of 401s (MMCA.Common.UI/Services/Auth/JwtAuthenticationStateProvider.cs:24, :50-53, :145-151). Every sign-out, and every sign-in, passes through that provider, which makes it the one place the sessionStorage-mirrored list state is dropped, so the next account on the same tab never inherits the previous one's search (JwtAuthenticationStateProvider.cs:18-22, :36-40, :121-143). A storage that does not implement it behaves as before. On
WebAssembly the first hydration (a JS interop hop for the session cookies plus a same-origin token
exchange) would otherwise run inline on whichever API call the user makes first, so a client host
may start TokenHydrationWarmup
(MMCA.Common.UI/Services/Auth/Tokens/TokenHydrationWarmup.cs:26) after builder.Build() and
discard the task, letting it overlap first render instead of delaying it (:11-15). It only reads
through ITokenStorageService.GetAccessTokenAsync, which never forces a refresh, so an anonymous
visitor gets a no-op, and it swallows and debug-logs every failure because the first real call
hydrates again with its own handling (TokenHydrationWarmup.cs:18-22, :36-57); the ADC client
wires it that way (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web.Client/Program.cs:78). The
ISessionCookieSync / JsFetchSessionCookieSync
pair keeps the server the only writer of the HttpOnly session cookies under both interactive render
modes: the browser implementation's SyncAsync sends nothing and reports success, because the server
already wrote the cookies when it obtained the token pair, while ClearAsync fires the fetch from
the browser through JS interop, so the Set-Cookie lands in the user's own jar, and reports
whether the jar was actually updated, false on a non-2xx answer or when JS interop is unavailable
(MMCA.Common.UI/Services/Auth/ISessionCookieSync.cs:8-19, JsFetchSessionCookieSync.cs:6-15, :24, :27-38). All three storage services agree
on one 30-second expiry skew, DefaultExpirySkew, read through JwtTokenInfo.IsFresh
(MMCA.Common.UI/Services/Auth/Tokens/JwtTokenInfo.cs:17, :24, :44-47, used at WasmTokenStorageService.cs:61,
ServerTokenStorageService.cs:96, :333 and SecureStoreTokenStorageService.cs:114), which reads only the
exp claim straight from the payload segment, with no token handler allocated, and without validating its
signature, because the API validates every request (JwtTokenInfo.cs:8-16). Every outbound call also passes
AuthDelegatingHandler, which attaches the stored bearer token to requests
that do not go through CreateAuthenticatedClientAsync
(MMCA.Common.UI/Services/Auth/AuthDelegatingHandler.cs:37), except one that sets its SkipBearer request
option: the token-refresh POST does, because that endpoint is anonymous and reading storage from
inside a refresh would re-enter the very acquisition waiting on it (AuthDelegatingHandler.cs:9-19).
The anonymous auth calls (forgot-password, the sign-in link, the passkey sign-in options) set the
same option through the internal AnonymousApiRequest
(MMCA.Common.UI/Services/Api/AnonymousApiRequest.cs:14), whose PostJson and Post build a
bearer-less POST (:21-36, used at AuthUIService.cs:233, :249, :394), so on WebAssembly and
MAUI an expired stored token does not trigger a refresh round trip before the user has signed in, and
a 401 for a wrong password is not reported to storage as a rejected session
(AnonymousApiRequest.cs:5-13). The lifecycle across render modes is
ADR-051; the cross-service
JWKS validation these tokens flow into is
ADR-004.
An opt-in same-origin API proxy: no token in the page at all. By default a browser client still
holds an access token in memory, the one /auth/session/token hands to script. A Blazor Web host can
remove even that by calling AddCommonSameOriginApiProxy(configuration) and
MapCommonSameOriginApiProxy() from MMCA.Common.UI.Web, a backend-for-frontend in which the browser
calls /api/** on the UI host's own origin and the host forwards to the gateway with the bearer taken
from the HttpOnly session cookie
(SameOriginApiProxyServiceExtensions,
MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyServiceExtensions.cs:12-18, :51;
SameOriginApiProxyEndpointExtensions,
MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpointExtensions.cs:15, :33).
SameOriginApiProxySettings
(MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxySettings.cs:22) binds SameOriginApiProxy
with a default for every value, so a host opts in with no section at all: a /api PathPrefix, a
GatewayAddress that falls back to Api:ApiEndpoint so a service-discovery name resolves exactly as
it does for the host's own clients, auth/login, auth/register and auth/oauth/exchange as the
token-issuing paths, auth/refresh and auth/revoke, and SameSite=Strict session cookies (:31,
:38, :46, :52, :59, :66, :74; the gateway fallback at
SameOriginApiProxyServiceExtensions.cs:57-64).
SameOriginApiProxySettingsValidator
(MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxySettingsValidator.cs:16) runs on start and
refuses a prefix or path carrying route syntax, a query, a fragment or whitespace, a gateway that is
not an absolute address, and any SameSite other than Strict or Lax, because a cookie that
authenticates data calls must never ride on a cross-site request (:7-13, :16, :26-49). Opting in
also makes the session cookies claims-only toward the browser and has /client-config advertise the
proxy, which is what moves the WebAssembly "APIClient" and notification hub onto it
(SameOriginApiProxyServiceExtensions.cs:21-28, :69-74).
Each request runs through SameOriginApiProxyEndpoint
(MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:30) in a fixed order (:15-28).
A foreign Origin or Sec-Fetch-Site is refused with 403 before anything else, and a WebSocket
upgrade must carry this host's own Origin, because an upgrade is not CORS-protected and the origin
is the only proof of who opened it (:115-131, :232-237); OPTIONS is answered locally with 204
and no CORS grant, so the gateway's CORS policy is never consulted on the proxy's behalf
(:241-245); and every unsafe method must carry the X-CSRF: 1 header named by
SameOriginProxyHeaders
(MMCA.Common.UI/Services/Auth/SameOriginProxyHeaders.cs:11, :14, :17), the one exemption being
an HTTP/2 WebSocket, to which a browser cannot add a header (SameOriginApiProxyEndpoint.cs:250-254).
The header is defense in depth behind the origin check and carries no secret
(SameOriginProxyHeaders.cs:3-9). The session step then validates or refreshes the cookie's access
token through the single-flighted ICookieSessionRefresher: a refused refresh token clears the
cookies and answers 401, while a refresh that could not be decided keeps them and answers 503 with
Retry-After, so a blip at the identity endpoint does not sign the user out (:22-25, :261-284).
A browser POST to the refresh path is answered by the proxy itself from the refresh cookie
(:351-356), and a safe method the gateway answers 401 gets one forced refresh and one replay, never
an unsafe one whose body the upstream could apply twice (:313-328). The per-request YARP transform
is SameOriginProxyTransformer
(MMCA.Common.UI.Web/SameOriginProxy/SameOriginProxyTransformer.cs:51): it maps {prefix}/rest to
{gateway}/rest, replaces whatever Authorization the browser sent with the session's bearer, and
keeps the session cookies and the CSRF header off the upstream request (:26-33, :55-62). Its
ProxyResponseMode (:14) picks the response treatment: Forward copies,
TokenIssuing moves a sign-in's token pair into the cookies and sends the browser the same JSON with
a claims-only accessToken and an empty refreshToken under no-store, and Revoke clears the
cookies whatever the upstream answered, so a failed revoke cannot strand the user in a session
(:16-23, :84-95, :100-145). Forwarding goes through
SameOriginProxyInvoker
(MMCA.Common.UI.Web/SameOriginProxy/SameOriginProxyInvoker.cs:19), one HttpMessageInvoker built
the way YARP requires rather than taken from IHttpClientFactory: no cookie container, which would
replay one user's upstream cookies on another user's request, no redirects or decompression, and none
of the host's default handlers, since a retry would replay a streamed body and the trusted-caller
header would exempt every browser request from the gateway's rate limiter (:9-18, :50-58). On the
client, SameOriginProxyRequestHandler
(MMCA.Common.UI/Services/Auth/SameOriginProxyRequestHandler.cs:11) is the innermost "APIClient"
handler: it strips any Authorization header, since the client only ever holds a claims-only token,
and stamps the CSRF header (:3-10, :18-20).
The Blazor Server circuit keeps calling the gateway server-to-server, but its tokens still have to
meet the browser's cookie jar, which it can reach only through a script fetch. The proxy therefore
replaces the circuit's ITokenRefresher and ISessionCookieSync with
HandoffTokenRefresher and
HandoffSessionCookieSync
(SameOriginApiProxyServiceExtensions.cs:83-84,
MMCA.Common.UI.Web/SameOriginProxy/HandoffSessionServices.cs:15, :39), which trade only
ciphertext with the page. SessionHandoffProtector
(MMCA.Common.UI.Web/SameOriginProxy/SessionHandoffProtector.cs:16) encrypts and signs with the
host's data-protection key ring under one purpose each way, so an access-token handoff can never be
replayed as a cookie write, and expires a handoff after one minute (:7-15, :19, :23-27); a
tampered, expired or wrong-purpose value unprotects to null (:57-72), and the cookie direction
serializes the pair as the private TokenPair record (:33-34, :75).
SessionHandoffEndpoints
(MMCA.Common.UI.Web/SameOriginProxy/SessionHandoffEndpoints.cs:17) maps the two halves,
POST /auth/session/handoff (validate-or-refresh from the cookies, answered with a protected access
token) and POST /auth/session-cookie/handoff (seed the cookies from a protected pair), both
requiring the CSRF header and both exchanging the HandoffBody { "handoff": "..." }
record (:17-18, :23-60, :64). Because a registration that lands later would silently put the
access token back in the page, MapCommonSameOriginApiProxy resolves both services and fails the boot
naming the culprit when either is not the handoff implementation, and it also fails when
AddCommonSameOriginApiProxy was never called, which it detects through the internal
SameOriginApiProxyMarker
(SameOriginApiProxyEndpointExtensions.cs:38-44, :59-92,
SameOriginApiProxyServiceExtensions.cs:77, :87-88). [Rubric §26, Front-End Security] is the home
category: with the proxy on, no token is readable by script on the page.
Front-end security beyond tokens. [Rubric §26, Front-End Security] assesses token handling, XSS
exposure and secret storage, and this group answers it in five places: keeping the refresh token out
of JS-reachable storage (above); BlazorCspPolicyProvider, which pins
connect-src to 'self' plus the configured API/Gateway origin and its wss form for the SignalR
hub (MMCA.Common.UI.Web/Security/BlazorCspPolicyProvider.cs:28, :49-79) and, when the endpoint
cannot be parsed, fails closed: connect-src narrows to 'self' and the policy stays enforced,
so a misconfiguration surfaces immediately as blocked calls in the console rather than as a
Report-Only header that protects nothing and nobody notices (BlazorCspPolicyProvider.cs:16-20,
:60-62), feeding the shared
SecurityHeadersMiddleware through
ICspPolicyProvider;
AuthenticatedNoStoreExtensions.UseAuthenticatedNoStore
(MMCA.Common.UI.Web/Hosting/AuthenticatedNoStoreExtensions.cs:8, :24), which emits
Cache-Control: no-store on authenticated HTML so a logged-out user pressing Back never sees the
previous user's page out of the bfcache while anonymous pages stay bfcache-eligible
(MMCA.Common.UI.Web/Hosting/AuthenticatedNoStoreExtensions.cs:24-44); the returnUrl sanitizer already
covered; and, on a native head, the app-lock overlay BiometricGate
(MMCA.Common.UI/Components/Capabilities/BiometricGate.razor.cs:18), which re-arms once the app has
sat in the background longer than its 30-second ReLockAfter parameter, short by design because a
device handed to someone else is usually away for longer than a glance at a notification
(BiometricGate.razor.cs:19-25). It subscribes to the resume event regardless of the current
preference, since app lock can be switched on later in the same session and the handler re-reads the
preference every time it fires (:52-55), and it moves focus onto the unlock button once the locked
branch has actually rendered, so the panel is a real interaction boundary rather than a picture of one
(:31-45).
The CSP has exactly one host-configurable allowance, and it is configured rather than coded.
BlazorCspSettings
(MMCA.Common.UI.Web/Security/BlazorCspSettings.cs:18) binds the BlazorCsp section and carries a
single FrameSources list, the https origins this host's pages may embed in an iframe (:21,
:35); with the default empty list the provider emits no frame-src directive at all, so frames
fall back to default-src 'self' and the baseline policy stays byte-identical
(BlazorCspPolicyProvider.cs:85-90), and when the list is non-empty the origins are canonicalized to
scheme://host[:port] and de-duplicated ordinally before being joined into frame-src 'self' ...
(BlazorCspPolicyProvider.cs:92-96, BlazorCspSettingsValidator.cs:61-62). frame-ancestors 'none',
which governs who may frame this host, is never relaxed by any of it
(BlazorCspPolicyProvider.cs:110). Because each entry is spliced verbatim into a security response
header, the value is validated at startup rather than at first use:
BlazorCspSettingsValidator
(MMCA.Common.UI.Web/Security/BlazorCspSettingsValidator.cs:13) is registered with ValidateOnStart
and rejects anything that is not a plain https origin, refusing whitespace and the character set
*'";,@?# outright (:19, :42-48) and then requiring the https scheme, a non-empty host and a
root-only path (:52-54), with a failure message naming the offending entry so the boot log says
which one (:26-36). The reasoning is on the type: a quote, semicolon or space could smuggle a
keyword or a whole new directive into the policy, and a wildcard or bare scheme would widen
frame-src to arbitrary sites (BlazorCspSettingsValidator.cs:6-12). The options registration and
the validator are added by the same AddCommonBlazorCsp() that registers the provider, the validator
through TryAddEnumerable so calling the method twice does not run the validation twice
(MMCA.Common.UI.Web/DependencyInjection.cs:66-76).
The UI host's own edge: a request limiter. The Blazor Web host is an externally reachable origin
separate from the Gateway, so the edge limiter of
ADR-088 never sees a
request to it, while every page load there opens an interactive Server circuit in a container
typically sized at 0.25 vCPU and 0.5 GiB
(MMCA.Common.UI.Web/Hardening/UiRateLimitingSettings.cs:11-15). MMCA.Common.UI.Web therefore
ships a limiter of its own. UiRateLimitingSettings
(UiRateLimitingSettings.cs:33) binds the UiRateLimiting section with an Enabled switch that
defaults on, a per-IP PermitLimit of 300 over a 60-second WindowSeconds, and a replica-wide
GlobalConcurrencyLimit of 200 (:36, :43, :58, :62, :76). The 300 sits well above any single
visitor on purpose, because an office or carrier NAT presents many visitors as one address, and a
host whose audience shares one egress (a venue's wifi) is told to raise it (:49-55).
UiRateLimitingExtensions
(MMCA.Common.UI.Web/Hardening/UiRateLimitingExtensions.cs:27) turns that into a chained global
limiter, so a request must pass both a fixed window keyed by client IP and one concurrency bucket for
the whole process, each with a zero-length queue so excess is rejected with 429 at once rather than
queued (:148-155, :169-185, :232-238). A rejection by the fixed window carries a Retry-After header in whole seconds rounded up, while a concurrency rejection has no hint and sends none (:45-64). The settings are validated on start and then
closed over once rather than resolved per request, because the partition callback runs on every
request (:197-209). Exemptions are declared rather than inferred from middleware order: /health,
/alive, /_framework, /_content and /hubs match on whole segments, and any path whose last
segment carries a file extension counts as a static asset unless it sits under the same-origin proxy prefix, whose traffic is API traffic whatever its last segment looks like, and the proxied {prefix}/hubs is exempt too; /_blazor has neither exemption and stays
inside the per-IP window because its negotiate is exactly what opens a circuit (:66-78, :86-98, :104-116). It is, however, kept out of the concurrency ceiling: the same prefix carries the circuit WebSocket, whose lease would otherwise be held for the circuit's whole lifetime and starve page loads, so circuits are bounded by BlazorCircuitLimits instead (:37-43, :158-162, :178). An
unresolvable client IP fails open instead of collapsing every such request into one shared bucket
(:140-146), and both counts are per replica and in memory, the same trade the Gateway kit makes so the
limiter never puts a network round trip in front of the site (UiRateLimitingSettings.cs:27-30).
AddUiRateLimiting(configuration) registers it and UseUiRateLimiting() adds the middleware
(UiRateLimitingExtensions.cs:197, :251).
And a ceiling on open circuits. A rate still lets a caller who opens circuits slowly enough
accumulate them, and CircuitOptions only bounds circuits that have already disconnected, which is
what the second bound closes (MMCA.Common.UI.Web/Hardening/BlazorCircuitLimitSettings.cs:10-15).
BlazorCircuitLimitSettings (BlazorCircuitLimitSettings.cs:17)
binds BlazorCircuitLimits with a MaxActiveCircuits of 200 per replica, derived from that
container's memory and stated as an abuse ceiling rather than a capacity plan, plus a tighter
disconnected retention of 25 circuits for 60 seconds against the framework's 100 and three minutes
(:20, :27-38, :46, :57). BoundedCircuitHandler
(MMCA.Common.UI.Web/Hardening/BoundedCircuitHandler.cs:43) keeps the count as a CircuitHandler,
the documented extension point that sees a circuit open and close (:14-20). It increments first and
rolls back on refusal so two simultaneous opens cannot both take the last slot, floors the close-side
decrement at zero so an unpaired close never hands out permits forever, and runs last among the
registered handlers (:55, :64-73, :84-88). Refusal is a thrown InvalidOperationException, one
of the few places the Result pattern does not apply, because OnCircuitOpenedAsync returns a Task
with no refuse value; the client sees Blazor's reconnect UI rather than a crashed page (:23-28,
:70-72). BlazorCircuitLimitExtensions
(MMCA.Common.UI.Web/Hardening/BlazorCircuitLimitExtensions.cs:19) keeps the two halves as separate
calls because they attach to different builders: RetentionFrom(configuration) returns the
CircuitOptions callback for AddInteractiveServerComponents, and AddBoundedBlazorCircuits()
validates the options on start and registers the handler as a singleton, since circuit handlers
resolve from each circuit's own scope and a scoped one would count to one and cap nothing (:13-17,
:28-40, :51-60). Both read the same section, so the two numbers cannot drift apart. The ADC Blazor
Web host wires all four calls (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:74, :62,
:127, :197). [Rubric §12, Performance & Scalability] and [Rubric §29, Resilience]: a public
origin sheds load at its own edge instead of letting an unauthenticated loop exhaust its container.
Forms declare their rules once. The shared auth forms (LoginModel,
RegisterModel, ForgotPasswordModel,
ResetPasswordModel) are plain data-annotation EditForm models, with
PasswordComplexityAttribute mirroring the server's rule (at least 8
characters with upper, lower, digit and a non-alphanumeric character) so the form gives the verdict
the API would, and deferring empty input to [Required] so a blank field shows one message rather
than two (MMCA.Common.UI/Pages/Auth/PasswordComplexityAttribute.cs:16, :21-30).
OptionalEmailAttribute
(MMCA.Common.UI/Validation/OptionalEmailAttribute.cs:26) covers the optional address the stock
[EmailAddress] cannot express: blank passes, and anything else must hold exactly one @ that is
neither first nor last, the server's EmailRules check (OptionalEmailAttribute.cs:5-23, :38-41).
The auth models resolve their messages through the internal AuthFieldMessages
(MMCA.Common.UI/Resources/AuthFieldMessages.cs:19) as an ErrorMessageResourceType, reading
SharedResource in the current UI culture with the key itself as fallback, because MudBlazor also
runs a For field's attributes on its own and shows the message verbatim, so a bare resource key
there reached the screen raw (AuthFieldMessages.cs:11-18, :44).
AbsoluteUrlAttribute
(MMCA.Common.UI/Validation/AbsoluteUrlAttribute.cs:26) is the same parity argument with sharper
stakes: it requires an absolute http/https URL (:39-52) because these values are rendered
straight into an image source or a link target, so accepting javascript: or data: on the client
and rejecting it on the server would leave a round trip as the only thing between a pasted script URL
and the page (AbsoluteUrlAttribute.cs:5-11). Beyond the auth pages, MudBlazor fields bind their
Validation parameter to a delegate from ModelValidation.For
(MMCA.Common.UI/Validation/ModelValidation.cs:26, :43-49), which hands the model and the member
path MudBlazor supplies to an IModelValidator
(MMCA.Common.UI/Validation/IModelValidator.cs:13). That indirection is the extension point: the
in-box DataAnnotationsModelValidator
(MMCA.Common.UI/Validation/DataAnnotationsModelValidator.cs:21) runs the attributes on the model and
resolves every produced message as a resource key with pass-through, so a model can declare
ErrorMessage = "Validation.AbsoluteUrl" and a plain-English message still renders verbatim
(DataAnnotationsModelValidator.cs:13-19, :36-41); an EditForm gets the same localizing path by swapping
<DataAnnotationsValidator /> for
LocalizedDataAnnotationsValidator
(MMCA.Common.UI/Validation/LocalizedDataAnnotationsValidator.cs:29), which writes the results into
the form's EditContext, re-validating a field when it changes and the whole model on submit
(:9-20); a consumer that keeps its rules in
FluentValidation supplies its own implementation and MMCA.Common.UI never references a validation
library. That client-side parity is the point of [Rubric §24, Forms, Validation & UX Safety]: the
client predicts, the server decides.
Sign-in, registration and terms acceptance ship as framework pages. The /login page's
Login code-behind (MMCA.Common.UI/Pages/Auth/Login.razor.cs:19) reads the error
query value the OAuth completion endpoint sends a refused external sign-in back with and maps the
machine code to words, never showing the raw code, with a dedicated resource for each refusal that
carries its own recovery path and a generic refusal for the rest (:25-29, :54-72); when device
storage dropped the OAuth attempt it disables the web-redirect provider buttons, since a flow
started there would be refused at completion; the attempt is minted at the click, so a second login tab replaces it only when the user clicks there (:19-23, :99-126). A refused password sign-in is worded by its error code when that code has a resource of its own (Auth.InvalidCredentials, Auth.AccountLocked), because the API's message is an English sentence, and otherwise falls back to the API's message, localized when it can be, then the generic invalid-credentials wording (:76-97). Both pages cancel an in-flight sign-in or registration when they are disposed (Login.razor.cs:13-16, MMCA.Common.UI/Pages/Auth/Register.razor.cs:15-19, :31-41). The /register page's
Register (MMCA.Common.UI/Pages/Auth/Register.razor.cs:13) validates any address the
user did type and blocks the registration on an invalid one instead of dropping it, while an
all-blank block, or a host with address collection off, sends no address (:43-67); the whole block is switchable through
RegistrationSettings.CollectAddress, bound from Registration and
defaulting to true so a host that configures nothing keeps the page as it was
(MMCA.Common.UI/Common/Settings/RegistrationSettings.cs:8, :11, :18). Legal documents are
LegalSettings (MMCA.Common.UI/Common/Settings/LegalSettings.cs:16), bound
from Legal: optional absolute URLs for the terms, the privacy policy, the code of conduct and the
account-deletion page, where an empty value renders nothing and a set TermsUrl is what makes the
register page require "I agree"; the current terms version itself stays server configuration
(LegalSettings.cs:5-15, :22, :26, :30, :34, :41). Consent owed after sign-up is
TermsAcceptanceGate
(MMCA.Common.UI/Components/Legal/TermsAcceptanceGate.razor.cs:29): it reads the signed-in user's
standing once per user from OnAfterRenderAsync, because the bearer token is readable only once the
renderer is interactive, renders nothing on any failed read so the gate never takes the app down with
the API, and otherwise holds a dialog with no close button, backdrop click, Escape or
close-on-navigation, since a list page rewriting its own URL right after load would otherwise dismiss
it for the rest of the session (:19-28, :31-45). Its client is
ILegalAcceptanceUIService
(MMCA.Common.UI/Services/Legal/ILegalAcceptanceUIService.cs:16), a Result-returning GetAsync and
AcceptAsync against Users/me/legal-acceptance that never throws for a server answer or a
transport fault, so a caller treats any failure as "do not block" (:6-15, :21, :27), implemented
by LegalAcceptanceUIService
(MMCA.Common.UI/Services/Legal/LegalAcceptanceUIService.cs:22) on the authenticated-service shape:
the read is retried, the accept POST is sent once (:14-20, :29-40; registered for every host at
MMCA.Common.UI/DependencyInjection.cs:218-220). On the profile page,
ChangePasswordCard
(MMCA.Common.UI/Components/Auth/ChangePasswordCard.razor.cs:23) validates all three fields
client-side first (each required, the new password at least MinLength, 8 by default, and passing the
shared PasswordComplexity rule the server evaluates, the confirmation equal to it), raises its busy
guard before the first await so a double click cannot resend a stale current password the server would
count toward lockout, and calls IAuthUIService.ChangePasswordAsync only for a valid form, toasting a
success in its own words and a refusal with the server's reason (:12-21, :51, :106-128,
:130-168). A refusal the server tied to the current or the new password is also shown under that
field through the private FieldRefusal record struct (:198), which holds the
message against the exact value it was raised for, so it clears itself as soon as the user edits the
field; it matches a validation target on its last path segment, case-insensitively, so NewPassword
and Request.NewPassword both land, and the handler's Auth.InvalidCurrentPassword code counts for
the current-password field (:32, :180-192, :200-225).
The component library is behind two facades. IToastService
(MMCA.Common.UI/Common/Interfaces/IToastService.cs:37) and
IAppDialogService
(MMCA.Common.UI/Common/Interfaces/IAppDialogService.cs:18) are the only way page code raises a
transient notification or asks a yes/no question. The toast contract carries the four named severities
plus a runtime-severity Show, a two-line ShowPersistent that stays until dismissed (the
push-notification shape: a message that arrived unprompted must not expire before the user looks at
the screen, IToastService.cs:64-72) and a ShowAction that renders a button for the undo/view/retry
case, with the explicit warning that the callback runs outside any render callback so a caller whose
work can fail must guard it (IToastService.cs:74-101); severity itself is the framework's own
ToastSeverity enum (IToastService.cs:8).
MudToastService (MMCA.Common.UI/Services/MudToastService.cs:33) and
MudAppDialogService (MMCA.Common.UI/Services/MudAppDialogService.cs:13)
are the only two types in the framework that name MudBlazor's ISnackbar and IDialogService,
and even the severity projection is written out as a switch rather than cast, because the two enums
agreeing numerically today is not a dependency worth taking silently
(MudToastService.cs:92-104). Announcement is deliberately not this service's job: the shared
provider block hosts MudBlazor's snackbar inside a role="status" aria-live="polite" element, so the
rendered toast already is the live-region content and a second channel would read the same sentence
twice (MudToastService.cs:12-17). Where toasts appear and how many show at once is framework
behaviour rather than app styling, because the toast service evicts the oldest pinned toast against
MudBlazor's MaxDisplayedSnackbars, so every head has to agree on it: the internal
SnackbarDefaults (MMCA.Common.UI/Services/SnackbarDefaults.cs:21) sets top
centre and a cap of three (:24, :27, :30-35), and AddUIShared inserts it once as the first
SnackbarConfiguration configure step (MMCA.Common.UI/DependencyInjection.cs:135,
SnackbarDefaults.cs:42-50), so it is a default rather than a decision: anything the host configures,
before or after AddUIShared, runs after it and wins (SnackbarDefaults.cs:13-19). A toast about the page being left can also be kept from following the user: with Layout:ClearToastsOnNavigation on (MMCA.Common.UI/Common/Settings/LayoutSettings.cs:58, off by default), MainLayout renders StaleToastSweeper (MMCA.Common.UI/Components/Notifications/StaleToastSweeper.cs:24), which renders nothing itself, records when each toast was first seen from ISnackbar.OnSnackbarsUpdated under a lock (expiry arrives on timer threads), and on LocationChanged removes only the toasts that had been on screen longer than its 750 ms Grace, so a toast raised as part of the navigation ("Order created, taking you to it") survives it (StaleToastSweeper.cs:7-17, :21, :47-65, :67-85). The dialog facade sends both overloads through ConfirmationDialog.ShowAsync, which collapses a
dismissal (Cancel, escape, backdrop click) onto false, so a caller only ever branches on true
(MudAppDialogService.cs:16-21, MMCA.Common.UI/Components/Forms/ConfirmationDialog.razor:65,
MMCA.Common.UI/Components/Forms/ConfirmationDialog.razor:92). Both are
registered by their own AddCommonUiFacades() (MMCA.Common.UI/DependencyInjection.cs:285-291),
separate from AddUIShared so a bUnit harness can resolve exactly these two without the rest of the
shared-UI surface. [Rubric §1, SOLID] (dependency inversion) and [Rubric §14, Testability]: a
component test records toasts instead of driving a rendered snackbar host.
Design system and theming. Visual consistency is centralized in one static
MMCATheme MudTheme instance (MMCA.Common.UI/Theme/MMCATheme.cs:9, :11) holding a
light palette (:13-55), a full dark palette (:56-111), an Inter-first typography scale (:112-190)
and a 6 px default border radius (:191-194). It is applied through the shared MmcaThemeProviders
component, which renders the four Mud providers every root layout needs exactly once and takes the
theme as a parameter defaulting to MMCATheme.Instance, so an app with its own brand passes a derived
MudTheme instead of duplicating the provider block
(MMCA.Common.UI/Theme/MmcaThemeProviders.razor:33-36). The palette itself comes from a
single C# source of truth, BrandColors (MMCA.Common.UI/Theme/BrandColors.cs:10),
whose doc comment states the duplication contract plainly: the CSS custom properties in
wwwroot/app.css must mirror these constants because C# cannot read CSS at build time, and
BrandColorTokenTests asserts the two stay in sync (BrandColors.cs:3-9). Color choices carry
explicit WCAG reasoning: Secondary is Teal 700 #00796B for about 5.3:1 on light surfaces because the
Teal 600 it replaced sat at about 4.0:1, under the AA 4.5:1 floor (BrandColors.cs:21-26), and
the light Warning is Amber 900 #A85D00 (4.96:1 on Surface, 4.79:1 on Background) rather than the
Material amber #F57F17, which measures only about 2.65:1 on white and so fails the 4.5:1 floor
everywhere the palette colour is used as text or as a border rather than as a fill, with
WarningContrastText moved to white in the same edit because the two values have to move together
(MMCATheme.cs:28-36). The dark palette makes the mirror-image choice, keeping rgba(0,0,0,0.87) on
#FFA726, where white would be about 2.0:1 and dark text is about 10.8:1 (MMCATheme.cs:83-85).
[Rubric §20, Design System, Theming & Consistency] is the home category (one token source, dark
mode, consistent typography) and [Rubric §21, Accessibility] is woven into the palette itself and
into the chrome, down to the skip-to-content link the shared layout renders first
(MMCA.Common.UI/Layout/MainLayout.razor:17).
Dark mode is a service, not a flag. ThemeService
(MMCA.Common.UI/Theme/ThemeService.cs:17, registered Scoped at DependencyInjection.cs:229)
owns the preference: InitializeAsync reads the stored value through a theme.js module and falls
back to the OS prefers-color-scheme only when nothing is stored (ThemeService.cs:35),
SetDarkModeAsync persists through the same module and raises OnChange (ThemeService.cs:29,
:54), and the JS module handle is held by LazyJsModule
(MMCA.Common.UI/Services/LazyJsModule.cs:20), a single-flight importer that caches the in-flight
import under a lock so two concurrent callers cannot leak a second module reference, and that drops a
failed task so an import attempted during prerender does not poison the module for the rest of the
circuit (LazyJsModule.cs:5-19, :22-25). MmcaThemeProviders subscribes to OnChange and
re-renders (MMCA.Common.UI/Theme/MmcaThemeProviders.razor:56), and every best-effort theme interop
call it makes goes through the internal ThemeInterop.TryAsync
(MMCA.Common.UI/Theme/ThemeInterop.cs:9, :18-29), which turns every failure
JsInteropFailure.IsUnavailable names into false, so a JS failure never
escapes a component lifecycle and kills the circuit (MmcaThemeProviders.razor:69, :98). That
internal predicate (MMCA.Common.UI/Common/JsInteropFailure.cs:9) is the framework's one definition
of "interop could not do its job here", shared so the set cannot drift between copies: an
InvalidOperationException (no interop on this renderer: SSR prerender, a render-mode transition, a
disposed dispatcher), a JSDisconnectedException (the circuit was torn down mid-call), a JSException
(the script is missing or threw in the browser) and an OperationCanceledException, which covers an
interop call that outlived the host's JS interop timeout; a caller that must let its own cancellation
propagate adds that condition to its filter (JsInteropFailure.cs:5-8, :17-31). The list-page state
service, the pending-toast service, the session-cookie sync, the proxy token refresher and the view-as
controls filter on the same predicate. An app whose own stylesheet must follow the mode opts into Layout:StampColorModeOnDocument (MMCA.Common.UI/Common/Settings/LayoutSettings.cs:41-51), and the provider then calls the internal ColorModeStamp (MMCA.Common.UI/Theme/ColorModeStamp.cs:15) after its first interactive render and after every theme change (MmcaThemeProviders.razor:76). It mirrors the mode onto <html data-mmca-color-mode="light|dark"> through the same best-effort ThemeInterop.TryAsync, because MudThemeProvider only swaps its palette variables and gives CSS nothing to select on; with the setting off (the default), with no layout settings registered, or on a non-interactive render it does nothing (ColorModeStamp.cs:8-13, :22-35). Honest caveat: on a web head the no-flash SSR bootstrap
is not wired for theme. InitializeAsync runs from OnAfterRenderAsync(firstRender) because JS
interop is unavailable during prerender (MmcaThemeProviders.razor:59-69), so the bound mode is
corrected just after hydration and a brief wrong-theme first paint is possible
(ADR-028). A head that already knows
the stored preference without JS closes that gap by registering an
IInitialThemeModeSource
(MMCA.Common.UI/Theme/IInitialThemeModeSource.cs:16), whose synchronous IsDarkMode (null when
unknown) MmcaThemeProviders reads during initialization, with the JS path still running afterwards
and staying authoritative; a MAUI hybrid head reading device preferences is the intended implementer,
and web heads register nothing (IInitialThemeModeSource.cs:3-13, :21,
MmcaThemeProviders.razor:44-54).
Internationalization: one culture decision, carried everywhere. The framework serves en-US and
Spanish (es) plus a development-only pseudo locale, and the hard part is not the translations, it is
making one culture decision agree across the InteractiveAuto split (SSR prerender, then an
InteractiveServer circuit, then an InteractiveWebAssembly client) and across the cross-origin REST
services behind the Gateway, with no language flash and no hydration mismatch
(ADR-027, which supersedes the
single-locale stance of ADR-011). A
single non-HttpOnly culture cookie is the source of truth. The WASM client reads it at startup through
MmcaCultureBootstrap.SetBrowserCultureAsync, which assigns
CultureInfo.DefaultThreadCurrent[UI]Culture before RunAsync() and falls back to
SupportedCultures.Default
(MMCA.Common.UI/Services/Culture/MmcaCultureBootstrap.cs:38-50). Outbound API calls forward the active
culture as an Accept-Language header through
CultureDelegatingHandler
(MMCA.Common.UI/Services/Culture/CultureDelegatingHandler.cs:13, :20-25), wired into the "APIClient"
pipeline at DependencyInjection.cs:180-181, because the cross-origin Gateway does not carry the
cookie through to the services and that header is what makes a backend failure come back localized.
View strings are externalized to co-located .resx resolved by IStringLocalizer<T>
(AddLocalization() at DependencyInjection.cs:117), anchored by two marker types:
SharedResource for cross-cutting chrome
(MMCA.Common.UI/Resources/SharedResource.cs:9) and MudTranslations for
MudBlazor's own component text (pager, filter menus, pickers,
MMCA.Common.UI/Resources/MudTranslations.cs:10), served through
ResxMudLocalizer, which AddUIShared TryAdds because AddMudServices
registers no MudLocalizer of its own (DependencyInjection.cs:126-130) and whose values degrade to
MudBlazor's built-in English when a key reports ResourceNotFound
(MMCA.Common.UI/Globalization/ResxMudLocalizer.cs:7-20). How MudBlazor reaches that fallback is
replaced too: AddUIShared installs
InvariantMudLocalizationInterceptor
(MMCA.Common.UI/Globalization/InvariantMudLocalizationInterceptor.cs:37) through MudBlazor's
AddLocalizationInterceptor, which replaces the default regardless of whether AddMudServices ran
first (MMCA.Common.UI/DependencyInjection.cs:144). The resolution order is unchanged (an English UI
culture, or no MudLocalizer, reads the built-in strings; any other culture asks the MudLocalizer
and falls back on ResourceNotFound, InvariantMudLocalizationInterceptor.cs:49-60), and the
English test is the parent language, so en-US counts as English while the neutral en goes
through the localizer like every other culture (:46-52). The one difference is how the built-in
strings are read. MudBlazor 9.7+ assigns CultureInfo.CurrentUICulture to the invariant culture and
then assigns the previous value back, and both writes land in an AsyncLocal, so the "restore"
leaves the calling thread's ExecutionContext carrying an explicit culture from then on; on a MAUI
hybrid head the renderer dispatches on the process's main thread, which nothing ever resets, so the
first MudBlazor chrome string a page renders pins the app to its launch language and a later switch
loses to the pinned value even after a WebView reload (:16-27). The private nested
BuiltInStrings (InvariantMudLocalizationInterceptor.cs:73) reads the same
embedded MudBlazor.Resources.LanguageResource through a ResourceManager with an explicit
invariant culture instead, addressing it by manifest name because MudBlazor's generated resource
class is internal (:75, :77, :89, :98-102), which is what the culture swap was for (no
satellite-assembly probing under a non-English culture) with no culture assignment at all.
Count-sensitive messages are handled by a suffix convention rather than by string concatenation:
StringLocalizerPluralExtensions.Plural
(MMCA.Common.UI/Globalization/StringLocalizerPluralExtensions.cs:20, :40) asks for {key}.One
when the count is exactly one and {key}.Other otherwise, falling back to the base key when the
plural sibling is missing so a resource set that has not been split yet keeps rendering its single
message instead of leaking a raw key name to the reader (:46-51); the send confirmation is the
current call site (MMCA.Common.UI/Pages/Notifications/NotificationSend.razor.cs:137). Two
categories cover both shipped cultures, and a language with more CLDR categories needs a category
selector rather than more suffixes, which would not change the call site
(StringLocalizerPluralExtensions.cs:13-19). Applying a switch is host-specific and sits
behind ICultureApplier: the web default
EndpointCultureApplier force-loads the server /culture/set endpoint so
the server re-renders SSR under the new cookie and the WASM runtime re-reads it on startup
(MMCA.Common.UI/Services/Culture/EndpointCultureApplier.cs:18-32), while a MAUI hybrid head, having no
ASP.NET pipeline, replaces it after AddUIShared with an in-process applier
(MauiCultureApplier, chapter 26). The
development-only pseudo locale is the group's own i18n test harness:
PseudoStringLocalizerFactory decorates IStringLocalizerFactory
unconditionally (MMCA.Common.UI/DependencyInjection.cs:124,
MMCA.Common.UI/Globalization/PseudoStringLocalizerFactory.cs:11) so every IStringLocalizer in the
host is wrapped in a PseudoStringLocalizer at once, and
PseudoLocalizer accents every letter, pads the text and wraps the result in a
bracket sentinel while leaving { } placeholders verbatim
(MMCA.Common.UI/Globalization/PseudoLocalizer.cs:20-30), which makes hard-coded strings,
fixed-width layouts and concatenated fragments all visible in one pass (PseudoLocalizer.cs:12-19).
Even the snackbar text is localized: ErrorMessages keeps its static call sites but
resolves each message from SharedResource once the root layout hands it a localizer, falling back to
the English format string until then (MMCA.Common.UI/Pages/Common/ErrorMessages.cs:24, :33), and
it never renders an exception's own Message, because raw exception text is neither localizable nor
safe to surface (ErrorMessages.cs:14-22). Time is shown on the viewer's clock rather than the
server's: ViewerTimeZone
(MMCA.Common.UI/Services/Culture/ViewerTimeZone.cs:22, registered scoped at
MMCA.Common.UI/DependencyInjection.cs:239) reads the browser's IANA zone once per scope through
time-zone.js, resolves it with TimeZoneInfo, and converts to UTC until then or whenever the zone
cannot be read, never to the server's own zone, which on Blazor Server and during prerender is the
wrong answer for every viewer elsewhere (ViewerTimeZone.cs:6-20, :36). Its Format renders nothing until the browser has been asked, so a prerendered UTC time never paints only to jump to the viewer's clock after hydration (:11-12). A page calls
EnsureResolvedAsync from its first OnAfterRenderAsync and re-renders when it returns true, which the first resolution does even when the zone stays UTC;
during prerender the call is skipped and a later one retries (:54, :67-79). [Rubric §27, Internationalization] is the home category
here, and adding a locale is a .es.resx sibling plus one allowlist entry, not new infrastructure.
Per-user preference persistence. A signed-in user's culture and theme follow them across devices
via the Identity profile. IUserPreferenceWriter /
ApiUserPreferenceWriter PUT to auth/preferences over the shared
"APIClient" (MMCA.Common.UI/Services/Preferences/ApiUserPreferenceWriter.cs:30, :108-113), with the bearer set on the request message itself because on Blazor Server the delegating handler resolves in a separate DI scope whose token store is empty (:15-19), using the private
UserPreferencesRequest record (:39), and
IUserPreferenceReader /
ApiUserPreferenceReader GET the same endpoint at login and return the
immutable UserPreferences record, whose null fields mean "leave unchanged"
(MMCA.Common.UI/Services/Preferences/UserPreferences.cs:9,
MMCA.Common.UI/Services/Preferences/ApiUserPreferenceReader.cs:22, :21-31). The write is strictly
best-effort: the cookie is the device-local runtime channel and a failed persist never breaks the
in-page switch. Best-effort has a cost, though, and both sides guard it, first by refusing to send
when the token is missing, unreadable or within 30 seconds of expiry via JwtTokenInfo.IsFresh
(ApiUserPreferenceWriter.cs:35, :93; ApiUserPreferenceReader.cs:21, :31), and second by
remembering the exact token the API last answered 401 to, so a revoked session costs one failed
request rather than one per toggle (ApiUserPreferenceWriter.cs:41-47, :98-104, :116-119).
Comparing the token rather than setting a latch is what lets a fresh sign-in resume writing with no
reset step. Saves are also sent one at a time in call order, each waiting at most five seconds for the one before it: a theme toggle followed quickly by a language switch otherwise sent two concurrent PUTs, and the switcher's force-reload either cut off the theme write or let the two race on the user row's concurrency token, so the next sign-in applied the old theme (ApiUserPreferenceWriter.cs:56, :58-74, :76-84). That is a [Rubric §13, Observability & Operability] detail as much as a [Rubric §19, State Management] one: at low traffic, one 401 per theme toggle is enough on its own to trip a
failed-request alert rule.
Pluggable UI modules. The module system that organizes the back end
(IModule, chapter 14) has a front-end counterpart in
IUIModule (MMCA.Common.UI/Common/Interfaces/IUIModule.cs:11). A module descriptor
exposes its navigation entries as NavItem values, the Assembly holding its Razor pages
so the host can add it to AdditionalAssemblies for route discovery, and five defaulted collections of
component types to render: in the app bar for a signed-in user, in the app bar for every visitor (a site search box, or a cart a signed-out shopper also uses), at the root layout, at the top of the main content region, and in the layout footer (IUIModule.cs:5-40, the footer collection documented from :41). The
registration prologue is shared too: AddUIModule<TModule>() runs one Scrutor scan that picks up
every IEntityService<,> implementation in the module's assembly as scoped, then registers the
descriptor as a singleton (MMCA.Common.UI/DependencyInjection.cs:486-495), so a module's own
Add{Module}UI() no longer carries its own copy of that scan and can still register services that
must win afterwards. UIModuleConfiguration lets a host switch a module off
through Modules:{name}:Enabled, defaulting to enabled when the section is absent
(MMCA.Common.UI/Common/Settings/UIModuleConfiguration.cs:28-35), and
IHomePageContent is the per-app landing-page hook behind the shared / route,
naming the component type and the page title
(MMCA.Common.UI/Common/Interfaces/IHomePageContent.cs:8-15). Adding a feature module therefore wires
its pages, its services and its menu entries into the shell with no edit to the shell.
[Rubric §18, UI Architecture] and [Rubric §1, SOLID] (open/closed).
A complete vertical slice shipped inside the framework: notifications. Unlike the rest of the
package, which is base classes consumers extend, the Notifications area is a finished feature an app
switches on with one call. NotificationUIModule
(MMCA.Common.UI/Notifications/NotificationUIModule.cs:15) contributes a user-facing inbox nav entry
plus a push-notification entry gated on the NotificationPermissions.Manage permission rather than on
a role name (:17-21, the permission facet at :20), the app-bar
NotificationBell (:23) and a root-layout listener component (:25);
NotificationInbox, NotificationList and
NotificationSend (with its NotificationSendModel
form model) render it; NotificationInboxService and
PushNotificationService (behind
INotificationInboxUIService and
IPushNotificationUIService) call the API; and
NotificationHubService
(MMCA.Common.UI/Services/Notifications/NotificationHubService.cs:45) holds the SignalR
connection to the API's NotificationHub. A dropped
connection reconnects for as long as the service is alive: the internal
UnboundedReconnectPolicy
(MMCA.Common.UI/Services/Notifications/UnboundedReconnectPolicy.cs:32, wired at
NotificationHubService.cs:222) walks a 0, 2, 5 and 10 second warm-up and then retries every 30
seconds, where the SignalR default gives up after about 42 seconds and leaves live notifications dead
until a page reload (UnboundedReconnectPolicy.cs:6-14, :38, :43-49, :65-73). Every delay is
jittered down by up to 30 percent and the first retry is spread over one second, so clients dropped by
one replica restart or deploy do not hit the recovering replica in synchronized bursts, and no wait
ever exceeds the 30-second cap (:15-21, :34-41, :76-85). A connection that still
closes with an error is restarted under the same 30-second cap with the same jitter, a deliberate stop
or dispose is never restarted, and a 401 or 403 handshake ends both loops, since an expired session
cannot recover by retrying (:22-26, :93-109, NotificationHubService.cs:33-42, :298, :318). The same connection
carries ephemeral live channel events
(ADR-039): components join through
JoinChannelAsync (NotificationHubService.cs:320), membership is reference-counted per key by
ChannelReferenceCounter
(MMCA.Common.UI/Services/Notifications/ChannelReferenceCounter.cs:25) so one subscriber leaving does
not cut the channel off for the others, handlers are multicast through disposable
ChannelSubscription handles (NotificationHubService.cs:772), and every held
channel is re-joined on Reconnected because SignalR group membership does not survive a new
connection (NotificationHubService.cs:227). On a WebAssembly client whose host runs the same-origin
proxy, the hub connects through it and sends the proxy's CSRF header instead of an access token
(NotificationHubService.cs:100-110, :541). Which notifications a user sees can be narrowed by
INotificationScopeProvider, an app-supplied scope key such as
"event:2" that both HTTP services consume so a send and the reads that follow agree, defaulting to
the unscoped NullNotificationScopeProvider and contractually
forbidden from throwing, with the further instruction to fail closed (return the last known key)
rather than degrade to null, since a null silently widens the view to every notification
(MMCA.Common.UI/Services/Notifications/INotificationScopeProvider.cs:9-22). Shared unread state
lives in NotificationState
(MMCA.Common.UI/Services/Notifications/NotificationState.cs:18), which stamps when the count was
last established so a subscriber can ask IsStale instead of re-fetching on every trigger (:7-12)
and arbitrates a single active-poller slot by owner reference rather than a counter, so a teardown
that never unregisters cannot strand the slot for the life of the circuit (:23-29). Both of the
badge's timings are configuration rather than compiled-in constants:
NotificationBellOptions
(MMCA.Common.UI/Common/Settings/NotificationBellOptions.cs:12) binds a 30-second default
PollInterval and a 30-second NavigationRefreshMaxAge, so a deployment paying per API call widens
the poll and a page change within the window keeps the count it has (:22, :29), read by the bell
through IOptions and a TimeProvider
(MMCA.Common.UI/Components/Notifications/NotificationBell.razor.cs:34, :36-37). The bell also
registers strictly symmetrically, because hosts render it twice inside <AuthorizeView> and a routine
token refresh tears both instances down and rebuilds them (NotificationBell.razor.cs:22-29). The
whole feature is wired by its own AddNotificationUI()
(MMCA.Common.UI/Notifications/DependencyInjection.cs:12, :20-42), kept separate so an app that does
not want real-time notifications never pays for the SignalR plumbing. A host that skips it can also set
HideNotificationPagesWhenUnregistered (MMCA.Common.UI/Common/Settings/LayoutSettings.cs:49), and
NotificationPageGate
(MMCA.Common.UI/Notifications/NotificationPageGate.cs:11) then has the router answer the three
notification pages with the not-found page whenever no NotificationUIModule is registered
(:14-31). The router places the internal
NotificationPageNotFoundStatus
(MMCA.Common.UI/Notifications/NotificationPageNotFoundStatus.cs:11) beside that not-found page; it
renders nothing and calls NavigationManager.NotFound() on initialization, so a server render
answers 404 rather than 200 (:5-10, :18). The pages themselves declare the
mmca:notification-pages policy instead of a bare [Authorize], because [Authorize] is endpoint
metadata and the authorization middleware would challenge a signed-out visitor to sign in before the
router's gate ever ran, for a page that does not exist on this host
(NotificationPageRequirement,
MMCA.Common.UI/Notifications/NotificationPageRequirement.cs:18, :23, rationale at :14-19).
NotificationPageAuthorizationHandler
(MMCA.Common.UI/Notifications/NotificationPageAuthorizationHandler.cs:16) passes an authenticated
caller, and every caller while the host hides the pages, reusing the gate's own predicate so the two
cannot disagree (:26-30); AddUIShared registers the policy and the handler for every host
(MMCA.Common.UI/DependencyInjection.cs:79-86).
Administration screens ship as components, not pages. Identity administration is the second
finished feature in the package
(ADR-116), and it is
delivered as components an app routes itself: UserAdminList<TUser>
(MMCA.Common.UI/Pages/Administration/UserAdminList.razor.cs:44), RoleAdminList
(MMCA.Common.UI/Pages/Administration/RoleAdminList.razor.cs:28) and
RoleAdminEdit (MMCA.Common.UI/Pages/Administration/RoleAdminEdit.razor.cs:36)
carry no @page directive, so the route, the authorization attribute and the links between them stay
the app's decision (UserAdminList.razor.cs:17-22, RoleAdminList.razor.cs:12-14,
RoleAdminEdit.razor.cs:13-14). The account roster is the one shipped screen that derives from the
list-page base itself (MMCA.Common.UI/Pages/Administration/UserAdminList.razor:4) and it is generic
over the app's own DTO, constrained only to IUserAdminDTO (UserAdminList.razor.cs:47-48). It has
two data paths: by default it reads through
IUserAdminUIService<TUserDto>
(MMCA.Common.UI/Services/Administration/IUserAdminUIService.cs:17), whose endpoint takes a search
term and a role rather than the grid's per-column filter syntax
(IUserAdminUIService.cs:11-16, :27-32), while an app whose roster lives on its own filtered
endpoint passes a FetchPage delegate instead and the service is never resolved for reads, with the
free-text box injected under the SearchFilterKey filter key (UserAdminList.razor.cs:32-39,
:50-55). The three account actions always go through
IUserAdminActionsUIService
(MMCA.Common.UI/Services/Administration/IUserAdminActionsUIService.cs:16), the non-generic half so a
component that only acts on an account never names the DTO, and they are hidden on the signed-in
operator's own row: an operator who locked or demoted themselves would lose the very capability needed
to undo it, and the API has no notion of "the caller" (UserAdminList.razor.cs:40-44). SetRoleAsync
is its own member rather than a default interface implementation over SetRolesAsync, because a
default implementation is not virtual on the interface a mock proxies, so a test could neither stub
nor verify it (IUserAdminActionsUIService.cs:40-54).
Role administration is non-generic throughout, since a role and a permission are both strings the
framework already owns (IRoleAdminUIService,
MMCA.Common.UI/Services/Administration/IRoleAdminUIService.cs:22, rationale at :11-15). The roster
reports the permissions a role's code grants and the permissions stored rows grant as two separate
counts, because only the stored half is editable and a single total would hide that removing a
compiled permission is a code change (RoleAdminList.razor.cs:16-20). The editor offers only what the
server's catalog declares, so nothing it can submit is a permission no endpoint checks, and it locks
two kinds of checkbox: one the host compiled in for this role, and ManageRoles itself, which guards
this very screen and which the server refuses to store, so offering it would be offering an action
guaranteed to fail (RoleAdminEdit.razor.cs:17-29). The rest are grouped by the area before the first
colon of an area:capability name through the private PermissionGroup record,
with un-prefixed permissions filed under a localized "General" (RoleAdminEdit.razor.cs:39, :245-247,
:338-340). Wording stays the app's: every string these three render is looked up in an app-supplied
IStringLocalizer first and falls back to the framework's
UserAdminListResources,
RoleAdminListResources and
RoleAdminEditResources markers, so "Deactivate" instead of "Lock" costs
no parameter per word (UserAdminList.razor.cs:24-31,
MMCA.Common.UI/Pages/Administration/RoleAdminListResources.cs:9-14). Both implementations,
UserAdminService<TUserDto>
(MMCA.Common.UI/Services/Administration/UserAdminService.cs:26) and
RoleAdminService
(MMCA.Common.UI/Services/Administration/RoleAdminService.cs:24), derive from
AuthenticatedServiceBase rather than the entity-service base, because
these endpoints are not CRUD over an entity resource, and they read every answer back through
ProblemDetailsResultReader inside
HttpResultExecutor so only the caller's own cancellation still propagates
(UserAdminService.cs:15-22, RoleAdminService.cs:64-78, :89-101). [Rubric §18, UI Architecture & Component Design] again: the framework ships the screen, the app keeps the route, the vocabulary and
the DTO.
Two-factor and permission-gated pages follow the same opt-in shape. Two-factor authentication
ships on the notification pattern. TwoFactorUIModule
(MMCA.Common.UI/TwoFactor/TwoFactorUIModule.cs:16), registered by AddTwoFactorUI(), contributes
the account page's navigation item and the layout listener that sends a session refused for want of
a second factor to that page, and a host that never registers it has no page, no nav item and no
listener (TwoFactorUIModule.cs:10-15). TwoFactorPageGate
(MMCA.Common.UI/TwoFactor/TwoFactorPageGate.cs:12) has the router answer the page with the
not-found page whenever the module is absent, because the page needs a client and API endpoints such
a host does not have (:6-11), and the page declares the policy behind
TwoFactorPageRequirement
(MMCA.Common.UI/TwoFactor/TwoFactorPageRequirement.cs:14) instead of a bare [Authorize], so on
such a host every caller reaches the router and gets a 404 rather than a sign-in challenge for a page
that does not exist, the same rule the notification pages follow (:5-13), evaluated by
TwoFactorPageAuthorizationHandler. A permission-gated page
needs no registration at all: HasPagePermissionAttribute
(MMCA.Common.UI/Authorization/HasPagePermissionAttribute.cs:19) requires a signed-in caller whose
token carries the named permission claim, in every head, and checks it with the same
HasPermissionClaim as NavItem.RequiredPermission, so a menu entry and the page it opens cannot
disagree; it reads the claim only, since a UI head has no permission registry, so a role-only token
never passes (:5-17). PagePermissionPolicyConfigurator
(MMCA.Common.UI/Authorization/PagePermissionPolicyConfigurator.cs:16) registers one policy per
permission declared in MMCA.Common.UI or in a registered UI module's assembly when the
authorization options are first built, after the host has registered its modules, and keeps any
policy the host already registered under the same name (:8-14). [Rubric §26, Front-End Security]
and [Rubric §18, UI Architecture].
Writes made offline, and a log the app can show. IOfflineWriteQueue
(MMCA.Common.UI/Services/Offline/IOfflineWriteQueue.cs:11), registered scoped by
AddOfflineWriteQueue (MMCA.Common.UI/DependencyInjection.cs:416), is a durable queue in the
device's local store: each entry belongs to the user signed in when it was queued and is replayed
through the IOfflineWriteHandler registered for its kind, matched ordinally
(IOfflineWriteQueue.cs:5-10, MMCA.Common.UI/Services/Offline/IOfflineWriteHandler.cs:5-9).
OfflineWriteQueue (MMCA.Common.UI/Services/Offline/OfflineWriteQueue.cs:58)
keeps the whole queue as one list under one semaphore, so concurrent callers of one instance never
lose a write, while two tabs or two circuits over one store are not coordinated (:15-20). A replay
walks the user's entries oldest first: an entry older than MaxAge is discarded as Expired without
being sent, an entry with no handler is skipped and kept, a transport failure, a timeout, an
unavailable, too-many-requests or unauthorized answer, or a handler that throws a transport fault keeps
the entry with one more attempt and stops the pass, since every later write would fail the same way;
an unexpected error (a 500 or any unnamed 5xx) or any other thrown exception also keeps the entry but
continues the pass, so one write the server keeps failing never holds back the writes behind it, and
nothing is discarded by attempt count. A commit with an unknown outcome is never resent, because the
write may already be durable: it settles as Rejected with the code attached so the app can read the
item back; any other conflict discards the entry as Conflict and any other failure as Rejected
(:23-40, the outcomes being OfflineWriteOutcome). Each handler answer is
reduced to a private ReplayVerdict, settle with an outcome, keep and stop, or keep
and continue (:276-298, :411-428). A replay starts when the device comes
back online, on the notifier component's first interactive render, and from a single retry timer on
the injected TimeProvider, first set 5 seconds after a replayable write is queued online, whose delay
doubles after each pass that settled nothing and returns to the initial delay after one that settled a
write; the timer is removed when nothing is left to retry, when the device goes offline and on dispose
(:41-53, :61). Signing out clears the local store and the queue with it (:54-56; the clear is the
optional ILocalCacheStore in AuthUIService, MMCA.Common.UI/Services/Auth/AuthUIService.cs:54,
:629). Separately, AddInAppDiagnostics registers InAppLogBuffer
(MMCA.Common.UI/Services/Diagnostics/InAppLogBuffer.cs:11), a bounded, thread-safe in-memory ring
buffer filled by InAppLoggerProvider and read by the InAppDiagnosticsLog
component, held only in process memory so nothing is written to disk or sent anywhere and the entries
are gone on restart (:5-10); its size and lowest recorded level are
InAppDiagnosticsOptions
(MMCA.Common.UI/Services/Diagnostics/InAppDiagnosticsOptions.cs:6-10). [Rubric §29, Resilience]
and [Rubric §13, Observability & Operability].
One composed Blazor web host. The registration list, the request pipeline and the
additional-assembly list every Blazor Server plus WebAssembly head repeats are three calls on
BlazorWebHostExtensions
(MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:44, :32-39). AddMmcaBlazorWebHost(options)
registers, in a fixed order, the service defaults, Razor components with interactive server
components, bounded circuits and the UI rate limiter, MudBlazor, the shared UI services, the session
cookie pair, the trusted-caller header, session-cookie authentication, server token storage, the
same-origin proxy, the web form factor, the Blazor CSP and finally the security headers (:50-61,
:75). UseMmcaBlazorWebPipeline puts the UI rate limiter ahead of the exception handler and the
not-found re-execute, so a throttled request answers 429 without re-rendering a page, adds the
authenticated no-store header, and maps the client-config, session-cookie, same-origin proxy,
culture, static-asset and service-worker endpoints (:166-173, :181, :203), and
GetMmcaRazorComponentAssemblies supplies the head's additional assemblies (:225). What differs
between heads arrives through MmcaBlazorWebHostOptions and
MmcaBlazorWebPipelineOptions; render-mode registration stays per
head, so the package takes no WebAssembly server dependency (:35-38), and a head must not register
ITokenRefresher or ISessionCookieSync after the call, because the same-origin proxy replaces both
and fails the boot when displaced (:62-67).
How it wires up at startup. A host's Program.cs calls AddUIShared(configuration) once, a C#
extension(IServiceCollection) member (see
primer §4) on
DependencyInjection (MMCA.Common.UI/DependencyInjection.cs:36, :44).
In order it binds and validates on start ApiSettings, so a missing endpoint
fails the host rather than the first request (:49-52; its WasmApiEndpoint lets the server call an
internal URL while the browser is handed an external one,
MMCA.Common.UI/Common/Settings/ApiSettings.cs:10, :19-25); binds
LayoutSettings, LegalSettings, RegistrationSettings, SignInSettings and
NotificationBellOptions without validation, deliberately optional so a host that configures none
of them keeps the compiled-in defaults; TryAdds TimeProvider.System as the clock those
staleness policies are measured against; registers the
notification pages' and two-factor page's authorization policies with their handlers, and the
page-permission policy configurator and handler (:82-114); sets up localization, the
pseudo/Mud localizer decorators, the snackbar defaults and the MudBlazor localization interceptor
(:116-144); registers the auth and culture delegating handlers and the named
"APIClient" whose base address comes from ApiSettings and whose timeout is pinned to
HttpResilienceDefaults.TotalRequestTimeout
rather than the BCL's arbitrary 100s, so the transport never pre-empts the resilience budget
(:146-181; when Api:SameOriginApiEndpoint is configured the base address is that proxy endpoint
and SameOriginProxyRequestHandler joins as the innermost handler,
:154-155, :170, :183-189); calls AddCommonUiFacades() for the toast, dialog and pending-toast
facades (:193); then TryAdds AuthUIService (:196),
SignOutNavigator (:199), the email-confirmation client (:203), the
terms-acceptance client (:220), the OAuthFlowStateStore (:224),
the two list-page state services (:225-226), ThemeService (:229),
EndpointCultureApplier (:235), ViewerTimeZone (:239),
NavigationPublicLinkBuilder behind
IPublicLinkBuilder (share-sheet and QR links resolved against the browser
origin, which a MAUI head replaces because its WebView origin is a virtual host nobody else can open,
MMCA.Common.UI/Services/Navigation/IPublicLinkBuilder.cs:9,
MMCA.Common.UI/Services/Navigation/NavigationPublicLinkBuilder.cs:11), the preference reader and writer, and a
default IOAuthUISettings, registered with TryAdd as
ConfigurationOAuthUISettings, which reads provider availability
from the OAuth section for a server host and from pre-computed Enabled flags for a WASM client, so a
head that configures no provider registers nothing and a head with its own rule registers it before
or after the call
(:251-257, MMCA.Common.UI/Services/Auth/OAuth/ConfigurationOAuthUISettings.cs:20, :5-11); and finally
calls AddDeviceCapabilityDefaults() so every capability contract resolves on every head (:266,
ADR-042, chapter 26).
The TryAdd* discipline is what lets a consumer pre-register its own implementation and win. Browser
hosts add AddClientAuthSessionCookieSync() (:303) and AddWasmFormFactor() (:315); a
Blazor Server head adds AddCommonServerTokenStorage(), AddCommonBlazorCsp() (before
AddCommonSecurityHeaders, so it beats the TryAdded static provider) and
AddCommonWebFormFactor() from MMCA.Common.UI.Web
(MMCA.Common.UI.Web/DependencyInjection.cs:40, :67, :85; the first also registers BrowserOriginHandler, :47-48) plus the
UseAuthenticatedNoStore() middleware. A Blazor Web host that should install as a web app with an offline page also maps MapCommonServiceWorker() from ServiceWorkerEndpointExtensions (MMCA.Common.UI.Web/Pwa/ServiceWorkerEndpointExtensions.cs:15, :60-70): an anonymous GET /service-worker.js at the root so the worker's scope covers the whole site, excluded from the OpenAPI description and served no-cache (:17-18, :34-37), while the host supplies the app identity (manifest, icons, theme-color, :10-14). The worker never caches pages or data, because a server-rendered page carries the signed-in user's data: it sends every GET navigation to the network and falls back to the offline page only when the network fails, leaving every other request to the browser (:40-46). The package version is written into the embedded script, so each framework release is a byte change the browser installs on its next update check (:48-51, :73-84), and setting Pwa:ServiceWorker:Enabled to false serves a retired worker with no fetch handler that deletes the offline cache, so retiring a bad worker is a configuration change rather than a release (:24, :52-57, :64-66). The administration screens are opt-in on the same pattern:
AddUserAdministrationUI<TUserDto>() registers the generic service and forwards the non-generic
actions contract to that same instance, so the roster and the actions it performs go through one
object and one substitute in a test (MMCA.Common.UI/DependencyInjection.cs:324-331), and
AddRoleAdministrationUI() registers the role client (:359-361); nothing in the framework calls
either, so an app serving no administration endpoints registers nothing and the components are
simply never rendered. An
SSR host behind the gateway also calls AddTrustedCallerHeader(configuration), which composes
TrustedCallerHandler
(MMCA.Common.UI.Web/Security/TrustedCallerHandler.cs:35) onto every HttpClient the host creates,
inserted at index 0 so the origin gate judges the authority the caller wrote rather than one Aspire's
service-discovery handler has already rewritten (MMCA.Common.UI.Web/DependencyInjection.cs:112,
:143-156), and registers nothing at all when no secret, header name or parseable gateway origin is
configured (the early return at :137). The breadth is the point: the call that suffers most from the gateway's per-IP
limiter partition, the cookie-session token refresh, is created by the framework under a name a host
cannot reach, while the handler itself stays narrow, stamping the secret only on a request whose
scheme, host and port match the gateway origin and replacing rather than appending the header, because
the gateway compares one single-valued header in constant time (TrustedCallerHandler.cs:9-27,
:67-79). UISharedAssemblyReference
(MMCA.Common.UI/DependencyInjection.cs:501) is the marker other assemblies scan against.
How a WebAssembly client learns its API address. The WASM bundle is static, so the API base
address is fetched at runtime rather than baked in. On the server side,
ClientConfigEndpointExtensions
(MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:19) adds
MapClientConfigEndpoint, an anonymous GET /client-config excluded from the OpenAPI description
whose framework-owned Api section carries Api:WasmApiEndpoint (:22, :25, :84-131). It
fails closed: when that key is missing or is not an absolute http(s) URL (a deployment placeholder,
for one) it throws rather than fall back to Api:ApiEndpoint, which is the server head's
service-discovery name a browser cannot resolve, so the client fails to start instead of pointing at
the wrong API (:42-48, :87-95). When the host runs the same-origin proxy, the same api section
also carries sameOriginApiEndpoint, the proxy prefix with a trailing slash, which is what moves the
client's "APIClient" onto it (:144-160). Beside it the document forwards the server head's own
settings so the client does not drift after hydration: a modules section carrying only each
configured module's resolved enabled flag, so a module the head disables does not come back on the
client (:27-31, :51-57, :138-142); the layout, registration, signIn and legal sections
built by ClientConfigUiSections, limited to the keys the server actually
sets (:59-65, :108-114); and an oAuth section built by
ClientConfigOAuthSection
(MMCA.Common.UI.Web/ClientConfig/ClientConfigOAuthSection.cs:20), which projects the head's
IOAuthUISettings into exactly the shape
ConfigurationOAuthUISettings reads on the client, so the sign-in
page lists the same providers after hydration as the prerender did (:6-11;
ClientConfigEndpointExtensions.cs:66-72, :116-121). That projection is two private records,
OAuthFlags for the Google, GitHub and Apple flags plus one
OidcProviderFlags entry per OIDC provider with its enabled flag, display name
and whether it uses email domains, and it forwards availability only, never a client id, secret,
authority or domain list, because the document is anonymous; a head that registers no
IOAuthUISettings gets no section (ClientConfigOAuthSection.cs:12-16, :31-45, :47-55). The
endpoint declares AllowAnonymous itself, because the client fetches the document before it can hold
a session and a host's fallback policy would otherwise gate it (ClientConfigEndpointExtensions.cs:73-78,
:130). A host adds its own sections through a per-request
ClientConfigBuilder
(MMCA.Common.UI.Web/ClientConfig/ClientConfigBuilder.cs:19), whose Add refuses a blank name, the
reserved Api and Modules sections and a duplicate, and whose remarks warn that everything added is
served to every browser before sign-in, so only public values belong there (:14-18, :41-62). The
host's sections are written last, so one under a forwarded name replaces the forwarded copy, which is
why a host must not add its own OAuth section: it would drop the OIDC providers
(ClientConfigEndpointExtensions.cs:123-126, ClientConfigOAuthSection.cs:16-18). The client
half is MmcaClientConfigBootstrap
(MMCA.Common.UI/Common/Settings/MmcaClientConfigBootstrap.cs:28), whose LoadAsync fetches the
document from the app's own origin with a 15-second per-attempt timeout and a single retry after one
second (for the cold-start case where the Server host is still warming), then rethrows a second
failure on purpose, and returns a buffered stream because browser fetch streams do not support the
synchronous reads AddJsonStream performs (:12-26, :34, :37, :49, :72-90). Only an HTTP
failure or the timeout it did not ask for is retried, never the caller's own cancellation (:83).
When the document carries an origin-relative sameOriginApiEndpoint, the bootstrap resolves it
against the address the document was fetched from, since the server cannot know the public origin a
browser used behind ingress, and returns any other document byte for byte (:89, :92-124). ADC
wires both halves, the server half through the ClientConfig callback it hands
UseMmcaBlazorWebPipeline
(MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:120,
MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:162,
MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web.Client/Program.cs:30).
The small Level-0 supporting cast fills in the rest: NotificationRoutePaths
(MMCA.Common.UI/Common/NotificationRoutePaths.cs:6), whose deep-link builder formats invariantly
because the route's :int constraint is the validation boundary (:14-20);
QrErrorCorrectionLevel, the framework's own enum for QrCodeImage so the
component's public API does not pin consumers to QRCoder's ECCLevel
(MMCA.Common.UI/Components/Sharing/QrErrorCorrectionLevel.cs:9);
RatingStars (MMCA.Common.UI/Components/Ratings/RatingStars.razor.cs:13), five
read-only stars out of a MaxValue of 5 rendered as one role="img" element whose required
AriaLabel carries the numeric figure, so the stars stay decorative rounding (whole stars fill, a
half star shows at .5 and above, :6-11, :16, :31-33, :46-54), which the ADC feedback and
speaker dashboards render
(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Feedback/OrganizerSessionFeedback.razor:67);
ApiFileDownloadButton
(MMCA.Common.UI/Components/Forms/ApiFileDownloadButton.razor.cs:20), which gives browsers a plain download
link and native heads a fetch-then-save flow through the head's ISensitiveFileSaver, stripping
directory segments from the supplied file name so a value built from entity data cannot steer the write
out of the staging folder (:11-19, :30-39);
and MauiBackNavigationBridge with its
BackNavigationResult for MAUI hardware-back handling, which reports both
whether history.back() fired and whether the WebView is at the root of its stack so a host can decide
to exit (MMCA.Common.UI/Services/Navigation/MauiBackNavigationBridge.cs:19, :28). Device
capabilities (clipboard, external links, maps, speech and the like) live in their own layer
(IExternalLinkService and friends, chapter 26). The
presentational helper MoneyExtensions formats
Money for display, grouping a mixed collection by
currency so unrelated amounts never collapse under whichever symbol came first
(MMCA.Common.UI/Extensions/MoneyExtensions.cs:14, the single-price form at :29-30 and the
collection form at :33), keeping a display concern out of the
domain value object, exactly where Clean Architecture wants it.
Read the per-type sections that follow for the mechanics. The consumer-side module UIs live in the ADC
module-UI chapter (chapter 21), and the bUnit component tests plus the
Playwright/axe-core E2E suite that exercise this package are covered in the testing chapter
(chapter 27), which is where [Rubric §28, Front-End Testing]
lives.
PagePermissionPolicy
MMCA.Common.UI ·
MMCA.Common.UI.Authorization·MMCA.Common/Source/Presentation/MMCA.Common.UI/Authorization/PagePermissionPolicy.cs:9· Level 0 · class (static)
- What it is: the naming rule for the page permission policies. It turns a permission name such as
conference:sessions:manageinto the policy name a HasPagePermissionAttribute asks for. - Depends on: nothing.
- Concept introduced, a policy name as a shared contract. ASP.NET Core authorization looks a policy up by string, so the attribute that names a policy and the code that registers it must agree on the exact string. Putting the format in one static class makes that agreement a compile-time reference rather than two copies of a literal.
[Rubric §26, Front-End Security]assesses whether client-side route guards are consistent and hard to get wrong; one builder used by both sides is how this code keeps the guard and its registration from drifting. - Walkthrough:
Prefix = "page-perm:"(PagePermissionPolicy.cs:12) andNameFor(string permission) => Prefix + permission(PagePermissionPolicy.cs:17). Nothing else. - Why it's built this way: the class doc comment (
PagePermissionPolicy.cs:3-8) records why the prefix differs from the API'sperm:: the API's policy provider, which a web host may install by replacement, intercepts everyperm:name, while apage-perm:name falls through to the default provider and so reaches the policyAddUISharedregistered. A distinct prefix is what lets the page guard coexist with ADR-020's API policies on a Blazor Web head that hosts both. - Where it's used: the HasPagePermissionAttribute constructor passes
NameFor(permission)to its base (MMCA.Common/Source/Presentation/MMCA.Common.UI/Authorization/HasPagePermissionAttribute.cs:24), and PagePermissionPolicyConfigurator registers under the same name (MMCA.Common/Source/Presentation/MMCA.Common.UI/Authorization/PagePermissionPolicyConfigurator.cs:35). The permission-coverage fitness rule strips the same prefix to recover the permission from an[Authorize(Policy = ...)](MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Api/ArchitectureRules.PermissionCoverage.cs:16,:140-142). - Caveats / not-in-source: the fitness rule keeps its own
"page-perm:"literal (ArchitectureRules.PermissionCoverage.cs:16) rather than referencingPrefix, so the two strings agree by convention, not by the compiler.
PagePermissionRequirement
MMCA.Common.UI ·
MMCA.Common.UI.Authorization·MMCA.Common/Source/Presentation/MMCA.Common.UI/Authorization/PagePermissionRequirement.cs:11· Level 0 · record (internal, sealed)
- What it is: the authorization requirement behind every page permission policy: the caller's token carries a
permissionclaim equal toPermission. - Depends on:
Microsoft.AspNetCore.Authorization.IAuthorizationRequirement(PagePermissionRequirement.cs:1). - Concept: the requirement/handler split of ASP.NET Core authorization, the same shape as NotificationPageRequirement in this group: a requirement is pure data, and a separate handler decides whether it is met.
- Walkthrough: one positional record,
internal sealed record PagePermissionRequirement(string Permission) : IAuthorizationRequirement;(PagePermissionRequirement.cs:11). The doc comment (PagePermissionRequirement.cs:5-10) names its evaluator, PagePermissionAuthorizationHandler. - Why it's built this way: internal, because nothing outside the framework constructs one; a host only writes the attribute. A record gives value equality for free, which is all a requirement needs.
- Where it's used: constructed once per declared permission by PagePermissionPolicyConfigurator (
MMCA.Common/Source/Presentation/MMCA.Common.UI/Authorization/PagePermissionPolicyConfigurator.cs:40). The shipped nav-guard contract base recognizes it by type name to model what a guarded page demands (MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Navigation/NavItemGuardContractTestsBase.cs:50,:313-315), which is why it can stay internal.
UISharedAssemblyReference
MMCA.Common.UI ·
MMCA.Common.UI·MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:505· Level 0 · class
- What it is: an empty marker class whose only job is to give code a compile-checked
typeof(...).Assemblyhandle on the shared UI assembly. - Depends on: nothing.
- Concept introduced, the assembly-marker type. Reflection over an assembly needs an
Assemblyinstance, and there are two ways to get one: a string (Assembly.Load("MMCA.Common.UI"), which fails at run time when someone renames the project) or a type reference (typeof(UISharedAssemblyReference).Assembly, which fails at compile time and is carried along by a rename refactoring). Every layer of the framework ships an equivalent marker; this is the UI layer's.[Rubric §15, Best Practices & Code Quality]assesses exactly this kind of refactor-safety over stringly-typed lookups. - Walkthrough: a single declaration using the semicolon type body,
public class UISharedAssemblyReference;(DependencyInjection.cs:505), with its doc comment on line 513. It shares a file with DependencyInjection but is declared at namespace scope beneath it, outside that static class, because a type nested inside a static class could not serve as a public marker the same way. It carries no members, so nothing can accidentally depend on state it does not have. - Why it's built this way: type-only, public and empty is the whole point. It is the assembly's identity expressed as a symbol the compiler tracks.
- Where it's used: the architecture fitness suite is the real consumer.
CommonArchitectureMapregisters the assembly as the framework's UI layer withFramework(Layer.Ui, typeof(Common.UI.UISharedAssemblyReference).Assembly)(MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/CommonArchitectureMap.cs:27), which is what lets the shared layer-dependency rules know which assembly is the UI layer;AnonymousEndpointTestsincludes it in the assemblies it scans (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Api/AnonymousEndpointTests.cs:19); andNavigationContractTestsenumerates its types withtypeof(UI.UISharedAssemblyReference).Assembly.GetTypes()(MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Ui/NavigationContractTests.cs:105).[Rubric §34, Architecture Governance & Documentation]applies: this one-line type is what makes a layer boundary machine-checkable. - Caveats / not-in-source: the doc comment (
DependencyInjection.cs:504) offers "e.g., for assembly scanning" as the motivating case, but no assembly-scanning registration in this file takes its scan root from this marker.AddUIModule<TModule>()passestypeof(TModule).AssemblytoAddAssignableTypes(DependencyInjection.cs:493-497), taking the root from the module descriptor's own assembly instead. Trust the call sites: the current consumers are the architecture tests.
HasPagePermissionAttribute
MMCA.Common.UI ·
MMCA.Common.UI.Authorization·MMCA.Common/Source/Presentation/MMCA.Common.UI/Authorization/HasPagePermissionAttribute.cs:19· Level 1 · class (sealed attribute)
- What it is: the attribute a Blazor page puts on itself to require a signed-in caller whose token carries a given permission claim, in every UI head (web, WebAssembly and MAUI), for example
@attribute [HasPagePermission(ConferencePermissions.ActivitiesManage)](MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Activities/ActivityList.razor:2). - Depends on: PagePermissionPolicy;
Microsoft.AspNetCore.Authorization.AuthorizeAttribute(HasPagePermissionAttribute.cs:1,:19). - Concept introduced, the page-side twin of a menu permission. The doc comment (
HasPagePermissionAttribute.cs:5-10) states the design goal: the attribute and NavItem'sRequiredPermissioncheck the claim with the sameHasPermissionClaim(ClaimsPrincipalExtensions,MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:128), so a menu entry gated on a permission and the page it opens cannot disagree; the menu runs that check atMMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor.cs:125.[Rubric §25, Navigation & IA]assesses whether navigation and route access are consistent; here the two derive from one predicate.[Rubric §26, Front-End Security]assesses route guards: the attribute derives fromAuthorizeAttribute, so the Blazor router's standard[Authorize]handling applies it, rather than each page checking in code. The server-side counterpart is ADR-020's API permission policy; this attribute is a UI guard only, and the API still authorizes every call itself. - Walkthrough:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)](HasPagePermissionAttribute.cs:18). The constructor passesPagePermissionPolicy.NameFor(permission)to the base as the policy name and keeps the raw permission (HasPagePermissionAttribute.cs:23-24), exposed asPermission(HasPagePermissionAttribute.cs:27) so the configurator can read it back by reflection. - Why it's built this way: the second paragraph of the doc comment (
HasPagePermissionAttribute.cs:11-16) gives the two decisions. No registration is needed, becauseAddUISharedregisters one policy per permission declared on a component inMMCA.Common.UIor in any registered UI module's assembly (see PagePermissionPolicyConfigurator). And the check reads the claim only, because a UI head has no permission registry, so it suits a host whose token issuer stamps permission claims; a role-only token never passes. - Where it's used: ADC's Conference management pages (for example the activity, category and event list, create and detail pages,
MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Events/EventList.razor:2); the module descriptor notes that its nav items require the same permissions so an editor sees exactly the entries its grant opens (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/ConferenceUIModule.cs:27). The permission-coverage fitness rule reads the attribute by full name and itsPermissionvalue (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Api/ArchitectureRules.PermissionCoverage.cs:9,:120).
PagePermissionAuthorizationHandler
MMCA.Common.UI ·
MMCA.Common.UI.Authorization·MMCA.Common/Source/Presentation/MMCA.Common.UI/Authorization/PagePermissionAuthorizationHandler.cs:12· Level 1 · class (internal, sealed)
- What it is: the handler that decides a PagePermissionRequirement: it succeeds when the principal carries the permission claim.
- Depends on: PagePermissionRequirement,
HasPermissionClaimfrom ClaimsPrincipalExtensions (PagePermissionAuthorizationHandler.cs:2);AuthorizationHandler<TRequirement>. - Concept: cross-reference NotificationPageAuthorizationHandler, which uses the same
HasPermissionClaimfor its optional permission (MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationPageAuthorizationHandler.cs:39). - Walkthrough:
HandleRequirementAsync(PagePermissionAuthorizationHandler.cs:15-28) guards both arguments (:19-20), callscontext.Succeed(requirement)only whencontext.User.HasPermissionClaim(requirement.Permission)(:22-25), and returnsTask.CompletedTask(:27). It never callsFail, so a missing claim simply leaves the requirement unmet. - Why it's built this way: the doc comment (
PagePermissionAuthorizationHandler.cs:6-11) callsHasPermissionClaimthe framework's single definition of a token-granted permission and the same check the nav menu runs, so page and menu entry cannot disagree. The handler does not test authentication itself: the policy addsRequireAuthenticatedUser()(PagePermissionPolicyConfigurator.cs:39), so an unauthenticated principal never passes. - Where it's used: registered by
AddUISharedthroughTryAddEnumerableas a transientIAuthorizationHandler(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:113-114).
PagePermissionPolicyConfigurator
MMCA.Common.UI ·
MMCA.Common.UI.Authorization·MMCA.Common/Source/Presentation/MMCA.Common.UI/Authorization/PagePermissionPolicyConfigurator.cs:16· Level 3 · class (internal, sealed)
- What it is: an
IConfigureOptions<AuthorizationOptions>that discovers every permission a HasPagePermissionAttribute declares and registers one policy for each, so a host adds a guarded page with no registration call of its own. - Depends on: IUIModule (primary constructor,
PagePermissionPolicyConfigurator.cs:16), PagePermissionPolicy, HasPagePermissionAttribute, PagePermissionRequirement;System.ReflectionandMicrosoft.Extensions.Options(PagePermissionPolicyConfigurator.cs:1-3). - Concept introduced, options configuration as late discovery. An
IConfigureOptions<T>runs when the options instance is first built, not when it is registered. The doc comment (PagePermissionPolicyConfigurator.cs:8-14) relies on exactly that: it runs after the host has registered its modules, so the module list it scans is complete regardless of whetherAddUISharedwas called before or after theAdd{Module}UI()calls.[Rubric §33, Developer Experience]assesses how many steps a common change takes; adding a guarded page here is one attribute. - Walkthrough:
Configure(PagePermissionPolicyConfigurator.cs:20-43) builds the permission set as one LINQ pipeline (:24-31): every module'sAssembly(:25), plus the framework's own UI assembly (:26), deduplicated (:27), flattened to their types throughLoadableTypes(:28), each type'sHasPagePermissionAttributes read withinherit: true(:29), projected toPermission(:30) and deduplicated ordinally (:31). For each permission it computes the policy name (:35) and, only whenoptions.GetPolicy(name)is null (:36), adds a policy that requires an authenticated user and a PagePermissionRequirement (:38-40).LoadableTypes(:47-57) returnsassembly.GetTypes()and, on aReflectionTypeLoadException, the types that did load (:53-55); its comment (:45-46) explains that a module assembly referencing something the head does not load would otherwise fail the whole scan. - Why it's built this way: keeping an existing policy of the same name (
:36) leaves the host the last word, consistent with theTryAddconvention of DependencyInjection. Scanning the registered modules, rather than every loaded assembly, bounds the reflection to the assemblies that can contribute routable pages. - Where it's used: registered by
AddUISharedthroughTryAddEnumerableas a transientIConfigureOptions<AuthorizationOptions>(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:111-112); its module list comes from theAddSingleton<IUIModule, TModule>()thatAddUIModule<TModule>()performs (DependencyInjection.cs:499). - Caveats / not-in-source: the framework assembly is scanned too (
:26), but no.razoror.csfile underMMCA.Common/Source/Presentationapplies the attribute today, so in practice the policies come from module assemblies.
DependencyInjection
MMCA.Common.UI ·
MMCA.Common.UI·MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:36· Level 10 · class (static, with oneextension(IServiceCollection)block)
- What it is: the composition root of the UI layer. One
AddUIShared(configuration)call wires the shared UI infrastructure every head needs (Blazor Server, WebAssembly, MAUI), and eleven smaller methods cover the per-head, per-module and per-opt-in registrations. - Depends on: nearly the whole group. Settings: ApiSettings / ApiSettingsValidator, LayoutSettings, LegalSettings, RegistrationSettings, SignInSettings, NotificationBellOptions. Authorization: NotificationPageRequirement / NotificationPageAuthorizationHandler, TwoFactorPageRequirement / TwoFactorPageAuthorizationHandler, PagePermissionPolicyConfigurator / PagePermissionAuthorizationHandler. Localization: PseudoStringLocalizerFactory, ResxMudLocalizer, InvariantMudLocalizationInterceptor. Snackbar: SnackbarDefaults. HTTP: AuthDelegatingHandler, CultureDelegatingHandler, SameOriginProxyRequestHandler, HttpResilienceDefaults. Facades: IToastService / MudToastService, IAppDialogService / MudAppDialogService, IPendingToastService / PendingToastService. Services: IAuthUIService / AuthUIService (which also backs ISignInLinkUIService and IPasskeyUIService), SignOutNavigator, IEmailConfirmationUIService / EmailConfirmationUIService, IOidcDiscoveryUIService / OidcDiscoveryUIService, ILegalAcceptanceUIService / LegalAcceptanceUIService, OAuthFlowStateStore, ListPageStateService, ListPageQueryStateService, ThemeService, ICultureApplier / EndpointCultureApplier, ViewerTimeZone, IPublicLinkBuilder / NavigationPublicLinkBuilder, IUserPreferenceWriter / ApiUserPreferenceWriter, IUserPreferenceReader / ApiUserPreferenceReader, IOAuthUISettings / ConfigurationOAuthUISettings, IForbiddenReExecutionDetector / NoForbiddenReExecutionDetector, ISessionCookieSync / JsFetchSessionCookieSync. Opt-ins: IUserAdminUIService<TUserDto> / UserAdminService<TUserDto>, IUserAdminActionsUIService, IRoleAdminUIService / RoleAdminService, IMachineClientAdminUIService / MachineClientAdminService, IViewAsGrantsUIService / ViewAsGrantsService, IAuditHistoryUIService / AuditHistoryService, IOfflineWriteQueue / OfflineWriteQueue / OfflineWriteQueueOptions / IOfflineWriteHandler, IFeatureFlagAdminUIService / FeatureFlagAdminService / FeatureFlagAdminUIOptions. Composition: IUIModule, IEntityService<TEntityDTO, TIdentifierType>, and the framework's own internal registration helpers ServiceCollectionDecoration (
DecorateWith,AddAssignableTypes) and ScanRegistration, reached throughusing MMCA.Common.DependencyInjection(DependencyInjection.cs:7). Externals: MudBlazor, andMicrosoft.AspNetCore.AuthorizationplusMicrosoft.Extensions.{Configuration, DependencyInjection, Localization, Options}(DependencyInjection.cs:1-28). - Concept introduced, the composition root written as an
extension(T)block. The whole registration surface lives insideextension(IServiceCollection services)(DependencyInjection.cs:38) rather than as classicthis-parameter extension methods; the class doc comment calls them C# extension members (DependencyInjection.cs:32-35). See primer, C# extension(T) types for the language mechanics, taught once.[Rubric §15, Best Practices & Code Quality]assesses one consistent idiom across layers, and this file matches the otherDependencyInjectionclasses in every layer of the workspace.[Rubric §33, Developer Experience]assesses fail-fast startup and a small number of calls per host.[Rubric §12, Performance & Scalability]assesses whether concerns are wired once, centrally: localization, snackbar defaults, culture forwarding, authentication, page authorization and the HTTP time limit are all configured here rather than per page. - Walkthrough: twelve methods in the extension block.
AddUIShared(IConfiguration configuration)(:44-269), in order:- Options. ApiSettings binds with
.ValidateOnStart()(:49-51) andTryAddEnumerableregisters the source-generated ApiSettingsValidator as itsIValidateOptions<ApiSettings>(:52); the comment (:46-48) records why: the validator checks the data annotations with no reflection and noOptions.DataAnnotationspackage on a WebAssembly client. A missingApiEndpointtherefore fails the host at startup rather than at the first HTTP call. LayoutSettings binds without validation because empty defaults are acceptable (:55-56), and so do LegalSettings (:60-61, the footer, registration-checkbox and terms-dialog links; an absent section leaves every URL empty, which renders none of them, per:58-59), RegistrationSettings (:65-66, the optional blocks of the shared register page; an absent section keeps every block), SignInSettings (:70-71, the optional actions of the shared sign-in pages such as sign-in links under ADR-116; an absent section offers nothing new, per:68-69) and NotificationBellOptions (:74-75, an absent section leaving the compiled-in defaults, per:73). - Clock.
TryAddSingleton(TimeProvider.System)(:80), the clock the notification bell and the stale-toast sweep measure against, with a comment explaining both directions of theTryAdd(:77-79): a host that already registered one, asAddInfrastructuredoes, keeps it, and a test substitutes aFakeTimeProvider. - Page policies. One
AddAuthorizationCorecall (:86-102) registers three policies:NotificationPageRequirement.PolicyNamecarrying a plain NotificationPageRequirement (:88-90),NotificationPageRequirement.ManagePolicyNamecarrying one built withNotificationPermissions.Manage(:91-93), the policy for the history and compose pages, andTwoFactorPageRequirement.PolicyNamecarrying a TwoFactorPageRequirement (:99-101).TryAddEnumerableadds the transient NotificationPageAuthorizationHandler and TwoFactorPageAuthorizationHandler (:103-106). The comments state the shared rule:[Authorize]semantics (plusnotifications:managefor the history and compose pages), except that a host without the notification UI (noAddNotificationUI) lets the request reach the router, which answers 404 instead of the sign-in challenge or Access Denied (:82-85); the two-factor account page follows the same rule for a host withoutAddTwoFactorUI, and its policy is registered unconditionally so the page's attribute resolves in every host (:95-98). Then the page permission guards:TryAddEnumerableregisters PagePermissionPolicyConfigurator as a transientIConfigureOptions<AuthorizationOptions>(:111-112) and PagePermissionAuthorizationHandler as a transientIAuthorizationHandler(:113-114). The comment (:108-110, ADR-020) explains that there is one policy per permission a page declares through HasPagePermissionAttribute, discovered from the registered UI modules when the options are first built, so a host adds a guarded page without a registration call of its own[Rubric §26, Front-End Security]. - Localization (ADR-027).
AddLocalization()(:117) forIStringLocalizer<T>, thenDecorateWith<IStringLocalizerFactory, PseudoStringLocalizerFactory>()(:124), the framework's own decoration helper on ServiceCollectionDecoration, which throws when noIStringLocalizerFactoryis registered (MMCA.Common/Source/Build/DependencyInjection/ServiceCollectionDecoration.cs:166). It is registered unconditionally because the pseudo-locale transform is inert under every other culture and the pseudo locale is only ever activatable in Development (:119-123).TryAddTransient<MudBlazor.MudLocalizer, ResxMudLocalizer>()(:130) localizes MudBlazor's own component text; the comment (:126-129) records whyTryAddis authoritative regardless of host registration order, namely thatAddMudServicesregisters noMudLocalizerof its own and a DI resolution test guards that assumption. - Snackbar defaults.
SnackbarDefaults.Register(services)(:135) applies, through SnackbarDefaults, the snackbar position and on-screen cap every head shares; the comment (:132-134) notes that MudToastService's pinned-toast eviction is measured against that cap, and that it is registered as the first configure step, so a host that configures the snackbar itself still wins whichever order it callsAddMudServicesin. - Interceptor.
AddLocalizationInterceptor<InvariantMudLocalizationInterceptor>()(:144) follows: MudBlazor's own default interceptor reads its built-in English strings by assigningCultureInfo.CurrentUICulture(invariant, then the previous value back), which writes anAsyncLocalculture into the calling context; on a MAUI hybrid head, where that is the main thread, nothing resets it and the app pins to its launch language even after a culture switch reloads the thread defaults. InvariantMudLocalizationInterceptor reads the same resource under an explicit invariant culture instead, and registers with replace semantics so it wins whetherAddMudServicesran before or after this call (ADR-027 Decision 10) (:137-143). - The one HTTP client. Both delegating handlers register transient (
:148-149). Before the client itself,usesSameOriginProxyis computed from the raw configuration (:154-155): it is true only whenApi:SameOriginApiEndpointcarries a value, which per the comment (:151-153) happens only on a WebAssembly client whose Server host opted into the same-origin API proxy (ADR-131) and handed that value down through/client-config; every other host (Server, MAUI, a WASM client of a host that did not opt in) keeps the pipeline unchanged. Then the named"APIClient"(:158-181), whose builder is kept inapiClient(:158) so a handler can be appended afterwards. Its factory resolvesIOptions<ApiSettings>(:165) and setsclient.BaseAddress = new Uri(apiSettings.SameOriginApiEndpoint ?? apiSettings.ApiEndpoint!, UriKind.Absolute)(:170): the same-origin proxy base, when present, replaces the gateway URL for data calls, and the comment (:167-169) notes the bootstrap has already resolved it to an absolute address. There is deliberately no hand-written endpoint guard, and the comment says why (:160-164): resolving.Valueruns theApiSettingsValidatorregistered above, so a missing[Required]endpoint already fails as anOptionsValidationException, and a second check would only give the same failure a different, less informative exception.client.Timeoutis pinned to HttpResilienceDefaults.TotalRequestTimeout(:176), and the comment (:172-175) says why it matters: this is the one time limit on the client in every render mode, because WebAssembly and MAUI add no resilience handler and the Blazor web host (AddMmcaBlazorWebHost) removes the oneAddServiceDefaults()puts on every factory client; it is the shared 90-second total-request timeout rather than the BCL's 100-second default[Rubric §29, Resilience & Business Continuity]. Default headers are cleared andAccept: application/jsonadded (:177-178), and the two handlers chain in order (:180-181) so every outgoing call carries both the bearer token and the active UI culture asAccept-Language(:146-147). WhenusesSameOriginProxyis true, SameOriginProxyRequestHandler is registered transient and appended as the innermost handler (:183-189); the comment (:185-186) gives the reason for that position: it must see, and strip, everyAuthorizationheader the outer handlers or a service'sDefaultRequestHeadersattached, and it stamps the proxy's CSRF header[Rubric §26, Front-End Security]. - Facades.
services.AddCommonUiFacades()(:193), factored out so a bUnit harness can register exactly these three without pulling in the whole shared-UI surface (:191-192). - Scoped services, all via
TryAddso several composing hosts cannot double-register: IAuthUIService to AuthUIService (:196); SignOutNavigator (:199, signing out and landing on a chosen page in one navigation withoutRedirectToLoginracing it, per:198); IEmailConfirmationUIService to EmailConfirmationUIService (:203, the/confirm-emailpage's client per ADR-116; a separate interface rather than newIAuthUIServicemembers, so a consumer's ownIAuthUIServiceimplementation keeps compiling, per the comment at:201-202); ISignInLinkUIService (:207) and IPasskeyUIService (:212, ADR-139), both mapped onto the framework'sAuthUIServiceso a redeemed link or a passkey sign-in stores its tokens through the same path a password sign-in does (:205-206,:209-211; the passkey client is inert until a host offers passkeys throughSignIn:OfferPasskeysor renders the passkeys panel); IOidcDiscoveryUIService to OidcDiscoveryUIService (:216, home-realm discovery for the sign-in page's "Sign in with your organization" step, inert until the host configures an OIDC provider that declares email domains, per:214-215); ILegalAcceptanceUIService to LegalAcceptanceUIService (:220, the terms-acceptance client behindTermsAcceptanceGate, registered for every host and inert until a host renders the gate, per:218-219); OAuthFlowStateStore (:224, binding an OAuth completion to the flow this client started so a deep-linked completion code from someone else's provider round trip is dropped instead of exchanged, per:222-223); ListPageStateService (:225) and ListPageQueryStateService (:226); ThemeService (:229, ADR-028); ICultureApplier defaulting to EndpointCultureApplier (:235); ViewerTimeZone (:239, the viewer's browser time zone, so UTC instants such as notification and session times render on the clock the person reads, per:237-238); IPublicLinkBuilder defaulting to NavigationPublicLinkBuilder (:245); and the per-user preference writer and reader, ApiUserPreferenceWriter and ApiUserPreferenceReader (:248-249), documented as best-effort and a no-op for an anonymous user (:247). Two singletons close the list:TryAddSingleton<IOAuthUISettings>(_ => new ConfigurationOAuthUISettings(configuration))(:257), which reads OAuth provider availability through ConfigurationOAuthUISettings from the OAuth section of the configuration handed toAddUIShared, offers no provider when there are no OAuth keys, and reads that configuration when first resolved so a source the head adds afterwards still counts; a head with its own rule registers it withTryAddbefore the call or withAddSingletonafter (:251-256), andTryAddSingleton<IForbiddenReExecutionDetector, NoForbiddenReExecutionDetector>()(:262), the not-found page's "is this a 403 re-execution" question, which always answers false because a WebAssembly or MAUI head has no request to read; the Blazor Web host replaces it with the request-reading one (:259-261). - Capabilities.
AddDeviceCapabilityDefaults()(:266, ADR-042) so every capability contract resolves on every head, registered here specifically so MAUI and browser hosts can override afterwards under last-registration-wins (:264-265).
- Options. ApiSettings binds with
AddCommonUiFacades()(:289-295): threeTryAddScopedcalls, IToastService to MudToastService (:291), IAppDialogService to MudAppDialogService (:292) and IPendingToastService to PendingToastService (:293), the toast that survives aforceLoadnavigation and is injected by the shared layout'sPendingToastHost. Its doc comment (:271-288) is the clearest statement of the facade rule anywhere in the codebase: apart from the two Mud-backed implementations (and theConfirmationDialogthey open), the only framework type that names MudBlazor'sISnackbaris StaleToastSweeper, which injects it to remove toasts a navigation left behind, askingMudToastServicewhich of them are pinned (:276-278); pages, other components and theResulthelpers depend on the contracts, so a test can record toasts without a rendered snackbar host. They are scoped to match the MudBlazor services they wrap, and the method is called both byAddUISharedand by the shipped bUnit base so a component test resolves the facades without the rest of the shared-UI surface (:280-285).AddClientAuthSessionCookieSync()(:303-307): oneTryAddScoped<ISessionCookieSync, JsFetchSessionCookieSync>()(:305), the browser session-cookie sync. Its doc comment (:297-302) states the contract: it clears the HttpOnly session cookies at logout and writes nothing on sign-in, because the server is the only writer of those cookies. Called from both the Blazor Server host and the WebAssembly client.AddUserAdministrationUI<TUserDto>()(:324-334), the ADR-116 UI opt-in for user administration: registers IUserAdminUIService<TUserDto> to UserAdminService<TUserDto> (:326), then forwards IUserAdminActionsUIService to the same instance rather than registering it a second time (:330-331), so the actions the component performs and the reads the app makes go through one instance (and one substitute, in a test), per the comment at:328-329. The doc comment (:309-323) states the call convention (once per app, afterAddUIShared, with the app's own administration DTO) and that an app which serves no administration endpoints registers nothing and the component the service backs is simply never rendered.AddRoleAdministrationUI()(:350-355): the non-generic ADR-116 sibling, registering IRoleAdminUIService to RoleAdminService (:352). Its doc comment (:336-349) explains why it takes no type parameter unlikeAddUserAdministrationUI<TUserDto>(): roles and permissions are strings the framework already owns, so there is no app DTO to name (:343-344).AddMachineClientAdministrationUI()(:365-370), the ADR-140 opt-in: IMachineClientAdminUIService to MachineClientAdminService (:367), the client theMachineClientAdminpage reads and writes the app'sAdmin/MachineClientsendpoints through (:357-364).AddSupportAccessLogUI()(:383-388), the ADR-137 opt-in: IViewAsGrantsUIService to ViewAsGrantsService (:385), the client theSupportAccessLogpage reads the app'sAdmin/ViewAsGrantsendpoint through (:372-382).AddAuditHistoryUI()(:402-407), the ADR-075 opt-in: IAuditHistoryUIService to AuditHistoryService (:404), the HTTP client anAuditHistoryPanel'sFetchPagedelegate reads anAuditHistoryControllerBaseendpoint through; the doc comment (:390-401) adds that calling it again changes nothing and an app's own registration made first is kept.AddOfflineWriteQueue(Action<OfflineWriteQueueOptions>? configure = null)(:420-432): the opt-in durable offline write queue (ADR-144). It registers IOfflineWriteQueue to OfflineWriteQueue scoped (:422), because the browser connectivity service and local store it reads are scoped (:410-411),TimeProvider.Systemunless one is registered (:423), and OfflineWriteQueueOptions with the optional callback applied (:425-429). The doc comment (:409-419) notes that Common'sMainLayoutalready hosts theOfflineWriteNotifierthat drains and reports the queue.AddOfflineWriteHandler<THandler>()(:440-446), constrained toTHandler : class, IOfflineWriteHandler(:441): oneTryAddEnumerableof a scoped IOfflineWriteHandler (:443), the replay handler for one write kind, so registering the same handler type again adds nothing (:434-439).AddFeatureFlagAdministrationUI(params string[] sources)(:461-470), the ADR-031 opt-in: guardssources(:463), registers IFeatureFlagAdminUIService to FeatureFlagAdminService (:465) and appends the sources to FeatureFlagAdminUIOptions.Sources(:466-467). Each source is the API route prefix of one service'sFeatureFlagsControllerBase(for exampleAdmin/Conference/FeatureFlags), so a multi-service host lists every service's flags in one table (:454-456).AddUIModule<TModule>()(:490-500), constrained toTModule : class, IUIModule(:491): an assembly scan through the framework's internalAddAssignableTypeshelper (ServiceCollectionDecoration) overtypeof(TModule).Assembly, registering every IEntityService<TEntityDTO, TIdentifierType> implementation scoped under each of its implemented interfaces (ScanRegistration.ImplementedInterfaces) (:493-497), thenAddSingleton<IUIModule, TModule>()(:499). The doc comment (:472-485) records the deliberate boundary: this is the two-step prologue every module'sAdd{Module}UI()opens with, and module-specific services stay with the caller afterwards, so a module whose service must beat a shared default still controls its own registration order. The type-parameter doc (:486-489) states the constraint that follows from using the descriptor's assembly as the scan root: it must live alongside the module's entity services and Razor pages. That sameIUIModuleregistration is what PagePermissionPolicyConfigurator enumerates to find guarded pages.
- Why it's built this way:
TryAddthroughout is both a safety property (several composing hosts callingAddUISharedcannot double-register) and the override mechanism (a host that registers its own implementation before the call wins). Several ordering choices push in the opposite direction and are called out in comments because they are load-bearing: ICultureApplier's default round-trips a server/culture/setendpoint that a MAUI hybrid head does not have, so hybrids override it afterAddUIShared(:231-234); IPublicLinkBuilder's default resolves against the browser origin, which is wrong for a MAUI WebView whose origin is a virtual host nobody else can open, so that is overridden after as well (:241-244); and IForbiddenReExecutionDetector's default answers false everywhere until the Blazor Web host replaces it (:259-261). SnackbarDefaults takes the opposite position on purpose: it registers as the first configure step, so a host's own snackbar configuration wins regardless of call order (:132-135). InvariantMudLocalizationInterceptor follows the same head-dependent pattern one layer down: MudBlazor's own interceptor is correct everywhere except the MAUI hybrid main thread, so the replacement is registered unconditionally here rather than left to the affected head to override, because replace semantics make the registration order irrelevant (:137-144). SameOriginProxyRequestHandler is the one registration decided by configuration rather than by order: it is added only whenApi:SameOriginApiEndpointis present (:154-155,:183-189), so a host that never opts in carries no trace of it in its pipeline. The page permission policies avoid ordering altogether by deferring discovery to options build time (:108-112). Read together, the file encodes a rule worth carrying into any new registration: a contract whose correct implementation depends on the head is defaulted here and replaced later (or, where replace semantics make order irrelevant, registered outright), while a contract that is the same everywhere isTryAdded and left alone. The opt-ins follow the same principle one level up: nothing else in the framework calls any of them (:318-319,:345-346,:361-362,:378-379,:397-398,:416,:456), so an app that serves none of those endpoints registers nothing and the corresponding component is simply never rendered. - Where it's used: called once at startup by all six consuming UI hosts (ADC's
MMCA.ADC.UI.Web,MMCA.ADC.UI.Web.Clientand MAUIMMCA.ADC.UI, plus the three Store equivalents), each followed by the per-moduleAdd{Module}UI()calls, which are usually one-liners overAddUIModule<TModule>(), for exampleMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs:24andMMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.UI/DependencyInjection.cs:35.AddCommonUiFacades()has a second caller outside any host, the shipped bUnit base (MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Infrastructure/BunitComponentTestBase.cs:54). The administration, audit, offline and feature-flag opt-ins are each meant to be called once per app, afterAddUIShared(for example:314,:341), by an app that opts into the corresponding surface; nothing inside the framework itself calls any of them. The"APIClient"configured here is the client every EntityServiceBase<TEntityDTO, TIdentifierType>-derived service resolves. The assembly this class lives in is also the one UISharedAssemblyReference names for the architecture fitness suite. - Caveats / not-in-source: the count of six consuming UI hosts is carried over from the prior section; only the two
AddUIModulecall sites and the bUnit caller were re-read in this pass. The extension block registers no form-factor service, and noIFormFactororWasmFormFactortype exists underMMCA.Common/Source.
BreakpointConstants
MMCA.Common.UI ·
MMCA.Common.UI.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/BreakpointConstants.cs:9· Level 0 · class (static)
- What it is: a one-method static helper that answers "is this viewport a mobile viewport?", so C# viewport detection and the CSS media-query boundary agree on one number.
- Depends on:
MudBlazor.Breakpoint(NuGet, imported atBreakpointConstants.cs:1). Nothing first-party. - Concept introduced, the single authoritative breakpoint.
[Rubric §22, Responsive & Cross-Browser]assesses whether a codebase has one definition of "small screen" rather than a magic number re-chosen per component; this class embodies it by making the mobile/desktop split a named predicate. The doc comment (BreakpointConstants.cs:11-15) pins the threshold as MudBlazor's Xs or Sm breakpoint (< 960 px) and states plainly that this is not the sidebar boundary: the layout's sidebar collapses separately, below 1024 px. So this class is the one definition of "mobile" for the data-grid-versus-cards switch, not for every responsive decision.[Rubric §20, Design System & Theming]applies for the same reason: one named threshold keeps every list page switching modes at the same width instead of at slightly different ones. - Walkthrough: the type has exactly one member.
IsMobileBreakpoint(Breakpoint breakpoint)(BreakpointConstants.cs:16-17) is expression-bodied and returnsbreakpoint is Breakpoint.Xs or Breakpoint.Sm. That pattern is the whole rule:Mdand wider is desktop, and there is no third state. - Why it's built this way: static and dependency-free, so a component can call it without injecting anything, and moving the mobile threshold is a one-line edit rather than a hunt through component code.
- Where it's used: exactly one production call site, DataGridListPageBase<TDto>'s viewport-change handler
NotifyBrowserViewportChangeAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DataGridListPageBase.cs:444), which setsIsMobilefrom it at line 414 and, on a desktop-to-mobile transition, resetsMobileCurrentPageto 1 and re-requests the mobile data (DataGridListPageBase.cs:454-458). That single assignment is what swaps a desktopMudDataGridfor the MobileInfiniteScrollList<TItem> card layout on every list page in both consumer apps.
ComponentLifetimeExtensions
MMCA.Common.UI ·
MMCA.Common.UI.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ComponentLifetimeExtensions.cs:18· Level 0 · class (static, extension methods)
- What it is: one extension method,
LifetimeToken(this CancellationTokenSource?), that gives a component a cancellation token it can read at any point of its lifetime without risking an exception. - Depends on:
System.Threading.CancellationTokenSource,CancellationTokenandObjectDisposedException(BCL). Nothing first-party. - Concept introduced, the always-safe lifetime token.
[Rubric §15, Best Practices & Code Quality]assesses whether a recurring hazard has one shared answer. ReadingCancellationTokenSource.TokenafterDispose()throwsObjectDisposedException, and a Blazor component's async continuation can easily run after the component is gone. The extension converts that failure mode into the correct behavior: a component that has ended gets a token that is already cancelled, so the in-flight call stops instead of throwing out of a dead render tree. - Walkthrough:
LifetimeToken(ComponentLifetimeExtensions.cs:26-42) has three outcomes. Anullsource, or one whoseIsCancellationRequestedis already true, returnsnew CancellationToken(canceled: true)(:28-31). Otherwise it returnssource.Token(:35) inside atry; anObjectDisposedException(a source disposed without being cancelled first) is caught and also returns a cancelled token (:37-41), with the comment that the component is gone all the same. - Why it's built this way: an extension on the nullable source, rather than a wrapper type, so a component keeps its familiar
_ctsfield and writes_cts.LifetimeToken()where it used to write_cts.Token.nullis treated as ended (:28), which covers a component whose source was never created. - Where it's used: LatestLoadGuard reads its token through it (
MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/LatestLoadGuard.cs:58), and theResultUiExtensionsexamples show_cts.LifetimeToken()as the call-site shape (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ResultUiExtensions.cs:48,:63). The convention is enforced byArchitectureRules.ComponentsReadTheirTokenThroughLifetimeToken(MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Ui/ArchitectureRules.LifetimeTokens.cs:28), which fails the build on a direct_cts.Tokenread, wrapped for subclassing byLifetimeTokenConventionTestsBase(MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Ui/LifetimeTokenConventionTestsBase.cs:13). It is on the shipped public surface (MMCA.Common/Source/Presentation/MMCA.Common.UI/PublicAPI.Shipped.txt:1391).
JsInteropFailure
MMCA.Common.UI ·
MMCA.Common.UI.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/JsInteropFailure.cs:9· Level 0 · class (internal, static)
What it is: one predicate,
IsUnavailable(Exception), that is the framework's single definition of "this JS interop call could not do its job here", shared by every best-effort interop call so the set of absorbed exceptions cannot drift between copies (JsInteropFailure.cs:5-8).Depends on:
Microsoft.JSInteropforJSDisconnectedExceptionandJSException(JsInteropFailure.cs:1);InvalidOperationExceptionandOperationCanceledException(BCL). Nothing first-party.Concept introduced, best-effort interop with a closed failure set.
[Rubric §15, Best Practices & Code Quality]assesses whether a recurring hazard has one shared answer instead of a hand-writtencatchlist per call site. A JS interop call that escapes a component lifecycle method ends a Blazor Server circuit, and one that escapes an event handler is fatal on a MAUI head (JsInteropFailure.cs:12-14), so optional interop (theme stamping, list-page state, pending toasts, passkey probes) must absorb the failures that mean "interop is not available right now" while still letting a genuine bug surface.[Rubric §19, State Management & Data Flow]applies too: the predicate is what lets a component treat a missing renderer as "no stored state" rather than as a crash.Walkthrough: one expression-bodied member,
IsUnavailable(Exception exception)(JsInteropFailure.cs:27-31), returningtruefor exactly four exception types, each documented with the situation it stands for (:17-26):InvalidOperationException: no interop on this renderer (SSR prerender, a render-mode transition, a disposed dispatcher).JSDisconnectedException: the circuit was torn down mid-call.JSException: the script or module is missing, or the call threw in the browser.OperationCanceledException: this also covers theTaskCanceledExceptionan interop call throws when it exceeds the host's JS interop timeout or its token is cancelled.
Anything else (a
FormatException, aNullReferenceException) returnsfalse, so the exception propagates.Why it's built this way: a predicate rather than a wrapper that runs the call, so each caller keeps its own
tryand writescatch (Exception ex) when (JsInteropFailure.IsUnavailable(ex)), which leaves the stack unwound only for the absorbed cases and lets the caller choose its own fallback value. FoldingOperationCanceledExceptionin means a caller that must let its own cancellation propagate has to say so: the doc comment (:24-25) prescribes adding!cancellationToken.IsCancellationRequestedto the filter, andBrowserPasskeyCapabilitydoes exactly that (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Capabilities/Auth/BrowserPasskeyCapability.cs:113). It isinternal, not on the public API surface; the sibling packages reach it throughInternalsVisibleToentries forMMCA.Common.UI.Tests,MMCA.Common.UI.MauiandMMCA.Common.UI.Web(MMCA.Common/Source/Presentation/MMCA.Common.UI/MMCA.Common.UI.csproj:22,:25,:28).Where it's used: as an exception filter at every best-effort interop call in the framework: ListPageStateService (
MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/ListPageStateService.cs:140,:169,:198), PendingToastService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/PendingToastService.cs:36,:62), ThemeInterop (MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/ThemeInterop.cs:25, which reportsfalseinstead of throwing,:14), ColorModeStamp (MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/ColorModeStamp.cs:38), JsFetchSessionCookieSync (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/JsFetchSessionCookieSync.cs:33), SameOriginProxyTokenRefresher (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/SameOriginProxyTokenRefresher.cs:31),BrowserPasskeyCapability(BrowserPasskeyCapability.cs:52,:71,:90,:113), the view-as banner and button (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/ViewAsBanner.razor.cs:136,MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/ViewAsButton.razor.cs:97), and, across the package boundary, the handoff session services in UI.Web (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/HandoffSessionServices.cs:37,:61,:73). Covered byJsInteropFailureTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Common/JsInteropFailureTests.cs:13): a five-case theory pins prerender, disconnected, browser, timeout and cancelled as absorbed (:15-22), a fact pins that an unrelatedFormatExceptionis not (:24-26), and two facts pin thatThemeInterop.TryAsyncreportsfalseon an interop timeout andtrueon success (:28-38)[Rubric §28, Front-End Testing].
LatestLoadGuard
MMCA.Common.UI ·
MMCA.Common.UI.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/LatestLoadGuard.cs:38· Level 0 · class (sealed,IDisposable)
- What it is: a small per-page helper that keeps a routed component showing the load it asked for last, by giving every load a generation number and a cancellation token and cancelling the previous one as the next begins.
- Depends on:
System.Threading.CancellationTokenSourceandObjectDisposedException.ThrowIf(BCL), and ComponentLifetimeExtensions for the token it hands out. - Concept introduced, generation-guarded supersession.
[Rubric §19, State Management & Data Flow]assesses the correctness of in-flight asynchronous state, and this is the canonical bug it looks for. The doc comment states it precisely (LatestLoadGuard.cs:5-10): Blazor reuses a routed component instance across route-parameter changes, so a page that opens entity 100 (slow response) and then navigates to entity 101 (fast response) receives 100's late answer after 101 has already rendered. Assigning it unconditionally leaves the URL on 101 while the page holds 100, and any action bound to the loaded entity then fires against the wrong record. Cancellation alone does not fix this, because a fetch that ignores its token still completes; the integer generation is the authoritative check. The same pattern appears at component scope inside MobileInfiniteScrollList<TItem>, which snapshots a generation before awaiting and drops the result if the world moved;LatestLoadGuardis that idea extracted into a reusable object so a detail page gets it in three lines.[Rubric §15, Best Practices & Code Quality]applies: the alternative is every page hand-rolling a token source, a counter and a dispose path. - Walkthrough: three private fields (
LatestLoadGuard.cs:40-42): the currentCancellationTokenSource?, theint _generation, and a_disposedflag.Begin()(:50-59) is the entry point. It throws if the guard is disposed (:52), cancels and disposes the previous load through the privateCancelAndDisposeCurrent()(:54), publishes a fresh token source (:55), increments the generation (:56), and returns the pair(CancellationToken Token, int Generation)(:58), with the token read as_cts.LifetimeToken()rather than_cts.Token(:58) so it is the always-safe token of ComponentLifetimeExtensions. Returning a tuple rather than exposing two properties is what makes the generation a snapshot: the caller holds the value it started with, so a laterBegin()cannot retroactively change what it compares against.IsCurrent(int generation)(:67) is the check after the await:!_disposed && generation == _generation. Disposal counts as not-current, so a component torn down mid-fetch also drops its answer instead of assigning into a dead render tree.Dispose()(:70-79) is idempotent via the_disposedearly return (:72-75) and cancels the in-flight load on the way out.CancelAndDisposeCurrent()(:81-91) null-guards, then cancels, disposes and nulls the source, so the guard never double-disposes a token source and never leaks one.- The usage shape is spelled out as a
<code>block in the doc comment (:15-31): aprivate readonly LatestLoadGuard _load = new();field,var (token, generation) = _load.Begin();at the top ofOnParametersSetAsync, anif (!_load.IsCurrent(generation)) { return; }immediately after the await, andpublic void Dispose() => _load.Dispose();.
- Why it's built this way: deliberately not thread-safe, and the doc comment says so in bold (
:32-36). It is built for the renderer's synchronization context, where component lifecycle methods and event callbacks are already serialized, so the fields need no interlocking and the type stays allocation-cheap. That is a contract, not an oversight: sharing one instance across threads is documented as unsupported. - Where it's used: the framework's
DetailPageBaseexposes one asprotected LatestLoadGuard LoadGuard { get; } = new();and disposes it (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DetailPageBase.cs:34,:95), so every detail page derived from it inherits the guard.RoleAdminEditholds its own_loadand runs theBegin()/IsCurrent(generation)shape directly (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/RoleAdminEdit.razor.cs:42,:162,:174,:187), and ADC's public event, session and speaker detail pages andSessionCreatealso call it (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Public/Events/PublicEventDetail.razor.cs,Pages/Public/Sessions/PublicSessionDetail.razor.cs,Pages/Public/Speakers/PublicSpeakerDetail.razor.cs,Pages/Sessions/SessionCreate.razor.cs). It is on the shipped public surface (MMCA.Common/Source/Presentation/MMCA.Common.UI/PublicAPI.Shipped.txt:37-41). It is also exercised by LatestLoadGuardTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Common/LatestLoadGuardTests.cs:11, six test methods coveringBegincancelling the prior token, generation advance,IsCurrentafter supersession, and behavior after disposal)[Rubric §28, Front-End Testing];DetailPageBaseTestscovers the base-class wiring (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/DetailPageBaseTests.cs). - Caveats / not-in-source: the guard is not thread-safe by contract, and a page that bypasses it (assigning a fetch result unconditionally) is not caught by any analyzer; adoption is by
DetailPageBaseinheritance or by hand, asRoleAdminEditdoes.
NavGroup
MMCA.Common.UI ·
MMCA.Common.UI.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/NavGroup.cs:23· Level 0 · record (sealed)
- What it is: the optional rendering description of one collapsible sidebar group, keyed by the NavItem
Groupstring: its icon, whether it starts expanded, and its position within its section. - Depends on: nothing first-party at compile time (its doc comment cross-references NavItem and IUIModule).
- Concept introduced, describing a group by key rather than by ownership.
[Rubric §25, Navigation & Information Architecture]assesses whether a menu's structure is declared rather than hard-coded. A group has no owner: it exists because items carry the sameGroupkey, and the doc comment (NavGroup.cs:8-12) makes the consequence explicit. A module may describe a group whose items another module contributes (for example a framework-owned entry an app wants to place), the first registered description of a key wins, and a group nobody describes renders as before: the folder icon, collapsed, in the order its first item appears.[Rubric §27, Internationalization]applies through what the record deliberately does not carry: no display text. The heading is still theKeyresolved against the first item'sTitleResource(NavGroup.cs:14-17, ADR-027). - Walkthrough: a positional record on one line (
NavGroup.cs:23) with four parameters, three optional.string Key: theNavItem.Groupvalue the description applies to.string? Icon = null:nullkeeps the folder icon.bool Expanded = false: whether the group starts expanded.int Order = 0: the group's position among the units of its section, where each group and the section's ungrouped items (which count as order 0) are units; ties keep first-appearance order (NavGroup.cs:4-6,:22).
- Why it's built this way: a separate record rather than more parameters on NavItem, so group metadata is stated once per group instead of repeated on every item, and so an app can arrange a group it does not own. Every member defaults to the old behavior, so a host that declares no group renders exactly as it did. The menu realizes it in two steps:
NavMenu.OnInitializedAsynccollects every module'sNavGroupswithTryAdd, which is the first-registered-wins rule (MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor.cs:77-81), and the privateArrangegroups a section by key in first-appearance order, applies the description'sIcon ?? Icons.Material.Filled.Folder,Expanded ?? falseandOrder ?? 0to each NavUnit, then stable-sorts the units byOrder(NavMenu.razor.cs:51-66). - Where it's used: declared through the defaulted
IReadOnlyList<NavGroup> NavGroups => []member of IUIModule (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Interfaces/IUIModule.cs:22) and consumed by NavMenu. ADC'sConferenceUIModuleis the consumer example: it describes its organizer layout, with Conference Day and Program starting expanded and the framework's Notifications group placed last (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/ConferenceUIModule.cs:95-99). Covered byNavMenuOrderingTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Layout/NavMenuOrderingTests.cs:39,:82,:101,:124), which pins the undescribed default, a described icon and expanded state, group ordering with ties, and the first-declaration-wins rule across modules[Rubric §28, Front-End Testing]. ADR-067 records the UI shell composition it belongs to.
NavSection
MMCA.Common.UI ·
MMCA.Common.UI.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/NavSection.cs:7· Level 0 · enum
- What it is: classifies a sidebar entry into one of three audience groups: everyone, signed-in users, or administrators.
- Depends on: nothing. Consumed by NavItem and by the shared nav menu.
- Concept introduced, audience as a first-class navigation axis.
[Rubric §25, Navigation & Information Architecture]assesses whether the menu structure is declarative and audience-aware rather than a hand-maintained pile of conditionals.[Rubric §11, Security]touches it too, but with an important distinction worth internalizing early: the section is a grouping hint, not an authorization check. What actually hides a link isRequiredRole/RequiredClaimon NavItem, evaluated by the menu (MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor.cs:123-124), and what actually protects the destination is page-level and API-level authorization. - Walkthrough: three values in declaration order, and the order is itself a contract because the doc comment states sections render in enum declaration order (
NavSection.cs:5).General(:10) is for items visible to everyone, anonymous and authenticated alike.User(:13) is for signed-in non-admin items.Admin(:16) is for administrator items. - Why it's built this way: an enum rather than a string gives the renderer exhaustive, typo-proof matching, which is exactly what
NavMenu.razor.csrelies on when it partitions the flattened item list into three sections withi.Section is NavSection.General/User/Admin, arranging each one into its units (NavMenu.razor.cs:128-130). It is a plain C# enum rather than a smart enumeration because no member needs to carry data or behavior, which is the default this codebase commits to (ADR-104). - Where it's used: the
Sectionparameter of NavItem (NavItem.cs:16, defaulting toGeneral), and the three-way partition atNavMenu.razor.cs:128-130. NotificationUIModule shows both non-default values in one file: its inbox item isSection: NavSection.User(MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationUIModule.cs:19) and its push-management item isSection: NavSection.Admin(:20).
NotificationRoutePaths
MMCA.Common.UI ·
MMCA.Common.UI.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/NotificationRoutePaths.cs:6· Level 0 · class (static)
- What it is: the route constants for the framework's own notification feature, "route path constants for the Notification UI module" in its doc comment (
NotificationRoutePaths.cs:3-5): three literal paths and nothing else. - Depends on: nothing.
- Concept introduced: none of its own. The "one source of truth for route strings" idea is taught at RoutePaths; this class is that convention's module-specific half, the per-module
*RoutePathsclassRoutePathsitself points to. - Walkthrough: three
public static readonly stringmembers.Notifications = "/notifications"(:8), the admin push-management list.NotificationSend = "/notifications/send"(:9), the admin send page.NotificationInbox = "/notifications/inbox"(:10), the per-user inbox.
- Why it's built this way: kept separate from RoutePaths so an app that never enables the notification module carries no irrelevant constants, and so notification routes evolve on their own
[Rubric §25, Navigation & Information Architecture]. As inRoutePaths,static readonlyis enough because the strings feed navigation calls and nav entries, not attribute arguments, so the pages'@pagedirectives keep their own literals. - Where it's used: the notification surfaces navigate by these constants rather than by literals:
NotificationSend.razor.cs:72(its breadcrumb back to the list),:142(navigation back to the list after a send) and:161(NavigateToList),NotificationList.razor.cs:190(NavigateToSend), andNotificationBell.razor.cs:316(NavigateToInbox). NotificationUIModule builds its two NavItem entries fromNotificationInboxandNotifications(MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationUIModule.cs:19-20). In ADC,AppActionRouteMapmaps the notifications app action toNotificationRoutePaths.NotificationInbox(MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/Services/AppActionRouteMap.cs:60), andAppActionRouteMapTestsasserts that mapping (MMCA.ADC/Tests/Modules/Engagement/MMCA.ADC.Engagement.UI.Tests/Services/AppActionRouteMapTests.cs:39). - Caveats / not-in-source: the inbox page also answers a per-item route,
@page "/notifications/inbox/{Id:int}"beside@page "/notifications/inbox"(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Notifications/NotificationInbox.razor:1-2), but this class carries no constant or builder for it, so a caller that deep-links to one item composes the segment itself. The three constants are baselined inPublicAPI.Shipped.txt(MMCA.Common/Source/Presentation/MMCA.Common.UI/PublicAPI.Shipped.txt:2176-2178).
PersistedTally
MMCA.Common.UI ·
MMCA.Common.UI.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/PrerenderStateBudget.cs:105· Level 0 · class (private sealed, nested in PrerenderStateBudget)
- What it is: the per-state running total behind PrerenderStateBudget's page-wide cap: the set of keys already persisted into one
PersistentComponentStateand the UTF-8 JSON bytes they add up to. - Depends on:
HashSet<string>andStringComparer.Ordinal(BCL). Nothing first-party. - Concept introduced: none of its own; the budget concept is taught at PrerenderStateBudget. What this type adds is how a pass boundary is detected without any hook from the framework.
- Walkthrough: two fields,
_keys(an ordinalHashSet<string>,PrerenderStateBudget.cs:107) and_totalBytes(:108).Fits(string key, int bytes, int budget)(:116-117) only reads: it returns(_keys.Contains(key) ? 0 : _totalBytes) + bytes <= budget. A key already counted means a new persistence pass, because one pass cannot persist a key twice, so such a key is measured against an empty tally (:111-114) without the tally being changed.Add(string key, int bytes)(:122-132) is where the restart happens. If_keys.Add(key)reports the key was already present (:124), it clears the set, re-adds the key and zeroes the total (:126-128), so the new tally holds only this key (:120); either way it then adds the key's bytes (:131).
- Why it's built this way: split into a read-only check and a commit so the caller counts a key, and applies any restart, only after
PersistAsJsonhas accepted it (PrerenderStateBudget.cs:95-99). A keyPersistAsJsonrejects (a duplicate within one pass throws) therefore leaves the running total intact (:113-114), which a check that cleared the tally itself could not guarantee. It holds no lock itself; the caller locks the instance around both calls (:86). - Where it's used: only inside PrerenderStateBudget, which keeps one per state in a
ConditionalWeakTable<PersistentComponentState, PersistedTally>(PrerenderStateBudget.cs:51) and creates it on first use (:85). Exercised indirectly throughPrerenderStateBudgetTests(see PrerenderStateBudget), includingARejectedRepeatKey_InOnePass_KeepsTheRunningTotal(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Common/PrerenderStateBudgetTests.cs:51), which persists a 10 KB key, catches theArgumentExceptionfrom persisting the same key again in the same pass, and asserts that a second 10 KB key is still skipped because the first one still counts (:78-81). - Caveats / not-in-source: the restart branch of
Add(a repeated key in a later pass over the same state instance) has no dedicated test: the only repeated key inPrerenderStateBudgetTests.cs(:64) is rejected byPersistAsJsonbeforeAddruns.
RoutePaths
MMCA.Common.UI ·
MMCA.Common.UI.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/RoutePaths.cs:7· Level 0 · class (static)
- What it is: the route-path constants owned by the shared UI package itself. Module-specific routes live in their own
*RoutePathsclasses. - Depends on: nothing.
- Concept introduced, one source of truth for route strings.
[Rubric §25, Navigation & Information Architecture]also covers URL hygiene: a literal"/profile/sessions"typed into four components is four places to get a rename wrong. The class comment (RoutePaths.cs:3-6) states both halves of the convention: centralized paths shared across all UI modules and hosts live here, and module-specific paths live in their own class. That convention is followed consistently across the workspace, by NotificationRoutePaths in this package and byConferenceRoutePaths,EngagementRoutePathsandIdentityRoutePathsin the consumer modules. - Walkthrough: two
public static readonly stringmembers.Home = "/"(RoutePaths.cs:9).Sessions = "/profile/sessions"(:16), the signed-in-devices page. Its doc comment (:11-15) records why it belongs to the framework rather than to an app: the page is framework-owned (MMCA.Common.UI.Pages.Auth.Sessions), lists the user's live refresh sessions with per-device and account-wide sign-out, and is reachable from the shared nav menu's authenticated section, so a consuming app gets it without doing any routing work.
- Why it's built this way:
static readonlyrather thanconstis sufficient because these strings are consumed in navigation andHrefexpressions, not in attribute arguments. That has one consequence worth knowing: a@pagedirective still needs its own literal, soHome.razor:1writes@page "/"directly and this constant covers only the linking and navigating side.Sessionsshows the cost of the convention: the route literal appears in the page's own@pagedirective and again here, and only the tests hold the two together. - Where it's used:
RoutePaths.Homebacks the navbar brand link (MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor:18), the Home nav link (NavMenu.razor:58), and the first breadcrumb of the sessions page (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor.cs:75).RoutePaths.Sessionsbacks the authenticated-section nav link (NavMenu.razor:142) and is asserted by name in both repos' component tests:MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Layout/NavMenuTests.cs:76pins that the link renders inside.nav-auth-section,:75pins its position,:88pins that it is absent for an anonymous user, andMMCA.Store/Tests/Modules/Identity/MMCA.Store.Identity.UI.Tests/Pages/Users/Profile/ProfileTests.cs:67pins that the profile page links to it. - Caveats / not-in-source:
Sessionsis still listed inPublicAPI.Unshipped.txt(MMCA.Common/Source/Presentation/MMCA.Common.UI/PublicAPI.Unshipped.txt:339) whileHomeis baselined inPublicAPI.Shipped.txt:916, so the two members sit at different points in the public-API baseline cycle.
NavItem
MMCA.Common.UI ·
MMCA.Common.UI.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/NavItem.cs:20· Level 1 · record
- What it is: the immutable description of one sidebar entry a UI module contributes: title, href, icon, the resource type its title resolves against, optional role, claim and permission gates, its NavSection, an optional collapsible group, and an optional sort position.
- Depends on: NavSection;
System.Type(BCL). - Concept introduced, navigation as data contributed by modules.
[Rubric §25, Navigation & Information Architecture]assesses modular, role-aware navigation. The shared menu never knows which modules exist: it flattens every injected module'sNavItems, filters, partitions into sections and arranges each one (MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor.cs:121-130). That mirrors the server-side IModule contract one layer up (ADR-059 for the server, ADR-067 for this one).[Rubric §27, Internationalization]applies throughTitleResource(ADR-027).[Rubric §11, Security]and ADR-020 apply throughRequiredPermission. - Walkthrough: a positional record (
NavItem.cs:20) with nine parameters, five of them optional, plus oneinitproperty in its body:Title,Href,Icon: required, positional.Type TitleResource: required, and the fourth positional parameter. This is the localization contract, and the doc comment states it precisely (NavItem.cs:13-18):TitleandGroupare resource keys, resolved againstTitleResourceat render time, per-circuit, so the menu follows the active culture. A key the resource type does not declare renders as the raw string, which is what makes a not-yet-translated entry legible instead of blank.NavMenuimplements exactly that, callingLocalizerFactory.Create(item.TitleResource)[item.Title]for an item (NavMenu.razor.cs:29-33) and resolving a group heading against the resource of the group's first registered item (NavMenu.razor.cs:35-46,:59), with the ADR-027 rule restated in a code comment at:26-28.string? RequiredRole = nullandstring? RequiredClaim = null: render gates. The menu applies them asitem.RequiredRole is null || _user?.IsInRole(item.RequiredRole) == trueand the equivalent claim-type test (NavMenu.razor.cs:123-124).string? RequiredPermission = null: a third, permission-based render gate, layered on top of role and claim. The menu applies it asitem.RequiredPermission is null || _user.HasPermissionClaim(item.RequiredPermission)(NavMenu.razor.cs:125), the same permission-claim mechanism ADR-020 uses on the write side, so a nav entry can be hidden by permission instead of only by role.NavSection Section = NavSection.General: which sidebar section the item lands in (NavMenu.razor.cs:128-130).string? Group = null: nests the item inside a collapsibleMudNavGroup; the menu's privateArrangegroups each section by it withGroupBy(item => item.Group)(NavMenu.razor.cs:53), and a NavGroup with the same key can describe that group's icon, initial state and position.int Order { get; init; }(NavItem.cs:22-27): the item's position within its group, or within its section's ungrouped items.Arrangesorts each unit's items with a stableOrderBy(item => item.Order)(NavMenu.razor.cs:63), so ties keep registration order and an app that sets no order renders as it would without the property.
- Why it's built this way: a positional record gives value semantics and a one-line construction per entry, which is what makes a module's
NavItemsread as a small declarative list. MakingTitleResourcea required positional parameter rather than an optional nullable one is the load-bearing design choice: there is no way to register a nav item that bypasses localization, so "all visible text follows the selected language" holds for the menu by construction rather than by review. ADR-067 records the shape at this exact line (NavItem.cs:20).RequiredPermissionis a third, independent gate rather than folded intoRequiredClaim, so a caller can express "hide by permission" without hand-building the permission claim type/value pair itself.Ordersits in the record body rather than among the positional parameters, so it changed no constructor signature (NavItem.cs:22-25) and is set with an object initializer,new(...) { Order = 1 }. - Where it's used: returned from the
NavItemsproperty of every IUIModule implementation (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Interfaces/IUIModule.cs:14) and rendered by NavMenu. NotificationUIModule is the framework's own example and shows both the minimal and the maximal form:new("Nav.NotificationInbox", NotificationRoutePaths.NotificationInbox, Icons.Material.Filled.Inbox, typeof(SharedResource), Section: NavSection.User)(MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationUIModule.cs:19) andnew("Nav.PushNotifications", NotificationRoutePaths.Notifications, Icons.Material.Filled.NotificationsActive, typeof(SharedResource), RequiredPermission: NotificationPermissions.Manage, Section: NavSection.Admin, Group: "Nav.Group.Notifications")(:20). ADC'sConferenceUIModuleshowsOrderin use across all three sections, for example{ Order = -50 }on its first public entry and{ Order = 1 }through{ Order = 4 }inside each admin group (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/ConferenceUIModule.cs:56,:79-92). Covered by NavMenuTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Layout/NavMenuTests.cs), which drives the menu through aStubUiModule(IReadOnlyList<NavItem> navItems)(:308), and byNavMenuOrderingTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Layout/NavMenuOrderingTests.cs:138) for item ordering with ties. - Caveats / not-in-source:
RequiredRoleandRequiredClaimcontrol rendering only. They hide a link; they do not authorize the destination. The menu keeps a section-level authentication check alongside the per-item one deliberately (MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor:118), but page-level and API-level authorization remain the enforcing gates.
PrerenderStateBudget
MMCA.Common.UI ·
MMCA.Common.UI.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/PrerenderStateBudget.cs:20· Level 1 · class (static, extension method)
- What it is: one extension method on
PersistentComponentState,TryPersistAsJsonWithinBudget, that persists a component's prerender state only when it fits both a per-key cap and a page-wide total, so the circuit-start message never outgrows SignalR's limit. - Depends on:
PersistentComponentState(ASP.NET Core Components),System.Text.Json(JsonSerializer,JsonDocument,JsonSerializerOptions) andConditionalWeakTable(BCL); its nested PersistedTally. - Concept introduced, a byte budget for prerendered state.
[Rubric §12, Performance and Scalability]assesses whether a resource limit is designed for rather than discovered in production, and[Rubric §19, State Management & Data Flow]whether handed-over client state has a bound. The class doc states the failure precisely (PrerenderStateBudget.cs:7-13): on a Blazor Server circuit the browser sends every component's persisted state back inside the SignalR message that starts the circuit, and a message over the hub'sMaximumReceiveMessageSize(32 KB by default) closes the connection, so the page reconnects, sends the same state again and never becomes interactive, with only a Debug-levelInvalidDataExceptionas a trace. The remedy rests on one safe fallback (:15-18): skipping is always correct, because a component that finds nothing to restore fetches on its interactive pass exactly as it would without a prerender. ADR-056 records this budget as part of the render-mode strategy. - Walkthrough:
MaxJsonBytes = 14 * 1024(PrerenderStateBudget.cs:30): the per-key cap, under half of the 32 KB limit. The doc comment (:22-29) shows the arithmetic: each value is base64 inside the state dictionary, which is Data Protection protected and base64 encoded again, so a JSON byte costs about 16/9 of a byte on the wire and 14 KB of JSON lands near 25 KB.SerializerOptions(:34):JsonSerializerDefaults.Web, the optionsPersistAsJsonandTryTakeFromJsonuse, so bytes measured here restore unchanged.MaxTotalJsonBytes = 16 * 1024(:45): the page-wide total across every key persisted through this class into one state, about 28 KB on the wire. Its doc comment (:36-44) records why the per-key cap was not enough: two components each just under it (a catalog page and a grid beside it) reached 28.5 KB of the 32 KB limit.Tallies(:51): aConditionalWeakTable<PersistentComponentState, PersistedTally>, keyed weakly by the state object, so a tally lives exactly as long as the scope that owns the state and needs no DI registration.TryPersistAsJsonWithinBudget<TValue>(this PersistentComponentState state, string key, TValue instance, int maxJsonBytes = MaxJsonBytes)(:71-75): null-guardsstate(:77), serializes once to UTF-8 (:79) and returnsfalseover the per-key cap (:80-83). It then fetches or creates the state's tally (:85), locks it (:86) and returnsfalseif the bytes do not fit what is left ofMaxTotalJsonBytes(:88-91). Otherwise it parses the measured bytes into aJsonDocumentand persists itsRootElement(:97-98), becausePersistentComponentStatetakes no raw bytes publicly and aJsonElementis written token for token without serializingTValueagain (:93-94). Only then does it add the key to the tally (:99) and returntrue(:100); the comment at:95-96records why: a throw leaves the tally untouched, sinceFitsonly reads and the repeat-key restart happens inAdd(see PersistedTally).
- Why it's built this way: an extension method, so a page calls it where it would have called
PersistAsJsonand no service is injected. The remarks (:58-64) state the boundaries honestly: a largermaxJsonBytesdoes not raise the page-wide budget, and a small fixed-size value persisted withPersistAsJsondirectly sits outside the total, which the headroom between 28 KB and 32 KB absorbs. It is public so a consumer page persisting its own content-sized state uses the same budget (:17-18). - Where it's used: DataGridListPageBase<TDto>'s persisting callback calls it with the grid's PersistedGridState (
MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DataGridListPageBase.cs:279), with a comment that a wide grid of large DTOs at a large page size would otherwise outgrow the circuit-start message (:274-275). Covered byPrerenderStateBudgetTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Common/PrerenderStateBudgetTests.cs:17), which pins that the second of two 10 KB keys on one state is skipped (:24), that a repeated key rejected within one pass keeps the running total (:51), that three 4 KB keys under the total all persist (:85), and that two state instances never share a total (:106)[Rubric §28, Front-End Testing].
ResultUiExtensions
MMCA.Common.UI ·
MMCA.Common.UI.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ResultUiExtensions.cs:75· Level 4 · class (static, extension methods)
What it is: the page-side half of the Result transport. It is the four things a Blazor page ever does with a failed Result, written once so no page hand-rolls them again: unwrap the value, push the message into an inline alert, raise it as a toast, or branch on why it failed.
Depends on: Result, Error, ErrorType and ErrorTypeSeverity from
MMCA.Common.Shared.Abstractions(ResultUiExtensions.cs:5); ProblemDetailsResultReader fromMMCA.Common.Shared.Http(:6) and the synthesized-failure codes of HttpResultExecutor (:9); IToastService and ToastSeverity (:7); the framework's SharedResource resource pair (:8);Microsoft.Extensions.Localization.IStringLocalizer(:4);System.Resources.ResourceManager(:3);System.Globalization.CultureInfo(:2);System.Diagnostics.CodeAnalysis.NotNullWhenAttributeandSuppressMessageAttribute(:1).Concept introduced, localize-with-pass-through, and severity-ordered deduplication.
[Rubric §24, Forms, Validation & UX Safety]assesses whether a failure reaches the user as one clear, actionable sentence;[Rubric §27, Internationalization]assesses whether that sentence follows the active culture;[Rubric §15, Best Practices & Code Quality]assesses whether the same five lines get re-typed per page. Two mechanisms carry all three.- Pass-through localization (
:23-27): every message is looked up as a resource key, and one the localizer does not declare renders verbatim. That is what lets a single call site handle both an API error whose text the server already localized and a client-side error whoseMessageis a resource key. - Code-keyed fallback for synthesized failures (
:27-34): a failure the client built itself, with no server-phrased message to pass through (a bodiless HTTP status, a transport failure, a client timeout, a 2xx body that could not be read), is looked up by its error code instead:Http.{status}, then the genericHttp.Statusformat,Http.TransportFailure,Http.Timeout,Http.MalformedResponse. A code the supplied localizer does not hold resolves from the framework's ownSharedResourcepair for the current UI culture, so a consumer page passing its ownIStringLocalizer<PageType>(which holds noHttp.*keys) still shows the translated sentence; the English message is the last resort. The class holds a privateResourceManager SharedResources = new(typeof(SharedResource))(:85) and the format keyHttpStatusFallbackKey = "Http.Status"(:79) for this. - Severity-ordered deduplication (
:37-40): messages are made distinct withStringComparer.Ordinaland ordered most-severe-first via ErrorTypeSeverity, so a real 403 or 500 leads and an incidental validation message never buries it. The shape this guards against is common onceResult.Combineaggregates invariants: the same sentence arriving under several codes now reads as one sentence. This is the client mirror of the server-side status selection recorded in ADR-013, using the very same ranking type hoisted intoShared(MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ErrorTypeSeverity.cs:60) so both edges classify one aggregate identically.
The class doc even ships a before/after pair (
:43-74) contrasting the oldtry/catch (Exception ex)shape withif (result.TryGetValue(out var dto)) { ... } else { result.NotifyOnFailure(Toast, L); }, both reading the token as_cts.LifetimeToken()(ComponentLifetimeExtensions). TheTryGetValuein that example is the instance method on Result<T> itself, not a member of this class (the class doc's bullet list says so at:17).- Pass-through localization (
Walkthrough: twelve public members plus five private helpers, in four tiers.
- Unwrapping. The plain unwrap lives on the result:
Result<T>.TryGetValue([MaybeNullWhen(false)] out T value)(MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Result.cs:206-216) decides the branch byIsFailurealone and returnstruefor any success, so whenTis itself nullable the value stays nullable on the success branch (Result.cs:202). This class adds only the three-argument overloadTryGetValue<T>(this Result<T>, [NotNullWhen(true)] out T? value, out IReadOnlyList<Error> errors)(ResultUiExtensions.cs:104-121), whose doc cross-references the instance method (:88) and which hands the errors back on the failing branch. Its success test is stricter:result.IsSuccess && result.Value is not null(:111). It documents that edge honestly (:91-96): a success carrying a null value also takes the failing branch, and a success has no errors, soerrorscomes back empty. The framework's own services never produce that shape (a 2xx with no value fails withHttp.EmptyResponse), and the renderers here treat an empty list as nothing to say rather than an empty alert, but a caller switching on the error list should not assume it is non-empty. - Composing the message.
LocalizedErrorMessages(this Result, IStringLocalizer?)(:133-147) returns an empty list for a success, so a caller can bind it without a null or success check, and otherwise orders byErrorTypeSeverity.Rankdescending, localizes each error through the privateLocalizeError(:144) rather than its bare message, drops blanks, and takes ordinal-distinct values (:142-146).LocalizedErrorMessage(:157-161) joins that list with a space and returnsnullfor a success.LocalizeDistinct(IEnumerable<string>?, IStringLocalizer?)(:173-185) gives the same treatment to a plain message list, specifically theMudForm.Errorsshape whose entries are resource keys produced by the model's DataAnnotations; it preserves original order rather than re-ranking, since those entries carry noErrorType. - Rendering.
OnFailureSetError(this Result, Action<string?> setError, IStringLocalizer?)(:215-222) hands the composed message to the page's own error field, the one an inlineMudAlertor thePageErrorStatecomponent renders (its doc comment names it by its current home,MMCA.Common.UI.Components.PageState.PageErrorState, at:188-189, matching the file atMMCA.Common/Source/Presentation/MMCA.Common.UI/Components/PageState/PageErrorState.razor:1), and clears it on success by passing the composed message, which isnullfor a success (:220), which is why a retry that succeeds does not leave a stale alert on screen.NotifyOnFailure(this Result, IToastService, IStringLocalizer?, ToastSeverity = Error, string? fallback = null)(:267-286) raises one toast, never one per error, callingtoast.Show(message, severity)only when the chosen message is non-null (:280-283). With nofallbackthe message is the composed one; with afallbackit isActionErrorMessage(localizer, fallback)(:277-279), so a user action keeps its own wording for an unexpected fault while a refusal the API stated still shows the API's text (:241-247, example at:261-264).ActionErrorMessage(this Result, IStringLocalizer?, string fallback)(:317-330) is that choice as a public method: it rejects a blankfallback(:320), returnsnullfor a success, returnsfallbackwhen any error isErrorType.Unexpected(a 500, a transport failure, a timeout, whose own text is diagnostic), and otherwise the composed message, falling back tofallbackagain when that composes to nothing (:327-329). Both rendering methods return the same result instance so the call can sit inline, and both have aResult<T>overload that delegates to the non-generic one and returns the typed result (:227-231,:291-300), which is what keeps(await Service.AddAsync(dto, token)).NotifyOnFailure(Toast, L)chainable. All four rendering overloads carry the same[SuppressMessage("ApiDesign", "RS0026...")](:214,:226,:266,:290): two public overloads with optional parameters is the shape RS0026 forbids, and the justification records them as grandfathered, released after the v1.152 public-API baseline while RS0026/RS0027 were off, so changing the signatures now would be a breaking change. - Branching on why.
HasErrorType(this Result, ErrorType)(:340-344) is the general predicate; the doc comment (:333-335) notes the category survives the HTTP round trip through ProblemDetailsResultReader, which is what makes this meaningful client-side at all.IsNotFound()(:352) andIsUnauthorized()(:360) are the two named cases, and their doc comments state the intended UI reaction: a 404 becomes a "not found" state rather than an error alert, a 401 becomes a redirect to the login route. - The private helpers.
LocalizeError(Error, IStringLocalizer?)(:362-385) chooses the lookup per error. With no localizer it returns the message verbatim. For a synthesized HTTP status (ProblemDetailsResultReader.TryGetSynthesizedStatus) it tries the status's ownHttp.{status}code, then theHttp.Statusformat with the status code as argument, then the message (:372-377). For any other client-synthesized failure it tries the code, then the message (:379-382).IsSynthesizedClientFailure(:414-420) decides that: the executor's transport and timeout codes match only when the message is still the executor's own English sentence, so a caller that reused one of those codes with a message of its own keeps it (:416-417), whileProblemDetailsResultReader.MalformedResponseCode("Http.MalformedResponse",MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ProblemDetailsResultReader.cs:78) always matches, because the reader puts the raw serializer text in that message, which is neither localizable nor fit to render (ResultUiExtensions.cs:410-413,:418). Anything else falls toLocalize.LookUpByCode(:389) asks the caller's localizer first and then the framework'sSharedResources, andFormatByCode(:398) does the same for a format string.Localize(string message, IStringLocalizer?)(:422-431) is where pass-through actually happens: a null localizer or a blank message returns the input unchanged, otherwise it indexes the localizer and returnslocalized.ResourceNotFound ? message : localized.Value(:430).
- Unwrapping. The plain unwrap lives on the result:
Why it's built this way: extension methods on
Resultrather than an injectable service, because there is no state and nothing to resolve, so a page uses them without a constructor parameter and a unit test calls them directly. Every rendering helper returns the result it was given, which is what allows the fluent one-liner style the class doc advertises. The nullableIStringLocalizer?parameter everywhere means the helpers work from a context that has no localizer (they then render verbatim) rather than forcing one in.Where it's used: by every page and component that calls an IEntityService<TEntityDTO, TIdentifierType> member, across the framework package and both consumer apps, plus the shared deduplicating error-summary component. Covered by ResultUiExtensionsTests (
MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Common/ResultUiExtensionsTests.cs:22)[Rubric §28, Front-End Testing].Caveats / not-in-source: the class doc names the Result transport's record as ADR-013 (
ResultUiExtensions.cs:14): that is ADR-013, including the 2026-08-27 revision that namesResultUiExtensions; the client data-access half is ADR-094. Whether that ADR revision's member list already includesActionErrorMessageand thefallbackparameter is not determinable from source; trust the code over the ADR text for the exact surface.
IAppDialogService
MMCA.Common.UI ·
MMCA.Common.UI.Common.Interfaces·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Interfaces/IAppDialogService.cs:18· Level 0 · interface
- What it is: the framework's modal-confirmation contract, one
ConfirmAsyncmethod in three overloads (plain, with adestructiveflag, and with adestructiveflag plus a caller-chosen test id) that asks a yes/no question and resolves once the user answers. It exists so page code never names the component library that draws the dialog. - Depends on: nothing first-party (the file carries no
usingdirectives at all). Implemented by MudAppDialogService over MudBlazor'sIDialogService. - Concept introduced, the vendor-neutral UI facade.
[Rubric §32, Dependency & Supply-Chain]assesses whether a third-party dependency is contained behind your own contract or spread across call sites;[Rubric §14, Testability]assesses whether a unit of behavior can be exercised without its infrastructure;[Rubric §1, SOLID]covers the dependency-inversion half of the same idea. The framework applies all three the same way twice: this interface and its sibling IToastService are the only shapes pages depend on, and their two implementations are the only types in the framework that name MudBlazor'sIDialogService/ISnackbar(MudAppDialogService atMMCA.Common/Source/Presentation/MMCA.Common.UI/Services/MudAppDialogService.cs:13, doc comment at:7-12). The payoff is concrete: a bUnit test answers a confirmation prompt with a stub instead of rendering, driving and dismissing a real dialog. The doc comment (IAppDialogService.cs:3-17) also states the deliberate scope limit (:4-7): only the yes/no shape is abstracted, and the localized delete promptDeleteConfirmationis built on top of it rather than growing this contract (it injects the service atMMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/DeleteConfirmation.razor:2and callsConfirmAsyncat:27). It also states a safety default every prompt shares (:8-10): Cancel is rendered first and focused, so a stray Enter declines rather than confirms, and Escape declines too. - Walkthrough: three overloads of one member, all returning
Task<bool>.ConfirmAsync(string title, string message, string confirmText, string cancelText)(IAppDialogService.cs:30) is documented for a non-destructive action (:21-23).ConfirmAsync(string title, string message, string confirmText, string cancelText, bool destructive)(:45) adds the flag the doc defines at:40-43:truewhen confirming destroys or ends something (a delete, a lock, a sign-out), which draws the confirming button in the error color instead of the primary one.ConfirmAsync(string title, string message, string confirmText, string cancelText, bool destructive, string confirmTestId)(:60) behaves as the five-argument form but stamps a caller-chosendata-testidon the confirming button so an end-to-end test can target that specific prompt (:47-51);DeleteConfirmationpassesconfirm-delete(DeleteConfirmation.razor:9).- Two contract details hold for all three and are honored by the implementation. First, every string parameter is documented as "already-localized" (
:25-28,:36-39): the facade never touchesIStringLocalizer, the caller resolves its own copy, which is what keeps the resource key next to the page that owns it (ADR-027). Second, dismissing the dialog without choosing counts as declining (:21-23,:33-34), so a caller only ever has to branch ontrue. - MudAppDialogService forwards the four-string overload to the five-argument one with
destructive: false(MudAppDialogService.cs:16-17), and the five- and six-argument ones open the framework's ownConfirmationDialogthrough its internalShowAsync(MudAppDialogService.cs:20-25;MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/ConfirmationDialog.razor:65), whoseconfirmTestIdparameter defaults toconfirm-actionwhen the caller names none (ConfirmationDialog.razor:21,:72). That helper collapses every non-answer tofalsewithreturn result is { Canceled: false, Data: true };(ConfirmationDialog.razor:92). The dialog is deliberately notMudMessageBox, whose action row pins initial focus to the Yes button (ConfirmationDialog.razor:1-5): it puts the Cancel button first (:14), starts its focus trap on the first child (:6), and colors the confirm buttonColor.ErrorwhenDestructiveis set,Color.Primaryotherwise, stamping itsdata-testidfromConfirmTestIdon the same line (:15).
- Why it's built this way: a four-string method with a
boolanswer is the smallest contract that covers every confirmation prompt in the framework, and the two extra overloads are the only variations pages need (a red confirm button for an irreversible action, and a stable test id for a prompt an end-to-end test must find). Keeping it that small is what makes the vendor genuinely swappable: the whole surface an alternative renderer must satisfy is one method in three shapes. It is registered byAddCommonUiFacades()alongside the toast facade (DependencyInjection,MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:292), scoped to match the MudBlazor services it wraps. See ADR-067, whose 2026-08-29 revision records the vendor choice and these two facades, and whose 2026-08-31 revision records their move into their own registration call. - Where it's used: injected by the shared framework surfaces that ask before doing something lossy: DataGridListPageBase<TDto>, the notification list, send and inbox pages,
ListPageActions, the signed-in-devices page (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor.cs), theDeleteConfirmationcomponent (DeleteConfirmation.razor:2), and theUnsavedChangesGuardcomponent. ADC pages call it directly too, for example the room detail page (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Rooms/RoomDetail.razor.cs) and the user detail page (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserDetail/UserDetail.razor.cs). Registered for component tests by the shipped bUnit base'sServices.AddCommonUiFacades()call (MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Infrastructure/BunitComponentTestBase.cs:54), which usesTryAddsemantics so a test that wants a recording double registers one afterwards (BunitComponentTestBase.cs:51-53).
IHomePageContent
MMCA.Common.UI ·
MMCA.Common.UI.Common.Interfaces·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Interfaces/IHomePageContent.cs:8· Level 0 · interface
- What it is: the hook that lets each consuming application supply its own landing page at the
/route without forking the shared routing or layout. - Depends on:
System.Type(BCL) and, at the consuming end,Microsoft.AspNetCore.Components.DynamicComponent, which the doc comment names as the rendering mechanism (IHomePageContent.cs:3-7). - Concept introduced, late-bound content injection into a packaged shell.
[Rubric §18, UI Architecture & Component Design]assesses whether shared UI infrastructure adapts to per-app content without duplication. The shared package owns the route:Home.razordeclares@page "/"once (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Home.razor:1), injectsIEnumerable<IHomePageContent>(Home.razor:3), and renders<DynamicComponent Type="_contentType" />when a provider resolved (Home.razor:8-11). Because the component arrives as a runtimeTyperather than a compile-time reference, the framework package renders an app's landing page without referencing the app. When no implementation is registered the page falls back to a localized welcome panel (Home.razor:12-21), so a brand-new host still renders something coherent. - Walkthrough: two read-only members.
ComponentType(IHomePageContent.cs:11) is theSystem.Typeof the Razor component to render as the home-page body.PageTitle(IHomePageContent.cs:14) is the browser-tab title, bound byHome.razor:6. - Why it's built this way: an inverted dependency (the app registers into the framework, never the reverse) is what lets the whole shell ship as a NuGet package. Compare the sibling mechanism in IUIModule: both hand the framework a
Typeor anAssemblyand let reflection do the binding, and both exist for the same reason (ADR-067). - Where it's used: implemented once per app and registered once per head. ADC registers
ADCHomePageContentas a singleton in all three heads (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:79,MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web.Client/Program.cs:42,MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/MauiProgram.cs:133), with one implementation shared by the web and MAUI heads, living in the Conference UI module (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Home/ADCHomePageContent.cs:11). Store does the same withStoreHomePageContent(MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:101,MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web.Client/Program.cs:41,MMCA.Store/Source/Hosts/UI/MMCA.Store.UI/MauiProgram.cs:76). - Caveats / not-in-source: the injection point is
IEnumerable<IHomePageContent>, so several registrations do not fail; which one wins is decided byHome.razor's selection code (Home.razor:23onward), not by this interface. Every current host registers exactly one.
ToastSeverity
MMCA.Common.UI ·
MMCA.Common.UI.Common.Interfaces·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Interfaces/IToastService.cs:8· Level 0 · enum
- What it is: the framework's own five-level scale for how prominent a toast is, and therefore which color and icon the host renders it with.
- Depends on: nothing. Declared above IToastService in the same file.
- Concept reinforced, keeping the vendor enum out of call sites. The facade idea is taught at IAppDialogService; this enum is the part of it that is easy to skip. A contract that abstracts the snackbar but takes
MudBlazor.Severityas a parameter has not abstracted anything, because every caller still references the vendor assembly. The doc comment says exactly that (IToastService.cs:3-7): the five levels mirror what every component library exposes, so a host maps them one-to-one without losing anything, and "naming them here is what keeps the vendor's own severity enum out of page code".[Rubric §32, Dependency & Supply-Chain]and[Rubric §9, API & Contract Design]both apply: the mapping toMudBlazor.Severitylives in one private method inside MudToastService, so swapping renderers is a change to oneswitch. - Walkthrough: five explicitly numbered members, each documented by what it means for the user rather than by color.
Normal = 0(IToastService.cs:11), neutral with no color emphasis.Info = 1(:14), something happened that the user did not ask for.Success = 2(:17), the action the user asked for completed.Warning = 3(:20), completed partially or with something worth knowing.Error = 4(:23), the action failed. The explicit values keep the enum stable if members are ever reordered. - Why it's built this way: five levels rather than four, because
Normal(an uncolored toast) is a distinct affordance fromInfo, and not more, because there is no shape beyond these that the framework raises.Infois the default parameter value on bothShowPersistentandShowAction(:72,:100), which is the neutral choice for an unprompted message. - Where it's used: the
severityparameter ofIToastService.Show,ShowPersistentandShowAction; theseverityparameter of ResultUiExtensions.NotifyOnFailure, where it defaults toToastSeverity.Error(MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ResultUiExtensions.cs:271); and MudToastService, the one type that maps it toMudBlazor.Severity(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/MudToastService.cs:45).
LayoutSettings
MMCA.Common.UI ·
MMCA.Common.UI.Common.Settings·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Settings/LayoutSettings.cs:9· Level 0 · class (sealed)
- What it is: the five settings that make the shared shell look and behave like a specific application: the navbar brand text, an optional brand logo URL, the footer text, an optional role gate on the framework-owned "signed-in devices" nav entry, and an opt-in that stamps the current color mode on the document element.
- Depends on: nothing first-party.
System.Diagnostics.CodeAnalysis.SuppressMessage(BCL) for one analyzer waiver, and theMicrosoft.Extensions.Optionsbinder at registration time. - Concept introduced, a settings section as a bound options class.
[Rubric §17, DevOps & Deployment](assesses whether configuration is centralized and typed rather than read ad hoc) and[Rubric §20, Design System and Theming](assesses whether the look of the app is expressed once rather than repeated per page). The shape repeats across every settings class in this namespace: apublic static readonly string SectionNamenaming the configuration section (line 12),init-only properties with compiled-in defaults, and oneservices.AddOptions<T>().Bind(configuration.GetSection(T.SectionName))call inAddUIShared(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:55-56). Because every property has a default, an absent section is not an error: the host simply gets the compiled-in values. Components then takeIOptions<LayoutSettings>and read.Value, so nothing in the shell parses configuration itself. - Walkthrough:
SectionName = "Layout"(line 12).BrandName(line 15) defaults to"MMCA".NavMenurenders it as the brand link's text and folds it into the link's localized accessible name (Layout/NavMenu.razor:23,:31).FooterText(line 18) defaults tostring.Empty.MainLayoutrenders the footer block when the text is non-blank, whenLegalSettingshas footer links, or when a module contributesFooterComponentTypes(Layout/MainLayout.razor:113). With none of the three, the empty default means "no footer", not "an empty footer".BrandLogoUrl(line 30) defaults to empty, which renders the text-only brand. When set,NavMenuemits animgbeside the brand text withalt=""andaria-hidden="true"(Layout/NavMenu.razor:27-29): the image is decorative because the brand link already carries its own accessible name, so alt text here would only repeat it to a screen reader (lines 20-24). The property carries a[SuppressMessage]for CA1056 (lines 26-29) whose justification records why it is astringand not aUri: the value is usually a host-relative path such as/img/logo.svg, whichSystem.Uricannot represent withoutRelativeOrAbsoluteround-tripping.SessionsNavRequiredRole(line 39) is nullable and unset by default, which shows the "signed-in devices" nav entry to every signed-in user.NavMenucomputes_showSessionsLinkas unset-or-blank OR the current user is in that role (Layout/NavMenu.razor.cs:120-121). The gate covers only the menu entry:/profile/sessionsitself stays available to any signed-in account whether or not the link is shown (lines 32-38).StampColorModeOnDocument(line 51) defaults tofalse, which sets nothing. Whentrue,ColorModeStampwritesdata-mmca-color-mode="light|dark"on the document element in step with the Day/Dark toggle, so an app's own stylesheet can select on the mode (MudThemeProvider only swaps palette variables). It acts only on an interactive render (MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/ColorModeStamp.cs:25), so a prerendered page carries no value until then; a MAUI head that loadstheme-prepaint.jswithdata-stamp-color-modeon its script tag gets the value before the first paint instead. The attribute is distinct from the MAUI head's pre-paintdata-mmca-theme, whose rules it does not trigger (lines 41-50).- Two shell behaviors are deliberately not settings here. The framework's notification pages answer with the not-found page in a host with no registered
NotificationUIModule, a decisionNotificationPageGatetakes from the registered UI modules alone (MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationPageGate.cs:20-21,:26). AndMainLayoutrendersStaleToastSweeperunconditionally on every head (Layout/MainLayout.razor:152-153).
- Why it's built this way: the shell ships in the framework package, so the only way a consuming app can brand it, narrow a framework-owned menu entry, or opt into a shell behavior without forking is configuration. The one opt-in defaults to setting nothing, so a host that never sets the key sees no change. Keeping the branding in
appsettings.jsonalso means a deployment can rebrand without a rebuild. - Where it's used: injected as
IOptions<LayoutSettings>byLayout/NavMenu.razor:13andLayout/MainLayout.razor:13, read inLayout/NavMenu.razor.cs:120, and resolved byColorModeStamp(Theme/ColorModeStamp.cs:24). Forwarded to the WebAssembly client through/client-configas one of the shared UI sections (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigUiSections.cs:39). Configured by the UI hosts, for exampleMMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/appsettings.json:33andMMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/appsettings.json:14. Covered byNavMenuTests,MainLayoutFooterTests,PublicAppBarComponentTestsandMmcaThemeProvidersColorModeTests.
LegalSettings
MMCA.Common.UI ·
MMCA.Common.UI.Common.Settings·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Settings/LegalSettings.cs:16· Level 0 · class (sealed)
- What it is: the four legal-document URLs a host can publish (Terms of Service, Privacy Policy, Code of Conduct, and the page explaining how to delete an account), plus a computed flag saying whether any footer document is configured. Every URL defaults to empty, which means "not configured" and hides the link it drives.
- Depends on: nothing first-party.
System.Diagnostics.CodeAnalysis.SuppressMessage(BCL) for the CA1056 waivers, and theMicrosoft.Extensions.Optionsbinder at registration time. - Concept introduced, an empty default as the off switch.
[Rubric §17, DevOps & Deployment](assesses whether configuration is centralized and typed rather than read ad hoc). It follows the same bound-options shape asLayoutSettings: apublic static readonly string SectionName = "Legal"(line 22) andinit-only properties with compiled-in defaults. Here the default doubles as the feature toggle: an unset URL isstring.Empty, and each consumer testsstring.IsNullOrWhiteSpacebefore rendering a link, so a host opts into each document by configuring it and a host that configures nothing sees no legal UI at all. The section is optional for the same reason; ADR-070 (fail-fast configuration contract) is the reference for which settings must be present and which, like this one, may be absent. - Walkthrough:
TermsUrl(line 26),PrivacyUrl(line 30) andCodeOfConductUrl(line 34) arestringproperties defaulting tostring.Empty. The doc comment onTermsUrlstates the double effect: empty hides both the footer link and the registration checkbox (line 24).DeleteAccountUrl(line 41) is the page that explains how to delete an account, which app stores require for apps that offer sign-up (lines 36-39). It is deliberately outside the footer group.- Each URL carries a
[SuppressMessage]for CA1056 (lines 25, 29, 33, 40) sharing oneUrlJustificationconstant (lines 18-19): the value is bound from configuration and emitted straight into anhref, and the empty default is not a validSystem.Uri, the same precedent asLayoutSettings.BrandLogoUrl. HasFooterLinks(lines 44-47) is true when any of the three footer documents (Terms, Privacy, Code of Conduct) is non-blank.DeleteAccountUrlis not part of it.
- Why it's built this way: the shared shell and the register page ship in the framework package, so the only way an app can publish its own legal documents without forking is configuration. Computing
HasFooterLinksonce on the settings class keeps the "is there anything to show" decision out of every markup file. - Where it's used: bound by
services.AddOptions<LegalSettings>().Bind(...)inMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:60-61.Layout/MainLayout.razorinjects it (line 13), renders the footer when footer text orHasFooterLinksis present (line 87), and emits oneExternalLinkper configured document (lines 104-114).Components/Legal/TermsAcceptanceGate.razor.csreads it throughIOptions<LegalSettings>(lines 70, 78) and the gate markup checksLegal.HasFooterLinks(TermsAcceptanceGate.razor:17).Pages/Auth/Register.razorinjects it (line 17) and shows the Terms checkbox only when a Terms URL is configured (line 143;Pages/Auth/RegisterModel.cs:46). ADC'sLegalAndDataCard.razor.cson the profile page reads it too. Covered byMainLayoutFooterTestsandRegisterTermsTestsinMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests.
NotificationBellOptions
MMCA.Common.UI ·
MMCA.Common.UI.Common.Settings·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Settings/NotificationBellOptions.cs:12· Level 0 · class (sealed)
- What it is: the two numbers that define how stale the unread-notification badge is allowed to be: how often it re-reads the API, and how old its count may be before a navigation re-reads it.
- Depends on: nothing first-party.
TimeSpan(BCL). Bound with the same options shapeLayoutSettingsintroduces. - Concept introduced, staleness as a stated policy.
[Rubric §19, State Management](assesses whether client-side state has an explicit freshness contract) and[Rubric §31, Cost and FinOps](assesses whether the design lets an operator trade money against latency). Both numbers are host decisions rather than compiled constants: a deployment paying per API call widens the poll, one where an unread count must feel instant narrows it (lines 6-10). The framing in the doc comment is important for reading the code: the periodic read is the backstop behind the real-time push, not the primary path, soPollIntervalis the budget for "how long a missed push may go unnoticed" (lines 17-22). - Walkthrough:
SectionName = "NotificationBell"(line 15).PollInterval(line 23), default 30 seconds.NotificationBellbuilds itsPeriodicTimerfrom it (Components/Notifications/NotificationBell.razor.cs:103), against the injected clock rather than the ambient one. Zero or a negative value disables periodic polling while the push refresh and the navigation refresh keep working (lines 20-21): the bell returns before creating the timer whenPollInterval <= TimeSpan.Zero(NotificationBell.razor.cs:96-99), becausePeriodicTimerrejects such a period and throwing there faulted the circuit (lines 94-95).NavigationRefreshMaxAge(line 30), default 30 seconds. On a page change the bell accepts the count it already holds unless it is older than this window (NotificationBell.razor.cs:166, viaState.IsStale(...)). That is what keeps a user clicking through five pages in ten seconds from issuing five reads of a number that has not moved (lines 25-29).
- Why it's built this way: both values are pure policy with no correct universal answer, so they belong in configuration; and because both have defaults, a host that says nothing keeps the framework's chosen 30-second budgets.
- Where it's used: bound in
AddUIShared(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:74-75) and injected asIOptions<NotificationBellOptions>byNotificationBell(Components/Notifications/NotificationBell.razor.cs:36). Covered indirectly byNotificationBellTests.
RegistrationSettings
MMCA.Common.UI ·
MMCA.Common.UI.Common.Settings·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Settings/RegistrationSettings.cs:8· Level 0 · class (sealed)
- What it is: a one-property settings class that lets a host turn the register page's optional postal-address block on or off.
- Depends on: nothing first-party. The
Microsoft.Extensions.Optionsbinder at registration time. - Concept introduced, a feature switch that defaults to the framework's existing behavior.
[Rubric §17, DevOps & Deployment](assesses whether configuration is centralized and typed rather than read ad hoc).CollectAddressdefaults totrue(line 18), so a host that never configures theRegistrationsection (SectionName, line 11) keeps the address block it always had; only a host that setsfalsechanges anything. ADR-070 (fail-fast configuration contract) covers why an absent optional section is not an error. - Walkthrough:
CollectAddress(line 18,get; set;) is the only member.trueshows the optional address block;falsehides it and the registration request carries no address (lines 13-17). - Why it's built this way: not every deployment wants to ask for a postal address at sign-up, and the register page is framework-owned, so configuration is the only way a consuming app can drop the block without forking the page.
- Where it's used: bound in
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:65-66.Pages/Auth/Register.razorinjectsIOptions<RegistrationSettings>(line 18) and wraps the address block in@if (CollectAddress)(line 107);Pages/Auth/Register.razor.csexposesCollectAddressfrom the options (line 13) and branches on it at line 24. Covered byRegisterAddressOptionTestsinMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth.
SignInSettings
MMCA.Common.UI ·
MMCA.Common.UI.Common.Settings·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Settings/SignInSettings.cs:13· Level 0 · class (sealed)
- What it is: the three settings that decide which optional actions the shared sign-in pages offer: an "Email me a sign-in link" button, a "Sign in with a passkey" button with passkey autofill, and the local page a redeemed sign-in link lands on (
SignInSettings.cs:3-7). - Depends on: nothing first-party. The
Microsoft.Extensions.Optionsbinder at registration time. - Concept introduced: none new. It follows the bound-options shape
LayoutSettingsintroduces (SectionName = "SignIn", line 16) and the "default to the existing behavior" switch ofRegistrationSettings: both offers default tofalse, so a host that configures nothing sees the sign-in page it always had.[Rubric §26, Front-End Security](assesses whether the front end treats configured or caller-supplied navigation targets as untrusted) applies to the landing path: an absolute or off-site value is ignored in favour of the default (lines 33-36). - Walkthrough:
OfferSignInLink(line 23), defaultfalse. The doc comment (lines 18-22) ties it to the server'sAuthentication:SignInLinks:Enabled: turned on alone, the button sends requests the API ignores.Pages/Auth/Login.razor:154shows the button only when it is on and the page is not waiting on a second factor.OfferPasskeys(line 31), defaultfalse, paired with the server'sPasskeys:Enabled(ADR-139) and shown only where the head can run WebAuthn (IPasskeyCapability.IsAvailable), so a MAUI head never shows it (lines 25-30).Pages/Auth/Login.razor.cs:201reads it.SignInLinkLandingPath(line 37), default"/".Pages/Auth/SignInLinks/SignInLink.razor.cs:189passes it throughReturnUrlProtector.Sanitize(..., "/")before the full-page navigation, which is what enforces the "local path only" rule.- Unlike
LayoutSettings, the properties areget; set;rather thaninit.
- Why it's built this way: both offers need a server-side feature enabled as well, and the sign-in page is framework-owned, so a host-level switch with an off default is the only way an app can adopt them without forking the page (ADR-116). The remarks (lines 8-12) record the WebAssembly half:
client-configforwards the server head'sSignInsection, so an option turned on in server configuration reaches the client with no second copy. - Where it's used: bound in
AddUIShared(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:70-71), forwarded byMMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigUiSections.cs:41, injected byPages/Auth/Login.razor:23andPages/Auth/SignInLinks/SignInLink.razor.cs:68, and read by ADC's profile page (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/Profile.razor.cs). Configured inMMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/appsettings.json:51andMMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/appsettings.json:25. Covered byLoginSignInLinkTests,LoginPasskeyTestsandLoginSecondFactorTestsinMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests, and by the shippedSignInLinkPageTestsBase(MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Pages/SignInLinkPageTestsBase.cs). - Caveats / not-in-source: nothing in this class checks that the matching server switch is on; a mismatch shows up only as a button whose requests the API ignores.
UIModuleConfiguration
MMCA.Common.UI ·
MMCA.Common.UI.Common.Settings·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Settings/UIModuleConfiguration.cs:17· Level 0 · class (static)
- What it is: a one-method helper that answers "is this UI module enabled in this head?" by reading
Modules:{moduleName}from configuration: a module is enabled only when its entry exists and itsEnabledis notfalse. - Depends on:
Microsoft.Extensions.Configuration.IConfiguration(GetSection,Exists,GetValue). Nothing first-party, which is what lets a host call it before any DI registration has happened. - Concept introduced, composing a UI host from configuration.
[Rubric §7, Microservices Readiness](assesses whether the same codebase can be deployed as different subsets) and[Rubric §17, DevOps & Deployment]. The server-side module system registersIModuleimplementations in topological order; the UI side has its own analogue,IUIModule, registered by each module'sAddXUI()extension (ADR-067). This helper is the gate in front of those calls: a head that switches a module off never callsAddXUI(), so noIUIModuledescriptor is registered, and the shell composes without that module's routes, nav entries or services. The rule is the one the service hosts apply to their own modules,ModulesSettings.IsModuleEnabled(ADR-059): a module missing from the section, or a missing section, is disabled (lines 5-11), so a UI head and its services agree on what "enabled" means. - Walkthrough:
ModulesSectionName = "Modules"(line 19) andIsModuleEnabled(IConfiguration configuration, string moduleName)(lines 28-35). It guards both arguments (ThrowIfNullandThrowIfNullOrWhiteSpace, lines 30-31), walks two section levels,Modulesthen the module name (line 33), and returnssection.Exists() && section.GetValue("Enabled", true)(line 34). Read carefully, that is one requirement and one default: the module's entry must exist, and once it exists a missingEnabledkey counts as enabled. Lookup is case-insensitive, as configuration keys are (lines 21-22). The remarks (lines 12-16) cover the WebAssembly client of a Blazor Web head: it receives the head's resolved flags in themodulessection of/client-config, loaded into configuration before the client registers modules, so both halves of one head register the same modules. - Why it's built this way: a static helper over
IConfiguration(rather than a bound options class) is what makes it usable at the exact point it is needed, insideProgram.cs/MauiProgram.csbefore the service provider exists. Keeping the check in the framework rather than hand-rollingbuilder.Configuration["Modules:X:Enabled"]per head is what keeps the semantics identical across all six heads and in line with the service hosts. - Where it's used: all six UI hosts gate their module registrations with it. ADC:
MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:85-95,MMCA.ADC.UI.Web.Client/Program.cs:52-61,MMCA.ADC.UI/MauiProgram.cs:136-145(Identity, Conference, Engagement, Notification). Store:MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:74-81,MMCA.Store.UI.Web.Client/Program.cs:59-66,MMCA.Store.UI/MauiProgram.cs:103-110(Catalog, Sales, Identity). The/client-configendpoint applies it when it serves themodulessection (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs). The corresponding configuration blocks start atMMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/appsettings.json:9andMMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/appsettings.json:8. Covered byUIModuleConfigurationTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Common/Settings/UIModuleConfigurationTests.cs). - Caveats / not-in-source: because absence now means disabled, a head whose configuration has no
Modulessection registers no feature modules at all; every head has to list the modules it serves.
ApiSettings
MMCA.Common.UI ·
MMCA.Common.UI.Common.Settings·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Settings/ApiSettings.cs:10· Level 0 · class (sealed)
- What it is: the bound options class for the
"Api"configuration section, validated at startup so a host with no API endpoint fails immediately instead of at the first request. It implements no interface: consumers takeIOptions<ApiSettings>directly (ApiSettings.cs:10). - Depends on:
System.ComponentModel.DataAnnotations.RequiredAttribute(BCL) only. - Concept introduced, fail-fast configuration.
[Rubric §29, Resilience, Reliability & Business Continuity]and[Rubric §15, Best Practices and Code Quality]. The class is three properties of data, but the behavior lives in how it is registered:AddOptions<ApiSettings>().Bind(...).ValidateOnStart()plus the source-generatedApiSettingsValidator(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:49-52). The[OptionsValidator]generator turns the[Required]attribute into an options validator at compile time, with no reflection and no data-annotations validation package on a WebAssembly client, andValidateOnStartruns that validator during host startup rather than lazily on first resolution, so a missingApi:ApiEndpointsurfaces as anOptionsValidationExceptionnaming the key before the host accepts traffic (ADR-070). That is what licenses the null-forgivingapiSettings.ApiEndpoint!in the client factory (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:167-170): the validator, not a local check, is the guarantee. - Walkthrough:
SectionName = "Api"(line 13), the same convention every settings class here uses.[Required] public string? ApiEndpoint { get; init; }(lines 16-17). Nullable so the binder can leave it unset,[Required]so leaving it unset fails validation.init-only, so a bound instance is immutable after construction.WasmApiEndpoint { get; init; }(line 25) carries no[Required]: it is the browser-facing endpoint a Server head serves to its WebAssembly client through/client-config, which lets the server itself use an internalApiEndpoint(faster, no public DNS) while the browser uses the external URL, and it falls back toApiEndpointwhennull(lines 19-24). The fallback is applied by each reader, for exampleapi.WasmApiEndpoint ?? api.ApiEndpointin the CSP builder (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Security/BlazorCspPolicyProvider.cs:51), while/client-configrefuses to serve without it (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:87-91).SameOriginApiEndpoint { get; init; }(line 39) isnulleverywhere except on a WebAssembly client whose Server host opted in withAddCommonSameOriginApiProxy(lines 27-38). The host serves it as an origin-relative path in/client-configandMmcaClientConfigBootstrap.LoadAsyncresolves it to an absolute address. When it is set, the"APIClient"and the notification hub target it instead ofApiEndpoint, send noAuthorizationheader (the proxy attaches the bearer from the HttpOnly session cookie server-side) and add the proxy's CSRF header;ApiEndpointkeeps the gateway URL for full-page navigations that must reach the gateway itself, such as the external sign-in challenge (ADR-131). In the client factory the switch isclient.BaseAddress = new Uri(apiSettings.SameOriginApiEndpoint ?? apiSettings.ApiEndpoint!, ...)(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:170), and the same configuration key decides at registration time whether the proxy pipeline is wired at all (DependencyInjection.cs:151-155).
- Why it's built this way:
sealedplusinitgives an immutable snapshot of configuration that cannot drift while the app runs. Putting the validation attribute on the options class rather than writing a guard in theHttpClientfactory keeps one failure mode with one message: the comment atMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:160-164records that a second hand-written check would only give the same failure a different, less informative exception. - Where it's used: bound in
AddUIShared(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:49-51); read by the named"APIClient"HttpClientfactory to setBaseAddress(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:158-170, alongside the 90-second total-request timeout at:172-176); read byApiFileDownloadButtonfor its browser download URL,SameOriginApiEndpoint ?? WasmApiEndpoint ?? ApiEndpoint(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/ApiFileDownloadButton.razor.cs:132-142); read byNotificationHubServiceandBlazorCspPolicyProvider; and served to the WebAssembly client by each Server head's/client-configendpoint, both routed through the sharedMapClientConfigEndpoint(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:84-95; mapped byUseMmcaBlazorWebPipelineatMMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:211, which the hosts call atMMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:120-126andMMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:86-94).
IToastService
MMCA.Common.UI ·
MMCA.Common.UI.Common.Interfaces·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Interfaces/IToastService.cs:37· Level 1 · interface
- What it is: the framework's contract for transient user notifications ("toasts"), covering four named severities, a runtime-chosen severity, a persistent two-line notification, and a toast that carries a clickable action.
- Depends on: ToastSeverity (same file). Implemented by MudToastService over MudBlazor's
ISnackbar. - Concept introduced, fire-and-forget by design. The facade rationale is taught at IAppDialogService; what is specific here is that every method returns
void. The doc comment explains why (IToastService.cs:31-35): during server-side prerender there is no toast host at all, so the call is a silent no-op, and a contract that reported whether the message rendered would force every call site to handle a condition it can do nothing about.[Rubric §24, Forms, Validation & UX Safety]assesses whether outcomes surface to the user in a recoverable way;[Rubric §27, Internationalization]applies because every parameter is documented as already localized, which pushes resource resolution out to the page that owns the key. That last rule is enforced, not merely documented: an architecture fitness regex fails the build on a literal first argument to any toast method (Toast\.(?:Success|Info|Warning|Error|Show|ShowPersistent|ShowAction)\(\s*\$?", atMMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Ui/ArchitectureRules.LocalizedText.cs:14, with the comment at:12-13recording that it is the same guard that previously watched directISnackbaruse at:9). - Walkthrough: seven members, in three tiers.
- The four named severities,
Success(IToastService.cs:41),Info(:45),Warning(:49) andError(:53), each taking one already-localized message. MudToastService implements each as a one-linesnackbar.Add(message, Severity.X)(MudToastService.cs:15-42). Show(string message, ToastSeverity severity)(:62) is the same thing with the level as a parameter, and the doc comment names its motivating caller: ResultUiExtensions.NotifyOnFailure, which carries the severity through as an argument rather than picking one of the four (:55-58).ShowPersistent(string title, string body, ToastSeverity severity = ToastSeverity.Info)(:72) is the push-notification shape: an emphasized title above a body, staying on screen until dismissed. The reasoning (:64-67) is that a message arriving unprompted must not expire before the user has looked at the screen. MudToastService builds it as a render fragment, a<strong>title, a<br>, then the body (MudToastService.cs:59-69).ShowAction(string message, string actionText, Func<Task> onAction, ToastSeverity severity = ToastSeverity.Info, bool requireInteraction = false)(:96-101) is the undo / view-it / retry shape a bare message cannot express. Two contract details are documented rather than enforced. First, the callback runs outside any render callback, so nothing catches what it throws: a caller whose work can fail must guard it and raise its own failure toast (:78-81, restated at:86-88). Second,requireInteraction: truepins the toast open until the user dismisses it or takes the action, and the MudBlazor implementation additionally renders it filled, following the same emphasis conventionShowPersistentuses, "because a toast that waits for the user has to look like it is waiting" (:90-95).
- The four named severities,
- Why it's built this way: a small,
void-returning, already-localized contract is what allows the vendor to appear in exactly one class. It is registered scoped byAddCommonUiFacades()(DependencyInjection,MMCA.Common.UI/DependencyInjection.cs:291) to match the lifetime of the MudBlazorISnackbarit wraps. See ADR-067. - Where it's used: essentially everywhere a page reports an outcome. Inside the framework package: DataGridListPageBase<TDto>, MobileInfiniteScrollList<TItem>,
ListPageActions, the three notification pages, the sessions page, and theUnsavedChangesGuard,SharePageButton,ApiFileDownloadButtonandNotificationListenercomponents. Outside it, every consumer page reaches it indirectly through ResultUiExtensions.NotifyOnFailure. Component tests resolve it from the shipped bUnit base (BunitComponentTestBase.cs:54, whose comment at:50-51records that without it a consumer's component test fails to resolveIToastServiceand each repo ends up re-registering the same pair).
IPendingToastService
MMCA.Common.UI ·
MMCA.Common.UI.Common.Interfaces·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Interfaces/IPendingToastService.cs:16· Level 1 · interface
- What it is: the contract for a toast that must survive a full page reload. The caller parks one message, navigates with
forceLoad: true, and the next page load shows it. - Depends on: ToastSeverity (the level of the parked toast). Implemented by PendingToastService over
sessionStorage. - Concept introduced, a toast that outlives the page that raised it. IToastService is fire-and-forget against the live
ISnackbar, so a toast raised just before a forced reload dies with the old document.[Rubric §24, Forms, Validation & UX Safety]assesses whether outcomes surface to the user in a recoverable way; this interface is what keeps a "your account was deleted" style confirmation visible across a sign-out that reloads the app.[Rubric §27, Internationalization]applies as for the live facade: themessageis documented as already localized (IPendingToastService.cs:31). - Walkthrough: two members.
QueueAsync(ToastSeverity severity, string message, CancellationToken ct = default)(:40) parks the toast. The documented usage is: call it, await it, then navigate withforceLoad: true(:27-30). The token comes with a trap spelled out in the doc comment (:33-37): when the same action signs the user out of an[Authorize]page, the sign-out re-renders the route into the login redirect and disposes the page, which cancels the page's lifetime token and silently drops the toast, so passCancellationToken.None(or nothing) there.TakeAsync(CancellationToken ct = default)(:48) reads and removes the parked toast, returning a(ToastSeverity Severity, string Message)?that isnullwhen nothing is waiting or storage is unavailable (:47). It is called byPendingToastHost; a host that renders its own layout calls it once after its first interactive render (:43-45).
- Why it's built this way: a nullable tuple and a
ValueTaskkeep the contract free of any storage type, so thesessionStoragechoice stays inside PendingToastService, which also swallows every interop failure (prerender, torn-down circuit, refused storage) because losing the toast must not fail the action that raised it (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/PendingToastService.cs:36-39, with the same catch inTakeAsyncat:62-65). It is registered scoped withTryAddScoped<IPendingToastService, PendingToastService>()(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:293). See ADR-067. - Where it's used: implemented by PendingToastService; drained by
PendingToastHost(PendingToastHostTests.cscovers it); queued by the ADC profile page after account deletion (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/Profile.razor.cs), withProfileDeleteAccountTestsand theAccountDeletionTestsE2E workflow exercising it.
ApiSettingsValidator
MMCA.Common.UI ·
MMCA.Common.UI.Common.Settings·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Settings/ApiSettingsValidator.cs:11· Level 2 · class (internal, sealed, partial)
- What it is: the source-generated options validator for
ApiSettings: it checks the same data annotationsValidateDataAnnotationswould, without reflection, so it also runs on a trimmed WebAssembly client that carries noMicrosoft.Extensions.Options.DataAnnotations(ApiSettingsValidator.cs:5-9). - Depends on:
ApiSettings(the type it validates) andIValidateOptions<T>plus the[OptionsValidator]source generator (Microsoft.Extensions.Options). - Concept introduced: see the fail-fast configuration concept on
ApiSettings. This type is the compile-time half of it: the declaration is one line with no body (line 11), and the[OptionsValidator]attribute (line 10) makes the options source generator emit theValidatemethod from the annotations onApiSettings.[Rubric §23, Front-End Performance](assesses whether the client avoids work and payload it does not need) applies because the generator removes a reflection path and a package from the WebAssembly download. - Walkthrough: registered in
AddUISharedright after the options binding,AddOptions<ApiSettings>().Bind(...).ValidateOnStart()(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:49-51), withservices.TryAddEnumerable(ServiceDescriptor.Singleton<IValidateOptions<ApiSettings>, ApiSettingsValidator>())(line 52).TryAddEnumerablekeeps a repeatedAddUISharedcall from registering the validator twice;ValidateOnStartis what runs it during host startup. The comment at lines 46-48 states the reason for the generated validator. - Why it's built this way: an
internalgenerated validator keeps the validation rule on the options class's own attributes while costing the client nothing at run time, and the client factory's null-forgiving read ofApiEndpointrelies on it (comment,DependencyInjection.cs:161). - Where it's used: only in
AddUIShared(DependencyInjection.cs:52), and named in theApiSettingsdoc comment (Common/Settings/ApiSettings.cs:8). Covered byApiClientRegistrationTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/ApiClientRegistrationTests.cs). - Caveats / not-in-source: the generated
Validatebody is produced at build time and is not in the source tree.
MmcaClientConfigBootstrap
MMCA.Common.UI ·
MMCA.Common.UI.Common.Settings·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Settings/MmcaClientConfigBootstrap.cs:28· Level 2 · class (static)
- What it is: the WebAssembly client's bootstrap-time fetch of the
client-configdocument (served byClientConfigEndpointExtensions.MapClientConfigEndpoint) into a streamAddJsonStreamcan consume, with one automatic retry on failure or timeout, and with a same-origin API proxy path resolved to an absolute address on the way through. - Depends on:
ApiSettings, used only for itsSectionNameand theSameOriginApiEndpointproperty name when rewriting the document; otherwiseSystem.Net.Http.HttpClient,System.Text.Json.NodesandSystem.Text.Encoding(BCL). Nothing it touches needs a service provider, which is deliberate, since it runs beforebuilder.Servicesexists. - Concept introduced, a bounded retry at the one point in startup where configuration itself is still unknown.
[Rubric §29, Resilience, Reliability & Business Continuity](assesses whether a single transient failure at startup is survivable) and[Rubric §17, DevOps & Deployment]. Every other resilience mechanism in the framework (Polly pipelines, the outbox, internal commands) runs once DI and configuration exist; this runs before both, inProgram.cs, fetching the very document that will configure the rest of the client. APolly-based retry is unavailable at this point (no service provider yet), so the retry is hand-rolled: one attempt, then one retry after a fixed delay, with the caller's ownHttpClientand its ownTimeout. - Walkthrough:
ClientConfigPath = "client-config"(line 31), the relative path both overloads fetch, matching the endpoint's own route.DefaultTimeout(line 34, 15 seconds) andDefaultRetryDelay(line 37, 1 second) are the defaults the single-argument overload uses.LoadAsync(Uri baseAddress, CancellationToken)(lines 49-60) is the convenience overload: it builds a short-livedHttpClientscoped tobaseAddresswithDefaultTimeout, then delegates to the caller-owned overload. It carries an RS0027[SuppressMessage](line 48) whose justification records it as a grandfathered public overload whose signature cannot change without a breaking change.LoadAsync(HttpClient client, TimeSpan retryDelay, CancellationToken)(lines 72-90) is the real logic: fetch the bytes (line 81), and onHttpRequestExceptionor a caller-uncancelled timeout (IsTimeout, lines 83, 142-143) waitretryDelaythen fetch once more (lines 85-86) with no further retry.IsTimeout(lines 142-143) is the detail that makes the retry precise:HttpClientreports its own per-request timeout asTaskCanceledException, the same exception type the caller's own cancellation produces, so the two are told apart by checking whether the caller's token was the one that fired; only a timeout the caller did not ask for is retried.- The result passes through
ResolveSameOriginApiEndpointagainst the client'sBaseAddressand is wrapped in a non-writableMemoryStream(line 89), the shapeAddJsonStreamexpects. ResolveSameOriginApiEndpoint(byte[], Uri?)(lines 98-128,internal) exists because a host running the same-origin API proxy servesApi:SameOriginApiEndpointas an origin-relative path (the server cannot know the public origin a browser used behind ingress) while the"APIClient"needs an absolute base address (lines 92-97). It returns the document byte for byte unless every precondition holds: an absolute base address (line 100), a document that parses (aJsonExceptionis left for configuration binding to report, lines 110-114), anApiobject holding a non-blank stringSameOriginApiEndpointthat is not already an http(s) URL (lines 116-124). Only then does it replace the value withnew Uri(baseAddress, path).AbsoluteUriand re-serialize (lines 126-127). Parsing is case-insensitive on property names (line 108).IsHttpAbsolute(string)(lines 136-138,internal) accepts only an absolutehttporhttpsURI. A bare absolute-Uri.TryCreatecheck is not enough: on Unix-like runtimes, browser WebAssembly included,"/api/"parses as the absolutefile:///api/, so the relative path would be left unresolved and every client call would go tofile:///api/...(lines 130-135).
- Why it's built this way: a single flaky fetch (a cold container, a brief network blip during a rollout) would otherwise fail the entire WASM client boot before it can render anything, including an error page with any styling. One retry buys resilience against exactly that class of transient failure without turning a genuine outage into a long hang, since both attempts still respect
DefaultTimeout. Resolving the proxy path here rather than on the server keeps the server ignorant of the browser-facing origin, and doing it on the raw document means every later consumer ofApiSettingson the client sees an absolute address (ADR-131). - Where it's used:
MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web.Client/Program.cscallsLoadAsyncto populate the WASM client's configuration before any service is registered. The endpoint it fetches from isClientConfigEndpointExtensions(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs). Covered byMmcaClientConfigBootstrapTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Common/Settings/MmcaClientConfigBootstrapTests.cs) andSameOriginProxyClientTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/SameOriginProxyClientTests.cs). - Caveats / not-in-source: only one retry is ever attempted regardless of how the second attempt fails; a second transient failure fails the boot outright.
IUIModule
MMCA.Common.UI ·
MMCA.Common.UI.Common.Interfaces·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Interfaces/IUIModule.cs:11· Level 2 · interface
- What it is: the UI-side counterpart to the server's IModule. A pluggable UI module declares its navigation entries (and optionally how their nav groups look), its Razor assembly for route discovery, and optionally components it injects into the shell (the signed-in and public halves of the top app bar, the root layout, the content header, the footer) and a replacement for the framework's not-found content.
- Depends on: NavItem; NavGroup;
System.Reflection.Assembly(IUIModule.cs:1). - Concept introduced, plugging into a packaged application shell.
[Rubric §18, UI Architecture & Component Design]assesses whether there is a coherent composition model. ADR-067 states the problem this solves: before it, every Blazor head owned its ownApp/Routes/ layout / nav markup, so adding a module meant editing the host (a new nav link, a new assembly in the router, a new drawer in the layout), and two apps built on the same framework drifted apart in shell behavior even where they agreed. The framework already shipped the shell; what was missing was a contract letting a module contribute into it. Resolution isIEnumerable<IUIModule>from DI, so the shell composes whatever is registered without naming any module.[Rubric §25, Navigation & Information Architecture]applies because nav is contributed rather than hard-coded, and[Rubric §7, Microservices Readiness]applies in the same spirit as the server contract: a module that can be added or removed by one registration line is a module that can move. - Walkthrough: nine members, seven of them defaulted.
IReadOnlyList<NavItem> NavItems(IUIModule.cs:14): the module's contribution to the shared sidebar. Flattened byMMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor.cs:122with.SelectMany(m => m.NavItems).IReadOnlyList<NavGroup> NavGroups => [](:22): descriptions of nav groups by key (icon, initially expanded, order within the section) that apply to every module's items carrying that NavItem.Group, not only this module's (:16-21). The menu folds them into a dictionary withTryAdd, so the first registered description of a key wins, the same rule asNotFoundContentType(NavMenu.razor.cs:77-81). The empty default leaves every group as a collapsed folder in first-appearance order.Assembly Assembly(:25): the assembly containing the module's Razor pages. The router consumes it asAdditionalAssemblies="UIModules.Select(m => m.Assembly)"(MMCA.Common/Source/Presentation/MMCA.Common.UI/Routes.razor:13), which is what makes a module's@pageroutes discoverable at run time with no central route table to edit.IReadOnlyList<Type> AppBarComponentTypes => [](:31): a default interface member returning an empty collection expression. Components listed here render inside the top app bar for a signed-in user only, inside anAuthorizeView(MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/MainLayout.razor:51-58, gathered at:192; the mobile quick-actions row does the same atMMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor:50-56, gathered atNavMenu.razor.cs:74).IReadOnlyList<Type> PublicAppBarComponentTypes => [](:39): the same slot for every visitor, signed in or not, rendered ahead of the culture switcher and theme toggle in both the app bar (MainLayout.razor:44-49, gathered at:193) and the quick-actions row (NavMenu.razor:44-49, gathered atNavMenu.razor.cs:75). A component that should look different per sign-in state decides that itself (:33-38).IReadOnlyList<Type> LayoutComponentTypes => [](:42): the same idea at the root-layout level, for drawers, overlays and headless listeners (MainLayout.razor:154-157, gathered at:194).IReadOnlyList<Type> ContentHeaderComponentTypes => [](:48): components rendered at the top of the main content region, above the page body and beside the offline banner, for a banner the user must see before the page itself (:44-47).MainLayoutgathers them atMainLayout.razor:195and renders them in the block documented at:88-93.IReadOnlyList<Type> FooterComponentTypes => [](:61): components rendered inside the layout's onecontentinfofooter, after the configured footer text and legal links (MainLayout.razor:144-149, gathered at:196). Any contribution renders the footer even with noLayoutSettings.FooterTextand no legal links (MainLayout.razor:113). The remarks (:56-60) say why this is not a layout component: layout components are siblings of the sidebar and main region in the desktop flex row, so visible content there becomes an extra column instead of a footer.Type? NotFoundContentType => null(:70): a component the framework's not-found page renders in place of its default icon, title, message and home button (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/NotFound.razor:24-28). The page keeps its title and still renders the Access Denied view for a re-executed 403; when several modules supply one, the first registered wins (NotFound.razor:49,FirstOrDefaultover the non-null values).
- Why it's built this way: the seven default interface members are what keep the simple case simple. A module that only contributes navigation implements two properties, not nine, and can gain nav-group, app-bar, layout, content-header, footer or not-found contributions later without a breaking change to anything already written. Splitting the app bar into a signed-in slot and a public slot lets a control every visitor needs (a search box, a cart a signed-out shopper uses) live in the shell without each component re-implementing the sign-in gate. Passing an
Assemblyrather than a list of page types keeps route discovery reflective, so adding a page is never a framework edit. - Where it's used: implemented by module descriptors across the workspace: the framework's own NotificationUIModule (
MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationUIModule.cs:15), ADC'sConferenceUIModule(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/ConferenceUIModule.cs:31),EngagementUIModule(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/EngagementUIModule.cs:22),IdentityUIModule(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/IdentityUIModule.cs:19) and the MAUI-head-onlyDeviceUIModule(MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/DeviceUIModule.cs:19), plus Store'sCatalogUIModule(MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.UI/CatalogUIModule.cs:16),SalesUIModule(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.UI/SalesUIModule.cs:17),IdentityUIModule(MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.UI/IdentityUIModule.cs:14) andMauiUIModule(MMCA.Store/Source/Hosts/UI/MMCA.Store.UI/MauiUIModule.cs:14). The optional members earn their keep in practice: ADC'sConferenceUIModuledescribes six organizer nav groups (two of them expanded, each with its own icon and order, the framework's Notifications group last) (ConferenceUIModule.cs:97-105);NotificationUIModulecontributesNotificationBellto the signed-in app bar andNotificationListenerto the layout (NotificationUIModule.cs:23-25); Store'sSalesUIModulecontributesCartButtonto the public app bar,CartDrawerto the layout andOrphanOrderRecoveryto the content header (SalesUIModule.cs:33-40); Store'sCatalogUIModulecontributesStoreSearchBoxto the public app bar,StoreFooterLinksto the footer andStoreNotFoundas the not-found content (CatalogUIModule.cs:31-37); ADC'sEngagementUIModulecontributesLiveEventListener(EngagementUIModule.cs:45), ADC'sIdentityUIModulecontributesTermsAcceptanceGate(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/IdentityUIModule.cs:49), and ADC'sDeviceUIModulecontributes five native-integration layout components at once (DeepLinkListener,BiometricGate,PushRegistrationListener,NativeThemeSync,AppActionTitleRefresher;DeviceUIModule.cs:33). Registration goes throughAddUIModule<TModule>()(see DependencyInjection), which each module's own one-lineAdd{Module}UI()delegates to, for exampleMMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.UI/DependencyInjection.cs:19. A stub implementation drives the menu tests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Layout/NavMenuTests.cs:308) and another drives the backend-less component gallery (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Gallery/Stubs/GalleryUIModule.cs:14).
IEntityService<TEntityDTO, TIdentifierType>
MMCA.Common.UI ·
MMCA.Common.UI.Common.Interfaces·MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Interfaces/IEntityService.cs:20· Level 3 · interface
- What it is: the generic CRUD contract every module page injects to talk to its API endpoints. Seven asynchronous members, every one of them returning a Result.
- Depends on: Result and ErrorType from
MMCA.Common.Shared.Abstractions(IEntityService.cs:1); IBaseDTO<TIdentifierType> as theTEntityDTOconstraint (:21) and BaseLookup<TIdentifierType> as a return type (:41), both fromMMCA.Common.Shared.DTOs(:2). Implemented by EntityServiceBase<TEntityDTO, TIdentifierType>. - Concept introduced, the Result railway crossing the HTTP boundary intact.
[Rubric §18, UI Architecture & Component Design]assesses separation of components from their data access, and[Rubric §9, API & Contract Design]assesses whether the client contract mirrors the server surface. But the teaching point is the second paragraph of the doc comment (IEntityService.cs:10-16): every member returns "the same railway type the server produced, read back from its Problem Details response with the originalErrorTypeintact". A page therefore branches on the outcome instead of catching an exception. That is what makes a 404 renderable as an empty state and a 401 as a redirect without pattern-matching message text, and it is why the sibling helper ResultUiExtensions exists. ADR-013's 2026-08-27 revision records this as the retirement of the UI-layer deviation, and ADR-094 records the surrounding data-access contract. Note also the layering rule this respects:MMCA.Common.UImay referenceMMCA.Common.Sharedonly, which is why both constraints come fromSharedand never from Application or Domain[Rubric §3, Clean Architecture]. - Walkthrough: two generic constraints (
:21-22) bindTEntityDTOto IBaseDTO<TIdentifierType> and requireTIdentifierType : notnull. Then seven members, every one ending in a defaultedCancellationToken:GetAllAsync(bool includeFKs, bool includeChildren, CancellationToken)(:25-28) returnsResult<IReadOnlyList<TEntityDTO>>; the two flags map to API query options.GetPagedAsync(Dictionary<string, (string Operator, string Value)> filters, int pageNumber, int pageSize, string? sortColumn, string? sortDirection, bool includeChildren, CancellationToken)(:31-38) returnsResult<(IReadOnlyList<TEntityDTO> Items, int TotalItems)>. TheTotalItemshalf of that tuple is what makes server-side paging work at all: a grid needs the total to size its pager without fetching the rest of the table. The filter dictionary is the client half of the dynamic query contract (ADR-034).GetAllForLookupAsync(string nameProperty, CancellationToken)(:41-43) returns lightweightId + NameBaseLookup<TIdentifierType> items for dropdowns and autocompletes, so a picker never pulls whole entities.GetByIdAsync(TIdentifierType id, bool includeChildren, CancellationToken)(:50-53) returnsResult<TEntityDTO>, and the doc comment (:45-49) pins the contract that used to be ambiguous: a missing entity is anErrorType.NotFoundfailure, never a success carrying null. That is what lets a detail page writeif (result.IsNotFound())instead of a null check that cannot distinguish "absent" from "the call failed".AddAsync(TEntityDTO entity, CancellationToken)(:56-58) returns the server-assigned DTO including its generated id.UpdateAsync(TEntityDTO entity, CancellationToken)(:61-63) andDeleteAsync(TIdentifierType id, CancellationToken)(:66-68) return the non-genericResult, because there is no value to carry back, only a verdict.
- Why it's built this way: an interface keeps Blazor components testable (mock the contract, no HTTP) and hides the API URL structure behind a typed surface. The generic-over-DTO shape is the client mirror of the server's generic controller layer (ADR-034), which is why one base class implements it for every entity in the system. The uniform
Resultreturn is deliberate rather than convenient: mixing nullable returns for reads withboolfor writes forces each call site to invent its own error story, whereas returningResulteverywhere means one small set of helpers covers all seven members. - Where it's used: implemented for every entity by EntityServiceBase<TEntityDTO, TIdentifierType> (
MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:35-41, a primary-constructor class overAuthenticatedServiceBasethat takes only the endpoint, theIHttpClientFactoryand theITokenStorageService, with no client-side read cache) and consumed by every module CRUD page, most of them through DataGridListPageBase<TDto>. Registration is automatic:AddUIModule<TModule>()calls the framework's ownAddAssignableTypesscan over the module's assembly, which picks up every class assignable toIEntityService<,>and registers it scoped as its implemented interfaces (DependencyInjection,MMCA.Common.UI/DependencyInjection.cs:493-497). The(Items, TotalItems)shape ofGetPagedAsyncis also the shape MobileInfiniteScrollList<TItem>'s page-fetch delegate expects.
QrErrorCorrectionLevel
MMCA.Common.UI ·
MMCA.Common.UI.Components.Sharing·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Sharing/QrErrorCorrectionLevel.cs:9· Level 0 · enum
- What it is: the four QR error-correction strengths the framework's QR components expose. Higher levels survive more damage or occlusion but pack fewer characters into the same module count, so the code grows denser (lines 4-5).
- Depends on: nothing. It is a bare enum with no using directives.
- Concept introduced, a framework-owned enum instead of a re-exported vendor type.
[Rubric §9, API and Contract Design](assesses whether a public surface is expressed in types the owner controls) and[Rubric §32, Dependency and Supply-Chain](assesses whether third-party types leak into contracts consumers must compile against). The doc comment states the decision outright (lines 6-7): declaring this rather than exposing QRCoder's ownECCLevelkeeps the component's public API from pinning consumers to the encoder package. The mapping to the vendor type is a private detail of the component, a one-lineswitchinComponents/QrCodeImage.razor:77-82, so replacing the encoder would not be a breaking change for any page that names this enum. - Walkthrough: four members with explicit values and a stated recovery budget each:
Low = 0(line 12, about 7% recovery, densest code, short payloads on clean screens),Medium = 1(line 15, about 15%, the usual screen and print trade-off),Quartile = 2(line 18, about 25%, printed sheets that may get scuffed) andHigh = 3(line 21, about 30%, codes overlaid with a logo or scanned in poor light). The explicit values matter because the enum is bound as a component parameter and compared for change detection. - Why it's built this way: the recovery percentages are properties of the QR standard, not of the encoder, so documenting them on a framework enum keeps the decision (how much damage must this code survive?) at the call site where the physical context is known.
- Where it's used:
QrCodeImagetakes it as a parameter defaulting toMedium(Components/QrCodeImage.razor:36) and maps it toQRCodeGenerator.ECCLevelbefore encoding (:77-82);QrCodeButtondefaults toQuartile(Components/QrCodeButton.razor:65). ADC passesMediumexplicitly on the attendee badge (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Pages/CheckIns/MyBadge.razor:36) and the speaker QR page (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Speakers/SpeakerQr.razor:29). Covered byQrCodeImageTests.
RatingStars
MMCA.Common.UI ·
MMCA.Common.UI.Components.Ratings·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Ratings/RatingStars.razor.cs:13· Level 0 · class (partial component)
- What it is: a five-icon star rating display over a
doublevalue on a 0-5 scale, rendering full, half, or empty stars per position. - Depends on: MudBlazor's
Sizeenum andIcons.Material.Filled.{Star,StarHalf,StarBorder}. Nothing first-party. - Concept introduced, a pure display component with no state of its own.
[Rubric §18, UI Architecture](assesses whether a component's responsibility is genuinely narrow) and[Rubric §21, Accessibility](assesses whether a visual-only rendering carries an equivalent text alternative). Unlike an editable star-rating input, this component only renders: it has no click handler and no two-way binding, so the sameValuealways paints the same five icons regardless of interaction history. The single requiredAriaLabelparameter is what keeps the rating accessible to a screen reader, which otherwise would see five decorative icons and no number. - Walkthrough:
MaxValue = 5(line 115) is the fixed scale; the markup renders exactly that many icons regardless ofValue.Value(line 127) is adoubleon the 0-MaxValuescale. The doc comment (lines 121-125) states the intended caller pattern explicitly: a caller holding adecimalaverage casts it todouble, because the half-star threshold this component applies needs no decimal precision.AriaLabel(lines 130-132) is[EditorRequired], so the compiler enforces that every usage supplies the accessible name for the whole rating; there is no per-star label.Size(line 136) defaults toSize.Small.FillFor(int star)(lines 145-153) is the per-position logic: a star index at or belowValueisFullStar; otherwise it isHalfStarwhenValueis within half a star of that position (Value >= star - 0.5), elseEmptyStar.IconFor(string fill)(lines 138-143) maps those three string constants to the three MudBlazor icon glyphs through aswitch, defaulting to the empty-star border icon for any other value.
- Why it's built this way: three private string constants (
FullStar/HalfStar/EmptyStar) rather than an enum keep the fill/icon mapping a two-function, easily-read pair; the component stays a pure function ofValuewith no fields to maintain across renders. - Where it's used: exercised directly by
RatingStarsTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Ratings/RatingStarsTests.cs) and by 4 further call sites in Store's Catalog UI renderingProduct.RatingSummaryon catalog and product-detail pages. - Caveats / not-in-source: the exact call sites beyond the test project were not opened for this section (the brief lists "5" and "and 4 more"); which pages render it is not itemized here.
DetailLoadState
MMCA.Common.UI ·
MMCA.Common.UI.Components.PageState·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/PageState/DetailLoadState.cs:8· Level 0 · enum
- What it is: where a single-record page's load stands:
Loading,Loaded,NotFoundorFailed. It is the state aDetailPageBasepage exposes and theDetailLoadStateContentcomponent switches on to render a spinner, a "not found" alert, or an error with a Retry button. - Depends on: nothing. It is a bare enum with no using directives.
- Concept introduced, "missing" and "could not fetch" are different answers.
[Rubric §19, State Management & Data Flow](assesses whether UI state models the outcomes the user must react to) and[Rubric §29, Resilience, Reliability & Business Continuity](assesses graceful behavior when a dependency fails). The doc comment states the decision outright (DetailLoadState.cs:3-7): the two failure states are separate on purpose, because a failed load on venue Wi-Fi is the common case, and telling the reader the record is missing tells them not to try again. A single "not found" body for both would turn every transient network failure into a dead end. - Walkthrough: four members, each with a one-line contract.
Loading(line 11): a load is in flight and nothing has been shown yet.Loaded(line 14): the record is loaded and the page renders it.NotFound(line 17): the server answered that the record does not exist (HTTP 404).Failed(line 20): the load failed for any other reason, and the page offers a retry. - Why it's built this way: the mapping from a result to a state lives once in the base page, not in each page:
DetailPageBasestarts inLoading(Pages/Common/DetailPageBase.cs:52),BeginLoadresets toLoadingwhile superseding the load in flight throughLatestLoadGuard(:59-64), andCompleteLoadsetsLoadedon success andresult.IsNotFound() ? NotFound : Failedotherwise, but only when the load is still current (:78-95). Pages then only branch on the enum, so every detail page draws the same line between "gone" and "try again". - Where it's used:
DetailLoadStateContenttakes it as itsStateparameter and rendersPageLoadingState,PageErrorStateor the Retry alert per member, falling through toChildContentforLoaded(Components/PageState/DetailLoadStateContent.razor:10-34). ADC detail pages built onDetailPageBasebranch onLoadState != DetailLoadState.Loaded(for exampleMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Events/EventDetail.razor:19,Pages/Speakers/SpeakerDetail.razor:20,Pages/Sponsors/SponsorDetail.razor:18);SpeakerDashboardkeeps its own_loadStatefield of this type and applies the sameIsNotFound()split by hand (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Speakers/SpeakerDashboard.razor.cs:51,:139). Covered byDetailPageBaseTestsandDetailLoadStateContentTests.
IListLayoutSource
MMCA.Common.UI ·
MMCA.Common.UI.Components.Lists·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Lists/IListLayoutSource.cs:9· Level 0 · interface (internal)
- What it is: a one-property internal interface,
bool IsLayoutKnown { get; }(line 12), that tellsListPageShell<TItem>whether the page owning itsServerDatacallback has learned its viewport and chosen grid or card list. The shell reads it only when the page does not passListPageShell.IsLayoutKnownitself (doc comment, lines 3-8). - Depends on: nothing. It is a bare interface with no using directives.
- Concept introduced, a capability probe on the delegate's target.
[Rubric §18, UI Architecture & Component Design](assesses whether a shared component gets what it needs without every caller wiring it). The shell already receives the page's ownLoadServerDatamethod asServerData, so the delegate'sTargetis the page; casting that target to this interface gives the shell the page's layout state with no extra parameter (ListPageShell.razor.cs:167). Keeping itinternalkeeps the probe out of the package's public surface: only the framework's own page base implements it. - Walkthrough: the single getter (line 12).
DataGridListPageBase<TDto>declares it in its base list (Pages/Common/DataGridListPageBase.cs:24) and implements it explicitly asbool IListLayoutSource.IsLayoutKnown => IsLayoutKnown;(:90) over its ownprotectedIsLayoutKnown(:87), which the first viewport notification sets to true (:451-452). - Why it's built this way: an explicit implementation over a
protectedproperty lets the shell read the flag without exposing it on the page's public surface, and lets every list page built on the base gain the layout gate without a markup change (doc comment, lines 6-7). - Where it's used: implemented by
DataGridListPageBase(Pages/Common/DataGridListPageBase.cs:24,:90) and read byListPageShell'sLayoutKnown(Components/Lists/ListPageShell.razor.cs:167). Exercised throughListPageShellLayoutGateTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Lists/ListPageShellLayoutGateTests.cs).
RatingInput
MMCA.Common.UI ·
MMCA.Common.UI.Components.Ratings·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Ratings/RatingInput.razor.cs:12· Level 1 · class (partial component)
- What it is: the editable twin of
RatingStars: a MudBlazorMudRatingwrapped in arole="radiogroup"element that is named by a visible caption and, while a validation message is shown, described by it. Bound with@bind-Value, where 0 means no star selected (doc comment,RatingInput.razor.cs:6-11). - Depends on:
RatingStars(itsMaxValueconstant is the default scale, line 31), MudBlazor'sMudRating,MudText,SizeandTypo(NuGet), andEventCallback<int>(ASP.NET Core Components). - Concept introduced, supplying the group semantics a vendor control leaves out.
[Rubric §21, Accessibility](assesses whether a custom control exposes a name, role and state to assistive technology) and[Rubric §24, Forms/Validation/UX Safety](assesses whether validation errors are announced and tied to the field they belong to). The markup comment (Components/Ratings/RatingInput.razor:1-6) states the gap:MudRatingrenders one radio per star but no group around them, so a caption beside it is not their label and an error under it is not linked to them. The wrapper adds theradiogrouprole witharia-labelledbypointing at the caption (RatingInput.razor:8-9) and setsaria-describedbyto the error element only while an error exists (RatingInput.razor:10), which is what WCAG 1.3.1 and 3.3.1 ask for. The same role is what consumer E2E page objects locate the control by (RatingInput.razor:5-6), alongsidedata-testid="rating-input"(RatingInput.razor:12). - Walkthrough:
- Ids:
_labelIdand_errorId(lines 14-15) are per-instancerating-label-{guid}andrating-error-{guid}strings, so several ratings on one form (one per feedback question) never share an id. - Parameters:
Label(lines 18-20,[EditorRequired], the visible caption and accessible name),Value(lines 23-24) andValueChanged(lines 27-28) for two-way binding,MaxValue(lines 31-32, defaults toRatingStars.MaxValue),ErrorText(lines 38-39, rendered and linked while non-empty, cleared by setting it to null),Disabled(lines 42-43),Size(lines 46-47, defaults toSize.Largeas a comfortable touch target),LabelTypo(lines 50-51, defaults toTypo.subtitle2) andClass(lines 54-55, extra classes on the group element). HasError(line 57) is!string.IsNullOrEmpty(ErrorText); the markup renders the error as a caption withrole="alert"only when it is true (RatingInput.razor:19-22).OnSelectedValueChangedAsync(int value)(lines 59-63) stores the value locally and invokesValueChanged, the handler the markup wires toMudRating.SelectedValueChanged(RatingInput.razor:13-17).
- Ids:
- Why it's built this way: wrapping
MudRatingrather than forking it keeps MudBlazor's star rendering and keyboard handling, and adds only the missing ARIA structure. MakingLabelrequired means a rating can never ship without an accessible name, the same choiceRatingStarsmakes with its requiredAriaLabel. - Where it's used: ADC's feedback forms render one per rating question,
MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Pages/Feedback/SessionFeedback.razor:69andMMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Pages/Feedback/EventFeedback.razor:58. Covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Ratings/RatingInputTests.cs.
InfiniteScrollObserver<TOwner>
MMCA.Common.UI ·
MMCA.Common.UI.Components.Lists·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Lists/InfiniteScrollObserver.cs:17· Level 1 · class (internal sealed, generic)
- What it is: the one place that talks to
infinite-scroll.jsfor the two infinite-scroll components. It owns a per-instance observer id, a lazily imported JS module, theDotNetObjectReferenceback to its owner, and anIsObservingflag (lines 25-40). Its owner (a component exposing a[JSInvokable]callback) constructs it asnew InfiniteScrollObserver<TOwner>(JS, this)and callsObserveAsync,UnobserveAsyncandDisposeAsyncfrom its lifecycle. - Depends on:
IJSRuntime,ElementReference,DotNetObjectReference<TOwner>,IAsyncDisposable, and the internalLazyJsModuleimport wrapper (line 35). Nothing else first-party; consumed byInfiniteScrollSentinelandMobileInfiniteScrollList<TItem>(theTOwnerconstraint isclass, line 18). - Concept introduced, one JS-interop lifecycle shared by two components.
[Rubric §23, Front-End Performance](assesses whether observers are attached on demand and detached so they stop costing anything) and[Rubric §18, UI Architecture]. Before the extraction each component carried its own copy of the import, attach, detach and dispose code; the helper makes a fix to one race a fix to both. - Walkthrough:
ObserveAsync(ElementReference sentinel)(lines 48-78) awaits_module.GetOrImportAsync()(line 52), a single-flight import: Blazor does not serializeOnAfterRenderAsync, so a second call can start while the first import is in flight, and an unguarded??=would import twice and leak the overwritten instance (comment, lines 32-34). If the owner was disposed while the import was in flight, the late module is released and no observer is attached that nobody would ever detach (lines 54-62). Otherwise it creates theDotNetObjectReferenceonce (line 66), callsobservewith the reference, the element and the id (line 67), and setsIsObserving(line 68).JSDisconnectedExceptionandJSExceptionare both swallowed (lines 70-77): the list simply stops at the pages already loaded.UnobserveAsync()(lines 82-104) returns unless the module is imported and an observer is attached (line 84), callsunobservewith the id (line 92), tolerates both exceptions, and clearsIsObserving(line 103).DisposeAsync()(lines 107-133) guards re-entry with_disposed(lines 109-114), unobserves and disposes the module (lines 118-119), tolerates both exceptions, and disposes theDotNetObjectReferencein afinally(line 131) so the .NET side is released even if JS already went away.
- Why it's built this way: the observe path is where the two components had drifted apart (one tolerated
JSException, one did not); a single internal class with the guarded import fixes the leak and the dispose-during-import race once. - Where it's used:
InfiniteScrollSentinel.razor.cs(lines 35, 59-60, 78-80) andMobileInfiniteScrollList.razor.cs; exercised throughInfiniteScrollSentinelTests.
InfiniteScrollSentinel
MMCA.Common.UI ·
MMCA.Common.UI.Components.Lists·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Lists/InfiniteScrollSentinel.razor.cs:21· Level 0 · class (partial component)
- What it is: a bottom-of-list marker that raises
OnVisiblewhen it scrolls near the viewport, so the hosting page can fetch and append its next page. It owns the IntersectionObserver and nothing else: the item markup, the fetch, and the accumulated list stay with the page. - Depends on:
IJSRuntime,ElementReference, and MudBlazor'sMudProgressCircularin the markup; first-party, onlyInfiniteScrollObserver<TOwner>, which owns the shared JS module_content/MMCA.Common.UI/infinite-scroll.js(wwwroot/infinite-scroll.js). It is a sibling ofMobileInfiniteScrollList<TItem>, which drives the same JS module. - Concept introduced, the observer as a child component so disposal is correct.
[Rubric §23, Front-End Performance](assesses render and network cost: paging on demand instead of loading everything, and detaching observers so they stop costing anything),[Rubric §21, Accessibility](assesses whether dynamic content changes are announced without hijacking focus) and[Rubric §18, UI Architecture]. The design point recorded in the doc comment (lines 14-19) is a lifecycle one: a page deriving fromDataGridListPageBase<TDto>cannot hook async disposal because itsDisposeAsyncis not virtual, whereas a child component is disposed by the renderer the moment the host stops rendering it. Rendering the sentinel only while more pages exist therefore makes "detach the observer" a rendering decision rather than a bookkeeping one, and a filter reset that refills the list gets a fresh instance with a fresh observer. - Walkthrough:
- Parameters:
OnVisible(line 26),IsLoading(line 29) which renders the inline progress row, andLoadingLabel(line 32), the localized accessible name for that row. - State (lines 34-41): the
_sentinelRefelement reference (line 34), the_observerfield (line 35, anInfiniteScrollObserver<TOwner>that now owns the observer id, the imported JS module, theDotNetObjectReferenceand the observing flag),_wasLoading(line 40, the previous render'sIsLoading), and_disposed(line 41). OnSentinelVisible()(lines 47-49) is the[JSInvokable]callback. Its name is fixed by the shared JS module, which calls it by string (lines 43-46). It returns immediately when disposed, otherwise marshals onto the renderer withInvokeAsyncbefore invokingOnVisible.OnAfterRenderAsync(lines 52-63) attaches the observer on the first render, and re-attaches it on the render where a load has just finished:loadJustFinishedis_wasLoading && !IsLoading && _observer?.IsObserving == true(line 54),_wasLoadingis then updated (line 55), and either condition lazily creates the observer helper (line 59) and callsObserveAsync(_sentinelRef)(line 60). The reason is recorded on the field (lines 37-39): an IntersectionObserver reports threshold crossings only, so a sentinel that is still inside the viewport when the appended page arrives would never fire again and the list would stall until the user scrolled away and back. Re-observing creates a fresh observer, which delivers a fresh initial entry.- The module import, the
DotNetObjectReference, theobserve/unobservecalls and the swallowedJSDisconnectedException/JSExceptionlive in the shared helper, not here; seeInfiniteScrollObserver<TOwner>. DisposeAsync(lines 67-82) suppresses finalization, guards re-entry with_disposed(lines 71-74), and delegates teardown to_observer.DisposeAsync()when one was created (lines 78-80), so the detach, the module release and theDotNetObjectReferencedisposal happen in the helper.- The markup (
Components/InfiniteScrollSentinel.razor:4-13) is a singledivcarrying the element reference, with the progress row rendered only whileIsLoading. That row isrole="status" aria-live="polite" aria-busy="true"(line 9), matchingPageLoadingState's politeness so a screen reader hears that more items are loading without the announcement interrupting reading. - The JS side is deliberately tiny:
observedisconnects any prior observer for the id, creates anIntersectionObserverwithrootMargin: '200px'and invokesOnSentinelVisibleon intersection (wwwroot/infinite-scroll.js:3-14);unobservedisconnects and forgets the id (lines 16-22). The 200px margin is what makes the next page start loading slightly before the sentinel is on screen, and the disconnect-before-create step is what makes the post-load re-attach above safe to call repeatedly with the same id.
- Parameters:
- Why it's built this way: extracting just the observer is what lets a page keep its own cards, empty state and error state and still get infinite scroll (lines 10-13). The alternative, folding the behavior into the list component, would force any page that wants infinite scroll to also adopt that component's layout.
- Where it's used: ADC's public speaker list renders it below the card grid while more pages exist, wiring
OnVisibleto its own loader and passing a localized loading label (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Public/Speakers/PublicSpeakerList.razor:144-145, insidePublicSpeakerList). Covered byInfiniteScrollSentinelTests.
MobileInfiniteScrollList<TItem>
MMCA.Common.UI ·
MMCA.Common.UI.Components.Lists·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Lists/MobileInfiniteScrollList.razor.cs:20· Level 3 · class (generic partial component)
- What it is: the mobile card list every list page falls back to on a narrow viewport. It owns the whole loop: an IntersectionObserver sentinel that asks for the next page, an accumulated item list rendered through a caller-supplied card template (with optional per-card actions beside it), a rendered-item cap that bounds DOM growth, generation-guarded supersession of in-flight fetches, and localized load-failure handling with a Retry button.
- Depends on:
Resultand its generic form (the fetch delegate's return type),SharedResourcethroughIStringLocalizer<SharedResource>,ResultUiExtensions.LocalizedErrorMessage, theEmptyStatecomponent, theClickableCardcomponent each row's card is wrapped in, and, throughInfiniteScrollObserver<TOwner>, the shared_content/MMCA.Common.UI/infinite-scroll.jsmodule it shares withInfiniteScrollSentinel. Externals:IJSRuntime,DotNetObjectReference,CancellationTokenSource, MudBlazor primitives. - Concept introduced, generation-guarded supersession.
[Rubric §19, State Management](assesses whether concurrent updates to client state have a defined winner) and[Rubric §23, Front-End Performance]. The hard problem in an infinite list is not fetching, it is what happens when the user changes the filter while a fetch is in flight. Cancellation alone is not enough: the fetch delegate is consumer-supplied and may ignore itsCancellationTokenentirely, so a superseded call can still complete successfully and try to append rows to a list that was cleared. The answer here is a monotonically increasing_generationcounter (line 72). A load snapshots it before awaiting (line 167) and discards its results if the value moved while it waited (line 183). The token cancellation is still issued (it stops work that does honor it), but the generation, not the token, is authoritative (comment, lines 180-182). The second half of the pattern is that the page counter is computed, not committed:targetPage = _currentPage + 1(line 174) and_currentPageonly advances on a successful, non-superseded completion (line 198), so a cancelled, failed or superseded fetch leaves nothing to compensate back and no page is ever re-requested (comment, lines 171-173). - Concept introduced, card actions beside the clickable area, not inside it.
[Rubric §21, Accessibility]assesses whether interactive controls are nested inside other interactive controls.CardActionsTemplate(lines 29-37) renders a row's delete or edit buttons beside the card body rather than inside the element that carries the card's button role, so a clickable card that also holds actions is not axe nested-interactive and a tap on an action does not raiseOnCardClick. - Walkthrough:
- Injected services (lines 22-23:
IJSRuntimeand the localizer, no toast service) and parameters (lines 25-62).CardTemplateis an[EditorRequired]RenderFragment<TItem>(line 27);CardActionsTemplateis the optionalRenderFragment<TItem>?for per-card controls (line 37).FetchPageResult(line 47), also[EditorRequired], is the fetch delegate in the shape every Result-returning UI service already has,(page, pageSize, cancellationToken)returningResult<(IReadOnlyList<TItem> Items, int TotalItems)>, which isIEntityService<TEntityDTO, TIdentifierType>.GetPagedAsyncminus the filter and sort arguments.PageSizedefaults to 10 (line 49),EmptyIcontoSearchOff(line 55),MaxRenderedItemsto 500 (line 62). - State (lines 64-94):
_items,_totalCount,_currentPage,_generation, the four render flags (_isInitialLoad,_isLoadingMore,_hasMore,_loadError),_loadErrorMessage, the interop handles (_sentinelRef,_observer, the sharedInfiniteScrollObserver<TOwner>that owns the module, theDotNetObjectReferenceand the observer id, and_cts),_reobservePending(line 93) and_disposed. OnInitializedAsync(lines 96-102) validates the delegate then loads page 1.ValidateFetchParameter(lines 109-116) throws anInvalidOperationExceptionwhenFetchPageResultis null, deliberately before the load, so a misconfigured call site fails loudly instead of rendering as a load failure with a Retry button that can never succeed (lines 104-108).OnAfterRenderAsync(lines 118-128) consumes and clears_reobservePending(lines 120-121), then attaches the observer only while more pages exist, there are items to scroll past and the initial load is done, either when none is observing yet (_observer?.IsObserving != true) or when a re-observe was queued (line 123). It lazily creates the sharedInfiniteScrollObserver<TOwner>(line 125) and callsObserveAsync(_sentinelRef)(line 126); the helper toleratesJSDisconnectedExceptionandJSExceptionon both paths.OnSentinelVisible()(lines 130-143), the[JSInvokable]entry point, returns a completed task when already loading, exhausted or disposed (lines 133-136), otherwise theInvokeAsynctask that loads on the renderer's context and re-renders (lines 138-142).LoadNextPageAsync(bool isInitial)(lines 145-238) is the core. It guards re-entry (lines 147-150), sets_isLoadingMoreand clears the error state (lines 152-154), and, for a next-page load only, queues a render at once so the "Loading more items" status paints while the fetch is in flight, because a load started from a JS callback or the Retry button otherwise renders nothing until it ends (lines 156-163). The initial load has its own progress bar, and a Retry after a failed first page (an empty list) renders that same bar while_isLoadingMoreholds (comment, lines 158-159). It then snapshots the generation and publishes a freshCancellationTokenSource(lines 165-169), computestargetPage(line 174), and awaits the delegate (line 178). After the await it checks disposal and generation (line 183), unwraps theResultwithTryGetValueand routes a failure toSetLoadFailed(lines 188-194), and only then commits: advance the page (line 198), append the items throughAppendNewand keep the count of new rows (line 200), record the total (line 201), set_hasMorefromHasMoreAfter(appended)(line 202), which is where the DOM cap and the empty-append guard stop the loop, and callMarkReobserveAfterAppend(isInitial)(line 204).OperationCanceledExceptionis swallowed as a normal supersession (lines 206-209); any other exception, caught under a scopedCA1031suppression, raises the generic failure, again only for the current generation (lines 210-220). Thefinally(lines 221-237) is careful about ownership: only the current generation may clear_isLoadingMore(a superseding reset already cleared it and may have set it again), and only the still-currentCancellationTokenSourceis disposed here (ReferenceEquals, line 230), because a resetter that took one over already cancelled and disposed it.AppendNew(IEnumerable<TItem> items)(lines 246-254) appends only the rows not already shown and returns how many were new. Offset paging plus an insert ahead of the window can repeat a row across pages, and rows are keyed by value (@key="item"), so a repeat would be two siblings with one key and a render error (lines 240-245). It filters lazily with_items.Containswhile adding (line 251), so a row repeated inside the same page is caught too; records compare by value, the same equality@keyuses.HasMoreAfter(int appended)(lines 262-263) isappended > 0 && _items.Count < _totalCount && _items.Count < MaxRenderedItems: besides the rendered-item cap it stops when a page added nothing new (an empty page, or a window shifted by a whole page), so the re-observed sentinel cannot re-request the same page forever;ResetAsyncstarts over (lines 256-261).MarkReobserveAfterAppend(bool isInitial)(lines 269-275) sets_reobservePendingafter a non-initial append that left more pages. The IntersectionObserver reports threshold crossings only, so a sentinel still inside the viewport after the append would never fire again; re-observing creates a fresh observer, which delivers an initial entry with the current state (lines 90-92). This is the same stallInfiniteScrollSentinelguards against with its post-load re-attach.SetLoadFailed(Result? failure)(lines 287-291) sets the inline error state and nothing else: no toast is raised, because the inline alert is announced on its own, rendered in place of the list for a failed first page or below it for a later page (lines 277-280). The message comes fromfailure?.LocalizedErrorMessage(L)(line 290); a raw exception passesnull, because exception text is neither translatable nor safe to surface (lines 282-286), and the generic resource string is used instead.CardCallback(TItem item)(lines 300-303) binds one row's click behavior for the markup below. WhenOnCardClickhas a delegate it returns anEventCallback.Factory.Createwrapping the invoke; when it does not, it returnsdefault, deliberately notEventCallback.Empty, becauseEventCallback.Emptywraps a no-opActionso itsHasDelegateis still true and every card would present as interactive.defaultis the only valueClickableCardreads as "no handler wired", which is what lets it render a plain, non-focusable card instead of a keyboard control that does nothing (lines 293-299).CardActions(TItem item)(line 309) binds one row toCardActionsTemplate, or returnsnullwhen the consumer supplied none, which keepsClickableCardon its original one-element markup (lines 305-308).RetryAsync(line 311) is a plainLoadNextPageAsync(isInitial: false); the load queues its own render.ResetAsync()(lines 317-355) is the public API a page calls when filters change. Order matters and is commented: bump the generation first so any in-flight fetch is already superseded (line 321), then cancel and dispose the stale token source (lines 323-330), then clear_isLoadingMoreexplicitly (lines 332-335, because the superseded load will not clear it), then reset the list and every flag (lines 337-343), detach the observer (lines 345-348), and reload from page 1 (lines 350-354).DisposeAsync(lines 357-378) guards re-entry, cancels and disposes the token source (lines 368-372), then delegates to_observer.DisposeAsync()(lines 374-377), which detaches the observer, releases the JS module and disposes theDotNetObjectReference.- The markup (
Components/Lists/MobileInfiniteScrollList.razor:1-66) renders one of four shapes: an indeterminate progress bar inside arole="status"live region on the initial load, and also while the list is empty with a fetch in flight (_isInitialLoad || (_items.Count == 0 && _isLoadingMore), line 5), because a Retry after a failed first page clears the error before its fetch settles and an empty list that is still loading is never "no records" (lines 5-16); the load-failure alert when the first page itself failed (lines 17-22, because a failed first page is not an empty list);EmptyStatewhen the list came back empty (lines 23-26); or aMudStackofClickableCardwrappers around the caller's template, each keyed by item and wired toCardCallback(item)andCardActions(item)(lines 29-36). Below the cards it renders the sentineldivonly while_hasMore, with a polite live-region spinner while a page loads (lines 38-51), and the same alert when a later page failed (lines 53-56). That alert is oneRenderFragment,LoadFailedAlert, carryingrole="alert"with the message and a Retry button (lines 62-65).
- Injected services (lines 22-23:
- Why it's built this way: the component encapsulates the part of infinite scroll that is genuinely hard to get right (supersession, cancellation ownership, disposal, the DOM cap) and leaves the part that is app-specific (what a card looks like, where the data comes from) to parameters. The
Result-returning delegate rather than a rawTask<List<T>>is what makes a localized failure message reachable without the component knowing any error catalogue. - Where it's used: the mobile branch of every page built on
ListPageShell<TItem>, which renders it atComponents/Lists/ListPageShell.razor:47once the page's layout is known (the ADC conference admin lists such asSessionList.razor,SpeakerList.razorandRoomList.razor, and Store'sCategoryList.razor,ProductList.razorandShoppingCartList.razor). Pages that render it directly: ADC'sPublicEventList.razor:25,PublicSessionListView.razor:6and the check-inAttendeeSearchPanel.razor:28, and Store'sMMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.UI/Pages/Orders/OrderList.razor:39. Covered byMobileInfiniteScrollListTests. The list-shell placement is recorded in ADR-146 (Website/docs-src/adr/146-ui-page-bases-and-list-shell.md). - Caveats / not-in-source:
MaxRenderedItemsbounds the DOM but there is no virtualization, so 500 rendered cards remain in the DOM; whether that is acceptable on a given device is not determinable from source. A consumer fetch delegate that ignores itsCancellationTokenstill runs to completion after a reset: the generation guard discards its results, but the request itself is not stopped.
ListPageShell<TItem>
MMCA.Common.UI ·
MMCA.Common.UI.Components.Lists·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Lists/ListPageShell.razor.cs:23· Level 4 · class (generic partial component)
- What it is: the shared chrome of an admin list page: a
PageHeaderwith a cancel-loading button and header actions, a search row with filters, then either the phone card list or the server-paged data grid, the inline empty and failed states, and the delete confirmation. Until the page knows its viewport it renders neither layout, only a loading placeholder. A page built on DataGridListPageBase<TDto> supplies the data callbacks, the columns and the card template; the shell supplies everything else (ADR-146,Website/docs-src/adr/146-ui-page-bases-and-list-shell.md). - Depends on: MobileInfiniteScrollList<TItem> for the phone branch
(
ListPageShell.razor:47;ListPageShell.razor.cs:156), IListLayoutSource for the layout gate (ListPageShell.razor.cs:167), MudBlazor'sMudDataGrid<TItem>,MudDataGridPagerandMudProgressLinear(ListPageShell.razor:58,:81,:41), thePageHeader,ListNoRecordsContentandDeleteConfirmationcomponents (ListPageShell.razor:7,:77,:89), Result in the fetch delegate shape (ListPageShell.razor.cs:89), and SharedResource for the default labels (:27). - Concept introduced, one list layout that every list page inherits.
[Rubric §18, UI Architecture & Component Design]assesses whether repeated page structure lives in one component instead of being copied. Every list page passes the same parameters into one shell, so a change to the header, the search row, the empty state or the pager reaches every list at once.[Rubric §21, Accessibility]is served the same way:SearchAriaLabeldefaults to the placeholder text, because a placeholder alone is not an accessible name (WCAG 4.1.2), so every list's search field is named with no page change (doc comment,ListPageShell.razor.cs:61-66). - Concept introduced, measure the viewport before choosing a layout.
[Rubric §23, Front-End Performance]assesses whether a page avoids wasted fetches and layout shift.IsMobilestarts as a default, not a measurement, so rendering a layout before the first viewport notification took the desktop grid, which a phone then swapped for the card list: two fetches and everything below it moving (markup comment,ListPageShell.razor:36-39). The shell therefore holds both layouts back behind a viewport-highrole="status"placeholder and fetches nothing whileLayoutKnownis false (ListPageShell.razor:34-44); the first notification picks one. - Walkthrough
- Header:
Title([EditorRequired],:30-32),IsLoading, which shows the cancel button and the grid's loading bar (:35),OnCancelLoading(:38),CancelLabelandCancelAriaLabel, which default to the sharedCommon.Button.CancelandList.Aria.CancelLoadingtexts (:41,:44), andHeaderActions(:47). - Search row:
ShowSearchdefaults to true (:50),SearchTextto empty (:53),SearchTextChangedis raised debounced (:56),SearchPlaceholderdefaults toList.Search.Placeholder(:59), andFiltersrenders after the search box (:69). - Layout:
IsMobile(:72) andIsLayoutKnown, abool?that defaults tonull(:74-84). The privateLayoutKnown(:161-167) isIsLayoutKnown ?? (ServerData?.Target as IListLayoutSource)?.IsLayoutKnown ?? true: the explicit value when passed, otherwise the page that ownsServerData(bound as the page's own method, so the delegate'sTargetis the page), otherwise open. A shell driven by anything other than aDataGridListPageBasetherefore renders its layout at once. The page re-renders the shell after its viewport notification, so the gate is read again on the render that follows. - Phone branch: the
[EditorRequired]MobileFetchandCardTemplate(:87-89,:92-94),CardActionsTemplatefor controls beside the card body (:96-101),OnCardClick(:104) andMobilePageSize, default 10 (:107). - Grid branch: the
[EditorRequired]ServerDatacallback (:110-112),CurrentPagewithCurrentPageChangedfor@bind-CurrentPage(:115,:118),RowsPerPagedefault 10 (:121),Densedefault true (:124), the[EditorRequired]Columns(:127-129) andPageSizeOptions, whosenulloffers 5, 10, 25, 50 and 100 (:132,:169). - States:
LoadFailed,EmptyConfirmedandEmptyMessage(:135-141),OnRetry(:144),ShowDeleteConfirmationdefault true andDeleteEntityType(:147,:150). - Exposed references:
Gridisnullon a phone (:153),MobileListisnullon desktop (:156) andDeleteDialogisnullwhen the confirmation is not rendered (:159), so a page cannot act on the branch that is not showing. RetryAsync(:171-179) invokesOnRetrywhen a delegate is wired and otherwise reloads the grid's server data.
- Header:
- Why it's built this way: the shell holds no data and no state beyond the component references,
so the page base keeps ownership of loading, filtering and paging while the markup is written once.
Reading the layout gate from the
ServerDatadelegate's target is what lets every list page wired the usual way get the gate with no markup change (doc comment,ListPageShell.razor.cs:74-83). - Where it's used: ADC's conference admin lists (for example
MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Sessions/SessionList.razor:10,ActivityList.razor:10,EventList.razor:10,PartnerList.razor:10,QuestionList.razor:10,RoomList.razor:11,SpeakerList.razor:10,SponsorList.razor:10) and Store's admin lists (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.UI/Pages/Products/ProductList.razor:10,CategoryList.razor:10,ReviewList.razor:11,CustomerList.razor:10,InventoryItemList.razor:10,ShoppingCartList.razor:10). Pinned byListPageShellTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Lists/ListPageShellTests.cs),ListPageShellLayoutGateTests(same folder) for the layout gate, and theProbeListPageconformance page, and referenced byPageHeadingTestsBaseandDataGridListPageTestsBase.
ApiFileDownloadButton
MMCA.Common.UI ·
MMCA.Common.UI.Components.Forms·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/ApiFileDownloadButton.razor.cs:20· Level 6 · class (partial component)
- What it is: a payload-agnostic icon button that hands the user a file produced by an API endpoint. On a browser it is, by default, a plain download link to the endpoint; on a native (MAUI) head, where the WebView cannot download, it fetches the bytes over the API client and hands them to the head's
ISensitiveFileSaver, which stages them in the head's dedicated, purged folder and opens the OS share sheet. An endpoint that needs the caller's bearer token opts in withRequiresAuthentication, and the browser then fetches through the same API client and saves the bytes through the browser saver. Every client-side fetch is capped byMaxBytes(25 MiB by default), so one click cannot buffer an unbounded payload. Callers supply the endpoint, the file name, the MIME type and the labels; the button knows nothing about what the payload is (ApiFileDownloadButton.razor.cs:11-19,Components/Forms/ApiFileDownloadButton.razor:12-19). - Depends on:
IExternalLinkServiceandISensitiveFileSaver(the device-capability abstractions),IHttpClientFactory,ApiSettingsthroughIOptions<ApiSettings>,IToastService, andIStringLocalizer<ApiFileDownloadButton>over the component's own.resxpair, all injected in the markup file (Components/Forms/ApiFileDownloadButton.razor:5-10). The code-behind also injectsIServiceProvider(ApiFileDownloadButton.razor.cs:120-121) so it can resolveITokenStorageServiceoptionally, and it callsAuthDelegatingHandler.TrackTokenOwneron the authenticated fetch (:230). The file name goes through the package's staticSafeFileNamehelper (Services/Capabilities/Files/SafeFileName.cs:14). Externals:HttpCompletionOption,MemoryStream,AuthenticationHeaderValue, and MudBlazor'sMudIconButton. - Concept introduced, one component, two heads, one contract.
[Rubric §18, UI Architecture](assesses whether components have a single clear responsibility and keep host differences out of pages) and[Rubric §26, Front-End Security](assesses whether the front end treats caller-supplied data as untrusted). The head split is decided by a capability query, not by a compilation symbol: the markup branches onExternalLink.InterceptsLinks || RequiresAuthentication(ApiFileDownloadButton.razor:21). The first branch is a button whose click runsDownloadThroughClientAsync(:23-28); the second is the plain link (:32-36). Both render the sameMudIconButtonwith the same icon, size and accessible name, so the affordance looks identical while the mechanism differs (ADR-042). How the bytes reach the user is the head'sISensitiveFileSaver: the browser saver saves through a temporary object URL, the MAUI saver stages in the head's own folder (purged before each write, at app start and on every identity transition) and opens the share sheet. The security concept is path containment: a file name built from entity data must not be able to steer a filesystem write, which is why the name passes throughSafeFileName.Reducebefore the fetch. A second, smaller one is a bounded buffer: the client-side fetch holds the whole file in memory, which on a Blazor Server circuit is server memory per click, so it refuses anything pastMaxBytes. - Walkthrough:
DefaultMaxBytes(line 23) is the public default forMaxBytes,25L * 1024 * 1024(25 MiB).- Parameters (lines 25-114). Three are
[EditorRequired]:RelativeApiPath(line 28),FileName(line 39) andShareTitle(line 44).ContentTypedefaults toapplication/octet-stream(line 52) and is what the share sheet uses to pick target apps.Icondefaults to the generic download glyph (line 56),SizetoSize.Small(line 60).AriaLabel,UnavailableMessageandFailureMessage(lines 68, 75, 82) are nullable overrides over localized defaults.HttpClientNamedefaults to"APIClient"(line 89), the framework's bearer-token plus culture-header client.RequiresAuthentication(line 103) defaults tofalse: the doc comment (lines 91-101) records the trade, the plain link streams a large file without loading it into memory but carries cookies only, whiletruefetches through the named client with the signed-in user's bearer read from the component's own token storage and set on the request, on every head, a Blazor Server circuit included, and saves through the head's saver.MaxBytes(line 114) defaults toDefaultMaxBytesand bounds what the client-side fetch (a native head, or a browser withRequiresAuthentication) will hold in memory; a larger response is refused with the failure toast, and the plain browser link is not affected because the browser streams that download itself (lines 105-112). There is no staging-folder parameter: the folder belongs to the head's saver. Services(lines 120-121) is an injectedIServiceProvider, used only to resolveITokenStorageServiceoptionally: per the comment (lines 118-119), a host or a component test that registers no token storage still gets the handler's own bearer.AccessibleLabel(line 123) resolvesAriaLabel ?? L["Button.Download.Aria"].Value, and the markup binds it to BOTHaria-labelandtitleon either branch (ApiFileDownloadButton.razor:25-26,:34-35), so an icon-only control always carries a name (WCAG 4.1.2, per theAriaLabeldoc comment at lines 62-66). The default key lives in the component's own resource file (Components/Forms/ApiFileDownloadButton.resx:15).BrowserDownloadUrl(lines 132-142) is the link branch'sHref. The anchor is a plain top-level navigation, so it carries cookies but never anAuthorizationheader (lines 125-131), and the base is chosen in that light asSameOriginApiEndpoint ?? WasmApiEndpoint ?? ApiEndpoint(line 137). On a WebAssembly client of a host running the same-origin API proxy the link targets the proxy, the same base the"APIClient"uses: the browser sends the HttpOnly session cookie and the proxy attaches the real bearer server-side, so an authenticated download works with no token in script (ADR-131). Everywhere else it prefersWasmApiEndpointoverApiEndpointbecause the browser needs the externally reachable gateway URL: on the Server headApiEndpointmay be a container-internal name, and on the WASM headApiEndpointis already the browser-reachable value fetched from/client-config. With no base URL configured it falls back to the relative path (lines 138-139); otherwise it composes an absolute URI (line 140).DownloadThroughClientAsync(lines 147-202) is the click path of every head that does not use the plain link (comment, lines 144-146). It re-entrancy-guards on_isExportingand an empty path (lines 149-152), reducesFileNamethroughSafeFileName.Reducebefore the fetch so an unusable name costs no download (lines 157-163), pulls the bytes throughFetchAsync(line 165) and toasts the failure when that returnsnullfor an over-cap payload (lines 166-170), then hands them toFileSaver.SaveAsyncwith the sanitized name,ContentTypeandShareTitle(line 172), toastingUnavailableMessageor its localized default when no surface took the file: no share target accepted it, the browser circuit is gone, or the head registered no saver (lines 174-176). Three catch blocks all surface the failure toast throughWarnDownloadFailed(line 274) rather than throwing:HttpRequestException(line 179),OperationCanceledException(line 183, which here is theHttpClienttimeout, not a disposal, since no token is passed), and a bareException(line 190, under a scoped CA1031 waiver at line 189) covering a failed staging write, the share sheet and a failed browser save, because this runs in anOnClickcallback where an unhandled exception is fatal to a native host (lines 193-195). Thefinallyclears the guard (line 200).FetchAsync(lines 218-248) creates the named client and builds a GET for the relative path (lines 220-221). WithRequiresAuthenticationset it resolvesITokenStorageServicefrom the component's own scope (line 223); when that yields a non-blank access token it sets theBearerheader on the request (line 229) and callsAuthDelegatingHandler.TrackTokenOwner(token, tokenStorage)(line 230). It then sends withHttpCompletionOption.ResponseHeadersRead(line 236), so the size cap runs before the body is buffered (the default completion option would read the whole body insideSendAsync, per the comment at lines 234-235), and callsEnsureSuccessStatusCode(line 237, so a non-success status becomes theHttpRequestExceptionthe caller catches). AContent-LengthaboveMaxBytesreturnsnullbefore any body byte is read (lines 238-241); otherwise the body stream goes throughReadCappedAsync(lines 243-247). The doc comment (lines 204-217) gives the reason for setting the header here:IHttpClientFactorybuildsAuthDelegatingHandlerin a DI scope of its own, which on a Blazor Server circuit is not the circuit's, so left to the handler the download could go out anonymous; the handler leaves an existingAuthorizationheader alone and is told which storage owns the token, so a 401 still renews (or ends) the session this page holds. It is the same patternAuthenticatedServiceBaseandApiUserPreferenceWriterfollow. WithoutRequiresAuthentication, or with no token storage registered, the request carries no header of its own and the handler attaches its bearer.ReadCappedAsync(lines 256-272) copies the body into aMemoryStreamin 81,920-byte chunks (line 259) and returnsnullas soon as the buffered length plus the next chunk would pass the cap (lines 263-266), otherwise the array (line 271). Per its doc comment (lines 250-255) this covers a chunked body with noContent-Lengthand a length header that understates the body.- The sanitizer is not a private method of the component: it is the public static
SafeFileName.Reducein the same package (Services/Capabilities/Files/SafeFileName.cs:23-32), which trims the name, reduces it to a bare name withPath.GetFileNameand rejects an empty result,.and..(lines 25-31), returning null when nothing usable remains. Its remarks (lines 7-13) state the exact hazard:Path.Combinediscards the root outright when its second argument is rooted, and..segments walk out of it, so an unsanitized name built from entity data or taken from a response header would decide where a staging delete and write land. The browser sensitive-file saver (Services/Capabilities/Files/BrowserSensitiveFileSaver.cs:30) and the MAUI staging folder (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/Capabilities/Files/SensitiveFileStagingFolder.cs:31,:58) call the same helper again on the name they receive.
- Why it's built this way: the download mechanics are the part every consumer would otherwise re-implement per file type, and they are exactly the part that differs per head, so they belong in the framework behind a capability query (ADR-042). Delegating the save to
ISensitiveFileSaverputs every staged file of a native head in the one folder the head purges, so a downloaded calendar file or report gets the same lifetime as the personal-data export. Making the authenticated browser path an opt-in keeps the streaming plain link as the default for public files. The opt-in sets the bearer from the component's own token storage rather than trusting the delegating handler, because the handler's DI scope is not the circuit's on Blazor Server; reading the token where the page lives is what makes it the signed-in user's token on every head. The byte cap is checked twice (the header, then the running copy) because a server can omit or understateContent-Length, and only the copy loop sees the real size. Keeping the wording out of the component (labels are parameters with localized fallbacks) is what lets one button serve a calendar file, an export, or a receipt without the framework knowing any of those words. - Where it's used: ADC wraps it in a thin calendar affordance,
MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Components/AddToCalendarButton.razor:8, which suppliesContentType="text/calendar", the calendar glyph, and its own localized aria-label and failure messages while the download and save mechanics stay here. ADC's ticket insights CSV export uses it withRequiresAuthentication="true"because the export needs the organizer's bearer token (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Pages/Tickets/Insights/InsightReportSection.razor:25-32). Covered byApiFileDownloadButtonTestsandApiFileDownloadButtonAuthenticatedTests. - Caveats / not-in-source: with
RequiresAuthenticationthe browser holds the whole payload in memory before saving it, which the plain link avoids (lines 91-101);MaxBytesbounds that buffer but does not stream it. No ADC caller in this source setsMaxBytes. ADC's personal-data export on the profile page does not use this component:LegalAndDataCardhands the file toISensitiveFileSaverdirectly (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/LegalAndDataCard.razor.cs:44,:156), the same saver this button uses, whose MAUI head stages into themmca-exportsfolder named atMMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/MauiProgram.cs:108. Which apps a native share sheet offers for a given MIME type is OS behavior and not determinable from this source.
FilePickerButton
MMCA.Common.UI ·
MMCA.Common.UI.Components.Forms·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/FilePickerButton.razor.cs:14· Level 0 · class (partial component)
- What it is: a file picker a keyboard can reach: a visually hidden
<input type="file">that keeps its tab stop, a<label for>styled as aMudButtonthat opens it on click, and a focus ring on the wrapper while the input has focus (FilePickerButton.razor.cs:7-13). - Depends on: nothing first-party. ASP.NET Core's
InputFileandInputFileChangeEventArgs(Microsoft.AspNetCore.Components.Forms) and MudBlazor'sMudButton,Variant,Color,SizeandIcons. - Concept introduced, keep the native control focusable and dress up its label.
[Rubric §21, Accessibility](assesses whether every interactive control is operable by keyboard and carries an accessible name). The obvious way to restyle a file input is to hide it with thehiddenattribute and forward clicks, which removes it from the tab order and leaves a keyboard or switch user no way to open the picker (WCAG 2.1.1). Here theInputFilekeeps its tab stop under thevisually-hiddenclass (FilePickerButton.razor:17-24), and the visible control is aMudButtonrendered withHtmlTag="label"andforpointing at the input (:8-9), so a click anywhere on it opens the picker and its text is the input's accessible name. A label takes no focus of its own, so the wrapper carries a:focus-withinring and the keyboard path stays visible (WCAG 2.4.7,:1-6). - Walkthrough:
Text(line 19) andOnChange(line 24) are[EditorRequired]: the visible text (also the accessible name) and the callback that receives the picked files, bound straight to theInputFile(FilePickerButton.razor:18).InputId(line 31) is optional.EffectiveInputId(line 84) falls back to a per-instanceGeneratedInputIdoffile-picker-{Guid:N}(line 82), so the label'sforand the input'sidalways match; set it when a test or page selects the input by id, such as Playwright'sSetInputFilesAsync("#id", ...)(lines 26-29).Accept(line 38): the doc comment (lines 33-36) says to name MIME types as well as extensions, because the Android picker filters on MIME types only.AriaLabel(line 45) overrides the label-derived name only when it should differ fromText; unset, the markup emits noaria-labeland the label names the input (FilePickerButton.razor:22).Disabled(line 49) applies to both the button and the input (FilePickerButton.razor:14,:21);Multiple(line 53) maps to the input'smultiple.- Presentation:
Icondefaults to the upload glyph (line 57),VarianttoVariant.Outlined(line 61),ColortoColor.Default(line 65),SizetoSize.Medium(line 69), andClass(line 73) adds wrapper classes. InputAttributes(lines 79-80) captures unmatched attributes and splats them on theInputFile, not the button (FilePickerButton.razor:24), so adata-testidlands on the element a test drives.
- Why it's built this way: every upload page needs the same picker, and the version that looks simplest is the one that fails keyboard users, so the accessible shape is written once in the framework and pages pass only their text, callback and filter.
- Where it's used: ADC's session-asset upload (
MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/SessionAssets/SessionAssetComposer.razor:28), ticket roster upload (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Pages/Tickets/TicketRosterUpload.razor:10) and profile photo upload (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/Profile.razor:60). Covered byFilePickerButtonTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Forms/FilePickerButtonTests.cs) and listed inEditorRequiredParameterConventionTests. - Caveats / not-in-source: the
:focus-withinring itself lives in the component's scoped stylesheet, which this section does not cite line by line.
BuiltInStrings
MMCA.Common.UI ·
MMCA.Common.UI.Globalization·MMCA.Common/Source/Presentation/MMCA.Common.UI/Globalization/InvariantMudLocalizationInterceptor.cs:73· Level 0 · class (private, sealed, nested, implementsIStringLocalizer)
- What it is: a private class nested inside
InvariantMudLocalizationInterceptorthat resolves MudBlazor's own built-in English strings straight from its embedded resource file, instead of MudBlazor's generatedLanguageResourceclass, which isinternalto the MudBlazor assembly and therefore unreachable directly. - Depends on:
System.Resources.ResourceManagerandSystem.Globalization.CultureInfo(BCL); reads the manifest resource named"MudBlazor.Resources.LanguageResource"offtypeof(MudLocalizer).Assembly(MudBlazor, NuGet). Nothing first-party beyond its owner. - Concept: no new pattern; addressing an internal library resource by its manifest name, plus a minimal singleton (a
privateconstructor and astatic Instanceproperty, lines 79-83). - Walkthrough:
this[string name](85-92) callsResources.GetString(name, CultureInfo.InvariantCulture)(89) and returns aLocalizedStringwhoseresourceNotFoundflag is set when that lookup returns null.this[string name, params object[] arguments](94-104) does the same lookup, then formats the resolved string withCultureInfo.CurrentCulturewhen it was found, or falls back to the barenamewhen it was not (98-101).GetAllStrings(bool includeParentCultures)(106-122) enumerates the invariant-cultureResourceSet(108) and yields aLocalizedStringper entry, or nothing if the set cannot be created (109-112). - Why it's built this way:
privateandsealed, nested inside its only consumer, because it exists solely to giveInvariantMudLocalizationInterceptoranIStringLocalizerit can pass as the English fallback to the baseAbstractLocalizationInterceptorconstructor; reading the manifest resource by string name is the only way to reach MudBlazor's built-in strings since the generated resource class itself is internal to MudBlazor. - Where it's used: constructed once via
Instanceand passed as the built-in localizer argument toInvariantMudLocalizationInterceptor's base constructor call (line 38); not referenced outside the file that defines it.
PseudoLocalizer
MMCA.Common.UI ·
MMCA.Common.UI.Globalization·MMCA.Common/Source/Presentation/MMCA.Common.UI/Globalization/PseudoLocalizer.cs:20· Level 0 · class (static)
- What it is: a pure string transform that "pseudo-localizes" text. It accents every letter, pads the result by roughly 40% to simulate real-translation expansion, and wraps it in
[!! ... !!]bracket sentinels, while leaving composite-format placeholders ({0},{name}) byte-identical so the string can still be formatted with arguments (ADR-027 §8). - Depends on:
System.Text.StringBuilderandchar.IsLetter(BCL). Nothing first-party. It is consumed byPseudoStringLocalizer. - Concept introduced, pseudo-localization as an i18n fitness test.
[Rubric §27, Internationalization](assesses whether the app is genuinely translation-ready, not just wired for one extra language) and[Rubric §28, Front-End Testing](assesses whether i18n defects are caught automatically). Pseudo-localization is a development-time technique that surfaces three classes of bug in a single visual pass, without needing a real second translation, and the<remarks>block (PseudoLocalizer.cs:12-19) enumerates exactly those three: (1) any string that stays plain ASCII was hard-coded rather than pulled from a resource, and stands out beside the accented text; (2) any UI that truncates the padded text has a fixed-width layout that a real (longer) translation would break; (3) any label built by concatenating fragments shows one sentinel per fragment, exposing the joins that translate badly. - Walkthrough:
- Three constants (lines 22-24):
OpenSentinel = "[!! ",CloseSentinel = " !!]", andCombiningAcute(the combining acute accent code point) appended after each base glyph so the letter stays readable while visibly altered. Transform(string value)(lines 30-74): returns null/empty input unchanged (lines 32-35); pre-sizes aStringBuilderwith slack for the padding (line 37) and appends the open sentinel (line 38); then walks each character in aswitch(lines 42-66) tracking aninsidePlaceholderflag toggled by{and}(lines 46-53) so placeholder bodies are copied verbatim, and for every letter outside a placeholder appends the combining accent and increments aletterscounter (lines 54-64); finally computes the pad length asMath.Max(1, letters * 2 / 5)(about 40%, line 69), appends a separating space (line 70), that many~characters (line 71) and the close sentinel (line 72), and returns the string (line 73).
- Three constants (lines 22-24):
- Why it's built this way: keeping the transform pure and static (input string to output string, no culture check inside) makes it trivially unit-testable and lets the culture gating live one layer up in
PseudoStringLocalizer. Preserving{...}placeholders is essential: transforming them would corruptstring.Format, so pseudo-loc must accent the template and only then substitute arguments (see the two-step inPseudoStringLocalizer). - Where it's used: called by
PseudoStringLocalizeron every resolved string when the current UI culture is the pseudo locale (SupportedCultures.PseudoLocale, referenced in the doc comment at line 10); inert otherwise. Covered byPseudoLocalizationTests.
StringLocalizerPluralExtensions
MMCA.Common.UI ·
MMCA.Common.UI.Globalization·MMCA.Common/Source/Presentation/MMCA.Common.UI/Globalization/StringLocalizerPluralExtensions.cs:20· Level 0 · class (static)
- What it is: a static extension class that adds a
Plural(key, count, args)method toIStringLocalizer, resolving the count-appropriate resource key (a.Onesuffix for a count of exactly one,.Otherfor every other count, zero included) with a fallback to the base key when the plural-specific entry is missing. - Depends on:
Microsoft.Extensions.Localization.IStringLocalizer/LocalizedString(NuGet). No first-party dependency. - Concept introduced, plural-form resolution via key suffixing.
[Rubric §27, Internationalization]assesses whether the app handles languages whose plural rules diverge from a naive singular-versus-plural split; this extension implements the simpler English-style two-category split (one, other) as a suffix convention on top of the standardIStringLocalizerindexer, rather than pulling in a full CLDR plural-rules library.OneSuffix(".One", line 23) andOtherSuffix(".Other", line 26) are the two constants callers key their resx entries against. The C#extension(IStringLocalizer localizer)block (line 28) is the new extension-member syntax the workspace'sLangVersion: previewsetting enables, in place of a classicthis IStringLocalizer localizerfirst parameter. - Walkthrough:
Plural(string key, int count, params object[] args)(lines 40-52) validates its arguments (42-44), pickspluralKeyaskey + OneSuffixwhencount == 1orkey + OtherSuffixotherwise (46), resolves it through the localizer's indexer (47), and if that lookup'sResourceNotFoundis true, falls back to the basekeyitself (51): the comment at 49-50 records why the fallback matters,ResourceNotFoundis how aResourceManager-backed localizer reports a missing key, by handing back the key name itself, which must never reach the screen. - Why it's built this way: the fallback to the unsuffixed
keymeans a resx file that has not yet been split into.One/.Otherentries still renders something legible instead of a raw resource-key string; the suffix convention keeps plural-aware resources in the same flat resx format every other string uses, no separate plural-rules resource format. - Where it's used: not referenced outside the file that defines it.
NotificationPageNotFoundStatus
MMCA.Common.UI ·
MMCA.Common.UI.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationPageNotFoundStatus.cs:11· Level 0 · class (internal, sealed)
- What it is: a render-nothing
ComponentBasewhose only job is to tell the host the response is a 404 when the router answers a notification route with the not-found page. - Depends on: externals only:
Microsoft.AspNetCore.Components(ComponentBase,[Inject],NavigationManager). No first-party types. - Concept introduced, a not-found that is a real status.
[Rubric §25, Navigation, Routing & Information Architecture]assesses whether the routing answer matches what the host composed. Rendering the not-found page alone would still return HTTP 200 on a server render; callingNavigationManager.NotFound()is the framework signal that sets the 404 status. - Walkthrough
Navigation(lines 14-15) is an[Inject]ed privateNavigationManager.OnInitialized()(line 18) is the whole behavior:Navigation.NotFound().
- Why it's built this way: the call has to run inside a component lifecycle, so the signal is a tiny component rather than code in
Routes.razor;internalbecause only the router uses it. - Where it's used: mounted through
<DynamicComponent Type="typeof(NotificationPageNotFoundStatus)" />in the hidden branch of the router (MMCA.Common/Source/Presentation/MMCA.Common.UI/Routes.razor:25), next to the not-found page rendered by NotificationPageGate's decision.
NotificationPageRequirement
MMCA.Common.UI ·
MMCA.Common.UI.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationPageRequirement.cs:24· Level 0 · class (internal, sealed, primary constructor)
- What it is: the
IAuthorizationRequirementbehind the two policies the notification pages declare instead of a bare[Authorize]:mmca:notification-pages(the inbox, any signed-in caller) andmmca:notification-manage-pages(history and compose, a signed-in caller who also holdsnotifications:manage). It carries two policy-name constants (PolicyName, line 29;ManagePolicyName, line 35) and an optional required permission (Permission, line 41). - Depends on: externals only:
Microsoft.AspNetCore.Authorization(IAuthorizationRequirement). The class doc references LayoutSettings and NotificationPageGate. - Concept introduced, a policy that can defer to the router.
[Rubric §11, Security]and[Rubric §25, Navigation, Routing & Information Architecture]. A bare[Authorize]becomes endpoint metadata, so on a Blazor Web host the authorization middleware challenged a signed-out request (a sign-in redirect) before the router's gate ran, and a page that does not exist for this host asked the visitor to sign in (class remarks). The same metadata is what answers a full page load, so the history and compose pages carry thenotifications:managepermission here: a signed-in caller without it is refused at authorization (403, the in-shell Access Denied) instead of being served a page that renders Forbidden under a 200. The requirement only carries the optional permission; the decision is made by NotificationPageAuthorizationHandler. - Walkthrough:
PolicyNameis"mmca:notification-pages"(line 29, any signed-in caller).ManagePolicyNameis"mmca:notification-manage-pages"(line 35, signed in and holdingNotificationPermissions.Manage).Permission(line 41) is the constructor'spermissionargument,nullwhen being signed in is enough. - Why it's built this way: a named policy with its own requirement lets the pass condition be "the pages are hidden, or signed in (with the permission when one is named)" while still reading as
[Authorize]semantics on the page. One requirement type with an optional permission serves both policies, so there is a single handler. - Where it's used: both policies are added in
AddUIShared:PolicyNamewithnew NotificationPageRequirement()andManagePolicyNamewithnew NotificationPageRequirement(NotificationPermissions.Manage)(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:89-93); evaluated by the handler (NotificationPageAuthorizationHandler.cs, 4 references).
FocusOnInAppNavigate
MMCA.Common.UI ·
MMCA.Common.UI.Layout·MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/FocusOnInAppNavigate.razor.cs:12· Level 0 · class (sealed, partial component, implementsIDisposable)
- What it is: a wrapper around Blazor's built-in
FocusOnNavigatethat moves focus to the new page's heading only after an in-app navigation, never on the initial page load, and ignores location changes that only rewrite the query string or fragment (doc comment,FocusOnInAppNavigate.razor.cs:6-11). - Depends on:
ComponentBase,NavigationManager,RouteData,LocationChangedEventArgsand theFocusOnNavigatecomponent (ASP.NET Core Components, BCL/framework). Nothing first-party. - Concept introduced, focus management that does not steal the skip link.
[Rubric §21, Accessibility](assesses whether keyboard and screen-reader users can move through the app predictably) and[Rubric §25, Navigation & IA](assesses whether a route change is announced and orients the user). In a single-page app a route change does not reload the document, so focus stays wherever it was; moving it to the new page'sh1tells assistive technology that the page changed. The markup comment (Layout/FocusOnInAppNavigate.razor:1-4) records why the stock component is not used directly:FocusOnNavigatealso fires on the first render, which put focus on theh1of a freshly loaded page, so the first Tab skipped the "Skip to main content" link. This component renders nothing until the first real navigation (FocusOnInAppNavigate.razor:5-8), leaving focus at the document start on load. - Walkthrough:
- State:
_hasNavigated(line 14) gates the render and_initialPath(line 15) remembers the path the component was first shown on.Navigation(lines 17-18) is an injectedNavigationManager. - Parameters:
RouteData(lines 21-23) is[EditorRequired]and passed through toFocusOnNavigate;Selector(lines 26-27) is optional, and the markup falls back to"h1"when it is null (FocusOnInAppNavigate.razor:7). OnInitialized(lines 33-37) records the absolute path of the current URI (line 35) and subscribes toLocationChanged(line 36).OnLocationChanged(lines 39-49) returns early when the component has already flipped, or when the new location's absolute path equals_initialPathunderOrdinalIgnoreCase(lines 41-42), which is how a list page that mirrors its grid state into the query string avoids being treated as a navigation. Otherwise it sets_hasNavigated(line 47) and schedules a re-render withInvokeAsync(StateHasChanged)(line 48). From that render on,FocusOnNavigateis in the tree and handles every later navigation itself.Dispose(line 30) unsubscribes fromLocationChanged.
- State:
- Why it's built this way: wrapping rather than reimplementing keeps the framework's own focus logic (selector lookup, focus call) in charge; the wrapper only decides when that logic enters the tree. The flag is one-way because after the first navigation the stock component's "focus on every render" behavior is exactly what is wanted.
- Where it's used: rendered by the shared router in
MMCA.Common/Source/Presentation/MMCA.Common.UI/Routes.razor:52withSelector="h1", so every host that uses the sharedRoutesgets it. Covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Layout/FocusOnInAppNavigateTests.cs.
InvariantMudLocalizationInterceptor
MMCA.Common.UI ·
MMCA.Common.UI.Globalization·MMCA.Common/Source/Presentation/MMCA.Common.UI/Globalization/InvariantMudLocalizationInterceptor.cs:37· Level 1 · class (internal, sealed)
- What it is: MudBlazor's interception point for resolving its own chrome text, tuned so the neutral
"en"culture (whose parent is the invariant culture) still routes through the app'sMudLocalizerlike every other non-English culture, and only"en-US"(and other cultures whose parent is literally English) short-circuits straight to MudBlazor's built-in strings (ADR-027). - Depends on:
BuiltInStrings(its own nested Level 0 type, passed as the built-in localizer), an optionalMudLocalizerconstructor parameter (MudBlazor, NuGet), and the base class the constructor chains into,AbstractLocalizationInterceptor(BuiltInStrings.Instance, mudLocalizer)(line 38). - Concept introduced, matching a library's own "is this English" test rather than assuming one.
[Rubric §27, Internationalization]. The comment at lines 46-48 records the design constraint directly: this interceptor deliberately reproduces MudBlazor's own definition of "is this culture English", the culture's parent's two-letter ISO name equals"en"so a specific culture like"en-US"counts as English, but the neutral"en"culture itself (whose parent is the invariant culture, not English) does not, and instead flows throughMudLocalizerlike any other culture, falling back to the built-in string only if that lookup reportsResourceNotFound. - Walkthrough: the primary constructor (line 37) takes an optional
MudLocalizer? mudLocalizerand passes it, alongsideBuiltInStrings.Instance, to the baseAbstractLocalizationInterceptor.Handle(string key, params object[] arguments)(lines 41-61) validates its arguments (43-44), computesisEnglishby comparingCultureInfo.CurrentUICulture.Parent.TwoLetterISOLanguageNameto"en"withOrdinalIgnoreCase(49-52), and returns straight fromBuiltIn(key, arguments)(56) whenMudLocalizeris null or the culture is English (54-57); otherwise it triesMudLocalizer[key, arguments](59) and falls back toBuiltInwhen that translation reportsResourceNotFound(60). The privateBuiltIn(string key, object[] arguments)helper (65-66) is a no-argument-indexer call whenargumentsis empty, the comment at 63-64 notes that formatting a value containing literal braces with an empty argument list would throw, and MudBlazor's own strings are looked up the same way. - Why it's built this way: reusing MudBlazor's own English-detection rule, rather than a simpler "does the culture name start with
en" check, keeps this interceptor's fallback behavior identical to MudBlazor's defaultDefaultLocalizationInterceptorfor the one case (the neutral"en"culture) where a naive check would diverge from it. - Where it's used:
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs(1 reference, its registration). Tested byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Globalization/InvariantMudLocalizationInterceptorTests.cs.
PseudoStringLocalizer
MMCA.Common.UI ·
MMCA.Common.UI.Globalization·MMCA.Common/Source/Presentation/MMCA.Common.UI/Globalization/PseudoStringLocalizer.cs:13· Level 1 · class (sealed)
- What it is: an
IStringLocalizerdecorator that pseudo-localizes every resolved string, but only when the current UI culture is the pseudo locale; under every other culture it delegates unchanged to the wrapped localizer, so it is inert in production (ADR-027 §8). - Depends on:
PseudoLocalizer(the transform, Level 0),SupportedCultures(itsIsPseudoLocalefromMMCA.Common.Shared.Globalization), andIStringLocalizer/LocalizedString/CultureInfo(BCL and NuGet). Constructed with aninnerIStringLocalizervia a primary constructor (line 13). - Concept introduced, the decorator that gates on culture.
[Rubric §2, Design Patterns](assesses idiomatic use of patterns; this is a textbook Decorator, same interface in and out, wrapping behavior around a delegate) and[Rubric §27, Internationalization]. The key design move is that pseudo-localization is a cross-cutting transform applied to the localizer, not to any call site: because it implementsIStringLocalizerand forwards toinner, it can be slid underneath everyIStringLocalizer<T>in the app at once by decorating the factory (PseudoStringLocalizerFactory), with zero changes to consumers. - Walkthrough:
IsPseudoActive(lines 16-17), a private static bool that returnsSupportedCultures.IsPseudoLocale(CultureInfo.CurrentUICulture.Name), the single gate every member checks.this[string name](lines 20-29): resolvesinner[name](line 24), then, if pseudo is active, returns a newLocalizedStringwhose value isPseudoLocalizer.Transform(localized.Value)while preservingResourceNotFound/SearchedLocation(line 26); otherwise returns the inner value untouched (line 27).this[string name, params object[] arguments](lines 32-48): when pseudo is inactive, delegates straight toinner[name, arguments](lines 36-39); when active it does the two-step that makes placeholders survive, transform the raw template first (lines 43-44), thenstring.Formatthe accented template with the arguments (line 45), so the substituted values are never accented or padded.GetAllStrings(bool includeParentCultures)(lines 51-57): maps the transform over every string when active (line 55), passes them through otherwise (line 56).
- Why it's built this way: gating inside the decorator (rather than conditionally registering it) keeps DI wiring unconditional and simple, the decorator is always present and simply does nothing outside the pseudo locale, which per the doc comment (lines 10-11) is never an activatable request culture in production. Splitting the pure transform (
PseudoLocalizer) from the culture-aware decorator keeps each single-responsibility and independently testable ([Rubric §1, SOLID]). - Where it's used: produced by
PseudoStringLocalizerFactoryaround every localizer the inner factory creates, so it transparently wrapsIStringLocalizer<SharedResource>,IStringLocalizer<MudTranslations>, and every other localizer in the host.
ResxMudLocalizer
MMCA.Common.UI ·
MMCA.Common.UI.Globalization·MMCA.Common/Source/Presentation/MMCA.Common.UI/Globalization/ResxMudLocalizer.cs:18· Level 1 · class (sealed, internal)
- What it is: MudBlazor's
MudLocalizerimplementation that resolves the library's built-in component text from theMudTranslationsresource pair, so MudBlazor chrome (pager, filter menus, pickers, close buttons) follows the active UI culture (ADR-027). - Depends on:
MudBlazor.MudLocalizer(the abstract base, NuGet),IStringLocalizer<MudTranslations>(injected via primary constructor, line 17), andMudTranslations(Level 0). Nothing else first-party. - Concept introduced, adapting a third-party localization hook.
[Rubric §2, Design Patterns](this is an Adapter, bridging MudBlazor'sMudLocalizercontract to the ASP.NET CoreIStringLocalizerworld) and[Rubric §27, Internationalization]. MudBlazor exposes exactly one extension point for translating its built-in strings: subclassMudLocalizerand override its indexer. This adapter routes that indexer straight toIStringLocalizer<MudTranslations>. MudBlazor's ownDefaultLocalizationInterceptorconsults this localizer only for non-English cultures and falls back to its built-in English whenever the returnedLocalizedString.ResourceNotFoundis true (per the doc comment,ResxMudLocalizer.cs:9-12), so any untranslated key degrades gracefully. - Walkthrough: a one-member class.
internal sealed class ResxMudLocalizer(IStringLocalizer<MudTranslations> localizer) : MudLocalizer(line 17) with a singlepublic override LocalizedString this[string key] => localizer[key];(line 19). The doc comment (lines 13-15) also notes that because resolution flows through the DIIStringLocalizerFactory, thePseudoStringLocalizerFactorydecorator applies here too, so under the development-onlyqps-Plocculture MudBlazor's chrome pseudo-localizes alongside the application text. - Why it's built this way:
internalbecause it is pure host wiring no consumer needs to name; delegating to the injectedIStringLocalizer<MudTranslations>reuses the exact same.resx/factory pipeline as app strings (one localization mechanism, not two), which is what lets pseudo-loc reach MudBlazor for free. - Where it's used: registered as MudBlazor's
MudLocalizerinAddUISharedviaservices.TryAddTransient<MudBlazor.MudLocalizer, ResxMudLocalizer>()(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:130).TryAddis authoritative becauseAddMudServicesdoes not register aMudLocalizerof its own (guarded by a DI-resolution test, per the comment atDependencyInjection.cs:126-129), regardless of host registration order. Covered byResxMudLocalizerTests.
PseudoStringLocalizerFactory
MMCA.Common.UI ·
MMCA.Common.UI.Globalization·MMCA.Common/Source/Presentation/MMCA.Common.UI/Globalization/PseudoStringLocalizerFactory.cs:11· Level 2 · class (sealed)
- What it is: an
IStringLocalizerFactorydecorator that wraps every localizer the inner factory produces in aPseudoStringLocalizer, so decorating this one factory pseudo-localizes everyIStringLocalizer<T>andIStringLocalizerin the host at once (ADR-027 §8). - Depends on:
PseudoStringLocalizer(Level 1) andIStringLocalizerFactory/IStringLocalizer(Microsoft.Extensions.Localization, NuGet). Constructed with theinnerfactory via a primary constructor (line 11). - Concept introduced, decorate the factory to reach every product.
[Rubric §2, Design Patterns](Decorator applied at the factory level) and[Rubric §6, CQRS & Event-Driven Design](assesses whether cross-cutting behavior is injected in one place rather than scattered). BecauseStringLocalizer<T>resolves its backing localizer through theIStringLocalizerFactory, wrapping the factory means every localizer the DI container ever hands out is already pseudo-aware: no per-type registration, no consumer change. This is the same "decorate the boundary, not the callers" idea the CQRS pipeline uses (see primer §2), applied to localization. - Walkthrough: two forwarding overrides, each wrapping the inner factory's product:
Create(Type resourceSource)(lines 14-15):new PseudoStringLocalizer(inner.Create(resourceSource)), the path used byIStringLocalizer<T>.Create(string baseName, string location)(lines 18-19):new PseudoStringLocalizer(inner.Create(baseName, location)), the path used by name-based localizers.
- Why it's built this way: registering the wrapper on the factory is the minimal, DI-idiomatic way to make pseudo-loc universal; combined with the culture gate inside
PseudoStringLocalizer, it can be registered unconditionally because it is inert under every non-pseudo culture, so production wiring is not conditional on environment (the registration comment,DependencyInjection.cs:119-123, says exactly that: the pseudo locale is only ever activatable in Development). - Where it's used: registered via
services.DecorateWith<IStringLocalizerFactory, PseudoStringLocalizerFactory>()(the framework's own linked decoration helper,MMCA.Common/Source/Build/DependencyInjection/ServiceCollectionDecoration.cs:166) inAddUIShared(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:124), afterservices.AddLocalization()(line 117). Its reach includes MudBlazor chrome throughResxMudLocalizer, which resolves itsIStringLocalizer<MudTranslations>through this same factory.
NavUnit
MMCA.Common.UI ·
MMCA.Common.UI.Layout·MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor.cs:133· Level 2 · record (private, sealed, nested positional record)
- What it is: the render model for one block of a sidebar section in
NavMenu: either a named group of nav items or the section's ungrouped items, carrying everything the markup needs to draw it. - Depends on:
NavItem(itsItemslist) andSystem.Typefor the resource that localizes the heading. It is built from aNavGroupdescription when one is registered. - Concept introduced: none of its own; it is the arranged output of the grouping and ordering rules taught in
NavMenu. - Walkthrough: six positional members (line 135):
Key(the group key, or null for the ungrouped block),TitleResource(the resource type the heading key resolves against, taken from the group's first registered item),IconandExpanded(from the describedNavGroup, defaulting to the folder icon and collapsed),Order(the unit's sort key, 0 when undescribed) andItems(the group's items already sorted byNavItem.Order). All six are filled inNavMenu.Arrange(NavMenu.razor.cs:51-66). - Why it's built this way: precomputing icon, expansion and item order into an immutable record at rebuild time keeps the markup a plain loop with no lookups, and
private sealedkeeps it an implementation detail of the menu. - Where it's used: only inside
NavMenu:DisplayGroup(NavMenu.razor.cs:37-46) localizes its heading, and theSectionUnitsrender fragment (MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor:131-152) draws aMudNavGroupfor a unit with a key and flatMudNavLinks for the unit without one.
NotificationUIModule
MMCA.Common.UI ·
MMCA.Common.UI.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationUIModule.cs:15· Level 7 · class (sealed)
- What it is: the notification feature's IUIModule descriptor. It declares the two nav entries (user inbox, admin push notifications), the app-bar component, the layout component, and the assembly to scan for routable pages.
- Depends on: first-party: IUIModule (the contract, line 15), NavItem and NavSection (the nav item shape and its placement enum), NotificationRoutePaths (the two routes), SharedResource (the resx type each nav label resolves against), NotificationPermissions (the
Managegate), plus the NotificationBell andNotificationListenercomponents in the same package (lines 23, 25). Externals:MudBlazor(Icons.Material.Filled.*),System.Reflection(Assembly). - Concept introduced, the UI module pattern (the client-side counterpart to IModule).
[Rubric §25, Navigation, Routing & Information Architecture]assesses how navigation is composed and how routes are discovered. Server modules declare their registrations and dependencies throughIModule; UI features do the same for the shell. Nothing here calls into a layout: the module declares nav items and component types as data, and the host discovers every registered IUIModule and assembles the menu, app bar, and layout from those declarations. Adding a feature therefore never edits a sharedMainLayout.razoror a central menu file.[Rubric §18, UI Architecture & Component Design]applies to the two component collections:AppBarComponentTypesandLayoutComponentTypesareTypehandles, so the shell renders them dynamically without a compile-time reference to the feature.[Rubric §11, Security]applies to the permission gate: the admin entry carriesRequiredPermission: NotificationPermissions.Manage(line 20) on the nav item itself, so the authorization fact lives next to the thing it protects rather than in a layoutif.[Rubric §27, Internationalization & Localization]: the nav labels are resource keys plus a resource type,"Nav.NotificationInbox"and"Nav.PushNotifications"withtypeof(SharedResource)(lines 19-20), not literal English. A descriptor is a singleton built once at startup, so it cannot hold a localized string; carrying the key and the resx anchor instead is what lets the shell resolve the label per circuit under the active culture.
- Walkthrough
NavItems(lines 17-21) is an immutableIReadOnlyList<NavItem>with two entries: the inbox keyNav.NotificationInboxtoNotificationRoutePaths.NotificationInboxwith theInboxicon inNavSection.User(line 19, no role, so any authenticated user sees it), andNav.PushNotificationstoNotificationRoutePaths.Notificationswith theNotificationsActiveicon, gated onNotificationPermissions.Manage, inNavSection.Adminand grouped under the resource key"Nav.Group.Notifications"(line 20), so the group heading is localized like the labels.AppBarComponentTypes(line 23) is[typeof(NotificationBell)], the badge the shell injects into the top bar.LayoutComponentTypes(line 25) is[typeof(NotificationListener)], mounted once per layout so the SignalR callback wiring has exactly one owner.Assembly(line 27) returnstypeof(NotificationUIModule).Assembly, which the host adds to the Blazor router's additional assemblies so the pages in this package become routable in the consumer app.
- Why it's built this way: expressing contributions as data (collections of records and
Types) keeps the shell open for extension and closed for modification, and it is what allows a package to ship a complete feature (routes, nav, app-bar widget, background listener) that a host enables with one DI call. The class issealedand every member is a get-only auto-property initialized inline, so the descriptor is safely shared as a singleton. - Where it's used: registered as a singleton IUIModule by
AddNotificationUI()in the notifications DependencyInjection (Notifications/DependencyInjection.cs:39); enumerated by the host shell at startup to build navigation and to discover this package's routable components.
NotificationPageGate
MMCA.Common.UI ·
MMCA.Common.UI.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationPageGate.cs:11· Level 8 · class (internal, static)
- What it is: the two-method predicate (
HidesandHidesNotificationPages) the framework router consults to decide whether a matched notification page should be answered with the not-found page instead, because the host never registered the notification UI (noAddNotificationUI(), so no NotificationUIModule) and those pages need services such a host does not have (class doc, lines 6-10). - Depends on: first-party: IUIModule (the registered modules it scans), NotificationUIModule (the module whose presence means "registered"), and the three routable pages it guards, NotificationList, NotificationInbox and NotificationSend. Externals: BCL
System.Typeand LINQ (Contains,Any). - Concept introduced, a feature's routes follow its registration.
[Rubric §25, Navigation, Routing & Information Architecture]assesses whether what is reachable by URL matches what the host actually composed. The notification pages ship in theMMCA.Common.UIassembly itself, so they are routable in every host whether or not it calledAddNotificationUI(); a host that never registered the feature would serve pages whose services it never registered, which fail at render. The UI module pattern (ADR-067) already makes the NotificationUIModule singleton the evidence of registration, so the gate reads that rather than probing for individual services.- Unconditional, not configured. There is no setting to turn the gate on or off: whether the pages are hidden depends only on the registered modules. A host that registers the notification UI is unaffected; a host that does not gets the not-found answer for those pages.
- Walkthrough
NotificationPages(line 14) is a private staticType[]oftypeof(NotificationList),typeof(NotificationInbox)andtypeof(NotificationSend), the routable pages that need the servicesAddNotificationUI()registers.Hides(Type pageType, IEnumerable<IUIModule> modules)(lines 20-21) isNotificationPages.Contains(pageType) && HidesNotificationPages(modules): the matched page must be one of the three before the host-level question is asked.HidesNotificationPages(IEnumerable<IUIModule> modules)(lines 26-27) is the page-independent half:!modules.Any(m => m is NotificationUIModule). It ispublicso NotificationPageAuthorizationHandler can ask the same question without a page type.
- Why it's built this way: keeping the decision in a small
internal staticpredicate, with the page type and module list passed in, keepsRoutes.razorto a one-line branch and lets a unit test cover every combination without rendering a router. Answering with the framework's own not-found page inside the main layout gives the user the same experience as any unknown URL instead of a render failure. - Where it's used: called once per route match from the
<Found>branch of the framework router,NotificationPageGate.Hides(routeData.PageType, UIModules) || TwoFactorPageGate.Hides(routeData.PageType, UIModules)(MMCA.Common/Source/Presentation/MMCA.Common.UI/Routes.razor:15), which rendersPages.NotFoundinsideMainLayoutwhen either returnstrue(TwoFactorPageGate is the two-factor twin of this gate); also referenced from the doc comments of NotificationPageNotFoundStatus and NotificationPageRequirement; pinned byNotificationPageGateTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Notifications/NotificationPageGateTests.cs, 4 references).
DependencyInjection
MMCA.Common.UI ·
MMCA.Common.UI.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/DependencyInjection.cs:12· Level 8 · class (static)
- What it is: the notification-UI registration entry point, a single
AddNotificationUI()extension onIServiceCollectionthat wires the two typed HTTP services, the shared per-circuit state, the SignalR client, the scope provider, and the IUIModule descriptor. - Depends on: first-party: INotificationScopeProvider + NullNotificationScopeProvider, IPushNotificationUIService + PushNotificationService, INotificationInboxUIService + NotificationInboxService, NotificationState, NotificationHubService, and IUIModule + NotificationUIModule. Externals:
Microsoft.Extensions.DependencyInjection(IServiceCollection,AddScoped,AddSingleton) andMicrosoft.Extensions.DependencyInjection.Extensions(TryAddScoped). - Concept: the C#
extension(IServiceCollection services)registration idiom used package-wide (see primer); the block opens at line 14 and the method inside it is an ordinary extension method in the new form. Note this is one of severalDependencyInjectionclasses in the UI packages: this one is specifically the Notifications registrar, the sibling of theMMCA.Common.UI.Webhost registrar above.[Rubric §33, Developer Experience & Inner Loop]assesses how much a consumer must know to switch a feature on; the answer here is one call.[Rubric §3, Clean Architecture]assesses where composition lives; the feature owns its own DI, so nothing about notifications leaks into a host'sProgram.csbeyond the single line.TryAddversusAddis a deliberate signal. The scope provider is registered withTryAddScoped(line 24) precisely so an app that registers its own INotificationScopeProvider wins regardless of the order the two registration calls run in (the comment on lines 22-23 says so); everything else uses plainAddScoped/AddSingletonbecause this package owns those contracts.
- Walkthrough: inside the extension block (line 14),
AddNotificationUI()(line 20) registers, in order, INotificationScopeProvider to NullNotificationScopeProvider viaTryAddScoped(line 24, the default no-op scope consumed by both HTTP services and read for the caption on NotificationSend), IPushNotificationUIService to PushNotificationService (scoped, line 27), INotificationInboxUIService to NotificationInboxService (scoped, line 30), NotificationState as a concrete scoped type (line 33, one unread-count owner per Blazor circuit), NotificationHubService (scoped SignalR client, line 36), and finally NotificationUIModule as a singleton IUIModule (line 39), because the descriptor is immutable shell metadata rather than per-circuit state. It returnsservicesfor chaining (line 41). - Why it's built this way: the scoped-versus-singleton split is the load-bearing part. HTTP services, state, and the hub connection are per-circuit (a Blazor circuit is a DI scope, and the unread count belongs to one user's session), while the nav and shell descriptor is process-wide and immutable. Bundling all six behind one extension keeps host startup honest and makes the feature's dependency surface reviewable in one screen.
- Where it's used: called from the
Program.csof each consuming host (Blazor Web and MAUI) that opts into the notification UI; it complements the mainMMCA.Common.UIregistration rather than replacing it. - Caveats / not-in-source: this method does not register NotificationBellOptions. The bell injects
IOptions<NotificationBellOptions>(NotificationBell.razor.cs:40) and the options type supplies its own defaults (NotificationBellOptions.cs:23,30), so the unconfigured case works, but where a host binds theNotificationBellconfiguration section is not visible from this file.
NotificationPageAuthorizationHandler
MMCA.Common.UI ·
MMCA.Common.UI.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationPageAuthorizationHandler.cs:13· Level 9 · class (internal, sealed)
- What it is: the
AuthorizationHandler<NotificationPageRequirement>that evaluates both notification policies (mmca:notification-pagesandmmca:notification-manage-pages,NotificationPageRequirement.cs:27,33): it succeeds for an authenticated caller who also holds the requirement's permission when one is named, and for every caller when the host hides the notification pages because it never registered the notification UI. - Depends on: first-party: NotificationPageRequirement (the requirement it handles), NotificationPageGate (
HidesNotificationPages), IUIModule (the registered modules). Externals:Microsoft.AspNetCore.Authorization. - Concept introduced, authorization that steps aside for a 404.
[Rubric §11, Security]assesses that access rules are explicit and centrally evaluated. The handler keeps[Authorize]semantics but lets a hidden page reach the router, so a signed-out visitor to a route the host does not serve gets a not-found answer instead of a sign-in challenge (requirement doc,NotificationPageRequirement.cs, class remarks). Nothing is ever failed explicitly: the handler only callsSucceed, so an unauthenticated caller, or a signed-in caller missing the named permission, on a host that shows the pages falls through to the default denial. - Walkthrough
- Primary constructor (line 13) takes only
IEnumerable<IUIModule> modules. HandleRequirementAsync(lines 17-31) guardscontextandrequirementwithArgumentNullException.ThrowIfNull(lines 21-22), then callscontext.Succeed(requirement)(line 27) whenNotificationPageGate.HidesNotificationPages(modules)is true (line 24) orIsSignedInWithPermissionis true (line 25), and returnsTask.CompletedTask(line 30).IsSignedInWithPermission(lines 35-39): true when any identityIsAuthenticatedand eitherrequirement.Permissionisnullorcontext.User.HasPermissionClaim(requirement.Permission). It is the same check the pages run themselves, so the policy and the in-page gate cannot disagree.
- Primary constructor (line 13) takes only
- Why it's built this way: delegating the "hidden" question to
NotificationPageGate.HidesNotificationPagesmeans the router and the policy cannot disagree about when the pages are hidden. The handler is synchronous work wrapped in a completed task because no I/O is needed. - Where it's used: registered as a transient
IAuthorizationHandlerwithTryAddEnumerableinAddUIShared(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:103-104), alongside the two notification policy registrations at lines 87-92 (the two-factor policy and its handler sit beside them at lines 98-100 and 104-105); also named byNavItemGuardContractTestsBase(MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Navigation/NavItemGuardContractTestsBase.cs, 1 reference).
NavMenu
MMCA.Common.UI ·
MMCA.Common.UI.Layout·MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor.cs:14· Level 8 · class (partial component, implementsIDisposable)
- What it is: the shared sidebar every host renders: the account block (identity, the Sessions link, log out or log in/register), then the General, My Account and Administration sections, built from the nav items of every registered
IUIModule, filtered by the signed-in user and arranged into groups (ADR-067; doc comment,NavMenu.razor.cs:9-13). - Depends on: injected in the markup (
MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor:8-13):IEnumerable<IUIModule>,AuthenticationStateProvider,SignOutNavigator,IOptions<LayoutSettings>,IStringLocalizer<SharedResource>andIStringLocalizerFactory. Works overNavItem,NavGroup,NavSectionand its own nestedNavUnit, and usesHasPermissionClaimfromClaimsPrincipalExtensions. MudBlazor suppliesMudNavMenu,MudNavGroup,MudNavLinkand the icons. - Concept introduced, a shell menu composed from module contributions.
[Rubric §25, Navigation & IA](assesses whether navigation is coherent, role-appropriate and discoverable) and[Rubric §18, UI Architecture](assesses whether features plug into the shell without the shell knowing them). No module edits the menu: each contributesNavItems,NavGroupsand app-bar component types throughIUIModule, and the menu flattens, filters and arranges them per request.[Rubric §27, Internationalization]applies too: item titles and group keys are resource keys resolved at render time (ADR-027, comment atNavMenu.razor.cs:26-28), and[Rubric §11, Security]through the role, claim and permission filter (ADR-020). The filter hides entries only; it is not the authorization of the pages themselves. - Walkthrough:
- Fields (lines 16-24): the current
_user, the authenticated and public app-bar component type lists,_groupDescriptionskeyed by group key, the three arranged section lists (_generalUnits,_userUnits,_adminUnits),_showSessionsLinkand the_subscribedflag. Display(NavItem)(lines 29-33) creates a localizer for the item'sTitleResourcethrough the factory and returns the rawTitlewhen the key is not found.DisplayGroup(NavUnit)(lines 37-46) does the same for a group heading against the resource of the group's first registered item (comment at 35-36), returning an empty string for the ungrouped unit.Arrange(IEnumerable<NavItem>)(lines 51-66) groups items byGroupin first-appearance order, builds aNavUnitper group with the described icon (defaultIcons.Material.Filled.Folder, line 60), expansion (default collapsed, line 61) and order (default 0, line 62), sorts items inside the unit byNavItem.Order(line 63) and the units by their order (line 65). Both sorts are stable, so a host that describes no group and orders no item keeps the former arrangement (comment at 48-50).OnInitializedAsync(lines 72-90) collects the app-bar component types from every module (74-75), registers group descriptions with first-registration-wins viaTryAdd(78-81), builds the sections from the current auth state (83), then subscribes toAuthenticationStateChanged(88-89). The comment at 85-87 gives the reason: a failed silent refresh signs the user out in-circuit without a reload, and the admin and user sections must not stay visible to a signed-out visitor.OnAuthenticationStateChanged(lines 94-95) discards the task ofRefreshFromAuthStateAsync(lines 97-111), which rebuilds and re-renders insideInvokeAsyncand swallows theObjectDisposedExceptionraised when the renderer is torn down between the event and the dispatch (107). The comment at 92-93 explains the discard as avoiding anasync voidhandler (VSTHRD100).RebuildFromAuthStateAsync(lines 113-131) stores the user, shows the Sessions link whenLayoutSettings.SessionsNavRequiredRoleis blank or the user is in that role (118-119), keeps each item whoseRequiredRole,RequiredClaimandRequiredPermissionare each either unset or satisfied (121-126), and arranges the survivors perNavSection(128-130).HandleLogoutAsync(line 70) delegates toSignOutNavigator.SignOutAsync("/login")(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/SignOutNavigator.cs:47), which runsIAuthUIService.LogoutAsyncand then issues the one forced navigation to/login. The comment at 68-69 gives the reason: a plain sign-out on a protected page was raced byRedirectToLogin's own navigation, and while the navigator's sign-out is in flightRedirectToLoginstands down (SignOutNavigator.cs:16-21). The log-out link binds it atNavMenu.razor:93.Dispose(bool)(lines 137-146) unsubscribes once, guarded by_subscribed;Dispose()(lines 149-153) calls it and suppresses finalization.- In the markup, the My Account and Administration sections render only for an authenticated user with at least one surviving item (
NavMenu.razor:110-123); the comment at 116-118 notes the authentication check is repeated there becauseNavItem.RequiredRoledefaults to null, so an admin item registered without a role would otherwise disclose its URL to anonymous visitors.
- Fields (lines 16-24): the current
- Why it's built this way: computing the sections from the user in code-behind, and recomputing them on every auth-state change, keeps the menu correct across in-circuit sign-out (ADR-097 covers the refresh sessions behind the Sessions page). Resolving titles at render time rather than at registration lets the menu follow a culture switch. Group descriptions are optional, so a module can contribute items without describing any group and still get a sensible default.
- Where it's used: rendered by the shared layout in every Blazor host; ADC modules contribute to it through their UI modules (
MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/ConferenceUIModule.cs,MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/EngagementUIModule.cs,MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/DeviceUIModule.cs). Covered byNavMenuTestsandNavMenuOrderingTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Layout/), the sign-out path byLayoutSignOutTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Navigation/LayoutSignOutTests.cs), and theNavItemGuardContractTestsBasecontract inMMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Navigation/NavItemGuardContractTestsBase.cs. - Caveats / not-in-source: Not determinable from source within this unit's budget: the exact layout file that places
<NavMenu />was not opened, so "the shared layout" is not cited by line.
FeatureFlagAdminResources
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/FeatureFlagAdminResources.cs:13· Level 0 · class (sealed, empty)
- What it is: the empty resx-marker class
public sealed class FeatureFlagAdminResources;, the generic argument of theIStringLocalizer<FeatureFlagAdminResources>thatFeatureFlagAdminfalls back to. - Depends on: nothing; no members.
- Concept reinforced: the app-localizer-first fallback
RoleAdminEditResourcesintroduces.[Rubric §27, Internationalization].FeatureFlagAdmininjects it asL(FeatureFlagAdmin.razor.cs:72) and itsT(key, args)helper (:120-132) consults the app'sLocalizerparameter first. - Walkthrough: no members.
- Why it's built this way: one marker per component, so the flag page's resx and its fallback scope stay independent of the other administration components.
- Where it's used:
FeatureFlagAdmin.razor.cs(3 references) and 2 more, includingMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs.
MachineClientAdminResources
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/MachineClientAdminResources.cs:13· Level 0 · class (sealed, empty)
- What it is: the same empty resx-marker shape, scoped to
MachineClientAdmin. - Depends on: nothing; no members.
- Concept reinforced: the app-localizer-first fallback
RoleAdminEditResourcesintroduces.[Rubric §27, Internationalization]. Injected asLinMachineClientAdmin.razor.cs:52and reached through itsT(key, args)helper (:92-104). - Walkthrough: no members.
- Why it's built this way: one marker per component, same rationale as its siblings.
- Where it's used:
MachineClientAdmin.razor.cs(3 references) andMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/MachineClientAdminTests.cs(3 references).
PermissionGroup
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/RoleAdminEdit.razor.cs:340· Level 0 · record (private, sealed, nested)
- What it is: a private record nested inside
RoleAdminEditthat groups the permissions filed under onearea:capabilityprefix, the shape the edit form renders one checkbox section per. - Depends on: nothing first-party beyond its own owner; an
IReadOnlyList<string>for the member permissions. - Concept: no new pattern; a compact in-memory grouping record with two positional properties.
- Walkthrough:
Area(the text before the first colon, or the localized "General") andPermissions(that area's permissions, ordered). Built byRoleAdminEdit.Group(IEnumerable<string>)(RoleAdminEdit.razor.cs:317-329), which groups the catalog's permissions byRoleAdminEdit.AreaOfand orders both the groups and each group's members withStringComparer.Ordinal, so the checkbox layout is stable across loads. - Why it's built this way:
privateandsealedbecause it exists only to shape one component's markup loop; nothing outsideRoleAdminEditneeds it. - Where it's used: the
_groupsfield ofRoleAdminEdit(RoleAdminEdit.razor.cs:131), populated byGroup(...)and iterated by the permission checkbox markup.
RoleAdminEditResources
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/RoleAdminEditResources.cs:14· Level 0 · class (sealed, empty)
- What it is: an empty marker class,
public sealed class RoleAdminEditResources;, whose only job is to be the generic argument of anIStringLocalizer<RoleAdminEditResources>. - Depends on: nothing; it carries no members.
- Concept introduced, a fallback-resource marker for an app-first localization pattern.
[Rubric §27, Internationalization]assesses whether an app can supply its own wording without forking framework code.RoleAdminEditinjectsIStringLocalizer<RoleAdminEditResources>asL(RoleAdminEdit.razor.cs:160) and its privateT(key, args)helper (:205-217) checks the caller-suppliedLocalizerparameter first, falling through toL(this marker's resx) only when the app's localizer does not carry the key. The marker class itself defines no strings; it exists purely so .NET's resource-file convention (RoleAdminEditResources.resxbeside the class) has something to key against. - Walkthrough: no members.
- Why it's built this way:
sealedbecause nothing subclasses a resource marker; kept as a distinct class per component (paired withRoleAdminListResources,UserAdminListResources) rather than one shared marker, so each component's resx file, and its "app localizer not consulted for this key" fallback, is scoped independently. - Where it's used:
RoleAdminEdit.razor.cs(3 references: the injectedLproperty, theTfallback call, and the DI registration type argument) and 2 more, includingMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs.
RoleAdminListResources
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/RoleAdminListResources.cs:14· Level 0 · class (sealed, empty)
- What it is: the same empty resx-marker shape as
RoleAdminEditResources, scoped toRoleAdminListinstead. - Depends on: nothing; no members.
- Concept reinforced: the app-localizer-first fallback
RoleAdminEditResourcesintroduces.[Rubric §27, Internationalization]. - Walkthrough: no members.
- Why it's built this way: kept distinct from
RoleAdminEditResourcesso the two components' resx files, and their independent "app localizer missing this key" fallbacks, do not share one namespace. - Where it's used:
RoleAdminList.razor.cs(3 references) and 2 more, includingMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs.
SupportAccessLogResources
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/SupportAccessLogResources.cs:14· Level 0 · class (sealed, empty)
- What it is: the same empty resx-marker shape, scoped to
SupportAccessLog. - Depends on: nothing; no members.
- Concept reinforced: the app-localizer-first fallback
RoleAdminEditResourcesintroduces.[Rubric §27, Internationalization]. Injected asLinSupportAccessLog.razor.cs:69; that component'sT(key)(:150-162) takes no format arguments, the one difference from its siblings. - Walkthrough: no members.
- Why it's built this way: one marker per component, same rationale as its siblings.
- Where it's used:
SupportAccessLog.razor.cs(3 references) and 2 more, includingMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs.
UserAdminListResources
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/UserAdminListResources.cs:14· Level 0 · class (sealed, empty)
- What it is: the same empty resx-marker shape, scoped to
UserAdminList<TUser>. - Depends on: nothing; no members.
- Concept reinforced: the app-localizer-first fallback
RoleAdminEditResourcesintroduces.[Rubric §27, Internationalization]. - Walkthrough: no members.
- Why it's built this way: same rationale as its two siblings, one marker per component so each keeps its own resx and fallback scope.
- Where it's used:
UserAdminList.razor.cs(3 references) and 2 more, includingMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs.
FlagRow
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/FeatureFlagAdmin.razor.cs:252· Level 3 · record (private, sealed, nested)
- What it is:
private sealed record FlagRow(string Source, FeatureFlagStatusResponse Flag), nested inFeatureFlagAdmin: one table row, pairing a flag with the API route prefix it was listed from. - Depends on:
FeatureFlagStatusResponse. - Concept: no new pattern; the same private nested-record shape as
PermissionGroup. - Walkthrough:
Sourceis the route prefix the row came from, which is where a later set or clear must be sent;Flagis the server's status for that flag. Rows are built inLoadAsync(FeatureFlagAdmin.razor.cs:156) and replaced with awithexpression after a save (:213) or a clear (:237). - Why it's built this way: carrying
Sourceon the row lets one table span several modules' flag endpoints while every row action still reaches the endpoint that owns the flag. - Where it's used: only inside
FeatureFlagAdmin(_rows,:36;_editing,:37).
FeatureFlagAdmin
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/FeatureFlagAdmin.razor.cs:30· Level 4 · class (partial,ComponentBase, IDisposable)
- What it is: the operator page component for ADR-031 runtime flag overrides: it lists every flag from one or more API sources and lets an operator set or clear an override (mode, percentage, users, groups, and a reason) per flag.
- Depends on:
IFeatureFlagAdminUIService(injected asFlags, line 70),FeatureFlagAdminUIOptions(ConfiguredSources, 74),IStringLocalizer<FeatureFlagAdminResources>(L, 72, seeFeatureFlagAdminResources), the shared contractsFeatureFlagStatusResponse,SetFeatureFlagOverrideRequest,FeatureFlagOverrideMode,FeatureFlagLifetimeandFeatureFlagValueKind,Result, and its nestedFlagRow. Externals: Blazor'sComponentBase,IOptions<T>,IStringLocalizer. - Concept introduced, a multi-source admin table.
[Rubric §18, UI Architecture & Component Design]assesses whether a reusable component adapts to an app's layout without a fork. Flags are declared per module, and an app can expose several flag endpoints, so the component reads a list of route prefixes: theSourcesparameter (56) when supplied, otherwise the sourcesAddFeatureFlagAdministrationUIconfigured (EffectiveSources, 76).LoadAsync(141-171) walks every source in order, appends each source's flags asFlagRows, and keeps only the first failure (firstFailure ??=, 160), so one unreachable source still leaves the other sources' rows on screen beside an inline failure. The source column renders only when there is more than one source (ShowSource, 79). - Concept reinforced: the app-localizer-first
T(key, args)fallbackRoleAdminEditintroduces (120-132 here, same shape).[Rubric §27, Internationalization]. Enum values are localized by key composition:LifetimeText(134,Lifetime.{value}orLifetime.Unknown),ValueText(137),ModeText(139). - Walkthrough:
- State (32-50):
Modes, everyFeatureFlagOverrideModevalue for the mode picker (32), the component-scopedCancellationTokenSource(34),_rows(36),_editing(37, the row whose editor is open), the editor fields_mode/_percentage/_users/_groups/_reason(38-42),_saving(43),_disposed(44),_loadResult/_saveResult(47, 50, the last outcomes rendered inline). - Parameters:
Sources(56),Heading(59, default the localized "Feature flags"),Localizer(65).IsLoading(68) is the protected spinner flag. OnInitializedAsync(91) runsLoadAsynconce;Dispose(bool)(98) cancels and disposes_cts, the same idempotent shape as its siblings.BeginEdit(row)(173): seeds the editor from the stored override (mode defaults toOff, users and groups joined with", ") and always clears_reason(183): the reason belongs to this change, not the previous one.SaveAsync(193-226): builds aSetFeatureFlagOverrideRequest(203) with the comma lists split bySplitList(114, trimmed, empties dropped), callsFlags.SetOverrideAsync(row.Source, row.Flag.Name, request, ...)(210), and on success replaces the row with the server's updated flag (213) and closes the editor; a failure stays in_saveResultinside the editor.ClearAsync(row)(228): callsFlags.ClearOverrideAsync(230); a failure goes to_loadResult, a success replaces the row locally with no override andEffectiveset back toConfigured(237), without a reload.Replace(240): swaps a row by reference index in_rows.
- State (32-50):
- Why it's built this way: the component is a page body, not a page, so the app supplies the route and the authorization attribute; every write carries a reason because overrides are an audited operator action (see ADR-031).
- Where it's used: registered in
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs; MMCA.ADC wires it fromMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/DependencyInjection.cs, and bothMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/FeatureFlags/AdminFeatureFlagsController.csandMMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/AdminFeatureFlagsController.csreference it. Tested byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/FeatureFlagAdminTests.cs; covered by the heading fitness baseMMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Ui/PageHeadingTestsBase.cs. - Caveats / not-in-source: what the two ADC API controllers reference it for (a comment or a route constant) was not read for this section.
MachineClientAdmin
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/MachineClientAdmin.razor.cs:21· Level 4 · class (partial,ComponentBase, IDisposable)
- What it is: the operator component for ADR-140 machine clients (OAuth client credentials): it lists the clients, creates one, and rotates, promotes or revokes a client's secret, showing a freshly issued secret once.
- Depends on:
IMachineClientAdminUIService(Clients, 50),IStringLocalizer<MachineClientAdminResources>(L, 52, seeMachineClientAdminResources), the shared contractsMachineClientResponse,MachineClientSecretResponseandCreateMachineClientRequest, andResult. Externals: Blazor'sComponentBase,IStringLocalizer. - Concept introduced, a 404 read as "feature off".
[Rubric §18, UI Architecture & Component Design]. Every machine-client route answers 404 whileMachineClients:Enabledis false on the server, soNotEnabled(61) is true when nothing is loaded and the load failed as not found; the component then renders a notice in place of the form and the list instead of an error. - Concept introduced (2), a show-once secret.
[Rubric §11, Security]assesses how credentials are handled. A create (CreateAsync, 137) or rotate (RotateAsync, 164) returns aMachineClientSecretResponse; the component keeps it in_issued(26) only untilDismissSecret(196) clears it, and adds or replaces the client row fromissued.Client(148, 170). - Concept reinforced: the app-localizer-first
T(key, args)fallback (92-104), as introduced inRoleAdminEdit.[Rubric §27, Internationalization]. - Walkthrough:
- State (23-36):
_cts(23),_clients(25),_issued(26), the form fields_name/_role(27-28),_saving(29),_disposed(30),_loadResult(33, the last load's or row action's outcome),_saveResult(36, the last create's outcome). - Parameters:
Heading(39, default the localized "Machine clients"),Localizer(45). StatusText(client)(106-111):Status.RevokedwhenRevokedOnis set,Status.RotationPendingwhile a secondary secret exists, otherwiseStatus.Active.LoadAsync(113): oneClients.GetAllAsynccall, unwrapped withTryGetValue.CreateAsync(137): postsCreateMachineClientRequest(_name, _role)(143); on success records the secret, appends the client, and clears the form.PromoteAsync(178) andRevokeAsync(181) shareApplyRowResult(184): replace the row on success, put the failure in_loadResultotherwise.Replace(198) matches byClientId.Dispose(bool)(75): the idempotent cancel-and-dispose shape.
- State (23-36):
- Why it's built this way: rows are updated from each server answer rather than reloaded, and the 404-as-disabled reading keeps one component usable in hosts where the feature is off. See ADR-140.
- Where it's used: registered in
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs; wired by MMCA.ADC inMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs. Tested byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/MachineClientAdminTests.csandMMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/Pages/Users/MachineClientsPageTests.cs; covered byMMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Ui/PageHeadingTestsBase.cs.
RoleAdminEdit
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/RoleAdminEdit.razor.cs:36· Level 4 · class (partial,ComponentBase, IDisposable)
- What it is: the UI half of ADR-116 role administration: an editable, grouped checkbox matrix of every permission the catalog knows about for one
Role, with code-compiled permissions shown locked and only the operator's extra grants persisted. - Depends on:
IRoleAdminUIService(injected asRoles, line 80),IToastService(Toast, 82),IStringLocalizer<RoleAdminEditResources>(L, 84, seeRoleAdminEditResources),LatestLoadGuard(MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/LatestLoadGuard.cs:38, held as_load, line 42), its own nestedPermissionGrouprecord, andAdministrationPermissions.ManageRoles(MMCA.Common.Shared.Auth.Administration). Externals:Microsoft.Extensions.Localization.IStringLocalizer, Blazor'sComponentBase. - Concept introduced, a compiled/stored permission split rendered as locked vs. editable checkboxes.
[Rubric §11, Security]assesses whether a role's code-granted authority stays visible and non-revocable from the UI;[Rubric §18, UI Architecture & Component Design]assesses whether that split is legible to the operator._compiled(line 47) is the set of permissions the role's code already grants (the registry, unconditionally locked);_stored(48) is the operator-editable overlay persisted to thePermissionGranttable. A permission is ticked when either set contains it (IsChecked, line 253) but is read-only, and therefore excluded from a save, when it is compiled OR isAdministrationPermissions.ManageRolesitself (IsReadOnly, 258-260): the second clause is a deliberate lockout guard, an operator can never uncheck the one permission that lets a role reach this very page. - Concept introduced (2), an app-localizer-first fallback with per-call override args.
[Rubric §27, Internationalization]. The privateT(key, args)helper (141-153) checks the caller-suppliedLocalizerparameter first via its indexer (overridden.ResourceNotFound), falling back toL(anIStringLocalizer<RoleAdminEditResources>) only when the app's localizer does not carry the key; the same shape repeats verbatim inRoleAdminListandUserAdminList<TUser>. - Walkthrough:
- State (39-59):
GeneralAreaKeyconst"Group.General"(39, the resource key for an ungrouped permission), a component-scopedCancellationTokenSource(41), theLatestLoadGuard_load(42, supersedes an in-flight load),_compiled/_storedasHashSet<string>(StringComparer.Ordinal)(47-48,IDE0028suppressed because a collection expression cannot carry the comparer),_groups(51, the display-readyPermissionGrouplist),_loadResult/_saveResult(52-53, the last load/save outcome for inline rendering),_loadedRole(54, guards a redundant reload),_isDirty(58, whether_storedhas diverged from what was last loaded or saved, the whole unsaved state a navigation guard protects),_disposed(59). - Parameters:
Role(62-64,[EditorRequired]),ListHref(67-69,[EditorRequired], the route back to the roster),Heading(72, optional override of the default "Permissions for {role}" title),Localizer(78). OnParametersSetAsync(108): reloads only whenRoleactually changed (string.Equals(_loadedRole, Role, Ordinal)), so a parent re-render does not throw away an operator's half-made edits. ARolechange also supersedes the load still in flight (the doc comment at 103-105), so a late answer for the previous role can never become what Save posts for the current one.Dispose(bool)(116-): cancels and disposes_ctsand also disposes_load(127).LoadAsync(160-217): opens a generation with_load.Begin()(162), capturing(token, generation), and snapshotsRoleintorequestedRole(163). It loads the role with that token, then the catalog; after eachawaitit returns silently unless_load.IsCurrent(generation)still holds (174, 187), so a superseded load never touches the form. Each result is unwrapped withTryGetValue(role.TryGetValue(out var loadedRole), 179;catalog.TryGetValue(out var permissionCatalog), 192), so no null-forgiving.Value!read remains; either failure sets_loadResultand callsReset()(219) and returns early. It clears_isDirty(169) up front, since a fresh load has nothing unsaved yet. On success it repopulates_compiledfromloadedRole.RegisteredPermissions(200) and_storedfromloadedRole.StoredPermissions(202), then builds_groupsfrompermissionCatalog.PermissionsviaGroup(...)(204). AnOperationCanceledExceptionis swallowed only when the load is no longer current (206), andfinallyclearsIsLoadingonly for the current generation (212), so the newer load owns the spinner.Group(permissions)(233): groups byAreaOf(243, the text before the first:or the localizedGeneralAreaKey), orders groups and, within each, members, both withStringComparer.Ordinal, so the rendered layout is deterministic across loads.ReadOnlyHint(permission)(265): the reason text beside a locked checkbox,Hint.Compiledwhen the code grants it,Hint.ManageRolesfor the self-lockout case, empty otherwise.Toggle(permission, granted)(277-289): adds or removes the permission from_storedonly, a compiled permission is never touched because it is not a member of_storedto begin with, and sets_isDirty = true(288) unconditionally, since either direction of a toggle is an edit worth protecting.SaveAsync(291-335): capturessavedRole = Rolebefore the await (303, the save-side twin of the load guard) and posts_stored, ordered, viaRoles.SetStoredPermissionsAsync(savedRole, permissions, _cts.LifetimeToken())(304). AfterwardsformStillShowsSavedRole(305) comparessavedRolewith the currentRole: whenRolechanged while the save was in flight, the form belongs to the newly loaded role, so a failure (detected by!result.TryGetValue(out var saved), 306) no longer sets_saveResult(308-311) and a success no longer re-seeds the form. On success, while the form still shows the saved role, it does not trust what it submitted: it re-seeds_compiledand_storedfrom the server's response,saved.RegisteredPermissionsandsaved.StoredPermissions(323, 325) (the comment at 317-319 records that the two lists the server reports are disjoint, so a permission the host compiles in moves to the locked half even if the operator's own submission still carried it as stored), and it clears_isDirty(326) now that the form matches what the server holds. The toast fires either way (313, 329).- The nested
PermissionGrouprecord (340) closes the file.
- State (39-59):
- Why it's built this way: reseeding from the server's answer rather than the submitted payload is the same "server is the authority, reload rather than assume" principle
Sessionsapplies after a revoke; lockingManageRolesunconditionally is a UI-level backstop for a lockout the server-side authorization gate would otherwise only catch after the fact. - Where it's used: wrapped by MMCA.ADC's
RoleEdit.razor.cs(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Roles/RoleEdit.razor.cs), registered inMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs. Tested byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/RoleAdminEditTests.cs(17 tests),MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/RoleAdminEditPageTests.cs(over the shared baseMMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Pages/RoleAdminEditPageTestsBase.cs),MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/Pages/Roles/RoleEditTests.cs, and the shared e2e page objectMMCA.Common/Source/Hosting/MMCA.Common.Testing.E2E/PageObjects/RoleAdminPage.cs; the UI gallery stubs it throughMMCA.Common/Tests/Presentation/MMCA.Common.UI.Gallery/Stubs/StubRoleAdminUIService.cs. See ADR-116.
RoleAdminList
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/RoleAdminList.razor.cs:28· Level 4 · class (partial,ComponentBase, IDisposable)
- What it is: the ADR-116 role roster: every declared role with a link into
RoleAdminEditfor each, loaded whole in one call rather than through a paged grid. - Depends on:
IRoleAdminUIService(Roles, 49),IStringLocalizer<RoleAdminListResources>(L, 51, seeRoleAdminListResources). Externals: sameComponentBase/IStringLocalizershape as its sibling. - Concept reinforced: the app-localizer-first
T(key, args)fallbackRoleAdminEditintroduces (100-112 here, identical shape).[Rubric §27, Internationalization]. - Walkthrough:
- State (30-33):
_cts(30),_rolesasIReadOnlyList<RolePermissionsResponse>(32, defaulting empty),_disposed(33). - Parameters:
Heading(36, optional),EditHref(39-41,[EditorRequired]Func<string, string>that builds the route to one role's editor),Localizer(47). OnInitializedAsync(69) callsLoadRolesAsynconce.LoadRolesAsync(114): callsRoles.GetAllAsync(_cts.LifetimeToken())(121), stores the wholeResultin_loadResult(59, private field) for inline failure rendering, and sets_rolesthroughresult.TryGetValue(out var roles) ? roles : [](123): the unwrapped value on success, empty on failure.- Dispose pattern (
Dispose(bool), 76): the same idempotent cancel-and-dispose shape asRoleAdminEditandSessions.
- State (30-33):
- Why it's built this way: unlike
UserAdminList<TUser>, which pages throughMudDataGrid's server-data contract, this component loads the entire roster in oneGetAllAsynccall: the declared-role set is small and bounded by the app's own role list, so a paging protocol would add ceremony without solving a real scale problem. - Where it's used: wrapped by MMCA.ADC's
RoleList.razor.cs(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Roles/RoleList.razor.cs), registered inMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs. Tested byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/RoleAdminListTests.cs(7 tests),MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/RoleAdminListPageTests.cs(over the shared baseMMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Pages/RoleAdminListPageTestsBase.cs),MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/Pages/Roles/RoleListTests.cs, and the shared e2e page objectMMCA.Common/Source/Hosting/MMCA.Common.Testing.E2E/PageObjects/RoleAdminPage.cs; the UI gallery stubs it throughMMCA.Common/Tests/Presentation/MMCA.Common.UI.Gallery/Stubs/StubRoleAdminUIService.cs. See ADR-116.
SupportAccessLog
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/SupportAccessLog.razor.cs:33· Level 4 · class (partial,ComponentBase, IDisposable)
- What it is: the read-only audit view for ADR-137 view-as support access: a filtered, paged list of every view-as grant (who viewed whom, when, and the grant's status).
- Depends on:
IViewAsGrantsUIService(Grants, 67),ViewerTimeZone(ViewerTime, 71),IStringLocalizer<SupportAccessLogResources>(L, 69, seeSupportAccessLogResources), the shared contractsViewAsGrantListRequest,ViewAsGrantSummaryResponseandViewAsGrantStatus, andResult. Externals: Blazor'sComponentBase, MudBlazor'sColor. - Concept introduced, date filters on the viewer's clock.
[Rubric §27, Internationalization]assesses locale and time-zone correctness. The From and To pickers mean local days, soStartOfViewerDayUtc(date, addDays)(133-142) converts a local midnight to UTC throughViewerTime.Zone.GetUtcOffset(141). To is sent as the start of the NEXT local day (addDays: 1, 178), an exclusive bound that is not always 24 hours later across a daylight-saving change. Until the browser reports its zone,ViewerTimeZone.Zoneis UTC;OnAfterRenderAsync(86) awaitsEnsureResolvedAsync(89) on the first render and re-renders once the zone is known. - Concept reinforced: the app-localizer-first fallback, here as
T(key)with no format arguments (150-162).[Rubric §27, Internationalization]. - Walkthrough:
- State (35-50):
_cts(35),_grants(37),_applied(38, the filter set the current page was loaded with),_currentPage/_totalPages(39-40),_disposed(41), the unapplied filter inputs_staffFilter/_viewedFilter/_fromFilter/_toFilter/_statusFilter(43-47),_loadResult(50). - Parameters:
Heading(53, default the localized "Support access log"),Localizer(59),PageSize(62, defaults toViewAsGrantListRequest.DefaultPageSize; the server clamps it toMaxPageSize). StatusColor(116):LiveisWarning,EndedisSuccess,Expiredand anything elseDefault.StatusText(164),StatusFilterText(166) andDisplay(169,Display.NotOnRecordfor a missing email) localize the cells.ApplyFiltersAsync(171): builds a newViewAsGrantListRequestfrom the inputs (blank text becomes null, text is trimmed), resets to page 1 (181), and loads.ClearFiltersAsync(185) blanks every input and applies.OnPageChangedAsync(199): moves the pager, and puts it back on the previous page (205) when the load fails, so the pager matches the rows still shown.LoadPageAsync(211): sends_applied with { PageNumber, PageSize }(218) throughGrants.GetPageAsync(219), stores the result for inline rendering, and computes_totalPagesfrom the server'sTotalItemCount(227), at least 1.Dispose(bool)(100): the idempotent cancel-and-dispose shape.
- State (35-50):
- Why it's built this way: support access is audited, so the log is a framework component every adopting app gets the same way; the filters are applied only on an explicit action, so paging never mixes two filter sets. See ADR-137.
- Where it's used: registered in
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs, referenced fromMMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IViewAsGrantsUIService.cs, and wired by MMCA.ADC inMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs. Tested byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/SupportAccessLogTests.cs; covered byMMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Ui/PageHeadingTestsBase.cs.
UserAdminList<TUser>
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/UserAdminList.razor.cs:44· Level 4 · class (partial, generic, constrainedwhere TUser : IUserAdminDTO)
- What it is: a drop-in, generic account roster component covering the ADR-116 user-administration operator actions (lock, unlock, change role, optional delete), built as a component rather than a page so the app supplies the route, the authorization attribute, and the detail link.
- Depends on:
IUserAdminActionsUIService(Actions, 138, the three account actions),IAppDialogService(Dialogs, 140, confirmation dialogs),AuthenticationStateProvider(142, to find the signed-in operator's own id),IStringLocalizer<UserAdminListResources>(L, 144, seeUserAdminListResources),MudDataGrid<TUser>/MobileInfiniteScrollList<TUser>(148-149),DeleteConfirmation(150), andIUserAdminDTOas theTUserbound. Its class declaration (UserAdminList.razor.cs:44-46) shows no base in this partial; the base isDataGridListPageBase<TDto>, declared by@inherits MMCA.Common.UI.Pages.Common.DataGridListPageBase<TUser>in the pairedUserAdminList.razor:4, which is whyTitle,GridRef,OnParametersSet,OnInitializedAsync,SaveFiltersandRestoreFiltersareprotected override. Two base helpers carry the layout plumbing:ReloadActiveLayoutAsync(mobileList)(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DataGridListPageBase.cs:1879) andMobilePageFetcher(...)(DataGridListPageBase.cs:1101). - Concept introduced, one required data source delegate.
[Rubric §18, UI Architecture & Component Design]assesses whether a reusable component adapts to an app's own backend without a fork. The roster reads only throughFetchPage(87-95,[EditorRequired], a delegate in the standard paged entity-service shape: filter bag with operators, page, page size, sort column, sort direction, token). There is no default path and noIUserAdminUIService<TUser>fallback:OnParametersSet(165) throws a directiveInvalidOperationExceptionwhenFetchPageis null, validating at parameter-set time rather than first fetch because the grid's load pipeline would report a throwing fetch as an inline "could not load" state that reads as a transient failure.LoadServerData(248) andMobileFetch(252) both go through that one delegate. The three account actions (lock/unlock/role-change) go throughIUserAdminActionsUIService. - Concept introduced (2), hiding an operator's destructive power over their own row.
[Rubric §11, Security].CanAdminister(user)(219) is false when_currentUserId(set fromAuthenticationStateProviderinOnInitializedAsync, 178-186, read once per load withBL0013suppressed at 182-184 because subscribing would need a dispose hook the base's non-virtualDisposeAsyncdoes not offer) equals the row'sId, and every administration affordance (lock, role, delete) checks it: an operator who locked, demoted or deleted themselves would lose the very capability needed to undo it (self-service deletion stays on the profile page), and the API itself has no notion of "the caller", so the guard is UI-only and deliberately placed here. - Walkthrough:
- Parameters:
Heading(48),DetailHref([EditorRequired], declared just aboveAssignableRoles),AssignableRoles(60, ordered least to most privileged, offered as "Set role to X" menu items, empty offers only lock/unlock),RoleLabel(68, maps a stored role value to a display label; raw value shown when null),Columns/TrailingColumns/CardContent(71-77, extension render fragments),FetchPage(87-95, required),Sortable(103, defaults false; turn it on when the endpoint behindFetchPagehonors the sort column and direction, which the generic paged entity endpoint does),ShowSearch(106, default true),MobileFilters(114, the app's own filter controls for the mobile card list, rendered under the search box on a phone only, since the card list has no column headers),InjectMobileFilters(122, adds the app's mobile filter choices to the filter bag of every mobile fetch, read at fetch time; the desktop grid never runs it),OnDelete(129, null means no Delete affordance at all: account erasure has its own authorization rule the framework does not assume exists),Localizer(136). - State:
_currentUserId(146),_dataGrid/_infiniteList(148-149, the two render-mode grid handles),_deleteConfirm(150),_searchString(151). RoleText(role)(211):RoleLabel?.Invoke(role) ?? role.SaveFilters/RestoreFilters(223-228): persist and restore_searchStringunder the"search"key, the list-page filter-persistence contractDataGridListPageBase<TDto>defines.ReloadAsync(235): the public entry point that reloads the active layout from its first page (mobile card list on a phone, grid otherwise); an app calls it after itsMobileFilterschoice changes. It goes through the privateReloadActiveLayoutAsync()(237), which hands_infiniteListto the base'sReloadActiveLayoutAsync(mobileList); on a phone the base saves the filter state before resetting the card list (DataGridListPageBase.cs:1879-1883).LoadServerData(248):LoadServerDataAsync(state, FetchPage, InjectSearchFilter), nothing else.MobileFetch(252-260): the card list's fetch delegate, built by the base'sMobilePageFetcher(FetchPage, filters => { InjectSearchFilter; InjectMobileFilters }, "Email"), so a phone page applies the search box then the app's mobile filters and sorts by"Email"ascending (the helper's default direction,DataGridListPageBase.cs:1106).InjectSearchFilter(269): adds the free-text box to the filter bag as a"contains"filter on the plainEmailkey the generic paged endpoint resolves, only when non-blank. When the grid already filters Email, the base's additional-filter step keeps the column's filter on that key and moves this one to the aliased search key, so the server ANDs both.ToggleLockAsync(278-306): confirms viaIAppDialogService, marking the dialogdestructive: locking(287) so a lock reads as destructive and an unlock does not, then callsActions.LockAsync/UnlockAsyncwithuser.Id, toasts, and reloads the active layout on success.ChangeRoleAsync(308-332): confirms, callsActions.SetRoleAsync(user.Id, role), toasts, and reloads.DeleteUserAsync(335): routes throughListPageActions.DeleteWithConfirmationAsync, the shared delete-confirm-toast-reload sequence, callingOnDelete!(user)(the null-forgiving operator is safe here because the Delete button only renders whenOnDeleteis non-null).
- Parameters:
- Why it's built this way: a single required
FetchPagereplaces the earlier injected-service-or-delegate fork, so there is one fetch path to reason about and a list rendered without a source fails loudly instead of showing nothing; the framework's own users endpoint is reached by the app passing its entity service'sGetPagedAsync. - Where it's used: wrapped by MMCA.ADC's
UserList.razor.cs(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserList.razor.cs, 2 references), registered inMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs, and referenced fromRoleAdminEdit.razor.csandRoleAdminList.razor.cs. Tested byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/UserAdminListTests.cs(8 tests) andMMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/Pages/Users/UserListTests.cs, with prerender coverage inMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/UserAdminListPrerenderTests.cs; its[EditorRequired]parameters are checked byMMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Ui/EditorRequiredParameterConventionTests.cs.
ConfirmationState
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ConfirmEmail.razor.cs:67· Level 0 · enum (private, nested)
- What it is: the four states
ConfirmEmailmoves through while redeeming an email-confirmation link:Working,Form,ConfirmedandPasswordProof(ConfirmEmail.razor.cs:67-80). - Depends on: nothing; a private nested enum with no other type references.
- Concept: a private nested enum used purely as component render-state, the same shape used throughout the UI layer to drive conditional markup without a separate view-model class.
- Walkthrough:
Working(:70) is the initial field value (:53) and is set again when a new link opened on the showing page replaces the form's values (RedeemNewLinkAsync,:198); it stays current through the redeem attempt.Form(:73) covers manual entry with any refusal or resend notice above it. It is chosen up front when the address or the token is missing, without posting anything (RedeemOrShowFormAsync,:208), whenConfirmAsyncfinds either blank (:248), after a refused redeem (:276), and after a password-proof post the API refuses with the invalid-token code (:351).Confirmed(:76) marks a successful redeem, from the plain post (:262) or the post that carries a password (:342).PasswordProof(:79): the token is valid but the account holds a password, so the page asks for the current password or a new one before posting the same address and token again.ShowPasswordProofsets it (:303) when the plain redeem answersAuthErrorCodes.EmailConfirmationPasswordRequired(:266-270); a wrong password, a lockout or a refused new password keeps this state with the API's message (:346, summary:312-317).
- Why it's built this way: a private enum keeps the state vocabulary scoped to the one component that interprets it, rather than promoting it to a shared UI-layer type nothing else needs. A missing token, a refused redeem and a completed resend all land the visitor on the same manual-entry form, with only the
_errorMessage/_linkSentfields (not the enum) distinguishing which of those happened.PasswordProofis a state of its own because it renders a different panel (password fields and a toggle between current and new password) and holds a token that is still unspent, unlike every path intoForm. - Where it's used: only inside
ConfirmEmail, which stores it in_stateand switches its markup on the value (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ConfirmEmail.razor:19,:28,:40).
EmailedLinkReader
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth.Links·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Links/EmailedLinkReader.cs:11· Level 0 · class (internal, static)
- What it is: a pure helper that reads the address and single-use token an emailed link carries, as
emailandtokenpairs in the URL fragment or, as a fallback, in the query string, for the two pages whose links share that shape:ConfirmEmailandResetPassword(doc comment,EmailedLinkReader.cs:5-10). It holds no page state. - Depends on:
NavigationManagerand itsGetUriWithQueryParametersextension (Microsoft.AspNetCore.Components); BCLUri,StringComparer,StringComparison,Dictionary<TKey,TValue>. No first-party type. - Concept introduced, one parser for every emailed credential link, with an explicit merge mode.
[Rubric §26, Front-End Security]assesses whether the front end keeps secrets out of logs and the address bar. Two pages read the sameemail/tokenlink and both must answer the same two questions: which value wins when the page already holds one, and how a live token leaves the URL. Putting the parser in oneinternal staticclass makes both pages answer them identically. Thereplaceflag (doc,:16-21) names the two situations:falseon the first render, where only empty values are filled so the query string and the first pair win;truefor a new link opened on a page that is already showing, where nothing the form held survives a fragment that carries either pair, so an old token is never submitted under a new address. - Walkthrough:
MergeLinkFragment(fragment, replace, email, token)(:25-53): treats a null address or token as empty (:27-28) and returns(false, email, token)unchanged for a blank fragment (:29-32). It splits on&(:35), skips any pairTryReadLinkPairrejects (:37-40), and inreplacemode clears both values on the first recognized pair only (:42-46). Every recognized pair then goes throughFillEmpty(:49), so within one fragment the firstemailand the firsttokenwin. It returns whether any pair was recognized plus the merged values (:52).LinkQueryOf(location)(:62-68): the query-string fallback. It returns the query without its leading?only whenMergeLinkFragmentrecognizes anemailortokenpair in it (:64-67), otherwisenull.ScrubLinkQuery(navigation, location)(:77-80): navigates withreplace: trueto the same location with theemailandtokenquery parameters set tonull, removing them from the address bar and the history entry while keeping other parameters and the fragment (doc,:70-76).HasFragment(location)(:85-89): true when a non-empty fragment follows the#.FillEmpty(:97-110): writes the value into the address or the token only when that one is still blank.TryReadLinkPair(:120-139): rejects a pair with no=or an empty name (:125-128), matches the namesemailandtokenexactly with ordinal comparison (:131-135), and returns the value throughUri.UnescapeDataString(:137).
- Why it's built this way: a pure static class is trivially unit-testable and cannot drift between the two pages. Treating the query string as a second input to the same merge means a link that arrives in the older query shape gets the same precedence rules and the same scrub as a fragment link (the doc comments cite the Store review findings D3 and R6b,
:20,:73). - Where it's used:
ConfirmEmail(ConfirmEmail.razor.cs:172,:159,:163,:217) andResetPassword(ResetPassword.razor.cs:54,:60,:92).SignInLinkdoes not use it: it parses its own fragment. - Caveats / not-in-source:
internal, so a consuming app cannot call it; the pages are the only entry points.
LinkState
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth.SignInLinks·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/SignInLinks/SignInLink.razor.cs:65· Level 0 · enum (private, nested)
- What it is: the three states
SignInLinkmoves through on its landing page:Reading,Ready,Failed(SignInLink.razor.cs:65-75). - Depends on: nothing; a private nested enum.
- Concept: the same render-state shape as
ConfirmationState, with one meaningful difference in vocabulary: there is aReadystate between reading the link and acting on it, because this page never redeems on its own (seeSignInLink). - Walkthrough:
Readingis the initial value (:42) while the fragment is read on first render.Readymeans both the address and the token are present and the page is waiting for a tap on Continue (:112).Failedcovers an incomplete link (:105-109) and a refused redemption (:196), and is where the page offers a fresh link. - Why it's built this way: scoping the vocabulary to the one component that interprets it keeps a page-specific state out of the shared UI surface. A refused redemption and an incomplete link share
Failedbecause the way on is the same in both cases: request a new link; the_errorMessagefield carries which one happened. - Where it's used: only inside
SignInLink, which stores it in_stateand switches its markup on the value (SignInLink.razor:19,:28).
PasswordComplexityAttribute
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/PasswordComplexityAttribute.cs:16· Level 1 · class (sealed attribute)
- What it is: a custom
ValidationAttributethat enforces the framework's password-strength rule on any form that sets a new password: at least 8 characters including an uppercase, a lowercase, a digit, and a special (non-alphanumeric) character. - Depends on:
System.ComponentModel.DataAnnotations(ValidationAttribute,ValidationResult,ValidationContext, BCL) and the first-partyPasswordComplexityrule inMMCA.Common.Shared.Auth(MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/PasswordComplexity.cs:18). - Concept introduced, extending DataAnnotations with a domain rule defined once for both sides.
[Rubric §24, Forms, Validation & UX Safety]assesses client-side validation parity with the server. Beyond the built-in[Required]and[EmailAddress], a bespoke rule subclassesValidationAttributeand overridesIsValid, which plugs it straight into the same validator that drives the rest of the form. Parity is structural rather than copied: the attribute does not encode the character rules itself, it callsPasswordComplexity.Evaluate(PasswordComplexity.cs:52), the single Unicode-aware definition the server'sStrongPasswordRulesalso uses (doc comment, lines 6-13;PasswordComplexity.cs:5-17). That definition counts any\p{Lu}as uppercase, any\p{Ll}as lowercase, any\p{Nd}as a digit, and anything that is neither a letter nor a decimal digit as special (PasswordComplexity.cs:27-43), so an accented or CJK letter is a letter, never the special character. What happens to an accepted password server-side (PBKDF2-HMAC-SHA512 hashing with legacy-hash compatibility) is ADR-032; this attribute is only the client-side gate, never the security boundary. - Walkthrough:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)](line 14), so it is applied as[PasswordComplexity]on a single property.- The constructor (lines 17-20) seeds the base
ErrorMessagewith the full English rule, so a usage that does not override the message still shows something actionable. The framework's own forms override it with anErrorMessageResourceType/ErrorMessageResourceNamepair that points atAuthFieldMessages.PasswordComplexity(seeRegisterModel). IsValid(object?, ValidationContext)(lines 22-36): one guard (line 24) returnsValidationResult.Successfor a non-string, a null/empty input, or a password for whichPasswordComplexity.Evaluateis true. Deferring the empty case toRequiredAttributekeeps the field to one message rather than two. On failure it returns aValidationResultscoped to the member name (lines 34-35) so the message attaches to the right input; the member lookup is null-conditional (validationContext?.MemberName, line 34) because the base class routes the context-freeIsValid(object)overload here with no context (comment, lines 29-30), and there is then no member to attach the error to.- The message is built with
FormatErrorMessage(validationContext?.DisplayName ?? string.Empty)(line 35), not the rawErrorMessageproperty (comment, lines 31-33):FormatErrorMessagealso resolves anErrorMessageResourceType/ErrorMessageResourceNamepair, which is how the auth models localize inside the attribute, and it returns a plainErrorMessageor the default message unchanged.
- Why it's built this way: because the rule is an attribute rather than page code, a second form that sets a password gets identical behavior by adding one line, which is exactly how the reset vertical picked it up. Delegating the predicate to a type in the Shared project, the one project both client and server may reference, is what makes the two verdicts identical by construction rather than by review. Delegating emptiness to
[Required]keeps one field from stacking two errors. The length cap is deliberately not part of this attribute:PasswordComplexity.MaximumLengthis a separate rule with its own message on both sides (PasswordComplexity.cs:24,:45-49). - Where it's used: applied to
RegisterModel.Password(RegisterModel,RegisterModel.cs:28) and toResetPasswordModel.NewPassword(ResetPasswordModel,ResetPasswordModel.cs:26); evaluated by theLocalizedDataAnnotationsValidatorinRegister.razor(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Register.razor:33) andResetPassword.razor(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ResetPassword.razor:43). Unit-tested inMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/PasswordComplexityAttributeTests.cs:12; its agreement with the server rule is pinned by the architecture testMMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Ui/PasswordRuleParityTests.cs:21. - Caveats / not-in-source: the doc comment (line 7) still describes the attribute as the rule "for the Register form" although the reset form carries it too; the code is the wider truth.
ForgotPasswordModel
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ForgotPasswordModel.cs:15· Level 2 · class (sealed)
- What it is: the
EditFormbacking model for the Forgot Password page: oneEmailstring carrying DataAnnotations for shape validation. Nothing else is collected, because nothing else is needed to start a reset. - Depends on:
System.ComponentModel.DataAnnotations(BCL):[Required],[EmailAddress], and the first-partyAuthFieldMessagesresource type that supplies both messages. - Concept introduced, validation deliberately capped at "shape" because of an anti-enumeration contract.
[Rubric §24, Forms, Validation & UX Safety]assesses whether a form gives a clear per-field verdict before submit;[Rubric §26, Front-End Security]assesses whether the front end avoids leaking information the back end withholds. Every other form in this group validates as much as it can client-side. This one stops at "is this a syntactically valid address", because the interesting question, does an account exist for it, is one the server refuses to answer: ADR-091 Decision 3 has the reset request succeed on every path (malformed address, no account, throttled, failed send), so a distinguishable client-side outcome would reintroduce exactly the account-enumeration oracle the endpoint exists to avoid. The doc comment (ForgotPasswordModel.cs:7-8) states that trade-off directly. - Walkthrough: one
get; set;property.Email(line 19) carries[Required]and[EmailAddress](lines 17-18), each namingErrorMessageResourceType = typeof(AuthFieldMessages)withErrorMessageResourceName = nameof(AuthFieldMessages.EmailRequired)/nameof(AuthFieldMessages.EmailInvalid), and defaults tostring.Empty. The message is read from the shared resources inside the attribute (AuthFieldMessages,MMCA.Common/Source/Presentation/MMCA.Common.UI/Resources/AuthFieldMessages.cs:19, ADR-027), so the form's validator and MudBlazor's own field-level pass (which runs theForproperty's attributes when a field is touched) both show localized text, never a raw key (AuthFieldMessages.cs:11-17; model doc comment,ForgotPasswordModel.cs:10-12). - Why it's built this way:
sealedand mutable (set, notinit) becauseEditFormtwo-way-binds the input to the model; keeping the model to one field is what makes the page's anti-enumeration behavior easy to reason about, since there is no second field whose validation could betray a lookup. - Where it's used: instantiated as
_modelbyForgotPassword.razor(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ForgotPassword.razor:71) and bound by its<EditForm Model="_model" OnValidSubmit="HandleRequestAsync">plus<LocalizedDataAnnotationsValidator />(lines 38-39), with the field wiredFor="@(() => _model.Email)"(line 41) so the message attaches to that input. On valid submitHandleRequestAsync(lines 80-97) callsIAuthUIService.RequestPasswordResetAsync(_model.Email)(line 86, contract atMMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/IAuthUIService.cs:55) inside atrywhosecatchis empty on purpose (lines 88-91) and whosefinallysets_isSubmitted = trueunconditionally (line 95), so the confirmation renders for every submitted address whether the call succeeded, failed, or threw. - Caveats / not-in-source:
RequestPasswordResetAsyncreturns aResultand the call site never inspects it (line 86); the comment block above the method (lines 75-79) records that this is the anti-enumeration rule rather than a dropped result. The gallery E2E suite pins the behavior by asserting the confirmation appears with no backend at all (MMCA.Common/Tests/Presentation/MMCA.Common.UI.E2E.Tests/Auth/ForgotPasswordPageE2ETests.cs:28), with WCAG 2.1 AA scans on both the form and the confirmation state (:41,:50).
LoginModel
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/LoginModel.cs:15· Level 2 · class (sealed)
- What it is: the
EditFormbacking model for the Login page: two string properties (Email,Password) carrying DataAnnotations for field-level validation, plus an unvalidatedTwoFactorCodefor the second-factor step. - Depends on:
System.ComponentModel.DataAnnotations(BCL):[Required],[EmailAddress]. The only first-party reference isAuthFieldMessages, the resource type its attributes read their messages from. - Concept introduced, the form-backing model plus a localizing DataAnnotations validator.
[Rubric §24, Forms, Validation & UX Safety]assesses whether forms validate at the field level with clear inline messages before submit;[Rubric §26, Front-End Security]assesses that client-side checks are a UX convenience, not the trust boundary;[Rubric §27, Internationalization]assesses whether validation messages translate. A BlazorEditFormbinds to a plain model, a<LocalizedDataAnnotationsValidator />reads the attributes and surfaces a per-field message as the user types, and the submit handler only fires on a valid form. Each message is read from the shared resources throughAuthFieldMessagesinside the attribute (doc comment,LoginModel.cs:10-12, ADR-027), so the model carries no English text and the localized text shows whether the form's validator or MudBlazor's own field-level pass runs the attribute. The doc comment (LoginModel.cs:7-8) is also explicit that the server remains the authority on whether the credentials are actually valid: the form only prevents an obviously malformed request. - Walkthrough: three
get; set;properties.Email(line 19),[Required]plus[EmailAddress](lines 17-18), each withErrorMessageResourceType = typeof(AuthFieldMessages)and the nameEmailRequired/EmailInvalid, defaulting tostring.Empty.Password(line 22),[Required]with the namePasswordRequired(line 21). There is deliberately no complexity rule here: login validates an existing credential, not a new one, and rejecting a legacy password client-side would lock a user out of their own account.TwoFactorCode(line 29), a nullable string for the authenticator or recovery code. It carries no validation attribute (doc comment, lines 24-28): the field is shown only once the API answers that the account needs a second factor, so an attribute would block every first attempt; the page checks it in code while the step is shown (BuildLoginRequest,Login).
- Why it's built this way:
sealedand mutable becauseEditFormtwo-way-binds each input; each attribute names oneAuthFieldMessagesentry so each field shows exactly one verdict, in the reader's language. - Where it's used: instantiated as
_model(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor:295) and bound by<EditForm Model="_model" OnValidSubmit="HandleLoginAsync">plus<LocalizedDataAnnotationsValidator />(Login.razor:42-43), with inputs boundFor="@(() => _model.Email)"andFor="@(() => _model.Password)"at lines 99 and 106 so eachMudTextFieldshows its own message, and the code field bound to_model.TwoFactorCodeat line 115. On valid submit theLogincode-behind builds aLoginRequestfrom it (Login.razor.cs:152,:162) and the page sends it throughIAuthUIService(Login.razor:361). Sibling ofRegisterModel; its shape rules are unit-tested alongside the other auth models inMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/AuthModelValidationTests.cs:11.
RegisterModel
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/RegisterModel.cs:16· Level 2 · class (sealed)
- What it is: the
EditFormbacking model for the Register page: name, email, and password fields with DataAnnotations, plus six optional address fields. - Depends on:
System.ComponentModel.DataAnnotations([Required],[StringLength],[EmailAddress],[Compare]), the sibling first-partyPasswordComplexityAttribute,AuthFieldMessagesfor every message, andPasswordComplexityfor the shared length cap. - Concept reinforced, multi-field form validation with a cross-field compare.
[Rubric §24, Forms, Validation & UX Safety]. This builds on theLoginModelshape with three richer rules:[PasswordComplexity]on the password (paired with a[StringLength(PasswordComplexity.MaximumLength)]cap, 128 atMMCA.Common/Source/Core/MMCA.Common.Shared/Auth/PasswordComplexity.cs:24, the constant the server rule shares),[Compare(nameof(Password))]on the confirmation (a cross-field equality check the validator resolves by property name), and an address block left attribute-free because it is optional. The doc comment (lines 8-13) notes the annotations mirror the server's rules so client and server agree, and that every message is read from the shared resources throughAuthFieldMessagesinside the attribute (ADR-027), so both the form's validator and MudBlazor's field-level pass show localized text. - Walkthrough: every attribute below names
ErrorMessageResourceType = typeof(AuthFieldMessages)plus anErrorMessageResourceName = nameof(AuthFieldMessages.X)entry.FirstName/LastName(lines 19, 22), each[Required]with its own entry,FirstNameRequired/LastNameRequired(lines 18, 21).Email(line 26),[Required]plus[EmailAddress](lines 24-25), entriesEmailRequired/EmailInvalid.Password(line 31),[Required](PasswordRequired) plus[StringLength(PasswordComplexity.MaximumLength)](PasswordMaxLength) plus[PasswordComplexity](PasswordComplexity) (lines 28-30).ConfirmPassword(line 35),[Required](ConfirmPasswordRequired) plus[Compare(nameof(Password))](ConfirmPasswordMismatch) (lines 33-34).AddressLine1plus nullableAddressLine2/City/State/ZipCode/Country(lines 38-43), with no validation attributes; the inline comment (line 37) states that a block left entirely blank means "no address supplied".AcceptedTerms(line 48), the "I agree to the Terms" box. It carries no validation attribute: it is required only when the host configures a Terms URL (LegalSettings.TermsUrl), and the page enforces that by keeping the submit button disabled until it is ticked (comment, lines 45-47).
- Why it's built this way: the address fields stay attribute-free so a user can register without supplying one; the model is a flat view-model that the page projects onto the wire DTO at submit time rather than reusing a domain type directly, which is what lets the optional-address rule live in page code instead of leaking into the contract.
- Where it's used: instantiated as
_modeland bound byRegister.razor(<EditForm Model="_model" OnValidSubmit="HandleRegisterAsync">plus<LocalizedDataAnnotationsValidator />,MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Register.razor:63-64, field at line 195). On valid submit the page projects it into aRegisterRequest(Register.razor:250-251), folding the address fields into anAddressthroughBuildAddressResult()(defined in theRegistercode-behind,Register.razor.cs:88, called atRegister.razor:237), which returnsnullwhen address collection is off (Register.razor.cs:90-93) or all six fields are blank (lines 95-103) and otherwise callsAddress.Create(...)(line 105). Its password block is mirrored byResetPasswordModel; the accepted password is hashed server-side per ADR-032. Shape rules are unit-tested inMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/AuthModelValidationTests.cs:11; rendering and validation behavior are covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/RegisterFormTests.cs:23and the gallery E2E suite (MMCA.Common/Tests/Presentation/MMCA.Common.UI.E2E.Tests/Auth/RegisterPageE2ETests.cs:9).
ResetPasswordModel
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ResetPasswordModel.cs:17· Level 2 · class (sealed)
- What it is: the
EditFormbacking model for the Reset Password page: the address and the emailed reset token that identify the request, plus the new password and its confirmation. - Depends on:
System.ComponentModel.DataAnnotations([Required],[StringLength],[EmailAddress],[Compare]), the sibling first-partyPasswordComplexityAttribute,AuthFieldMessagesfor every message, andPasswordComplexityfor the shared length cap. - Concept reinforced, the same password block as registration, on a credential-carrying form.
[Rubric §24, Forms, Validation & UX Safety]and[Rubric §26, Front-End Security]. The password half is exactly the shapeRegisterModelintroduced, which is the payoff of expressing the complexity rule as an attribute rather than page code. What is new is the top half:EmailandTokenare not values the user chooses, they are the credential the server minted and mailed. The client validates only that both are present and that the address is well formed; every substantive rejection (unknown, expired, mismatched, or attempt-capped token) collapses into one server-side error by design (ADR-091 Decision 3), so the form must not try to pre-judge a token it cannot verify. As on the sibling models, each message is read from the shared resources throughAuthFieldMessagesinside the attribute (doc comment, lines 12-14, ADR-027). - Walkthrough: four
get; set;properties, each defaulting tostring.Empty; every attribute namesErrorMessageResourceType = typeof(AuthFieldMessages)plus anErrorMessageResourceNameentry.Email(line 21),[Required]plus[EmailAddress](lines 19-20), entriesEmailRequired/EmailInvalid.Token(line 24),[Required]with entryTokenRequired(line 23) and nothing more: length, encoding, and freshness are all properties of the server-side cache record.NewPassword(line 29),[Required](PasswordRequired) plus[StringLength(PasswordComplexity.MaximumLength)](PasswordMaxLength) plus[PasswordComplexity](PasswordComplexity) (lines 26-28).ConfirmPassword(line 33),[Required](ConfirmPasswordRequired) plus[Compare(nameof(NewPassword))](ConfirmPasswordMismatch) (lines 31-32), the cross-field check retargeted atNewPassword.
- Why it's built this way: the doc comment (lines 7-10) records the load-bearing choice, that
EmailandTokenarrive prefilled from the reset link but stay editable, so a user who only has the raw token text from the email (the situation on a native head with no working deep link) can paste it by hand. Making those two ordinary bound fields rather than read-only parameters buys that fallback for free. - Where it's used: instantiated as
_modelbyResetPassword.razor(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ResetPassword.razor:105) and bound by its<EditForm Model="_model" OnValidSubmit="HandleResetAsync">plus<LocalizedDataAnnotationsValidator />(lines 42-43). The model is prefilled from two sources, both of which fill a field only when it is still blank so a value the user corrected by hand is not overwritten. First, the page declares[SupplyParameterFromQuery]EmailandTokenproperties (lines 99-103) and copies them inOnParametersSet(lines 112-123, blank checks at 114 and 119). Second,OnAfterRenderAsync(lines 130-177) reads the URL fragment once on first render through thelocationHashTakeJS call (line 143), which also scrubs it from the address bar, and fillsemail/tokenfrom it (lines 161-170); the comment at lines 125-129 explains why: a fragment is never sent to a server, so the live token stays out of ingress logs and request telemetry, while the query-string path keeps older links working.HandleResetAsync(lines 179-204) callsIAuthUIService.ResetPasswordAsync(_model.Email, _model.Token, _model.NewPassword)(line 186, contract atMMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/IAuthUIService.cs:62), flips_isCompletedon success, and on failure rendersresult.LocalizedErrorMessage(L)or the genericAuth.Reset.GenericErrorstring (line 193), which a thrown call also falls back to (lines 196-199). The prefill path is pinned by a gallery E2E test (MMCA.Common/Tests/Presentation/MMCA.Common.UI.E2E.Tests/Auth/ResetPasswordPageE2ETests.cs:31), with a WCAG 2.1 AA scan alongside it (:43). - Caveats / not-in-source: the model has no rule tying
Tokento the address; that pairing is enforced by the server's cache record (ADR-091 Decision 1), not by anything visible here.
ResetPassword
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ResetPassword.razor.cs:12· Level 2 · class (partial, page code-behind)
- What it is: the code-behind half of the shared Reset Password page (
@page "/reset-password",MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ResetPassword.razor:1). The markup half's@codeblock owns the form, the query and first-render prefill and the submit (ResetPassword.razor:101-175); this file owns what happens when a second emailed link is opened in a tab that is already showing the page, plus the fragment read and merge both paths share. - Depends on:
EmailedLinkReader(ResetPassword.razor.cs:54,:60,:92),CapabilitiesJsModule(resolved optionally,:83),ResetPasswordModel(the_modelfield,ResetPassword.razor:108); externals:NavigationManager.LocationChangedandLocationChangedEventArgs(Microsoft.AspNetCore.Components.Routing), BCLIAsyncDisposable,ValueTask. - Concept introduced, a page that is not rebuilt must still notice a new link.
[Rubric §26, Front-End Security]and[Rubric §24, Forms, Validation & UX Safety]. Opening a fresh reset link in a tab already on/reset-password(for example after asking for a new one) changes only the fragment or query string, so Blazor keeps the component and its first-render read never runs again (remarks,ResetPassword.razor.cs:30-35). Without a listener the form would keep the old, spent token. The page therefore subscribes toLocationChangedand treats a navigation that carries link data as a new link whose values replace the stale ones, exactly as a fresh tab would, and scrubs the new single-use token from the address bar as it reads it. - Walkthrough:
OnInitialized()(:36-40): subscribesOnLocationChangedand records_locationHandlerRegistered(field atResetPassword.razor:113).OnLocationChanged(:42-64): ignored once disposed or before the first-render read has run (_fragmentRead,:44-47; set atResetPassword.razor:143). A location with a non-empty fragment (:49-50) is read throughTakeFragmentAsync, which also scrubs it, and handed toPrefillNewLink(:52). Otherwise, whenEmailedLinkReader.LinkQueryOffinds anemailortokenpair in the query (:54), the page callsEmailedLinkReader.ScrubLinkQuery(:60) and prefills from that query (:61). Both run throughInvokeAsync, because the event is raised outside the renderer's context.PrefillNewLink(link)(:68-78): merges withreplace: true(:70) and, only when the link carried a recognized pair, resets_isCompletedand_errorMessageand re-renders (:75-77), so a page that showed "password changed" for the previous link returns to the form.TakeFragmentAsync()(:81-87): resolvesCapabilitiesJsModulefromServicesand callslocationHashTake, returningnullwhen the module is absent.ApplyFragment(fragment, replace)(:90-100): callsEmailedLinkReader.MergeLinkFragmentwith the model's current values (:92) and writes them back only when a pair was recognized (:93-97). The markup's first-render read calls it withreplace: false(ResetPassword.razor:144), so a value the query string already put in the form wins.DisposeAsync()(:16-27): sets_disposedand unsubscribes the handler when it was registered.
- Why it's built this way: the replace rule is the security point: on a new link nothing the form held survives, so an old token is never submitted under a new address. Scrubbing the query-string variant the same way as the fragment keeps the single-use token out of the address bar and history whichever shape the email used. Keeping the parser in
EmailedLinkReaderis what makes this page andConfirmEmailbehave identically. - Where it's used: routed at
/reset-passwordin any host that maps the framework's Auth pages; the model it fills is described underResetPasswordModel. Covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/Recovery/ResetPasswordFragmentTests.csandResetPasswordQueryLinkTests.csin the same folder, and byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/AuthFormValidationMessageTests.cs. The server half is ADR-091. - Caveats / not-in-source: the first-render read and the submit live in the
.razor@codeblock, not in this file;HandleResetAsync(ResetPassword.razor:150-175) is not cancellable, sinceResetPasswordAsyncis called without a token (ResetPassword.razor:157).
Login
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor.cs:19· Level 4 · class (partial, page code-behind)
- What it is: the code-behind half of the shared Login page (
@page "/login",MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor:1). The markup half owns the form, the initialization and the submit handler; this file owns the steps around a sign-in: the second-factor step, the resend prompt for an unconfirmed address, the emailed sign-in link request, the OIDC and "Sign in with your organization" starts, the passkey offer, the address handed over by another auth page, turning refusal codes into words, starting a web-redirect provider sign-in, and the page lifetime that cancels a sign-in still in flight (IDisposable,Login.razor.cs:19). - Depends on:
LoginModel(the_modelfield,Login.razor:295),LoginRequest(Login.razor.cs:152,:162),LoginRefusalsandLoginRefusal(:125-134),AuthEmailPrefill(:182,:211),ISignInLinkUIService(:231),IOidcDiscoveryUIService(:285),OidcProviderOption(:45),IPasskeyCapabilityandIPasskeyUIService(:202-203),SignInSettings(asSignInOptions,Login.razor:23),IExternalAuthBroker(Login.razor:22),OAuthFlowStateStore(Login.razor:15),ReturnUrlProtector(:207),IStringLocalizer<SharedResource>asL(seeSharedResource),Resultand itsLocalizedErrorMessageextension,ComponentLifetimeExtensions.LifetimeToken(MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ComponentLifetimeExtensions.cs:26); externals:[SupplyParameterFromQuery]andNavigationManager(Microsoft.AspNetCore.Components), MudBlazorMudTextField<string>, BCLIDisposable,CancellationTokenSource,HttpRequestException,InvalidOperationException,OperationCanceledException. - Concept introduced, a refusal code is a machine value that is mapped to words and never displayed.
[Rubric §27, Internationalization]assesses whether user-facing text translates;[Rubric §26, Front-End Security]assesses whether the front end leaks internals. The OAuth completion endpoint sends every refusal back to/login?error={code}, andError(Login.razor.cs:82-83, bound by[SupplyParameterFromQuery(Name = "error")]) receives it.ExternalSignInErrorMessage(:326-332) mapsnullor empty to no message,oauth_failedandmissing_claimsto their own resources, and any other code toRefusalMessage(:334-338). That helper looks upAuth.Login.ExternalError.{code}and, when the resource is missing (ResourceNotFound), falls back to the genericAuth.Login.ExternalError.Refusedtext. The doc comment (:317-323) explains the split: a code with a recovery path of its own (a locked account, an email already linked to another sign-in, an unverified provider email) gets its own resource, and every other domain code (for example an invalid name) shows the generic refusal. The raw code is never rendered. - Concept introduced (2), the second factor as a step of the same form.
[Rubric §11, Security]and[Rubric §24, Forms, Validation & UX Safety]. A password sign-in for an account with two-factor turned on is refused with a codeLoginRefusals.Classifyrecognizes (:125).HandleRefusalStep(:123-140, doc:116-122) then keeps the email and password, sets_awaitingSecondFactor, clears any previous code and asks for focus on the code field (:126-131). It returnstrueforSecondFactorRequired, so no error shows the first time the step appears, andfalseforSecondFactorInvalid, so a wrong code keeps the step and shows the message. AnEmailNotConfirmedrefusal records the trimmed address for the resend prompt (:134-137). The markup wires it as_errorMessage = HandleRefusalStep(result) ? null : PasswordLoginErrorMessage(result)(Login.razor:364). - Walkthrough:
_ctsand_disposed(:24-25): the page's lifetime source and its dispose guard. The comment (:21-23) states the purpose: a sign-in still in flight when the user navigates away, or when anInteractiveAutorender-mode transition tears the page down, stops instead of completing into a component that is gone.- State fields (
:31-67):_externalSignInUnavailable(:31, set when device storage dropped the OAuth attempt, which disables the web-redirect provider buttons, doc:27-30),_existingAccountEmail(:37),_signInLinkSentToand_isSendingLink(:40-42),_oidcProviders(:45),_offersOrganizationSignInand_isDiscovering(:48-50),_offersPasskeys(:53),_awaitingSecondFactor(:59),_codeFieldand_focusCode(:61-64),_unconfirmedEmail(:67). Reason(:74-75, bound to?reason=):two-factor-enabledortwo-factor-requiredshows its notice; any other value is ignored (doc:69-73).Error(:82-83) is described above.Dispose()(:86-90) andDispose(bool)(:94-104, doc:92-93): the standard dispose pattern. The protected overload returns early when already disposed or not disposing (:96-99), otherwise sets_disposed, cancels_ctsand disposes it (:101-103), so it is safe to call more than once.OnAfterRenderAsync(:107-114): moves focus to the code field once it exists (:112), so a keyboard or screen-reader user lands on the new input.BuildLoginRequest()(:147-163, doc:142-146): clears the resend prompt; outside the code step it returns a plainLoginRequest(:152), so a first attempt never carries a stale code. In the step, an empty code setsAuth.Login.SecondFactor.CodeRequiredand returnsnull(:155-160); otherwise the request carries the trimmedTwoFactorCode(:162). The markup returns early onnull(Login.razor:350) and passes_cts.LifetimeToken()toAuthService.LoginAsync(Login.razor:361).StartOver()(:166-174): leaves the step and clears the code, the password and both messages, so another account can sign in (Login.razor:143).ApplyHandedOverEmail()(:180-193): prefills the address another auth page handed over throughAuthEmailPrefill.Read(:182), which uses history state and never the URL, and raises the existing-account notice when registration refused the address as already registered (:189-192). Called on initialization (Login.razor:310).OffersPasskeys()(:200-203): true only whenSignInSettings.OfferPasskeysis on, the head'sIPasskeyCapabilityreportsIsAvailable, and anIPasskeyUIServiceis registered; both are resolved optionally, so a host that registers neither shows no button (doc:195-199, ADR-139).OnPasskeySignedInAsync(:206-207) lands the user on the sanitized return URL as a password sign-in does.OpenPasswordReset()(:210-211): opens/forgot-passwordwith the typed address handed over (Login.razor:63).SendSignInLinkAsync()(:217-257, doc:213-216, ADR-116): asks for an emailed sign-in link. An empty address showsAuth.Login.EmailMeLink.EnterEmail(:223-227);ISignInLinkUIServiceis resolved at the click (:231), so a host that never offers the button need not register it. On success it records the address for the sent notice (:243); the endpoint answers 202 for every well-formed address, so the notice says only "if an account exists". A failure shows the localized message orAuth.Login.GenericError(:247), and a cancellation while disposed is swallowed (:249).SignInWithOidcAsync(provider)(:264-265): starts a configured OIDC provider through the system-browser broker whenExternalAuthBroker.IsAvailable, otherwise through the web redirect (Login.razor:265for the per-provider buttons).SignInWithOrganizationAsync()(:272-315, doc:267-271): the email-first organization step. It resolvesIOidcDiscoveryUIServiceat the click (:285), asks which provider claims the address's domain (:294), showsAuth.Login.SignInWithOrganization.NotFoundwhen none does (:297), and otherwise starts that provider (:301). AnHttpRequestExceptionbecomes the generic error (:307-310).PasswordLoginErrorMessage(Result)(:349-361, doc comment:340-348): the API's message is an English sentence, not a resource key, so when the failure carries exactly one error with a non-empty code (:351) the code itself is looked up inL(:353) and, if a resource exists (Auth.InvalidCredentials,Auth.AccountLocked), that text is returned in the active culture (:354-357). Any other refusal keeps the previous chain:result.LocalizedErrorMessage(L), then the genericAuth.Login.InvalidCredentialswording when nothing renderable came back (:360).SignInWithRedirectAsync(provider)(:373-394, doc comment:363-371): the attempt is minted at the click, not at first render, so its lifetime runs from the moment the user chose a provider and a second login tab replaces the attempt only when the user clicks there (latest click wins; the comment cites M237). It awaitsOAuthFlowState.BeginAsync(_cts.LifetimeToken())(:378) into a localoauthState. AnOperationCanceledExceptionraised while_disposedis set (:380-384) means the page went away mid-write, so it returns with nothing to navigate from. If the store throwsInvalidOperationException(:385), because storage accepted the write without keeping it (storage full, site data blocked, private mode), it sets_externalSignInUnavailable, showsAuth.Login.ExternalSignInStorageUnavailable, and returns without navigating (:387-389); the page re-renders on its own as the handler completes. Otherwise it callsNavigation.NavigateTo(BuildOAuthUrl(provider, oauthState), forceLoad: true)(:393), a full load because the challenge is a server endpoint, not a route (comment,:392).
- Why it's built this way: the completion page refuses a flow whose state it cannot find one redirect later, with no explanation; failing at the click, staying on the page with the buttons disabled and a reason on screen, turns a silent dead end into an actionable message (doc comment,
:363-371). Keeping the second factor on the same form, with the password retained read-only, means the user types the code without re-entering credentials, and sending the code only while the step is shown keeps a stale code out of an ordinary attempt. Resolving the optional services (sign-in links, OIDC discovery, passkeys) at the moment of use lets a host that does not opt in skip their registration entirely. The fallback-to-generic rule means a new domain error code never surfaces as a raw key, and resolving the password refusal by error code keeps it in the viewer's culture instead of the API's English sentence. Reading the token throughLifetimeToken()rather than_cts.Tokenmatters because the work can resume afterDispose: on a disposed source the rawTokenthrowsObjectDisposedException, whileLifetimeTokenreturns an already-cancelled token so the work stops through its normal cancellation path (ComponentLifetimeExtensions.cs:3-10). Thewhen (_disposed)filter keeps a cancellation the page did not cause from being silently swallowed. - Where it's used: the
Login.razorprovider buttons callSignInWithRedirectAsync("apple"),("google")and("github")(Login.razor:207,:229,:251), andBuildOAuthUrl(Login.razor:313) appends the state to the provider redirect query. The second-factor step is covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/SecondFactor/LoginSecondFactorTests.cs, the passkey offer byPasskeys/LoginPasskeyTests.cs, the OIDC starts byOidc/LoginOidcTests.cs, the sign-in link request bySignInLinks/LoginSignInLinkTests.csand the resend prompt byEmailConfirmation/LoginResendPromptTests.cs(all under the samePages/Auth/test folder). Error mapping is covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/LoginErrorQueryTests.cs, the attempt flow byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/LoginOAuthAttemptTests.cs, the in-flight cancellation byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/Lifetime/AuthSubmitLifetimeTests.cs, and the form models byLoginModel. The OAuth design is ADR-036 and the native callback is ADR-043. - Caveats / not-in-source: the markup half was read only for the cited lines; the form submit path and provider buttons live there, not here.
ConfirmEmail
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ConfirmEmail.razor.cs:46· Level 4 · class (sealed, partial, page code-behind)
- What it is: the code-behind for the shared, anonymous landing page of the emailed confirmation link (
@page "/confirm-email"with[AllowAnonymous],MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ConfirmEmail.razor:1-3; summaryConfirmEmail.razor.cs:15-18, ADR-116). It reads the address and token from the URL fragment or the query string, redeems them once on the first interactive render, asks for the account's password (or a new one) when the API requires that proof, and falls back to manual entry plus a resend option when redemption is refused. - Depends on:
IEmailConfirmationUIService(injected asConfirmationService,:90),CapabilitiesJsModule(the optional JS interop module that takes the URL fragment, resolved throughIServiceProviderat:221),EmailedLinkReader(:172,:176,:180,:234),AuthErrorCodes.EmailConfirmationPasswordRequired(:266),ConfirmEmailRequest(:329-331),Resultand itsLocalizedErrorMessageextension (:275,:294-295),SharedResource(asIStringLocalizer<SharedResource>,:96),ComponentLifetimeExtensions.LifetimeToken(:259,:337,:379), the private nestedConfirmationState(:67-80); externals:[SupplyParameterFromQuery],[Inject],NavigationManagerand itsLocationChangedevent,LocationChangedEventArgs(Microsoft.AspNetCore.Components.Routing), BCLIDisposable,CancellationTokenSource,StringComparison,OperationCanceledException. - Concept: the remarks (
:19-45) give four rules. The credentials arrive in the URI fragment (.../confirm-email#email=..&token=..), which a browser never sends to a server, so the live token stays out of access logs, telemetry andRefererheaders, andlocationHashTakescrubs it from the address bar and history; query-string parameters are a fallback and both fields stay editable (:20-27). One POST per link, through a service that never retries, because the token is single-use (:28-34). The page is anonymous because an unconfirmed account may not be able to sign in (:35-38). An account that holds a password must prove it: onAuthErrorCodes.EmailConfirmationPasswordRequiredthe token is still unspent and the page offers the current password or a new one (a new one claims the account and signs out every other session), then posts the same address and token again with it (:39-44). On the first render the query values are applied first (OnParametersSet) and the fragment only fills what is still empty (ApplyFragment(..., replace: false),:155); a new link opened on the showing page replaces both (replace: true,:191). - Walkthrough: the const
InvalidConfirmationTokenCode("Authentication.InvalidConfirmationToken",:49), thirteen private fields (_ctsthrough_newPassword,:51-64, including_locationHandlerRegistered,_claimWithNewPassword,_currentPasswordand_newPassword), and two query-bindable properties (EmailFromQuery,:83-84;TokenFromQuery,:87-88).Dispose()(:99-114): idempotent through_disposed; unsubscribes fromNavigation.LocationChangedwhen it was registered (:107-110), then cancels and disposes_cts.OnInitialized()(:122-126): subscribes toNavigation.LocationChanged, because a new link opened in this tab changes only the fragment or query and does not rebuild the page (remarks:117-121).OnParametersSet()(:133-144): fills_email/_tokenfrom the query parameters only when the field is still empty, so a value the visitor corrected by hand survives a re-render.OnAfterRenderAsync(firstRender)(:147-157): runs once (_attempted,:149-154), merges the taken fragment without replacing (:155) and callsRedeemOrShowFormAsync(:156).OnLocationChanged(sender, e)(:165-184, summary:159-164): ignored once disposed or before the first read (:167-170). A location with a fragment re-takes it and redeems it as a new link (:172-174); otherwise a query carrying the link's pairs (LinkQueryOf,:176) is scrubbed from the address bar (:180) and redeemed (:181). Both paths marshal onto the renderer throughInvokeAsync.RedeemNewLinkAsync(link)(:189-200): does nothing once disposed or when the link carries no recognized pair (:191-194); otherwise clears_linkSentand_errorMessage, returns toWorking(:196-198) and redeems as a fresh tab does (:199).RedeemOrShowFormAsync()(:202-214): with the address or the token blank it goes straight toFormand re-renders without posting (:204-211); otherwise it callsConfirmAsync(:213).TakeFragmentAsync()(:216-226): resolvesCapabilitiesJsModulefromServicesand callslocationHashTake, returningnullwhen the module is absent (SSR prerender, a component test, a host without the capabilities module, comment:218-220).ApplyFragment(fragment, replace)(:232-238): delegates toEmailedLinkReader.MergeLinkFragment(:234) and returns whether a pair was recognized.ConfirmAsync()(:240-292): with either value blank it showsAuth.Confirm.EmailAndTokenRequiredinForm(:245-250). Otherwise it sets_isBusyand re-renders (:252-255), postsConfirmEmailAsync(_email.Trim(), _token.Trim(), _cts.LifetimeToken())(:259), and moves toConfirmedon success (:260-264), toPasswordProofthroughShowPasswordProofon the password-required code (:266-270), or toFormwith the API's own wording orAuth.Confirm.GenericErroron any other refusal, which the server collapses into one indistinguishable error (:272-276). A cancellation is swallowed as expected during disposal or anInteractiveAutotransition (:278-281), and thefinallyre-renders unless disposed (:282-291).HasErrorCode(result, code)(:294-295): an ordinal match overresult.Errors.ShowPasswordProof()(:297-304): clears the message, resets the toggle to "current password" and empties both password fields, then setsPasswordProof.ToggleProof()(:306-310): switches between the current-password and new-password inputs, clearing the message; bound to a button in the markup (ConfirmEmail.razor:92).ConfirmWithPasswordAsync()(:318-362, summary:312-317): an empty password showsAuth.Field.Password.Required(:322-327). It builds aConfirmEmailRequestcarryingNewPasswordorCurrentPasswordby the toggle (:329-331) and posts it throughConfirmEmailWithPasswordAsync(:337). Success clears both password fields and moves toConfirmed(:338-344). A refusal sets the API's message (:346); only the invalid-token code clears the passwords and returns toFormfor a resend (:347-352), so a wrong password, a lockout or a password the policy refuses keeps the password step. Bound to a button in the markup (ConfirmEmail.razor:81).ResendAsync()(:364-398): an empty address showsAuth.Confirm.EmailRequired(:369-373); otherwise it callsResendEmailConfirmationAsync(_email.Trim(), _cts.LifetimeToken())(:379) and sets_linkSenton success without changing_state(:384). The endpoint answers 202 whether or not the address holds an unconfirmed account, so the notice says exactly that (comment:382-383), the same anti-enumeration rule theForgotPasswordModelflow uses.
- Why it's built this way: separating the automatic redeem attempt from the manual/resend UI means a stale, already-used, or malformed link degrades to a working form instead of a dead end. The password step exists because a confirmation link alone must not hand over an account that already holds a password: the token stays unspent until the visitor proves the password or claims the account with a new one, and only a dead token sends the visitor back to request a fresh link. Listening for location changes means a fresh link opened from the resend notice in the same tab is redeemed, not ignored. Collapsing resend and redeem-failure onto the same
Formstate keeps_statepurely about which panel renders, while_errorMessageand_linkSentcarry the finer detail. - Where it's used: reached wherever a host maps the framework's shared Auth pages. Exercised by the shared conformance test base
MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Pages/ConfirmEmailPageTestsBase.cs, and backed downstream by ADC's confirm-email domain and application workflow thatIEmailConfirmationUIServiceultimately calls through the API (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ConfirmEmail/ConfirmEmailHandler.cs,ConfirmEmailCommand.cs,MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IEmailConfirmableUser.cs) and the sharedMMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/ConfirmEmailHandlerBase.cs. - Caveats / not-in-source: the markup half was read only for the cited lines. Which server-side rule decides that an account needs password proof lives behind the API, not in this component.
Register
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Register.razor.cs:13· Level 4 · class (partial, page code-behind)
- What it is: the code-behind half of the shared Register page. It holds one decision the markup needs, whether the user supplied an address and if so whether it is a valid one, plus the page lifetime that cancels a registration still in flight when the page goes away (
IDisposable,Register.razor.cs:13). - Depends on:
RegisterModel(the_modelfield the markup declares),RegistrationSettings(read throughRegistrationOptions.Value.CollectAddress,Register.razor.cs:33, injected atMMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Register.razor:18), and the first-partyAddressvalue object plusResult(Register.razor.cs:88,:67); BCLIDisposableandCancellationTokenSource. - Concept introduced, an optional block that is validated if touched.
[Rubric §24, Forms, Validation & UX Safety]assesses whether a form drops or silently accepts bad input.BuildAddressResult()(:50-68) returnsResult<Address>?with three outcomes. With address collection off (CollectAddress,:20) it returnsnull, because there is no block to type into (:52-55). With collection on and all six fields blank (:57-65) it also returnsnull: no address is legitimate. Otherwise it callsAddress.Create(...)(:67) and returns thatResult, so anything the user did type is validated and an invalid address blocks the registration. The doc comment (:43-49) records the reason: the account used to be created with no address at all when the typed address was invalid. - Walkthrough: two lifetime fields, one computed property, the dispose pair and one method.
_ctsand_disposed(:16-17): the page's lifetime source and its dispose guard; the comment (:13-15) says a registration in flight when the user navigates away, or when anInteractiveAutorender-mode transition tears the page down, stops instead of completing into a component that is gone. The markup passes_cts.LifetimeToken()(seeComponentLifetimeExtensions) toAuthService.RegisterAsync(Register.razor:256).CollectAddress(:20).Dispose()(:22-27) andDispose(bool)(:31-41, doc comment:29-30): returns early when already disposed or not disposing, otherwise sets_disposed, cancels and disposes_cts, so it is safe to call more than once.BuildAddressResult(:50): the markup calls it on valid submit (Register.razor:235), stops with the first error message when it failed (Register.razor:236-239), and otherwise projects the success value into aRegisterRequest(Register.razor:248-256), as described underRegisterModel.
- Why it's built this way: returning a nullable
Resultrather than a bareAddress?is what lets "nothing entered" (null) stay distinct from "entered and invalid" (a failedResult), which a plain null could not express. The lifetime pair is the same shape asLogin, so both auth pages stop cleanly on teardown. - Where it's used: bound by
Register.razor; behavior is covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/RegisterFormTests.cs,RegisterAddressOptionTests.csandRegisterTermsTests.csin the same folder, and the in-flight cancellation byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/Lifetime/AuthSubmitLifetimeTests.cs. - Caveats / not-in-source: the Terms checkbox enforcement lives in the markup half, not in this file; only the address rule is here.
SignInLink
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth.SignInLinks·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/SignInLinks/SignInLink.razor.cs:46· Level 4 · class (sealed, partial, page code-behind)
- What it is: the code-behind for the anonymous landing page of an emailed sign-in or invitation link (
@page "/auth/sign-in-link"with[AllowAnonymous],MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/SignInLinks/SignInLink.razor:1-3). It reads the address and single-use token from the URL fragment, waits for the user to tap Continue, redeems the link, and offers a fresh link when the one it holds is incomplete or refused (summary,SignInLink.razor.cs:19-22, ADR-116). - Depends on:
ISignInLinkUIService(injected asSignInLinks,:77),SignInSettings(asSignInOptions,:81, forSignInLinkLandingPath),LegalSettings(asLegalOptions,:83),CapabilitiesJsModule(resolved optionally,:211),EmailedLinkReader(:227),ReturnUrlProtector(:251),SharedResourceasIStringLocalizer<SharedResource>(:87),Resultand itsLocalizedErrorMessageextension (:292),ComponentLifetimeExtensions.LifetimeToken(:246,:285), the private nestedLinkState(:65-75), and the framework'sExternalLinkcomponent (:200); externals:[Inject],NavigationManagerand itsLocationChangedevent,LocationChangedEventArgs(Microsoft.AspNetCore.Components.Routing),RenderFragment,IOptions<T>, MudBlazorUnderline, BCLIDisposable,CancellationTokenSource,Uri,OperationCanceledException. - Concept introduced, a link that opens a session is redeemed on a tap, never on render.
[Rubric §26, Front-End Security]and[Rubric §11, Security]. The remarks (:23-45) give three rules. First, the credentials arrive in the URI fragment, as onConfirmEmail: a browser never sends a fragment to a server, so the live token stays out of access logs, telemetry andRefererheaders, andlocationHashTakescrubs it from the address bar and history (:24-28). Second, unlike the confirmation page, which redeems on first render, this token opens a session, so a mail scanner that renders the page with script enabled would otherwise spend the token and sign itself in (:29-34). The page therefore stops inLinkState.Readyand posts only from the Continue button (SignInLink.razor:28,:45). One POST per tap, through a service that never retries, because a retried POST of a single-use token can only spend it twice (:35-38). Third, a second link opened while the page is showing is read too (:39-44): on MAUI an app link that lands on this route is a same-page navigation that renders nothing new, so the page reads the fragment of every location change to its own route, waits for Continue on the new link, and never shows a token it already posted again. - Walkthrough:
- State fields (
:48-62):_cts,_state(starts atLinkState.Reading),_email,_token,_errorMessage,_linkSent,_isBusy,_attempted,_disposed, plus_ownPath(the route the page was opened on) and_submittedToken(the last token Continue posted, comment:59-60). RequiresTerms(:92): true when the host published a Terms URL inLegalSettings, the same rule the register page uses (comment,:91).Dispose()(:95-106): idempotent through_disposed; unsubscribes fromNavigation.LocationChanged(:103), then cancels and disposes_cts.OnInitialized()(:109-113): records_ownPathfrom the current URI's absolute path and subscribes toNavigation.LocationChanged.OnAfterRenderAsync(firstRender)(:116-126): runs once (_attempted,:118-123), passes the taken fragment toShowLink(:124), then re-renders.OnLocationChanged(sender, e)(:133-144, summary:128-132): ignores the event until the first read has happened, when the new location carries no fragment, or when its path is not_ownPath(case-insensitive,:135-141); otherwise it marshalsShowNewLinkAsyncwith the fragment minus its hash onto the renderer throughInvokeAsync(:143). Before the first read the pendingOnAfterRenderAsyncpicks the new fragment up itself.ShowNewLinkAsync(fragment)(:146-167): does nothing once disposed or while a redemption is in flight, because that redemption owns the page (:149-152). It callsTakeFragmentAsynconly to scrub the new link from the address bar and history, since the values already came with the navigation (:156), then drops a link whose token equals_submittedToken(:158-162). Otherwise it clears_linkSent(:164) and shows the link throughShowLink(:165).ShowLink(fragment)(:174-188, summary:169-173): parses the fragment into_emailand_token(:176) and moves toFailedwithAuth.SignInLink.Incompletewhen either is missing (:178-182), otherwise clears any earlier message and moves toReady(:183-187).LegalDocument(url, name)(:192-205): renders a document name in the consent sentence as anExternalLinkwhen the host published that document, plain text when it did not; the markup shows the sentence only whenRequiresTermsholds (SignInLink.razor:31-41).TakeFragmentAsync()(:207-216): resolvesCapabilitiesJsModulefromServicesand callslocationHashTake, returningnullwhen the module is absent (SSR prerender, a component test, a host without the capabilities module, comment:209-210).ParseFragment(fragment)(:225-229, summary:218-222): returns an(Email, Token)tuple, each empty when the fragment does not carry it, by callingEmailedLinkReader.MergeLinkFragment(fragment, replace: true, email: null, token: null)(:227). It goes through the same emailed-link parserEmailedLinkReaderthe confirm-email and reset-password pages use, so a duplicated pair resolves the same way on every page: the first one wins.RedeemAsync()(:231-268): returns at once while busy or when the trimmed token equals_submittedToken, so a second tap or the same link opened again never spends it twice (:233-238), then records the token as submitted (:240). It callsRedeemSignInLinkAsync(_email.Trim(), token, RequiresTerms, _cts.LifetimeToken())(:246), so the tap carries the Terms acceptance. On success it does a full-load navigation to the sanitizedSignInLinkLandingPath, falling back to/(:251), so every component re-reads the new auth state. On failure it clears_token(the token is spent or was never valid), sets the message fromRefusalMessageand moves toFailed(:256-258). A cancellation is swallowed as expected during disposal or anInteractiveAutotransition (:260-263).RequestNewLinkAsync()(:270-302): an empty address showsAuth.Confirm.EmailRequired(:275-279); otherwise it callsRequestSignInLinkAsync(_email.Trim(), _cts.LifetimeToken())(:285) and sets_linkSenton success, or shows the localized error orAuth.SignInLink.GenericError(:292). The markup words the sent notice as "if that address has an account", because the endpoint answers 202 either way (SignInLink.razor:68).RefusalMessage(result)(:310-322, summary:304-309): when the failure carries exactly one error with a non-empty code, that code is looked up as a resource (an invalid link, an account that needs its second factor) and used if it exists (:312-319); otherwise the genericAuth.SignInLink.GenericError(:321). The raw code is never rendered, the same rule asLogin.
- State fields (
- Why it's built this way: waiting for the tap is what keeps a link-scanning mail gateway from consuming the token and holding a session the user never asked for, and it gives the Terms acceptance an explicit user action to ride on. Clearing the token on any refusal means the only way forward is a fresh link, which the
Failedpanel offers in place with the address kept. Listening for same-route navigations closes the loop on MAUI, where the fresh link the user asked for from that panel opens on the page that is already showing, and remembering the posted token keeps that second read from ever posting a token twice. - Where it's used: routed at
/auth/sign-in-linkin any host that maps the framework's Auth pages; the emailed link is composed server-side byMMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/SendSignInLinkHandlerBase.cs. TheLoginpage requests the same links from its "email me a link" button. Covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/SignInLinks/SignInLinkPageTests.csand the shared conformance baseMMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Pages/SignInLinkPageTestsBase.cs;MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Api/AnonymousEndpointTests.csalso references it. Shell composition is ADR-067. - Caveats / not-in-source: the markup half was read only for the cited lines. Whether
ISignInLinkUIServiceis registered is a host decision; this page injects it directly (:77), so a host that routes the page must register the service.
Sessions
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor.cs:29· Level 7 · class (partial, page code-behind)
- What it is: the code-behind for the signed-in devices page at
/profile/sessions: one row per live refresh session, with a per-device sign-out and a sign-out-everywhere, each behind a confirmation dialog, followed by the account's sign-in history (every sign-in, ended ones included,Sessions.razor:111-126). - Depends on:
IAuthUIService(line 31),SignOutNavigator(line 32),IToastService(line 33),IAppDialogService(line 34),SharedResourceasIStringLocalizer<SharedResource>(line 35),ViewerTimeZone(line 36),RefreshSessionSummaryResponse(the row DTO, line 43),SignInSummaryResponse(the history row, line 48),Result(lines 46 and 51),ResultUiExtensions(IsNotFound,NotifyOnFailure),UserAgentSummaryandDeviceMetadata(line 267),ComponentLifetimeExtensions.LifetimeToken(MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ComponentLifetimeExtensions.cs:26),RoutePaths(line 75), and, in the markup,SignInHistoryTable(Sessions.razor:125). Externals: MudBlazor'sBreadcrumbItem/MudTable. - Concept introduced, two revoke paths with deliberately different endings.
[Rubric §11, Security]assesses whether a user can see and end their own live credentials;[Rubric §25, Navigation & IA]assesses whether a destructive action leaves the app in a coherent place. The class comment (lines 16-28) states the model: a row's button calls the per-session revoke, which ends one other device's session and leaves this one alone, while the page-level button is the account-wide revoke, which also ends the session the caller is using and therefore must be followed by the local sign-out and a redirect, but only once the server confirmed the revoke (line 24). The consequence is visible in the markup: the row for the current device offers no button at all (Sessions.razor:68-75), because revoking it from a row would leave the app signed in on a dead session until the access token expired, which reads to a user as a broken sign-out. - Concept introduced (2), a single in-flight gate over two different operations.
[Rubric §18, UI Architecture & Component Design].IsBusy(line 65) is_revokingSessionId is not null || IsRevokingAll, and every button in the markup reads it (Sessions.razor:80,:97). One flag over both operations is what stops a second click from starting a concurrent revoke while the list is about to be rebuilt underneath it, and_revokingSessionIddoubles as the per-row spinner selector (Sessions.razor:84). Both revoke handlers checkIsBusytwice, before and after the awaited confirmation dialog (lines 150 and 162, 218 and 230), because another operation can start while the dialog is open. - Walkthrough:
- State (lines 38-68): a component-scoped
CancellationTokenSource(line 40) passed into every service call (as_cts.LifetimeToken(), the repo convention) and cancelled on dispose,_breadcrumbs,_sessions, the nullable_loadResultthat carries the last load outcome for inline rendering (line 46),_signInsand the nullable_signInsResultfor the history, null while its read is in flight (lines 48-51),_revokingSessionId,IsLoading(line 59),IsBusy(line 65), andIsRevokingAll(line 68).LoginRouteis aconst(line 38). OnInitializedAsync(lines 70-81): builds the breadcrumbs here rather than in a field initializer so the injected localizer is available (comment at line 72, ADR-027), then loads the sessions and then the sign-in history (lines 79-80).OnAfterRenderAsync(firstRender)(lines 84-91): on first render, while not disposed, awaitsViewerTime.EnsureResolvedAsync(_cts.LifetimeToken())and callsStateHasChangedwhen it resolved a zone (line 89). Session times render on the viewer's clock, and the browser's zone is only readable once JS is available, so the page re-renders once the zone is known. SeeViewerTimeZone.LoadSessionsAsync(lines 93-122): stores the wholeResultin_loadResult(line 101) so the markup can render the failure inline with a retry button rather than as a toast (Sessions.razor:17,:23-30; the comment atSessions.razor:15-16explains why: an empty table and a failed load look identical once a toast expires). On failure it empties_sessionsdeliberately (lines 107-112), so a stale device list can never be left on screen for a user to act on.OperationCanceledExceptionis swallowed as expected-on-disposal (lines 114-117) andIsLoadingclears in thefinally.LoadSignInsAsync(lines 128-140, doc comment lines 124-127): readsIAuthUIService.GetSignInsAsync(line 132, contract atMMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/IAuthUIService.cs:79), keeps the rows only on success and empties them otherwise (line 133), so a stale history is never left on screen, then stores the result (line 134). The markup shows a loading state while_signInsResultis null, the failure in place of the table, or the rows throughSignInHistoryTable(Sessions.razor:115-126); it loads on its own, so a failed history read never hides the device list or the other way round (Sessions.razor:111-112).RevokeSessionAsync(session)(lines 148-207): refuses to run while busy or for the current device (lines 150-153, a second guard behind the markup's), then asks for confirmation throughIAppDialogService.ConfirmAsyncwith a message naming the device viaDescribeDevice(lines 155-160), because the device loses its session at once (doc comment, lines 142-147). After the post-dialog re-check (lines 162-165) it marks the row in flight (line 167) and callsStateHasChanged(line 172): the dialog completed asynchronously, so Blazor has already rendered once for the click and will not render again until the handler returns, which would otherwise leave the button showing no progress for the length of the revoke call (comment, lines 169-171). It then treats three outcomes distinctly. Success toasts (line 180). A not-found result, which means the session is already revoked (the server answersAuth.SessionAlreadyRevokedafter a duplicate click or once the device signed itself out) or no longer exists, toasts at info severity instead (lines 182-188), because the user's intent is satisfied and there is nothing to correct. Any other failure goes throughresult.NotifyOnFailure(Toast, L)and returns without reloading (lines 189-193). On either satisfied outcome it reloads the list from the server rather than removing the row locally, and reloads the sign-in history too, because the revoked device's sign-in has just ended (lines 195-197); the server is the authority on what is still live and a reload also catches a session that expired while the page sat open.RevokeAllAsync(lines 216-260): guards onIsBusy(line 218), confirms throughConfirmAsync(lines 223-228) because this also ends the session the user is on, re-checks (line 230), renders the busy state before the long call (StateHasChanged, line 238, same reasoning as the per-device revoke), then runsIAuthUIService.RevokeAllSessionsAsync(contract atMMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/IAuthUIService.cs:98), the account-wide revoke followed, on success, by the local sign-out, throughSignOutNavigator.SignOutAsync(signOut, LoginRoute)(line 246; the internal overload atMMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/SignOutNavigator.cs:69). The reason is in the comment (lines 242-244): the page is[Authorize], so the local sign-out re-renders it intoRedirectToLogin, whose own navigation (offering to come back here) would otherwise reach the browser first. The navigator holds a claim on the next navigation for the whole round trip and, only on success, force-loads/login, so the circuit and any cached client state are rebuilt rather than kept alive against a revoked identity; on a refusal it releases the claim and navigates nowhere (SignOutNavigator.cs:85-89). A failed revoke is shown throughresult.NotifyOnFailure(Toast, L)(line 249) and the page stays put: the doc comment (lines 209-215) explains that a best-effort logout would claim every device was signed out even when the server refused.OperationCanceledExceptionis swallowed as expected-on-disposal (lines 252-255) andIsRevokingAllclears in thefinally(lines 256-259).DescribeDevice(session)(line 267, doc comment lines 262-266): a one-line delegate toUserAgentSummary.Describe(session.Device, session.UserAgent, L)(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Devices/UserAgentSummary.cs:137). The label (the reported device name and model, else the native app, or browser and platform) is shared with the administrator's sessions table instead of being composed in this page, and the word-order and "unknown device" handling live with the shared helper (Parseis atUserAgentSummary.cs:86).[Rubric §27, Internationalization]. The same label feeds the per-row confirmation message andaria-label.FormatInstant(DateTime)(line 274, doc comment lines 269-273): delegates toViewerTime.Format(instant). It formats in the viewer's browser time zone and current culture, because the endpoint reports UTC and "signed in at 03:14" only means something on the clock the reader uses;DateTime.ToLocalTimewould be the server's zone on Blazor Server and in prerender, which is why the method is no longer a static local-time conversion.Dispose(bool)/Dispose()(lines 276-296): the standard idempotent pattern, cancelling and disposing the CTS.
- State (lines 38-68): a component-scoped
- Why it's built this way: rendering the load failure inline instead of as a toast is a deliberate
[Rubric §24, Forms, Validation & UX Safety]choice for a page whose empty state is indistinguishable from its failure state, and it is the same reasoningDataGridListPageBase<TDto>encodes in itsLoadFailedflag. Treating "already revoked" as an informational outcome rather than an error avoids punishing a user for a double click on an idempotent action. Confirming both revokes before acting is the same section's destructive-action rule: each one signs a device out immediately. - Where it's used: routed at
/profile/sessionsbehind[Authorize]with[StreamRendering(false)](MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor:1-6), reachable in any host that maps the framework's UI pages. Its component behavior is covered by bUnit tests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/SessionsTests.cs:31) and its rendered accessibility by the gallery E2E WCAG 2.1 AA scan (MMCA.Common/Tests/Presentation/MMCA.Common.UI.E2E.Tests/Auth/SessionsPageE2ETests.cs:21). - Caveats / not-in-source: whether
RevokeAllSessionsAsynccompletes the local sign-out when the server call succeeds but token clearing fails is a property ofIAuthUIService, not of this file; any exception other thanOperationCanceledExceptionstill propagates out of both handlers with no toast (SignOutNavigatorreleases its claim and rethrows,SignOutNavigator.cs:79-83).LoadSignInsAsynchas noIsLoading-style flag of its own; the null_signInsResultis its in-flight signal. The accessibility markers the page relies on (the text-variant "this device" chip atSessions.razor:58-59, chosen so the marker does not depend on color alone, and the per-buttonaria-labels at:83and:100) live in the markup half, not in this code-behind.
CachedPage
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/OfflineFirstPageSnapshot.cs:40· Level 0 · record (sealed, private, nested)
- What it is: the on-disk shape of an offline list snapshot, a two-field record
(List<TItem> Items, int TotalItems)nested privately insideOfflineFirstPageSnapshot<TItem>. It is what actually gets serialized when a list page remembers its first page for a dead network. - Depends on: nothing first-party. It is round-tripped through
ILocalCacheStore, whoseSetAsync/GetAsync<T>do the JSON work (OfflineFirstPageSnapshot.cs:45-46,:63). - Concept introduced, the private nested cache payload.
[Rubric §19, State Management & Data Flow]assesses whether client-held state has an explicit, owned shape rather than being smeared across ad-hoc dictionaries;[Rubric §29, Resilience & Business Continuity]assesses whether a surface degrades instead of failing when a dependency is gone. Declaring the payload as aprivate sealed recordinside the only type that reads and writes it makes the snapshot format an implementation detail: no consumer can take a dependency on the field names, so the shape can change without a public-API break. The trade-off is the flip side of that: because the format is private and unversioned, a shape change silently orphans whatever is already in the device store. - Walkthrough: one line.
private sealed record CachedPage(List<TItem> Items, int TotalItems);(line 26). Written byRememberAsync, which materializes the fetched rows into a fresh list with a collection expression,new CachedPage([.. fetched.Items], fetched.TotalItems)(line 44), so the cached copy is decoupled from the caller's live list. Read back byTryReadAsyncasstore.GetAsync<CachedPage>(cacheKey, cancellationToken)(line 63) and immediately destructured into the tuple the grid expects,(cached.Items, cached.TotalItems)(line 64). - Why it's built this way: a
recordgives value semantics and a positional constructor for free, which is all a serialization payload needs;List<TItem>rather thanIReadOnlyList<TItem>is the concrete collection the round-trip materializes into. Nesting it privately keeps the type out of the package's public surface entirely. - Where it's used: only inside
OfflineFirstPageSnapshot<TItem>. Its round-trip is covered end to end byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/OfflineFirstPageSnapshotTests.cs:15. - Caveats / not-in-source: the doc comment states that
TItem"must be JSON round-trippable" (OfflineFirstPageSnapshot.cs:15), but nothing in this file enforces that; a DTO the store's serializer cannot handle fails at runtime, not at compile time.
ErrorMessages
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/ErrorMessages.cs:24· Level 0 · class (static)
- What it is: a small factory of user-facing failure strings (load, save, delete, delete-failed, not-found, validation) so every page code-behind reports an outcome with identical, culture-correct phrasing, resolved through a shared localizer once one is configured (ADR-027).
- Depends on:
IStringLocalizer/LocalizedString(Microsoft.Extensions.Localization, NuGet) andstring.FormatwithCultureInfo.CurrentCulture(BCL). No first-party types at all. The localizer it is handed is anIStringLocalizer<SharedResource>(doc comment,ErrorMessages.cs:32), so it shares theSharedResource.resxkeys. - Concept introduced, the static helper back-filled with an injected localizer, and the "never show raw exception text" rule.
[Rubric §27, Internationalization]assesses whether user-facing copy resolves per UI culture from resources instead of being hard-coded English;[Rubric §15, Best Practices & Code Quality]assesses whether a wording change lands in one place;[Rubric §24, Forms, Validation & UX Safety]assesses that internal error text never leaks to the user. The mechanism is the interesting part: the API isstatic, so any page can callErrorMessages.LoadError(Title, ex)without taking a DI dependency, yet the output is culture-aware because the root layout hands the class one shared localizer at startup. Every method routes through a privateLocalize(key, fallbackFormat, args)that returns the resource value when the localizer is set and the key resolves, and the inline English format string otherwise. The scope note in the class comment (lines 14-22) is what pins the responsibility boundary: a server answer reaches a page as aResultand is rendered byResultUiExtensions(NotifyOnFailure,OnFailureSetError), so these helpers only cover the exceptions a page can still see, which are its own faults (a JS-interop failure, a mapping bug, a callback the page supplied). Such an exception'sMessageis never rendered: raw exception text is neither localizable nor safe to surface (ADR-027 Decision 9). - Walkthrough: one mutable static field plus pure builders.
_localizer(line 26), a nullableIStringLocalizer?, null until configured.Configure(IStringLocalizer localizer)(line 33), the single wiring point: an expression-bodied assignment, idempotent, called once from the root layout.Localize(key, fallbackFormat, args)(lines 35-47), the resolution core: when_localizeris set and the lookup'sResourceNotFoundis false it returnslocalized.Value(lines 37-44); otherwisestring.Format(CultureInfo.CurrentCulture, fallbackFormat, args)(line 46).LoadError/SaveError/DeleteError(lines 56-57, 60-61, 64-65), the three CRUD failure paths, keyedCommon.Error.Load/Save/Delete. Each passes the entity name andex.Messageas format arguments, and the shipped templates deliberately ignore the second one (doc comment, lines 49-55), so the exception text is available to a resource that wants it while the shipped copy never prints it. The two siblings carry<inheritdoc cref="LoadError"/>(lines 59, 63) rather than repeating the rationale.DeleteFailed(string entityName)(lines 67-68, keyCommon.Error.DeleteFailed), the "the call returned but the delete did not happen" case, distinct fromDeleteError, which carries an exception.NotFound(string entityName, object id)(lines 70-71, keyCommon.Error.NotFound), interpolating the entity name and the missing id.ValidationError(lines 73-74, keyCommon.Error.Validation), a parameterless property and the only fixed sentence.
- Why it's built this way: keeping the API static means call sites never move, while the
Configureindirection adds localization without a signature change anywhere. The uniform "template only" answer is what makes the class safe to call from anycatch: there is no branch on exception type, so no curated-message path can accidentally become a leak path. The mutable static is a deliberate, single exception to the framework's no-static-state rule and is named explicitly in the architecture fitness allowlist (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Ui/StateManagementConventionTests.cs:22, with the reasoning at lines 16-21: write-once wiring, not per-user state). - Where it's used: configured once per host by
ErrorMessages.Configure(L)in the root layout (MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/MainLayout.razor:103). Called byDataGridListPageBase<TDto>on the two non-Resultfailure paths (DataGridListPageBase.cs:1497paged,:665virtualized,:767mobile), byNotificationSend(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Notifications/NotificationSend.razor.cs:127), and by the Store entity pages forNotFoundandValidationError(for exampleMMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.UI/Pages/Products/ProductDetail.razor.cs:86and:200). - Caveats / not-in-source: the
.resxpayloads (SharedResource.resx,SharedResource.es.resx) are resources, not.cs, so per-key contents are not enumerable here; a shipped template that did consume{1}would print the exception text, and only the unit tests pin that it does not (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/ErrorMessagesTests.cs:10, including the explicit case that even aDomainInvariantViolationExceptiongets the plain template,:45).
PersistedGridState
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DataGridListPageBase.cs:2067· Level 0 · record (sealed, private, nested)
- What it is: a tiny serializable record
(List<TDto> Items, int TotalItems)that carries the grid's already-fetched rows from the SSR pre-render pass into the interactive circuit, so the first interactiveServerDatacall can answer instantly instead of re-hitting the API. - Depends on:
Microsoft.AspNetCore.Components.PersistentComponentState(the Blazor mechanism that serializes it). Nested privately insideDataGridListPageBase<TDto>. - Concept introduced,
PersistentComponentStateto skip the double fetch.[Rubric §19, State Management & Data Flow]and[Rubric §23, Front-End Performance & Rendering]assess whether redundant work is avoided across render-mode transitions. Under InteractiveAuto a page renders more than once (static SSR, then interactive Server, then WebAssembly), and naively each transition re-runs the data fetch, which the user sees as a fetch-cancel-refetch flicker. Blazor'sPersistentComponentStateserializes chosen data into the pre-rendered HTML and rehydrates it in the interactive circuit;PersistedGridStateis the payload for the grid's data slice, so that cycle disappears. - Walkthrough: declared as
private sealed record PersistedGridState(List<TDto> Items, int TotalItems)(line 1034) at the very bottom of the file, under a doc comment (lines 1030-1033). On the persisting side, the callback registered inOnInitializedwritesnew PersistedGridState([.. _lastSuccessfulGridData.Items], _lastSuccessfulGridData.TotalItems)(line 189) under the keygrid:{GetType().FullName}(built at line 171), and only when a successful fetch has actually happened (line 187). On the restoring side, the synchronousOnInitializedcallsApplicationState.TryTakeFromJson<PersistedGridState>(persistKey, out var restored)(line 172) and, when present, rebuilds aGridData<TDto>into_persistedGridData(line 174) that the firstLoadServerDataAsyncreturns directly (lines 513-522). - Why it's built this way:
privatebecause the persistence is purely an implementation detail of the base class; asealed recordfor JSON friendliness and value semantics; the items are materialized into a freshList<TDto>with a collection expression (line 189) so the persisted snapshot is decoupled from the live grid data. - Where it's used: exclusively inside
DataGridListPageBase<TDto>, so every derived list page inherits the behavior with no wiring of its own. - Caveats / not-in-source: the persisting callback is registered with an explicit
Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveAuto(line 194) to satisfy the framework's "callback must be associated with a render mode" rule during the static prerender pass, because the page inherits its render mode from<Routes @rendermode="InteractiveAuto">rather than declaring one itself; the inline comment (lines 177-183) quotes the exact framework error this avoids. The restore runs in the synchronousOnInitialized, before any async lifecycle work.
CancellablePageBase
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/CancellablePageBase.cs:16· Level 0 · class (abstract)
- What it is: the smallest page base in the framework: a
ComponentBasethat owns one page-scopedCancellationTokenSource, exposes its token asPageToken, and carries the dispose pattern around it (class CancellablePageBase : ComponentBase, IDisposable, line 16). The class summary (lines 6-11) names its two derivations,DetailPageBaseandCreatePageBase, so every page base shares one cancellation contract instead of repeating the source and its dispose method (ADR-146). - Depends on:
Microsoft.AspNetCore.Components.ComponentBaseandIDisposable, plusComponentLifetimeExtensionsforLifetimeToken(). Nothing else. - Concept introduced, one cancellation contract for every page base.
[Rubric §18, UI Architecture & Component Design]assesses whether a cross-cutting component concern lives once;[Rubric §15, Best Practices & Code Quality]assesses the disposable pattern. UnderInteractiveAutoa page can be torn down while a call it started is still in flight, by a navigation or by the render-mode transition from Server to WebAssembly (ADR-056). HandingPageTokento every awaited call makes disposal the single event that stops that work, so it cancels instead of completing into a component that is gone. - Walkthrough:
- State (lines 18-19): a
readonly CancellationTokenSource _ctscreated at construction and a_disposedidempotency flag, bothprivate, so a derived page never sees the source. PageToken(line 27):protected, returning_cts.LifetimeToken()rather than the raw_cts.Token. The doc comment (lines 21-26) states the reason: reading it after dispose returns an already-cancelled token and never throws, so work started late in a disposed page stops through its normalOperationCanceledExceptionpath.Dispose()(lines 30-34): the public entry point, delegating toDispose(true)and callingGC.SuppressFinalize(this).Dispose(bool)(lines 41-55):protected virtual, returning at once when_disposedis set; whendisposingit cancels and then disposes_cts, and marks the page disposed. The class remarks (lines 12-15) give the override rule: release your own resources, then call the base, which cancels and disposes the source exactly once.
- State (lines 18-19): a
- Why it's built this way: before this base each page base carried its own copy of the source, the token property and the dispose pair. Lifting it one level means a fix to the cancellation contract (such as the late-read guarantee of
LifetimeToken()) lands in every page base at once, and a derived page can pass the token on but cannot cancel or dispose it out from under the base. - Where it's used: derived by
DetailPageBase(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DetailPageBase.cs:27) andCreatePageBase(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/CreatePageBase.cs:21), and exercised through both byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/CreatePageBaseTests.csandDetailPageBaseTests.csbeside it. - Caveats / not-in-source:
DataGridListPageBase<TDto>does not derive from it; the list base swaps its source on every load (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DataGridListPageBase.cs:1639), which a single construction-time source cannot express.
CreateSubmitOptions
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/CreateSubmitOptions.cs:8· Level 0 · record (sealed)
- What it is: the optional knobs of
CreatePageBase.SubmitAsync, as asealed recordwith threeinitproperties (line 8), so a create page that needs none of them passes nothing. - Depends on:
Microsoft.Extensions.Localization.IStringLocalizeronly. - Concept introduced, an options record instead of a growing parameter list.
[Rubric §15, Best Practices & Code Quality]assesses whether an API stays stable as callers' needs differ;[Rubric §24, Forms, Validation & UX Safety]applies because two of the three knobs are about what the user sees when a submit stops. - Walkthrough: three properties.
PreCheck(line 14):Func<string?>?, run after the form validated and before the save. A non-null return stops the submit and is shown as a warning toast;nulllets it continue.ToastOnFailure(line 20):bool, defaulting totrue. A page that shows a failed save some other way passesfalse.Localizer(line 26):IStringLocalizer?, passed toNotifyOnFailure(ResultUiExtensions) so the failure toast resolves each error message through it;nullshows the messages as they are.
- Why it's built this way: an
init-only record keeps call sites readable (new CreateSubmitOptions { PreCheck = ..., Localizer = L }) and lets a new knob arrive without breaking any existing caller ofSubmitAsync. - Where it's used: read by
CreatePageBase.SubmitAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/CreatePageBase.cs:56,:66), and built by ADC's Conference create pages, for exampleMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Events/EventCreate.razor.cs,SessionCreate.razor.cs,SpeakerCreate.razor.csandRoomCreate.razor.cs. Covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/CreatePageBaseTests.cs. - Caveats / not-in-source: what each ADC page puts in its
PreCheckis page logic in those code-behind files, not visible here.
TwoFactorPageState
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/TwoFactor/TwoFactorAccount.razor.cs:58· Level 0 · enum (private, nested)
- What it is: the six states the two-factor account page can show, nested privately inside
TwoFactorAccount(line 59):Loading(line 62),LoadFailed(line 65),NotEnrolled(line 68),Enrolling(line 71),RecoveryCodes(line 74) andEnabled(line 77). - Depends on: nothing.
- Concept introduced, one explicit state instead of a set of booleans.
[Rubric §19, State Management & Data Flow]assesses whether a component's modes are explicit and mutually exclusive. The page holds a single_statefield (TwoFactorAccount.razor.cs:44), so it cannot be both "enrolling" and "showing codes" at once, and each transition is one assignment in a named handler. - Walkthrough: the member doc comments carry the meaning:
Loadingwhile the status is read,LoadFailedwhen it could not be read (a retry is offered),NotEnrolledwhen the second factor is off (setting it up is offered),Enrollingwhile the new secret is shown and a code is asked for,RecoveryCodeswhile a new set of codes is shown once, andEnabledwhen the second factor is on. - Why it's built this way:
privatebecause the states are the page's own rendering concern; no other type reads them. - Where it's used: only inside
TwoFactorAccount:LoadStatusAsync(TwoFactorAccount.razor.cs:137),BeginAsync(:165), the enrollment callbacks (:194,:203,:209),RegenerateAsync(:232) andDisableAsync(:263) set it. - Caveats / not-in-source: which markup each state renders lives in
TwoFactorAccount.razor, not verifiable from the.csfile.
OfflineFirstPageSnapshot<TItem>
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/OfflineFirstPageSnapshot.cs:30· Level 1 · class (sealed, generic)
- What it is: a small helper that keeps the last successful first page of a list on the device and hands it back when a fetch fails while the device is offline, so a dead venue network still shows content instead of an empty grid (ADR-042).
- Depends on:
ILocalCacheStoreandIConnectivityStatusService, both taken through the primary constructor along with astring cacheKeyand an optionalstring? userScope = null(lines 29-33), plus the private nestedCachedPagepayload. No external NuGet dependency at all. - Concept introduced, offline-first read-through with a deliberately tiny blast radius.
[Rubric §29, Resilience & Business Continuity]assesses whether a surface degrades gracefully when a dependency is unreachable;[Rubric §19, State Management & Data Flow]assesses where client-side state lives and who owns it;[Rubric §22, Responsive & Cross-Browser]applies because the behavior is head-dependent by design. The teaching point is how narrowly the fallback is scoped. Three conditions must all hold before a cached row is ever shown (CanServe, line 43): the device reports itself offline, the store is available on this head, and the grid asked for page 1. That means the live path is untouched: an online user never reads the cache, a paged-past-page-1 user never reads it, and a head with no local store (Blazor Server, where SSR always has the live API) never reads it becauseILocalCacheStorereports itself unavailable there. The class comment states exactly that contract. - Walkthrough: three public members over a primary constructor, plus a computed field.
- The
_scopedKeyfield (lines 35-37):string.IsNullOrWhiteSpace(userScope) ? cacheKey : $"{cacheKey}.u{userScope}", computed once at construction and used by every store call in place of the barecacheKey. CanServe(int page)(line 43): the single predicate,!connectivity.IsOnline && store.IsAvailable && page == 1. It is public so a caller can also use it as an exception filter, which is how the ADC consumer avoids swallowing a throw it has nothing to answer with.RememberAsync((IReadOnlyList<TItem> Items, int TotalItems) fetched, int page, CancellationToken)(lines 49-59): writes only whenpage == 1 && store.IsAvailable(line 54), materializing aCachedPageand handing it tostore.SetAsync(_scopedKey, ..., cancellationToken)(lines 56-57). Any other page is silently left alone, so a user who paged deep does not overwrite the snapshot of page 1 with page 7.TryReadAsync(int page, CancellationToken)(lines 67-78): returnsnullimmediately unlessCanServe(page)(lines 71-74), then readsstore.GetAsync<CachedPage>(_scopedKey, ...)(line 76) and projects it back into the same tuple shape the fetch delegate returns (line 77), so the caller substitutes it without reshaping anything.
- The
- Why it's built this way: it is a plain class constructed by the consuming service rather than a DI-registered singleton, because the
cacheKeyis per surface and cannot be resolved from the container. The doc comment on that parameter states the invariant plainly: the key must be unique per list surface (and per scope, when one head shows the same list for different tenants or events), since a shared key would let one page serve another page's rows. TheuserScopeparameter folds the signed-in subject id into the stored key: a device is shared, so a snapshot written for one account must not be readable by the next one. Sign-out already wipes the store (ILocalCacheStore.ClearAsync), and_scopedKeyis the defense in depth for the paths that never reach sign-out, an app killed mid-session or a token that simply expired. Returningnullrather than an empty page keeps "nothing cached" distinguishable from "cached and genuinely empty", which is what lets the caller fall through to the real failure. - Where it's used: composed by ADC's
PublicSessionScheduleService, which builds one instance with a per-surface constant key (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Public/PublicSessionScheduleService.cs:27-33) and wires all three members into one fetch:RememberAsyncon every success (:42), a snapshot read when the live query returns a failedResult(:49-50), andCanServeas the exception filter on the guardedcatch(:52-59) so a throw from the store itself is rethrown when there is nothing cached to answer with. Behavior is pinned byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/OfflineFirstPageSnapshotTests.cs:15, including the per-key isolation case (:97-98). - Caveats / not-in-source: the snapshot has no expiry, no size cap, and no versioning; how long a stale first page can be served is a property of
ILocalCacheStoreand of the head's storage, not of this file. The class is best-effort by design: a store write failure insideRememberAsyncis not caught here.
TwoFactorAccount
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/TwoFactor/TwoFactorAccount.razor.cs:37· Level 7 · class (partial)
- What it is: the signed-in account's two-factor page (
/profile/two-factor), routable only in a host that calledAddTwoFactorUI(): the status, setting it up (QR code, text key, a code to confirm), the recovery codes shown once, new recovery codes, and turning it off (class summary, lines 16-20; ADR-116). - Depends on:
ITwoFactorUIService,SignOutNavigator(SignOutAsync),IAppDialogService,IToastService,LoginRefusals,AuthErrorCodes,ReturnUrlProtector,RoutePaths,SharedResource,ComponentLifetimeExtensions,Result, the responsesTwoFactorStatusResponse,TwoFactorSetupResponseandTwoFactorRecoveryCodesResponse, its privateTwoFactorPageState, and the child panelsTwoFactorEnrollmentPanelandRecoveryCodesPanel. Externals:AuthenticationState, MudBlazor'sBreadcrumbItem. - Concept introduced, enrollment ends the session.
[Rubric §11, Security]assesses session and second-factor handling. The class remarks (lines 21-36) state the three rules: the API does not re-issue tokens when enrollment is confirmed and the current token carries no second factor, so once the codes are saved the page signs out and sends the user to sign in again with a password and a code; an account that signs in only through an external provider or a sign-in link sets a password or registers a passkey before enrolling; and the secret and recovery codes live only in this component's memory, never logged, never in the URL, never cached on the device.[Rubric §24, Forms, Validation & UX Safety]applies to the destructive confirm on disable and the single busy flag. - Walkthrough:
- State (lines 39-55):
LoginRoute = "/login"(line 39), a page-scoped_cts(line 41), the breadcrumbs, the_state(line 44), the loaded status and itsResult, the transient_setupand_codes,_codesFromEnrollment, the action code and error,_recentSignInRequired,_hasMultiFactor,_isBusyand_disposed. - Inputs:
Required(lines 83-84,[SupplyParameterFromQuery(Name = "required")]), set when the API refused the session for want of a second factor so the page says the role requires one; the cascadingAuthState(line 86); five injected services (lines 88-96). - Dispose (lines 99-117):
Dispose()delegates to aprotected virtual Dispose(bool)that cancels and disposes_ctsonce. OnInitializedAsync(lines 120-135): builds the localized breadcrumbs (in the method, not a field initializer, so the injected localizer is available), readsHasMultiFactor()from the user (line 131), thenLoadStatusAsync(line 137), which setsEnabledorNotEnrolledfrom the status, orLoadFailed.- Enrollment:
BeginAsync(line 162) callsBeginEnrollmentAsyncand moves toEnrolling. The panel's callbacks land inOnEnrollmentConfirmed(line 191, dropping the secret before the codes are shown),OnEnrollmentCancelled(line 200) andOnRecentSignInRequired(line 206).OnCodesSavedAsync(line 217) then either signs out and back in after an enrollment, withLoginRefusals.TwoFactorEnabledReason, or re-reads the status after a regeneration. - Code-proved actions:
RegenerateAsync(line 229) andDisableAsync(line 260) both take the trimmed code fromActionCode()(line 339) and claim the busy flag throughTryStartAction()(line 324). Disable first asks a destructive confirm throughIAppDialogService.ConfirmAsync(lines 269-274). A refusal goes throughShowRefusal(line 353): a refusal carryingAuthErrorCodes.TwoFactorRecentSignInRequired(line 355; the shared code atMMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthErrorCodes.cs:66) shows the sign-in-again notice, any other showsLoginRefusals.Describe(...). - Sign out and back in:
SignInAgainAsync(line 302) andSignOutAndSignInAgainAsync(lines 310-320) build/login?reason=..., append areturnUrlonly whenReturnUrlProtector.Sanitize(line 313) yields something other than/, and hand the target toSignOutNavigator.SignOutAsync(line 319), which callsLogoutAsyncand then navigates withforceLoad: true(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/SignOutNavigator.cs:47,:51,:91). The method summary (lines 304-308) gives the reason: this page is[Authorize], so a plain sign-out re-rendered it intoRedirectToLogin, whose own/login?returnUrl=...navigation dropped the notice.
- State (lines 39-55):
- Why it's built this way: a single state enum plus one busy flag keeps every action mutually exclusive and every transition visible in one file, while the two panels own their own rendering and focus. Signing out after enrollment is the honest answer to a token that cannot gain a second factor in place, and the forced reload ensures no in-memory state from the old session survives; routing the sign-out through
SignOutNavigatorkeeps the page from rendering its own redirect in between. - Where it's used: routed through
TwoFactorPageGate(TwoFactorPageGate,MMCA.Common/Source/Presentation/MMCA.Common.UI/TwoFactor/TwoFactorPageGate.cs). Covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/TwoFactor/TwoFactorAccountTestsBase.csandTwoFactorAccountEnabledTests.cs, and byTwoFactorPageGateTests.cs,TwoFactorRoutesTests.csandTwoFactorPageAuthorizationTests.csunderMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/TwoFactor/. - Caveats / not-in-source: the page's markup (
TwoFactorAccount.razor), including the route directive and howRequired,_hasMultiFactorand_recentSignInRequiredrender, is not verifiable from the.csfile; the route is taken from the class summary. HowAddTwoFactorUI()makes the page routable is outside this file.
RecoveryCodesPanel
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/TwoFactor/RecoveryCodesPanel.razor.cs:15· Level 2 · class (sealed, partial)
- What it is: the code-behind of the panel that shows a freshly issued set of two-factor recovery codes once, with a copy button and a "saved" check that enables the way on (class summary, lines 10-14). It is a child of
TwoFactorAccountfor theRecoveryCodesstate (ADR-116). - Depends on:
IToastService,IClipboardService(resolved at the click, not injected),IServiceProvider, andIStringLocalizer<SharedResource>(SharedResource). - Concept introduced, secrets that live only in a parameter.
[Rubric §11, Security]assesses that sensitive values are never persisted or leaked: the summary states the codes are never logged, never put in the URL and never cached here, living in the parameter only for as long as the page shows this state.[Rubric §18, UI Architecture & Component Design]applies to the optional-capability resolution. - Walkthrough:
- State (lines 17-19): an
ElementReference _heading, the_savedcheck, and a_focusedone-shot flag. - Parameters:
Codes(line 24,[EditorRequired], in the order the API issued them),ContinueText(line 28, defaulting to the localized "Continue"), and theOnContinuecallback (line 32), run once the user confirmed the codes are saved. - Injected services (lines 34-38): the toast service, the service provider, and the localizer.
OnAfterRenderAsync(lines 41-50): moves focus to the codes' heading once. The inline comment gives the reason: the codes replace the previous state in place, so without the move a keyboard or screen-reader user would stay on a control that no longer exists.CopyAsync(lines 56-70): resolvesIClipboardServicethroughServices.GetServiceat the click (line 58), so a host that registers no clipboard capability still renders the panel. It copies the codes joined one per line and toastsAuth.TwoFactor.RecoveryCodes.Copiedon success (line 64) orAuth.TwoFactor.GenericErrorwhen the clipboard is missing or the copy failed (line 68).
- State (lines 17-19): an
- Why it's built this way:
GetServicerather than[Inject]keeps the panel usable on every head regardless of which device capabilities it wires; a missing clipboard degrades to an error toast instead of a render failure. - Where it's used: rendered by
TwoFactorAccountin its markup for both a first enrollment and a regeneration (the page sets_codesatTwoFactorAccount.razor.cs:195and:245). - Caveats / not-in-source: how
_savedgates the continue button, and whereContinueTextis shown, are markup inRecoveryCodesPanel.razor, not verifiable from the.csfile.
CreatePageBase
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/CreatePageBase.cs:21· Level 3 · class (abstract)
- What it is: the shared base for an admin create form. It owns the submit pipeline every such page otherwise repeats: validate the form, run an optional pre-check, save with
PageToken, clear the dirty flag before the page's own success step, keep a failedResultfor the error summary, and always end the saving state (class summary, lines 9-14). The page owns its model and its service call (ADR-146). - Depends on:
CancellablePageBase(its base and the source ofPageToken),IToastService,CreateSubmitOptions,ErrorMessages(ValidationError),ResultUiExtensions(NotifyOnFailure), andResult/Result<T>. External: MudBlazor'sMudForm. - Concept introduced, the create-form submit pipeline.
[Rubric §24, Forms, Validation & UX Safety]assesses that a form validates before it saves, cannot double-submit, keeps the failure visible, and does not leave an unsaved-changes prompt armed after a successful save.[Rubric §18, UI Architecture & Component Design]assesses the reuse. The class remarks (lines 15-20) spell out the page's half of the contract: bind@ref="Form", feedSaveResultto<ErrorSummary>, readIsDirtyin the unsaved-changes guard, callMarkDirtyfrom each field's@bind-Value:after, and put the success toast and navigation in theonCreatedcallback. - Walkthrough:
- Surface (lines 24-39): the injected
Toast(line 24,protected), theFormref (line 27), and threeprotectedproperties withprivate set:IsSaving(line 30),IsDirty(line 33) andSaveResult(line 36).MarkDirty()(line 39) is the one-line setter. SubmitAsync<TCreated>(saveAsync, onCreated, options)(lines 53-110): guards both delegates (lines 58-59) and returnsfalsewhenFormis unbound or a save is already in flight (line 61), which is the double-submit guard. It defaultsoptions(line 66), clearsSaveResult(line 67) and validates (line 68); an invalid form toastsErrorMessages.ValidationErroras a warning and stops (lines 69-73). A non-nullPreCheckmessage toasts as a warning and stops (lines 75-80).- The save (lines 82-109): sets
IsSaving, awaitssaveAsync(PageToken)(line 85), and on success clearsSaveResultandIsDirtybefore callingonCreated(lines 86-92), so the navigation in that callback is not stopped by the unsaved-changes guard. On failure it keeps the result inSaveResult(line 94) and, whenToastOnFailure, callsresult.NotifyOnFailure(Toast, options.Localizer)(lines 95-98). AnOperationCanceledExceptionreturnsfalse(line 102), and thefinallyalways clearsIsSaving(lines 106-109). The return value istrueonly when the save succeeded andonCreatedran.
- Surface (lines 24-39): the injected
- Why it's built this way: the order inside
SubmitAsyncis the part each page used to get subtly wrong (the dirty flag cleared after navigation, a missingfinally, a second click starting a second save). Owning the order in one base means a page supplies only the two things that differ: its service call and its success step. - Where it's used: ADC's Conference create pages pass a
CreateSubmitOptionsto it (for exampleMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Events/EventCreate.razor.cs,ActivityCreate.razor.cs,SponsorCreate.razor.cs).FormsConventionTestsBase(MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Ui/FormsConventionTestsBase.cs) names this base in its form conventions, exercised byMMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Ui/FormsConventionTestsBaseTests.cs. Behavior is covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/CreatePageBaseTests.cs. - Caveats / not-in-source: whether a given ADC create page inherits through
@inheritsin its.razoror in its code-behind is not visible from the usage scan;ErrorSummaryis a Razor component, so what it renders fromSaveResultis not verifiable here. An exception other thanOperationCanceledExceptionfromsaveAsyncoronCreatedpropagates to the page afterIsSavingis cleared.
DetailPageBase
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DetailPageBase.cs:27· Level 3 · class (abstract)
- What it is: the shared framework base for a single-aggregate detail page (loaded by route id, edited inline). It owns the concerns every such page otherwise repeats: a
LatestLoadGuardfor route-driven reloads, the load outcome (LoadState, set throughBeginLoad/CompleteLoad), and the inline edit-mode lifecycle (IsEditing/IsDirtyplus the enter and leave transitions the unsaved-changes guard reads). The page-scoped cancellation token and its dispose pattern come from its base,CancellablePageBase(class DetailPageBase : CancellablePageBase, line 27). - Depends on:
CancellablePageBase(PageToken,Dispose), the siblingLatestLoadGuardit exposes throughLoadGuard(line 34),DetailLoadState(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/PageState/DetailLoadState.cs:8, valuesLoading,Loaded,NotFound,Failed),Result, andResultUiExtensions.IsNotFound(ResultUiExtensions,MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ResultUiExtensions.cs:352). - Concept: the detail-page counterpart of the list-page base,
DataGridListPageBase<TDto>: the same stale-load and dirty-tracking plumbing, but for the one-aggregate-by-id shape instead of the paged-grid shape. The inheritedPageTokenis handed to every awaited call the page makes outside the guarded load (class remarks, lines 17-20), so navigating away, or anInteractiveAutorender-mode transition swapping the component out, cancels the in-flight work.LoadGuard(line 34) is the companion for the route-driven load itself, andBeginLoad/CompleteLoadwrap it so the page also learns where the load stands: a record that does not exist and a record that could not be fetched never share the same "not found" body (doc comment onLoadState, lines 36-40).[Rubric §24, Forms, Validation & UX Safety]applies to that split and to the dirty flag. - Walkthrough:
LoadGuard(line 34): aprotectedLatestLoadGuardproperty, disposed with the page.Begin()at the start of each load cancels the load it supersedes, andIsCurrent(generation)after each await tells a stale response to leave the page state alone.LoadState(line 41):protectedwithprivate set, starting atDetailLoadState.Loading. A page rendersDetailLoadStateContentfor every state butLoaded.BeginLoad()(lines 48-53): callsLoadGuard.Begin(), putsLoadStateback toLoading, and returns the(CancellationToken Token, int Generation)pair the load passes to its awaited calls and completes with.CompleteLoad(generation, result)(lines 67-84): returnsfalsewithout touching anything whenLoadGuard.IsCurrent(generation)is false (a newer load superseded it); otherwise setsLoadStatetoLoadedand returnstrueon success, or toNotFoundwhenresult.IsNotFound()andFailedfor every other failure, returningfalse. Atruereturn is the page's permission to adopt the value.IsEditing/IsDirty(lines 87, 90): bothprotectedwithprivate set, so only the transition methods below can move them.MarkDirty()(line 93): the one-line setter bound to every editable field's@bind-Value:after.ClearDirty()(line 99): clears the dirty flag without opening or closing the editor, for a child panel that reports its own dirty state in both directions while the page's editor state stays as it is.BeginEdit()(lines 102-106) andEndEdit()(lines 109-113): open the editor on a clean slate, and close it clearing the dirty flag, so the dirty flag can never be left set behind a closed editor.Dispose(bool)(lines 120-129):protected override; whendisposingit disposesLoadGuard(idempotent, so a second dispose stays a no-op) and then callsbase.Dispose(disposing), which cancels and disposes the page-scoped source once. The class remarks (lines 22-25) tell a page that owns further disposables to override it and call the base last.
- Why it's built this way: the guard component consumes
IsDirtydirectly to drive the "are you sure" prompt, so that prompt is driven by one flag with a small, fixed set of writers rather than by per-page bookkeeping. Putting the load outcome next to the load guard means the not-found versus failed decision is made once, from theResult's error type, instead of each page collapsing both into one empty body. The cancellation source moved down intoCancellablePageBaseso this base andCreatePageBaseshare one copy of it (ADR-146). Adding a new detail page costs an@inheritsline and aBeginLoad/CompleteLoadpair. - Where it's used:
MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/DetailPageBaseTests.cs, the conformance probeMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/Conformance/ProbeDetailPage.csdriven by the packagedDetailPageLoadStateTestsBase(MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Pages/DetailPageLoadStateTestsBase.cs), and, in ADC's Conference UI,EventDetail(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Events/EventDetail.razor.cs),PublicEventDetail(Pages/Public/Events/PublicEventDetail.razor.cs),PublicSpeakerDetail(Pages/Public/Speakers/PublicSpeakerDetail.razor.cs) andPublicSessionDetail(Pages/Public/Sessions/PublicSessionDetail.razor.cs).LifetimeTokenConventionTests(MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Ui/ComponentConventions/LifetimeTokenConventionTests.cs) also names this base. - Caveats / not-in-source:
DetailLoadStateContentis a Razor component (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/PageState/DetailLoadStateContent.razor), so what it renders per state is not verifiable from this.csfile. Whether a given page inherits this base through an@inheritsdirective in.razormarkup rather than in its code-behind is not verifiable from a.cs-scoped scan.
ListPageActions
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/ListPageActions.cs:14· Level 3 · class (static)
- What it is: one static helper every admin list page shares: the confirm-delete-toast-reload flow,
DeleteWithConfirmationAsync(line 32). - Depends on:
IToastService,Result, and theDeleteConfirmationdialog component (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/DeleteConfirmation.razor:27). - Concept introduced, the shared page helper that stays out of the base class.
[Rubric §15, Best Practices & Code Quality]assesses whether a repeated flow exists once;[Rubric §24, Forms, Validation & UX Safety]assesses that destructive actions confirm first and that failures surface to the user. The placement argument is in the class comment (lines 7-13): the flow is a plain static rather than a member onDataGridListPageBase<TDto>, so a page that composes its own layout can reuse it without inheriting anything. The same comment records why the layout reload is not here: it lives on the base asReloadActiveLayoutAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DataGridListPageBase.cs:1879), because on a phone it must save the page's filters, which only the page can read. - Walkthrough:
DeleteWithConfirmationAsync(deleteConfirm, entityName, deleteAsync, toast, successMessage, errorMessage, reloadAsync)(lines 32-69) takes the page'sDeleteConfirmationref, the entity display name, aFunc<Task<Result>>delete call, the toast service, a localized success message, aFunc<Result, string>error mapper, and a reload callback. It guards every reference argument withArgumentNullException.ThrowIfNull(lines 41-45), shows the dialog, and returns immediately when it answersfalse(lines 47-50):DeleteConfirmation.ShowAsyncreturns a plainTask<bool>(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/DeleteConfirmation.razor:24), and Escape backs out withfalse(the component comment at line 6), so a dismissal is a cancel, not a confirm. On confirm it awaits the delete and branches on theResult(lines 54-59): a failure toasts the mapped error and returns without reloading, a success toasts and awaitsreloadAsync(lines 61-62). The singlecatch (OperationCanceledException)(lines 64-67) is swallowed with a comment naming the two causes, component disposal and the InteractiveAuto render-mode transition. - Why it's built this way: passing the localized strings and the error mapper in as parameters keeps this class free of any resource dependency, so each page supplies its own translated text (ADR-027) while the flow itself stays identical everywhere. The
errorMessagedelegate is what lets a page choose between a fixed sentence and the API's own wording viaresult.LocalizedErrorMessage(L), which the parameter doc (lines 26-30) spells out. Taking the reload as a delegate is what lets the phone-aware reload stay on the base. - Where it's used: Common's own
UserAdminList(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/UserAdminList.razor.cs) and ADC's Conference list pagesActivityList,ConferenceCategoryList,EventList,PartnerList,QuestionList,RoomList,SessionList,SpeakerListandSponsorList(underMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/). Covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/ListPageActionsTests.cs. - Caveats / not-in-source:
DeleteWithConfirmationAsynccatches onlyOperationCanceledException; any other throw from the caller'sdeleteAsyncorreloadAsyncdelegate propagates to the page's own handler, which is not visible from this file. Store call sites were not part of this unit's usage scan.
DataGridListPageBase<TDto>
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Common·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DataGridListPageBase.ColumnFilters.cs:20· Level 4 · class (abstract, partial)
- What it is: the abstract Blazor base for every server-paged
MudDataGrid<TDto>list page. It folds the otherwise copy-pasted concerns (cancellation lifecycle, loading, failure and confirmed-empty flags, mobile/desktop viewport detection and the layout-known gate, filter, column-filter and sort extraction and restore, error reporting, scroll tracking and restore, density toggle, URL plus session plus prerender state plumbing, an opt-in virtualization funnel, newest-load-wins ordering for overlapping loads, and disposal) into one reusable component. It is split over two files: the main declarationpublic abstract partial class DataGridListPageBase<TDto> : ComponentBase, IBrowserViewportObserver, IListLayoutSource, IAsyncDisposable, IDisposable(DataGridListPageBase.cs:24) and the column-filter persistence part (DataGridListPageBase.ColumnFilters.cs:20). - Depends on:
IToastService,SharedResource(asIStringLocalizer<SharedResource>),ListPageStateand itsColumnFilterStateentries,ListPageStateService,ListPageQueryStateService,BreakpointConstants,ErrorMessages,ResultUiExtensions(NotifyOnFailure),ComponentLifetimeExtensions(LifetimeToken),MobileInfiniteScrollList<TItem>,IListLayoutSource(implemented explicitly),QueryFilterKeys(Alias,SearchTag),Result, and the nestedPersistedGridState. Externals: MudBlazor'sMudDataGrid<T>,GridState<T>,GridStateVirtualize<T>,GridData<T>,FilterDefinition<T>,IBrowserViewportObserver/IBrowserViewportService, and Blazor'sPersistentComponentState,NavigationManager,IJSRuntime,RendererInfo. - Concept introduced, a behavior-rich Blazor base component.
[Rubric §18, UI Architecture & Component Design]assesses reuse, and every list page in both apps inherits this behavior with no copy-paste (ADR-146).[Rubric §23, Front-End Performance & Rendering]assesses render and fetch cost: only the requested page is ever fetched, the prerender cache skips a redundant round trip, and the opt-in virtualization funnel keeps the DOM small for large sets.[Rubric §19, State Management & Data Flow]covers the four-channel persistence (URL, in-memory, sessionStorage, prerender cache), which now carries the grid's own column filters and restored sort as well as the page's filters, and the newest-load-wins rule for overlapping fetches.[Rubric §27, Internationalization]applies because the cancellation toast and everyResultfailure message resolve throughSharedResource.[Rubric §24, Forms, Validation & UX Safety]shows up in two flags:LoadFailed(line 55), because a failed fetch renders zero rows, which is visually identical to a genuinely empty list once the error toast expires, andEmptyConfirmed(lines 66-68), true only when the NEWEST load completed withTotalItems == 0, because the loading state ends and renders before MudDataGrid has received the rows. Many of the members below carry an inline diagnosis of the E2E-discovered defect they fix, touching[Rubric §28, Front-End Testing]. - Walkthrough, in teaching order (lines are in
DataGridListPageBase.csunless the column-filter file is named):- Abstract and virtual surface: derived pages supply the abstract
Title(line 72) and may overrideSaveFilters/RestoreFilters(lines 191, 194),GridRef(line 204),MobileListRef(line 214, the page's card list),OnRestoredStateAppliedAsync(line 755),OnBeforeFetchAsync(line 1077),OnMobileDataRequestedAsync(line 1999), and the three virtualization knobsVirtualizeGrid(line 227, defaultfalse),VirtualizedGridHeight(line 235, default70vh) andVirtualizedItemSize(line 243, default 52). - Public and protected state:
IsLoading(lines 42-44),LoadFailed(line 55),EmptyConfirmed(lines 66-68),IsMobile(line 75),IsLayoutKnown(line 87, surfaced through the explicitIListLayoutSourcemember at line 90), the mobile card-view blockMobileItems/MobileTotalItems/MobileCurrentPage/MobilePageSize(lines 93-96), the bindableCurrentPageState(line 103, 0-indexed),RowsPerPageState(line 113, defaulting to 10 to match MudDataGrid v9's own default), andDenseGrid(line 122).IsLoadingis computed asfield || !RendererInfo.IsInteractive(line 44): always true during the non-interactive SSR prerender pass, because the grid fetches fromOnAfterRenderAsync, which a static render never reaches.EmptyConfirmedis its mirror image,field && RendererInfo.IsInteractive(line 68).IsLayoutKnownstays false until the first viewport notification setsIsMobile: its summary (lines 77-86) records that rendering a layout before then took the desktop grid, which a phone swapped for the card list, fetching twice and shifting everything below the list (CLS 0.3 to 0.44, X-17), soListPageShell<TItem>renders a viewport-high placeholder and fetches nothing until it is true. - Constants (lines 128, 132):
PrerenderFetchTimeoutMs = 5000bounds the SSR fetch, andVirtualizedScrollContainerSelector = ".mud-table-container"records where a virtualized grid actually scrolls. - Private fields (lines 134-182): the nullable CTS, the
_disposedguard, the scroll module and itsDotNetObjectReference, the persistence subscription, the prerender caches,_newestPagedLoad(line 142), the saved-state mirrors,_restoredPagePending(line 153),_restoredSortPending(line 160, so a restored sort wins over the default column sort every page seeds),_shadowedGridSort(line 163),_restoreGridWhenRendered(line 168, set both on widening and when the first-render setup finds no grid yet), the_layoutRenderPending/_setupWaitsForLayoutRenderpair that parks the first-render setup until the layout render has run,_navigatingAway(line 179), the re-entrancy and deferral flags, and a per-instance_scrollTrackerId(line 182). The observer contract'sIdandResizeOptions(a 250 ms report rate) sit at lines 185 and 188. OnInitialized(from line 252), synchronously: restores anyPersistedGridStateunder the keygrid:{GetType().FullName}(line 258); registers the persisting callback with an explicitRenderMode.InteractiveAuto(line 284); pins_ownRoutePathto this page's route (line 291); reads the URL throughListPageQueryStateService, falling back to the in-memoryListPageStateServicesnapshot; primes the pager, sort, density and page filters, and takes the restored column filters (RestoreColumnFilters, line 317) so the grid's firstServerDatacall already fetches the right rows.OnLocationChanged(from line 339): does nothing once the page is navigating away (line 349), reacts only to same-path back/forward navigation (anOrdinalpath compare, line 357), re-reads the URL (including column filters, line 380), and hands off toReloadActiveLayoutAfterNavigationAsync(line 401): on a phone with a card list it reloads the way a filter change does, throughReloadActiveLayoutAsync; otherwise the grid takes the URL's page, column filters (line 419) and sort and reloads.IsEchoOfSavedState(line 1948) recognizes a location that carries exactly the query the last save wrote.ApplyCurrentPageFromUrl(line 435) is BL0005-suppressed (line 434).- Viewport (
NotifyBrowserViewportChangeAsync, line 444): recomputesIsMobilefromBreakpointConstantsand, on the first notification, setsIsLayoutKnown(line 452) and marks the render it queues as the layout render. When the viewport widens from the card list back to the grid,PrepareGridRestoreAfterWidening(line 473) seeds the newly created grid from the saved pager and sort, because the new grid starts on page 1 at the default page size and sort. - First render:
OnAfterRenderAsync(line 500) awaitsRunFirstRenderSetupAsync(line 554) on the first render andOnLaterRenderAsync(line 532) after that. The setup subscribes to the viewport first (SubscribeToViewportAsync, line 679), because that first notification picks the layout aListPageShellholds back; when the notification queued a layout render, the setup parks (_setupWaitsForLayoutRender, line 571) andOnLaterRenderAsyncresumes it once the grid or card list has mounted.ContinueFirstRenderSetupAsync(line 582) then hydrates session state (ApplyHydratedStateAsync, line 638), checks_disposedafter each interop round trip, starts scroll tracking (StartScrollTrackingAsync, line 695, importing./_content/MMCA.Common.UI/list-page-scroll.jsat line 701), restores the grid state and awaitsOnRestoredStateAppliedAsync.OnLaterRenderAsyncalso puts the saved pager and sort on a grid that has just been created when_restoreGridWhenRenderedis set.ReleaseLateFirstRenderSetupAsync(line 763) andReleaseScrollTrackingAsync(line 779) release what the setup created when the page went away mid-setup; JS calls back into[JSInvokable] OnScrollPositionChanged(line 820). - Pager and sort restore:
RestoreCurrentPageAfterRowsPerPageReset(line 844, BL0005-suppressed at line 843) works around the MudDataGrid v9RowsPerPagesetter that resetsCurrentPage.ApplyRestoredState(line 882) feeds the column filters too (line 895).RestoreGridStateAsync(line 905) is the single entry point for the pager-restore machinery, thenApplyRestoredSortOrReloadAsync(line 955) puts the restored column filters on the grid (line 964) and the restored sort throughRestoreSort(line 974) andApplyRestoredSortToGridAsync(line 989). The latter's summary gives the reason: every list page seeds a default column sort, so without it a shared?s=Name&sd=desclink was rewritten to the default on first load. - Column-filter persistence (
DataGridListPageBase.ColumnFilters.cs): the grid's own column filters are saved with the rest of the list state (URLc:keys, in-memory state andsessionStorage) and put back on the grid on restore, so a filter survives opening a row and pressing Back, a refresh and a shared link (content comment, lines 7-12).RestoreColumnFilters(line 29) takes the restored set and marks it pending;ResolveColumnFilters(line 49) is what a fetch sends and saves: while a restore is pending (or was pending when the fetch started, therestorePendingAtLoadStartparameter) it builds the restored definitions against the rendered grid, otherwise it uses the grid's own.ApplyRestoredColumnFiltersToGrid(line 75) replaces the grid'sFilterDefinitionsdirectly rather than throughAddFilterAsync, so the filter panel stays closed and no load starts.SnapshotColumnFilters(line 92) writes values in the invariant culture throughFormatFilterValue, andBuildColumnFilterDefinitionsdrops a saved filter whose column the grid does not render or allow filtering on, or whose value no longer parses (TryParseFilterValueandTryParseDateOrNumber: string, bool, enum, Guid,DateOnly,DateTimeround-trip, then numbers throughConvert.ChangeType). - Paged loads:
LoadServerDataAsync(line 1051, remarks at lines 1041-1050) startsLoadPagedAsync(line 1137), records it in_newestPagedLoadbefore anything yields, and returnsNewestPagedResultAsync(line 1187), so overlapping calls end on the NEWEST call's rows, never a superseded call's empty cancelled page (MudDataGrid applies whicheverServerDatacall completes last).FetchPagedAsync(line 1204) holds the fetch, awaitingOnBeforeFetchAsyncand sending the resolved column filters;FetchWithinRangeAsync(line 1265) fetches the last page instead when the requested page lies past the end, andMovePagerToRows/MovePagerTo(lines 1307, 1321) put the pager on the page the returned rows belong to. OnBeforeFetchAsync(line 1077): aprotected virtualhook awaited by every loader and by every delegateMobilePageFetcherbuilds, before the filter bag is built, so a page that must wait for state its filter callback reads (a picker's options loading) waits in one place. The default does nothing; a throw inside a grid loader is reported like a throwing fetch.MobilePageFetcher(line 1101): turns the grid's fetch delegate and filter callback into theFetchPageResultdelegate aMobileInfiniteScrollList<TItem>takes, so one fetch method serves the grid and the phone list. It applies an optional default sort and an optionalafterFetchAsyncstep, and returns theResultunchanged (no toast, no page state change), because the list owns retry and error display.- Virtualized and mobile loads:
LoadVirtualizedServerDataAsync(line 1356) maps the row window MudBlazor asks for onto the same page-based fetch throughComputeVirtualWindow(line 1538,internal staticso the tests drive it directly).LoadMobileDataAsync(line 1577) is the card-list equivalent, withClearMobileItems(line 1628) as its page-1 failure shape. - One fetch pipeline:
RunFetchAsync<TResult>(line 1453) sits behind the paged, virtualized and mobile loaders. It takes the load's own source rather than re-reading_cts, sets and clears the loading and failure flags, runs the caller's fetch inside thetryso a throw from page code cannot strandIsLoading, and toasts the localizedGrid.Snackbar.LoadCancelled(line 1481) only for a current, undisposed load.FailedFetch<TResult>(line 1516) is theResult-branch counterpart, andEmptyGridData(line 1523) the empty shape.CreateFetchCts(line 1560) links the load's lifetime token, the caller's token, and the 5 s prerender timeout during non-interactive rendering. - Load identity:
ResetCancellationTokenAsync(line 1639) swaps in a fresh CTS first and returns the source it swapped in.IsCurrentLoad(line 1673) isReferenceEquals(loadSource, _cts), andThrowIfSuperseded(line 1680) ends a superseded load on the silent cancellation path. - Filters and sort:
ExtractGridFilters(line 1699) flattens the grid's filter definitions one entry per column throughEffectiveColumnFilters(line 1715);ApplyAdditionalFilters(line 1733) runs the page's callback without letting it overwrite a grid key, moving a clashing value toQueryFilterKeys.Alias(key, QueryFilterKeys.SearchTag).ExtractSortParameters(line 1757) andResolveSortParameters(line 1770) pick the sort, letting a pending restored sort win over the grid's seeded default. - Saving state:
SaveCurrentState(line 1822) also takes the column filters to save, falling back to the stored entry's and then the restored set.SaveFilterState(line 1869) saves the page's filters keeping pager and sort, andReloadActiveLayoutAsync(mobileList)(line 1879) reloads whichever layout is rendered: on a phone it saves the filters first and resets the card list from page 1 (the list's fetch saves nothing, so a filter changed there was otherwise lost on leaving); otherwise it reloadsGridRef.ToggleDensity/PersistDensity(lines 1895, 1916) andResolvePagerState(line 1907) complete the persistence. - Route pinning, leaving and teardown:
_ownRoutePath(line 1939),GetRoutePath()(line 1941) andIsOwnRouteCurrent()(line 1967, false once_navigatingAwayis set, line 1968, then anOrdinalIgnoreCasecompare at line 1969) drop a stale write after navigation.NavigateAway(uri, forceLoad, replace)(line 1987) is what a derived page calls instead ofNavigationManager.NavigateTowhen it redirects in response to a same-route navigation: it sets_navigatingAway, so the base neither reloads on that location change nor mirrors its state to the URL, because the base's replace navigation, landing after the redirect, cancelled it (summary, lines 1971-1979, A-23).CancelLoading(line 2001) is the manual cancel hook.DisposeAsync(line 2004),Dispose(bool)(line 2032),UnsubscribeLocationChanged(line 2048) andDispose(line 2057) release the subscription, the scroll module and the CTS,_disposed-idempotent.PersistedGridStatecloses the file at line 2067.
- Abstract and virtual surface: derived pages supply the abstract
- Why it's built this way: every concern here was independently re-implemented (and re-broken) on individual pages before being lifted into one base, so a single fix now propagates to every list page at once. The four-channel persistence covers how a user can leave and return to a list (browser back, in-app navigation, refresh or
forceLoad, a shared link), and the column filters and restored sort now travel the same way, so none of those paths silently drops part of what the user set. The delegate signature mirrorsIEntityService<TEntityDTO, TIdentifierType>.GetPagedAsyncexactly (remarks at lines 1041-1050), so a page passes a method group with no adapter. The column-filter logic lives in its own partial file to keep the main file's concerns readable. The phone reload moved here fromListPageActionsbecause it must save the page's filters, which a static helper cannot read. - Where it's used: base class for the list pages in both apps, including ADC's
PublicSessionListViewandPublicSessionList(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Public/Sessions/), ADC'sEventFilteredListPageBase(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Common/EventFilteredListPageBase.cs), and Engagement'sAttendeeSearchPanel(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Pages/CheckIns/AttendeeSearchPanel.razor.cs); Common'sListPageShellandInfiniteScrollSentinel(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Lists/) reference it. Covered by bUnit tests atMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/DataGridListPageBaseTests.csand, beside it,DataGridListPageBaseLifecycleTests.cs,DataGridListPageBaseFilterStateTests.csandDataGridListPageBaseMobileFetchTests.cs, plus the conformance probeConformance/ProbeListPage.cs. - Caveats / not-in-source: three BL0005-related members set
grid.CurrentPagefrom outside the component (justifications inlined at lines 434 and 843). The prerender optimization assumes a warm backend; under a cold one the prerender fetch times out at 5 s and the interactive pass refills the grid. Thelist-page-scroll.jsmodule andListNoRecordsContentare referenced here only by name, so their behavior is not verifiable from these.csfiles. The route comparison isOrdinalinOnLocationChanged(line 357) butOrdinalIgnoreCaseinIsOwnRouteCurrent(line 1969); the source does not state why the two differ.
TwoFactorEnrollmentPanel
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Auth.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/TwoFactor/TwoFactorEnrollmentPanel.razor.cs:17· Level 4 · class (sealed, partial)
- What it is: the code-behind of the panel shown in the
Enrollingstate ofTwoFactorAccount: it displays the authenticator secret the enrollment call returned and asks for a code to confirm it (class TwoFactorEnrollmentPanel : IDisposable, line 17; ADR-116). - Depends on:
ITwoFactorUIService(ConfirmEnrollmentAsync),LoginRefusals(HasCode,Describe),AuthErrorCodes(TwoFactorRecentSignInRequired,MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthErrorCodes.cs:66),TwoFactorSetupResponseandTwoFactorRecoveryCodesResponse,ComponentLifetimeExtensions, andIStringLocalizer<SharedResource>. External: MudBlazor'sMudTextField<string>. - Concept introduced, a child component that reports outcomes upward.
[Rubric §18, UI Architecture & Component Design]assesses whether a component owns one step and hands its result to the parent: the panel never changes the page's state itself, it raises one of three callbacks.[Rubric §11, Security]applies to the recent-sign-in refusal path. - Walkthrough:
- State (lines 19-26): a page-scoped
_cts, the code field ref, the entered_code,_errorMessage, and the_isBusy,_focusedand_disposedflags. - Parameters:
Setup(line 31,[EditorRequired]), and the callbacksOnConfirmed(line 35, carrying the recovery codes),OnCancelled(line 39) andOnRecentSignInRequired(line 46, raised when the API refuses because the session did not sign in recently). GroupedKey(lines 53-55): the shared key in groups of four, which is how authenticator apps ask for it.Dispose(lines 58-68): idempotent; cancels and disposes_cts.OnAfterRenderAsync(lines 71-79): moves focus to the code field once, because the panel replaces the "set up" button in place.ConfirmAsync(lines 81-119): an empty code setsAuth.Login.SecondFactor.CodeRequiredand stops (lines 86-90); otherwise it callsConfirmEnrollmentAsync(code, _cts.LifetimeToken())(line 95). Success raisesOnConfirmedwith the codes (line 98); a refusal carrying the sharedAuthErrorCodes.TwoFactorRecentSignInRequiredcode (line 102) raisesOnRecentSignInRequired(line 104); any other failure clears the code and showsLoginRefusals.Describe(...)withAuth.TwoFactor.GenericErroras the fallback (line 109). A cancellation is swallowed onlywhen (_disposed)(line 111), and thefinallyclears_isBusy(line 117).
- State (lines 19-26): a page-scoped
- Why it's built this way: keeping the confirm call in the panel and the state machine in the page means the page's
TwoFactorPageStatetransitions stay in one file, while the panel owns its own in-flight call and cancels it on its own disposal. - Where it's used: rendered by
TwoFactorAccount, which handles its callbacks inOnEnrollmentConfirmed,OnEnrollmentCancelledandOnRecentSignInRequired(TwoFactorAccount.razor.cs:191,:200,:206). - Caveats / not-in-source: how the QR code and
GroupedKeyrender, and how_isBusydisables the form, are markup inTwoFactorEnrollmentPanel.razor, not verifiable from the.csfile.
MudTranslations
MMCA.Common.UI ·
MMCA.Common.UI.Resources·MMCA.Common/Source/Presentation/MMCA.Common.UI/Resources/MudTranslations.cs:10· Level 0 · class (sealed)
- What it is: an empty marker class that anchors a
.resxresource pair for MudBlazor's own built-in component text: the data-grid pager and filter menus, pickers, table editing, pagination, snackbar and alert close buttons, and input adornments (ADR-027). - Depends on: nothing first-party. The type has no members: it is the single declaration
public sealed class MudTranslations;(line 10). Its meaning comes from its co-located resources, whose keys mirror MudBlazor's ownLanguageResourcekeys (v9.6.0) with the English values copied verbatim so en-US behavior is unchanged, and fromResxMudLocalizer, which injectsIStringLocalizer<MudTranslations>and hands those strings to MudBlazor's localization interceptor. - Concept reinforced, the resource-anchor type. The idiom is introduced in full at
SharedResource: ASP.NET Core'sIStringLocalizer<T>resolves keys against the.resxwhose base name matchesT, so a dedicated empty class becomes the name of a shared string table.MudTranslationsis the second anchor, scoped to third-party chrome rather than app chrome.[Rubric §27, Internationalization]assesses whether all user-visible copy follows the active culture, including the component library's;[Rubric §20, Design System & Theming]assesses a coherent design system, and a pager that still reads "Rows per page" under anesUI would break that coherence at exactly the surface the user interacts with most. - Walkthrough: there are no members. The whole contract is "be a public sealed type named
MudTranslationsin this namespace, with sibling.resxfiles whose keys match MudBlazor'sLanguageResource". The doc comment (lines 3-9) records the verbatim-English-mirror invariant. - Why it's built this way: MudBlazor exposes exactly one extension point for translating its built-in strings (an injectable
MudLocalizer), and it needs some resource base to read from. A separate anchor keeps the library's keys in their own table, mirroring the upstream names one to one, cleanly apart from the app's ownSharedResourcechrome. This is the ADR-027 way to translate a dependency you do not own. - Where it's used: injected as
IStringLocalizer<MudTranslations>byResxMudLocalizer, whichAddUISharedregisters as MudBlazor'sMudLocalizerviaTryAddTransient(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:130). Because resolution flows through the DIIStringLocalizerFactory, thePseudoStringLocalizerFactorydecorator registered atMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:124reaches these strings too. - Caveats / not-in-source: the
.resxfiles and their per-key match to MudBlazor v9.6.0'sLanguageResourceare resources, not.cs; individual key contents are not enumerated here.
PhoneDeliveryLine
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Notifications/NotificationList.razor.cs:114· Level 0 · record (private, sealed, nested in NotificationList)
- What it is: one already-localized line of the "Phone" column on the push-notification history page: the text of a per-platform native delivery outcome plus the MudBlazor chip color and icon that go with it. It is declared as
private sealed record PhoneDeliveryLine(string Text, Color Color, string Icon);(line 114), so nothing outside NotificationList can see it. - Depends on: nothing first-party in its shape. Externals:
MudBlazor(Color, and theIcons.Material.Filledstring constants its producers pass in). - Concept reinforced, the text carries the meaning. The doc comment on the record (line 113) states the rule: the text carries the status, so color and icon are never the only cue.
[Rubric §21, Accessibility]assesses whether information survives without color (WCAG 1.4.1, use of color); here a green check, an amber warning and a red error each come with a sentence such as "Android: delivered (1 of 1 batch)", so a screen-reader user or a color-blind operator reads the same outcome. The markup comment repeats the rule where the chip is rendered (NotificationList.razor:96-98). - Walkthrough: a positional record with three members.
Textis the finished sentence, built byAddPhoneDeliveryLinefrom the localizedNotif.Phone.LineorNotif.Phone.LineNoUnitformat (NotificationList.razor.cs:95-97) or, for an unattributed failure, fromNotif.Phone.StatusOnly(line 74).ColorandIconcome fromPhoneDeliveryStatus(lines 101-111):SuccesswithCheckCirclewhen every attempted unit was delivered,WarningwithWarningwhen some were,ErrorwithErrorwhen none were. - Why it's built this way: a private record keeps the three values that must travel together in one immutable value, without adding a public type to the package surface for what is purely a rendering detail of one page.
- Where it's used: produced only by
NotificationList.PhoneDeliveryLinesandAddPhoneDeliveryLine(NotificationList.razor.cs:67-99) and consumed only by the Phone cell of the history table, which renders one outlinedMudChipper line, or-when the list is empty (NotificationList.razor:99-112).
SharedResource
MMCA.Common.UI ·
MMCA.Common.UI.Resources·MMCA.Common/Source/Presentation/MMCA.Common.UI/Resources/SharedResource.cs:9· Level 0 · class (sealed)
- What it is: an empty marker class that anchors
IStringLocalizer<SharedResource>over its co-located.resxfiles, the single home for cross-cutting UI chrome strings (ADR-027). - Depends on: nothing first-party. The type is empty:
public sealed class SharedResource;(line 9). Its meaning comes from the co-located resourcesSharedResource.resx(the English default) andSharedResource.es.resx(Spanish), named in the doc comment (line 7), and from the ASP.NET Core localization stack that bindsIStringLocalizer<T>to the.resxnamed afterT. - Concept introduced, the resource-anchor type.
[Rubric §27, Internationalization]assesses whether user-facing copy is externalized to per-culture resources keyed stably rather than hard-coded. ASP.NET Core'sIStringLocalizer<T>convention resolves keys against the resource file whose base name matches the typeT, so a dedicated empty class becomes the name that ties many components to one shared string table: injectingIStringLocalizer<SharedResource>anywhere reads the same dotted, stable keys (Common.Error.Load,Grid.Snackbar.LoadCancelled,Auth.Sessions.Title). The doc comment (lines 3-8) enumerates the chrome it covers: buttons, layout labels, snackbar and error templates, and the culture- and theme-switcher text. Its counterpart for library chrome isMudTranslations. - Walkthrough: there are no members. The whole contract is "be a public sealed type named
SharedResourcein this namespace, with sibling.resxfiles". The work lives in the key/value pairs and in the localization middleware that resolves them by culture. - Why it's built this way: a marker type is the idiomatic ASP.NET Core way to scope a shared resource table without inventing a real class, and one anchor keeps the chrome strings in a single table every component shares (ADR-027).
- Where it's used: injected as
IStringLocalizer<SharedResource>byDataGridListPageBase<TDto>for its cancellation toast and itsResulterror rendering (DataGridListPageBase.cs:27), bySessionsfor every label on the devices page (Sessions.razor.cs:35), by the auth pages for their field labels and messages, and handed toErrorMessages.Configurefrom the root layout (MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/MainLayout.razor:103) so the static helper resolves the same table. - Caveats / not-in-source: the
.resxfiles are resources, not.cs; their per-key contents are not enumerated here.
AuthFieldMessages
MMCA.Common.UI ·
MMCA.Common.UI.Resources·MMCA.Common/Source/Presentation/MMCA.Common.UI/Resources/AuthFieldMessages.cs:19· Level 1 · class (internal static)
- What it is: a static lookup of the localized validation messages the auth page models attach to their form fields (first name, last name, email, password, confirm password, token), resolved from the shared resource table.
- Depends on:
SharedResourceonly, as the type that names the.resxtable; it builds aResourceManagerovertypeof(SharedResource).FullNameandtypeof(SharedResource).Assembly(line 21). - Concept: the validation-attribute counterpart to injecting
IStringLocalizer<SharedResource>. A DataAnnotations attribute on a model property needs its message at attribute-evaluation time, where there is no DI container to inject a localizer from, so the messages are static properties read through aResourceManageron demand. Each property is a one-lineGet("Auth.Field.<Field>.<Rule>")call (lines 24-42):FirstNameRequired,LastNameRequired,EmailRequired,EmailInvalid,PasswordRequired,PasswordMaxLength,PasswordComplexity,ConfirmPasswordRequired,ConfirmPasswordMismatchandTokenRequired.[Rubric §27, Internationalization]assesses that user-facing copy is externalized to per-culture resources. - Walkthrough:
Get(line 44) callsResources.GetString(key, CultureInfo.CurrentUICulture)and falls back to the key itself when the entry is missing, so a missing translation shows a stable dotted key rather than throwing or rendering blank. Because it readsCurrentUICultureon every access, the message follows the active culture at the moment the validator runs. - Why it's built this way: keeping the auth messages in the same
SharedResourcetable as the rest of the chrome means one.resxpair per locale (ADR-027) rather than a second resource file just for validation text. The type isinternal, so it is an implementation detail of this assembly, not framework surface. - Where it's used: the auth page models
RegisterModel.cs(10 references),ResetPasswordModel.cs(9),LoginModel.cs(4) andForgotPasswordModel.cs(3), all underMMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/. - Caveats / not-in-source: the
Auth.Field.*keys live in theSharedResource.resxfiles, which are resources rather than.cs, so their per-key text is not enumerated here. How the model attributes bind to these properties (for example throughErrorMessageResourceType) is in the model files, not in this type.
NotificationSendModel
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Notifications/NotificationSendModel.cs:19· Level 1 · class (sealed)
- What it is: the two-property form model for the push-notification compose page. Its DataAnnotations are the single declaration of that form's field rules.
- Depends on: first-party: SendPushNotificationRequest (the endpoint contract, whose length constants it reuses, lines 23 and 28). Externals:
System.ComponentModel.DataAnnotations(RequiredAttribute,MaxLengthAttribute). It is consumed by NotificationSend through ModelValidation and DataAnnotationsModelValidator. - Concept introduced, one number shared by the cap, the message, and the server invariant. The lengths are not declared here.
MaxLength(SendPushNotificationRequest.TitleMaxLength)(line 23) andMaxLength(SendPushNotificationRequest.BodyMaxLength)(line 28) point at the shared request contract, which fixes them at 200 and 2000 (MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/PushNotifications/SendPushNotificationRequest.cs:15,21). The same constants drive the input cap and the character counter in the markup (NotificationSend.razor:49-50,61-62), and the server-side validator enforces the same numbers.[Rubric §24, Forms, Validation & UX Safety]assesses whether client and server agree. Here they cannot disagree, because there is one literal and everything else is a reference to it.[Rubric §9, API & Contract Design]assesses whether contract facts live with the contract; putting the length constants on the request record (the type the endpoint binds) rather than on the form model is what makes the sharing possible in the first place.[Rubric §27, Internationalization & Localization]: eachErrorMessageis a resource key ("Notif.Send.Field.Title.Required", line 22, and its three siblings), resolved by the page's localizing DataAnnotationsModelValidator per ADR-027. This is the concrete case the pass-through localization in that validator was designed for.
- Walkthrough: two mutable
stringproperties, both initialized tostring.Emptyso a fresh model binds cleanly.Title(line 24) carries[Required]with keyNotif.Send.Field.Title.Required(line 22) and[MaxLength(200)]with keyNotif.Send.Field.Title.MaxLength(line 23).Body(line 29) carries the matching pair,Notif.Send.Field.Message.Required(line 27) andNotif.Send.Field.Message.MaxLengthwith the 2000-character cap (line 28). - Why it's built this way: a settable class rather than a record with
initaccessors, because MudBlazor two-way binding (@bind-Value="_model.Title") writes back into the instance. It is a separate type from SendPushNotificationRequest because the form model is mutable and carries presentation rules, while the request record is the immutable wire contract; the page maps one to the other in a single line (NotificationSend.razor.cs:131). - Where it's used: held as
private readonly NotificationSendModel _model = new()by NotificationSend (NotificationSend.razor.cs:46) and bound by both fields in its markup.
NotificationInbox
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Notifications/NotificationInbox.razor.cs:28· Level 4 · class (partial, page)
- What it is: the code-behind for the per-user notification inbox, routed at both
@page "/notifications/inbox"and@page "/notifications/inbox/{Id:int}"(NotificationInbox.razor:1-2). It fetches the signed-in user's notifications a page at a time, renders each as a read or unread card, lets the user mark items read individually or all at once, highlights and scrolls to a deep-linked notification, and reloads the current page when a real-time push asks for a refresh. A failed load is also rendered inline: anErrorSummarybound to the last outcome, plus a Retry button when the list is empty (NotificationInbox.razor:17,40-47). - Depends on: first-party: INotificationInboxUIService (the typed read-side HTTP service), NotificationState (the per-circuit unread-count store and refresh signal), UserNotificationDTO (the row shape), IToastService (the toast abstraction), ResultUiExtensions (the
NotifyOnFailurehelper), SharedResource (the resx anchor for the localizer), ViewerTimeZone (the viewer's clock for sent times, resolved after first render), and ComponentLifetimeExtensions (theLifetimeTokenread). Externals:MudBlazor(IScrollManager,ScrollBehavior,BreadcrumbItem,Icons),Microsoft.AspNetCore.Components([Inject],[Parameter],OnInitializedAsync,OnParametersSet,OnAfterRenderAsync,InvokeAsync,StateHasChanged),Microsoft.Extensions.Localization(IStringLocalizer<T>), BCLCancellationTokenSource,IDisposable,Math.Ceiling,CultureInfo.InvariantCulture. - Concept introduced, the Blazor code-behind page pattern (
.razorplus.razor.cspartial class). The three notification pages in this unit are authored as partial classes split across two files: the.razorholds declarative MudBlazor markup and the routes, the.razor.csholds the C# (public partial class NotificationInbox, line 28), the injected services, the view state, and the handlers. The framework constructs the component, callsOnInitializedAsync(line 79, which returns the load task directly rather than beingasync) once, and re-renders when a handler mutates a field. Four habits recur across all three pages and are worth learning once here:- Disposal-safe async with a per-component
CancellationTokenSource. Areadonly CancellationTokenSource _cts(line 48) is created with the component and its token is read through_cts.LifetimeToken()(ComponentLifetimeExtensions) and passed to every service call (lines 115, 227, 291, 306, 327). Reading.Tokenoff a disposed source throwsObjectDisposedException, soLifetimeTokenreturns an already-cancelled token instead and the work stops through the normalOperationCanceledExceptionpath (ComponentLifetimeExtensions.cs:3-10,26-31).Dispose(bool)(lines 358-370) cancels and disposes it behind the classic_disposedguard (line 356). Every async handler swallowsOperationCanceledExceptionsilently (for example lines 251-254) because that is the expected outcome when the user navigates away mid-fetch. - Result-typed failures, not exceptions. The service calls return a
Result, so the page branches onTryGetValue(line 229) and routes the failure throughresult.NotifyOnFailure(Toast, L)(line 248). A failure now has two surfaces: the toast, and the last outcome kept in_loadResult(line 62) for an inlineErrorSummaryplus a Retry button. The list is left as it was rather than blanked, so a transient failure does not erase what is on screen. - Busy flags gate the UI.
IsLoadingandIsSaving(lines 54-55) areprotectedwith private setters; the markup shows progress while loading and setsDisabled="IsSaving"on the action controls (NotificationInbox.razor:18) so a double click cannot double-post. - Push-driven refresh via an event subscription.
OnInitializedAsyncsubscribes toNotificationState.OnRefreshRequested(line 89) andDispose(bool)unsubscribes (line 364). [Rubric §19, State Management & Data Flow]assesses where state lives; transient view state stays in private fields (_notifications,_currentPage,_totalPages,_loadResult, lines 57-62) while the shared unread count is written back into the scoped NotificationState (lines 309, 343) and its refresh signal is read. Local stays local, shared stays shared.[Rubric §25, Navigation, Routing & Information Architecture]assesses route structure. The second@pagedirective is a typed deep link: a push payload or an email can point straight at one notification. The class doc (lines 19-25) states the two design rules that follow from it: the:introute constraint is the validation boundary, so a malformed id never reaches the component (the router rendersNotFoundinstead), and an id that is simply not on the loaded page degrades silently to the plain inbox rather than raising an error the user can do nothing about.[Rubric §21, Accessibility]: the icon-only mark-read control carries an explicit localizedaria-label(NotificationInbox.razor:66).[Rubric §27, Internationalization & Localization]: this page holds no literal English. The injectedIStringLocalizer<SharedResource> L(line 34) resolves the title (line 50), the breadcrumbs, and every toast (L["Notif.AllMarkedRead"], line 344). The breadcrumb trail is built insideOnInitializedAsync(from line 79), not in a field initializer, so the injected localizer is available and labels re-resolve per circuit under the active culture (comment in that method, citing ADR-027).
- Disposal-safe async with a per-component
- Walkthrough
PageSize(line 30) isconst int 20: fixed-size server-side pagination, not infinite scroll. InjectedInboxService,NotificationState,Toast,L, MudBlazor'sScrollManager, andViewerTime(lines 32-37).[Parameter] public int? Id(line 46) is the deep-link route parameter. The doc (lines 39-45) explains the type choice:UserNotificationIdentifierTypeis anintalias, and a route parameter's type must be written out for the:intconstraint to bind, so the parameter is declaredint?and converted where it is used.- Deep-link state is four separate fields, and each exists for a distinct reason (lines 67-77):
_highlightedId(found on the loaded page),_pendingScrollId(a scroll the next render owes),_scrolledId(already scrolled, so a re-render or push-driven reload never scrolls twice), and_appliedId(theIdthe state was last computed for, to detect a re-navigation). OnParametersSet(lines 100-109) clears the_scrolledIdlatch when_appliedId != Idand then recomputes the target. The doc (lines 94-99) records the bug this prevents: navigating from/notifications/inbox/5to/notifications/inbox/9reuses the component instance, so without clearing the latch the second deep link would highlight but never move the viewport.OnAfterRenderAsync(lines 112-130) first resolves the viewer's time zone: on the first render, while the component is alive, it awaitsViewerTime.EnsureResolvedAsync(_cts.LifetimeToken())and callsStateHasChangedwhen the zone changed (lines 114-118), because sent times render on the viewer's clock and the zone is only readable once JS is available (comment above line 114). It is also the only place a scroll happens. It returns unless a scroll is pending and the component is alive, clears_pendingScrollIdand sets_scrolledIdbefore the await (comment, line 125, so a re-entrant render cannot queue the same scroll twice), and callsScrollManager.ScrollIntoViewAsync(CardSelector(id), ScrollBehavior.Smooth)(line 129).ApplyDeepLinkTarget(lines 138-152) matches the route id against what the loaded page actually holds:Id is not { } id || id <= 0 || !_notifications.Exists(n => n.Id == id)clears both the highlight and the pending scroll (lines 140-145). The doc (lines 132-137) is the "no toast" decision, a deep link the user cannot act on is not an error they caused.- The card-chrome helpers:
IsDeepLinkTarget(line 154);CardElementId(lines 156-159, formattingnotification-{id}withCultureInfo.InvariantCulturebecause it becomes a DOM id) andCardSelector(line 161);CardElevation(from line 164, 4 when deep-linked, else 1 for unread and 0 for read);CardClass(from line 181), which emits only state classes (notification-card,readorunread, plusdeep-linked). The chrome those classes select lives inwwwroot/app.css(.notification-card.unreadand.notification-card.deep-linked,app.css:519,523), built from MudBlazor palette tokens only so both themes stay legible: a primary left border marks unread, a secondary-colored ring plus a faint surface tint marks the deep link (doc aboveCardClass).[Rubric §20, Design System & Theming]shows up here: the page builds no inline styles, so its colors come from the theme's tokens in one stylesheet. - Push coalescing.
HandleRefreshRequested(lines 189-197) isEventHandler-shaped so it cannot beasync Task; it discards intoInvokeAsync(RefreshFromPushAsync)(line 196).RefreshFromPushAsync(lines 199-216) sets_refreshPending = trueand returns when a load is already in flight (from line 206); the comment beside it states the invariant, never drop the push, so overlapping pushes coalesce into exactly one trailing reload instead of vanishing. LoadNotificationsAsync(lines 218-274) returnsTask<bool>(true when the page loaded) and starts by settingIsLoading(line 223). It clears_loadResult, callsGetInboxAsync(_currentPage, PageSize, _cts.LifetimeToken())(line 227) and stores the outcome in_loadResult(line 228) so the markup can show a failure inline. On success (line 229) it materializespage.Items, computes_totalPagesfrompage.PaginationMetadata.TotalItemCountwithMath.Ceiling(line 233) clamped to a floor of 1 so an empty inbox never renders a zero-page pager, then recomputes the deep-link highlight (only a successful load can decide whether the id is present). A failure goes throughresult.NotifyOnFailure(Toast, L)(line 248). The tail (from line 263) drains_refreshPendingwith one moreRefreshFromPushAsync; the flag is cleared first (line 265), so a push arriving during this reload queues one more and no further.OnPageChangedAsync(int page)(lines 276-284): remembers the previous page (line 278), records the new one, reloads, and restores the previous page number when the load failed (lines 280-282), because a failed load keeps the previous page's rows on screen and the pager must point back at the page those rows belong to.MarkReadAsync(UserNotificationDTO)(lines 286-320): callsMarkReadAsync(notification.Id, _cts.LifetimeToken())(line 291), returns early on failure after a toast, then optimistically patches local state, locating the row withFindIndex(line 299) and replacing it via arecord with-expression,notification with { IsRead = true, ReadOn = DateTime.UtcNow }(line 302). It then refetches the authoritative unread count (line 306) and pushes it intoNotificationState.SetUnreadCountonly when the count call succeeded (lines 307-310); a failed count means "unknown", so the badge keeps its value.MarkAllReadAsync(lines 322-354): one service call (line 327), a loop flipping every unread row in place (line 339), thenSetUnreadCount(0)(line 343) and a localized success toast (line 344).- Disposal:
_disposed(line 356),Dispose(bool)(lines 358-370) unsubscribing the refresh event (line 364) and cancelling the_cts(line 365),Dispose()(lines 372-376) withGC.SuppressFinalize(line 375).
- Why it's built this way: the page is a thin view over INotificationInboxUIService, so all HTTP and JSON live in the service and the component stays testable against a stub. Patching local state after a mark-read (rather than refetching the page) keeps the interaction snappy while still reconciling the shared badge from the server, and the coalescing refresh keeps the list current when pushes arrive in bursts. The deep-link machinery is worth reading as a case study in idempotent side effects: a scroll is a one-shot action in a component model that re-renders freely, so it needs the "owed" and "already done" flags to be correct under re-render, re-navigation, and disposal.
- Where it's used: rendered at
/notifications/inbox(and/notifications/inbox/{Id:int}) for authenticated users; the route constant and nav entry come from NotificationRoutePaths and NotificationUIModule. NotificationBell reads the same NotificationState this page writes, and the layout-mountedNotificationListenerraises theOnRefreshRequestedsignal it consumes. Its admin siblings are NotificationList and NotificationSend.
NotificationList
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Notifications/NotificationList.razor.cs:22· Level 6 · class (partial, page)
- What it is: the code-behind for the admin/organizer push-notification history page, routed at
@page "/notifications"(NotificationList.razor:1). It loads previously sent broadcasts and renders them in a status table (title, recipients, status, phone delivery, sent time;NotificationList.razor:70-74), with a button onward to the compose page. It renders only for an account holding thenotifications:managepermission claim; any other account gets the 403 view and the history endpoint is never called (field comment, lines 36-39). - Depends on: first-party: IPushNotificationUIService (the send and history HTTP service), PushNotificationDTO (the row shape, carrying status, recipient count, and the per-platform native counts
AndroidSent,AndroidFailed,AppleSent,AppleFailedplusNativeDeliveryUnit,MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/PushNotifications/PushNotificationDTO.cs:32-47), PhoneDeliveryLine (its private phone-cell line record), NotificationRoutePaths (the route constants), IToastService, ResultUiExtensions (NotifyOnFailure), and SharedResource. Externals:MudBlazor(BreadcrumbItem,Icons,Color),Microsoft.AspNetCore.Components(NavigationManager,[Inject]),Microsoft.Extensions.Localization. - Concept reinforced, the same code-behind shape as NotificationInbox. Same
[Inject]service set (lines 26-30), samereadonly CancellationTokenSource _ctsplus dispose pattern (lines 34, 192-211), sameIsLoadinggate (line 45), same cancellation-swallowing load, sameresult.NotifyOnFailure(Toast, L)failure surface (line 162), sameTask<bool>load plus revert-on-failureOnPageChangedAsync, and the same inline_loadResultoutcome. It differs mainly in what it loads and who may see it.[Rubric §25, Navigation, Routing & Information Architecture]assesses route structure and inter-page flow; navigation goes through NotificationRoutePaths constants (NavigateToSendtargetsNotificationRoutePaths.NotificationSend, line 190) rather than a literal URL, so a route change happens in exactly one file.[Rubric §27, Internationalization & Localization]picks up an extra trick here:DisplayStatus(string status)(lines 55-59) looks upL[$"Notif.Status.{status}"]and falls back to the raw wire value whenlocalized.ResourceNotFound(line 58). The comparison value stays the untranslated wire string while only the displayed chip text localizes, which keeps transport values and presentation separate and means a newly added server status renders (untranslated) instead of blanking (the comment above it cites ADR-027). This is the same pass-through-on-unknown-key discipline that DataAnnotationsModelValidator applies to error messages. The phone column applies it once more to the delivery unit: the unit word is looked up asNotif.Phone.Unit.{unit}.Oneor.Other, chosen by whether the attempted count is 1, and an unknown unit name drops the word (theNotif.Phone.LineNoUnitformat) rather than show a raw key (lines 92-97).- Concept introduced, the per-platform native delivery outcome (ADR-044). Each history row shows, per platform the native (OS-level) leg counted, a status-first line with the unit explicit, for example "Android: delivered (1 of 1 batch)" (doc comment, lines 61-66). The point is operator feedback: a sender learns whether the phones actually received the broadcast, not only how many recipients were addressed. The status is derived from two nullable counts, so a platform with neither count recorded contributes no line, and a recorded unit with no per-platform counts at all is shown as one "Phones: failed" line, because that is a failure the sender could not attribute to a platform (FCM) (lines 63-65, 72-76). Each line is a PhoneDeliveryLine whose text, not only its chip color and icon, carries the status (
[Rubric §21, Accessibility]).
- Walkthrough
- Injected
NotificationService,NavigationManager,Toast,L,ViewerTime(lines 26-30) and a cascadingAuthenticationState(line 32);TitlereadsL["Notif.List.Title"].Value(line 41);_breadcrumbs(line 43) is built Home to Push Notifications inOnInitializedAsync(lines 126-130), with the leaf crumbdisabled: trueto mark the current page (line 129). _notificationsis anIReadOnlyCollection<PushNotificationDTO>initialized empty (line 47), alongside the paging state_currentPageand_totalPages(lines 48-49) and the last outcome_loadResult(line 52).PhoneDeliveryLines(PushNotificationDTO)(lines 67-79) builds the phone cell for one row: it callsAddPhoneDeliveryLinefor Android and then Apple with that platform's sent and failed counts and the row'sNativeDeliveryUnit(lines 70-71), and when neither produced a line but a unit was recorded it adds the single error line fromNotif.Phone.StatusOnly(lines 72-76). An empty list renders as-(NotificationList.razor:100-103).AddPhoneDeliveryLine(lines 81-99) returns when both counts are null, takesdelivered = sent ?? 0andattempted = delivered + (failed ?? 0)(lines 88-89), and formats the line.PhoneDeliveryStatus(lines 101-111) maps the two counts to a status key, color and icon:Notif.Phone.Deliveredwhenattempted == delivered, otherwiseNotif.Phone.PartlyFailedwhen anything was delivered andNotif.Phone.Failedwhen nothing was.OnInitializedAsync(lines 116-133) first reads the cascading auth state and sets_canManage = user.HasPermissionClaim(NotificationPermissions.Manage)(lines 118-119); when it is false it returns before building breadcrumbs or loading anything (lines 120-123), so the 403 view never triggers the history call. Otherwise it builds the breadcrumbs then awaitsLoadNotificationsAsync(line 132).OnAfterRenderAsync(lines 136-143) resolves the viewer's time zone on the first render throughViewerTime.EnsureResolvedAsync(_cts.LifetimeToken())and re-renders when it changed, because sent times render on the viewer's clock and the zone is only readable once JS is available.LoadNotificationsAsync(lines 147-174) returnsTask<bool>and loads one server page:GetHistoryAsync(_currentPage, PageSize, _cts.LifetimeToken())(line 153) withPageSize20 (line 24). It stores the outcome in_loadResult(line 154) for inline rendering, copieshistory.Itemsinto_notificationson success and sets_totalPagestoMath.Max(1, ceiling(TotalItemCount / PageSize))(line 158), then returns true; on failure it raises the localized toast (line 162) and returns false.OnPageChangedAsync(lines 180-188) records the page, reloads, and restores the previous_currentPagewhen the load failed (lines 184-187), so the pager stays on the page whose rows are still shown.NavigateToSend(line 190) sends the "send new" button to the compose page.- Disposal mirrors the family:
_disposed(line 192),Dispose(bool)cancelling the_cts(lines 194-205),Dispose()(lines 207-211).
- Injected
- Why it's built this way: broadcast history is paged on the server, 20 rows at a time (
PageSize, line 24), so the page never holds more than one window, and a failed load keeps the previous rows on screen while the pager reverts. Keeping HTTP behind IPushNotificationUIService mirrors the inbox and keeps the component a thin view. The shared[Rubric §18, UI Architecture & Component Design]story is told under NotificationInbox. - Where it's used: rendered at
/notificationsfor accounts holding thenotifications:managepermission (the nav entry from NotificationUIModule carriesRequiredPermission: NotificationPermissions.Manage,NotificationUIModule.cs:20); it links onward to NotificationSend. - Caveats / not-in-source: the page size (
PageSize, 20, line 24) is a client-side constant in this file; any server-side cap onpageSizeis not visible here.
NotificationSend
MMCA.Common.UI ·
MMCA.Common.UI.Pages.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Notifications/NotificationSend.razor.cs:23· Level 6 · class (partial, page)
- What it is: the code-behind for the compose-and-broadcast form, routed at
@page "/notifications/send"(NotificationSend.razor:1). It collects a title and a message into NotificationSendModel, validates them against that model's own annotations, sends one broadcast through the Notification API, reports the recipient count, and returns to the history page. - Depends on: first-party: IPushNotificationUIService (the
SendAsynccall), NotificationSendModel (the form model), ModelValidation + DataAnnotationsModelValidator (the validation bridge), INotificationScopeProvider (the targeting caption), SendPushNotificationRequest (the wire contract), PushNotificationDTO (the result carryingRecipientCount), Result, NotificationRoutePaths, ErrorMessages, IToastService, ResultUiExtensions, and SharedResource. The markup also composes anUnsavedChangesGuardbound toIsDirty(NotificationSend.razor:12). Externals:MudBlazor(MudForm,BreadcrumbItem,Icons),Microsoft.AspNetCore.Components(NavigationManager,OnInitialized,OnInitializedAsync),Microsoft.Extensions.Localization. - Concept introduced,
MudFormvalidation driven entirely by the model. This is the family's form page, and it is the worked example of the validation stack in this unit. The markup declares<MudForm @ref="_form" Model="_model">with two fields that setFor,Validation="@_validate", and read their affordances off the same model (NotificationSend.razor:43-66). No rule is declared in markup: the comment above the form (lines 38-42 of the markup) spells out the division,Requireddrives the asterisk andaria-requiredwhile its message still comes from the model,MaxLengthcaps the input, andCountershows the budget from the shared request contract so the numbers cannot drift from the server. The C# holds the form by reference (MudForm? _form, line 47) and explicitly drives validation before sending:await _form.ValidateAsync()then a guard on_form.IsValid(lines 122-129). MudForm has noOnValidSubmit, so that explicit pass is the gate (comment, lines 120-121).[Rubric §24, Forms, Validation & UX Safety]assesses input validation, double-submit protection, and feedback. All four are present: model-declared rules run through the shared delegate, anIsSavingflag (line 44) bound toDisabledon both buttons (NotificationSend.razor:73,80) so the send cannot be fired twice (backed in code by a re-entrancy guard,_form is null || IsSaving, raised before the first await at lines 109-113: each send mints its own idempotency key, so a second click that slipped in while the first was still validating would broadcast twice), a warning toastErrorMessages.ValidationErroron a failed gate (line 127), and a success toast naming the recipient count (line 137).- Two failure surfaces, deliberately not one.
_sendResult(line 53) holds the last attempt's outcome and is rendered inline by the sharedErrorSummarycomponent (NotificationSend.razor:36), while the toast stays the transient cue. The markup comment (lines 31-35) records the design constraint: the summary is deliberately not fedMudForm.Errors, because every field already renders its own message inline and MudBlazor contributes a generic "Required" of its own that would stack on top of the model's wording. The code repeats the point at the failed-validation branch (comment, lines 125-126): the per-field messages are already on screen, theErrorSummaryis deliberately not fed them, so the snackbar stays the summary cue._sendResultis nulled at the start of every attempt (line 118), so the summary never shows a stale failure. [Rubric §21, Accessibility]and[Rubric §18, UI Architecture & Component Design]meet in theErrorSummary: a failure that only appeared as a toast would time out on a long form and be unrecoverable for a screen-reader user who missed it (comment, lines 146-147).[Rubric §27, Internationalization & Localization]: every string resolves throughIStringLocalizer<SharedResource> L(line 28), including the success messageL.Plural("Notif.Send.SentTo", sent.RecipientCount, sent.RecipientCount)(line 137), which passes the count through the shared plural extension so the resource file (not C#) picks the plural form as well as the word order. As with its siblings the breadcrumb trail is built in an initialization hook, here the synchronousOnInitialized(lines 66-78, comment citing ADR-027).[Rubric §24, Forms, Validation & UX Safety]again, for the navigate-away guard:Sent(a private bool, set true immediately before the post-sendNavigateTo) andIsDirty(true wheneverSentis false and either field is non-blank) feed the markup'sUnsavedChangesGuard, so leaving with typed-but-unsent text prompts, while the send's own redirect never does. The comment on theSentsetter records the ordering: it is set before the navigation call, because the guard reads the live accessor.
- Walkthrough
- Injected
NotificationService,NavigationManager,Toast,L, andScopeProvider(lines 25-29), plus a cascadingAuthenticationState(line 31);_cts(line 33);_canManage(line 38);Title(line 40);_breadcrumbs(line 42) built Home to Push Notifications to Send (lines 69-74), where the middle crumb is a real link viaNotificationRoutePaths.Notifications(line 72) and the leaf isdisabled: true(line 73). _model(line 46) is areadonly NotificationSendModelcreated with the component;_validate(line 57) is the singleFunc<object, string, IEnumerable<string>>MudBlazor calls with(model, member path), wired inOnInitializedasModelValidation.For(_model, new DataAnnotationsModelValidator(L))(line 77). One delegate serves both fields, and no rule is written twice (comment, lines 55-56).OnInitializedAsync(lines 80-105) first reads the cascading auth state and sets_canManage = user.HasPermissionClaim(NotificationPermissions.Manage)(lines 82-83); when it is false it returns before touching the scope provider (lines 84-87), and the page renders the 403 view instead of the compose form (field comment, lines 35-38). Otherwise it resolves the optional scope caption:ScopeProvider.GetCurrentScopeDisplayNameAsync(_cts.LifetimeToken())(line 95), and only when the name is non-blank does it build_scopeCaption(lines 96-99). The field doc (lines 59-64) and the comment (lines 89-92) give the reasoning: a scoped application applies its scope to the send automatically, so without a caption the operator would be composing a broadcast with no visible statement of who receives it, and when there is no scope the page renders no caption at all rather than an empty line.[Rubric §24, Forms, Validation & UX Safety]again: making an implicit targeting decision visible is part of a safe destructive-ish action.SendNotificationAsync(lines 107-159): returns at once when_formis null or a send is already in flight (lines 109-113), setsIsSaving(line 115), and inside thetryclears_sendResult(line 118) and validates, warning on failure (lines 122-129), so a failed validation also releases the flag infinally; then buildsnew SendPushNotificationRequest(_model.Title, _model.Body)(line 131) and awaitsSendAsync(request, _cts.LifetimeToken())(line 132), storing the result for the summary (line 133). On a non-null PushNotificationDTO it raises the success toast withsent.RecipientCount(line 137), setsSent = true(line 141), and navigates back to the list; otherwiseresult.NotifyOnFailure(Toast, L)(line 148). The cancellation catch (lines 151-154) additionally names theInteractiveAutorender-mode transition, the case where the WebAssembly runtime takes over mid-call;IsSavingis cleared infinally(lines 155-158).NavigateToList(line 161) is the Cancel button's handler, back toNotificationRoutePaths.Notifications.Sent(a private bool property) andIsDirty(!Sent && (Title or Body non-whitespace)) are declared just afterNavigateToList, immediately above the disposal members;Sentis documented as being set the moment a send has succeeded and the page is about to navigate away on its own, so the unsaved-changes guard does not prompt over work that has just left the building.- Disposal mirrors the family:
_disposed(line 177),Dispose(bool)(lines 179-190),Dispose()(lines 192-196).
- Injected
- Why it's built this way: a deliberately small form that still demonstrates the full pattern. The rules live on NotificationSendModel so the client cap, the client message, and the server invariant all read the same constants; HTTP stays behind IPushNotificationUIService so the component is unit-testable; and the
Sent/IsDirtypair keeps the unsaved-changes guard from firing on the page's own post-send redirect, which is the one navigation on this page that is not the user abandoning work. The send is fire-and-confirm: the server fans out to recipients through the push pipeline (see Group 10) and returns only the aggregate count. - Where it's used: rendered at
/notifications/sendfor accounts holding thenotifications:managepermission (the same gate as the navigation entry,NotificationUIModule.cs:20; other accounts get the 403 view), reached from the button on NotificationList. The server-side validator for SendPushNotificationRequest enforces the same rules a second time, so client validation is a UX affordance rather than the security boundary.
ColumnFilterState
MMCA.Common.UI ·
MMCA.Common.UI.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/ColumnFilterState.cs:10· Level 0 · record (sealed, positional)
- What it is: one saved grid column filter, reduced to the two strings a list page needs to put it
back: the MudDataGrid operator and the filter value (
ColumnFilterState.cs:10). - Depends on: nothing. It is a leaf value carried inside ListPageState.
- Concept introduced, persisting a vendor filter as plain strings.
[Rubric §19, State Management & Data Flow]assesses whether UI state can cross every boundary it has to cross. A MudDataGrid filter definition is a live object bound to a grid column, so it cannot travel throughsessionStorageJSON or a URL; this record is the transport-neutral form of it. The summary (ColumnFilterState.cs:3-7) fixes the two rules that make the round trip deterministic: the value is written in the invariant culture, and it isnullfor an operator that takes no value (is empty). - Walkthrough
Operatoris the MudDataGrid operator text, for examplecontainsor>=(ColumnFilterState.cs:4-5, parameter doc atColumnFilterState.cs:8).Valueis the invariant-culture value ornull(ColumnFilterState.cs:9).- The grid page builds one per effective column filter through
new ColumnFilterState(definition.Operator!, FormatFilterValue(definition.Value))(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DataGridListPageBase.ColumnFilters.cs:92-95). - ListPageQueryStateService writes it to the URL as
c:<property>=<operator>:<value>and parses it back, mapping an empty value after the colon tonull(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/ListPageQueryStateService.cs:258-270).
- Why it's built this way: a positional sealed record gives value equality, so two snapshots of the
same filters compare equal, and JSON serialization for the
sessionStoragetier with no custom converter. Keeping the value a string (not anobject) means the same shape works for text, number, date and enum columns; the grid page re-parses it against the column type on restore, and a value that no longer parses is dropped rather than sent to the API (DataGridListPageBase.ColumnFilters.cs:17-18). - Where it's used: the
ColumnFiltersmember of ListPageState (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/ListPageStateService.cs:60), the saved dictionary in DataGridListPageBase<TDto> (DataGridListPageBase.ColumnFilters.cs:22) and thec:codec in ListPageQueryStateService (ListPageQueryStateService.cs:193-222). Pinned byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/ListPageQueryStateServiceTests.csandPages/Common/DataGridListPageBaseFilterStateTests.csunder the same test project.
LazyJsModule
MMCA.Common.UI ·
MMCA.Common.UI.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/LazyJsModule.cs:20· Level 0 · class (internal sealed)
- What it is: a small single-flight importer that owns one JavaScript module reference for a UI service: it imports on first use, shares one import across concurrent callers, and disposes the reference safely when the circuit ends.
- Depends on:
Microsoft.JSInterop(IJSRuntime,IJSObjectReference,JSDisconnectedException) and the .NETSystem.Threading.Locktype. No first-party dependencies. - Concept introduced, single-flight JS module import.
[Rubric §23, Front-End Performance]assesses whether the client loads only what it needs, when it needs it; deferringimport()until first use is the lazy half of that, and collapsing concurrent imports into one is the correctness half. The class comment (LazyJsModule.cs:5-13) states the exact defect this replaces: an unguarded_module ??= await import(...)lets two concurrent callers each start an import, after which the browser holds two module instances and the later assignment leaks the earlier reference, which is never disposed.[Rubric §15, Best Practices & Code Quality]applies to the second half of the design: a failed import is dropped rather than cached, so an import attempted during SSR prerender (when JS interop does not exist yet) does not poison the module for the rest of the circuit. - Walkthrough
- The primary constructor takes the
IJSRuntimeand the module path (LazyJsModule.cs:20). State is three fields: aLock(LazyJsModule.cs:22), the in-flight import task (LazyJsModule.cs:24) and the resolved module (LazyJsModule.cs:25).IsImported(LazyJsModule.cs:28) exists so disposal can skip work. GetOrImportAsync(LazyJsModule.cs:37) starts with a lock-free fast path returning the cached module (LazyJsModule.cs:39-42), then takes the lock only to publish or read the in-flight task (LazyJsModule.cs:47-51); the inline comment (LazyJsModule.cs:44-45) notes why holding a lock there is safe, sinceImportAsyncreaches its first await immediately and nothing slow runs under it. The import is started with no caller token at all (LazyJsModule.cs:49), and each caller then awaits the shared task throughWaitAsync(cancellationToken)(LazyJsModule.cs:55), so a caller's token cancels only that caller's wait, never the import. The method summary (LazyJsModule.cs:30-36) gives the reason: binding the import to the first caller's token would let that one caller's cancellation fault the import for every concurrent awaiter.- The
finallyblock is the subtle part (LazyJsModule.cs:57-73): it clears the field only when the task has completed and did not complete successfully (LazyJsModule.cs:63), and only when the field still holds this task (LazyJsModule.cs:67), because clearing unconditionally could drop a newer import started after this one completed and split the next set of callers. The inline comment (LazyJsModule.cs:59-62) covers the cancellation case: a caller that stopped waiting on its own token leaves the import still running rather than failed, so it stays cached for the others. ImportAsync(LazyJsModule.cs:76-86) performs the actualjs.InvokeAsync<IJSObjectReference>("import", CancellationToken.None, modulePath)(LazyJsModule.cs:79-81) and assigns_module(LazyJsModule.cs:84). The call sits inside a#pragma warning disable BL0016pair (LazyJsModule.cs:78andLazyJsModule.cs:82), and the justification on the disable line is the design point: a failed import must fault the shared task, soGetOrImportAsyncevicts it and every awaiting caller observes the failure.DisposeAsync(LazyJsModule.cs:89-106) returns immediately when nothing was imported (LazyJsModule.cs:91-94), nulls the field before awaiting (LazyJsModule.cs:96), and swallowsJSDisconnectedException(LazyJsModule.cs:102-105), since a torn-down circuit is the normal end of life for a scoped UI service.
- The primary constructor takes the
- Why it's built this way: the remarks (
LazyJsModule.cs:14-19) draw the responsibility line. This class deliberately does not swallow anything on the import path, so each consuming service keeps its own degradation contract (return a default, fall back to a navigation, no-op). That is why ListPageStateService wraps its calls in catch-and-ignore blocks while MmcaCultureBootstrap, which does not use this type at all, imports its module directly under anawait using. - Where it's used: ThemeService (
ThemeService.cs:26), ListPageStateService (ListPageStateService.cs:77), CapabilitiesJsModule (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Capabilities/CapabilitiesJsModule.cs:21), BrowserPasskeyCapability (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Capabilities/Auth/BrowserPasskeyCapability.cs:27), ViewerTimeZone (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Culture/ViewerTimeZone.cs:30), PendingToastService (PendingToastService.cs:21), AppLockInertBackground (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Capabilities/AppLockInertBackground.cs:20) and InfiniteScrollObserver<TOwner> (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Lists/InfiniteScrollObserver.cs:27). Pinned byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/LazyJsModuleTests.cs. - Caveats / not-in-source: it is
internal(LazyJsModule.cs:20), so it is not part of the published package surface: consumer apps get the benefit through the services that use it, not by using it directly.
QueryStringCodec
MMCA.Common.UI ·
MMCA.Common.UI.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/QueryStringCodec.cs:27· Level 0 · class (internal static)
- What it is: the package's own URL query-string reader and writer, behaving like ASP.NET Core's
QueryHelpers.ParseQueryandQueryHelpers.AddQueryStringwithout taking theMicrosoft.AspNetCore.WebUtilitiespackage (QueryStringCodec.cs:7-11). - Depends on: BCL only:
StringBuilder,UrlEncoder.Default,Uri.UnescapeDataStringandStringValuesfromMicrosoft.Extensions.Primitives(QueryStringCodec.cs:1-3). - Concept introduced, owning a small helper instead of a server dependency.
[Rubric §15, Best Practices & Code Quality]assesses whether a dependency earns its weight. The summary (QueryStringCodec.cs:10) gives the reason this one did not: the UI project stays WebAssembly-safe and carries no ASP.NET Core server dependency, so the two query-string operations the list pages need are owned here instead. The remarks (QueryStringCodec.cs:12-26) spell out the exact parsing and building rules, so the behavior is a documented contract rather than "whatever the old helper did". - Walkthrough
Parse(QueryStringCodec.cs:32-60) skips one leading?(QueryStringCodec.cs:36-39), splits on&only and skips empty segments (QueryStringCodec.cs:41-51), accumulating into a case-insensitive (StringComparer.OrdinalIgnoreCase) dictionary of lists (QueryStringCodec.cs:34). It then folds each list into aStringValues, single-valued when the key appeared once (QueryStringCodec.cs:53-57), so a repeated key keeps every value in order.- The private
Append(QueryStringCodec.cs:98-111) ends the key at the first=and treats a segment with no=as a key with an empty value (QueryStringCodec.cs:100-102).Decode(QueryStringCodec.cs:113-114) turns+into a space before percent-decoding, matching form encoding. AddQueryString(QueryStringCodec.cs:69-95) splits off any#fragmentfirst (QueryStringCodec.cs:74-76) so the pairs land before it, starts with?unless the URI already has a query (QueryStringCodec.cs:77andQueryStringCodec.cs:87), skips a pair whose value isnull(QueryStringCodec.cs:82-85), and encodes both key and value withUrlEncoder.Default(QueryStringCodec.cs:88-90).
- Why it's built this way: a
#is deliberately not special on the parse side, so a caller passes the query part only (QueryStringCodec.cs:18-19), which is whatUri.Queryalready gives ListPageQueryStateService. The parse walks the input as aReadOnlySpan<char>(QueryStringCodec.cs:35) and allocates strings only for decoded keys and values. - Where it's used: only by ListPageQueryStateService, in
ParseQueryString(ListPageQueryStateService.cs:67) andBuildPath(ListPageQueryStateService.cs:157). Pinned byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/QueryStringCodecTests.cs. - Caveats / not-in-source: it is
internal(QueryStringCodec.cs:27), so it is not a public utility of the package.
SnackbarDefaults
MMCA.Common.UI ·
MMCA.Common.UI.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/SnackbarDefaults.cs:21· Level 0 · class (internal sealed)
- What it is: the framework's default MudBlazor snackbar configuration: toasts at the top centre,
at most three on screen at once, applied on every head (web server, WebAssembly client and MAUI)
(class comment,
SnackbarDefaults.cs:7-12). - Depends on: no first-party type at runtime; its class comment names
MudToastService as the reason the cap exists (
SnackbarDefaults.cs:10-12). Externals:IConfigureOptions<SnackbarConfiguration>(Microsoft.Extensions.Options, implemented atSnackbarDefaults.cs:21), MudBlazor'sSnackbarConfigurationandDefaults.Classes.Position, andIServiceCollection/ServiceDescriptorfor the registration helper (usings atSnackbarDefaults.cs:1-3). - Concept introduced, a framework default that is still the host's to override.
[Rubric §20, Design System, Theming & UI Consistency]assesses whether shared UI behavior is consistent across surfaces. The on-screen cap is framework behavior, not app styling: MudToastService evicts the oldest pinned toast againstSnackbarConfiguration.MaxDisplayedSnackbars, so every head has to agree on that number (SnackbarDefaults.cs:9-12). At the same time it is registered as the FIRST configure step, so anything a host configures (AddMudServices(config => ...)before or afterAddUIShared, MmcaBlazorWebHostOptions.ConfigureMudServices, or a plainservices.Configure<SnackbarConfiguration>) runs after it and wins; a parameterlessAddMudServices()configures nothing, so the defaults stand (SnackbarDefaults.cs:13-19). The options pattern runs configure steps in registration order, which is what makes position zero mean "default". - Walkthrough
MaxDisplayedSnackbarsis aninternal const intof3(SnackbarDefaults.cs:24), andPositionClassreturnsDefaults.Classes.Position.TopCenter(SnackbarDefaults.cs:27). Both areinternalso tests can assert against the same values the configure step writes.Configure(SnackbarConfiguration options)(SnackbarDefaults.cs:30-35) null-checks the options and sets the two properties; it touches nothing else in the snackbar configuration.Register(IServiceCollection services)(SnackbarDefaults.cs:42-50) is idempotent: it returns early when a descriptor whoseImplementationTypeisSnackbarDefaultsalready exists (SnackbarDefaults.cs:44-47), otherwise it inserts a singletonIConfigureOptions<SnackbarConfiguration>at index0of the collection (SnackbarDefaults.cs:49) rather than appending it. The summary (SnackbarDefaults.cs:37-41) states the contract: ahead of every configure step already registered, once, however oftenAddUISharedruns.
- Why it's built this way: inserting at the front instead of using
TryAddorConfigureis what lets the call sit insideAddUISharedwithout caring whether the host calledAddMudServicesearlier or later. The DI comment says exactly that (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:132-134). - Where it's used: called once from
AddUIShared(DependencyInjection.cs:135). Pinned byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Registrations/SnackbarDefaultsTests.cs. - Caveats / not-in-source: the idempotence check matches on
ImplementationType, so a host that registers its ownIConfigureOptions<SnackbarConfiguration>is unaffected by it and simply runs later in the chain.
ListPageState
MMCA.Common.UI ·
MMCA.Common.UI.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/ListPageStateService.cs:10· Level 1 · record (sealed)
- What it is: the immutable snapshot of everything a list page needs to look the same after you navigate away and come back: which page, how many rows, how far down, which sort, which density, which named filters and which grid column filters.
- Depends on: ColumnFilterState for its column-filter entries. It is the
currency shared by
ListPageStateService (in-memory plus
sessionStorage), ListPageQueryStateService (URL encoding) and DataGridListPageBase<TDto> (the consumer). - Concept introduced, one state shape over three transports.
[Rubric §19, State Management & Data Flow]assesses whether UI state has a single defined shape rather than being reconstructed ad hoc per page; this record is that shape, and the fact that memory, session storage and the address bar all move the same record is what keeps the three from drifting. The record is documented as update-by-with(ListPageStateService.cs:6-8), so a caller changing scroll position cannot accidentally reset paging. - Walkthrough
- Nine
initmembers, all with defaults, sonew ListPageState()is a valid pristine state. Page(ListPageStateService.cs:13) is the MudDataGrid 0-indexed page;PageSize(ListPageStateService.cs:16) the chosen rows per page;MobilePage(ListPageStateService.cs:19) the 1-indexed card-list page, and it is the only member with a non-default default (= 1), because a mobile page zero does not exist.ScrollPosition(ListPageStateService.cs:27) is adoubleof pixels, and its doc comment (ListPageStateService.cs:21-26) names which element it measures: the document (document.scrollingElement.scrollTop) for a normal paged list page, and the grid's own height-bound viewport (.mud-table-container) for a page that opts into grid virtualization, where the document itself does not scroll.SortColumn(ListPageStateService.cs:33) holds theSortByproperty name of the active sort definition and is null or empty when unsorted;SortDescending(ListPageStateService.cs:39) is documented as ignored when it is.DenseGrid(ListPageStateService.cs:47) carries the compact-density opt-in, persisted alongside paging and sort so the chosen density survives navigation, refresh and shared links.Filters(ListPageStateService.cs:53) is anIReadOnlyDictionary<string, string>of page-specific named values (the doc gives"search"and"status"as examples) defaulting to an empty dictionary, so each page decides what it saves.ColumnFilters(ListPageStateService.cs:60) is anIReadOnlyDictionary<string, ColumnFilterState>keyed by the column's property name, also defaulting to empty. Its doc comment (ListPageStateService.cs:55-59) draws the contrast withFilters: the base list page saves and restores these itself, so a column filter survives opening a row and coming back, a refresh and a shared link without any per-page code.
- Nine
- Why it's built this way: a sealed record gives value equality and
with-based copies for free, which is what makes the "update only scroll position" and "update only density" paths in the services one-liners. - Where it's used: produced and consumed by both list-page state services and by
DataGridListPageBase<TDto> (
DataGridListPageBase.cs:878-880, where a non-emptyColumnFiltersalso counts as restorable state, andDataGridListPageBase.cs:882); serialized tosessionStorageas JSON and encoded into the query string. The column-filter half is read back byRestoreColumnFilters(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DataGridListPageBase.ColumnFilters.cs:29-32).
MudAppDialogService
MMCA.Common.UI ·
MMCA.Common.UI.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/MudAppDialogService.cs:13· Level 1 · class (internal sealed)
- What it is: the MudBlazor-backed implementation of the framework's confirm-prompt facade. All
three of its overloads open the shared
ConfirmationDialogcomponent and reduce the answer to a singlebool. - Depends on: IAppDialogService (implemented), MudBlazor's
IDialogServiceand the internalConfirmationDialogcomponent (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/ConfirmationDialog.razor:65), per the usings atMudAppDialogService.cs:1-3. It has no other state. - Concept introduced, quarantining the component library behind a facade.
[Rubric §15, Best Practices & Code Quality]assesses how much of the codebase would have to change if a vendor dependency changed; the class comment (MudAppDialogService.cs:7-12) records the answer for dialogs: this type and MudToastService are the only two types in the framework that name a component-library service. (The facade registration doc adds the one other type that touches MudBlazor'sISnackbar, StaleToastSweeper, plus theConfirmationDialogthis class opens:MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:275-278.)[Rubric §14, Testability]is the other half of the payoff, spelled out on the interface (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Interfaces/IAppDialogService.cs:12-16): a test can answer the prompt with a stub instead of driving a rendered dialog. - Walkthrough
- The primary constructor takes MudBlazor's
IDialogService(MudAppDialogService.cs:13); the class isinternal, so consumers only ever see the interface. - The four-argument
ConfirmAsync(string title, string message, string confirmText, string cancelText)(MudAppDialogService.cs:16-17) is the non-destructive case: it forwards to the five-argument overload withdestructive: false. The labels are already localized by the caller, per the interface doc (IAppDialogService.cs:25-28). - The five-argument
ConfirmAsync(..., bool destructive)(MudAppDialogService.cs:20-21) hands everything toConfirmationDialog.ShowAsync.destructiveis documented on the interface (IAppDialogService.cs:40-43) as "confirming destroys or ends something (a delete, a lock, a sign-out)", and the dialog draws the confirm button in the error color instead of the primary one (ConfirmationDialog.razor:15). - The six-argument
ConfirmAsync(..., bool destructive, string confirmTestId)(MudAppDialogService.cs:24-25) passes a caller-chosendata-testidfor the confirming button through toConfirmationDialog.ShowAsync, so an end-to-end test can target one specific prompt (IAppDialogService.cs:47-59). Without it the button carriesDefaultConfirmTestId,"confirm-action"(ConfirmationDialog.razor:21andConfirmationDialog.razor:15);DeleteConfirmationpasses"confirm-delete"(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/DeleteConfirmation.razor:9). ConfirmationDialog.ShowAsync(ConfirmationDialog.razor:65-93) returnsresult is { Canceled: false, Data: true }(ConfirmationDialog.razor:92), so Cancel, Escape and a backdrop dismissal all answerfalse(ConfirmationDialog.razor:53-56) and callers never branch on three outcomes. Escape is wired to Cancel throughCloseOnEscapeKey = true(ConfirmationDialog.razor:23-27).- The component comment (
ConfirmationDialog.razor:1-5) explains why it is not MudBlazor's message box: that box pins its focus trap to the Yes button, so a stray Enter confirmed. Here Cancel is rendered first and focused (DefaultFocus.FirstChild,ConfirmationDialog.razor:6andConfirmationDialog.razor:14). Every overload opens that one Cancel-first shape, andDeleteConfirmationgoes through this service too (MudAppDialogService.cs:10-11), so the interface can promise it to every prompt (IAppDialogService.cs:8-11).
- The primary constructor takes MudBlazor's
- Why it's built this way: the interface deliberately exposes only the one shape the framework needs
(a yes/no question before something irreversible or lossy), with
DeleteConfirmationa localized delete prompt built on it (IAppDialogService.cs:3-7). Keeping the implementationinternaland registered byAddUISharedmeans an app cannot accidentally depend on the MudBlazor type through this path. - Where it's used: registered with
TryAddScoped<IAppDialogService, MudAppDialogService>()(DependencyInjection.cs:292, under the facade-registration doc atDependencyInjection.cs:271-288). Consumers resolve the interface: the sharedDeleteConfirmationcomponent, through theconfirmTestIdoverload (DeleteConfirmation.razor:33), the sharedUnsavedChangesGuardcomponent (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/UnsavedChangesGuard.razor:14andUnsavedChangesGuard.razor:57) and the Helpdesk seed's ticket pages (MMCA.Helpdesk/Source/Hosts/UI/MMCA.Helpdesk.UI.Web/Components/Pages/Tickets.razor:175andComponents/Pages/TicketDetail.razor:448). A bUnit test pins the registration to this implementation (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Infrastructure/BunitComponentTestBaseFacadeTests.cs:32).
PendingToast
MMCA.Common.UI ·
MMCA.Common.UI.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/PendingToastService.cs:72· Level 1 · record (internal sealed, nested in PendingToastService)
- What it is: the stored payload of a parked toast, a two-field record of a ToastSeverity
and the message text (
PendingToastService.cs:72). It is the shape written to and read fromsessionStorage. - Depends on: ToastSeverity only.
- Walkthrough
- The doc comment (line 75) states the wire format: JS interop serializes it camelCase as
{ severity, message }. - PendingToastService constructs it on the write path
(
PendingToastService.cs:34) and asks interop to deserialize intoPendingToast?on the read path (PendingToastService.cs:48).
- The doc comment (line 75) states the wire format: JS interop serializes it camelCase as
- Why it's built this way: a record gives value equality and a positional constructor for a payload
that exists only to cross the JS boundary. It is nested and internal, so no consumer can depend on
the storage format; the public contract is the
(Severity, Message)tuple onIPendingToastService.TakeAsync(Common/Interfaces/IPendingToastService.cs:39). - Where it's used: only by PendingToastService, and pinned by
MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/PendingToastServiceTests.csandComponents/Notifications/PendingToastHostTests.csunder the same test project.
ListPageQueryStateService
MMCA.Common.UI ·
MMCA.Common.UI.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/ListPageQueryStateService.cs:29· Level 2 · class (sealed)
- What it is: the two-way translator between a ListPageState and the browser address bar, so browser back/forward, a refresh and a link pasted into chat all restore the same filtered, sorted, paged view.
- Depends on: ListPageState, ColumnFilterState and
QueryStringCodec, which parses and appends query strings, so the UI package
takes no query-helper dependency; externals
NavigationManagerandStringValues. - Concept introduced, the URL as shareable state.
[Rubric §25, Navigation & Information Architecture]assesses whether the address bar reflects what the user is looking at; this class is that contract for every list page. The remarks (ListPageQueryStateService.cs:14-28) document the reserved keys and why they are terse (they end up in shareable links):p(0-indexed desktop page),ps(page size),mp(1-indexed mobile page),s(sort column),sd(desconly, since ascending is the default),d(1only, since comfortable density is the default),q(free-text search),f:<name>for any other named filter andc:<property>for a grid column filter, written<operator>:<value>because MudDataGrid operators never contain a colon (ListPageQueryStateService.cs:25). Defaults are omitted entirely, so a pristine list page has a clean URL.[Rubric §19, State Management & Data Flow]applies because this is the second of the three transports the same record travels over. - Walkthrough
- The key names are private constants (
ListPageQueryStateService.cs:31-43), including the"search"filter name that maps toqby convention, thec:prefix and its:separator (ListPageQueryStateService.cs:39-40), and thedesc/1markers. A separateMaxPageSizeconstant (ListPageQueryStateService.cs:49) caps the page size a URL may ask for. It is not a literal: it is defined as KeysetPageRequest.MaxPageSize, which is1000(MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/KeysetPagination.cs:27), and its summary (ListPageQueryStateService.cs:45-48) calls that the one framework page cap, so the URL ceiling cannot drift from the server's. ReadCurrent()(ListPageQueryStateService.cs:54-58) is the instance entry point: it resolves the absolute URI from the injectedNavigationManagerand hands the query to the parser.ParseQueryString(ListPageQueryStateService.cs:65) is deliberatelystaticand public, documented as a pure helper exposed for unit testing without aNavigationManager(ListPageQueryStateService.cs:60-64). It parses throughQueryStringCodec.Parse(ListPageQueryStateService.cs:67), then reads the three integers throughTryGetInt(ListPageQueryStateService.cs:275-285, which parses withCultureInfo.InvariantCultureand falls back to the supplied default rather than throwing). Out-of-range values get the same fallback as unparsable ones (ListPageQueryStateService.cs:69-73): the page is floored at0, the mobile page at1, and a page size outside1..1000collapses to0, the page default, throughClampPageSize(ListPageQueryStateService.cs:273). The inline comment states the reason: a hand-edited or stale link withp=-3orps=5000must not leave the list stuck on a failing fetch. It then treats a blank sort value as no sort (ListPageQueryStateService.cs:76-83), matchesdesccase-insensitively (ListPageQueryStateService.cs:88) but the dense marker1ordinally (ListPageQueryStateService.cs:94), then hands the rest toParseFilters(ListPageQueryStateService.cs:97, body atListPageQueryStateService.cs:193-222), which skips empty values, foldsqinto thesearchfilter, strips thef:prefix off named filters and turns eachc:key into a ColumnFilterState (ListPageQueryStateService.cs:214-218). Both dictionaries land on the returned state (ListPageQueryStateService.cs:107-108).TryParseColumnFilter(ListPageQueryStateService.cs:258-270) splits the value at its first colon. A value with no colon or no operator (separator <= 0,ListPageQueryStateService.cs:261) is a hand-edited link and is ignored, and an empty value after the colon becomes anullvalue for an operator that takes none, such asis empty(ListPageQueryStateService.cs:253-257).BuildPath(ListPageQueryStateService.cs:117) is the inverse, and the omission rules are visible one by one: page only when> 0(ListPageQueryStateService.cs:124), page size only when> 0(ListPageQueryStateService.cs:129), mobile page only when> 1(ListPageQueryStateService.cs:134),sdonly when a sort column exists and is descending (ListPageQueryStateService.cs:139-146),donly when dense (ListPageQueryStateService.cs:148-151). Filters go throughAddFilterParameters(ListPageQueryStateService.cs:153, body atListPageQueryStateService.cs:225-251), which writesq, thef:keys and onec:<property>key per column filter that has an operator (ListPageQueryStateService.cs:244-250). With no parameters at all it returns the bare base path, otherwise it appends them withQueryStringCodec.AddQueryString(ListPageQueryStateService.cs:155-157).ReplaceState(ListPageQueryStateService.cs:176) writes the URL back usingNavigationOptions { ReplaceHistoryEntry = true }(ListPageQueryStateService.cs:189) so filter changes do not pollute the back stack.
- The key names are private constants (
- Why it's built this way: the most instructive part is the guard in
ReplaceState(ListPageQueryStateService.cs:181-186), which drops the write when the current path no longer matches the owningbasePath. The remarks (ListPageQueryStateService.cs:166-175) record the diagnosed defect: a grid-state write is inherently deferred (a debounced search, a lateServerDatacompletion), so it can land after the user has already navigated away. Building from the then-current URI used to stamp grid parameters onto the next page's URL and issue a spurious navigation that disposed it mid-load, and detail pages reached by clicking a list row had their first data fetch canceled about 66ms in, leaving them stuck on their loading state. - Where it's used: registered
TryAddScoped(DependencyInjection.cs:226) and injected into DataGridListPageBase<TDto> (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DataGridListPageBase.cs:30), which reads the URL on initialization and on parameter changes (DataGridListPageBase.cs:293andDataGridListPageBase.cs:371) and writes it back after a grid or filter change (DataGridListPageBase.cs:1853andDataGridListPageBase.cs:1930).
ListPageStateService
MMCA.Common.UI ·
MMCA.Common.UI.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/ListPageStateService.cs:71· Level 2 · class (sealed)
- What it is: the per-circuit memory of list-page state, keyed by route, with an optional
write-through to
sessionStorageso the state survives things a circuit-scoped dictionary cannot. - Depends on: ListPageState and LazyJsModule; externals
IJSRuntime,IJSObjectReferenceand thenav-interop.jsmodule shipped in the package'swwwroot. - Concept introduced, a synchronous fast path with an asynchronous durable path.
[Rubric §19, State Management & Data Flow]assesses how state survives lifecycle boundaries; this class answers with two tiers. The class comment (ListPageStateService.cs:63-70) names exactly what the durable tier buys: state survives circuit teardowns,forceLoad: truenavigations and the SSR to WASM render-mode transition. The synchronous dictionary matters just as much, because it is safe to read fromOnInitializedduring prerender, when JS interop does not exist yet. - Walkthrough
- Two constants set the contract: the module path
./_content/MMCA.Common.UI/nav-interop.js(ListPageStateService.cs:73) and themmca.lps:session-key prefix (ListPageStateService.cs:74). State is a plainDictionary<string, ListPageState>(ListPageStateService.cs:76) plus one LazyJsModule (ListPageStateService.cs:77). GetState(ListPageStateService.cs:84-85) is aGetValueOrDefaultand is documented as safe to call during SSR prerender (ListPageStateService.cs:79-83).SaveState(ListPageStateService.cs:92-93) stores in memory only.UpdateScrollPosition(ListPageStateService.cs:100-103) is the fast path for scroll events: it uses awithexpression to preserve every other field, and creates a minimal entry when none exists yet, for the case where the user scrolls before the grid has fired its first save.HydrateFromSessionAsync(ListPageStateService.cs:111-112) is a one-line forward to theinternalRecoverFromSessionAsync(ListPageStateService.cs:122), which invokessessionGeton the JS module (ListPageStateService.cs:132, the export atMMCA.Common/Source/Presentation/MMCA.Common.UI/wwwroot/nav-interop.js:12), adopts any persisted snapshot (ListPageStateService.cs:133-136) and also returns it (ListPageStateService.cs:138), ornullwhen there was none or storage was unavailable. Its summary (ListPageStateService.cs:114-121) explains why the return value exists: the dictionary write lands off the caller's render thread, so a save the caller makes before its own continuation runs (a list page's first load completing) can replace the entry in between. A caller that applies the recovered state therefore reads it from the return value, never back out of the dictionary.PersistToSessionAsync(ListPageStateService.cs:152) does the reverse throughsessionSet(ListPageStateService.cs:167,nav-interop.js:24), returning early when there is nothing in memory to write (ListPageStateService.cs:154-157).ClearAsync(ListPageStateService.cs:184) forgets every list page's state: it clears the in-memory dictionary first (ListPageStateService.cs:186), then callssessionRemoveByPrefixwith themmca.lps:prefix (ListPageStateService.cs:196, the export atnav-interop.js:45), leaving the tab's othersessionStoragekeys alone. Its summary (ListPageStateService.cs:176-183) gives the reason: the search and filters belong to the account that typed them,sessionStorageoutlives the session in the same tab, and clearing memory before the first await means a caller that cannot await still drops it at once.- All three interop methods share one exception filter,
catch (Exception ex) when (JsInteropFailure.IsUnavailable(ex))(ListPageStateService.cs:140,ListPageStateService.cs:169andListPageStateService.cs:198). JsInteropFailure (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/JsInteropFailure.cs:27) is the one shared definition, so the set cannot drift between copies (JsInteropFailure.cs:5-7): it matchesInvalidOperationException(prerender, a render-mode transition, a disposed dispatcher),JSDisconnectedException(a torn-down circuit),JSException(a missing module or a browser-side failure such as Safari Private mode or an exceeded quota) andOperationCanceledException, which covers an interop timeout or cancellation (JsInteropFailure.cs:17-26). PendingToastService uses the same filter. The catch inPersistToSessionAsync(ListPageStateService.cs:171-172) records why it matters there: the call is fire-and-forget from the grid page, so an escaping exception would be an unobserved fault. - The private
GetModuleAsync(ListPageStateService.cs:205-219) converts an unavailable runtime into anullmodule rather than an exception, which is what makes the public methods' early returns read cleanly.DisposeAsync(ListPageStateService.cs:222) simply forwards to the module wrapper.
- Two constants set the contract: the module path
- Why it's built this way: the degradation contract here is "never let storage failures break the calling page", which is why this class swallows what LazyJsModule deliberately does not. Scoped registration means one instance per circuit, so the in-memory dictionary is naturally per-user without any keying by identity.
- Where it's used: registered
TryAddScoped(DependencyInjection.cs:225) and injected into DataGridListPageBase<TDto> (DataGridListPageBase.cs:29), which reads it during state restore (DataGridListPageBase.cs:295), recovers from session on first render throughRecoverFromSessionAsync(DataGridListPageBase.cs:588) and applies the returned entry rather than re-reading the dictionary (DataGridListPageBase.cs:654andDataGridListPageBase.cs:666), records scroll offsets (DataGridListPageBase.cs:821), and saves plus persists after grid and density changes (DataGridListPageBase.cs:1832-1859andDataGridListPageBase.cs:1925-1934). JwtAuthenticationStateProvider takes it as an optional dependency (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/JwtAuthenticationStateProvider.cs:43) and callsClearAsyncon sign-in and sign-out (JwtAuthenticationStateProvider.cs:141,JwtAuthenticationStateProvider.cs:149andJwtAuthenticationStateProvider.cs:153-154); the session-ended handler cannot await, so it relies on the synchronous in-memory clear (JwtAuthenticationStateProvider.cs:147-148).
MudToastService
MMCA.Common.UI ·
MMCA.Common.UI.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/MudToastService.cs:33· Level 2 · class (internal sealed)
- What it is: the MudBlazor-backed IToastService. It is one of only two types in the framework that name a component-library service, the other being its sibling MudAppDialogService.
- Depends on: IToastService (the contract implemented at
MudToastService.cs:33) and ToastSeverity (the vendor-neutral level, taken as aShowparameter at line 56 and switched over at lines 205-210); MudBlazor'sISnackbar(held in a private field, line 35),Snackbar,Severity,Variant,ColorandSnackbarOptions, andMicrosoft.AspNetCore.Components.Rendering.RenderTreeBuilder(ASP.NET Core) for the one method that renders markup (lines 63-69). - Concept introduced, the vendor boundary.
[Rubric §20, Design System, Theming & UI Consistency]assesses whether the app depends on its own design vocabulary rather than on a specific component library's API. Every page, component andResulthelper in both applications depends onIToastService; apart from this class andMudAppDialogService(and theConfirmationDialogthe latter opens), the only framework type that names MudBlazor'sISnackbaris StaleToastSweeper, and the DI comment says so outright (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:275-280).[Rubric §14, Testability & Test Strategy]is the practical payoff: a test records toasts against the interface without rendering a snackbar host, which is how ResultUiExtensions.NotifyOnFailurecan be tested at all (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ResultUiExtensions.cs:267-269).[Rubric §1, SOLID Principles]covers the shape: an internal implementation behind a public interface means no consumer can name the concrete type even by accident. The class doc comment also states why toast text is not duplicated into a second screen-reader channel:MmcaThemeProvidershosts MudBlazor'sMudSnackbarProviderinside arole="status" aria-live="polite"element, so the rendered toast is itself the live-region content, and pushing the same sentence through a second channel would announce it twice and make every text locator ambiguous. - Walkthrough
- The class holds
ISnackbarin a private field (_snackbar, line 35) set by an explicit constructor (line 41) rather than a primary-constructor parameter; the two are behaviorally identical, only the field-access syntax changed. Beside it sit the pinned-toast bookkeeping, aList<Snackbar>(_pinned, line 38) and aLock(_pinnedSync, line 39). - Four one-liners cover the common levels:
Success,Info,WarningandError(lines 44, 47, 50, 53), each a direct_snackbar.Add(message, Severity.X).Show(message, severity)(line 56) is the same call with the level chosen at runtime. None of these is pinned, so they never touch the tracking list. ShowPersistent(title, body, severity)(line 59) is the push-notification shape. It renders a two-line body through aRenderTreeBuilder(a bolded title, a line break, then the body, lines 63-69) and setsRequireInteraction = truewithVariant.Filled(lines 75-76). The comment states the rule (lines 73-74): the message arrived unprompted, so it must survive until the user has actually looked at the screen rather than expiring on the default timer. The wholeAddcall is wrapped inAddPinned(...)(line 60) so the toast is tracked and capped.ShowAction(message, actionText, onAction, severity, requireInteraction)(line 80) is the undo-style toast. A localConfigurefunction (line 96) setsActionandActionColor(lines 98-99) and adapts MudBlazor's click signature to the caller's parameterless delegate by discarding theSnackbarinstance MudBlazor passes (line 103). It also setsDuplicatesBehavior = SnackbarDuplicatesBehavior.Allow(line 111): MudBlazor keys a snackbar on its message and, under the default duplicate prevention, would drop a second "Item removed." while the first is still up, and with it the second Undo. Plain toasts keep the host's de-duplication, because two identical notices say nothing new, but two Undo offers undo two different things (comment at lines 105-110).requireInteractionis opt-in: when false the toast goes straight to_snackbar.Add(line 93) so the host's own snackbar timing applies and the toast is not tracked; when true it goes throughAddPinned(line 89) andConfigurestates bothRequireInteractionandVariant.Filledoutright rather than relying on MudBlazor's null default (comment at lines 115-118, values at lines 119-120).AddPinned(Func<Snackbar?> add)(line 130) is the pinned-toast cap. MudBlazor shows at mostSnackbarConfiguration.MaxDisplayedSnackbarsat once and queues the rest out of sight, and a pinned toast never expires, so a burst of pushes would fill every slot and each newer toast would wait invisibly. Under the lock (line 132), when tracked toasts have reached the cap (_snackbar.Configuration.MaxDisplayedSnackbars, line 138, which SnackbarDefaults sets to 3 on every head) it removes the oldest one this service raised (lines 139-145), then adds the new one and subscribesForgetPinnedto itsOnClose(lines 149-154). The newest is therefore always the one on screen. The class comment states the scope: only toasts this service added are ever removed, timed toasts and snackbars raised elsewhere are untouched (MudToastService.cs:18-27), and the tracking is per circuit or per app because the service is scoped, with a lock because close events arrive on timer threads (lines 28-31). A null return fromadd()means the host's duplicate prevention suppressed the toast, so there is nothing to track (comment at line 148).- Two helpers keep the list honest.
ForgetPinned(line 190) drops a toast from the list when itsOnClosefires, under the same lock.ForgetRemovedPinned(line 164) catches removals that raise no event (ISnackbar.Remove,RemoveByKey,Clear): when fewer snackbars are shown than the cap, nothing is queued, so any tracked toast absent fromShownSnackbarsis gone and is pruned (lines 166-170). IsPinned(Snackbar)(line 182) isinternaland answers, under the lock, whether a snackbar is a still-open pinned toast this service raised. MudBlazor does not expose a snackbar's options, so the service that raised the toast is the only place that knows it is pinned (summary at lines 173-181); StaleToastSweeper asks it so a navigation never removes a toast the contract promises stays until dismissed (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Notifications/StaleToastSweeper.cs:92andStaleToastSweeper.cs:111-112).Map(ToastSeverity)(line 203) projects the neutral enum onto MudBlazor's with an explicit switch over all five members plus aNormaldefault (lines 205-210). It is written out rather than cast on purpose: the two enums agree numerically today, and an implicit dependency on that would break silently the day either side gains a member (comment at lines 198-202).- The cap behavior is pinned by
MudToastServicePinnedCapTests, which builds the service over aSnackbarConfigurationwithMaxDisplayedSnackbars = Cap(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/MudToastServicePinnedCapTests.cs:124). - Nothing wraps
onAction. The absence is a documented contract, pinned by a test that asserts a throwing callback propagates (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/MudToastServiceTests.cs:49-59): a caller whose work can fail guards it instead of discovering the failure as a swallowed no-op.
- The class holds
- Why it's built this way: keeping the vendor type behind a facade is what makes the component
library swappable in principle and mockable in practice, and it is the reason the framework ships
AddCommonUiFacades()as its own registration (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:289-295), factored out so a bUnit harness can register exactly these three services (toast, dialog and pending toast) without pulling in the whole shared-UI surface (comment at lines 283-286). Every method returnsvoid: a toast is fire-and-forget by design, and MudBlazor'sISnackbar.Addis synchronous. The pinned-toast eviction exists because a notification burst is the one case where fire-and-forget silently loses the newest message. - Where it's used: registered by
AddCommonUiFacadeswithTryAddScoped(DependencyInjection.cs:291), whichAddUISharedcalls for every host (DependencyInjection.cs:193). Consumers resolveIToastService, never this type: the framework'sNotificationListenerraises an incoming push as a persistent toast (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Notifications/NotificationListener.razor:49), ResultUiExtensions.NotifyOnFailureturns a failed Result into one (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ResultUiExtensions.cs:280-282), and ADC's LiveEventListener uses the action shape for its reconnect prompt (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Components/LiveEventListener.razor.cs:191,332). Its own behavior is pinned by MudToastServiceTests, which captures the options lambda and applies it to a freshSnackbarOptionscarrying MudBlazor's defaults, so the assertions see exactly what a rendered snackbar would (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/MudToastServiceTests.cs:176). - Caveats:
ShowPersistentrenders the title and body as content in a render fragment, so both are escaped by the renderer, but neither string is length-bounded in source: a long push body produces a correspondingly tall toast.Show,Successand the rest pass the caller's string straight to MudBlazor, so any localization has to happen before the call; the facade does not touchIStringLocalizer. The pinned-toast cap evicts only toasts this class raised and tracks them per scope, so two scopes (two circuits) never evict each other's toasts.
PendingToastService
MMCA.Common.UI ·
MMCA.Common.UI.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/PendingToastService.cs:14· Level 2 · class (internal sealed)
- What it is: the
sessionStorage-backed IPendingToastService, the toast that survives a full page reload. A toast raised through MudToastService lives in the current circuit or WebAssembly runtime, so one raised just beforeNavigateTo(url, forceLoad: true)dies with the page; this service parks it instead. - Depends on: IPendingToastService (implemented) and
IAsyncDisposable(PendingToastService.cs:14),IJSRuntimevia the primary constructor, a LazyJsModule over./_content/MMCA.Common.UI/nav-interop.js(lines 19, 21), ToastSeverity, JsInteropFailure for its exception filter, and the nested PendingToast payload. - Concept introduced, best-effort persistence across a reload.
[Rubric §20, Design System, Theming & UI Consistency]covers consistent user feedback: a confirmation that vanishes because the page reloaded reads as silence. The service reuses thenav-interop.jsmodule (sessionSet,sessionGet,sessionRemove) that ListPageStateService already uses (class comment, lines 6-12), under one fixed key,mmca.pendingToast(StorageKey, line 17). One toast is held at a time: queueing again overwrites it (IPendingToastService.cs:11). - Walkthrough
QueueAsync(severity, message, ct)(line 24) returns early for a blank message (lines 26-29), otherwise imports the module lazily and callssessionSetwith a new PendingToast (lines 33-34).TakeAsync(ct)(line 43) reads withsessionGet(line 48), returnsnullwhen nothing is parked, and removes the entry withsessionRemovebefore returning it (line 56). The comment (lines 54-55) gives the reason: removing first means a second render, or a second tab restoring the session, cannot show the same toast twice. A blank message or an undefined severity is discarded asnull(lines 58-60), so a tampered entry cannot reach the toast host.- Both methods swallow interop failure through the shared
JsInteropFailure.IsUnavailablefilter (lines 36 and 62; the definition atMMCA.Common/Source/Presentation/MMCA.Common.UI/Common/JsInteropFailure.cs:27): prerender (InvalidOperationException), a torn-down circuit (JSDisconnectedException), a browser-side failure (JSException) and an interop timeout or cancellation (OperationCanceledException, which coversTaskCanceledException). The comment at line 38 of the queue path says why: the toast is a courtesy and must not fail the action that raised it. DisposeAsync(line 69) forwards to the lazy module.
- Why it's built this way: parking in
sessionStoragerather than a cookie or server state keeps it per tab and off the wire. The interface also warns callers not to pass the page's lifetime token when the same action signs the user out of an[Authorize]page, because the re-render disposes the page and cancels that token, silently dropping the toast (IPendingToastService.cs:24-29). - Where it's used: registered by
AddCommonUiFacadeswithTryAddScoped<IPendingToastService, PendingToastService>()(DependencyInjection.cs:293). The shared layout rendersPendingToastHost(Layout/MainLayout.razor:19), which callsTakeAsyncon its first interactive render (Components/Notifications/PendingToastHost.razor:18) and shows the result through IToastService. ADC'sProfilepage queues through it before a forced reload (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/Profile.razor.cs). Tests:MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/PendingToastServiceTests.cs.
FeatureFlagAdminUIOptions
MMCA.Common.UI ·
MMCA.Common.UI.Services.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/FeatureFlagAdminUIOptions.cs:9· Level 0 · class (sealed)
- What it is: the options bag that tells FeatureFlagAdmin which services to list
flags from: one
Sourceslist of API route prefixes, in display order (line 12, default empty). - Depends on: nothing first-party; bound through the BCL options pattern (
IOptions<T>). - Concept: no new concept. It is the plain options class the registration call fills, so a
multi-service host lists every service's flags in one table (
DependencyInjection.cs:450-452). - Walkthrough:
Sources(line 12) is a settableIReadOnlyList<string>initialised to[].AddFeatureFlagAdministrationUI(params string[] sources)appends to it rather than replacing it (options.Sources = [.. options.Sources, .. sources],DependencyInjection.cs:462-463), so two calls accumulate their prefixes. - Why it's built this way: the page reads it as a fallback only:
EffectiveSourcesis the page's ownSourcesparameter when supplied, else this options value (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/FeatureFlagAdmin.razor.cs:76), and the page shows a source column only when more than one source is in play (line 79). - Where it's used: configured by DependencyInjection
(
DependencyInjection.cs:462); injected into FeatureFlagAdmin (FeatureFlagAdmin.razor.cs:74); ADC's Conference UI module registers its sources (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/DependencyInjection.cs:56); pinned byFeatureFlagAdminTests.cs.
IFeatureFlagAdminUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IFeatureFlagAdminUIService.cs:16· Level 3 · interface
- What it is: the typed client contract for the feature-flag admin page: list one source's flags,
set one flag's override, clear one flag's override. Every member takes the
sourceroute prefix first, so one client serves every service's flag endpoints. - Depends on: FeatureFlagStatusResponse
(the per-flag read shape), SetFeatureFlagOverrideRequest
(the override payload), and Result /
Result<T>for every return. Its sole implementation is FeatureFlagAdminService. - Concept: like IRoleAdminUIService, each member's XML doc names the wire
call it makes (
GET {source},PUT {source}/{name},DELETE {source}/{name}, lines 18, 26, 38), so the contract is also the endpoint map. The source parameter is what makes it multi-service: the doc givesAdmin/FeatureFlagsas an example prefix (line 19).[Rubric §9, API & Contract Design]assesses whether a client contract mirrors its server surface cleanly; here the three members map one-to-one onto the three verbs of the feature-flags controller. - Walkthrough:
GetAllAsync(source, ...)(lines 22-24) returnsIReadOnlyList<FeatureFlagStatusResponse>.SetOverrideAsync(source, name, request, ...)(lines 32-36) returns the flag's state afterwards.ClearOverrideAsync(source, name, ...)(line 43) returns a bareResult. - Why it's built this way: the opt-in UI half of reloadable feature flags
(ADR-031); an app that calls
no
AddFeatureFlagAdministrationUIregisters nothing (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:448-470). - Where it's used: registered with FeatureFlagAdminService by
DependencyInjection (
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:465); injected into FeatureFlagAdmin (FeatureFlagAdmin.razor.cs:70); mocked inFeatureFlagAdminTests.cs.
IMachineClientAdminUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IMachineClientAdminUIService.cs:10· Level 3 · interface
- What it is: the typed client contract for the machine-client admin page: list every client (revoked ones included), create one, rotate, promote and revoke its secret.
- Depends on: MachineClientResponse,
MachineClientSecretResponse (the create and rotate
result, which carries the secret), CreateMachineClientRequest,
and Result /
Result<T>. Client ids are plainGuid(lines 27, 33, 39). Its sole implementation is MachineClientAdminService. - Concept, a secret shown once.
CreateAsyncandRotateAsyncreturnMachineClientSecretResponseand their docs say the secret comes back once (lines 17, 23); every other member returns the secret-freeMachineClientResponse. Rotation is two-step:RotateAsyncissues a secondary secret andPromoteAsyncmakes it the primary, so a caller can deploy the new secret before the old one stops working.[Rubric §11, Security]assesses credential handling; the return types keep a secret off every read path after the one that minted it. - Walkthrough:
GetAllAsync(line 15),CreateAsync(request, ...)(line 21),RotateAsync(clientId, ...)(line 27),PromoteAsync(clientId, ...)(line 33),RevokeAsync(clientId, ...)(line 39). - Why it's built this way: the UI opt-in of machine clients
(ADR-140),
registered only by
AddMachineClientAdministrationUI(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:357-370). - Where it's used: registered with MachineClientAdminService by
DependencyInjection (
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:367); injected into MachineClientAdmin (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/MachineClientAdmin.razor.cs:50); mocked inMachineClientAdminTests.cs.
IRoleAdminUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IRoleAdminUIService.cs:22· Level 3 · interface
- What it is: the typed client contract for the role-admin editor: read every role's compiled and stored permissions, read one role, read the catalog an editor renders from, and replace one role's stored permission set.
- Depends on: first-party: RolePermissionsResponse (the
per-role read and write shape), PermissionCatalogResponse
(the closed sets a role editor may choose from), and Result
/
Result<T>(IRoleAdminUIService.cs:30,36,44,54) for every member's return type. Its sole implementation is RoleAdminService. - Concept: each member's XML doc names the exact endpoint it calls (
GET Admin/Roles,GET Admin/Roles/{role},GET Admin/Roles/catalog,PUT Admin/Roles/{role}/permissions, lines 27,32,40,47-48), so the contract doubles as the wire map for the role-admin surface without a separate reference.[Rubric §1, SOLID Principles]reads this as a small, role-scoped interface: it names only what a role editor needs and nothing a user editor would, the mirror decision to the split between IUserAdminActionsUIService and IUserAdminUIService<TUserDto> one member table below. - Walkthrough:
GetAllAsync(line 30) andGetAsync(string role, ...)(line 36) are the two reads that feed the role list and role-detail pages.GetCatalogAsync(line 44) reads the roles-plus- permissions catalog a role editor renders its checkboxes from.SetStoredPermissionsAsync(role, permissions, ...)(lines 54-57) replaces the complete stored permission set for one role in a single PUT, not an incremental add/remove, so the caller always sends the full desired set. - Why it's built this way: this is an ADR-116 opt-in surface (ADR-116): the admin app can wire role management by registering RoleAdminService against this contract without the framework hard-wiring an admin UI into every consumer.
- Where it's used: implemented by RoleAdminService and registered against it in
DependencyInjection (
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs); consumed byRoleAdminEdit.razor.csandRoleAdminList.razor.cs; its ADC identity pages carry the behavior-pinning tests (MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/Pages/Roles/RoleEditTests.cs,RoleListTests.cs).
IUserAdminActionsUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IUserAdminActionsUIService.cs:16· Level 3 · interface
- What it is: the account-mutation contract for user admin: lock, unlock, and two shapes of
role-replacement, a full-set
SetRolesAsyncand a single-role convenienceSetRoleAsync. - Depends on: first-party: SetUserRolesRequest (implied wire
shape behind
SetRolesAsync), Result (IUserAdminActionsUIService.cs:22,26,33,41,56,58);UserIdentifierType(the module's identifier alias) names every account parameter. Extended by IUserAdminUIService<TUserDto>. - Concept, a member that exists only because a mock cannot proxy a default interface method. The
remarks on
SetRoleAsync(lines 108-111) give the reasoning directly: the obvious shape would have been a default interface implementation overSetRolesAsyncthat wraps the single role in a one-element list, but a default implementation on an interface is not virtual to a mock proxy, so a test could neither stub nor verify it if it were written that way. DeclaringSetRoleAsyncas its own interface member keeps it mockable at the cost of one more line on the contract.[Rubric §14, Testability]is the rubric this decision serves. - Walkthrough:
LockAsync(userId, ...)(line 84) andUnlockAsync(userId, ...)(line 90) are the two session-revoking actions.SetRolesAsync(userId, roles, ...)(lines 97-100) replaces the complete role set an account holds.SetRoleAsync(userId, role, ...)(line 116) is documented as sending a one-element set to the same replacement endpoint (lines 102-106), the shape both shipped consumers need because each holds exactly one role per account. - Why it's built this way: separated from the read/page surface in IUserAdminUIService<TUserDto> so the mutating actions have one narrow, generic-free contract a page or a test can depend on without also depending on the DTO type parameter.
- Where it's used: extended by IUserAdminUIService<TUserDto>;
implemented by UserAdminService<TUserDto>; called directly from
UserAdminList.razor.csfor the lock/unlock/role actions on the user-admin grid, and pinned byUserListTests.cs(ADC) andUserAdminListTests.cs(Common).
IViewAsGrantsUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IViewAsGrantsUIService.cs:17· Level 3 · interface
- What it is: the one-member read contract behind the support access log: read one page of
view-as grants from
GET Admin/ViewAsGrants(doc comment, line 19). - Depends on: ViewAsGrantListRequest (filters plus page), ViewAsGrantSummaryResponse (the row), PagedCollectionResult<T> and Result. Its sole implementation is ViewAsGrantsService.
- Concept: no new concept; a read-only sibling of the other admin contracts in this part. The log it feeds is the audit trail of read-only support access (ADR-137), so the contract has no write member at all.
- Walkthrough:
GetPageAsync(request, ...)(lines 23-25) returnsResult<PagedCollectionResult<ViewAsGrantSummaryResponse>>. - Why it's built this way: opt-in through
AddSupportAccessLogUI; an app that serves no support access log registers nothing (DependencyInjection.cs:381-397). - Where it's used: registered with ViewAsGrantsService by
DependencyInjection (
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:385); injected into SupportAccessLog (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/SupportAccessLog.razor.cs:67); ADC's Identity UI module opts in (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs:41); mocked inSupportAccessLogTests.cs.
IUserAdminUIService<TUserDto>
MMCA.Common.UI ·
MMCA.Common.UI.Services.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IUserAdminUIService.cs:17· Level 4 · interface
- What it is: the read-plus-actions contract a user-admin page depends on: a single-account read
generic over the consumer's own user DTO, a read of the account's live sessions, a read of its
sign-in history, plus every mutation from
IUserAdminActionsUIService via interface inheritance. The roster
is deliberately not a member: it is the app's generic paged entity endpoint, read through the standard
entity service and handed to
UserAdminListas itsFetchPagedelegate (type doc comment). - Depends on: extends IUserAdminActionsUIService (line 17); its
read is generic over
TUserDto, the consumer-supplied user row shape.UserIdentifierTypenames the account parameter ofGetAsync(line 23),GetSessionsAsync(lines 32-34), which returns RefreshSessionSummaryResponse rows (line 32), andGetSignInsAsync(lines 43-45), which returns SignInSummaryResponse rows (line 43). Implemented by UserAdminService<TUserDto>. - Concept, the type parameter is the boundary between a shared service and an app-specific DTO. ADC
and Store each ship their own user row shape (different columns for the admin grid), so the interface
is generic rather than fixed to one DTO, and only the single-account read needs the parameter (the
sessions and sign-ins reads return fixed framework responses): the write half in
IUserAdminActionsUIService takes only an id and never returns a DTO, so
it carries no type parameter of its own.
[Rubric §1, SOLID Principles]reads the split as interface segregation again: a caller that only needs to lock or re-role an account depends on the narrower, non-generic interface. - Walkthrough:
GetAsync(userId, ...)(line 23) reads one account, including its lock state, fromGET Admin/Users/{userId}.GetSessionsAsync(userId, ...)(lines 32-34) reads the account's live (signed-in) sessions, newest first, fromGET Admin/Users/{userId}/sessions; it is view only (doc comment, lines 25-28).GetSignInsAsync(userId, ...)(lines 43-45) reads the account's sign-in history fromGET Admin/Users/{userId}/sign-ins: one row per sign-in, ended ones included, newest first, at most 50, also view only (doc comment, lines 36-39). The cap of 50 is stated by the doc comment; the client passes no limit, so it is the server's to enforce. - Why it's built this way: generic over
TUserDtorather than one fixed shape keeps the single-read plumbing in the framework while each consumer app supplies its own admin row DTO; the roster reuses the generic entity paging instead of a parallel admin-only listing. - Where it's used: implemented by UserAdminService<TUserDto>,
registered against it by DependencyInjection; consumed by
UserAdminList.razor.csand ADC'sUserDetail.razor.cs(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserDetail/UserDetail.razor.cs), and pinned byUserAdminListTests.cs(Common) andUserDetailTests.cs(ADC). ADC'sUserDetailrenders the sign-in history through SignInHistoryTable (UserDetail.razor.cs:173).
FeatureFlagAdminService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/FeatureFlagAdminService.cs:22· Level 4 · class (sealed)
- What it is: the HTTP implementation of IFeatureFlagAdminUIService:
a GET, a PUT and a DELETE against whatever route prefix the caller passes as
source. - Depends on: AuthenticatedServiceBase (base class, lines 22-25),
HttpResultExecutor (lines 34, 58, 77),
ProblemDetailsResultReader (lines 42, 66, 85),
FeatureFlagStatusResponse and
SetFeatureFlagOverrideRequest;
IHttpClientFactoryand ITokenStorageService are the primary-constructor parameters (lines 23-24). - Concept: the same executor-outside, retry-middle, reader-innermost composition as
RoleAdminService. All three calls, including the PUT and the DELETE, run inside
the inherited
RetryPolicy(lines 38, 62, 81): setting or clearing an override is a replace, so a repeat lands in the same state. - Walkthrough:
GetAllAsync(source, ...)(lines 28-46) guardssourcewithThrowIfNullOrWhiteSpace(line 32) and GETs the prefix itself.SetOverrideAsync(lines 49-70) null-checks the request (line 55) and PUTs it as JSON to the flag URL (line 63).ClearOverrideAsync(lines 73-88) DELETEs the flag URL (line 82) and reads a bareResult. The privateFlagUrl(source, name)(lines 90-96) guards both arguments and returns{source without trailing slash}/{escaped name}(line 95), so a prefix written with or without a trailing/and a flag name with reserved characters both round-trip. - Why it's built this way: taking the prefix per call instead of fixing one endpoint constant is what lets one registered client serve every service listed in FeatureFlagAdminUIOptions (ADR-031).
- Where it's used: registered against IFeatureFlagAdminUIService by
DependencyInjection (
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:465), and reached by FeatureFlagAdmin through that interface.
MachineClientAdminService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/MachineClientAdminService.cs:22· Level 4 · class (sealed)
- What it is: the HTTP implementation of
IMachineClientAdminUIService, five calls against the
Admin/MachineClientsendpoint family. - Depends on: AuthenticatedServiceBase (base class, lines 22-25), HttpResultExecutor (lines 31, 51, 82), ProblemDetailsResultReader (lines 39, 57, 89), MachineClientResponse, MachineClientSecretResponse and CreateMachineClientRequest.
- Concept, retry only on the read. Only
GetAllAsyncruns inside the inheritedRetryPolicy(line 35). The create POST (line 55) and the three action POSTs (line 86) go straight to the client, the same no-retry stance UserAdminService<TUserDto> documents for its lock POSTs. Here it matters more: a retried create or rotate would mint a second secret. - Walkthrough:
Endpoint(line 27) is the private constant"Admin/MachineClients".GetAllAsync(lines 30-42) GETs it bare.CreateAsync(request, ...)(lines 45-61) null-checks the request (line 49) and POSTs it as JSON.RotateAsync,PromoteAsyncandRevokeAsync(lines 64-65, 68-69, 72-73) are one-line calls into the private genericPostAsync<TResponse>(clientId, action, ...)(lines 81-91), which POSTs an empty body to{Endpoint}/{clientId}/{action}(lines 86-87) withrotate,promoteorrevokeas the action segment. - Why it's built this way: one private generic carries the three bodiless actions, the same factoring RoleAdminService uses for its reads (ADR-140).
- Where it's used: registered against
IMachineClientAdminUIService by
DependencyInjection (
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:367); ADC's Identity UI module opts in (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs:46). - Caveats / not-in-source: unlike
UserAdminService<TUserDto>, no source comment states why the POSTs skip retry; the reasoning above is read from the call shape.
RoleAdminService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/RoleAdminService.cs:24· Level 4 · class (sealed)
- What it is: the HTTP implementation of IRoleAdminUIService, the four calls
against the
Admin/Rolesendpoint family. - Depends on: AuthenticatedServiceBase (base class,
RoleAdminService.cs:24), IRoleAdminUIService (implemented interface), HttpResultExecutor (lines 64, 90), ProblemDetailsResultReader (lines 75, 98), RolePermissionsResponse and PermissionCatalogResponse (the response bodies), SetRolePermissionsRequest (the write payload, line 71);IHttpClientFactoryand ITokenStorageService (primary-constructor parameters, lines 26-27). - Concept, one private generic GET carries all three reads.
GetAsync<TResponse>(url, cancellationToken)(lines 89-101) is the whole shared shape: authenticate, retry through the inheritedRetryPolicy, read the body or the Problem Details.GetAllAsync,GetAsync(role, ...)andGetCatalogAsyncare each a one-line call into it with a different URL and response type (lines 33-35, 38-47, 50-51). Only the write,SetStoredPermissionsAsync, needs its own method, because it is the one call whose response reader differs (aRolePermissionsResponserather than a bare success) and whose HTTP verb isPUT. - Walkthrough:
Endpoint(line 30) is the private constant"Admin/Roles".GetAllAsync(lines 33-35) hits the endpoint bare.GetAsync(string role, ...)(lines 38-47) null-checksrolethen appendsUri.EscapeDataString(role), so a role name with reserved URL characters still round-trips.GetCatalogAsync(lines 50-51) appends/catalog.SetStoredPermissionsAsync(lines 54-79) null-checks both arguments, builds{Endpoint}/{role}/permissions, and PUTs a SetRolePermissionsRequest wrapping the complete permission list (line 71), inside the same authenticate-retry-read wrapper as the private read helper but written out separately because it POSTs (in fact PUTs) rather than GETs. Both the write and the private read return the executor's task directly rather than awaiting it (lines 64, 90), so they are notasyncmethods themselves. - Why it's built this way: matches the composition every other service in this package uses,
HttpResultExecutor outside,
RetryPolicyin the middle, ProblemDetailsResultReader innermost, so a reader who has studied EntityServiceBase<TEntityDTO, TIdentifierType> already knows the shape here. It is a plain AuthenticatedServiceBase subclass rather than an EntityServiceBase<TEntityDTO, TIdentifierType> one because roles are not a CRUD resource with create/delete: only read and one full-replace write exist. - Where it's used: registered against IRoleAdminUIService by
DependencyInjection
(
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs). See ADR-116.
ViewAsGrantsService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/ViewAsGrantsService.cs:24· Level 4 · class (sealed)
- What it is: the HTTP implementation of IViewAsGrantsUIService: one
paged GET against
Admin/ViewAsGrants, with the filters encoded as a query string. - Depends on: AuthenticatedServiceBase (base class, lines 24-27),
HttpResultExecutor (line 40),
ProblemDetailsResultReader (line 48),
ViewAsGrantListRequest,
ViewAsGrantSummaryResponse and
PagedCollectionResult<T>; BCL
StringBuilderandCultureInfo.InvariantCulturebuild the URL. - Concept, the query string is the contract. The controller binds
ViewAsGrantListRequestfrom the query, so the client's only real logic is serialising it the way the binder reads it: the page always, each filter only when set, instants in round-trip UTC form (doc comment, lines 54-57).[Rubric §14, Testability]assesses whether logic can be checked in isolation;BuildUrlisinternal static(line 60) so a unit test pins the URL without an HTTP call. - Walkthrough:
Endpoint(line 29) is"Admin/ViewAsGrants".GetPageAsync(request, ...)(lines 32-52) null-checks the request (line 36), builds the URL, and GETs it through the inheritedRetryPolicy(line 44).BuildUrl(request)(lines 60-72) always appendspageNumberandpageSize(line 63), thenstaff,viewed,from,toandstatus(lines 65-69);fromandtogo throughToUniversalTime().ToString("O", ...)(lines 67-68). The privateAppend(lines 74-80) skips a null or whitespace value and otherwise appends the trimmed,Uri.EscapeDataString-escaped value (line 78). - Why it's built this way: the support access log is read-only by design (ADR-137), so the client has one GET and nothing else.
- Where it's used: registered against IViewAsGrantsUIService by
DependencyInjection (
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:385);BuildUrlis pinned byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Administration/ViewAsGrantsServiceTests.cs.
UserAdminService<TUserDto>
MMCA.Common.UI ·
MMCA.Common.UI.Services.Administration·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/UserAdminService.cs:26· Level 5 · class (sealed)
- What it is: the HTTP implementation of
IUserAdminUIService<TUserDto>, generic over the consumer's user DTO,
covering single read, live-sessions read, sign-in history read, lock/unlock, and role replacement
against the
Admin/Usersendpoint family. The paged roster read is not here: the roster goes through the generic entity service. - Depends on: AuthenticatedServiceBase (base class),
IUserAdminUIService<TUserDto> (implemented interface),
HttpResultExecutor (lines 40, 61, 82, 119, 142),
ProblemDetailsResultReader (lines 48, 69, 90, 130, 155),
RefreshSessionSummaryResponse (line 55, the
sessions-read element), SignInSummaryResponse (line 76, the
sign-ins-read element), SetUserRolesRequest (line 126,
the role-replace payload);
UserIdentifierTypenames every account parameter;System.Globalization.CultureInfo.InvariantCultureformats every interpolated URL segment (lines 38, 59, 80, 117, 140). - Concept, the same read/write composition as its sibling RoleAdminService.
Every method builds a relative URL under
Admin/Users, then runs an executor-outside, retry-middle, reader-innermost lambda. The methods return the executor's task directly instead of awaiting it, so only the inner lambda isasync(lines 40, 61, 82, 119, 142). - Walkthrough:
Endpoint(line 31) is the private constant"Admin/Users".GetAsync(userId, ...)(lines 34-52) is a plain cache-free GET at{Endpoint}/{userId}.GetSessionsAsync(userId, ...)(lines 55-73) GETs{Endpoint}/{userId}/sessionsthrough the same retry and reads anIReadOnlyList<RefreshSessionSummaryResponse>, which feeds UserSessionsTable.GetSignInsAsync(userId, ...)(lines 76-94) has the identical shape against{Endpoint}/{userId}/sign-insand reads anIReadOnlyList<SignInSummaryResponse>, which feeds SignInHistoryTable.LockAsyncandUnlockAsync(lines 97-102) both delegate to the privatePostLockChangeAsync(userId, action, ...)(lines 135-158) with"lock"or"unlock"as the action segment.SetRoleAsync(userId, role, ...)(lines 105-109) wraps the single role in a one-element array and callsSetRolesAsync, the concrete implementation of the convenience member IUserAdminActionsUIService declares.SetRolesAsync(userId, roles, ...)(lines 112-133) PUTs SetUserRolesRequest to{Endpoint}/{userId}/roles.PostLockChangeAsync(lines 135-158) POSTs to{Endpoint}/{userId}/{action}with no retry: the comment (lines 147-149) states the reasoning directly, the endpoint is declared non-idempotent, so a retried POST is a second request rather than a replayed response, even though both lock and unlock are idempotent in the domain, because the client should not make that call on the endpoint's behalf. - Why it's built this way: matches the executor-outside/retry-middle/reader-innermost composition
every other service in this package uses, generic over
TUserDtoso ADC and Store each supply their own admin-grid row shape without a second copy of the HTTP plumbing. The deliberate absence of retry on the two POST actions is the one place this service diverges from the pattern, and it is a documented choice rather than an oversight. - Where it's used: registered against IUserAdminUIService<TUserDto>
by DependencyInjection
(
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs); consumed by ADC'sUserDetail.razor.cs.
ISessionCookieSync
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/ISessionCookieSync.cs:8· Level 0 · interface
- What it is: a two-method contract for mirroring the client's in-memory tokens into the browser's HttpOnly auth cookies, and for clearing them again on logout. Both methods report whether the cookie jar was actually updated.
- Depends on: nothing first-party. Implemented by
JsFetchSessionCookieSyncand, on a Blazor Server host that enabled the same-origin proxy, byHandoffSessionCookieSync(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/HandoffSessionServices.cs:53); consumed byWasmTokenStorageServiceand byServerTokenStorageService(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Services/ServerTokenStorageService.cs:51). - Concept introduced, the prerender visibility gap. A Blazor Web App renders a server-side pass
before the interactive circuit exists. During that pass there is no
Authorizationheader and no way to read the interactive client's in-memory access token, so an[Authorize]page opened by a deep link, an F5, or right-click "open in new tab" would bounce to/logineven for a signed-in user. The interface doc says exactly that (ISessionCookieSync.cs:3-7). The cookie is the one thing both sides can see, so keeping it in step with the in-memory token is what makes fresh GETs work.[Rubric §26, Front-End Security]assesses where browser credentials live. The target is an HttpOnly cookie, unreadable from JS, rather thanlocalStorage.[Rubric §25, Navigation, Routing & Information Architecture]assesses whether deep links behave. This contract is the reason a bookmarked authorized route renders instead of redirecting.
- Walkthrough: two members, both returning
Task<bool>:truewhen the cookie jar was updated,falsewhen the write failed or could not be attempted (a non-2xx answer, a dropped connection, JS interop unavailable).SyncAsync(accessToken, refreshToken)writes the pair (ISessionCookieSync.cs:15) andClearAsync()removes it (line 20). The two callers treat the answers differently on purpose. A failed sync is surfaced:WasmTokenStorageServicethrowsInvalidOperationExceptionwhenSyncAsyncreturnsfalse(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/WasmTokenStorageService.cs:141-144), soAuthUIServicereportsAuth.TokenStorageUnavailableinstead of a sign-in that silently ends at the first access-token expiry, when no cookie exists to refresh from (comment at lines 64-67;ServerTokenStorageServicedoes the same atServerTokenStorageService.cs:197). A failed clear is discarded (_ = await sessionCookieSync.ClearAsync(),WasmTokenStorageService.cs:155), because sign-out proceeds locally whatever the cookie endpoint answered. - Why it's built this way: the shape is the client half of
ADR-022, which decided
the BFF-style
mmca_auth_access/mmca_auth_refreshHttpOnly cookie pair and the/auth/session/tokenhydration endpoint. Keeping it an interface (rather than calling JS interop inline from token storage) is what lets a bUnit or unit test drive the storage services with a mock and no browser, whichWasmTokenStorageServiceTestsdoes (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/WasmTokenStorageServiceTests.cs:30). - Where it's used: registered by the dedicated extension
AddClientAuthSessionCookieSync(), whichTryAddScopedsJsFetchSessionCookieSync(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:303-305); the doc there records that both the Blazor Server host and the WebAssembly client call it (lines 300-301).
SameOriginProxyHeaders
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/SameOriginProxyHeaders.cs:11· Level 0 · class (static)
- What it is: two constants naming the fixed CSRF request header the same-origin API proxy
requires on every state-changing request:
CsrfHeaderName = "X-CSRF"(SameOriginProxyHeaders.cs:14) andCsrfHeaderValue = "1"(line 17). - Depends on: nothing. It lives in
MMCA.Common.UIrather thanMMCA.Common.UI.Webso the client that stamps the header and the server that checks it share one definition. - Concept introduced, a custom header as a CSRF signal. A cross-site page can make a browser send
a simple POST carrying the user's cookies, but it cannot add a custom header without a CORS
preflight. The proxy answers
OPTIONSitself with no CORS grant and refuses any request whoseOriginorSec-Fetch-Sitenames another origin, so the header is defense in depth behind that origin check; the value carries no secret (SameOriginProxyHeaders.cs:3-10).[Rubric §26, Front-End Security]assesses cookie-borne credentials against cross-site request forgery. Once the bearer moves into an HttpOnly cookie, a header the browser will not attach on a cross-site request is what distinguishes the app's own calls.
- Walkthrough: two
const stringmembers and no behavior. Beingconst, both values are baked into each caller at compile time. - Why it's built this way: one shared type instead of a literal per call site keeps the stamp and the check from drifting apart. The proxy design is ADR-131.
- Where it's used: stamped by
SameOriginProxyRequestHandler(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/SameOriginProxyRequestHandler.cs:19-20) and byNotificationHubServiceon the SignalR connection options (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NotificationHubService.cs:389); checked bySameOriginApiProxyEndpointinHasCsrfHeader, which demands exactly one value equal toCsrfHeaderValue(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:127-130); stripped before forwarding bySameOriginProxyTransformer(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginProxyTransformer.cs:80). Covered bySameOriginProxyClientTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/SameOriginProxyClientTests.cs:27).
JsFetchSessionCookieSync
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/JsFetchSessionCookieSync.cs:15· Level 1 · class (sealed)
- What it is: the browser
ISessionCookieSyncimplementation, for Blazor Server interactive mode and WebAssembly. The server is the only writer of the HttpOnly session cookies, so the sign-in half writes nothing; the logout half calls one small JS helper that issues a browser-sidefetch, so the clearingSet-Cookielands in the user's cookie jar (JsFetchSessionCookieSync.cs:6-14). - Depends on:
ISessionCookieSync(the contract),IJSRuntime(Microsoft.JSInterop, its only constructor parameter,JsFetchSessionCookieSync.cs:15),JsInteropFailure(the shared "interop unavailable" filter,MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/JsInteropFailure.cs:27), plus themmcaAuthCookieobject defined in the package's static web assetMMCA.Common/Source/Presentation/MMCA.Common.UI/wwwroot/mmca-auth-cookie.js:7. - Concept introduced, the server writes the cookie, the browser clears it. The server sets the
session cookies itself whenever it obtains or rotates the tokens, so the browser never posts a token
pair to have a cookie written. Clearing is different: on Blazor Server the code runs on the server,
so a server-issued HTTP call would put the clearing
Set-Cookiein the server's own handler, not the user's browser. Routing the clear through JS interop makes the browser the one issuing the request, which is the only way the expiry reaches the right cookie jar (JsFetchSessionCookieSync.cs:7-10).[Rubric §26, Front-End Security]again: no token passes through JS on this path at all.SyncAsyncsends its arguments nowhere (JsFetchSessionCookieSync.cs:20-21), and the clear carries no token.[Rubric §29, Resilience & Business Continuity]assesses degradation. An interop failure during the clear is caught and turned into afalseanswer, so a prerender pass or a disconnected circuit cannot throw out of a sign-out, yet the caller still learns the cookie was not cleared.
- Walkthrough:
SyncAsync(accessToken, refreshToken)(JsFetchSessionCookieSync.cs:24) isTask.FromResult(true): it writes nothing and reports success, because the server already wrote the cookies when it obtained this token pair (doc at lines 17-23).ClearAsync()(line 27) returnsInvokeAsync<bool>("mmcaAuthCookie.clear")(line 31): the script itself reports whether the endpoint answered 2xx, and the class doc records that it tries the clear twice (lines 11-12). Thecatchis filtered byJsInteropFailure.IsUnavailable(ex)(line 33), which names the four types that mean "there is no live JS runtime right now":InvalidOperationException,JSDisconnectedException,JSExceptionandOperationCanceledException(JsInteropFailure.cs:27-31). Such a failure returnsfalsebecause the cookie was not cleared by this call (lines 35-36).
- Why it's built this way: keeping the server as the single writer means a token never has to
travel back out to JS to become a cookie. The "interop unavailable" definition lives once in
JsInteropFailurerather than in a private filter per class. Reporting the clear rather than swallowing it silently lets the sign-out path know the cookie may still be present (seeISessionCookieSync). The cookie contract itself belongs to ADR-022. - Where it's used:
TryAddScopedbehindISessionCookieSyncbyAddClientAuthSessionCookieSync(), whose doc states it clears the cookies at logout and writes nothing on sign-in (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:298-301); consumed byWasmTokenStorageServiceandServerTokenStorageService. Covered byJsFetchSessionCookieSyncTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/JsFetchSessionCookieSyncTests.cs). - Caveats / not-in-source: the
mmcaAuthCookie.clearJS implementation lives inmmca-auth-cookie.js, outside this unit; only the C# side is described here.
SameOriginProxyRequestHandler
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/SameOriginProxyRequestHandler.cs:11· Level 1 · class (internal, sealed)
- What it is: the innermost handler of the
"APIClient"pipeline on a WebAssembly client whose host runs the same-origin API proxy. It removes anyAuthorizationheader and stamps the proxy's CSRF header on every request (SameOriginProxyRequestHandler.cs:3-10). - Depends on:
SameOriginProxyHeadersfor the header name and value; externalDelegatingHandler. - Concept introduced, the browser holds no usable bearer. Behind the proxy the client only ever
holds a claims-only token; the proxy attaches the real bearer server-side from the HttpOnly session
cookie. Any
Authorizationheader the outer handlers (such asAuthDelegatingHandler) or a service'sDefaultRequestHeadersattached is therefore noise at best, so this handler clears it rather than trusting every caller to know.[Rubric §26, Front-End Security]assesses whether a usable credential is reachable from browser code. Here it is not, and the transport enforces that for every request.
- Walkthrough: one override.
SendAsync(request, cancellationToken)(SameOriginProxyRequestHandler.cs:14) guardsrequestwithArgumentNullException.ThrowIfNull(line 16), setsrequest.Headers.Authorization = null(line 18), removes any existing CSRF header and adds exactly one withTryAddWithoutValidation(lines 19-20), then delegates tobase.SendAsync(line 21). Removing first guarantees a single value, which is what the proxy's check demands. - Why it's built this way: registering it innermost means it sees the request after every other
handler and service has had its say, so one place decides what reaches the proxy. It is
registered only when
Api:SameOriginApiEndpointis configured, so every other client (Blazor Server, MAUI, a WebAssembly client of a host that did not opt in) keeps its pipeline unchanged (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:150-155). The proxy design is ADR-131. - Where it's used:
AddTransientandAddHttpMessageHandlerinsideAddUIShared()behind theusesSameOriginProxycheck (DependencyInjection.cs:183-189), after the auth and culture handlers (lines 180-181). The proxy side that reads the CSRF header isSameOriginApiProxyEndpoint.
TokenOwner
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthDelegatingHandler.cs:407· Level 2 · record (private, sealed, nested inAuthDelegatingHandler)
- What it is: the value type of the handler's owner map: which storage attached a bearer, and
when (
AuthDelegatingHandler.cs:406-407). Two positional members,WeakReference<ISessionAwareTokenStorage> Storageandlong TrackedAt. - Depends on:
ISessionAwareTokenStorage(the storage it points at); externalsWeakReference<T>andEnvironment.TickCount64(the clockTrackedAtis stamped from). - Concept reinforced, a weak back-reference keyed by token. The map routes a 401 to the storage
instance that attached the refused bearer, but it is static, so a strong reference would keep every
ended circuit or scope alive. Holding the storage weakly means the map never extends a session's
lifetime (doc at
AuthDelegatingHandler.cs:75-78).[Rubric §29, Resilience & Business Continuity]assesses whether a long-lived process degrades: the entry carries its own timestamp, so a sweep can drop it on age as well as on a dead owner.
- Walkthrough: no members beyond the two positional properties. Entries are created by
TrackTokenOwnerAt(AuthDelegatingHandler.cs:98-102) and stored in the staticOwnersdictionary (line 56). They are read three ways:HasLiveOwner(lines 102-103) and the two report paths resolveStorage.TryGetTargetto find a live owner (lines 237, 318), andIsStale(lines 178-179) treats an entry as droppable whenTrackedAtis older thanRetentionMsor the target is gone. - Why it's built this way: a private nested record keeps the map's shape out of the public
surface; only the handler and its
internaltest hooks touch it. - Where it's used: only inside
AuthDelegatingHandler; no usage outside the defining file.
JwtAuthenticationStateProvider
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/JwtAuthenticationStateProvider.cs:24· Level 2 · class (sealed)
- What it is: the custom
AuthenticationStateProviderthat turns the stored JWT into theClaimsPrincipalBlazor'sAuthorizeViewand[Authorize]read, pushes a new state immediately on login and logout, signs the shell out when the token storage reports that the session ended on the server, and forgets the list pages' persisted search and filters on every sign-in and sign-out. - Depends on:
ITokenStorageService(required constructor parameter),ListPageStateService(optional constructor parameter, defaulted tonull) andISessionAwareTokenStorage(an optional capability it probes the storage for); externalsMicrosoft.AspNetCore.Components.Authorization.AuthenticationStateProvider,System.Security.ClaimsandJwtSecurityTokenHandler. - Concept introduced, Blazor's auth-state contract. Blazor does not know about JWTs; it asks an
AuthenticationStateProviderfor anAuthenticationStateand re-renders everyCascadingAuthenticationStateconsumer when the provider says the state changed. This class is the adapter between "there is a token in storage" and that framework contract.[Rubric §19, State Management & Data Flow]assesses how a cross-cutting piece of UI state propagates. Notifying rather than reloading is the whole point: a sign-in updates the navbar and every guarded fragment without a page refresh (lines 96-99). The class doc also makes this the one place per-tab list state is forgotten, because every sign-out passes through it (JwtAuthenticationStateProvider.cs:18-22).[Rubric §11, Security]assesses the trust boundary, and the class doc draws it: claims are extracted client-side without server validation to keep the UI responsive, and the WebAPI performs full token validation on every request (lines 9-11). The same doc records the second half of that boundary (lines 12-17): a session revoked from another device, or ended by account deletion, flips the shell to anonymous instead of leaving it signed in behind 401s (A-34).
- Walkthrough:
AnonymousState, a single staticAuthenticationStateover an emptyClaimsIdentity(JwtAuthenticationStateProvider.cs:26-27). Because aClaimsIdentitywith no authentication type reportsIsAuthenticated == false, this one shared instance is the "signed out" answer.- One constructor,
(ITokenStorageService tokenStorageService, ListPageStateService? listPageState = null)(line 41). It null-guards the storage (line 45), stores both into_tokenStorageServiceand_listPageState(fields at lines 29-30), and, when the storage is anISessionAwareTokenStorage, subscribesOnSessionEndedto itsSessionEndedevent (lines 50-53). The comment at line 49 explains why no unsubscribe is needed: the provider shares the storage's DI scope and lifetime, so the subscription never outlives either. The parameter doc gives the reason the list state is taken at all: it is mirrored tosessionStorage, which outlives the session in the same tab, so without the clear the next account signing in on that tab saw the previous account's search applied (lines 36-40). GetAuthenticationStateAsync()(line 61) reads the token (line 65) and returns the anonymous state on a blank token (lines 66-69), an unreadable token (lines 72-75), or an expired one (ValidTo < DateTime.UtcNow, lines 78-81). On success it builds aClaimsIdentityfrom the token's claims with the authentication type"jwt", and the comment at line 83 records why that string matters: naming an authentication type is what makes the identityIsAuthenticated. A barecatchunder an annotatedCA1031suppression ("an unreadable token is an anonymous user, never a broken authentication state", lines 88-93) turns any remaining failure, including JS interop being unavailable, into anonymous rather than an exception inside a render.NotifyUserAuthentication(token)(line 100) rebuilds the principal the same way and calls the baseNotifyAuthenticationStateChanged(line 106). It does not consult storage, because the caller has just been handed the token.NotifyUserLogout()(lines 112-113) pushesAnonymousStateback out.SignOutAsync()(line 121,internal) is the sign-out everyAuthUIServicepath ends in: it awaits the list-state clear, then callsNotifyUserLogout(). It is awaited so thesessionStorageremoval lands before the caller'sforceLoadnavigation to the sign-in page tears the page down (doc at lines 115-120).SignInAsync(token)(line 139,internal) is the sign-in counterpart: it awaits the list-state clear, then callsNotifyUserAuthentication(token). The doc (lines 127-137) records why it clears on EVERY sign-in, the same account's included: in WebAssembly a session revoked from another device while the tab was not running ends withoutSessionEnded, so a different account can sign in over a tab that still looks signed in, and telling accounts apart would need an identity that case no longer has. A token refresh is not a sign-in and keeps the state.OnSessionEnded(lines 145-151), the private event handler, starts the list-state clear without awaiting it (_ = ForgetListPageStateAsync(), line 149), because an event handler cannot await and the in-memory state clears synchronously inside the call (comment at lines 147-148), then callsNotifyUserLogout()(line 150). PerMMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/ISessionAwareTokenStorage.cs:3-10,14-18the event fires once, only on a definitive "no session" refresh answer (never on a transient failure), and the stored access token is already cleared when it does.ForgetListPageStateAsync()(lines 153-154) isTask.CompletedTaskwhen no list state was supplied, otherwise_listPageState.ClearAsync().AsTask().
- Why it's built this way: falling back to anonymous on every failure is the safe direction for a
UI gate, since the API rejects anything the client wrongly let through. Keeping the notify methods
public and adding the
internalSignInAsync/SignOutAsyncpair is what letsAuthUIServicedrive the state transition at the exact moment tokens change; it does so behind anis JwtAuthenticationStateProvidertype test (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:201,483,544), so a host that registered a different provider still works. Putting the list-state clear here rather than in each sign-out path means the server-ended session (driven by the storage event) and the client-driven sign-outs cannot disagree about what is forgotten. Both the list state and the session-aware capability are optional (a defaulted parameter and a type test), so a storage that does not implementISessionAwareTokenStoragebehaves exactly as before. - Where it's used: registered with
AddScoped<AuthenticationStateProvider, JwtAuthenticationStateProvider>()by the shared Blazor Server host wiring (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:144) and by the WebAssembly and MAUI heads (MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web.Client/Program.cs:54,MMCA.Store/Source/Hosts/UI/MMCA.Store.UI/MauiProgram.cs:130,MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web.Client/Program.cs:47,MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/MauiProgram.cs:174). Covered byJwtAuthenticationStateProviderTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/JwtAuthenticationStateProviderTests.cs:16), whoseWhenTheStorageReportsTheSessionEnded_NotifiesAnonymous(line 137) andWhenTheStorageReportsTheSessionEnded_ForgetsTheListPageStateAndNotifiesAnonymous(line 152) drive the session-ended path through a fake session-aware storage (itsEndSession, line 178).AuthUIServiceTestsconstructs a real one rather than a double, precisely because the type test above would not match a mock (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/AuthUIServiceTests.cs:80, and with a list state at line 609); the shared token-storage tests do the same (MMCA.Common/Tests/Shared/UI/TokenStorageServiceTestsBase.cs:316). ADR-051 (client auth token lifecycle) mentions it.
IPasskeyUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/IPasskeyUIService.cs:14· Level 3 · interface
- What it is: the client of the API's passkey endpoints under
auth/passkeys: register a passkey for the signed-in user, list, rename and delete them, and sign in with one (IPasskeyUIService.cs:7-13). - Depends on:
Resultand the passkey contractsPasskeyOptionsResponse,PasskeyResponse,PasskeyRegisterRequestandPasskeySignInRequest, plusAuthenticationResponse. Implemented byAuthUIService. - Concept reinforced, the bespoke UI service contract (introduced at
IAuthUIService).[Rubric §9, API & Contract Design]assesses extension without breakage: the doc states this is a separate interface rather than newIAuthUIServicemembers, so a consumer's ownIAuthUIServiceimplementation keeps compiling, following theISignInLinkUIServiceprecedent (lines 8-11).[Rubric §26, Front-End Security]shows in the split between the authenticated management members and the anonymous sign-in pair. - Walkthrough: seven members, every one returning a
Result, in two halves.- Registration is a two-step WebAuthn ceremony:
BeginRegistrationAsync(line 19,POST auth/passkeys/register/options) returns the flow and creation options, andCompleteRegistrationAsync(PasskeyRegisterRequest, ct)(line 25,POST auth/passkeys/register) sends the browser's attestation and a name back and returns the stored passkey. - Management:
ListAsync(line 30,GET auth/passkeys),RenameAsync(id, name, ct)(line 37,PATCH auth/passkeys/{id}) andDeleteAsync(id, ct)(line 43,DELETE auth/passkeys/{id}), whose doc names the refusal a page must expect: the last passkey of a password-less account (line 42). - Sign-in is the same two steps, anonymous:
BeginSignInAsync(line 48,POST auth/passkeys/signin/options) andSignInAsync(PasskeySignInRequest, ct)(line 57,POST auth/passkeys/signin), which stores the token pair and notifies the auth state like a password sign-in (lines 50-53).
- Registration is a two-step WebAuthn ceremony:
- Why it's built this way: implementing it on
AuthUIServicemeans a passkey sign-in stores its tokens through the password sign-in's path (lines 11-12, and the registration comment atMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:209-211). The registration is inert until a host offers passkeys (SignIn:OfferPasskeys) or renders the passkeys panel. The design is ADR-139. - Where it's used: registered
TryAddScoped<IPasskeyUIService, AuthUIService>()inAddUIShared()(DependencyInjection.cs:212); injected byPasskeySignInButton(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/PasskeySignInButton.razor.cs:40) andPasskeysPanel(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/PasskeysPanel.razor.cs:39), and probed byLoginto decide whether to offer passkeys (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor.cs:203).
ISignInLinkUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/ISignInLinkUIService.cs:16· Level 3 · interface
- What it is: the client behind the sign-in-link flow: ask for a link from the sign-in page, and
redeem one on the
/auth/sign-in-linklanding page (ISignInLinkUIService.cs:6-9). - Depends on:
ResultandAuthenticationResponse. Implemented byAuthUIService. - Concept reinforced, the bespoke UI service contract (introduced at
IAuthUIService).[Rubric §11, Security]shows twice in two members: the request side is anti-enumeration and the redeem side is single-use.[Rubric §9, API & Contract Design]: a separate interface rather than newIAuthUIServicemembers, so a consumer's ownIAuthUIServiceimplementation keeps compiling, theIEmailConfirmationUIServiceprecedent (remarks at lines 10-15). - Walkthrough: two members.
RequestSignInLinkAsync(email, ct)(line 25) asks the API to email a link. The endpoint answers 202 for every well-formed address, so a success says nothing about whether the address holds an account; a failure is a malformed request or an outage (lines 18-24).RedeemSignInLinkAsync(email, token, acceptedTerms, ct)(line 36) redeems a link and, on success, stores the token pair and signals the signed-in state. It posts exactly once, because the token is single-use and a retry could only spend it twice (lines 28-29).acceptedTermscarries whether the visitor accepted the Terms of Service on the page (line 33).
- Why it's built this way: implementing it on
AuthUIServicemeans a redeemed link stores its tokens and signals the auth state exactly as a password sign-in does (lines 13-14, and the registration comment atMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:205-206, which ties the flow to ADR-116). - Where it's used: registered
TryAddScoped<ISignInLinkUIService, AuthUIService>()inAddUIShared()(DependencyInjection.cs:207); injected by the landing pageSignInLink(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/SignInLinks/SignInLink.razor.cs:77) and resolved optionally byLoginfor the "email me a link" request (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor.cs:231).
IEmailConfirmationUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/IEmailConfirmationUIService.cs:22· Level 3 · interface
- What it is: the client-side contract for the email-confirmation flow: redeeming a confirmation link's token (alone, or with a password proof when the API asks for one), and asking for a fresh link when the first has expired or was never received.
- Depends on:
Result;ConfirmEmailRequest(the password-proof overload's payload); externals: BCL (Task,CancellationToken,string). - Concept reinforced, the bespoke UI service contract (introduced at
IAuthUIService).[Rubric §18, UI Architecture & Component Design]and[Rubric §26, Front-End Security](assesses that a resend cannot be used to enumerate registered addresses). Three members, all returningResultso a page branches on the outcome instead of catching.ResendEmailConfirmationAsync's own doc comment states the anti-enumeration rule directly, that the endpoint answers 202 whether or not the address holds an account, so a success means "accepted", never "this address exists" (IEmailConfirmationUIService.cs:43-45). The class-level remarks also record why there is no retry: the token is single-use and the resend spends a per-address request budget, so a repeat is a second request rather than a replayed response (IEmailConfirmationUIService.cs:17-19). - Walkthrough: three methods.
ConfirmEmailAsync(string email, string token, CancellationToken cancellationToken = default)(IEmailConfirmationUIService.cs:29) redeems a single-use token viaPOST auth/confirm-email; the doc comment records that the endpoint returns the same generic rejection for every bad token (IEmailConfirmationUIService.cs:24-28).ConfirmEmailWithPasswordAsync(ConfirmEmailRequest request, CancellationToken cancellationToken = default)(IEmailConfirmationUIService.cs:40) is the second attempt at the same endpoint: it is sent after the token alone was answered withEmailConfirmation.PasswordRequired, and carries either the request'sCurrentPasswordor itsNewPasswordas the proof. A failure is the API's own refusal (a wrong password, a lockout, an invalid token) (doc at lines 31-39).ResendEmailConfirmationAsync(string email, CancellationToken cancellationToken = default)(IEmailConfirmationUIService.cs:50) requests a fresh link viaPOST auth/send-email-confirmation, always reported as success at this layer regardless of whether the address is known.
- Why it's built this way: a narrow interface here, rather than the generic
IEntityService<,>, matches the same reasoningIAuthUIServicedocuments: confirming an email is not a CRUD operation on a resource with an identity, so it gets its own contract instead of being bent to fit one ([Rubric §14, Testability]). The registration comment adds the compatibility reason: a separate interface rather than newIAuthUIServicemembers keeps a consumer's ownIAuthUIServiceimplementation compiling (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:201-202). - Where it's used: implemented by
EmailConfirmationUIService; injected byConfirmEmail, which callsConfirmEmailAsyncand thenConfirmEmailWithPasswordAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ConfirmEmail.razor.cs:259,337), byEmailConfirmationResendPrompt(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/EmailConfirmationResendPrompt.razor.cs), by ADC'sEmailConfirmationReminder(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Components/EmailConfirmationReminder.razor.cs) and byMMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Pages/ConfirmEmailPageTestsBase.cs; registeredTryAddScopedinAddUIShared()(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:203).
AuthDelegatingHandler
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthDelegatingHandler.cs:37· Level 5 · class (sealed)
- What it is: the
DelegatingHandlerthat attaches the stored JWT as aBearerheader on every outgoing API request, so no UI service ever sets anAuthorizationheader by hand, and that reports a refused bearer back to the storage that holds it: a 401 triggers one renewal attempt, and a coded 403 raises the "second factor required" signal. One request can opt out through theSkipBearerrequest option. - Depends on:
ITokenStorageService(its only constructor parameter),ISessionAwareTokenStorage(the renewal capability a 401 is reported to),TokenOwner(its owner-map entry),MultiFactorRequiredSignalandAuthErrorCodes(the coded 403 path), andAuthenticatedServiceBase(replay-safety marking); externalsSystem.Net.Http.Headers.AuthenticationHeaderValue,DelegatingHandler,ConcurrentDictionary,StrongBox<long>,InterlockedandSystem.Text.Json.JsonDocument. - Concept introduced, the HTTP message-handler pipeline.
HttpClientcomposes handlers into a chain, each free to inspect or mutate a request before passing it to the next. Registering this one on the named"APIClient"client means auth is applied once, at the transport, for every typed service built on top of it.[Rubric §6, CQRS & Event-Driven Design]assesses whether concerns like auth are centralized rather than repeated per call. This is the client-side twin of the server's middleware pipeline: one registration covers every request, and the same place sees every refusal.[Rubric §11, Security]assesses session handling: a 401 to a bearer makes one refresh attempt, and a refused refresh ends the session so a protected page lands on the sign-in page. A token acquired that way is remembered and a 401 to it is not reported again, so an API that keeps refusing a freshly issued token cannot drive a refresh per request (class doc atAuthDelegatingHandler.cs:21-28).
- Walkthrough:
SkipBearer(AuthDelegatingHandler.cs:45) is a public staticHttpRequestOptionsKey<bool>named"MMCA.Common.UI.Auth.SkipBearer". The token refresh POST sets it: that endpoint is anonymous, and reading token storage from inside a refresh would re-enter the very acquisition that is waiting for the request to complete (doc at lines 40-44).- Four private constants:
SweepThreshold = 1024(line 48),RetentionMs = 24L * 60 * 60 * 1000, 24 hours, longer than any access token lives (line 51),SweepIntervalMs = 60L * 1000, the least time between two sweeps (line 58), andProblemJsonMediaType = "application/problem+json"(line 61). Three static fields hold the cross-request state: the ordinalConcurrentDictionarymapsOwners(token toTokenOwner, line 64) andRenewedTokens(token to the tick it was renewed at, line 67), andLastSweepAt, a readonlyStrongBox<long>holding the tick of the last claimed sweep (line 73), documented as process-wide bookkeeping, never per-user state (lines 69-72). TrackTokenOwner(accessToken, owner)(line 82,internal static) records which storage attached a bearer. It ignores a blank token or a storage that is not anISessionAwareTokenStorage(lines 84-87) and otherwise stores a weak reference stamped withEnvironment.TickCount64(line 89). The reason is in the class doc: the handler resolves its own storage in theIHttpClientFactoryhandler scope, which in a browser host is not the instance the component holds, so without this a service's 401 would go to the wrong storage (lines 30-34).TrackTokenOwnerAt(line 98) andMarkRenewedAt(line 107) write the maps directly and are the hooks tests use to age entries;HasLiveOwner(line 116),IsTrackedOwner(line 122) andIsMarkedRenewed(line 127) read them.- Both writers end with
SweepIfDue()(lines 101 and 110), which sweeps at most once perSweepIntervalMswhatever the call rate (line 157). It asksTryClaimSweep(ref lastSweepAt, now, intervalMs)(line 149,internal static), which reads the last tick withInterlocked.Readand claims the sweep withInterlocked.CompareExchange, so exactly one of any number of concurrent callers wins and the rest touch neither map (lines 151-153). The constant's doc gives the reason: without the pacing every tracked bearer would pay the all-locksCountread, and once the maps passSweepThresholdwith nothing removable (live circuits holding recent tokens), a full scan per call (lines 53-57). The winner runsSweepIfLarge()(line 133):SweepOwners(line 190) andSweepRenewed(line 204) still do nothing until a map holds more thanSweepThresholdentries, then drop the owner entries that are stale (older thanRetentionMsor whose storage is gone,IsStale, lines 217-218) and the renewal entries older thanRetentionMs(IsExpired, line 220). SendAsync(request, cancellationToken)(line 166) is a thin wrapper: it awaits the privateSendWithBearerAsyncinside atry, and on anHttpRequestExceptioncallsAuthenticatedServiceBase.MarkReplaySafety(ex, request)before rethrowing (lines 170-180). The shared retry policy sees only the exception, not the request, so this is where it is told whether the request may be resent: a keyless POST or PATCH may not, once sent (comment at lines 176-177).SendWithBearerAsync(line 222) holds the bearer logic. WhenSkipBeareris set totruethe request passes straight tobase.SendAsyncwithout touching token storage at all (lines 226-229). A request that already carries anAuthorizationheader also gets no stored token (theAuthorization is nullcheck at line 231): the forced-refresh replay sets the token it just acquired, and replacing it with the stored one would resend the token the server just rejected. Otherwise it awaitsGetAccessTokenAsync()(line 233), and only when the result is non-blank setsrequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token)(lines 234-237). It then reads the bearer it is about to send withBearerOf(line 241; the helper at lines 183-188 accepts only a non-blankBearerscheme), before the call, because the same-origin proxy handler further in strips the header (comment at line 240). Afterbase.SendAsync(line 242) a 401 to a request that carried a bearer goes toReportRejectedAsync(lines 244-247) and a 403 goes toReportMultiFactorRequiredAsync(lines 248-261). That 403 call sits in atrywhose barecatchdisposes the response and rethrows (lines 254-260): only a cancellation reaches it, and the caller never receives that response, so it is released here. Otherwise the response is returned unchanged (line 263): it is never replayed.ReportMultiFactorRequiredAsync(line 281) resolves the live owner of the token, falling back to the handler's own storage (lines 287-289), and returns early unless that owner has aMultiFactorRequiredSignalsubscriber and the body isapplication/problem+json(lines 290-294), so a host that never calledAddTwoFactorUI()never has its 403 bodies read (doc at lines 266-275). It buffers the content first so the caller still reads the same response (lines 299-300); a body that fails to arrive (the connection dropped mid-body) raises nothing, swallowed under an annotatedCA1031suppression that lets only a cancellation propagate (lines 302-309). It raises the signal whenCarriesMultiFactorRequired(line 320) findsAuthErrorCodes.MultiFactorRequiredundererrors[*].code(lines 311-314); a body that is not valid JSON is ignored (lines 337-340).PropertyOf(line 347) matches property names ignoring case.ReportRejectedAsync(rejectedToken, fallbackOwner)(line 373,internal static) is the 401 path. A token already inRenewedTokensis skipped, since refreshing again would loop (lines 375-379). Otherwise it resolves the live owner or the fallback as anISessionAwareTokenStorage(lines 381-387) and awaitsRenewRejectedAccessTokenAsync(rejectedToken)(line 391). A renewed token that differs from the refused one is tracked to the same owner and marked renewed (lines 392-396). Any exception other than cancellation is swallowed under an annotatedCA1031suppression (lines 398-403): the caller still receives the server's 401, which is the answer that matters. The doc records it is also the 401 handling for a bearer attached outside this pipeline, the notification hub's WebSocket handshake (lines 363-365). Note the freshness work happens inside the token service: by the time this handler sees a token, a stale one has already been re-acquired. The 401 path is the backstop for a token the server refuses anyway.
- Why it's built this way: a handler rather than a base-class helper, because the pipeline applies
to everything the named client sends, including calls made by code that never inherits from a
framework base. The owner and renewal maps are static because a handler instance is per handler
scope, not per component, and the map has to bridge the two; holding owners weakly, sweeping on
age and pacing the sweep to one claimed run per interval keeps that static state bounded without
making every tracked bearer pay for it. It is registered
AddTransient(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:148), the lifetimeAddHttpMessageHandlerexpects. - Where it's used: added to the
"APIClient"pipeline alongside the culture handler (DependencyInjection.cs:180-181). Code that attaches its own bearer registers its owner:AuthenticatedServiceBase(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:88),AuthUIService(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:597), the file download button (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/ApiFileDownloadButton.razor.cs:230), and the preference reader and writer (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/ApiUserPreferenceReader.cs:49,MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/ApiUserPreferenceWriter.cs:114).NotificationHubServicecallsReportRejectedAsyncfor a refused hub handshake (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NotificationHubService.cs:686). TheSkipBeareroption is set byDirectApiTokenRefresheron its refresh request (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/DirectApiTokenRefresher.cs:67) and byAnonymousApiRequeston every anonymous request it builds (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AnonymousApiRequest.cs:34). On a WebAssembly client of a host running the same-origin proxy,SameOriginProxyRequestHandlersits inside this handler and strips whatever header it attached (DependencyInjection.cs:187-188). Covered byAuthDelegatingHandlerTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/AuthDelegatingHandlerTests.cs:18, including the sweep pacing at lines 214 and 225), bySessionBearerRenewalTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Api/SessionBearerRenewalTests.cs:32) and by a DI resolution test that exists because the pipeline must be able to construct it (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/ApiClientRegistrationTests.cs:22).
IAuthUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/IAuthUIService.cs:17· Level 5 · interface
- What it is: the single client-side authentication contract: login, register, OAuth code
exchange, sign-out of this device, the three password flows, the signed-in-devices list with
revoke, the sign-in history, and sign-out of every device. The password-based auth pages in the
framework talk to this; the sign-in-link, passkey and email-confirmation flows have their own
narrow contracts beside it (
ISignInLinkUIService,IPasskeyUIService,IEmailConfirmationUIService). - Depends on:
Resultand its generic form fromMMCA.Common.Shared.Abstractions; theMMCA.Common.Shared.AuthcontractsLoginRequest,RegisterRequest,AuthenticationResponse,RefreshSessionSummaryResponseandSignInSummaryResponse; andErrorTypefor the failure kinds it documents. Implemented byAuthUIService. - Concept introduced, the failure travels with the call. The interface doc states the rule
(
IAuthUIService.cs:10-15): every call that talks to the API returns aResultcarrying the server's own errors, so the failure arrives with the call rather than on aLastErrorproperty that the next call would overwrite. Pages render it throughMMCA.Common.UI.Common.ResultUiExtensions(ResultUiExtensions).[Rubric §9, API & Contract Design]assesses whether return types carry meaning. Three different shapes appear here on purpose (Result<T>,Result, and one bareTask), and the deviation is argued in source rather than assumed.[Rubric §24, Forms, Validation & UX Safety]assesses whether a form can show the server's real message. Because the failure is the return value, a login page can bind the error next to the field without a second lookup.[Rubric §11, Security]shows in documented behaviors: the anti-enumeration contract on password reset, and the OAuth exchange keeping tokens out of the address bar and carrying the proof-key verifier a native sign-in started with.
- Walkthrough: eleven members, in the order they appear.
LoginAsync(LoginRequest, ct)andRegisterAsync(RegisterRequest, ct)both returnResult<AuthenticationResponse>and both store tokens on success (IAuthUIService.cs:20,23).ExchangeOAuthCodeAsync(code, codeVerifier, ct)(line 36) trades a single-use completion code carried in the redirect URL for the token pair throughauth/oauth/exchange, stores the tokens and notifies auth state; the doc's closing sentence names the reason for the indirection, keeping tokens out of the address bar (lines 25-28).codeVerifieris the proof-key verifier kept with the attempt (OAuthFlowStateStore.FindCodeVerifierAsync,OAuthFlowStateStore): required when the sign-in was started with its S256 challenge (the native heads),nullfor a flow started without one (lines 31-34).LogoutAsync()(line 45) is the deliberate no-Resultmember: it signs out this device only, revoking this device's server-side refresh session throughauth/revoke/currentand clearing local storage, so the account stays signed in on its other devices. It returns nothing because the local sign-out happens whatever the server answered: a user who asked to leave must never be kept signed in by a failed network call (lines 38-44).ChangePasswordAsync(currentPassword, newPassword, ct)(line 48) hitsauth/password.RequestPasswordResetAsync(email, ct)(line 55) hits the anonymousauth/forgot-password. The doc pins the semantics: the endpoint answers 202 for every well-formed address as an anti-enumeration measure, so a success means "accepted", never "an account exists" (lines 50-54).ResetPasswordAsync(email, token, newPassword, ct)(line 62) completes the reset via the anonymousauth/reset-password; an invalid, expired or already-consumed token comes back as a failure carrying the server's generic message (lines 57-61).GetSessionsAsync(ct)(line 70) returnsResult<IReadOnlyList<RefreshSessionSummaryResponse>>fromauth/my-sessions, newest first, and documents that exactly one row can carryIsCurrent, resolved server-side from the access token'ssidclaim (lines 64-69).GetSignInsAsync(ct)(line 79) returnsResult<IReadOnlyList<SignInSummaryResponse>>fromauth/my-sign-ins: one row per sign-in however often it refreshed, ended ones included with how they ended, newest first, at most 50, the caller's own carryingIsCurrent(lines 72-78).RevokeSessionAsync(sessionId, ct)(line 88) signs one device out viaauth/revoke/{sessionId}; another account's session id (or a nonexistent one) answers 404 and arrives as anErrorType.NotFoundfailure, and revoking an already-revoked session answers the same 404 (lines 81-85).RevokeAllSessionsAsync(ct)(line 98) signs out of every device viaauth/revokeand, unlikeLogoutAsync, returns the server's answer as aResult. A failed revoke is reported rather than hidden, and the local session is left in place so the caller can say so and let the user retry; on success it also performs the same local sign-outLogoutAsyncdoes (lines 90-97). The pair is the clearest statement of the return-shape rule: two sign-outs with opposite failure policies, because "leave this device" must never fail while "end every session" must never claim success it did not get.
- Why it's built this way: the interface is where the return shapes are justified, and each
justification is a behavior rule rather than a style preference. The eleven operations stay on one
contract because they share one consumer set (the shipped auth and devices pages are framework
types); newer flows were added as separate interfaces instead, so a consumer's own implementation
of this one keeps compiling (
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:201-202). Token renewal is not a member: it lives below this contract, in the token storage services, the refreshers (ITokenRefresher) and theAuthDelegatingHandler401 path. The device-list and revoke members are the UI surface of ADR-097; the OAuth exchange is the client end of ADR-036 and ADR-043. - Where it's used: registered
TryAddScopedagainstAuthUIServicebyAddUIShared()(DependencyInjection.cs:196, the comment at line 195 notingTryAddprevents duplicate registration when several hosts call in); injected by the shipped auth pages, includingLogin(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor:361),OAuthComplete, which passes the stored verifier (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/OAuthComplete.razor:90), andSessions, which lists devices and sign-ins and whose sign-out-everywhere action callsRevokeAllSessionsAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor.cs:100,132,246).SignOutNavigatorwrapsLogoutAsyncfor every component that signs out (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/SignOutNavigator.cs:47-51).
EmailConfirmationUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/EmailConfirmationUIService.cs:22· Level 7 · class (sealed)
- What it is: the
IEmailConfirmationUIServiceimplementation. It posts to the two confirmation endpoints and translates the response through the sharedHttpResultExecutor/ProblemDetailsResultReaderpath used across the auth services. - Depends on:
IEmailConfirmationUIService(the contract it implements);IHttpClientFactory(its only constructor parameter,EmailConfirmationUIService.cs:22);ConfirmEmailRequestandSendEmailConfirmationRequest(the payloads);HttpResultExecutorandProblemDetailsResultReader(MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ProblemDetailsResultReader.cs) for the transport and response-translation work;AnonymousApiRequest(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AnonymousApiRequest.cs:14) to build the bearer-less request. - Concept reinforced, one shared execution path for every anonymous auth POST. All three members
funnel through the private
PostOnceAsync<TRequest>helper, so the retry policy and response translation are written once rather than duplicated per endpoint.[Rubric §15, Best Practices & Code Quality]assesses duplication; the three public methods are each a single expression forwarding to the shared helper, without its ownasyncstate machine (EmailConfirmationUIService.cs:27-36).[Rubric §29, Resilience & Business Continuity]is answered by what the helper deliberately does not do: no retry, because a repeat here is a second request (a spent token, a second email), never a replayed response (EmailConfirmationUIService.cs:44-45).
- Walkthrough:
ApiClientName = "APIClient"(EmailConfirmationUIService.cs:24) names the shared named client.ConfirmEmailAsync(lines 27-28) posts aConfirmEmailRequest(email, token)toauth/confirm-email.ConfirmEmailWithPasswordAsync(lines 31-32) posts the caller's ownConfirmEmailRequest, the one carrying a password proof, to the sameauth/confirm-email.ResendEmailConfirmationAsync(lines 35-36) posts aSendEmailConfirmationRequesttoauth/send-email-confirmation.PostOnceAsync<TRequest>(relativeUrl, body, cancellationToken)(line 38) creates a freshHttpClientfrom the factory (line 42), builds the request withAnonymousApiRequest.PostJson(relativeUrl, body)(line 46), sends it withSendAsync(line 47) and reads the result withProblemDetailsResultReader.ReadAsync(line 49), all wrapped inHttpResultExecutor.ExecuteAsync(line 39) for the shared transport-fault translation.AnonymousApiRequestsetsAuthDelegatingHandler.SkipBeareron the request (AnonymousApiRequest.cs:28-35), so the"APIClient"pipeline neither attaches a token left from an earlier sign-in nor reads the token storage for one.
- Why it's built this way: both actions are anonymous on the server, so each request opts out of
the bearer explicitly rather than relying on there being no stored token (class remarks,
EmailConfirmationUIService.cs:16-17). Opting out also keeps a 401 here from being reported to the storage as a rejected session (AnonymousApiRequest.cs:8-12). A freshHttpClientper call (rather than a stored field) matches how the other anonymous auth services in this package are built, since the client is cheap to create from the factory and this service holds no other per-call state. - Where it's used: covered by
EmailConfirmationUIServiceTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/EmailConfirmationUIServiceTests.cs:16); registered againstIEmailConfirmationUIServiceinAddUIShared()(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:203).
AuthUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:49· Level 7 · class (sealed)
- What it is: the one client-side service that owns a user's session on a Blazor or MAUI head. It
calls the WebAPI
auth/*endpoints (sign in, register, OAuth code exchange, sign-in links, passkeys, change password, forgot and reset password, list and revoke devices, sign-in history, sign out), persists the returned token pair, and tells Blazor's authentication state that something changed, soAuthorizeViewand[Authorize]routes react without a page reload. It implements three contracts, IAuthUIService, ISignInLinkUIService and IPasskeyUIService (AuthUIService.cs:56), so every way of signing in stores its tokens through one path. Every method that talks to the API hands back a Result carrying the server's own error text, so no page has to interpret anHttpResponseMessage. - Depends on: first-party
ITokenStorageService (token persistence,
AuthUIService.cs:51), JwtAuthenticationStateProvider (injected as the frameworkAuthenticationStateProviderbase type atAuthUIService.cs:52and pattern-matched back down), IPushRegistrationService (native push cleanup,AuthUIService.cs:53), ILocalCacheStore (optional device-local document cache, defaulted tonull,AuthUIService.cs:54, wiped on sign-out), IDeviceMetadataReporter (optional per-session device reporter,AuthUIService.cs:55) run through DeviceMetadataReporting, an optionalILogger<AuthUIService>(AuthUIService.cs:56), AuthDelegatingHandler (owner tracking for the bearers it attaches), HttpResultExecutor (transport-fault translation), AnonymousApiRequest (the bearer-less request for every anonymous endpoint), ProblemDetailsResultReader (response translation), AuthClaimTypes (the view-as claim a sign-out tests for), and the shared auth contracts LoginRequest, RegisterRequest, OAuthCodeExchangeRequest, ChangePasswordRequest, ForgotPasswordRequest, ResetPasswordRequest, SendSignInLinkRequest, RedeemSignInLinkRequest, PasskeyRegisterRequest, PasskeySignInRequest, PasskeyOptionsResponse, PasskeyResponse, AuthenticationResponse, RegistrationOutcome, RefreshSessionSummaryResponse and SignInSummaryResponse. Externals:IHttpClientFactory,System.Net.Http.Json(PostAsJsonAsync,PutAsJsonAsync,PatchAsJsonAsync),System.Net.Http.Headers.AuthenticationHeaderValue,System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler, andMicrosoft.AspNetCore.Components.Authorization.AuthenticationStateProvider. - Concept introduced, the client-side session lifecycle as one service, with a sign-out that cannot
fail. Everything a session needs on the client (acquire a token pair, hold it, publish the
identity to the component tree, and tear all of that down) lives behind injectable interfaces with a
single implementation, so no component ever touches
localStorage, a Bearer header, or a token string.[Rubric §26, Front-End Security]assesses whether credentials are confined to a narrow, auditable surface in the browser: here the only code that reads or writes tokens is this service plus AuthDelegatingHandler, both of them going through ITokenStorageService rather than doing JS interop of their own.[Rubric §11, Security]assesses the end-to-end auth design. There are two sign-outs with opposite failure policies.LogoutAsyncis deliberately local-first and ends this device only: the local sign-out runs in afinally, and every remote step before it (the push unregister, the token read, the revoke) is best effort and bounded, so a dropped connection or a throwing refresh can never strand a user inside a session they asked to leave (AuthUIService.cs:106-140,148-160,561-578).RevokeAllSessionsAsyncis server-first: it reports a failed revoke and only signs out locally once the server confirmed, so "signed out everywhere" is never claimed when it did not happen (AuthUIService.cs:214-234). A view-as token (ADR-137) is never used to revoke a session of the viewed account: sign-out ends the view instead (AuthUIService.cs:123-134).[Rubric §19, State Management]assesses who owns mutable client state and when it is invalidated: this service is the single writer of auth state, and every sign-out it performs also wipes the device-local document cache, whose plaintext snapshots survive restarts and are keyed by surface rather than by user (AuthUIService.cs:36-41), and, through the provider, the per-tab list-page state.[Rubric §18, UI Architecture]sees the same shape the entity services use, a typed service over the named"APIClient"returningResult, so pages render failures with ResultUiExtensions instead of catching exceptions.[Rubric §14, Testability]is served by taking every collaborator through the primary constructor with no statics of its own, plus a test-onlyinittimeout: AuthUIServiceTests drives the whole class through a stubHttpMessageHandler. - Walkthrough
- Two public error codes head the class.
TokenStorageUnavailableCode = "Auth.TokenStorageUnavailable"(AuthUIService.cs:62) is reported when authentication succeeded but the tokens could not be written because JS interop was unavailable (SSR prerender, or a render-mode transition), andMissingAccessTokenCode = "Auth.MissingAccessToken"(AuthUIService.cs:68) covers a 2xx whose body carried no access token, which means the response shape drifted. Both areconst string, so tests and pages branch on them without duplicating literals. The private constantsApiClientName = "APIClient",RevokeCurrentPath = "auth/revoke/current"andViewAsEndPath = "auth/view-as/end"follow (AuthUIService.cs:70-72), and theinternalLogoutStepTimeoutproperty (line 78, aninitsettable by tests only) is 10 seconds: how long each remote step of a sign-out may take before the sign-out moves on without it (doc at lines 74-77). LoginAsync(line 81) andRegisterAsync(lines 90-91) are one-liners over the privateAuthenticateAsync, differing in the relative URL (auth/login,auth/register) and inRegisterAsyncpassingallowConfirmationPending: true: behind the email gate the API answers202 Accepted(account created, confirmation pending, no session), which comes back as a success carryingRegistrationOutcome.ConfirmationPendingwith nothing stored and no sign-in (remarks at lines 85-89).ExchangeOAuthCodeAsync(code, codeVerifier, ct)(AuthUIService.cs:94) guards the code client-side first: a blank code returnsError.Validation("Auth.OAuth.MissingCode", ...)without a round trip (AuthUIService.cs:96-100), then it hands an OAuthCodeExchangeRequest withCodeVerifierset toAuthenticateAsyncagainstauth/oauth/exchange(AuthUIService.cs:102). The single-use code arrives in the redirect URL, which is what keeps the tokens themselves out of the address bar (ADR-036,Website/docs-src/adr/036-external-oauth-login.md), and the verifier proves the native head that started the sign-in is the one finishing it (ADR-043,Website/docs-src/adr/043-mobile-deep-links-and-native-oauth-callback.md).AuthenticateAsync(AuthUIService.cs:446) is the shared body of every sign-in: login, register, OAuth exchange, sign-in-link redemption and passkey sign-in. It builds the credential POST withAnonymousApiRequest.PostJson(relativeUrl, request)(line 457), which setsAuthDelegatingHandler.SkipBearerso no stored token rides along and a 401 for a wrong password is not reported to the storage as a rejected session (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AnonymousApiRequest.cs:5-13), and sends it withSendAsync(line 458) through HttpResultExecutor (lines 453-467); when a 202 is allowed it short-circuits to the confirmation-pending success (lines 459-463), otherwise it readsProblemDetailsResultReader.ReadAsync<AuthenticationResponse>(line 465). It returns early on failure or confirmation-pending (lines 469-472), then checks the access token is actually present and fails withMissingAccessTokenCodeif it is not (lines 474-479). Only then does it calltokenStorageService.SetTokensAsync(line 483) inside atrythat converts anInvalidOperationExceptioninto aTokenStorageUnavailableCodefailure carrying the exception message as detail (lines 485-507). The point of that branch is that valid credentials nothing can hold are a failure, not a silent no-op; on browser hosts it also fires when the HttpOnly cookie write reports failure, because the token storage services throw on afalsefrom ISessionCookieSync. Before returning that failure it cleans up after itself: the server already minted a session and the storage took the access token in memory before the cookie write failed, so it revokes the session throughTryRevokeAsync(authentication.AccessToken, ...)(line 492) and then clears the stored tokens (line 495, swallowing a secondInvalidOperationException, lines 497-500), or the API client would behave signed in behind a page that reported failure (comment at lines 487-491). On success it pattern-matches the injectedAuthenticationStateProviderdown to JwtAuthenticationStateProvider and awaits itsSignInAsync(lines 511-514), which forgets the previous account's list-page state before publishing the new identity (comment at lines 509-510). Theistest rather than a cast is what lets a host register a different provider without breaking sign-in. Last it runsReportDeviceAsync(line 517), after the tokens are stored so the report's bearer names the new session.ReportDeviceAsync(lines 527-533) callsDeviceMetadataReporting.ReportAsync(line 531) only when a reporter was injected. The constructor doc records that the registered default is a no-op, the MAUI package replaces it, and its wait is bounded with failures logged and swallowed, so it can never fail or hold up a sign-in (lines 42-47).LogoutAsync(AuthUIService.cs:106) puts its remote steps in atryand the local sign-out in thefinally(SignOutLocallyAsync(), line 139), so the local half runs whatever the remote half did, a throwing refresh included (comment at lines 112-117). First the privateUnregisterPushAsync()(line 110). Second it reads the bearer throughReadAccessTokenForRevokeAsync()(line 118): that read may refresh a stale token, so the revoke is not refused as a 401, and it is bounded byLogoutStepTimeoutwith aWaitAsync(line 153) and answersnullon any failure or timeout, which skips the revoke (lines 143-160). With a token in hand it opens aCancellationTokenSourceofLogoutStepTimeout(line 121), bounded rather than left to the client's 90 sHttpClient.Timeoutso a hung backend cannot hold the sign-out. A view-as token (tested byIsViewAsToken, line 127) is refused onauth/revoke/currentand must never revoke a session of the viewed account, so it postsViewAsEndPathinstead, ending the view before the local sign-out clears the cookies and the overlay (lines 123-130); any other token goes toTryRevokeAsync(line 133).TryRevokeAsync(lines 169-170) is the shared best-effort revoke, a one-line forward toTryPostWithBearerAsync(RevokeCurrentPath, ...). It ends only the session that token belongs to, so the account stays signed in on its other devices, and it is shared with the login path that cannot store the session it was just issued, so the two revokes cannot drift (doc at lines 163-168).TryPostWithBearerAsync(line 176) creates an APIClient, sets the Bearer header by hand (line 179) and posts a bodiless request to the given path (line 183) inside a barecatchthat ignores every failure (lines 185-190).IsViewAsToken(line 197) reads the JWT withJwtSecurityTokenHandlerand looks for theAuthClaimTypes.ViewAsActorclaim (lines 201-203); a token that does not parse is simply not a view-as token (lines 205-210).RevokeAllSessionsAsync(AuthUIService.cs:214) postsauth/revokethrough HttpResultExecutor on an authenticated client, reading it with the non-generic reader (lines 216-224). Only when the result is a success does it runUnregisterPushAsync()thenSignOutLocallyAsync(), in the same order asLogoutAsyncso the push unregister still holds a valid access token (lines 226-232); either way it returns the server'sResult(line 234). A failure leaves the local session intact for the caller to report and retry.- The password trio all wrap HttpResultExecutor.
ChangePasswordAsync(line 238) is the only one that authenticates: it builds a ChangePasswordRequest andPUTs it toauth/password(lines 247-248).RequestPasswordResetAsync(line 254) andResetPasswordAsync(line 296) deliberately send no Bearer header, building their POSTs withAnonymousApiRequest.PostJson(lines 261 and 305-306), because a reset must not be bound to whatever session happens to be open (comment at lines 258-259). The comment at lines 264-265 records the contract that matters:auth/forgot-passwordanswers 202 for every well-formed address, so a success never means "this account exists". - The sign-in-link pair implements ISignInLinkUIService.
RequestSignInLinkAsync(line 271) posts a SendSignInLinkRequest to the anonymousauth/sign-in-linkthroughAnonymousApiRequest.PostJson(line 277) and reads it with the non-generic reader (line 280).RedeemSignInLinkAsync(line 285) hands a RedeemSignInLinkRequest carrying the email, token andacceptedTermsflag toAuthenticateAsyncagainstauth/sign-in-link/redeem(lines 290-293), so a redeemed link is stored and signalled exactly like a password sign-in. - The session methods back the devices page.
GetSessionsAsync(line 313)GETsauth/my-sessionsand reads it with the generic reader intoIReadOnlyList<RefreshSessionSummaryResponse>(lines 321-322);GetSignInsAsync(line 327) does the same forauth/my-sign-insintoIReadOnlyList<SignInSummaryResponse>(lines 335-336).RevokeSessionAsync(line 341) postsauth/revoke/{sessionId}and reads it with the non-generic reader (lines 350-351), because that endpoint answers 204 and ProblemDetailsResultReader's generic overload would turn an empty 2xx body into an "empty response" failure (comment at lines 348-349). Picking the wrong overload there would turn every successful revoke into an error. - The passkey members implement IPasskeyUIService, each on an authenticated
client except the sign-in pair:
BeginRegistrationAsync(line 356,auth/passkeys/register/options),CompleteRegistrationAsync(line 368,auth/passkeys/register),ListAsync(line 380),RenameAsync(line 391),DeleteAsync(line 403, the non-generic reader again because the endpoint answers 204, comment at line 409),BeginSignInAsync(line 416,auth/passkeys/signin/options, an empty bearer-less POST built withAnonymousApiRequest.Postat line 422, so a stale session cannot ride along, comment at line 420) andSignInAsync(lines 429-430), which goes throughAuthenticateAsyncagainstauth/passkeys/signin. - Private helpers close the class.
UnregisterPushAsync(line 541) callspushRegistration.UnregisterAsync(timeout.Token).WaitAsync(timeout.Token)under aLogoutStepTimeoutsource (lines 543-546) inside a barecatch(lines 548-553): the Devices DELETE is authenticated, so it has to happen while the access token is still valid, a hung DELETE may not hold the sign-out, and it is a no-op on web heads (ADR-044,Website/docs-src/adr/044-native-push-delivery.md, doc at lines 535-540).SignOutLocallyAsync(line 561) is the local half of both sign-outs in this class (doc at lines 556-560):tokenStorageService.ClearTokensAsync()undercatch (InvalidOperationException)for the interop-unavailable case (lines 563-570), thenClearLocalCacheAsync()(line 572), then the provider'sSignOutAsync()behind the type test (lines 574-577), which forgets the list-page state and notifies logout. The four#pragma warning disable CA1031blocks (lines 155-157 inReadAccessTokenForRevokeAsync, 185-187 inTryPostWithBearerAsync, 205-207 inIsViewAsToken, 548-550 inUnregisterPushAsync) are deliberate and annotated in place: catching everything is the correct policy for a best-effort step.CreateAuthenticatedClientAsync(line 586) creates the APIClient, setsDefaultRequestHeaders.Authorizationfrom the stored token (line 593) and registers that token's owner withAuthDelegatingHandler.TrackTokenOwner(line 597), so a 401 to it renews or ends the session this page holds rather than the handler's own storage (comment at lines 595-596); its doc comment states that it mirrors AuthenticatedServiceBase and cannot inherit it, because this is not an entity service and takes a different dependency set (lines 580-585).ReadAccessTokenAsync(line 603) swallowsInvalidOperationExceptionfrom the store and returnsnull, so an SSR prerender proceeds tokenless and lets the API answer 401 like any other failure (lines 609-614).ClearLocalCacheAsync(line 620) no-ops whenlocalCacheisnull(lines 622-625), otherwise callslocalCache.ClearAsync()(line 629) inside acatch (InvalidOperationException)for the same JS-interop-gone case the token clear guards against (lines 631-634), so a device-local offline snapshot never survives to be read by the next account on the same device.
- Two public error codes head the class.
- Why it's built this way: ADR-051 (
Website/docs-src/adr/051-client-auth-token-lifecycle.md) is the record behind the split visible in the constructor: storage and orchestration are different abstractions because each render mode (SSR prerender, Blazor Server, WebAssembly, MAUI) can hold and renew a credential differently, while the orchestration above them stays identical. Renewal is not this class's job at all: it happens further down, inside the storage service, the refreshers (ITokenRefresher) and the AuthDelegatingHandler 401 path, which is why the constructor takes no refresher. The refresh path itself is server-side rotation with reuse detection (ADR-050,Website/docs-src/adr/050-jwt-refresh-token-rotation.md), generalized to one row per device by ADR-097 (Website/docs-src/adr/097-multi-device-refresh-sessions.md), which is what givesGetSessionsAsync,RevokeSessionAsyncand the this-device-onlyauth/revoke/currentsomething to list and revoke. Browser hosts keep the refresh token in an HttpOnly cookie rather than in reachable storage (ADR-022,Website/docs-src/adr/022-browser-session-cookie-auth.md). Implementing the sign-in-link and passkey contracts on this class rather than in their own services means every sign-in sharesAuthenticateAsync, so token storage, the storage-failure revoke, the provider sign-in and the device report cannot drift between flows (registration comments atMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:205-211). ReturningResultinstead of throwing keeps every auth failure renderable: the API's Problem Details payload already carries the server's own wording and ErrorType, so the page shows that rather than a client-invented message. - Where it's used: registered three times in
AddUIShared(), asTryAddScoped<IAuthUIService, AuthUIService>(),TryAddScoped<ISignInLinkUIService, AuthUIService>()andTryAddScoped<IPasskeyUIService, AuthUIService>()(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:196,207,212), so every host that adds the shared UI gets it. Consumers inside the shared UI are the auth pages (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor:361,Pages/Auth/Register.razor:250,Pages/Auth/OAuthComplete.razor:90,Pages/Auth/ForgotPassword.razor:95,Pages/Auth/ResetPassword.razor:157), the devices page Sessions (Pages/Auth/Sessions.razor.cs:100,132,176,246), the sign-in-link and passkey surfaces through their own interfaces, and SignOutNavigator, which callsLogoutAsync(Services/Navigation/SignOutNavigator.cs:47-51) on behalf of the components that sign out (Layout/MainLayout.razor:218,Layout/NavMenu.razor.cs:70,Components/Capabilities/BiometricGate.razor.cs:270,Components/Legal/TermsAcceptanceGate.razor.cs:237,Pages/Auth/TwoFactor/TwoFactorAccount.razor.cs:319). Downstream, the shared ChangePasswordCard callsChangePasswordAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/ChangePasswordCard.razor.cs:149), and the consumer profile pages (Profile) host that card rather than calling the service themselves.ForgotPassword.razordiscards theResultof its call (line 95), because the page must look identical whether or not the address exists. The component gallery substitutes NoOpAuthUIService, and AuthUIServiceTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/AuthUIServiceTests.cs:40) pins the behavior end to end. - Caveats:
CreateAuthenticatedClientAsyncsets aDefaultRequestHeadersBearer while AuthDelegatingHandler would otherwise attach one to every APIClient request from storage (DependencyInjection.cs:180); the handler skips its own lookup when the request already carries anAuthorizationheader (Services/Auth/AuthDelegatingHandler.cs:231), so the stored token is read once here and the handler leaves that header alone. Behind the same-origin proxy both are then stripped by SameOriginProxyRequestHandler. TheSignOutLocallyAsyncdoc still names "an unrefreshable session" among its callers (AuthUIService.cs:557-558), but no such caller remains in this class: onlyLogoutAsyncandRevokeAllSessionsAsynccall it.
AppUserAgent
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Devices·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Devices/AppUserAgent.cs:10· Level 0 · class (public, static)
- What it is: builds the
User-Agentheader value a native MMCA app sends, in the shapeName/Version (Platform OsVersion; MmcaApp), so the server can tell an app session from a browser session and the signed-in-devices page can label it. - Depends on: nothing first-party; BCL only (
string.Normalize,CharUnicodeInfo,StringBuilder). - Concept introduced, a header value built from untrusted text must be made header-safe. App name,
version and OS version come from the device, and an HTTP header token cannot hold spaces,
parentheses, slashes or non-ASCII.
Buildtherefore sanitizes every part instead of trusting it.[Rubric §11, Security]assesses whether externally sourced text is neutralized before it reaches a protocol boundary. Comment text drops the delimiters(,), the escape\and the separator;(AppUserAgent.cs:112), so a hostile or odd OS string cannot close the comment early or forge theMmcaAppmarker.[Rubric §15, Best Practices & Code Quality]shows in the singleSanitizeroutine shared by both character classes (AppUserAgent.cs:79), parameterized by predicate and replacement character.
- Walkthrough:
Marker = "MmcaApp"(AppUserAgent.cs:13) is the public token the reader side looks for;FallbackName = "App"(line 16) stands in when nothing of the app name survives sanitizing, andTokenSymbols(line 19) lists the punctuation an RFC 9110 token may hold.Build(appName, appVersion, platform, osVersion)(line 29) rejects a blankappNamewithArgumentException.ThrowIfNullOrWhiteSpace(line 31), tokenizes the name (falling back toApp, lines 33-37) and the version, joins them asname/versionor justname(lines 39-40), then builds the comment from the normalized platform and OS version (lines 42-44). The result isproduct (system; MmcaApp), orproduct (MmcaApp)when both system parts are empty (lines 46-48).NormalizePlatform(line 55) renames MAUI's UI-stack names to OS names:WinUIbecomesWindowsandMacCatalystbecomesmacOS(lines 59-64).ToToken(line 71) andToCommentText(line 77) callSanitize(line 79): it folds accents withFormDand drops non-spacing marks, then collapses each run of disallowed characters into one replacement (a hyphen for tokens, a space for comment text), never leading with one.IsTokenChar(line 110) is ASCII letters, digits andTokenSymbols;IsCommentChar(line 112) is visible ASCII minus the four reserved characters.
- Why it's built this way: the writer and the reader are separate classes with one shared constant,
so the marker cannot drift:
UserAgentSummarymatches onAppUserAgent.Markerrather than a literal. Sanitizing at the writer keeps the reader's parse trivially simple. - Where it's used: called once by
MauiAppUserAgentHandlerto build its cached header (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/Services/MauiAppUserAgentHandler.cs:21); read back byUserAgentSummary.ParseApp(UserAgentSummary.cs:185,161). Pinned byAppUserAgentTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/Devices/AppUserAgentTests.cs).
BackfillGate
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Devices·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Devices/DeviceMetadataReporting.cs:95· Level 0 · class (private, sealed, nested)
- What it is: the two-flag state
DeviceMetadataReportingkeeps per reporter instance, answering "is the refresh backfill done?" and "is one running right now?" so the backfill reports until one report succeeds and never runs twice at once. - Depends on: nothing first-party; BCL
VolatileandInterlockedonly. - Walkthrough: two
intfields,_reportedand_running(DeviceMetadataReporting.cs:97-98).TryBegin(lines 100-101) returnstrueonly when_reportedstill reads 0 and aCompareExchangeflips_runningfrom 0 to 1, so a concurrent refresh that loses the race skips rather than waits.End(line 103) releases_running;MarkReported(line 105) sets_reportedfor good, after whichTryBeginalways refuses. - Why it's built this way: an
intpair withVolatile/Interlockedis the lock-free form of a one-shot gate: nothing blocks, and a joiner simply skips the backfill because another call is already doing it. The class doc states the two questions it answers (line 94). - Where it's used: only inside
DeviceMetadataReporting, created on demand byGates.GetValue(DeviceMetadataReporting.cs:47,75), opened byTryBegin(line 76), released in afinally(line 87) and closed byMarkReportedafter any recorded report (line 47).
IDeviceMetadataReporter
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Devices·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Devices/IDeviceMetadataReporter.cs:22· Level 0 · interface
- What it is: the client-side contract that reports the device this app runs on to the server,
which records it on the caller's current refresh session (
PUT auth/sessions/current/device), so the signed-in devices list and the sign-in history name the device instead of describing its user-agent (IDeviceMetadataReporter.cs:3-6). - Depends on: nothing first-party in its signature. Implemented by
NullDeviceMetadataReporter(the default on every head) and byMauiDeviceMetadataReporteron native heads; the metadata it sends is the server-sideDeviceMetadatarecord. - Concept introduced, a best-effort side call with a boolean contract. The device report rides
behind a sign-in or a refresh that already succeeded, so it must never be able to fail or delay
either. The interface encodes that in two ways: the class doc makes "should not throw" part of the
contract and says the callers bound the wait and swallow whatever escapes
(
IDeviceMetadataReporter.cs:14-20), and the single method returnsboolinstead of throwing, so "not recorded, try again later" is an ordinary answer.[Rubric §9, API & Contract Design]assesses whether a contract states its failure semantics.ReportAsyncdocuments both answers (IDeviceMetadataReporter.cs:28-32):truewhen the server recorded the report or there is nothing to report,falsewhen it was not recorded, so the refresh backfill tries again on the next refresh.
- Walkthrough: one member,
Task<bool> ReportAsync(CancellationToken cancellationToken = default)(IDeviceMetadataReporter.cs:33). The caller cancels the token after a short bound (line 27; the bound isDeviceMetadataReporting.Timeout). - Why it's built this way: the class doc (
IDeviceMetadataReporter.cs:7-13) explains the two callers. The sign-in path reports every time; the native token storage also reports after a successful refresh until one report in the process has succeeded, so a session that began before the server stored device metadata gets described within one access-token lifetime without a new sign-in. Rotation then carries the metadata to every successor session. It must be registered as a singleton because the once-per-process state is tracked per reporter instance (lines 17-19). The device capability abstraction this sits in is ADR-042; the refresh lifecycle it piggybacks on is ADR-051. - Where it's used: registered as the no-op default with
TryAddSingleton(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Capabilities/DependencyInjection.cs:72) and replaced on MAUI withAddSingleton(MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/DependencyInjection.cs:102). Called throughDeviceMetadataReportingbyAuthUIServiceafter each sign-in (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:531) and bySecureStoreTokenStorageServiceafter a refresh (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/SecureStoreTokenStorageService.cs:141). Pinned byAuthUIServiceDeviceReportTestsandSecureStoreDeviceBackfillTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/Devices/).
OidcProviderOption
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.OAuth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/OidcProviderOption.cs:12· Level 0 · record (sealed)
- What it is: one configured generic OIDC sign-in provider as the sign-in page sees it:
Name(the scheme name and the/auth/oauth/{name}route segment),DisplayName(the button text) andUsesDomains(whether the provider declares email domains, which turns on the email-first "Sign in with your organization" step) (OidcProviderOption.cs:3-12). - Depends on: nothing beyond the BCL.
- Concept reinforced, availability without secrets (introduced by
IOAuthUISettings). The record doc says it outright: never its client id or secret (line 4).[Rubric §26, Front-End Security]assesses what the client is told, and this shape carries only what a button needs. - Where it's used: listed by
IOAuthUISettings.OidcProviders(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/IOAuthUISettings.cs:22) and built from configuration byConfigurationOAuthUISettings(ConfigurationOAuthUISettings.cs:51-58). TheLoginpage holds the list (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor.cs:45), renders one button per entry (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor:260) and offers the organization step when any entry hasUsesDomains(line 304). Pinned byLoginOidcTestsandConfigurationOAuthUISettingsOidcTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/).
PendingAttempt
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.OAuth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/OAuthFlowStateStore.cs:172· Level 0 · record (private, sealed)
- What it is: one OAuth redirect in flight, as OAuthFlowStateStore keeps it:
State(the random value sent on the challenge URL),StartedAt(the timestamp used to expire an abandoned attempt) and an optionalCodeVerifier(the RFC 7636 proof-key verifier a native head starts its attempt with,nullfor a web attempt) (OAuthFlowStateStore.cs:172). - Depends on: nothing beyond the BCL (
string,DateTimeOffset). - Where it's used: only inside OAuthFlowStateStore, as the element of the
stored PendingAttempts list: created in
BeginCoreAsync(OAuthFlowStateStore.cs:104), filtered by age inReadLiveAttemptsAsync(OAuthFlowStateStore.cs:160-164), matched byStateinFindCodeVerifierAsyncandTryCompleteAsync(OAuthFlowStateStore.cs:91,148). It never crosses the store's own boundary.
PendingAttempts
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.OAuth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/OAuthFlowStateStore.cs:174· Level 1 · record (private, sealed)
- What it is: the value OAuthFlowStateStore writes under its single
StorageKey: a wrapper over a nullableIReadOnlyList<PendingAttempt>namedAttempts(OAuthFlowStateStore.cs:174), so several concurrent attempts (two tabs, or a retry while the first provider tab is still open) each keep their own entry rather than overwriting one another (OAuthFlowStateStore.cs:25-29). - Depends on: PendingAttempt (the element type); otherwise the BCL.
- Where it's used: only inside OAuthFlowStateStore.
BeginCoreAsyncwrites it and reads it back to confirm the new attempt was kept (OAuthFlowStateStore.cs:105,109-110);ReadLiveAttemptsAsyncreads it, tolerating a missing value, a null list or a null entry (OAuthFlowStateStore.cs:162-163);WriteAttemptsAsyncwrites it back, or removes the key when no attempt is left (OAuthFlowStateStore.cs:167-170).
DeviceMetadataReporting
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Devices·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Devices/DeviceMetadataReporting.cs:14· Level 1 · class (internal, static, partial)
- What it is: the one place that runs an
IDeviceMetadataReporterfor its two callers, the sign-in path and the refresh backfill, under the same rules: the wait is capped, and any failure (cancellation included) is logged and swallowed, so a report never fails or holds up the call it follows (DeviceMetadataReporting.cs:6-13). - Depends on:
IDeviceMetadataReporterand its own nestedBackfillGate; externalsConditionalWeakTable,CancellationTokenSource,Task.WaitAsyncand the[LoggerMessage]source generator. - Concept introduced, bounding a call you do not control. A cancellation token only works if the
callee honors it.
ReportAsynctherefore applies the bound twice: it links the caller's token to aCancelAfter(Timeout)source and passes that to the reporter, and it also wraps the returned task inWaitAsync(Timeout, cancellationToken), so a reporter that ignores cancellation still cannot hold the caller past the bound (comment and call atDeviceMetadataReporting.cs:41-43).[Rubric §13, Observability & Operability]assesses whether swallowed failures stay visible. The broadcatchis deliberate (theCA1031suppression at lines 52-54 names the reason, best-effort) and still logs through a generatedLogReportFailedatWarninglevel (lines 58, 91-92).
- Walkthrough:
Timeout = 3seconds (DeviceMetadataReporting.cs:20): the report follows a request that just succeeded, so it normally takes a fraction of that; the bound only caps a hung connection (lines 16-19).Gates(line 27) is aConditionalWeakTable<IDeviceMetadataReporter, BackfillGate>: backfill state keyed by reporter instance rather than a static flag, so it lives and dies with the reporter it describes (lines 22-26).ReportAsync(reporter, logger, cancellationToken)(line 34) runs one bounded report (lines 38-43). When the report was recorded it marks the reporter's gate reported, whoever the caller was, because a recorded device needs no backfill: rotation carries it forward (lines 44-48). Any exception is logged when a logger was supplied and turned intofalse(lines 53-62).ReportOncePerProcessAsync(reporter, logger)(line 73) is the refresh backfill. It gets the gate, returns immediately whenTryBeginrefuses (lines 75-79: already reported, or a report is already running), otherwise runsReportAsyncwithCancellationToken.Noneand releases the gate in afinally(lines 81-88). A failed report leaves the gate open, so the next successful refresh (one per access-token lifetime) tries again; nothing retries in between (doc at lines 65-69).
- Why it's built this way: two callers with one rule set is a duplication risk; centralizing the
bound, the swallow and the gate here keeps
AuthUIServiceandSecureStoreTokenStorageServiceto a one-line call each. Keying the gate by instance is what makes the "register as a singleton" requirement onIDeviceMetadataReporterload-bearing. - Where it's used:
ReportAsyncfromAuthUIService.ReportDeviceAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:531);ReportOncePerProcessAsyncfrom the native token storage after a refresh, deliberately after the hydrate slot is cleared because the report authenticates through theAPIClientpipeline whose bearer read comes back to that storage (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/SecureStoreTokenStorageService.cs:137-142).
IOAuthUISettings
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.OAuth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/IOAuthUISettings.cs:10· Level 1 · interface
- What it is: tells the shared login page which external identity providers this host can actually use: three booleans for the built-in providers plus the list of configured generic OIDC providers, so a sign-in button renders only where the provider is really wired up.
- Depends on:
OidcProviderOption(the element type ofOidcProviders). Implemented in the framework byConfigurationOAuthUISettings, which is also the default registration; consumed by the sharedLoginpage. - Concept introduced, default interface members as a safe-off baseline. All four members carry a
body: the three flags return
falseand the provider list returns[](IOAuthUISettings.cs:13,16,19,22), so an implementation can be an empty class and still compile with every provider hidden.[Rubric §18, UI Architecture & Component Design]assesses whether a component asks a typed contract rather than reaching into configuration. The login page injects this interface and never touchesIConfiguration, so the same markup works on a host that has no OAuth at all.[Rubric §26, Front-End Security]assesses what the client is told. The contract carries availability only: no client id, no secret, no redirect URI, and the OIDC entries carry a name, a display name and a domains flag. The class docs state the intent directly, that implementations declare availability so the login page can conditionally render social buttons (IOAuthUISettings.cs:5-6).
- Walkthrough: three get-only flags,
GoogleEnabled(IOAuthUISettings.cs:13),GitHubEnabled(line 16) andAppleEnabled(line 19), each declared asbool X => false, andIReadOnlyList<OidcProviderOption> OidcProviders => [](line 22), documented as the providers configured underOAuth:Oidc:<Name>, one sign-in button each (line 21). - Why it's built this way: external login is optional per host, and the decision has to be readable from the render tree. Making the interface the question (rather than a settings object) lets the framework register a configuration-driven default and lets a host swap in its own answer without any page change. Adding OIDC as a defaulted member kept every existing implementation compiling. The federated login flow the flags gate is recorded in ADR-036, and the mobile callback variant in ADR-043.
- Where it's used:
AddUIShared()registersConfigurationOAuthUISettingsas the default with aTryAddSingletonfactory, which offers no provider when no OAuth keys are configured (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:257, with the override instructions in the comment at lines 251-256). The shared login page injects it (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor:16), guards the Apple, Google and GitHub buttons on it (lines 192, 214, 236), renders one button per OIDC provider (line 260), and inOnInitializedfolds everything into one_hasExternalProvidersvalue (lines 305-306) that decides whether the whole external-login block renders (line 180). MMCA.ADC registersConfigurationOAuthUISettingson all three heads (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:80,MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web.Client/Program.cs:34,MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/MauiProgram.cs:96).
IOidcDiscoveryUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.OAuth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/IOidcDiscoveryUIService.cs:9· Level 1 · interface
- What it is: the client behind the sign-in page's "Sign in with your organization" step. It asks
the API which configured OIDC provider owns an email address's domain, which is home-realm discovery
(
IOidcDiscoveryUIService.cs:5-8). - Depends on:
OidcDiscoveryResponse(the shared answer: provider name and display name). - Concept introduced, home-realm discovery. With many organization providers configured, a button
per provider stops scaling and leaks which organizations use the app. The email-first step instead
takes the address, and the server maps its domain to a provider; the client only learns the one
match. The server side is
OidcProviderRegistry. - Walkthrough: one member,
DiscoverAsync(string email, CancellationToken)(IOidcDiscoveryUIService.cs:15), returning the provider ornullwhen no provider claims the domain (line 14). - Where it's used: registered with
TryAddScopedtoOidcDiscoveryUIService(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:216, comment at 214-215: inert until the host configures an OIDC provider that declares email domains). TheLoginpage resolves it at the click withGetServicerather than injecting it, so a host or a component test that never offers the step does not have to register it (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor.cs:283-289). Pinned byLoginOidcTests.
NullDeviceMetadataReporter
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Devices·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Devices/NullDeviceMetadataReporter.cs:8· Level 1 · class (sealed)
- What it is: the no-op
IDeviceMetadataReporter, the default on every head. A browser reports no device metadata; its sessions are described from the user-agent the server records at sign-in (NullDeviceMetadataReporter.cs:3-7). - Depends on:
IDeviceMetadataReporteronly. - Concept reinforced, the Null Object as a registration default (the same move
NullNotificationScopeProvidermakes for notification scoping).[Rubric §2, Design Patterns]assesses whether a pattern removes branching. The detail that matters is the answer:ReportAsyncreturnsTask.FromResult(true)(NullDeviceMetadataReporter.cs:11), "nothing to report", so the first sign-in closes the backfill gate inDeviceMetadataReportingand no caller ever retries it. - Where it's used: registered with
TryAddSingleton(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Capabilities/DependencyInjection.cs:72; comment at 70-71); the MAUI package replaces it withMauiDeviceMetadataReporter.
UserAgentSummary
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Devices·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Devices/UserAgentSummary.cs:21· Level 1 · class (internal, static)
- What it is: a deliberately tiny
User-Agentreader that turns a session's header into the device label a person recognizes their own device by: the browser and the platform for a web session, or the app name and platform for a native MMCA app. When a native client reported device metadata, the label uses that instead. Shared by the signed-in-devices page, the administrator's sessions table and the sign-in history table. - Depends on:
AppUserAgent(itsMarkerconstant,UserAgentSummary.cs:185),DeviceMetadata(the reported name, model and platform); externalsIStringLocalizer(forDescribe) andstring.ContainswithStringComparison.OrdinalIgnoreCase. - Concept introduced, scoping a parser to the question actually asked. The class doc argues the
design rather than describing it (
UserAgentSummary.cs:6-15): a device list only has to let someone answer "is that me?", so a full UA database buys precision nobody reads, while the browser-and-platform pair separates a phone from a work laptop. Anything unrecognized reportsnullfromParse, andDescribesupplies its own "unknown device" wording rather than dumping the raw header, which is neither readable nor localizable.[Rubric §27, Internationalization & Localization]assesses whether user-visible text survives translation. This is the sharpest example in the package: the parts are returned separately and never joined in code, because composing "Chrome on Windows" would hard-code English word order.Describeformats them through localizer resources (Auth.Sessions.Device.Format,Auth.Sessions.Device.AppFormat,Auth.Sessions.Device.Unknown,UserAgentSummary.cs:114-124, andAuth.Sessions.Device.NamedFormat, line 146; ADR-027 is named in the class doc, lines 16-19).[Rubric §32, Dependency & Supply-Chain]applies to what is absent: no UA-parsing library and no data file to keep current, which is a real dependency avoided for a cosmetic feature.
- Walkthrough:
Browsers, eleven(Token, Name)pairs in most-specific-first order (UserAgentSummary.cs:28-41). Order is load-bearing and the comment says why (lines 23-26): every Chromium browser also says "Chrome", and Chrome and Edge both say "Safari", soEdg/,EdgiOS/andEdgA/come beforeOPR/, which comes beforeCriOS/andChrome/, which come beforeSafari/.Platforms, ten pairs with the same rule (UserAgentSummary.cs:47-59):Windows PhonebeforeWindows,Mac OS XandMacintoshbeforeLinux, because an iPad reports "Macintosh" in desktop mode and Android reports "Linux".AppPlatforms, nine(Word, Name)pairs (UserAgentSummary.cs:65-76) for the one-word platform a native app header carries, including MAUI's desktop names (WinUItoWindows,MacCatalysttomacOS).Parse(string? userAgent)(line 86) returns(null, null)for a missing or blank header (lines 88-91), otherwise runs the shared matcher over each table and returns the pair (line 93).Describe(userAgent, localizer)(line 103) is the header-only label. It reads the native-app marker BEFORE the browser tokens, because an app header that also carries a WebView'sChrome/token is still the app (lines 107-115). Otherwise aswitchover theParsepair covers all four null combinations: both present uses theFormatresource, one present returns it bare, neither returns the localized unknown string (lines 117-125).Describe(device, userAgent, localizer)(line 137) is the overload every view calls. It treats blank metadata values as absent throughBlank(line 163), takes the device name, and builds a detail from the model and platform withDescribeHardware(line 154), which reuses the sameFormatresource so the word order stays a resource (comment at line 153). Name and detail together useNamedFormat(line 146), either one alone is returned bare, and with neither it falls back to the header-onlyDescribe(line 149), which is every browser session.ParseApp(line 169) finds the first(and the)after it (searching only from the(on, throughAsSpan(commentStart).IndexOf(')'), lines 182-183), splits the comment on;, and returns(null, null)unless the parts containAppUserAgent.Marker(lines 184-188). The app name is the product token before any/(lines 190-196); the platform is the first word of the first comment part, mapped byMatchAppPlatform(lines 198-201).MatchAppPlatform(line 208) checksAppPlatformscase-insensitively, then falls back to the browserPlatformstable, then to the raw word (lines 210-218).Match(userAgent, candidates)(line 221) walks a table in order and returns the first name whose token appears case-insensitively, ornull.
- Why it's built this way: ordered tables plus one loop keep the whole implementation small, so
adding a browser is one line and the ordering rule is visible at the point it matters. It is
internalbecause nothing outside the package should treat it as a UA parser, andDescribelives here (rather than in each view) so the views cannot label the same session differently. Reported metadata wins over the header because a native app's header names only the app and the platform, while the metadata names the device itself. - Where it's used: three call sites of the metadata-aware
Describe:Sessions.DescribeDevice(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor.cs:267), the adminUserSessionsTable.DescribeDevice(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/UserSessionsTable.razor.cs:69) andSignInHistoryTable(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/SignInHistoryTable.razor.cs:74). Pinned byUserAgentSummaryTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/Devices/UserAgentSummaryTests.cs). The devices page is the UI half of ADR-097.
OAuthFlowStateStore
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.OAuth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/OAuthFlowStateStore.cs:20· Level 2 · class (sealed)
- What it is: binds an OAuth authorize-redirect to the client that started it, by minting a random
statevalue, persisting it with a start time, and later checking that the value the provider's callback returns matches one of the attempts this client started. It is the anti-CSRF half of the flow described by ADR-036, and on the native heads it also carries the proof-key (PKCE) verifier across the redirect. - Depends on:
ILocalCacheStore(device-local storage, injected,OAuthFlowStateStore.cs:20) for persistence,TimeProvider(injected, defaulted toTimeProvider.System,OAuthFlowStateStore.cs:20,37) for the expiry check,System.Security.Cryptography.RandomNumberGeneratorto mint the state value, and its own private records PendingAttempts (the stored shape) and PendingAttempt (one entry in it). - Concept introduced, device-local state binding for a redirect-based flow. A browser or MAUI OAuth
challenge leaves the app entirely and comes back on a different navigation, so nothing in memory
survives the round trip; the only thing that can prove the callback belongs to the request this
client made is a value written to durable storage before the redirect and checked after it.
[Rubric §11, Security]assesses this exact class of defense:BeginAsyncmints the value withRandomNumberGenerator.GetHexString(32, lowercase: true)(OAuthFlowStateStore.cs:101), a cryptographically strong source, notGuid.NewGuid()or a counter. It also fails closed: with no storage to bind against, a completion is refused rather than waved through. - Walkthrough:
StorageKey = "auth.oauth-flow"(OAuthFlowStateStore.cs:23),MaxPendingAttempts = 5(OAuthFlowStateStore.cs:29, "two tabs, or a retry click while the first provider tab is still open, each keep their own. The oldest is dropped past this") andAttemptLifetime = 10minutes (OAuthFlowStateStore.cs:35, "comfortably longer than a provider round trip and far shorter than a session, so an abandoned attempt cannot be revived days later").IsEnforced(OAuthFlowStateStore.cs:44) reportsstore.IsAvailable:falseonly on a host that registered neither the browser nor the native local-storage capability. There nothing durable can be written across the redirect, so every completion is refused (doc at39-43).BeginAsync(OAuthFlowStateStore.cs:56) andBeginWithCodeVerifierAsync(OAuthFlowStateStore.cs:70, which first rejects a null or blank verifier, line 72) both delegate toBeginCoreAsync(OAuthFlowStateStore.cs:94). That returnsnullimmediately when storage is unavailable (96-99), otherwise mints the state, reads the live attempts, keeps the newestMaxPendingAttempts - 1of them plus the new PendingAttempt and stores them as one PendingAttempts value underStorageKey(101-105), then reads the value back and checks that some entry carries the new state, ordinal comparison (109-110). The read-back exists because the browser store swallows a failed write (comment at107-108); if the attempt was not kept (storage full, site data blocked, private mode) it throwsInvalidOperationException(112-113, documented at51-55), so the failure surfaces before the redirect for the page to explain rather than one redirect later as an unexplained refusal. On success it returns the state for the caller to append to the challenge URL (116).FindCodeVerifierAsync(OAuthFlowStateStore.cs:83) returns the verifier kept with the live attempt whose state matchesreturnedState, ornullwhen storage is unavailable, the value is empty, nothing matches, or the attempt was started without one (85-91). It does not consume the attempt, so a completion page reads it before callingTryCompleteAsync(doc at76-82).TryCompleteAsync(OAuthFlowStateStore.cs:132) returnsfalsewhen storage is unavailable (134-139, "fail closed: with nowhere to keep the attempt, no completion can be shown to belong to this client"). Otherwise it reads the attempts still insideAttemptLifetime(141), finds the one whose state matches a non-emptyreturnedStateexactly, ordinal comparison, and removes only that one (146-152). The remaining list is written back even without a match, which prunes the expired entries (154-155), and the call reports whether a match was found (156). An absent or empty value never matches: every legitimate flow round-trips the state, and accepting an omitted parameter would let a pasted link bypass the binding (comment at143-145). Because only the matching attempt is consumed, a stray or forged completion (a stale bookmark, a crafted link) is refused without consuming another tab's pending attempt (doc at119-128).ReadLiveAttemptsAsync(OAuthFlowStateStore.cs:160) drops null entries and anything older thanAttemptLifetime, oldest first;WriteAttemptsAsync(OAuthFlowStateStore.cs:167) removes the key outright when no attempt is left.
- Why it's built this way: ADR-036 (
Website/docs-src/adr/036-external-oauth-login.md) is the OAuth design this binds into; a single-use, time-boxed local record per attempt, together with refusing a completion that omits the state or cannot be bound at all, is what keeps a replayed, stale, or forged callback from being accepted. Keeping a short list rather than one slot lets concurrent attempts coexist. The verifier rides along because another app can register the same custom scheme and receive a native head's completion redirect; the server redeems the code only for the holder of the verifier (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/Capabilities/Auth/MauiExternalAuthBroker.cs:86-89). - Where it's used: registered in
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:224(TryAddScoped). The web flow begins on theLoginpage (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor.cs:378,BeginAsync); the native flow begins inMMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/Capabilities/Auth/MauiExternalAuthBroker.cs:91(BeginWithCodeVerifierAsync, the store injected at line 43). Both complete on theOAuthCompletepage, which reads the verifier and then consumes the attempt (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/OAuthComplete.razor:77,79). Pinned byOAuthFlowStateStoreTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/OAuthFlowStateStoreTests.cs), with the page wiring covered byLoginOAuthAttemptTestsandOAuthCompleteTests.
ConfigurationOAuthUISettings
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.OAuth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/ConfigurationOAuthUISettings.cs:20· Level 2 · class (sealed)
- What it is: the real
IOAuthUISettings: it computes provider availability and the generic OIDC provider list once at construction from theOAuthconfiguration section, and covers both a server host and a WASM client with a single class. - Depends on:
IOAuthUISettings(the contract it implements),OidcProviderOption(the list element) andOidcReservedProviderNames(the names an OIDC section may not take); externallyMicrosoft.Extensions.Configuration(IConfiguration,IConfigurationSection). - Concept introduced, one class over two configuration shapes. A server host holds the actual
OAuth client ids, so "is Google available" is answered by whether
OAuth:Google:ClientIdis populated. A WASM client must never receive a client id, so it is handed pre-computedOAuth:GoogleEnabledflags through its runtime configuration endpoint instead (ConfigurationOAuthUISettings.cs:9-12). The class accepts either signal. Generic OIDC providers follow the same two shapes underOAuth:Oidc:<Name>: a server lists a section whoseClientIdis set, a WASM client lists a section flaggedEnabled(class doc, lines 14-17).[Rubric §26, Front-End Security]assesses what configuration reaches the browser. The WASM path carries availability flags only, never the client id, and the class shape is what makes that possible without a second implementation.[Rubric §15, Best Practices & Code Quality]assesses duplication. One class, one rule per shape, every provider.
- Walkthrough:
- Four get-only auto-properties,
GoogleEnabled,GitHubEnabled,AppleEnabled(lines 23, 26, 29) andOidcProviders(line 32, "in configuration order"), set in the constructor (line 34), which null-guards the configuration (line 36), takes theOAuthsection (line 38), evaluates each built-in provider through the shared helper (lines 39-41) and reads theOidcchild section (line 42). IsProviderEnabled(oauth, provider)(line 45) is the built-in rule: parse{provider}Enabledas a bool (line 47), and return true when that flag is set or when{provider}:ClientIdis non-empty (line 48).ReadOidcProviders(oidc)(line 51) keeps each child section whose key is not reserved and that is enabled (line 53), and projects it to anOidcProviderOptionwith the section key asName, a trimmedDisplayNamefalling back to the key (line 56), andUsesDomains(lines 51-58). The reserved check isOidcReservedProviderNames.IsReserved(MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ExternalProviders/OidcReservedProviderNames.cs:22), a case-insensitive set ofgoogle,github,apple,complete,exchangeanddiscover(OidcReservedProviderNames.cs:16): the built-in provider names and the OAuth route segments, which a configured OIDC section may never shadow.IsOidcProviderEnabled(line 60) is the same flag-or-client-id disjunction onEnabledandClientId;UsesDomains(line 63) is true for aUsesDomainsflag or any non-blankDomainsentry.- Because the values are read once into properties, a render pass never re-walks configuration.
- Four get-only auto-properties,
- Why it's built this way: the flag-or-client-id disjunction is what lets the same type serve both
hosts. The server side of the pairing is documented from the API package, which notes that the same
OAuth:{Provider}:ClientIdkeys the API reads are what this class reads for itsGoogleEnabled/GitHubEnabledanswers (MMCA.Common/Source/Presentation/MMCA.Common.API/Authentication/ExternalAuthExtensions.cs:18). The federated-login design behind the flags is ADR-036. - Where it's used: it is the framework default, registered by
AddUISharedwithTryAddSingleton<IOAuthUISettings>through a factory that reads the configuration when first resolved, so a configuration source a head adds later still counts (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:257, comment at251-256: a head that configures noOAuthkeys needs no registration of its own, and a head with its own rule registers it withTryAddbefore that call orAddSingletonafter). MMCA.ADC registers no implementation of its own. On the server head,ClientConfigOAuthSectionprojects the resolved settings into theOAuthsection of/client-configin exactly the shape this class reads on the WASM client: the three built-in flags plus, per OIDC provider,Enabled,DisplayNameandUsesDomains, never a client id (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigOAuthSection.cs:31-44, written into the document atMMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:118-121). Pinned byConfigurationOAuthUISettingsOidcTests,OAuthUISettingsRegistrationTestsandClientConfigEndpointTests.
OidcDiscoveryUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.OAuth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/OidcDiscoveryUIService.cs:11· Level 2 · class (internal, sealed)
- What it is: the framework's
IOidcDiscoveryUIServiceover the API's anonymousGET auth/oauth/discoverendpoint, through the named"APIClient"HttpClient (OidcDiscoveryUIService.cs:6-10). - Depends on:
IOidcDiscoveryUIService,OidcDiscoveryResponse; externalsIHttpClientFactoryandSystem.Net.Http.Json. - Concept reinforced, a status code that is an answer versus one that is a failure. A 404 here
means "no provider claims this domain", a normal outcome the page turns into a message, while a
throttle or an outage must not be mistaken for that answer.
[Rubric §9, API & Contract Design]assesses whether a client maps the server's contract faithfully: this one maps exactly one status tonulland lets every other failure throw (theHttpRequestExceptionis documented atOidcDiscoveryUIService.cs:16). - Walkthrough:
ApiClientName = "APIClient"(line 13).DiscoverAsync(line 17) null-guards the address (line 19), creates the named client (line 21), sendsauth/oauth/discover?email=...with the address escaped throughUri.EscapeDataString(lines 22-24), returnsnullon404 Not Found(lines 28-31, reason in the comment at 26-27), callsEnsureSuccessStatusCode(line 33) and deserializes the response body (line 34). - Why it's built this way:
internalbecause hosts swap the interface, not this class, and a named client fromIHttpClientFactoryreuses theAPIClientregistration other UI services already go through, so the call needs no base address of its own (the URI is relative, line 23). - Where it's used: registered with
TryAddScoped(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:216) and reached only throughIOidcDiscoveryUIServicefrom theLoginpage.
ISecureTokenStore
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Tokens·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/ISecureTokenStore.cs:16· Level 0 · interface
- What it is: raw token persistence with no freshness semantics. It reads back exactly what was
written and never triggers a refresh, which is what separates it from the storage contract callers
actually consume,
ITokenStorageService. - Depends on: nothing first-party. Implemented by
MauiSecureTokenStoreover OS SecureStorage; consumed byDirectApiTokenRefresherand bySecureStoreTokenStorageService. - Concept introduced, splitting storage from freshness to keep the graph acyclic. This interface
exists for a dependency-graph reason that the source states in full
(
ISecureTokenStore.cs:4-9):ITokenStorageService, the layer callers consume, depends onITokenRefresher; the refresher in turn depends on this raw store. The chain runs storage, then refresher, then raw store, with no loop. Collapse the two storage interfaces into one and the refresher would depend on the very acquisition that invoked it, which is a re-entrancy hazard at runtime, not just a diagram problem.[Rubric §1, SOLID]assesses whether a single interface has one reason to change. Here two responsibilities that look identical from the outside (read a token, write a token) are separated precisely because one of them is allowed to go to the network and the other is not.[Rubric §11, Security]assesses where credentials rest. The remarks record that only hosts which persist tokens themselves implement it: MAUI backs it with OS SecureStorage, while the browser hosts hold the access token in memory and keep the refresh token in an HttpOnly cookie, so they have no raw store to expose (ISecureTokenStore.cs:10-14).
- Walkthrough: four members, all verbatim.
GetAccessTokenAsync()reads the stored access token ornull(ISecureTokenStore.cs:19).GetRefreshTokenAsync()does the same for the refresh token (line 22).SetTokensAsync(accessToken, refreshToken)persists both, replacing whatever was there (line 25).ClearTokensAsync()removes both, the logout path (line 28).
- Why it's built this way: the interface is deliberately dumber than the one above it. Because it promises no freshness, an implementation can be a thin wrapper over a platform API with no policy, and the single-flight hydration policy lives once, higher up, in the storage services.
- Where it's used: registered on the MAUI head only,
services.AddScoped<ISecureTokenStore, MauiSecureTokenStore>()(MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/DependencyInjection.cs:139, with the rationale at lines 113-123). Injected intoDirectApiTokenRefresher(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/DirectApiTokenRefresher.cs:27) and mocked directly inDirectApiTokenRefresherTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/DirectApiTokenRefresherTests.cs:31). - Caveats / not-in-source: no browser host implements it. Resolving it on a Blazor Server or WASM head is a DI failure by design, not an oversight.
ITokenRefresher
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Tokens·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/ITokenRefresher.cs:17· Level 0 · interface
- What it is: a one-method contract for acquiring a fresh JWT access token, abstracting over the fact that each host holds its refresh credential somewhere completely different.
- Depends on: nothing first-party. Implemented by
SameOriginProxyTokenRefresheron the browser heads andDirectApiTokenRefresheron MAUI; consumed byWasmTokenStorageService,ServerTokenStorageService,SecureStoreTokenStorageServiceandAuthUIService. - Concept introduced, one contract over two materially different security models. The interface
doc enumerates both (
ITokenRefresher.cs:4-15): on the browser the refresh token lives in an HttpOnly cookie and rotation happens server-side behind the same-origin/auth/session/tokenendpoint, so the refresh token is never exposed to JS; on MAUI the refresh token sits in OS SecureStorage and is exchanged directly against the API's cross-originauth/refresh.[Rubric §11, Security]assesses whether the strongest available mechanism is used per platform. A browser has an XSS surface and gets the cookie proxy; a native app has no DOM and gets direct token handling. The abstraction is what lets both be correct without a shared lowest common denominator.[Rubric §7, Microservices Readiness]shows in the fact that the two implementations talk to two different origins (the UI host for one, the API for the other) behind one signature.
- Walkthrough: a single member,
Task<string?> AcquireAccessTokenAsync(CancellationToken cancellationToken = default)(ITokenRefresher.cs:24). The nullable return is the whole error model:nullmeans no valid session exists, whether the refresh credential is missing, expired, or revoked (lines 15-19). There is no exception path a caller has to know about. - Why it's built this way: null-rather-than-throw matches how the callers use it. Token storage
calls this on a hot path (every outgoing request may hydrate) and "the session is gone" is an
ordinary outcome, not an exceptional one. Modelling it as an exception would force a
tryaround every hydrate. - Where it's used: registered per host,
AddScoped<ITokenRefresher, SameOriginProxyTokenRefresher>()on the Blazor Server and WASM heads (MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:115,MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web.Client/Program.cs:45) andAddScoped<ITokenRefresher, DirectApiTokenRefresher>()on MAUI (MMCA.Store/Source/Hosts/UI/MMCA.Store.UI/MauiProgram.cs:97).
TokenAcquisition
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Tokens·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/TokenAcquisition.cs:9· Level 0 · class (sealed)
- What it is: the three-way outcome of a token-acquisition attempt: a token, a definitive "no
session", or a transient failure. It is a sealed value holder with a private constructor
(
TokenAcquisition.cs:11), so the only ways to get one are its three factories. - Depends on: nothing first-party. Produced by
ISessionAwareTokenRefresherimplementations (SameOriginProxyTokenRefresher,DirectApiTokenRefresher) and read byWasmTokenStorageService. - Concept introduced, making "absent" and "unknown" different values. A nullable token collapses
two very different facts: the server said there is no session, or the attempt failed and said
nothing. Treating the second as the first makes a signed-in user look anonymous after a 429 or a
dropped connection.
[Rubric §12, Performance & Scalability]: only the definitiveNoSessionlets storage skip repeat token POSTs, and the type, not an exception or a magic null, carries that distinction.[Rubric §11, Security]: a revoked or reused refresh token isNoSession, but a 409 on a superseded token isUnavailable(DirectApiTokenRefresher.cs:86-89), so the stored pair is not cleared by a race.
- Walkthrough:
NoSession(line 35), the static outcome for an answer that proves there is no session (the endpoint's 401);AccessTokenisnullandIsUnavailableis false.Unavailable(line 38), for an attempt that failed without saying anything about the session;IsUnavailableis true, so the next read should try again (lines 43-47).Acquired(accessToken)(line 52) callsArgumentException.ThrowIfNullOrWhiteSpace(line 54) and returns an outcome carrying the token, so a blank token can never masquerade as success.AccessToken(line 41) isnullfor both non-success outcomes.
- Why it's built this way: the two static singletons avoid allocation on the hot "no token" paths, and the private constructor keeps the invariant (a token implies not unavailable) unforgeable. Design rationale: ADR-051.
- Where it's used: returned by
TryAcquireAccessTokenAsyncin both refreshers, and consumed inWasmTokenStorageService.HydrateAsync(WasmTokenStorageService.cs:200-202) and the handoff session services (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/HandoffSessionServices.cs). Covered throughWasmTokenStorageServiceTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/WasmTokenStorageServiceTests.cs).
ITokenStorageService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Tokens·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/ITokenStorageService.cs:8· Level 0 · interface
- What it is: the platform-agnostic token contract every other UI type depends on. Anything that needs a bearer token asks this, and never asks where the token is kept.
- Depends on: nothing first-party. Implemented by
WasmTokenStorageService,ServerTokenStorageServiceandSecureStoreTokenStorageService. - Concept introduced, the freshness-checking storage layer. It shares its four member signatures
with
ISecureTokenStore, and the difference is entirely in the promise: this one may go and acquire a token, the raw store may not. Reading the two interfaces side by side is the fastest way to understand the auth layering in this package.[Rubric §3, Clean Architecture]assesses whether presentation code depends on abstractions rather than platform APIs. Nothing above this line namesSecureStorage,HttpContext, or a cookie.[Rubric §11, Security]assesses the storage decision itself, and the doc makes it explicit: browser hosts hold the access token in memory and mirror the refresh token to an HttpOnly cookie, neverlocalStorage; MAUI uses OS SecureStorage (ITokenStorageService.cs:3-7).
- Walkthrough:
GetAccessTokenAsync()(ITokenStorageService.cs:11),GetRefreshTokenAsync()(line 14),SetTokensAsync(accessToken, refreshToken)called after a successful login or refresh (line 17), andClearTokensAsync()for logout (line 20). - Why it's built this way: four methods is the smallest surface that covers the whole client auth lifecycle, and keeping it free of any freshness parameter means the policy (skew, single-flight) belongs to the implementation, where it can differ per host.
- Where it's used: injected into
AuthDelegatingHandler,JwtAuthenticationStateProvider,AuthUIService,AuthenticatedServiceBase(which uses it for the direct-token path that bypasses the delegating handler,MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:73) andNotificationHubServicefor the SignalR access-token provider. Test hosts substituteStubTokenStorageServiceandNullTokenStorageService(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Gallery/Stubs/NullTokenStorageService.cs:8).
JwtTokenInfo
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Tokens·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/JwtTokenInfo.cs:17· Level 0 · class (static)
- What it is: one static predicate,
IsFresh, that answers whether a cached access token is still worth using or whether the caller should go and re-acquire one, plusDefaultExpirySkew, the single margin every caller passes to it. - Depends on: nothing first-party. Externals:
System.Buffers(ArrayPool<byte>),System.Buffers.Text(Base64Url),System.Text.Json(Utf8JsonReader),System.GlobalizationandDateTime.UtcNow; there is no JWT library in it. - Concept introduced, unvalidated client-side token inspection. Reading a JWT without checking its
signature looks alarming until you see what the answer is used for: it decides whether to call the
refresher, nothing else. The class doc states the boundary plainly, no signature validation because
the API validates every request (
JwtTokenInfo.cs:8-11).[Rubric §11, Security]assesses where trust decisions are made. A forged token that passed this check would still be rejected by the API on the first call, so the client-side read is an optimization, not an authorization.[Rubric §12, Performance & Scalability]assesses avoidable round trips and per-request cost. Without this check every outgoing request would have to hydrate; with it, a live token short-circuits the whole refresh path. Because the check itself runs on every outgoing request (on Blazor Server, on the server's CPU), it reads only theexpclaim straight from the payload segment, allocates no token handler and decodes the token once (remarks, lines 12-16), a cost tracked byJwtTokenInfoBenchmarks(MMCA.Common/Tests/Performance/MMCA.Common.Benchmarks/JwtTokenInfoBenchmarks.cs:9,43).
- Walkthrough:
DefaultExpirySkew, 30 seconds (JwtTokenInfo.cs:24): the margin every token storage and every direct bearer reader applies, held in one place so they can never disagree (lines 19-23). Three private constants bound the read:MaximumTokenLength, 250 KB, matching the token handler's default size limit (line 27);StackDecodeLimit, 1024 bytes (line 30);JwsSegmentCount, 3 (line 33).IsFresh(string? token, TimeSpan skew)(line 44) is expression-bodied: a non-blank token, an expiry thatTryReadExpirycould read, andexpiresAt > DateTime.UtcNow + skew(lines 45-47). The skew is a proactive margin, so the token is called stale slightly before it truly expires, and every uncertain case returnsfalse, biasing toward refreshing.TryReadExpiry(line 55,internalso the tests can read the parsed instant) rejects a token longer thanMaximumTokenLengthor with no payload segment (lines 58-61). A payload whose maximum decoded length fits in 1024 bytes is decoded into astackallocbuffer (lines 63-68); a larger one rents fromArrayPool<byte>.Sharedand returns the buffer in afinally(lines 70-78).TryGetPayloadSegment(line 91) trims the token, requires exactly two dots (line 95), and returns the middle segment only when the header and the payload are both non-empty (line 103).TryDecodeExpiry(line 82) uses theOperationStatusoverload ofBase64Url.DecodeFromChars, so a malformed segment is reported instead of thrown (lines 85-87).TryReadExpClaim(line 107) requires the JSON to open with an object (lines 113-116), walks the top-level properties (line 118) andSkip()s every other value (line 127), so anexpnested inside another claim is never read; aJsonExceptionis caught and reported as not fresh (lines 132-135).TryReadSeconds(line 139) accepts a NumericDate as a JSON number or as a numeric string parsed with the invariant culture (lines 143-151), rejects NaN, a negative value or one pastDateTimeOffset.MaxValue(lines 153-156), and floors the seconds ontoDateTime.UnixEpoch(line 158). A payload with noexpat all returnsfalse.
- Why it's built this way: a static pure function of two arguments is trivially testable and has
no lifetime to manage, and the deliberate fail-to-false makes every failure mode converge on the one
safe action (refresh). The only exception swallowed is
JsonException; a bad Base64 segment never throws in the first place, so a genuinely unexpected failure still surfaces. Reading one claim from one decode, on the stack for any ordinary token, keeps a per-request check off the allocation profile, and the length cap mirrors the limit the token handler would have enforced. - Where it's used: every caller passes
DefaultExpirySkew:WasmTokenStorageService.GetAccessTokenAsync(WasmTokenStorageService.cs:61),SecureStoreTokenStorageService.GetAccessTokenAsync(SecureStoreTokenStorageService.cs:114),ServerTokenStorageService(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Services/ServerTokenStorageService.cs:96,333), and the two preference calls that read the bearer themselves,ApiUserPreferenceReader(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/ApiUserPreferenceReader.cs:36) andApiUserPreferenceWriter(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/ApiUserPreferenceWriter.cs:90). Covered byJwtTokenInfoTests, which pins the 30-second value and the nested-expcase (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/Tokens/JwtTokenInfoTests.cs:20,72).
TokenHydrationWarmup
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Tokens·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/TokenHydrationWarmup.cs:26· Level 1 · class (static, partial)
- What it is: a one-method boot-time warm-up that reads the access token once through
ITokenStorageService, so the first hydration overlaps the app's first render instead of delaying whichever API call happens to go out first. - Depends on:
ITokenStorageService(resolved, not injected, so the call is optional at the call site) andMicrosoft.Extensions.Logging.ILoggerFactory, both pulled from the host's rootIServiceProvider(TokenHydrationWarmup.cs:37,42,46). - Concept introduced, a fire-and-forget warm-up that cannot fault.
[Rubric §23, Front-End Performance]assesses avoidable delay on first render; this type exists because hydration used to run inline on whicheverAPIClientcall the user made first.[Rubric §29, Resilience & Business Continuity]applies to the swallow-and-log shape: because the call is discarded (_ = TokenHydrationWarmup.WarmAsync(...)) rather than awaited, an unhandled fault here would surface as an unobserved task exception rather than anywhere useful, so the method is written to never throw. On the anonymous path a failed warm-up is expected (there is no session to hydrate), so the failure logs atDebug, notWarning(TokenHydrationWarmup.cs:52). - Walkthrough
WarmAsync(IServiceProvider services)(TokenHydrationWarmup.cs:37) null-guardsservices(line 38).- It resolves the logger before the
try(line 41), with the comment noting that this keeps the handler resolution itself from being the thing that throws. - Inside the
try, it resolvesITokenStorageServiceand callsGetAccessTokenAsync(), discarding the result (line 45): the point is the side effect (populating the in-memory token or the single-flight hydration), not the value. - A
catch (Exception ex)(line 48,CA1031suppressed with a comment explaining the design) logs through the source-generatedLogWarmupFailed(lines 54, 59-60) and returns normally.
- Why it's built this way: a
static partial classwith a[LoggerMessage]-generated logging method keeps the warm-up allocation-light and dependency-free at the call site: it takes the root provider rather than a constructor-injected service, because it runs once at startup before any component tree exists to inject into. - Where it's used:
MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web.Client/Program.cs:78, called and discarded (_ = TokenHydrationWarmup.WarmAsync(host.Services)) right afterMmcaCultureBootstrap.SetBrowserCultureAsyncand beforehost.RunAsync(); the surrounding comment (Program.cs:73-77) records the cost it replaces, about 2.4s added to the first cold-startAPIClientcall under the old inline hydration. Covered byTokenHydrationWarmupTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/TokenHydrationWarmupTests.cs:13), which exercises the success path (line 21), a storage failure (line 33) and a provider with no registered storage service (line 45).
ISessionAwareTokenRefresher
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Tokens·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/ISessionAwareTokenRefresher.cs:12· Level 1 · interface
- What it is: an
ITokenRefresherthat can say why it returned no token. It adds one method that reports aTokenAcquisitioninstead of a bare nullable string. - Depends on:
ITokenRefresher(base interface) andTokenAcquisition(the return type). Implemented bySameOriginProxyTokenRefresherandDirectApiTokenRefresher; consumed byWasmTokenStorageServiceandServerTokenStorageService(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Services/ServerTokenStorageService.cs). - Concept introduced, a capability interface instead of a changed contract. The base
Task<string?>answer cannot separate a definitive "no session" from a transient failure, and a caller that caches the absence of a session needs exactly that difference. Rather than break everyITokenRefresherimplementation, the richer method lives on a derived interface that callers probe for at runtime (WasmTokenStorageService.cs:198).[Rubric §1, SOLID](open for extension, closed for modification): the original contract is untouched and implementers opt in.[Rubric §12, Performance & Scalability]assesses redundant work: knowing "no session" is definitive is what lets storage skip repeat token POSTs for a short grace.
- Walkthrough: a single member,
Task<TokenAcquisition> TryAcquireAccessTokenAsync(CancellationToken cancellationToken = default)(ISessionAwareTokenRefresher.cs:17). Its documented result is "the acquired token, a definitive 'no session', or a transient failure" (line 16), and it does not throw for those cases. - Why it's built this way: see
ADR-051. A refresher
that does not implement it (for example the handoff one) keeps the previous reading, where
nullmeans "no session" (WasmTokenStorageService.cs:205-208). - Where it's used: the two refreshers above implement it, and
WasmTokenStorageService.HydrateAsynctype-tests for it (WasmTokenStorageService.cs:198). Covered byDirectApiTokenRefresherTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/DirectApiTokenRefresherTests.cs).
ISessionAwareTokenStorage
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Tokens·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/ISessionAwareTokenStorage.cs:12· Level 1 · interface
- What it is: an
ITokenStorageServicethat can report a session it held has ended on the server, and that can be told the API refused a token it handed out. It adds two members: theSessionEndedevent (ISessionAwareTokenStorage.cs:18) andRenewRejectedAccessTokenAsync, which carries a default implementation (line 37). - Depends on:
ITokenStorageService(base interface); the "ended" signal is the definitiveTokenAcquisition.NoSessionoutcome. Implemented byWasmTokenStorageService(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/WasmTokenStorageService.cs:30),ServerTokenStorageService(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Services/ServerTokenStorageService.cs:53) and the MAUISecureStoreTokenStorageService(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/SecureStoreTokenStorageService.cs:59); consumed byJwtAuthenticationStateProvider(the event) andAuthDelegatingHandler(the renewal). - Concept introduced, a session can end without this client signing out. Revoking from another
device ("Sign out everywhere") or deleting the account ends the server session while this shell
still believes it is signed in. The next refresh answers a DEFINITIVE "no session", and the interface
doc records the symptom it fixes: without the signal the shell stayed signed in behind 401s
(
ISessionAwareTokenStorage.cs:3-11).[Rubric §19, State Management & Data Flow]assesses whether auth state follows its source of truth. The storage is the first component to learn the session is gone, so it pushes that fact to the auth-state owner rather than waiting for a render to poll it.[Rubric §1, SOLID]: the same capability-interface move asISessionAwareTokenRefresher. The base contract is unchanged, and a storage that does not implement this behaves as before (line 10). The second member goes one step further: it is a default interface method returningnull(line 37), so a storage written before it keeps compiling and behaves as before (lines 34-35).
- Concept extended, an API 401 can end the session too. A refresh is the only place the first member
learns a session is gone, and a still-fresh token never triggers one. The remarks record the gap:
a locked user's fresh token kept the shell signed in behind "you are not signed in" errors until it
expired (
ISessionAwareTokenStorage.cs:32-34).RenewRejectedAccessTokenAsynccloses it by letting the HTTP pipeline report the refused token back to the storage that issued it. - Walkthrough:
event EventHandler? SessionEnded(ISessionAwareTokenStorage.cs:18). Its contract (lines 14-17): raised once, only when a refresh answered a definitive "no session" for a session this storage held, and the stored access token is already cleared when it fires. A transient refresh failure never raises it (line 9).Task<string?> RenewRejectedAccessTokenAsync(string rejectedAccessToken)(line 37). Its contract (lines 20-28): when the storage still holds the rejected token it discards it and attempts ONE refresh through the same single-flight a stale token takes; a definitive "no session" then clears the stored tokens and raisesSessionEnded, and an acquired token replaces the rejected one. A token the storage no longer holds (already replaced, or never held by this instance) changes nothing. It returns the token the storage holds afterwards, ornull(line 30).
- Why it's built this way: an event, not a polled flag, because the consumer must react the moment the hydrate lands; and the renewal goes through the storage's own single-flight rather than a separate refresh, so a burst of 401s for one token costs one refresh. See ADR-051 for the client token lifecycle this extends.
- Where it's used:
JwtAuthenticationStateProvidertype-tests its injected storage for it in the constructor and subscribes (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/JwtAuthenticationStateProvider.cs:50-53, same DI scope and lifetime as the storage, per the comment at line 49); itsOnSessionEndedhandler forgets the list-page state and callsNotifyUserLogout(lines 145-151).AuthDelegatingHandlerreports a 401 to the storage that owns the bearer:ReportRejectedAsyncfalls back to a type test of the handler's own storage (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthDelegatingHandler.cs:381-383) and callsRenewRejectedAccessTokenAsync(line 328), skipping a token that is itself the product of a renewal (lines 312-316).AuthenticatedServiceBasereads the same capability asStorageRenewsRejectedTokens, so a replaying caller does not refresh a second time (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:106).SessionEndedis raised byWasmTokenStorageService.HydrateAsync(WasmTokenStorageService.cs:231), byServerTokenStorageService(ServerTokenStorageService.cs:295) and bySecureStoreTokenStorageService.RaiseSessionEnded(SecureStoreTokenStorageService.cs:236). Pinned byWhenTheStorageReportsTheSessionEnded_NotifiesAnonymousandWhenTheStorageReportsTheSessionEnded_ForgetsTheListPageStateAndNotifiesAnonymous(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/JwtAuthenticationStateProviderTests.cs:137,152); the renewal contract by the sharedApiUnauthorized_*cases (MMCA.Common/Tests/Shared/UI/TokenStorageServiceTestsBase.cs:327,347,378) and end to end bySessionBearerRenewalTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Api/SessionBearerRenewalTests.cs:53).
SameOriginProxyTokenRefresher
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Tokens·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/SameOriginProxyTokenRefresher.cs:17· Level 2 · class (sealed)
- What it is: the browser
ISessionAwareTokenRefresher, used by both Blazor Server and WebAssembly. It asks a JS helper to POST the same-origin/auth/session/tokenendpoint and reports what comes back as aTokenAcquisition. - Depends on:
ISessionAwareTokenRefresher(the contract),TokenAcquisition,IJSRuntimeandJsInteropFailurefor the catch filter, plus themmcaAuthSessionhelper inMMCA.Common/Source/Presentation/MMCA.Common.UI/wwwroot/mmca-auth-cookie.js:32, whosegetTokenissues thefetch(line 35). - Concept introduced, the BFF hop. The refresh token never enters this process. The browser sends
its HttpOnly cookies with
credentials:'same-origin', the UI host validates or refreshes server-side, and only the access token comes back over the wire (SameOriginProxyTokenRefresher.cs:6-10). The server half isSessionCookieEndpoints, which mapsPOST /auth/session/token(MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:78).[Rubric §26, Front-End Security]assesses whether a long-lived credential is reachable from scripts. It is not: an XSS on this page can steal an access token that expires in minutes, not the refresh token behind it.[Rubric §7, Microservices Readiness]shows in the origin choice. The call goes to the UI host, not the API, so it stays same-origin and needs no CORS or cross-site cookie policy.
- Walkthrough: two methods.
AcquireAccessTokenAsync(cancellationToken)(SameOriginProxyTokenRefresher.cs:20) is a shim returning(await TryAcquireAccessTokenAsync(...)).AccessToken.TryAcquireAccessTokenAsync(line 24) invokesmmcaAuthSession.getTokenthrough interop (line 28) and maps a blank result toTokenAcquisition.NoSession, anything else toAcquired(line 29). The remarks (lines 12-16) record the script contract: it answersnullonly for the endpoint's 401 and throws for any other failure (a 429, a 5xx, a network error), which is what lets this method tell the two apart. The catch filters onJsInteropFailure.IsUnavailable(line 31), the framework's one shared definition of "interop could not do its job":InvalidOperationException,JSDisconnectedException,JSExceptionorOperationCanceledException(MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/JsInteropFailure.cs:27-31). Any of those is reported asUnavailable, with the comment saying none of these says anything about the session and that the server-side cookie path covers the interop-less phases (lines 32-34). - Why it's built this way: a proxy hop instead of a direct API call is the decision recorded in
ADR-022, including the
SameSite=LaxplusSec-Fetch-Sitecheck that hardens the refresh endpoint. The three-way outcome (see ADR-051) lets token storage tell "no session" from "interop not ready or endpoint failing", so a transient failure is not remembered as anonymous; the plainstring?shim still satisfies theITokenRefreshercontract. - Where it's used: registered for the Blazor Server head by
BlazorWebHostExtensions(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:141) and on each WASM client (MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web.Client/Program.cs:49,MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web.Client/Program.cs:46); consumed indirectly byWasmTokenStorageServiceandServerTokenStorageService. Covered bySameOriginProxyTokenRefresherTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/SameOriginProxyTokenRefresherTests.cs:14).
SecureStoreTokenStorageService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Tokens·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/SecureStoreTokenStorageService.cs:55· Level 2 · class (sealed)
- What it is: the MAUI head's
ITokenStorageService, declared as theISessionAwareTokenStoragecapability (SecureStoreTokenStorageService.cs:59). It is the freshness-checking layer over a persistentISecureTokenStore, the device counterpart ofWasmTokenStorageService(class doc, lines 7-12). - Depends on:
ISecureTokenStoreandITokenRefresher(required constructor parameters, lines 56-57); optionallyIDeviceMetadataReporterandILogger<SecureStoreTokenStorageService>(lines 58-59);JwtTokenInfofor the freshness check,ISessionAwareTokenRefresherthrough a runtime type test (line 249),DeviceMetadataReportingfor the backfill report; externalsSystem.Threading.Lock,InterlockedandVolatile. - Concept introduced, process-wide single-flight for a scoped service. The single-flight
hydration itself is taught at
WasmTokenStorageService; what is new here is its scope. The refresh slot, the token version and the session-ended handler list arestatic(lines 61-74), and the class doc gives the reason (lines 30-38): the service is scoped, and theAuthDelegatingHandlerbuilt byIHttpClientFactoryresolves its own instance in its handler scope. Per-instance state let the handler scope and the component scope each rotate the same refresh token, and the second rotation reads as reuse and revokes the session (BR-206); a per-instance event fired on the handler's instance while the auth state listened on the component's. A device runs one user session per process, so one slot is the right scope.- A definitive "no session" clears the stored pair. A token on a device can be hours or days old, and a dead pair left in the store made every read re-post a refresh the server could only refuse: the class doc records the 2026-10-17 conference-day loop of 6 to 31 refresh 401s a minute per device (lines 14-22). Clearing the pair ends that, because the next read finds no pair and the refresher answers without a request (line 22).
[Rubric §19, State Management & Data Flow]assesses where shared state lives and who may share it. The three statics are deliberate, and that is enforced:StateManagementConventionTestslists them as the only allowed mutable statics of the class, with the rationale that onlyAddCommonMauiTokenStorage()registers it, so no Blazor Server circuit can share them (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Ui/StateManagementConventionTests.cs:21-34).[Rubric §29, Resilience & Business Continuity]assesses how failures are told apart. Only a definitive "no session" for a held pair clears it; a transient failure (TokenAcquisition.Unavailable, a 409 superseded included) keeps the pair for the next attempt (lines 20-22, enforced at lines 260-263).
- Walkthrough:
- The proactive margin is not a field of this class: the freshness check passes
JwtTokenInfo.DefaultExpirySkew, 30 seconds (SecureStoreTokenStorageService.cs:114), the one value every storage shares. Statics:HydrateSyncandSessionEndedSync(lines 61, 63), the twoLocks;_hydrateInFlight(line 65), the shared hydrate task;_tokenVersion(line 72), bumped by every set and clear so a sign-in that lands mid-refresh wins over the "no session" answer read before it (M234, lines 67-71);_processSessionEnded(line 74), the process-wide handler list. Per instance:_subscriptions(line 76), the handlers this instance added. SessionEnded(line 79) is a custom event accessor:addandremove(lines 81-107) write the static list underSessionEndedSyncand record the handler in_subscriptions, so an event raised by the handler scope's instance reaches the listener subscribed on the component scope's.GetAccessTokenAsync()(line 111) returns the stored token when it is fresh (lines 113-117); otherwise it joins or starts the process-wide hydrate (line 125), awaits it (line 130) and clears the slot only if it still holds that task (line 134). After the slot is cleared, never inside the hydrate, a refreshed token triggers the once-per-process device report (lines 137-142): the report authenticates through the sameAPIClientpipeline, whose bearer read must find the fresh token instead of joining the refresh it follows.RenewRejectedAccessTokenAsync(rejectedAccessToken)(line 154) throws on a blank token (line 156), returns the stored token unchanged when it is not the rejected one (lines 158-162), and otherwise runs the same single-flight hydrate (lines 164-172). Concurrent 401s for one token therefore share one refresh, since a second rotation would read as reuse (remarks, lines 148-153).GetRefreshTokenAsync()(line 176) passes through to the store;SetTokensAsync(line 179) andClearTokensAsync(line 186) bump_tokenVersion(lines 181, 188) and delegate.Dispose()(line 193) removes from the static list every handler this instance added (lines 197-200), so a disposed scope's subscriber is not kept alive by the static event.JoinOrStartHydrate(line 213) publishes or reads the slot underHydrateSyncwith??=(line 217);ClearHydrateIfCurrent(line 225) clears it only onReferenceEquals(line 229), the same guard against dropping a newer hydrate (lines 221-224).RaiseSessionEnded(line 236) snapshots the handler list under the lock and invokes it outside it (lines 241-244).HydrateAsync()(line 247): a refresher that is not session-aware keeps the previous behavior, itsnullpassed through and the stored pair left alone (lines 249-254). Otherwise it captures the version and whether a refresh token is held (lines 256-257), callsTryAcquireAccessTokenAsync(line 259), and returns early on an acquired token, an unavailable answer or no held pair (lines 260-263). If the version moved meanwhile, a sign-in or sign-out owns the store and it returnsnullwithout touching it (lines 265-270). Only then does it clear the store, bump the version and raiseSessionEnded(lines 272-274).
- The proactive margin is not a field of this class: the freshness check passes
- Why it's built this way: the store underneath (
ISecureTokenStore) is deliberately policy-free, so the freshness check, the single-flight and the session-end decision live once, here. The refresh must never read this storage again: the class doc records thatDirectApiTokenRefresherposts through theAPIClientpipeline and opts out withAuthDelegatingHandler.SkipBearer, because the handler would otherwise await the very hydrate that is waiting for the refresh (lines 24-28). The token lifecycle is ADR-051. - Where it's used: registered on the MAUI head,
services.AddScoped<ITokenStorageService, SecureStoreTokenStorageService>()(MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/DependencyInjection.cs:140, documented at lines 117-119), on top ofMauiSecureTokenStore. Covered bySecureStoreTokenStorageServiceTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/SecureStoreTokenStorageServiceTests.cs:18), including the cleared pair with oneSessionEnded(line 37), the kept pair on an unavailable refresh (line 56), a sign-in mid-refresh (line 86),Dispose(line 108), the cross-instance signal (line 124) and an API 401 ending the session (line 155); the device backfill bySecureStoreDeviceBackfillTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/Devices/SecureStoreDeviceBackfillTests.cs:17). - Caveats / not-in-source: unlike the browser storage there is no anonymous grace window; after a
clear the next read relies on the refresher answering without a request (class doc, line 22). The
RenewRejectedAccessTokenAsyncpath never runs the device report, which onlyGetAccessTokenAsynctriggers (lines 139-142). Because the statics are process-wide, every test class that drives it joins theSecureStoreTokenStorageCollection(SecureStoreTokenStorageServiceTests.cs:17,233), which serializes them: two such classes in parallel would join each other's in-flight refresh (lines 228-230).
WasmTokenStorageService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Tokens·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/WasmTokenStorageService.cs:27· Level 2 · class (sealed)
- What it is: the WebAssembly
ITokenStorageService, declared as theISessionAwareTokenStoragecapability (WasmTokenStorageService.cs:30). The access token lives in memory only and is hydrated on demand from the HttpOnly cookies; there is nolocalStorageanywhere in it. - Depends on:
ISessionCookieSyncandITokenRefresher(constructor parameters,WasmTokenStorageService.cs:27-30), plusJwtTokenInfofor the freshness check; optionallyISessionAwareTokenRefresher(a runtime type test inHydrateAsync, line 198); externalsSystem.Threading.LockandTimeProvider. - Concept introduced, single-flight hydration. Several callers can ask for a token in the same
instant: the
AuthDelegatingHandleron an outgoing request, theJwtAuthenticationStateProviderduring a render, andNotificationHubService's access-token provider. Without coordination each would start its own refresh, and the last one to finish would overwrite the others' token. The fix is to share one in-flightTask, and the source is explicit that the lock, not a??=, is what makes it single (lines 71-74).- Remembering "no session" for a short grace. A visitor with no session would otherwise cost one
same-origin token POST per API call. After a hydrate returns a DEFINITIVE "no session", the service
answers
nullfrom memory forAnonymousGrace, 15 seconds (line 33), checked inGetAccessTokenAsync(lines 66-69). A transient failure is never remembered, andSetTokensAsyncresets the window so a login right after anonymous browsing does not wait it out (lines 133-134). - A login or logout wins over a hydrate already in flight (M234).
_tokenVersion(line 47) is bumped bySetTokensAsyncand twice byClearTokensAsync.HydrateAsynccaptures it before the acquisition and, if it moved by the time the answer arrives, discards that stale answer together with its grace (lines 194, 210-213). - A held session that ends on the server signs the shell out (A-34).
_sessionHeld(line 54) records whether this client holds a session. When a session-aware refresher answers a definitive "no session" while it is set, the service raisesSessionEnded(line 57) so the auth state goes anonymous (class doc, lines 20-21). A plain refresher'snullstill starts the grace but is not proof enough to sign a held session out (lines 192-193). [Rubric §19, State Management & Data Flow]assesses ownership of shared per-circuit state; the in-memory token and its in-flight hydration are exactly that.[Rubric §12, Performance & Scalability]assesses redundant work: a burst of concurrent callers costs one network round trip, not one each.[Rubric §11, Security]assesses at-rest exposure. The refresh token is never held client-side, the comment at line 127 saying it lives only in the HttpOnly cookie.
- Remembering "no session" for a short grace. A visitor with no session would otherwise cost one
same-origin token POST per API call. After a hydrate returns a DEFINITIVE "no session", the service
answers
- Walkthrough:
AnonymousGrace, 15 seconds (WasmTokenStorageService.cs:33). The class holds no skew of its own: the freshness check passesJwtTokenInfo.DefaultExpirySkew, 30 seconds, toJwtTokenInfo.IsFresh(line 61)._hydrateSync(line 35), theLock;_timeProvider(line 36), the injected clock (system clock when null);_accessToken(line 38), the in-memory token;_hydrateInFlight(line 39), the shared hydration task;_anonymousUntil(line 40), the end of the current grace;_tokenVersion(line 47), the counter that lets a login or logout invalidate an in-flight hydrate; and thevolatile_sessionHeld(line 54), set by a login and by every hydrate that acquired a token, cleared by a logout and when the session is found ended, and left alone by a transient failure (lines 49-53).SessionEnded(line 57) is theISessionAwareTokenStorageevent.- The primary constructor is the only one: the clock is its third parameter, a nullable
TimeProvider?with no default value (lines 27-30), so every caller supplies it (ornull) and there is no two-argument overload. GetAccessTokenAsync()(line 59) returns the cached token immediately when it is fresh (lines 61-64). If there is no token and the grace has not elapsed it returnsnullwithout any network call (lines 66-69). Otherwise it takes the lock only long enough to publish or read the in-flight task (lines 76-80), which is safe becauseHydrateAsyncreaches its firstawaitimmediately so nothing slow runs under the lock (lines 71-74). It then awaits the shared task (line 84) and, in afinally, clears_hydrateInFlightonly if it is still the same task (ReferenceEquals, line 92). That guard is the subtle half: an unguarded clear can drop a newer hydrate started after this one completed, splitting the next set of callers all over again (lines 88-89).RenewRejectedAccessTokenAsync(rejectedAccessToken)(line 106), theISessionAwareTokenStoragerenewal: it throws on a blank token (line 108), then under_hydrateSyncreturns the current token when it is not the rejected one (lines 113-116); otherwise it drops the token from memory, ends any grace and joins or starts the same in-flight hydrate (lines 118-121).AwaitHydrateAsync(line 164) awaits that task and clears the slot with the sameReferenceEqualsguard (line 176), so concurrent 401s for one token share one refresh, and a definitive "no session" raisesSessionEndedthroughHydrateAsync(remarks, lines 101-105).GetRefreshTokenAsync()(line 128) returnsnullunconditionally, an honest answer rather than a stub: in the browser there is nothing to return.SetTokensAsync(accessToken, refreshToken)(line 130) bumps_tokenVersion(line 133), resets_anonymousUntil(line 134), stores the access token in memory (line 135), sets_sessionHeld(line 136) and seeds the HttpOnly cookies throughISessionCookieSync.SyncAsync(line 141); the comment records that the refresh token transits JS only for that same-origin POST (lines 137-140). Afalsefrom the cookie write throwsInvalidOperationException(lines 141-144), after the in-memory token is set, soAuthUIServicereportsAuth.TokenStorageUnavailableinstead of a login that silently signs out at the first access-token expiry, when no cookie exists to refresh from.ClearTokensAsync()(line 147) bumps_tokenVersion, nulls the field and clears_sessionHeld(lines 149-151), clears the cookies (line 155), then bumps the version a second time and nulls the field again (lines 160-161). The second bump covers a hydrate that started during the clear, captured the first version and read the session the clear was still removing: its answer is discarded if in flight, and dropped if it already landed (lines 157-159). Clearing is best-effort by contract, so afalsefromClearAsyncis discarded; the comment points a caller that needs proof the session ended atIAuthUIService.RevokeAllSessionsAsync(lines 152-154). A logout therefore never raisesSessionEnded.HydrateAsync()(line 184) captures_tokenVersionfirst (line 194), then branches on the refresher's capability. When it is anISessionAwareTokenRefresher(line 198) it callsTryAcquireAccessTokenAsync, keepsAccessTokenin a local, readsIsUnavailableand computesdefinitiveNoSessionas a null token that is not unavailable (lines 200-203); otherwise it falls back toITokenRefresher.AcquireAccessTokenAsync, where anullmeans "no session" for the grace but never counts as definitive (line 207). If the version moved meanwhile it returns the current_accessTokenand publishes nothing (lines 210-213); otherwise it stores the answer (line 215). Only a null token that is not unavailable starts the grace (lines 217-220), so a 429, a 5xx or unavailable interop never makes a signed-in user look anonymous. Finally, an acquired token sets_sessionHeld(lines 222-225); a definitive "no session" while_sessionHeldis set clears it and raisesSessionEnded, the token already gone from memory (lines 226-232). SeeTokenAcquisition.
- Why it's built this way: the class doc records that it was hoisted out of the app WASM clients
because it carries no app-specific state, and names its Blazor Server sibling
ServerTokenStorageServicein MMCA.Common.UI.Web. The two share the skew (both passJwtTokenInfo.DefaultExpirySkew), theLock, and the same single-flight shape; the server one adds anHttpContextbranch for the prerender pass, and both implementISessionAwareTokenStorage. The cookie-only storage model is ADR-022; the token lifecycle is ADR-051. The MAUI head's counterpart isSecureStoreTokenStorageService, which keeps the same single-flight but process-wide, over a persistent store. - Where it's used: registered on the WASM clients,
AddScoped<ITokenStorageService, WasmTokenStorageService>()(MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web.Client/Program.cs:48,MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web.Client/Program.cs:45). Covered byWasmTokenStorageServiceTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/WasmTokenStorageServiceTests.cs:16), which inherits the sharedTokenStorageServiceTestsBasecases: the concurrency path (MMCA.Common/Tests/Shared/UI/TokenStorageServiceTestsBase.cs:73), the failed cookie write as a throw (line 181) and the API-401 renewal (lines 327, 347, 378).SessionBearerRenewalTestsdrives the renewal end to end through the real pipeline (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Api/SessionBearerRenewalTests.cs:53).
DirectApiTokenRefresher
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.Tokens·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/DirectApiTokenRefresher.cs:41· Level 6 · class (sealed)
- What it is: the MAUI
ISessionAwareTokenRefresher(and so anITokenRefresher). It reads the token pair out of OS SecureStorage, exchanges it against the API's cross-originauth/refreshendpoint, and writes the rotated pair back, reporting the outcome as aTokenAcquisition. - Depends on:
ISecureTokenStore(deliberately, notITokenStorageService),AuthDelegatingHandler(for itsSkipBearerrequest option),RefreshTokenRequestandAuthenticationResponsefromMMCA.Common.Shared.Auth; externalsIHttpClientFactory,System.Net.Http.JsonandSystem.Text.Json(forJsonException). - Concept introduced, direct token handling where there is no DOM. The class doc justifies the
choice: MAUI has no browser and thus no XSS surface, so holding a refresh token client-side and
posting it is acceptable there in a way it is not in a browser
(
DirectApiTokenRefresher.cs:9-11). This is the counterpart toSameOriginProxyTokenRefresher, and reading the two together is the clearest statement of the framework's per-platform threat model.[Rubric §11, Security]assesses per-platform credential handling, exactly as above.[Rubric §1, SOLID], dependency direction: the second doc paragraph is unusually explicit (lines 12-18). Every operation it performs is a raw read or write, so it takes the raw store; takingITokenStorageServiceinstead would close the loop and let a refresh re-enter the acquisition that started it.- The same cycle through the HTTP pipeline. The third doc paragraph (lines 19-24) names the
indirect route back into that loop: the
APIClientcarriesAuthDelegatingHandler, which reads the storage service for a bearer. The refresh POST therefore setsAuthDelegatingHandler.SkipBearer(line 67), so the anonymous refresh call never reaches the storage instance that is awaiting it. The handler honors the option by passing the request through untouched (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthDelegatingHandler.cs:45,226). - A 409 is transient, never "no session". The fourth doc paragraph (lines 26-33) explains
Auth.RefreshSuperseded: the presented token was rotated by another request inside the server's reuse grace. Clearing the pair on that answer would let a stolen-and-rotated token live for the full refresh lifetime, so the stored pair is left untouched and the next attempt presents it again. - Only a refusal is "no session". The fifth doc paragraph (lines 34-39) narrows
NoSessionto a refusal of the presented token (400, 401, 403). Every other failure (a 408, a 429, a 5xx during a revision swap, a dropped connection, an unrequested timeout) isUnavailable, asSameOriginProxyTokenRefresherreports it, because the caller treats "no session" as a sign-out and clears the stored pair.
- Walkthrough:
AcquireAccessTokenAsync(cancellationToken)(DirectApiTokenRefresher.cs:48) is an expression-bodied shim overTryAcquireAccessTokenAsync(line 52) that returns only.AccessToken, which keeps the plainITokenRefreshercontract intact. TheTrymethod is a straight line of early returns, each producing aTokenAcquisitionrather than an exception:- read both tokens from the store (lines 54-55), and return
NoSessionwhen either is blank (lines 57-60), so a never-logged-in device costs one storage read and no network call; - create the named
"APIClient"(ApiClientName, line 45), build anHttpRequestMessagePOSTing aRefreshTokenRequestcarrying both tokens asJsonContentto the relativeauth/refresh(lines 62-66), mark itSkipBearer(line 67), and send it inside atry(lines 69-82); - return
Unavailablewhen the send throwsHttpRequestException(line 74) or anOperationCanceledExceptionthe caller did not request, meaning anHttpClient.Timeout(lines 78-82), then hold the response in ausing var(line 84); - on
HttpStatusCode.Conflict(lines 86-89) delegate toReadSupersededOutcomeAsync(line 123), which re-reads the store: if another refresh in this process already stored a different non-blank pair it returnsAcquiredwith that access token, otherwiseUnavailablewith the pair left as it was (lines 125-132); - on any other non-success status (lines 91-96) return
NoSessiononly for 400, 401 or 403, which is how a revoked or reused refresh token arrives, andUnavailablefor the rest; - deserialize an
AuthenticationResponseinside atry(lines 98-108): a 2xx whose body is not the token document (a proxy or portal page, a truncated or version-skewed body) throwsJsonExceptionorNotSupportedException, which is caught and answeredUnavailable, because such a body says nothing about the session and the pair is kept for a later retry (lines 103-107); - return
NoSessionwhen the access token came back blank (lines 110-113); - persist the rotated pair through
ISecureTokenStore.SetTokensAsyncand returnTokenAcquisition.Acquiredwith the new access token (lines 115-116).
- read both tokens from the store (lines 54-55), and return
- Why it's built this way: the rotation-on-refresh shape it participates in is
ADR-097, which made
refresh sessions hashed, rotating and per device: writing the returned pair back is not an
optimization, it is required, because the old refresh token is dead after the exchange. An explicit
HttpRequestMessagerather thanPostAsJsonAsyncis what gives the call anOptionsbag to carrySkipBearer. Theusing var httpClient(line 62) and the relativeUriboth lean on the named client configured once inAddUIShared, which also attaches the delegating handler (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:158,180). - Where it's used: registered on the MAUI heads,
AddScoped<ITokenRefresher, DirectApiTokenRefresher>()(MMCA.Store/Source/Hosts/UI/MMCA.Store.UI/MauiProgram.cs:98,MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/MauiProgram.cs:173). Covered byDirectApiTokenRefresherTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/DirectApiTokenRefresherTests.cs:17), which stubs the store and the HTTP handler (lines 25-36) and asserts theSkipBearermark on the refresh POST (line 62).
CultureDelegatingHandler
MMCA.Common.UI ·
MMCA.Common.UI.Services.Culture·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Culture/CultureDelegatingHandler.cs:13· Level 0 · class (sealed)
- What it is: a one-method
DelegatingHandlerthat stamps the active UI culture onto every outgoing API call as anAccept-Languageheader, so validation and error text come back from the backend in the language the user selected. - Depends on: no first-party types. Externals:
System.Net.Http.DelegatingHandler,System.Globalization.CultureInfo, andSystem.Net.Http.Headers.StringWithQualityHeaderValue. It rides the same named"APIClient"pipeline as AuthDelegatingHandler. - Concept introduced, culture as a transport header rather than only a cookie.
[Rubric §27, Internationalization]assesses whether locale is carried end to end instead of being applied only at the rendering edge; this handler is the piece that closes that loop for server-produced strings. The class comment (CultureDelegatingHandler.cs:7-11) states the reason plainly: the cross-origin Gateway does not carry the ASP.NET culture cookie through to the services, so a cookie-only design would render the page in Spanish while the API answered in English.[Rubric §6, CQRS & Event-Driven Design]also applies, because this is a concern every service call needs and no service call implements: it is attached once in the HttpClient pipeline instead of at each call site. - Walkthrough
- The only member is the
SendAsyncoverride (CultureDelegatingHandler.cs:16). - It reads
CultureInfo.CurrentUICulture.Name(CultureDelegatingHandler.cs:20) and does nothing when that is blank (CultureDelegatingHandler.cs:21), so an unresolved culture sends no header rather than an empty one. - When there is a value it calls
AcceptLanguage.Clear()beforeAdd(...)(CultureDelegatingHandler.cs:23-24); the clear matters because a retried request object would otherwise accumulate a second language entry. - It returns
base.SendAsync(request, cancellationToken)directly (CultureDelegatingHandler.cs:27) rather than awaiting it, so the handler adds no async state machine to the hot path.
- The only member is the
- Why it's built this way: ADR-027
makes multi-locale a whole-stack concern. Registering the behavior as a message handler means the
culture travels on calls made by code that has never heard of localization. It is registered
transient in DependencyInjection
(
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:149) and appended to the"APIClient"pipeline after the auth handler (DependencyInjection.cs:180-181). - Where it's used: every request through the
"APIClient"named client, which is every call made by EntityServiceBase<TEntityDTO, TIdentifierType>, ChildEntityServiceBase, ApiUserPreferenceReader and ApiUserPreferenceWriter. - Caveats / not-in-source: it reads whatever ambient UI culture the head has already established. On a Blazor WebAssembly head that is set by MmcaCultureBootstrap before the host runs; the handler itself makes no attempt to resolve or validate a culture.
ICultureApplier
MMCA.Common.UI ·
MMCA.Common.UI.Services.Culture·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Culture/ICultureApplier.cs:14· Level 0 · interface
- What it is: the one-method contract for "switch the language and put the user back where they were", written as an abstraction because the mechanism differs per head.
- Depends on: nothing. Implemented by EndpointCultureApplier (the Blazor Web default) and by MauiCultureApplier in the device-capability layer.
- Concept introduced, a terminal call.
[Rubric §18, UI Architecture]assesses whether host-specific mechanics are hidden behind contracts the components can share; this interface is the clearest example in the UI package. The doc comment (ICultureApplier.cs:3-13) spells out both halves of the contract: a Blazor Web head round-trips the server/culture/setendpoint so the cookie, the SSR prerender and the WASM runtime all agree, while a MAUI Blazor Hybrid head has no ASP.NET pipeline and switches the process culture in place. Because each implementation owns landing the user back on the return path (a redirect on the web, a WebView reload on a hybrid head), callers must treatApplyAsyncas terminal and do no navigation of their own.[Rubric §25, Navigation & Information Architecture]applies for the same reason: navigation ownership is part of the contract rather than an afterthought at each call site. - Walkthrough
ApplyAsync(string culture, string returnPath, CancellationToken cancellationToken = default)(ICultureApplier.cs:27) is the whole surface.- Two documented behaviors belong to the contract rather than to any one implementation: a culture
outside
SupportedCultures.Allis ignored by the underlying mechanism rather than throwing (ICultureApplier.cs:19-22), and an emptyreturnPathfalls back to"/"(ICultureApplier.cs:23-25).
- Why it's built this way:
ADR-027. Hard-coding the endpoint
navigation into the culture switcher component would have made that component unusable on MAUI,
where the URL matches no route and the Blazor
Routerrenders the not-found page. The interface lets one shared component serve both heads. - Where it's used: injected by the shared
CultureSwitchercomponent, which persists the choice first and then treats the applier call as the last thing it does (MMCA.Common/Source/Presentation/MMCA.Common.UI/Globalization/CultureSwitcher.razor:6andCultureSwitcher.razor:44-48), and by the login page when reconciling a returning user's stored culture (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor:15andLogin.razor:239-244).
LoginRefusal
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/TwoFactor/LoginRefusals.cs:9· Level 0 · enum (internal)
- What it is: the four next steps a refused password sign-in can ask of the sign-in page
(
LoginRefusals.cs:8):Other(show the message,LoginRefusals.cs:12),SecondFactorRequired(the password was proved and the account has a second factor, so ask for the code,LoginRefusals.cs:15),SecondFactorInvalid(the code did not verify, so keep the code step and ask again,LoginRefusals.cs:18) andEmailNotConfirmed(offer to resend the confirmation link,LoginRefusals.cs:21). - Depends on: nothing. It is the return type of
LoginRefusals.Classify; the mapping from error codes lives in LoginRefusals, which introduces the concept. - Where it's used:
Login.HandleRefusalStep(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor.cs:123) switches on it: both second-factor values show the code step and clear the previous code (Login.razor.cs:126-131), onlySecondFactorRequiredcounts as fully handled with no message (Login.razor.cs:131), andEmailNotConfirmedrecords the trimmed address for the resend prompt (Login.razor.cs:134-137). See Login.
EndpointCultureApplier
MMCA.Common.UI ·
MMCA.Common.UI.Services.Culture·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Culture/EndpointCultureApplier.cs:18· Level 1 · class (sealed)
- What it is: the Blazor Web implementation of ICultureApplier. It
force-navigates to the server's
GET /culture/setendpoint, which writes the culture cookie and redirects the user back to where they were. - Depends on: ICultureApplier (implemented) and
Microsoft.AspNetCore.Components.NavigationManager. It pairs with the server endpoint mapped byMapCultureEndpoint()(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationExtensions.cs:83, theMapGet("/culture/set", ...)atWebApplicationExtensions.cs:101) and with MmcaCultureBootstrap on the WASM side. - Concept introduced, why the full page reload is deliberate.
[Rubric §27, Internationalization]assesses whether a locale switch is coherent across every rendering path; the class comment (EndpointCultureApplier.cs:8-10) says the force-load is load-bearing, because the server has to re-render SSR under the new cookie and the WASM runtime has to re-read it on startup, which keeps prerender and hydration on the same culture. A soft, client-only switch would leave the two disagreeing and show a locale flash on the next full load. - Walkthrough
ApplyAsync(EndpointCultureApplier.cs:21) rejects a null or whitespace culture up front withArgumentException.ThrowIfNullOrWhiteSpace(EndpointCultureApplier.cs:23).- It falls back to
"/"for an empty return path (EndpointCultureApplier.cs:25) and builds the URL withUri.EscapeDataStringon both values (EndpointCultureApplier.cs:26), so a return path containing a query string survives round-tripping. - It then calls
navigation.NavigateTo(url, forceLoad: true)(EndpointCultureApplier.cs:30) and returnsTask.CompletedTask(EndpointCultureApplier.cs:31): the method is synchronous in substance andTask-shaped only because the interface must also fit asynchronous heads. - The inline comment (
EndpointCultureApplier.cs:28-29) notes that validating the culture is the endpoint's job: an unsupported value lands the user back on the same page unchanged rather than failing.
- Why it's built this way:
ADR-027. The class comment
(
EndpointCultureApplier.cs:11-15) also records the boundary of its validity: a head with no ASP.NET pipeline would route/culture/setthrough the BlazorRouter, match no page and render the not-found page, which is exactly why MAUI heads register their own applier afterAddUIShared. - Where it's used: registered as the default with
TryAddScoped<ICultureApplier, EndpointCultureApplier>()(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:235), with the comment above it (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:231-234) recording that a hybrid head overrides it afterwards. The MAUI replacement is MauiCultureApplier.
MmcaCultureBootstrap
MMCA.Common.UI ·
MMCA.Common.UI.Services.Culture·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Culture/MmcaCultureBootstrap.cs:22· Level 1 · class (static)
- What it is: the Blazor WebAssembly culture bootstrap. It resolves the culture the way the server's request localization did during SSR prerender (the ASP.NET culture cookie, then the browser's preferred languages, then the default) and sets the WASM runtime's default thread cultures before the host starts running.
- Depends on: SupportedCultures from the
Shared layer and the
culture.jsmodule in the package'swwwroot. Externals:IJSRuntimeandCultureInfo. - Concept introduced, closing the prerender/hydration culture gap.
[Rubric §27, Internationalization]assesses whether every rendering path resolves the same locale; the class comment (MmcaCultureBootstrap.cs:7-21) states the outcome this buys: the interactive client renders in the same language the server prerendered, with no locale flash and no prerender/hydration mismatch.[Rubric §23, Front-End Performance]applies too, because the alternative (letting the client discover the culture after first render) costs a visible re-render of the whole page. - Walkthrough
- Two overloads of
SetBrowserCultureAsync. The one-argument form (SetBrowserCultureAsync(IJSRuntime jsRuntime),MmcaCultureBootstrap.cs:41) forwards withallowPseudoLocale: false, so the pseudo locale is never accepted through it. The real work is inSetBrowserCultureAsync(IJSRuntime jsRuntime, bool allowPseudoLocale)(MmcaCultureBootstrap.cs:57), null-guarded atMmcaCultureBootstrap.cs:59. A Development host passesbuilder.HostEnvironment.IsDevelopment()as the flag, because the server accepts the pseudo locale only in Development (MmcaCultureBootstrap.cs:44-53). - It imports
./_content/MMCA.Common.UI/culture.jsunder anawait using(MmcaCultureBootstrap.cs:62-63), so the module reference is released as soon as the calls are done: unlike the long-lived services, this runs once at startup and has no reason to hold it. - The import and both JS calls sit inside a
#pragma warning disable BL0016/restorepair (MmcaCultureBootstrap.cs:61andMmcaCultureBootstrap.cs:67). The suppression comment gives the reason: the code runs in the WASMProgram.csbefore the host starts, so there is no circuit, and an interop failure must reach that caller rather than silently boot in the default culture. Nothing here catches the exception. - The culture is a three-step
??chain (MmcaCultureBootstrap.cs:64-66). FirstgetCulture, whose JS side parses the.AspNetCore.Culturecookie'suic=segment and returns null when the cookie is absent or unparseable (MMCA.Common/Source/Presentation/MMCA.Common.UI/wwwroot/culture.js:4). The cookie always wins: the class comment notes it is written by the culture switch and, for a signed-in user, from the stored profile preference on sign-in, so a chosen language is never overridden by the browser's (MmcaCultureBootstrap.cs:16-17). Second, when the cookie yields nothing,getBrowserLanguagesreturnsnavigator.languages(or[navigator.language]), the list the browser turns into theAccept-Languageheader the server falls back to (culture.js:29). Third,SupportedCultures.Default. MatchFirst(MmcaCultureBootstrap.cs:79) tries at mostMaxBrowserLanguagesToTrybrowser languages, the constant3atMmcaCultureBootstrap.cs:30, chosen to equal the server'sAcceptLanguageHeaderRequestCultureProvider.MaximumAcceptLanguageHeaderValuesToTrydefault so the client never picks a culture the server would not have reached.Match(MmcaCultureBootstrap.cs:91) mirrors request localization's matching rule: it walks the candidate and then its parents viaParentOf(MmcaCultureBootstrap.cs:106, which strips the last-subtag), returning the first thatSupportedCultures.IsSupportedaccepts, or thatSupportedCultures.IsPseudoLocalematches whenallowPseudoLocaleis true (MmcaCultureBootstrap.cs:95-96). Soes-ESresolves toes, but only parents count, never siblings:en-GBdoes not resolve toen-US, exactly as on the server. The predicate is atMMCA.Common/Source/Core/MMCA.Common.Shared/Globalization/SupportedCultures.cs:35, the pseudo-locale check atSupportedCultures.cs:76, the"qps-Ploc"constant atSupportedCultures.cs:28, the allowlist atSupportedCultures.cs:18, and the"en-US"default atSupportedCultures.cs:12.- It then assigns only
CultureInfo.DefaultThreadCurrentCultureandCultureInfo.DefaultThreadCurrentUICulture(MmcaCultureBootstrap.cs:70-71), neverCurrentCulture/CurrentUICulturedirectly: setting the defaults makes every subsequently created thread inherit the culture, which is what a later switch needs in order to take effect.
- Two overloads of
- Why it's built this way:
ADR-027. The cookie is
non-HttpOnly by default for exactly this reader:
MapCultureEndpoint(bool httpOnly)(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationExtensions.cs:96) documents passingfalseon any host that serves a WebAssembly client (WebApplicationExtensions.cs:89-95), and the suppression comment above the cookie write (WebApplicationExtensions.cs:109) namesMmcaCultureBootstrap.SetBrowserCultureAsyncas the consumer. The browser-language step exists because, without it, a browser with no cookie got a server render in its own language and a WebAssembly render in the default one (MmcaCultureBootstrap.cs:18-19). The doc comment (MmcaCultureBootstrap.cs:13-14) also pins the call ordering: it must run afterbuilder.Build()and beforehost.RunAsync(). - Where it's used: both Blazor Web clients call the two-argument overload exactly as documented,
passing
builder.HostEnvironment.IsDevelopment()so hydration keeps the pseudo locale the server prerendered:MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web.Client/Program.cs:69andMMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web.Client/Program.cs:74. Its MAUI counterpart is MauiCultureInitializer.
Subscription
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/TwoFactor/MultiFactorRequiredSignal.cs:54· Level 1 · class (private sealed, nested)
- What it is: the handle MultiFactorRequiredSignal returns from
Subscribe: one subscriber, which on disposal removes itself only while it is still the current one for its storage (MultiFactorRequiredSignal.cs:53). - Depends on: ITokenStorageService (the key it belongs to) and the
enclosing class's
Subscriptionstable. ImplementsIDisposable. - Concept introduced: none of its own; the weak-keyed signal is taught at MultiFactorRequiredSignal.
- Walkthrough
- It holds the storage only through a
WeakReference<ITokenStorageService>(MultiFactorRequiredSignal.cs:56), so the handle a component keeps never pins an ended scope's storage, and the callback in a nullableAction?field (MultiFactorRequiredSignal.cs:57). Invoke(MultiFactorRequiredSignal.cs:59) calls the callback when one is still set.Dispose(MultiFactorRequiredSignal.cs:61) first nulls the callback (MultiFactorRequiredSignal.cs:63), so a raise that already fetched this handle becomes a no-op. It then removes the table entry only when the storage is still alive and the entry is this very instance (ReferenceEquals,MultiFactorRequiredSignal.cs:64-68): disposing a subscription a laterSubscribereplaced leaves the successor in place.
- It holds the storage only through a
- Where it's used: only through
MultiFactorRequiredSignal.Subscribe, whose caller is MultiFactorRequiredListener (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/MultiFactorRequiredListener.cs:41). - Caveats / not-in-source: the name is shared with unrelated webhook and broker-transport
Subscriptionidentifiers elsewhere in Common; this one is private to the signal class and has no other caller.
ViewerTimeZone
MMCA.Common.UI ·
MMCA.Common.UI.Services.Culture·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Culture/ViewerTimeZone.cs:22· Level 1 · class (sealed)
- What it is: a scoped service that learns the viewer's browser time zone once and converts the UTC
instants the API serializes onto the clock the person actually reads. Until the zone is known it
reports UTC (
ViewerTimeZone.cs:36). - Depends on: LazyJsModule (held as
_module, built over the host'sIJSRuntimein the constructor,ViewerTimeZone.cs:30) and thetime-zone.jsmodule named atViewerTimeZone.cs:24. ImplementsIAsyncDisposable. - Concept introduced, rendering instants on the viewer's clock.
[Rubric §27, Internationalization]assesses whether dates are shown the way the reader expects, not the way the server stores them. A server-sideToLocalTime()would use the server's zone; this service asks the browser instead. - Walkthrough
Zone(ViewerTimeZone.cs:36) defaults toTimeZoneInfo.Utc;IsResolved(ViewerTimeZone.cs:42) stays false while JS interop is unavailable, so a later call can retry.EnsureResolvedAsync(ViewerTimeZone.cs:54) returns early when already resolved, then imports the module and invokesgetTimeZone(ViewerTimeZone.cs:64-65). JS side:MMCA.Common/Source/Presentation/MMCA.Common.UI/wwwroot/time-zone.js:6returns theIntl.DateTimeFormatzone id, or null when the browser cannot say.- Failure handling is split by whether a retry could help.
InvalidOperationException(SSR prerender, no interop yet),JSDisconnectedExceptionandOperationCanceledExceptionreturn false without marking resolved (ViewerTimeZone.cs:67-80); aJSExceptionmeans the browser answered with an error, so the zone id becomes null and resolution is final (ViewerTimeZone.cs:81-85). - Once the browser has answered (successfully or not) it sets
IsResolved, assignsZonethrough the privateResolveZone, and returns true (ViewerTimeZone.cs:87-89). It returns true even when the zone stays UTC, because the first resolution is what turnsFormatoutput from the empty placeholder into a time, so the caller always re-renders once.ResolveZone(ViewerTimeZone.cs:128) falls back to UTC for a missing or unknown id. ToViewerTime(ViewerTimeZone.cs:100) readsUtcandUnspecifiedkinds as UTC (a deserialized value often arrives unspecified) and normalizesLocalfirst, then callsTimeZoneInfo.ConvertTimeFromUtc.Format(ViewerTimeZone.cs:118) returnsstring.EmptywhileIsResolvedis false (prerender, and the first interactive render beforeEnsureResolvedAsyncran); once resolved it formats the converted value withCultureInfo.CurrentCulture, default format"g".DisposeAsync(ViewerTimeZone.cs:122) forwards to the module wrapper.
- Why it's built this way: ADR-027
treats locale as a per-viewer concern. Returning a boolean from
EnsureResolvedAsynckeeps the service free of render coupling: the page calls it fromOnAfterRenderAsyncon its first render and decides whether to callStateHasChanged. Swallowing prerender interop failures lets the same component render on the server and then fill in after hydration; rendering an empty placeholder until then, rather than a UTC fallback, means a UTC time never paints only to jump to the viewer's clock a moment later. - Where it's used: registered with
TryAddScoped<ViewerTimeZone>()(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:239) and injected byNotificationList.razor.cs:30,NotificationInbox.razor.cs:37andSessions.razor.cs:36underMMCA.Common.UI/Pages/and byComponents/Auth/UserSessionsTable.razor.cs:32, plus ADC pages such asMMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Pages/Points/MyPoints.razor.cs. Covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Culture/ViewerTimeZoneTests.cs.
MultiFactorRequiredSignal
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/TwoFactor/MultiFactorRequiredSignal.cs:19· Level 2 · class (internal static)
- What it is: an in-process signal that carries "the API refused this session for want of a
second factor" from the API client's message handler to the page that should react to it
(
MultiFactorRequiredSignal.cs:6-12). - Depends on: ITokenStorageService (the key) and its nested
Subscription. Externals:
ConditionalWeakTable<TKey, TValue>. - Concept introduced, a signal keyed by the token owner, not by DI scope. The handler that sees
the refused response runs in the
IHttpClientFactoryhandler scope, not the component's, so a scoped event service would reach the wrong subscriber. The class keys the signal by the token storage that attached the bearer (the same owner AuthDelegatingHandler reports a 401 to), and the subscriber is the listener rendered in that storage's scope (MultiFactorRequiredSignal.cs:8-11).[Rubric §19, State Management]assesses whether cross-component state has one clear owner and lifetime; here the lifetime is the storage instance itself: theConditionalWeakTablekey means an ended circuit or scope is never kept alive by a subscription (MultiFactorRequiredSignal.cs:14-15).[Rubric §11, Security]applies because the signal is how a step-up demand from the API turns into a prompt instead of a silent failure. - Walkthrough
Subscriptions(MultiFactorRequiredSignal.cs:21) is the staticConditionalWeakTable<ITokenStorageService, Subscription>: one subscriber per storage.Subscribe(ITokenStorageService, Action)(MultiFactorRequiredSignal.cs:27) null-guards both arguments (MultiFactorRequiredSignal.cs:29-30), creates the handle and stores it withAddOrUpdate(MultiFactorRequiredSignal.cs:33), so a later subscription replaces an earlier one (MultiFactorRequiredSignal.cs:15-17), and returns it as anIDisposable(MultiFactorRequiredSignal.cs:34).HasSubscriber(owner)(MultiFactorRequiredSignal.cs:40-41) lets the handler skip all body inspection when nothing listens.Raise(owner)(MultiFactorRequiredSignal.cs:45) invokes the subscriber when there is one (MultiFactorRequiredSignal.cs:47-50) and is otherwise a no-op.
- Why it's built this way: ADR-051 makes the token storage the unit that owns a session on the client; keying the signal by that same instance keeps the 403 path aligned with the 401 renewal path.
- Where it's used:
AuthDelegatingHandler.ReportMultiFactorRequiredAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthDelegatingHandler.cs:281) resolves the owner of the refused bearer, returns early unlessHasSubscriberis true and the response is Problem Details (AuthDelegatingHandler.cs:290-293), buffers the body, and callsRaisewhen it carries the multi-factor-required code (AuthDelegatingHandler.cs:246-250). MultiFactorRequiredListener subscribes (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/MultiFactorRequiredListener.cs:41). Covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/TwoFactor/MultiFactorRequiredSignalTests.cs.
ITwoFactorUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/TwoFactor/ITwoFactorUIService.cs:16· Level 3 · interface
- What it is: the client contract for the signed-in account's own two-factor authentication
against
auth/two-factor: status, enrollment, recovery codes and turning it off (ITwoFactorUIService.cs:6-9). - Depends on: Result and the shared response contracts TwoFactorStatusResponse, TwoFactorSetupResponse and TwoFactorRecoveryCodesResponse.
- Concept introduced, a separate interface so existing implementations keep compiling.
[Rubric §1, SOLID]assesses interface segregation among other things; the remarks say this is a separate interface rather than new IAuthUIService members precisely so a consumer's ownIAuthUIServiceimplementation keeps compiling (ITwoFactorUIService.cs:11-12).[Rubric §24, Forms/Validation/UX Safety]applies to the write contract: every write is sent once and never retried, because enrollment mints a fresh secret per call, a code is accepted once per time step, and a regenerated set replaces the previous one (ITwoFactorUIService.cs:12-14). - Walkthrough
GetStatusAsync(ITwoFactorUIService.cs:21): whether the second factor is on and how many recovery codes are left.BeginEnrollmentAsync(ITwoFactorUIService.cs:29): the API mints a secret and returns the shared key and provisioning URI; the factor is not on yet.ConfirmEnrollmentAsync(code)(ITwoFactorUIService.cs:35): turns the factor on and returns the recovery codes, shown once.RegenerateRecoveryCodesAsync(code)(ITwoFactorUIService.cs:41) andDisableAsync(code)(ITwoFactorUIService.cs:47): both proved with a live authenticator or recovery code.- Every member returns
Result/Result<T>carrying the API's own refusal on failure.
- Where it's used: implemented by TwoFactorUIService and registered by
TwoFactorUIModule (
AddTwoFactorUI(),MMCA.Common/Source/Presentation/MMCA.Common.UI/TwoFactor/DependencyInjection.cs:27); injected by TwoFactorAccount and TwoFactorEnrollmentPanel. The UI gallery supplies a stub (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Gallery/Stubs/StubTwoFactorUIService.cs).
LoginRefusals
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/TwoFactor/LoginRefusals.cs:29· Level 3 · class (internal static)
- What it is: the refusal-code classification and notice mapping shared by the sign-in page and
the two-factor account page, kept out of their code-behind files (
LoginRefusals.cs:24-28). - Depends on: LoginRefusal, AuthErrorCodes,
Result and the
LocalizedErrorMessageextension on it. Externals:IStringLocalizer. - Concept introduced, match the code, never the wording.
[Rubric §27, Internationalization]assesses whether behavior survives translation; the class comment states the rule: refusals are matched on the error code, never on the message, which is localized and may change (LoginRefusals.cs:26-27).[Rubric §9, API & Contract Design]applies because the error code is the contract between API and UI. - Walkthrough
- Constants:
TwoFactorEnabledReason"two-factor-enabled"(LoginRefusals.cs:32) andTwoFactorRequiredReason"two-factor-required"(LoginRefusals.cs:35), thereasonquery values the two-factor page sends to the sign-in page. The class holds no error-code constants of its own: callers pass the sharedAuthErrorCodesvalues, such asAuthErrorCodes.TwoFactorRecentSignInRequired(MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthErrorCodes.cs:66). Classify(Result)(LoginRefusals.cs:40) returnsOtherunless there is exactly one error (list pattern[var error],LoginRefusals.cs:44-46), then mapsTwoFactorRequired,TwoFactorInvalidandEmailNotConfirmedto their steps (LoginRefusals.cs:49-54).HasCode(result, code)(LoginRefusals.cs:62-63) is an ordinal match over every error; both two-factor pages call it withAuthErrorCodes.TwoFactorRecentSignInRequired(TwoFactorAccount.razor.cs:355,TwoFactorEnrollmentPanel.razor.cs:102).ReasonNoticeKey(reason)(LoginRefusals.cs:71) maps the two reasons toAuth.Login.TwoFactorEnabledNoticeandAuth.Login.TwoFactorRequiredNoticeand ignores anything else (LoginRefusals.cs:73-75), so an arbitrary query value cannot select text.Describe(result, localizer, fallbackKey)(LoginRefusals.cs:87) picks words in three tiers: the resource named by a single error code when it exists (LoginRefusals.cs:92-98, because the API's message is an English sentence), then the API message localized when it can be, then the fallback key (LoginRefusals.cs:101).
- Constants:
- Where it's used: Login classifies with it
(
MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor.cs:125); TwoFactorAccount sends both reasons and usesHasCode/Describe(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/TwoFactor/TwoFactorAccount.razor.cs:222,TwoFactorAccount.razor.cs:302,TwoFactorAccount.razor.cs:355,TwoFactorAccount.razor.cs:361); TwoFactorEnrollmentPanel does the same for enrollment (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/TwoFactor/TwoFactorEnrollmentPanel.razor.cs:102andTwoFactorEnrollmentPanel.razor.cs:109).
TwoFactorUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auth.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/TwoFactor/TwoFactorUIService.cs:24· Level 4 · class (sealed)
- What it is: the HTTP implementation of ITwoFactorUIService over the
auth/two-factorendpoints (TwoFactorUIService.cs:10-12). - Depends on: AuthenticatedServiceBase (base class),
ITokenStorageService, HttpResultExecutor,
ProblemDetailsResultReader and
TwoFactorCodeRequest. Externals:
IHttpClientFactory. - Concept introduced: none new; it follows the authenticated-service shape of
MachineClientAdminService (
TwoFactorUIService.cs:14-18): the bearer comes from the component's own token storage so a 401 renews the right session, responses are read throughProblemDetailsResultReaderwith the API's error codes intact, and transport faults become failures throughHttpResultExecutor.[Rubric §29, Resilience & Business Continuity]assesses whether retries are applied only where safe; here only the status read is retried (TwoFactorUIService.cs:18-19).[Rubric §11, Security]applies too: neither the secret nor a recovery code is logged or cached, they live only in the returned value (TwoFactorUIService.cs:19-20). - Walkthrough
Endpointis"auth/two-factor"(TwoFactorUIService.cs:29).GetStatusAsync(TwoFactorUIService.cs:32) is the only call wrapped inRetryPolicy.ExecuteAsync(TwoFactorUIService.cs:37).BeginEnrollmentAsync(TwoFactorUIService.cs:47) POSTsenrollmentwith no body (TwoFactorUIService.cs:52-53).ConfirmEnrollmentAsync(TwoFactorUIService.cs:61-62) andRegenerateRecoveryCodesAsync(TwoFactorUIService.cs:65-66) share the privatePostCodeAsync(TwoFactorUIService.cs:92), which rejects a blank code (TwoFactorUIService.cs:94) and posts a trimmedTwoFactorCodeRequest, reading back the recovery codes (TwoFactorUIService.cs:100-106).DisableAsync(TwoFactorUIService.cs:69) applies the same blank-code guard (TwoFactorUIService.cs:71) and posts todisable, reading a non-genericResult(TwoFactorUIService.cs:77-82).
- Why it's built this way: ADR-094 sets the client data-access shape the authenticated services share; ADR-051's token-owner tracking is why the bearer comes from the injected storage rather than a shared client.
- Where it's used: registered as
TryAddScoped<ITwoFactorUIService, TwoFactorUIService>()byAddTwoFactorUI()(MMCA.Common/Source/Presentation/MMCA.Common.UI/TwoFactor/DependencyInjection.cs:27). Covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/TwoFactor/TwoFactorUIServiceTests.cs.
IPublicLinkBuilder
MMCA.Common.UI ·
MMCA.Common.UI.Services.Navigation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/IPublicLinkBuilder.cs:9· Level 0 · interface
- What it is: a one-method abstraction that turns an app-relative path into an absolute, publicly
shareable URL (
IPublicLinkBuilder.cs:9-13). It exists so share sheets, copy-link buttons and QR payloads produce a URL that still works once it leaves the app. - Depends on: nothing first-party. BCL
Uriandstring. Implemented by NavigationPublicLinkBuilder in this package and by MauiPublicLinkBuilder on the hybrid head. - Concept introduced, head-agnostic absolute link building.
[Rubric §18, UI Architecture]assesses whether shared components stay host-agnostic instead of branching on the host they run in, and[Rubric §25, Navigation & Information Architecture]assesses whether outbound links are built from one authority rather than string-concatenated per call site. The doc comment (IPublicLinkBuilder.cs:3-8) states the problem exactly: web heads can derive a shareable origin from the browser, but the MAUI head cannot, because its internal origin is the WebView's virtual host. Encoding that virtual origin into a QR code or a shared link would produce a URL nobody outside the app can open. One interface with two implementations moves the head-specific knowledge to the composition root and lets the pages stay identical on every head. - Walkthrough
- A single member,
Uri BuildAbsolute(string relativePath)(IPublicLinkBuilder.cs:13). It returns aUrirather than astring, so callers that need text do theToString()themselves, and the doc comment gives/sessions/42as the shape of the argument (IPublicLinkBuilder.cs:11). - The default binding resolves the path against
NavigationManager.BaseUri(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/NavigationPublicLinkBuilder.cs:25), after rejecting a blank path (NavigationPublicLinkBuilder.cs:23). - The hybrid binding resolves against the
PublicSite:BaseUrlkey pinned in the head's embedded configuration (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/Services/MauiPublicLinkBuilder.cs:17andMauiPublicLinkBuilder.cs:28-32), and throwsInvalidOperationExceptionat construction when the key is missing, so a misconfigured head fails at startup instead of shipping unusable links.
- A single member,
- Why it's built this way: the default is registered with
TryAddScoped(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:245) and the comment above it (DependencyInjection.cs:241-244) records the override rule: the hybrid head callsAddCommonMauiPublicLinkBuilder()afterAddUIShared(MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/DependencyInjection.cs:174-175, invoked atMMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/MauiProgram.cs:152) and the last registration wins. That is the same head-override composition convention ADR-042 establishes for the device capability layer. - Where it's used: the shared
SharePageButtoncomponent (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Sharing/SharePageButton.razor:4andSharePageButton.razor:43), the sharedQrCodeButtoncomponent (QrCodeButton.razor:1andQrCodeButton.razor:79), and app pages such as ADC's speaker QR page (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Speakers/SpeakerQr.razor.cs:26andSpeakerQr.razor.cs:62). A bUnit test pins the default registration to the browser-origin builder (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Navigation/NavigationPublicLinkBuilderTests.cs:59).
BackNavigationResult
MMCA.Common.UI ·
MMCA.Common.UI.Services.Navigation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/MauiBackNavigationBridge.cs:19· Level 0 · record (sealed)
- What it is: the outcome of a hardware-back or WebView-back attempt routed through MauiBackNavigationBridge: whether the WebView consumed the gesture, and whether the WebView is sitting at the root of its history stack.
- Depends on: nothing first-party. It is a two-field positional record produced and consumed by MauiBackNavigationBridge.
- Concept introduced, the interop return contract. This record is also the wire shape of a single
JS interop call:
nav-interop.js'stryGoBack()returns an object that deserializes straight into it (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/MauiBackNavigationBridge.cs:48), so the C# type and the JS return value are one contract. - Walkthrough:
public sealed record BackNavigationResult(bool Handled, bool AtRoot)(MauiBackNavigationBridge.cs:19).Handledistruewhen the WebView's history stack contained a previous entry andhistory.back()fired (MauiBackNavigationBridge.cs:9-13);AtRootistruewhen no previous entry exists, and the doc comment records that MAUI hosts typically exit the app on Android when that is reported (MauiBackNavigationBridge.cs:14-18). - Why it's built this way: a
sealed recordbuys structural equality and positional deconstruction for free, and it is the smallest thing that can carry the two facts the native host needs. Modeling the answer as data (rather than throwing, or mutating shared state) keeps the interop call pure and trivially testable. - Where it's used: returned by
MauiBackNavigationBridge
.HandleBackPressedAsync; consumed by MAUI hostContentPage.OnBackButtonPressedhandlers.
ReturnUrlProtector
MMCA.Common.UI ·
MMCA.Common.UI.Services.Navigation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/ReturnUrlProtector.cs:9· Level 0 · class (static)
- What it is: a pure sanitizer for
returnUrlquery parameters: it accepts only same-origin relative paths and replaces anything else with a safe fallback, closing the open-redirect hole in post-login and post-action redirects. - Depends on: nothing first-party;
System.Uri(BCL) supplies the final relative-URI parse guard. - Concept introduced, open-redirect defense.
[Rubric §26, Front-End Security]assesses whether user-controlled navigation targets are validated before use. An open redirect lets an attacker craft/login?returnUrl=https://evil.comso the victim lands on an attacker site after authenticating, a classic phishing amplifier.Sanitizerejects every off-host form rather than trying to enumerate attacks, and the ordered guards read as a documented threat model. - Walkthrough:
Sanitize(string? candidate, string fallback = "/")(ReturnUrlProtector.cs:18) runs a sequence of cheap, regex-free checks (a regex here would invite ReDoS), each returningfallbackon failure:- null or empty (lines 20-23);
- must start with
/, which rules out scheme-prefixed absolutes such ashttp://andjavascript:(lines 25-30); - the second character must not be
/or\, which browsers read as the start of an authority component and would send the user off-host (lines 32-37); - no backslash anywhere, since some browsers normalize
\to/(the source names"/\\evil.com"becoming//evil.comin Chrome, lines 39-44); - no control characters, which are header-injection, response-splitting and cookie-smuggling vectors (lines 46-51);
- and finally it must parse as a well-formed relative URI (
Uri.TryCreate(..., UriKind.Relative), lines 53-57). Only a candidate that survives all six is returned unchanged (line 59).
- Why it's built this way: a static pure function whose only input is the candidate is trivially unit-testable across every attack vector, and calling it centrally means no page hand-rolls its own redirect validation.
- Where it's used: login and post-authentication redirects sanitize the
returnUrlthey read from the query string;SignOutNavigator.SignOutAsyncalso runs its destination through it before navigating (SignOutNavigator.cs:71), andRedirectToLogin.LoginPathForsanitizes the return path before building the login link (RedirectToLogin.razor:30), so neither sign-out nor the login redirect can be turned into a redirect vector.
AuthEmailPrefill
MMCA.Common.UI ·
MMCA.Common.UI.Services.Navigation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/AuthEmailPrefill.cs:11· Level 0 · class (internal, static)
- What it is: a two-method helper that hands an email address from one shared auth page to the
next through the navigation's history state rather than the URL, so a page can open with the address
already typed (
AuthEmailPrefill.cs:5-10). - Depends on: nothing first-party.
Microsoft.AspNetCore.Components.NavigationManagerandNavigationOptions(ASP.NET Core Blazor,AuthEmailPrefill.cs:1). - Concept introduced, history state as a private side channel.
[Rubric §26, Front-End Security]assesses whether sensitive values stay out of places they leak from. A query string such as/login?email=...is written into the address bar, browser history, server request logs and theRefererheader of any outbound request;NavigationOptions.HistoryEntryStatetravels with the history entry and appears in none of those, which is exactly the reason the class doc gives (AuthEmailPrefill.cs:6-7).[Rubric §24, Forms, Validation & UX Safety]reads the other side: the user is not asked to retype an address the app already holds. - Walkthrough
- Two private prefixes tag the state string (
AuthEmailPrefill.cs:13-14):"mmca-auth:existing-account:"and"mmca-auth:prefill:". The prefix carries one extra bit, whether the address was just refused because it already holds an account. NavigateWithEmail(navigation, path, email, existingAccount = false)(AuthEmailPrefill.cs:23-27) callsNavigateTo(path, new NavigationOptions { HistoryEntryState = prefix + email }).Read(navigation, out bool existingAccount)(AuthEmailPrefill.cs:33-52) readsnavigation.HistoryEntryState, returnsnullwhen there is none (:38-41), setsexistingAccountand strips the prefix when the existing-account tag matches (:43-47), strips the plain prefix otherwise (:49-51), and returnsnullfor any state it did not write. Both comparisons areStringComparison.Ordinal.NonEmpty(:54) turns a blank remainder intonull, so a page never prefills an empty string over its own default.
- Two private prefixes tag the state string (
- Why it's built this way: the prefix check means a history entry written by some other code is
ignored rather than misread as an address, and keeping the class
internalholds the convention to the shared auth pages that read and write it. No ADR records the choice; the rationale is the class doc (AuthEmailPrefill.cs:5-10). - Where it's used: Register lands a duplicate address on sign-in with
existingAccount: true(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Register.razor:268) and sends the pending address to sign-in (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Register.razor.cs:79); Login reads it (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor.cs:182) and hands the typed address to/forgot-password(Login.razor.cs:211), which reads it back (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ForgotPassword.razor:82). bUnit tests drive the round trip (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/SignInLinks/LoginSignInLinkTests.cs:47,MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/RegistrationPending/RegisterPendingTests.cs:83). - Caveats: history state lives only on the history entry; a fresh URL typed or opened in a new tab carries no state, and the page falls back to an empty field.
IForbiddenReExecutionDetector
MMCA.Common.UI ·
MMCA.Common.UI.Services.Navigation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/IForbiddenReExecutionDetector.cs:17· Level 0 · interface
- What it is: a one-property contract that answers whether the page being rendered is a
status-code re-execution of a request the server already refused with 403 Forbidden
(
IForbiddenReExecutionDetector.cs:3-5,:23). - Depends on: nothing. Implemented by NoForbiddenReExecutionDetector
in this package and by
HttpContextForbiddenReExecutionDetector in
MMCA.Common.UI.Web. - Concept introduced, a server-only question behind a head-neutral contract.
[Rubric §18, UI Architecture & Component Design]assesses whether shared components stay host-agnostic. Hosts re-execute error statuses to/not-found(UseStatusCodePagesWithReExecute("/not-found")), so a full page load refused with 403 also lands on the not-found page with the original status still on the response (IForbiddenReExecutionDetector.cs:7-10). Only a server render can read that response, andMMCA.Common.UImust stay free of server types so it runs on Blazor WebAssembly (:10-11), so the question is asked through this interface and answered per head.[Rubric §25, Navigation, Routing & Information Architecture]reads the result: a signed-in user who lacks a permission sees Access Denied, not a misleading Page Not Found. - Walkthrough: a single getter,
bool IsForbiddenReExecution { get; }(IForbiddenReExecutionDetector.cs:23), documented to answerfalsewhenever there is no request to read (:19-22). - Why it's built this way: the same head-override composition used across the UI layer.
AddUISharedregisters the always-false default withTryAddSingleton(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:259-262), and the Blazor Web host'sAddMmcaBlazorWebHostreplaces it with the request-reading one (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:139), which comparesHttpContext.Response.StatusCodeto 403 (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Services/HttpContextForbiddenReExecutionDetector.cs:31-32). - Where it's used: injected by the shared
NotFoundpage (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/NotFound.razor:6), which renders theForbiddenview when it answerstrueand the not-found content otherwise (NotFound.razor:16-28).MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/NotFoundTests.cscovers both branches, andHttpContextForbiddenReExecutionDetectorTestscovers the server implementation.
InAppDiagnosticsOptions
MMCA.Common.UI ·
MMCA.Common.UI.Services.Diagnostics·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/InAppDiagnosticsOptions.cs:10· Level 0 · class (sealed)
- What it is: the options for the in-app diagnostics log: how many entries the in-memory buffer
keeps and the lowest level it records (
InAppDiagnosticsOptions.cs:7-9). - Depends on: nothing first-party.
System.ComponentModel.DataAnnotations.RangeAttributeandMicrosoft.Extensions.Logging.LogLevel. - Concept introduced: none new; a plain options class validated without reflection by InAppDiagnosticsOptionsValidator, the same shape as ApiSettings and ApiSettingsValidator.
- Walkthrough
DefaultCapacity = 500(InAppDiagnosticsOptions.cs:13).Capacity(:19-20),[Range(1, 100_000)], defaulting toDefaultCapacity; when the buffer is full each new entry drops the oldest (:15-18).MinimumLevel(:26), defaulting toLogLevel.Information, so Debug and Trace never reach the buffer (:22-25).
- Why it's built this way: compiled-in defaults let a host call
AddInAppDiagnostics()with no configuration at all, and the range bound keeps a mistyped capacity from allocating an oversized array. - Where it's used: configured through the optional callback of
DependencyInjection
.AddInAppDiagnostics(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/DependencyInjection.cs:27-33); read by InAppLogBuffer (capacity) and InAppLoggerProvider (minimum level).
InAppLogEntry
MMCA.Common.UI ·
MMCA.Common.UI.Services.Diagnostics·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/InAppLogEntry.cs:15· Level 0 · record (sealed, positional)
- What it is: one log record held by InAppLogBuffer: timestamp, level,
category, formatted message and an optional exception description (
InAppLogEntry.cs:15-20). - Depends on: nothing first-party.
Microsoft.Extensions.Logging.LogLevel, BCLDateTimeOffsetandCultureInfo. - Concept introduced: none; a positional record used as an immutable value.
- Walkthrough: the five positional members (
InAppLogEntry.cs:15-20), whereExceptionis astring?rather than anExceptionobject, so the buffer holds no live exception graph. TheToString()override (:27-33) is the text that is copied and shared (:22-26): an invariant-culture line of the UTC timestamp asyyyy-MM-dd HH:mm:ss.fffwith aZsuffix, the level in brackets, the category and the message (:29-31), plus a second indented line carrying the exception when there is one (:32). - Why it's built this way: formatting with
CultureInfo.InvariantCultureand UTC keeps a log a user shares readable by whoever receives it, whatever the device locale or time zone. - Where it's used: produced by the private InAppLogger, stored by
InAppLogBuffer, and rendered by the
InAppDiagnosticsLogcomponent.
NavigationPublicLinkBuilder
MMCA.Common.UI ·
MMCA.Common.UI.Services.Navigation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/NavigationPublicLinkBuilder.cs:11· Level 1 · class (sealed)
- What it is: the default IPublicLinkBuilder. It turns an app-relative route
such as
sessions/42into an absolute URL by resolving it against the origin the browser is currently served from, which is what a share sheet, a copy-link button or a QR payload needs. - Depends on: IPublicLinkBuilder (the contract it implements,
NavigationPublicLinkBuilder.cs:11);Microsoft.AspNetCore.Components.NavigationManager(ASP.NET Core Blazor,NavigationPublicLinkBuilder.cs:1,13) for the origin. Nothing else: no HTTP, no configuration, no JS interop. - Concept introduced, the origin a link is built from is a per-head decision, not a per-page one.
[Rubric §25, Navigation, Routing & Information Architecture]assesses whether routes and the URLs built from them are modelled once rather than reconstructed ad hoc at each call site. A page that wants to share itself has two candidate origins available, and only one of them is right: the in-process origin the component is rendering under, and the public web origin a recipient can open. On the Server and WebAssembly heads those coincide, soNavigationManager.BaseUriis the correct answer and this class is a two-line adapter over it. On the MAUI Blazor Hybrid head they do not: the WebView serves the app from an internal virtual host, so an absolute URL built fromBaseUrithere would be unopenable anywhere else (the class comment records exactly this at lines 5-10). Hoisting the decision behind an interface is what lets the sharedSharePageButtonandQrCodeButtonstay head-agnostic (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Sharing/SharePageButton.razor:4,MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Sharing/QrCodeButton.razor:1).[Rubric §18, UI Architecture & Component Design]reads the same choice from the component side: the shared components inject a contract, never aNavigationManager. - Walkthrough
- One readonly field,
_navigationManager(line 13), assigned by an expression-bodied constructor (lines 17-18). The class issealedand holds no other state, so a scoped instance costs a reference. BuildAbsolute(string relativePath)(line 21) rejects a blank path outright withArgumentException.ThrowIfNullOrWhiteSpace(line 23): an empty share link is a caller bug, not a condition to render, and this is the one place cheap enough to catch it.- The build itself is one expression (line 25):
new Uri(new Uri(_navigationManager.BaseUri, UriKind.Absolute), relativePath). The innerUriforces the base to be parsed as absolute, and the outer resolution applies standard URI reference resolution to the path. - The behavior callers rely on is pinned rather than assumed:
NavigationPublicLinkBuilderTests
asserts that
"/sessions/42"and"sessions/42"both resolve tohttp://localhost/sessions/42against the bUnit origin (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Navigation/NavigationPublicLinkBuilderTests.cs:21-25), that a query string survives (:27-29), and that a blank path throws (:31-41).
- One readonly field,
- Why it's built this way:
AddUISharedregisters this implementation withTryAddScoped(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:245), so every head gets a working builder without opting in, and the one head that must differ replaces it afterwards:AddCommonMauiPublicLinkBuilder()registers MauiPublicLinkBuilder over the configured public site URL (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/DependencyInjection.cs:175). The registration shape is itself asserted, implementation type and lifetime, so a refactor that changes the default is a red test rather than a silently wrong share link (NavigationPublicLinkBuilderTests.cs:43-62). - Where it's used: injected by the framework's share affordances,
SharePageButtonandQrCodeButton, and by ADC's SpeakerQr page, which encodes the absolute public URL into the badge QR rather than the WebView origin (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Speakers/SpeakerQr.razor.cs:26). The bUnit harnesses in both repos register it explicitly so component tests exercise the real builder (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/BunitTestBase.cs:43,MMCA.ADC/Tests/Modules/Conference/MMCA.ADC.Conference.UI.Tests/BunitTestBase.cs:35). - Caveats:
BuildAbsoluteperforms no allow-list check onrelativePath, and nothing in the class restricts the result to the app's own origin, so a path value that came from user input should be sanitized upstream.
MauiBackNavigationBridge
MMCA.Common.UI ·
MMCA.Common.UI.Services.Navigation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/MauiBackNavigationBridge.cs:28· Level 1 · class (static)
- What it is: a static bridge that routes a native MAUI back gesture (Android hardware back, iOS swipe) into the BlazorWebView's internal history stack, so pressing back inside a hybrid app behaves like a web back rather than tearing down the page.
- Depends on: BackNavigationResult (its return type);
Microsoft.JSInterop(IJSRuntime,IJSObjectReference,JSDisconnectedException,JSException) and thenav-interop.jsmodule shipped as static web assets of this package. - Concept introduced, MAUI-to-WebView interop.
[Rubric §22, Responsive & Cross-Browser]extends to hybrid hosts here: the same Blazor UI runs inside a MAUI WebView, and native chrome events must be reconciled with web navigation. The class doc states the required call site precisely, fromContentPage.OnBackButtonPressedviaBlazorWebView.TryDispatchAsync, so the call runs on the renderer thread with access to the WebView'sIJSRuntime(MauiBackNavigationBridge.cs:21-27). - Walkthrough:
HandleBackPressedAsync(IJSRuntime js)(line 38) null-checks the runtime (ArgumentNullException.ThrowIfNull, line 40), dynamically imports./_content/MMCA.Common.UI/nav-interop.js(ModulePath, line 30) into anawait usingmodule reference (line 47) and invokes itstryGoBack()helper, deserializing the answer into a BackNavigationResult (lines 48-49). The module reference is disposed on every call: the class is static, so nothing else owns it, and re-importing on each back press without disposing would leak one JS object reference per press (comment at lines 44-46). Three interop failure modes are caught explicitly and collapse to the same safe valuenew BackNavigationResult(Handled: false, AtRoot: true):InvalidOperationExceptionwhen Blazor is not yet hydrated (lines 51-55),JSDisconnectedException(lines 56-59, which also covers a dispose on a torn-down circuit), andJSException(lines 60-63). A not-yet-ready WebView therefore reports "at root, not handled" and the host falls back to its default back behavior. - Why it's built this way: a static helper with no state fits a one-shot interop call, and returning a data record instead of throwing keeps the native handler branch-free. Because it holds no state, it also cannot cache the imported module, which is why each call owns and disposes its own reference. Collapsing the three JS exception types into one safe default means an unhydrated or disconnected circuit never crashes the native back button.
- Where it's used: the MAUI host base page in
MMCA.Common.UI.Maui(MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/MainPageBase.cs:255) calls it from itsOnBackButtonPressedoverride (MainPageBase.cs:216); the returned BackNavigationResult tells the host whether to exit the app. - Caveats / not-in-source: the
nav-interop.jstryGoBack()implementation and theMainPageBasedispatch logic live outside this unit; only the C# side of the bridge is visible here.
InAppDiagnosticsOptionsValidator
MMCA.Common.UI ·
MMCA.Common.UI.Services.Diagnostics·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/InAppDiagnosticsOptionsValidator.cs:10· Level 1 · class (internal, sealed, partial)
- What it is: the source-generated validator for InAppDiagnosticsOptions:
it checks the same data annotations
ValidateDataAnnotationswould, without reflection (InAppDiagnosticsOptionsValidator.cs:5-8). - Depends on: InAppDiagnosticsOptions;
[OptionsValidator]andIValidateOptions<T>fromMicrosoft.Extensions.Options(:1,:9). - Concept introduced: cross-reference ApiSettingsValidator, which teaches
the same declaration-only
[OptionsValidator]partial: the generator writes the body at compile time, so validation also runs on a trimmed WebAssembly or MAUI build. - Walkthrough: the whole type is one line (
:10); the only rule it enforces is the[Range(1, 100_000)]onCapacity(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/InAppDiagnosticsOptions.cs:19). - Where it's used: registered by
AddInAppDiagnosticswithTryAddEnumerable, so a repeated call does not validate twice (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/DependencyInjection.cs:35-38).
NoForbiddenReExecutionDetector
MMCA.Common.UI ·
MMCA.Common.UI.Services.Navigation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/NoForbiddenReExecutionDetector.cs:8· Level 1 · class (internal, sealed)
- What it is: the default IForbiddenReExecutionDetector for heads
that never render a server response (Blazor WebAssembly, MAUI): with no request to read, a render is
never a 403 re-execution (
NoForbiddenReExecutionDetector.cs:3-7). - Depends on: IForbiddenReExecutionDetector only.
- Concept introduced: see IForbiddenReExecutionDetector.
- Walkthrough:
IsForbiddenReExecution => false(NoForbiddenReExecutionDetector.cs:11). No state, no constructor. - Why it's built this way: a constant answer keeps the shared
NotFoundpage renderable on every head without a server dependency, and registering it withTryAddSingleton(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:262) leaves the Blazor Web host free toReplaceit with HttpContextForbiddenReExecutionDetector (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:139). - Where it's used: the default on the WebAssembly and MAUI heads; the Common bUnit harness
registers it explicitly
(
MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/BunitTestBase.cs:47), and a test pins it as whatAddUISharedresolves (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/NotFoundTests.cs:66).
InAppLogBuffer
MMCA.Common.UI ·
MMCA.Common.UI.Services.Diagnostics·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/InAppLogBuffer.cs:11· Level 3 · class (sealed)
- What it is: a fixed-size, thread-safe ring buffer of InAppLogEntry records: the in-memory store behind the in-app diagnostics log.
- Depends on: InAppLogEntry, InAppDiagnosticsOptions
(through
IOptions<T>); BCLSystem.Threading.Lock. - Concept introduced, a bounded ring buffer as a crash-free log sink.
[Rubric §13, Observability & Operability]assesses whether a running system can be diagnosed. A MAUI store build has no console and no attached debugger, so its logs otherwise go nowhere (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/DependencyInjection.cs:21-23); this buffer keeps the most recent entries where the user can see them. A ring of fixed capacity is the right shape for that: memory is allocated once and never grows, however long the app runs, and the oldest entries are the ones worth losing. - Walkthrough
- Fields (
InAppLogBuffer.cs:13-16): aLockgate, the entry array,_next(the write index) and_count. - The constructor (
:20-26) readsCapacityfrom options, rejects anything below 1 withArgumentOutOfRangeException.ThrowIfLessThan(:24) and allocates the array once. Capacity(:29) is the array length;Count(:32-41) reads_countunder the lock.Add(:45-58) writes at_next, advances it modulo the length, and increments_countonly until the buffer is full (:51-57), so a full buffer overwrites its oldest slot.Snapshot()(:62-75) copies the held entries into a new array, oldest first, starting at(_next - _count + length) % length(:67), so callers never see the live array.Clear()(:78-86) wipes the array and resets both counters;ToText()(:90) joins the snapshot withEnvironment.NewLine, using each entry'sToString().
- Fields (
- Why it's built this way: every member takes the same lock, so the logger can write from any thread while the UI takes a snapshot. Returning a copy keeps rendering free of the lock after the snapshot is taken.
- Where it's used: written by InAppLoggerProvider, registered as a singleton
by
AddInAppDiagnostics(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/DependencyInjection.cs:41), and injected by the sharedInAppDiagnosticsLogcomponent (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Diagnostics/InAppDiagnosticsLog.razor:5), which ADC's MAUI head shows on its device settings page (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/Pages/DeviceSettings.razor:50). - Caveats: the buffer is process memory only; it is lost when the app exits, and nothing persists or uploads it unless the user copies or shares the text.
InAppLogger
MMCA.Common.UI ·
MMCA.Common.UI.Services.Diagnostics·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/InAppLoggerProvider.cs:44· Level 4 · class (private, sealed, nested in InAppLoggerProvider)
- What it is: the
ILoggerthat InAppLoggerProvider hands out per category; it turns each enabled log call into an InAppLogEntry in the shared InAppLogBuffer. - Depends on: its enclosing InAppLoggerProvider (buffer, clock and minimum
level through the primary constructor,
InAppLoggerProvider.cs:44), InAppLogEntry;Microsoft.Extensions.Logging.ILogger. - Concept introduced: none beyond the provider's; see InAppLoggerProvider.
- Walkthrough
BeginScopereturnsnull(InAppLoggerProvider.cs:46-47): scopes are not recorded.IsEnabled(:49-50) is true for any level other thanNoneat or above the configured minimum.Log(:52-72) null-checks the formatter, returns early when the level is disabled (:61-64), and adds an entry stamped withTimeProvider.GetUtcNow(), the category, the formatted message and, when present, a described exception (:66-71).DescribeException(:74-88) walks theInnerExceptionchain, writing each type's full name and message joined by" ---> "(:77-85). The stack trace is not kept.
- Why it's built this way: the exception is flattened to a string so the buffer holds no exception objects (and their captured state) alive, and the clock is injected so tests can assert timestamps.
- Where it's used: only through
InAppLoggerProvider.CreateLogger(InAppLoggerProvider.cs:36); it has no other reference.
InAppLoggerProvider
MMCA.Common.UI ·
MMCA.Common.UI.Services.Diagnostics·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/InAppLoggerProvider.cs:14· Level 4 · class (sealed)
- What it is: an
ILoggerProviderthat records log entries at or aboveInAppDiagnosticsOptions.MinimumLevelinto the in-memory InAppLogBuffer; nothing is written to disk or sent anywhere (InAppLoggerProvider.cs:8-12). - Depends on: InAppLogBuffer, InAppDiagnosticsOptions,
InAppLogger (nested), InAppLogEntry; BCL
TimeProvider,Microsoft.Extensions.LoggingandMicrosoft.Extensions.Options. - Concept introduced, a logging provider as a pluggable sink.
[Rubric §13, Observability & Operability]assesses whether diagnostics reach someone who can act on them. The logger factory fans everyILoggercall out to each registeredILoggerProvider, so adding this provider captures the output of every existing log call on the head with no change at a call site.[Rubric §30, Compliance, Privacy & Data Governance]applies to the destination: the log never leaves the process unless the user copies or shares it (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/DependencyInjection.cs:23-24). - Walkthrough
- Fields (
InAppLoggerProvider.cs:16-18): the buffer, the clock and the minimum level. - The constructor (
:24-33) null-checks its three arguments and readsMinimumLevelonce (:32). CreateLogger(categoryName)(:36) returns a new InAppLogger bound to this provider and the category.Dispose()(:39-42) releases nothing: the buffer is a DI singleton of its own and outlives the provider (:41).
- Fields (
- Why it's built this way: the buffer is a separate singleton so the UI can inject it directly without going through logging, and the minimum level is captured at construction, so a change needs a restart rather than a live reload.
- Where it's used: registered by
AddInAppDiagnosticswithTryAddEnumerable(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/DependencyInjection.cs:46); covered byMMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Diagnostics/InAppLoggerProviderTests.cs.
SignOutNavigator
MMCA.Common.UI ·
MMCA.Common.UI.Services.Navigation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/SignOutNavigator.cs:30· Level 6 · class (sealed)
- What it is: a scoped service that signs this device out and then lands the browser on a page the
caller chooses, with exactly one navigation (
SignOutNavigator.cs:7-9). It replaces the pair "IAuthUIService.LogoutAsync()then a forcedNavigateTo", which races. - Depends on: IAuthUIService (the sign-out it runs) and
NavigationManagerthrough the primary constructor (SignOutNavigator.cs:30); ReturnUrlProtector sanitizes the destination (:71);ResultfromMMCA.Common.Shared.Abstractions(:2). - Concept introduced, claiming the next navigation.
[Rubric §25, Navigation, Routing & Information Architecture]assesses whether navigation is predictable and owned by one authority. The class doc names the race (SignOutNavigator.cs:9-14): the sign-out flips the auth state, an[Authorize]page re-renders intoRedirectToLogin, and that component's own forced navigation to/login?returnUrl=...reaches the browser first, so the caller's destination is lost (the recorded case: "Delete my account" landed on the login page offering to sign back in to the deleted account). The fix is a flag, not an ordering trick: while a sign-out started here is in flight,RedirectToLoginstands down and this navigator issues the one navigation itself (:16-17). The component resolves the navigator optionally and returns early whenIsSigningOutis true (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/RedirectToLogin.razor:9-15), so a host or test that never registers it keeps the plain redirect.[Rubric §26, Front-End Security]applies to the destination: it is sanitized, never trusted. - Walkthrough
IsSigningOut(SignOutNavigator.cs:36),internalwith a private setter: the claim, readable only inside the package, byRedirectToLogin.SignOutAsync(string destination)(:47-54), the public entry point, wrapsauthService.LogoutAsync()in a delegate that answersResult.Success()and forwards to the overload below.SignOutAsync(Func<Task<Result>> signOut, string destination)(:69-93),internal, for a sign-out that can be refused, such as the account-wide revoke behind "Sign out everywhere" (:58-63). It sanitizes the destination withReturnUrlProtector.Sanitize(destination, "/")first (:71), sets the claim (:73), and awaits the sign-out (:75-78). An exception releases the claim and rethrows (:79-83); a failureResultreleases it and returns the failure with no navigation (:85-89). On success it callsNavigateTo(target, forceLoad: true)(:91) and returns the sign-out's own result.
- Why it's built this way: the claim is never released on success, deliberately
(
SignOutNavigator.cs:17-19): the forced load discards the scope (the circuit on Server, the runtime on WebAssembly, the page context on a hybrid head), and a redirect rendered after the navigation must still stand down. Releasing it on failure or exception (:20-21) means an ordinary redirect still works when the session survives. Holding the flag across the whole round trip of a refusable revoke keeps the auth flip from winning the race in that path too. No ADR records the choice; the rationale is the class doc. - Where it's used: registered with
TryAddScopedbyAddUIShared(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:199). The shared layout and menu sign-outs callSignOutAsync("/login")(MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/MainLayout.razor:218,MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor.cs:70), as do TermsAcceptanceGate (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Legal/TermsAcceptanceGate.razor.cs:237) and BiometricGate (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Capabilities/BiometricGate.razor.cs:270); TwoFactorAccount signs out to its own target (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/TwoFactor/TwoFactorAccount.razor.cs:319), and Sessions runs the refusable overload overRevokeAllSessionsAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor.cs:246).SignOutNavigatorTestspins one navigation to the destination, reproduces the race with the plain pair, lands an unsafe destination on the root, and checks that a throwing sign-out releases the claim (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Navigation/SignOutNavigatorTests.cs:39,:55,:74,:84). - Caveats: only a component that checks
IsSigningOutstands down; any other code that navigates on the auth-state flip still races the destination.
DependencyInjection
MMCA.Common.UI ·
MMCA.Common.UI.Services.Diagnostics·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/DependencyInjection.cs:13· Level 5 · class (static, with oneextension(IServiceCollection)block)
- What it is: the opt-in registration for the in-app diagnostics log, one method,
AddInAppDiagnostics(DependencyInjection.cs:27). This is theServices.Diagnosticsclass of that name, separate from theMMCA.Common.UIcomposition root that holdsAddUIShared. - Depends on: InAppDiagnosticsOptions,
InAppDiagnosticsOptionsValidator,
InAppLogBuffer, InAppLoggerProvider;
Microsoft.Extensions.DependencyInjection.ExtensionsandMicrosoft.Extensions.Options. - Concept introduced: none new. It uses the
extension(T)block for DI registration (primer, C# extension(T) types).[Rubric §33, Developer Experience]assesses how much a host must write to adopt a capability: here one call with no required configuration. - Walkthrough:
AddInAppDiagnostics(Action<InAppDiagnosticsOptions>? configure = null)(DependencyInjection.cs:27-49):AddOptions<InAppDiagnosticsOptions>(), applyingconfigurewhen given (:29-33).- InAppDiagnosticsOptionsValidator through
TryAddEnumerable, checked when the options are first read (:35-38). TryAddSingleton(TimeProvider.System)(:40), so a host or test clock registered earlier wins.TryAddSingleton<InAppLogBuffer>()(:41).- InAppLoggerProvider as an
ILoggerProviderthroughTryAddEnumerable(:46). The comment (:43-45) explains why noILoggingBuilderis needed: the logger factory takes everyILoggerProviderin the container, which is allAddProviderdoes, and the enumerableTryAddkeeps a repeated call from recording each entry twice.
- Why it's built this way: the method is idempotent (
:23), a property the registration tests call twice to prove (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Diagnostics/InAppDiagnosticsRegistrationTests.cs:46-47). It is opt-in rather than part ofAddUISharedbecause it is meant for MAUI store builds, which otherwise log nowhere, though it works on any Blazor head (:21-23). - Where it's used: ADC's MAUI head calls it
(
MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/MauiProgram.cs:122) and renders the log on its device settings page (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/Pages/DeviceSettings.razor:50).
ChannelReferenceCounter
MMCA.Common.UI ·
MMCA.Common.UI.Services.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/ChannelReferenceCounter.cs:25· Level 0 · class (internal, sealed)
- What it is: a small self-synchronized tracker of live-channel membership for one circuit. It counts the outstanding joins per channel key and remembers which held keys the server has confirmed joining on the current connection, so NotificationHubService asks the SignalR server to join a group while a held key is still unjoined (normally the first join) and to leave it only on the last matching leave.
- Depends on: nothing first-party. It is a
System.Threading.Lock, aDictionary<string, int>and aHashSet<string>(BCL). It is owned as a private field by NotificationHubService (NotificationHubService.cs:63), and sits beside (not inside) the separate handler bookkeeping that ChannelSubscription unwinds. - Concept introduced, reference-counted group membership with a confirmed-join flag.
[Rubric §19, State Management & Data Flow]assesses how a shared per-circuit resource is owned when more than one component holds it at once. A live channel is exactly that resource: an invisible layout listener and a page can both be watchingevent:1. The class remarks state why a set is the wrong structure for the count (ChannelReferenceCounter.cs:7-10): with set semantics the first leaver removes the only entry and cuts the channel off for every other subscriber still holding it. Counting joins per key turns membership into two edges, 0 to 1 and 1 to 0. The remarks then state why the count alone is not enough (lines 13-18): a first join the hub refused, or one that hit a transient hub error, leaves the key counted but not joined, and a later overlapping join sees a count above zero. The joined flag lets that later join retry without rolling the count back, since a rollback would let one holder's leave take the count to zero and drop another holder's live channel.[Rubric §29, Resilience & Business Continuity]applies as well, becauseSnapshot()is the replay list the hub service re-joins after a reconnect, andResetJoined()marks every held key as needing that re-join.[Rubric §14, Testability]shows in the visibility choice: the type isinternalwith anInternalsVisibleTofor the test project, and the project file records exactly why (MMCA.Common/Source/Presentation/MMCA.Common.UI/MMCA.Common.UI.csproj:11-16): the ref-count semantics cannot be reached through the public API, sinceJoinChannelAsyncstarts a realHubConnection, so a join-based test would need a live server and a multi-second backoff.
- Walkthrough: three fields, the
Lock(ChannelReferenceCounter.cs:27), the outstanding-joinDictionary<string, int>(line 31, whose default string comparer is ordinal, matching the hub's group-name semantics, lines 29-30), and the_joinedHashSet<string>of held keys the server confirmed joining on the current connection (line 34).AddRef(channelKey)(line 41) reads the current count, writescurrent + 1, and returnscurrent == 0, so only the 0-to-1 transition reportstrue(lines 45-47). Whether the server must be invoked is no longer read from that result;NeedsServerJoinanswers it.Release(channelKey)(line 60) returnsfalsefor a key that was never joined (lines 64-67), removes both the count entry and the joined flag and returnstruewhen the decrement reaches zero or below (lines 70-75), and otherwise stores the decremented value and returnsfalse(lines 77-78). The count therefore never goes negative and an unpaired leave is a no-op.NeedsServerJoin(channelKey)(line 88) istruewhen the key is counted but not in_joined(line 92): held, but not confirmed joined on this connection.MarkJoined(channelKey)(line 101) adds the key to_joinedonly while it is still counted (lines 105-108), so a join the server answers after its last leave cannot mark a later hold as joined.ResetJoined()(line 116) clears every joined flag and keeps the counts (line 120): a new connection holds no server group membership, so every held key needs joining again.Snapshot()(line 128) returns[.. _counts.Keys]under the lock (line 132): the distinct keys with at least one outstanding join, so a channel held twice is re-joined once.RefCountFor(channelKey)(line 139) returns the outstanding count, or zero when the channel is not held.- Every method takes the lock, because joins and leaves arrive from component lifecycle callbacks on different render batches (lines 21-22).
- Why it's built this way:
ADR-039 decided the shape this
implements: one hub,
JoinChannel/LeaveChannelmapping a connection into a SignalR group, multicast subscriptions so an invisible listener and a page can observe the same channel concurrently, and a re-join onReconnectedbecause group membership does not survive a new connection. The ADR says the hub service tracks membership; this class is how that tracking is done so two concurrent holders cannot evict each other. The joined flag is kept separate from the count because the two answer different questions: the count decides when the server is told to leave, the flag decides when it must be (re)told to join, and folding a refused join back into the count would break the one-join-one-leave pairing (ChannelReferenceCounter.cs:13-18). - Where it's used: every call site is inside NotificationHubService.
AddRefinJoinChannelAsync(NotificationHubService.cs:344, its result discarded, deliberately counted before the connection is started at line 346 so the replay insideStartAsyncsees it),NeedsServerJoingating the server invoke there (line 352) andMarkJoinedafter it succeeds (line 357);ReleaseinLeaveChannelAsync(line 382); andResetJoined,SnapshotandMarkJoinedinRejoinChannelsAsync(lines 842, 845, 858). Covered directly byChannelReferenceCounterTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Notifications/NotificationHubServiceTests.cs:893, whose summary names the H13 regression it locks down, line 890), including the joined-flag cases at lines 961, 991 and 1004. The two concurrent holders it exists for are real: LiveEventListener and the HappeningNow page both join the same event channel key. - Caveats / not-in-source: it tracks joins only; it knows nothing about handlers. Subscriptions
live in a separate
_channelSubscriptionsdictionary guarded by_channelSync(NotificationHubService.cs:56,64), so disposing a ChannelSubscription does not decrement the count, and leaving a channel does not remove handlers (NotificationHubService.cs:374-375states that pairing requirement). The count is never rolled back on a failed server join, so a holder that never leaves keeps the key in the replay list.
INotificationScopeProvider
MMCA.Common.UI ·
MMCA.Common.UI.Services.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/INotificationScopeProvider.cs:15· Level 0 · interface
- What it is: the contract that supplies the scope key the notification UI sends and reads under, plus an optional human-readable name for that scope, so an application can narrow its notifications to whatever it considers "current" (a conference event, a tenant, a season) without the framework knowing what that is.
- Depends on: nothing first-party. Both members return
Task<string?>and take aCancellationToken(BCL). Implemented in the framework by NullNotificationScopeProvider and consumed by both notification HTTP services, NotificationInboxService and PushNotificationService. - Concept introduced, the opaque scope key. The framework ships the notification feature but has
no vocabulary for what notifications belong to, so it inverts the question: the app answers with a
string and the framework treats it as opaque (
INotificationScopeProvider.cs:3-8). The value of putting one provider behind both HTTP services is agreement: a send and the reads that follow it resolve through the same instance, so the inbox, the unread badge and a bulk mark-read cannot disagree about which slice the user is looking at.[Rubric §9, API & Contract Design]assesses contract minimality and the meaning of defaults. Both members return a nullable string, and null carries a defined meaning ("unscoped", "no caption"), which is what lets the scoped and unscoped worlds share one code path instead of branching.- A default interface method as a non-breaking extension.
GetCurrentScopeDisplayNameAsyncis declared with a body,=> Task.FromResult<string?>(null)(INotificationScopeProvider.cs:41), so an application with no display name, and every implementation written before the member existed, keeps compiling untouched (the rationale is stated in the doc at lines 31-37).[Rubric §15, Best Practices & Code Quality]assesses whether a contract can grow without a coordinated sweep across every implementor; a default member is the language feature that makes that possible here. [Rubric §11, Security]assesses where authorization decisions live, and this contract is explicit that it is not one. The remarks require implementations never to throw, and they state the direction to fail in: in an application whose notifications are all scoped, fail closed, that is, return the last known scope key or fail the operation, rather than returning null, because degrading to null silently widens the view to every notification (INotificationScopeProvider.cs:9-14). Null is reserved for an application that genuinely runs unscoped. Ownership filtering itself stays on the server: a scope is a view filter, not a permission.- The display-name member fails closed differently, and the source says so: a missing caption hides
information, while a wrong one would state the wrong audience, so returning null is the safe
direction there (
INotificationScopeProvider.cs:34-36).
- Walkthrough: two members.
Task<string?> GetCurrentScopeKeyAsync(CancellationToken ct = default)(INotificationScopeProvider.cs:22) returns the key currently in force (the example in source is"event:2") or null when the application is unscoped (lines 17-21).Task<string?> GetCurrentScopeDisplayNameAsync(CancellationToken ct = default)(line 41) returns a human-readable name for that scope (the conference event's title, the tenant's name). The send page uses it to caption which scope the notification will be tagged with, so an operator can see the auto-applied scope rather than infer it (lines 24-30). The doc is explicit that the scope only decides which inbox view lists the notification and does not narrow delivery, which goes to every recipient the application's recipient provider returns, so the caption must not be read as the audience (lines 27-30). The one call site isMMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Notifications/NotificationSend.razor.cs:78.
- Why it's built this way: an interface rather than a settings value, because the answer is dynamic
(it changes as the app's current context changes) and may need an async lookup. Keeping the key a
plain string keeps the framework free of any domain concept, and the never-throw rule written into
the contract is what makes the fail-closed guarantee real rather than aspirational. See
ADR-024, which records the
optional
ScopeKeytravelling with a send. - Where it's used: injected into NotificationInboxService
(
NotificationInboxService.cs:32) and PushNotificationService (PushNotificationService.cs:18); registered withTryAddScopedagainst NullNotificationScopeProvider byAddNotificationUI()(MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/DependencyInjection.cs:24). In MMCA.ADC the real implementation is CurrentEventNotificationScopeProvider.
NotificationState
MMCA.Common.UI ·
MMCA.Common.UI.Services.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NotificationState.cs:18· Level 0 · class (sealed)
- What it is: the scoped shared state for the notification unread count. It holds the count, the timestamp of when that count was last established, and the single active-poller slot that keeps duplicate notification bells from each running their own poll loop.
- Depends on: nothing first-party. Externals: BCL
TimeProvider(injected, defaulting toTimeProvider.System,NotificationState.cs:18,21),System.Threading.Lock, and threeEventHandlerevents. Consumed by NotificationBell and the inbox page NotificationInbox. - Concept introduced, a scoped state store that owns both the value and its freshness.
[Rubric §19, State Management & Data Flow]assesses how shared UI state is owned and observed without threading it through the component tree.NotificationStateis registered scoped (MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/DependencyInjection.cs:33), so each Blazor circuit gets its own instance and components subscribe to its events instead of receiving cascading parameters. Two mechanisms are worth studying.- The staleness stamp.
LastFetchedUtc(line 41) records when the count was established, which is the state half of the client's staleness policy: a subscriber that fires on an ambient trigger (a navigation, a re-render) asksIsStale(maxAge)instead of re-reading the API every time the trigger happens to fire (lines 77-85). The subtle rule is stamped inSetUnreadCount: the stamp is written before the unchanged-count early return (line 66), because an API read that came back with the same number is still a read. Without that ordering, a quiet inbox (where the count almost never changes, so almost every read is the no-op read) would look permanently stale and re-fetch forever (lines 63-65).[Rubric §23, Front-End Performance]is the payoff. - The active-poller slot as an owner reference, not a counter.
_pollerOwner(line 29) holds the component instance that currently polls, or null when the slot is free, and the field's own doc explains why a counter was the wrong shape: a counter leaks one increment per teardown that never unregisters, and once it leaks no bell can ever win the slot again for the life of the circuit (lines 23-28). An owner reference makes register and unregister symmetric. [Rubric §14, Testability]shows in the constructor: the clock is aTimeProvider?parameter defaulting toTimeProvider.System(lines 14-18,21), so a test drivesIsStalewith a fake clock while an existing host keeps the previous no-argument constructor shape.
- The staleness stamp.
- Walkthrough: members in teaching order.
- Fields: the
Lock _pollerSync(line 20), the resolved_timeProvider(line 21), and the nullable_pollerOwner(line 29). UnreadCountwith a private setter (line 32) andLastFetchedUtcwith a private setter (line 41).- Three events:
OnChangewhen the count changes (line 44),OnRefreshRequestedwhen a real-time notification arrives and the badge should refetch the authoritative count (lines 46-50), andOnPollerSlotFreedwhen the active-poller slot becomes free so a surviving bell can take polling over (lines 52-57). SetUnreadCount(int)(lines 61-75) stampsLastFetchedUtcfirst (line 66), returns early when the value is unchanged (lines 68-71), and otherwise assigns and raisesOnChange.IsStale(TimeSpan maxAge)(lines 84-85) istruewhen there is no stamp at all or the stamp is older thanmaxAge;MarkStale()(line 92) discards the stamp outright, for a subscriber that learned the data moved (a real-time push) and knows age is no longer evidence of freshness.IncrementUnreadCount()(lines 95-99) bumps by one for an optimistic real-time update and always raisesOnChange.RequestRefresh()(line 102) raisesOnRefreshRequested.TryRegisterPoller(object owner)(lines 111-125) null-guards, takes_pollerSync, and returnsfalseonly when a different owner already holds the slot (lines 117-120); a caller that already holds it getstrueagain, so the call is idempotent.UnregisterPoller(object owner)(lines 133-150) releases the slot only when the caller is the holder (lines 139-142), so a non-owner disposing cannot evict the live poller.OnPollerSlotFreedis raised outside the lock (lines 147-149), because a subscriber claims the slot from its handler and would otherwise re-enter the lock on the disposing component's thread.
- Fields: the
- Why it's built this way: scoped because the count is per-user-session; event-based because subscribers live at arbitrary render-tree depth. The private setters funnel every mutation through the named methods, so no change can bypass the change-notification path or the freshness stamp. The owner-keyed slot plus the freed event is what survives the real lifecycle in a Blazor shell, where the desktop and mobile bell placements are rebuilt independently whenever the authentication state changes (lines 52-56).
- Where it's used: injected into NotificationBell, which claims the slot with
TryRegisterPoller(this), listens onOnPollerSlotFreedto take over, and gates its navigation refresh onIsStale(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Notifications/NotificationBell.razor.cs:60,63,152,164,200,218,334), and into NotificationInbox; driven by real-time pushes that arrive over NotificationHubService. Covered byNotificationStateTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Notifications/NotificationStateTests.cs:13).
UnboundedReconnectPolicy
MMCA.Common.UI ·
MMCA.Common.UI.Services.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/UnboundedReconnectPolicy.cs:32· Level 0 · class (internal, sealed)
- What it is: the SignalR automatic-reconnect schedule for the notification hub. It never gives up, never waits longer than 30 seconds between attempts, and jitters every delay so clients dropped together do not retry together, with one exception: when the server refused authentication, it stops.
- Depends on: nothing first-party. Externals:
IRetryPolicyandRetryContextfromMicrosoft.AspNetCore.SignalR.Client,HttpRequestException,HttpStatusCodeandRandom.Shared(BCL). Its primary constructor takes an optionalFunc<double>sample source (UnboundedReconnectPolicy.cs:32). - Concept introduced, an unbounded, jittered retry schedule with a terminal auth exception.
[Rubric §29, Resilience & Business Continuity]assesses recovery from outages of unknown length. The class remarks record that the SignalR default schedule (0, 2, 10 and 30 seconds, then stop) abandons a connection after about 42 seconds, which left live notifications dead until a page reload (UnboundedReconnectPolicy.cs:10-13); this policy replaces the give-up with a capped delay, so an outage of any length is recovered withinMaxDelayof the network returning (line 38). The second idea is jitter (lines 16-20): clients that lost the socket in one event (a hub replica restart, a deploy, a gateway blip) would otherwise retry at the same instants and hit the recovering replica in synchronized bursts. The jitter only shortens a delay, so no wait exceedsMaxDelay, and the first retry is spread over a window instead of being immediate for everyone. The one deliberate stop is a refused authentication, since an expired session cannot recover by retrying the same credentials (lines 23-25, enforced at lines 60-63). - Walkthrough:
- The primary constructor parameter
sample(line 32) feeds_sample, which falls back toRandom.Shared.NextDouble(line 52); theCA5394suppression around it states that the random value only spaces attempts apart and feeds no security decision (lines 51, 53). A test passes a constant to pin the schedule (lines 28-31). JitterFraction(line 35) is theconst0.3: the largest share of a delay the jitter takes off.MaxDelay(line 38) isinternal staticat 30 seconds so the hub's restart loop reuses the same cap (NotificationHubServiceMaxRetryDelay,NotificationHubService.cs:131).FirstRetrySpread(line 41) is one second, the window the first retry is spread over.WarmUp(lines 43-49) is the un-jittered base of the first four delays: zero, 2, 5 and 10 seconds.NextRetryDelay(line 56) null-checks the context and returnsnull(stop) whenIsAuthenticationRefused(retryContext.RetryReason)(lines 60-63). On the first retry (PreviousRetryCount == 0) it returnsFirstRetrySpread * _sample(), somewhere in the first second (lines 65-68). Otherwise it indexesWarmUpbyPreviousRetryCount, falls back toMaxDelayonce the warm-up is spent, and returns that base throughJitter(lines 70-73).Jitter(delay, sample)(line 84) isinternal static:delay * (1 - JitterFraction * Math.Clamp(sample, 0, 1))(line 85), so the result lies in 70 to 100 percent of the base and never past it, and a sample of 0 keeps the delay unchanged.IsAuthenticationRefused(line 93) walks the exception and itsInnerExceptionchain looking for anHttpRequestExceptionwhoseStatusCodeisUnauthorizedorForbidden(lines 95-100), and for anAggregateExceptionit answers from any member (lines 102-105). The hub's socket factory rethrows a refused WebSocket handshake as exactly that exception so this check can see the status (ConnectWebSocketAsync,NotificationHubService.cs:632-672).
- The primary constructor parameter
- Why it's built this way: a policy class instead of the lambda overload keeps the auth-refusal rule
testable on its own and shared with the start loop in
NotificationHubService(line 298), so the automatic reconnect and the restart loop agree on when to stop.Jitterisstaticfor the same reason: the hub's own start-retry and restart backoffs call it, so all three schedules spread their attempts the same way (doc atUnboundedReconnectPolicy.cs:76-80). The sample source is injectable so the jittered schedule stays deterministic under test. It isinternal sealedbecause it is an implementation detail of the hub service. The hub class doc states the contract (NotificationHubService.cs:33-42). - Where it's used: passed to
WithAutomaticReconnect(new UnboundedReconnectPolicy(() => JitterSample()))by NotificationHubService (NotificationHubService.cs:222), so the reconnect schedule draws from the service's settableJitterSample(line 139). ItsIsAuthenticationRefusedis called again from the start loop (NotificationHubService.cs:298), itsJitterfrom the start-retry backoff (line 318) and the restart backoff (line 744), andMaxDelayis the default ofMaxRetryDelay(line 131). Covered byNotificationHubServiceTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Notifications/NotificationHubServiceTests.cs:537, every delay within 70 to 100 percent and never past the cap, and line 576 forJitteritself).
NullNotificationScopeProvider
MMCA.Common.UI ·
MMCA.Common.UI.Services.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NullNotificationScopeProvider.cs:8· Level 1 · class (sealed)
- What it is: the framework's default INotificationScopeProvider: a no-op that always reports "unscoped", so an application that never scopes its notifications keeps exactly the behavior it had before the scope key existed.
- Depends on: INotificationScopeProvider (the interface it
implements);
Task.FromResult(BCL). - Concept reinforced, the Null Object pattern as a registration default. Rather than making the
scope provider optional and null-checking it in both HTTP services, the framework registers a
do-nothing implementation and lets the consumers depend on the interface unconditionally.
[Rubric §2, Design Patterns]assesses whether a pattern is used where it removes branching, which is exactly what happens here: NotificationInboxService and PushNotificationService contain no "is a provider registered" test.[Rubric §15, Best Practices & Code Quality]follows: the feature was additive, and an app that ignores it sees a byte-identical request. - Walkthrough: the whole type is one expression-bodied member,
GetCurrentScopeKeyAsync(CancellationToken ct = default) => Task.FromResult<string?>(null)(NullNotificationScopeProvider.cs:10-12). It does not overrideGetCurrentScopeDisplayNameAsync, which is why that member was added to the interface with a default body: the null object inherits the interface's own null answer unchanged. The class doc records the registration contract: it is the default wired byAddNotificationUI, and an app that scopes registers its own implementation, which wins (NullNotificationScopeProvider.cs:3-7). - Why it's built this way: the "wins" part is mechanical, not conventional.
AddNotificationUI()registers this type withTryAddScoped(MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/DependencyInjection.cs:24), and the source comment states the reason:TryAddmeans an app that registers its own provider wins whichever order the two registration calls run in (lines 22-23). A plainAddScopedwould have made host startup ordering load-bearing. - Where it's used: resolved as INotificationScopeProvider by NotificationInboxService and PushNotificationService in every host that has not registered its own; MMCA.ADC replaces it with CurrentEventNotificationScopeProvider.
INotificationInboxUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/INotificationInboxUIService.cs:11· Level 3 · interface
- What it is: the UI-side contract for the per-user notification inbox: paged retrieval, unread count, mark-one-read, and mark-all-read. Every member returns a Result carrying the API's own errors.
- Depends on: Result and its generic form
Result<T>, PagedCollectionResult<T>, and UserNotificationDTO (its return shapes), plus theUserNotificationIdentifierTypealias (INotificationInboxUIService.cs:26). - Concept introduced, the Result pattern carried all the way to the component.
[Rubric §18, UI Architecture & Component Design]assesses whether components talk to typed services rather than rawHttpClient; components depend on this interface, not on the HTTP implementation, so a bell or an inbox page can be tested against a stub. The sharper point is the return shape: every member isTask<Result...>, so a caller can tell a real answer apart from a failure without catching anything (INotificationInboxUIService.cs:6-10). See the primer's Result section for the pattern itself; this is where it crosses the presentation boundary.[Rubric §24, Forms, Validation & UX Safety]shows in the unread-count doc (lines 16-21), which defines what a failure means to a caller: the count could not be established (expired session, transient failure) and must be treated as "unknown". Callers leave the displayed count untouched, because reporting zero would erase a badge that a real-time push had just incremented. That is a contract-level statement about UI behavior, not just about data.[Rubric §9, API & Contract Design]shows in the paged signature: the inbox is fetched a page at a time with sane defaults, never as one unbounded dump.
- Walkthrough: four members (
INotificationInboxUIService.cs:13-29).GetInboxAsync(pageNumber = 1, pageSize = 20, cancellationToken)returns aResult<PagedCollectionResult<UserNotificationDTO>>(line 14);GetUnreadCountAsyncreturnsResult<int>(line 23);MarkReadAsync(id, ct)(line 26) andMarkAllReadAsync(ct)(line 29) are the two mutations, both returning a bare Result. - Why it's built this way: a thin interface at the presentation edge keeps components decoupled from transport and makes the inbox mockable in bUnit tests. Note the contract deliberately says nothing about scoping: the scope key is resolved inside the implementation through INotificationScopeProvider, so adding scoping did not change this interface or any caller.
- Where it's used: implemented by NotificationInboxService; consumed by NotificationBell (for the unread count) and the NotificationInbox page.
IPushNotificationUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/IPushNotificationUIService.cs:10· Level 3 · interface
- What it is: the UI-side contract for admin push operations: broadcast a notification and read paginated send history, both returning a Result.
- Depends on: Result, PagedCollectionResult<T>, PushNotificationDTO, and SendPushNotificationRequest.
- Concept reinforced: the same Result-returning UI-service abstraction as
INotificationInboxUIService (
[Rubric §18, UI Architecture & Component Design]), with the same "errors are values the API described, not exceptions the caller catches" rule stated in the doc (IPushNotificationUIService.cs:6-9). The difference is audience: this is the organizer/admin surface (send plus history), not the per-user inbox, and splitting the two keeps each page's dependency surface minimal. - Walkthrough: two members (
IPushNotificationUIService.cs:12-16).SendAsync(SendPushNotificationRequest, ct)returnsResult<PushNotificationDTO>for the created notification (line 13);GetHistoryAsync(pageNumber = 1, pageSize = 10, ct)returnsResult<PagedCollectionResult<PushNotificationDTO>>(line 16). - Why it's built this way: separating the admin contract from the inbox contract lets an app that never sends notifications avoid taking a dependency on the send path at all, and keeps the two registrations independent.
- Where it's used: implemented by PushNotificationService; consumed by the admin pages NotificationList and NotificationSend.
NotificationInboxService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NotificationInboxService.cs:29· Level 4 · class (sealed)
- What it is: the HTTP implementation of the inbox contract. It calls the
notifications/inboxWebAPI resource for paged retrieval, unread count, and the two mark-read operations, stamping every scopeable request with the application's current scope key and giving the two reads exactly one token renewal and replay when the API answers401. - Depends on: AuthenticatedServiceBase (its base, supplying
CreateAuthenticatedClientAsync,CreateClientWithToken, the shared staticRetryPolicy,StorageRenewsRejectedTokensandReadRenewedAccessTokenAsync), INotificationInboxUIService (the contract it implements), ITokenStorageService (and, through the base, ISessionAwareTokenStorage, the storage that renews a refused token), AuthDelegatingHandler (the client pipeline handler that has already made the renewal a 401 earns on such a storage), INotificationScopeProvider, ITokenRefresher (optional, defaulted to null, the fallback for a storage without that capability), HttpResultExecutor (turns a thrown transport failure into a failed Result), ProblemDetailsResultReader (turns the response into a Result carrying the API's ownProblemDetailserrors), PagedCollectionResult<T>, and UserNotificationDTO. Externals:IHttpClientFactory,System.Net.HttpStatusCode,CultureInfo.InvariantCulture. - Concept introduced, a typed HTTP UI service over a non-CRUD resource.
[Rubric §18, UI Architecture & Component Design]assesses UI-to-API access through typed services. This is a sibling of EntityServiceBase<TEntityDTO, TIdentifierType> for a resource whose verbs are read and mark rather than create/update/delete, so it inherits only the authenticated-client half. Every method has the same three-layer shape:HttpResultExecutor.ExecuteAsyncon the outside (exceptions become failed Results; the four public methods are expression-bodied and return thatTaskdirectly rather than wrapping it inasync/await, lines 42-115), the sharedRetryPolicyin the middle, andProblemDetailsResultReader.ReadAsyncat the end (a non-success response becomes the failure the API described).- The 401 renew-and-replay, and why only reads get it.
SendReadWithAuthRefreshAsync(lines 129-156) is the interesting mechanism: a badge poll or an inbox load that lands on an access token the server has already rejected gets one token renewal and one replay, instead of surfacing as an empty inbox or a blanked badge (lines 17-21). The doc states the constraint that makes it safe (lines 122-123): only the reads use it, because they are safe to replay, whereas a mark-read PUT gets no token refresh after a 401 (it still runs under the shared retry policy).ReplayTokenAsync(lines 169-177) holds the cost to exactly ONE renewal per 401: when the storage renews refused tokens, the API client's AuthDelegatingHandler has already renewed (and ended the session if the renewal was refused), so forcing a refresh here would be a second rotation for the same 401 (doc lines 158-165).[Rubric §29, Resilience & Business Continuity]is the category;[Rubric §11, Security]is the reason it is bounded, one attempt, no loop. - A failure is "unknown", deliberately not zero. The comment on the unread count (lines 73-75)
records the defect this shape fixed: reporting zero let a rejected token or a transient failure
erase a badge that a real-time push had just incremented. Now the failure travels as a failed
Result and the caller keeps the displayed count.
[Rubric §24, Forms, Validation & UX Safety]covers this class of "what does the UI show when the read failed" decision. [Rubric §30, Compliance, Privacy & Data Governance]shows in the scope query: the scope is what keeps a bulk mark-read from silently clearing notifications the user is not currently looking at.
- The 401 renew-and-replay, and why only reads get it.
- Walkthrough:
- A primary constructor forwards
IHttpClientFactoryand ITokenStorageService to AuthenticatedServiceBase and keepsscopeProviderand the optionaltokenRefresher(NotificationInboxService.cs:29-34);Endpointis the constant"notifications/inbox"(line 36);_refreshSyncand_refreshInFlight(lines 38-39) hold the single-flight token refresh. The refresher's default ofnullis documented as the graceful-degradation path: a host that registers none simply skips the retry, and the read reports failure rather than a fabricated empty result (lines 25-28). ScopeQueryAsync(separator, ct)(lines 249-256) is the shared helper: it asks INotificationScopeProvider for the current key and returns either an empty string (leaving the request byte-identical to the pre-scope one, lines 242-243) or{separator}scope={Uri.EscapeDataString(scopeKey)}(line 255). The separator parameter is"&"for a URL that already carries query parameters and"?"for one that does not (lines 245-247).GetInboxAsync(lines 42-60) resolves the scope with"&"(line 49), builds an invariant-culture relative URL (lines 50-52), sends throughSendReadWithAuthRefreshAsync(lines 54-55), and reads aResult<PagedCollectionResult<UserNotificationDTO>>(lines 57-58).GetUnreadCountAsync(lines 63-78) resolves the scope with"?"(line 67), goes through the same read path, and reads aResult<int>(line 76).MarkReadAsync(lines 81-97) PUTs to{Endpoint}/{id}/read(line 88) on a plain authenticated client. It is the one method that sends no scope: the id already identifies a single notification.MarkAllReadAsync(lines 100-115) PUTs to{Endpoint}/read-allwith the scope query (lines 104-106), so a bulk operation is bounded by the same filter the list was read under.- Both mutations pass the
cancellationTokeninto the retry policy as well as the request (lines 90-93, 108-111), and the comment says why: without it an abandoned mark-read sleeps out its full backoff budget instead of aborting. SendReadWithAuthRefreshAsync(lines 129-156) runs the send under the retry policy inside ausingfor the first client, recording the bearer that client carried assentToken(lines 135-139, line 137), returns the response untouched when it is not a401(lines 141-144), and otherwise asksReplayTokenAsyncfor a token (line 146). Anullanswer returns the original401(lines 147-150); a token disposes the first response and replays on a client built with it (lines 152-155). The doc notes the response content is fully buffered before the send task completes, which is what makes it legal to read the body after the client that produced it is disposed (lines 123-125).ReplayTokenAsync(rejectedToken, ct)(lines 169-177) chooses where the replay token comes from. WhenStorageRenewsRejectedTokensis true (the token storage is an ISessionAwareTokenStorage,MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:106) it returnsReadRenewedAccessTokenAsync(rejectedToken)(lines 171-174), which reads what the storage holds now and yieldsnullwhen no bearer was sent, the refused renewal ended the session, or the storage still holds the refused token (AuthenticatedServiceBase.cs:114-127). Only otherwise does it fall back toTryAcquireRefreshedTokenAsync, and only when a refresher is registered; with none it answersnull(line 176).TryAcquireRefreshedTokenAsync(lines 192-225) is single-flight, with the same shape as the token storage's hydrate: two reads that both land on a rejected token (the bell poll and the inbox page share this scoped instance) share one rotation, because on MAUI a second rotation presenting the same refresh token is read as reuse and revokes the whole session (BR-206; remarks at lines 183-190). Under_refreshSyncit startsAcquireRefreshedTokenAsynconly when no refresh is in flight or the stored one has completed (lines 199-207), underCancellationToken.Noneso one caller giving up cannot cancel the refresh another is awaiting (comment at lines 194-197). Each caller stops waiting on its own token viaWaitAsync(line 211), and thefinallyclears only its own finished task, so a still-running or newer refresh is not dropped (lines 213-224). The residual is stated in the remarks: it does not coordinate with the storage's own expiry-driven hydrate (lines 187-189).AcquireRefreshedTokenAsync(lines 227-239) forces one re-acquisition and returnsnullfor a blank token or when JS interop is unavailable during SSR prerender (lines 232-238), which is a "no refresh is possible here", not an error.
- A primary constructor forwards
- Why it's built this way: inheriting from AuthenticatedServiceBase
removes per-method boilerplate for auth and retry, and wrapping every body in
HttpResultExecutor means no method has to hand-write a try/catch to honor the
Result-returning contract. Routing the scope through a provider (rather than a parameter on every
call) is what keeps the UI contract unchanged while the inbox, badge and mark-all agree on one slice
(
NotificationInboxService.cs:11-16). - Where it's used: registered against
INotificationInboxUIService as scoped by
AddNotificationUI()(MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/DependencyInjection.cs:30); consumed by NotificationBell and the NotificationInbox page.
ChannelSubscription
MMCA.Common.UI ·
MMCA.Common.UI.Services.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NotificationHubService.cs:921· Level 2 · class (private, sealed, nested)
- What it is: the disposable handle returned when a caller subscribes to a live channel on NotificationHubService; disposing it removes the handler from the channel's subscriber list.
- Depends on: its owning NotificationHubService (a back-reference), a
channel-key string, and a
Func<string, string, Task>handler; implementsIDisposable. - Concept introduced, subscription-as-token. This is the classic "return an
IDisposableto unsubscribe" pattern. Instead of exposing anUnsubscribe(handler)method (which forces callers to hold and match the exact delegate),OnChannelEventreturns aChannelSubscription; when the component disposes it, the subscription calls back into the owner to unregister itself.[Rubric §1, SOLID]shows in the encapsulation: only the hub service can construct one, and only it knows how to remove one, so the bookkeeping has a single owner. - Walkthrough: a primary-constructor nested class capturing
owner,channelKeyandhandler(NotificationHubService.cs:921), exposingChannelKey(line 414) andHandler(line 416) as get-only properties.Dispose()(line 418) simply callsowner.RemoveSubscription(this), which takes the shared_channelSynclock, removes the entry, and prunes the channel's list once it empties (lines 373-386). TheHandlerproperty is whatDispatchChannelEventAsyncinvokes on each delivery (line 339). - Why it's built this way: nesting it privately inside
NotificationHubService keeps subscription bookkeeping fully encapsulated,
and the
IDisposableshape lets Blazor components tie unsubscription to their own lifetime. - Where it's used: constructed and returned by
NotificationHubService
.OnChannelEvent(line 260); disposed by the component that subscribed. - Caveats / not-in-source: disposing a subscription unregisters the handler only. It does not
release a channel join: those are counted separately by
ChannelReferenceCounter, and the source states the pairing requirement
explicitly (
NotificationHubService.cs:374-375).
ConnectionRestoredSubscription
MMCA.Common.UI ·
MMCA.Common.UI.Services.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NotificationHubService.cs:930· Level 4 · class (private, sealed, nested)
- What it is: the disposable handle returned when a caller subscribes to the "connection restored" signal of NotificationHubService; disposing it removes the handler from the service's restored-handler list.
- Depends on: its owning NotificationHubService (a back-reference) and
a
Func<Task>handler; implementsIDisposable. - Concept reinforced, subscription-as-token. It is the same "return an
IDisposableto unsubscribe" shape as ChannelSubscription, applied to a signal that has no channel key.OnConnectionRestoredreturns it instead of exposing a C# event, and the source says why (NotificationHubService.cs:437-438): a method lets the service await each handler, where an event handler would escape asasync void.[Rubric §1, SOLID]shows in the encapsulation: only the hub service constructs one, and only it knows how to remove one. - Walkthrough: a primary-constructor nested class capturing
ownerandhandler(NotificationHubService.cs:930), exposingHandleras a get-only property (line 911).Dispose()(line 913) callsowner.RemoveConnectionRestoredSubscription(this), which removes the entry under the shared_channelSynclock (lines 814-820). TheHandlerproperty is whatRaiseConnectionRestoredAsyncawaits, one handler at a time, each in its own guard (lines 791-812). - Why it's built this way: nesting it privately inside
NotificationHubService keeps the handler list fully encapsulated, and the
IDisposableshape lets a Blazor component or a channel helper tie unsubscription to its own lifetime. - Where it's used: constructed and returned by
NotificationHubService
.OnConnectionRestored(lines 427-438); the ADC LiveChannelSubscription holds one for its resync callback (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/SessionLive/LiveChannelSubscription.cs:59).
NotificationHubService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NotificationHubService.cs:45· Level 6 · class (sealed, partial)
- What it is: the client-side SignalR connection manager. It opens a connection to
/hubs/notificationsafter login, invokes a callback for received notifications (after an optional per-notification filter), and carries the ephemeral live-channel events that components join and subscribe to. - Depends on: ApiSettings (for the hub URL, via
IOptions<ApiSettings>, readingSameOriginApiEndpointfirst andApiEndpointsecond), ITokenStorageService (for the bearer token on a direct connection); AuthDelegatingHandler (its staticReportRejectedAsync, which renews a bearer the hub refused with 401); UnboundedReconnectPolicy (the reconnect schedule and the auth-refusal test); ChannelReferenceCounter (membership counting), ChannelSubscription (its channel subscription handle) and ConnectionRestoredSubscription (its restored-signal handle). Externals:Microsoft.AspNetCore.SignalR.Client(HubConnection,HubConnectionBuilder),Microsoft.AspNetCore.Http.Connections.Client(HttpConnectionOptions),ClientWebSocket,ILogger<T>with[LoggerMessage]source generation,System.Threading.Lock,SemaphoreSlimandCancellationTokenSource; implementsIAsyncDisposable. - Concept introduced, resilient client-side real-time with re-joinable channels and a lifetime.
[Rubric §6, CQRS & Event-Driven]extends to the browser here: the server pushes notifications and channel events over SignalR instead of the client polling for everything.[Rubric §29, Resilience & Business Continuity]shows in nine distinct mechanisms, each with its rationale in source:- the initial connect retries with exponential backoff up to
MaxRetries = 3starting atInitialRetryDelayof 2 seconds and doubling (lines 47, 125, 269-323), so a token-not-yet-ready or API-still-starting race recovers; WithAutomaticReconnect(new UnboundedReconnectPolicy(() => JitterSample()))(line 222) keeps long sessions alive for as long as the service lives, never giving up and waiting at most 30 seconds between attempts, and because SignalR group membership does not survive a new connection,ReconnectedrunsRejoinAndRaiseAsync(line 242, lines 792-801), which re-joins every held channel (RejoinChannelsAsync, lines 838-868);- if the connection still closes with an error (the server refused the reconnect),
ClosedrunsRestartAfterCloseAsync(line 247, lines 705-754): a loop that repeats the serialized start, with a doubling backoff capped atMaxRetryDelay(line 131, defaulting toUnboundedReconnectPolicy.MaxDelay; the cap is applied at line 752), until one connects, so live notifications do not stay dead for the rest of the session. AClosedwith a null error is a deliberate stop or dispose and is never restarted (line 247; class doc lines 32-43); - every one of those waits is jittered through
UnboundedReconnectPolicy
.Jitterwith samples fromJitterSample(line 139, doc lines 134-138): the automatic reconnect through the policy (line 222), the start retry (lines 318-320) and the restart backoff (lines 744-746), so clients dropped by one event do not retry in lockstep against the recovering replica. The logged delay is the jittered one; - a restored-connection signal tells subscribers to re-read what they show live, because SignalR
delivers nothing that was sent while the connection was down.
OnConnectionRestored(lines 442-453) registers a handler that runs once per restored connection, after the channel rejoin was attempted (even if a join failed), on both the automatic reconnect path and the restart that follows a close, and never for the first successful start of a connection or after a stop (doc lines 430-439). The reconnect path always signals unless the lifetime ended during the rejoin (lines 796-800); the restart loop signals only for a connection that is reallyConnected, and only whenInterlocked.Exchangeon the_restoredConnectionlatch (line 77) shows no one signalled it yet, so overlapping loops report one restored connection once and aReconnectingone is left to theReconnectedhandler (lines 730-742); - a lifetime token ends every start and restart loop on
StopAsyncorDisposeAsync._lifetime(line 73) is canceled and replaced byStopCoreAsync(lines 489-535); each loop runs under the token it began in and re-checksIsLifetimeOver(line 756) under_startSyncbefore building or starting a connection, so nothing begun before a stop connects after it, and the cancellation also cuts short the backoff delays and an in-flight connect (DelayUnlessStoppedAsync, lines 553-563); - a refused authentication (401 or 403) ends both the automatic reconnect and the restart loop: the
start loop logs
LogAuthenticationRefused, discards the connection and returnsfalse(lines 298-305), whichRestartAfterCloseAsyncreads as "stop" (lines 725-728). The nextStartAsynctries again. On a direct connection a 401 handshake that carried a bearer is first handed toReportRefusedHandshakeAsync(lines 684-687, called at line 661), which gives it to AuthDelegatingHandler.ReportRejectedAsyncfor ONE renewal; a refused renewal ends the session, so a locked or revoked user's shell signs out instead of keeping a hub that only reconnects into 401s. A 403, or a handshake with no bearer, changes nothing (doc lines 674-680); - a terminal start failure discards the connection object (
DiscardUnstartedConnectionAsync, lines 694-703) instead of leaving it in the field, because a connection that never started must not satisfy the guard inStartCoreAsync, or every laterStartAsync(including one reached throughJoinChannelAsync) would no-op forever (comment at lines 311-313). The guard itself only leaves a connected, connecting or reconnecting connection alone (line 257); aDisconnectedone is discarded and rebuilt (lines 262-265); - a channel join the hub refused, or one that hit a transient hub error, is retried by the next
join of the same key, not only by the next reconnect: the join is counted before the connection
starts and never rolled back, and the server is invoked while
ChannelReferenceCounter
.NeedsServerJoinreports the key held but unconfirmed (lines 348-352), withMarkJoinedrecorded only after the invoke succeeds (line 357); StartAsyncis serialized by aSemaphoreSlim(line 61), since two components callingJoinChannelAsyncat once on Blazor Server (which has no single synchronization context) could both see a null connection, both build one, and leak the loser socket with duplicate server registrations (doc lines 152-157).[Rubric §13, Observability & Operability]applies too: every outcome is a source-generated structured log (lines 885-919, includingLogReconnectExhaustedat line 895,LogRestartRetryingat line 898 andLogConnectionRestoredHandlerFailedat line 919), and failures on the channel and restored-handler paths are logged, never thrown.
- the initial connect retries with exponential backoff up to
- Walkthrough:
- Constants and fields: the four hub method names (lines 48-51),
_sameOriginProxyEndpoint(line 54),_channelSyncguarding the subscription dictionary and the restored-handler list (line 56),_lifetimeSyncguarding the lifetime swap (line 57),_startSyncguarding start (line 61, aSemaphoreSlimrather than aLockbecause the guarded body awaits, lines 59-60), the ChannelReferenceCounter (line 63),_channelSubscriptionsmapping a channel key to its handler list (line 64),_connectionRestoredSubscriptionsholding the ConnectionRestoredSubscription handles (line 65), and the_restoredConnectionlatch naming the connection a restored signal was last raised for (lines 75-77). NotificationCallback(line 83) is a settableFunc<string, string, Task>?the host assigns to surface a snackbar.NotificationFilter(line 91) is an optionalFunc<IReadOnlyDictionary<string, string>?, Task<bool>>consulted with the notification's live metadata (null for an unscoped send) before the callback runs;falsedrops the notification for this client, which is how the listener leaves another scope's notifications out of the toast and the badge.IsConnected(line 119) reports the connection state;InitialRetryDelay(line 125) andMaxRetryDelay(line 131) areinternaland settable so a test can exercise the terminal-failure path and the unbounded restart loop without waiting out the real backoff;JitterSample(line 139) is theinternalsettableFunc<double>(defaultRandom.Shared.NextDouble) every reconnect, start-retry and restart delay is jittered with, so a test can pin the schedule;ConnectionFactory(line 146) is aninternaltest-only hook that replaces theHubConnectionBuildercall so a test can supply a connection over an in-memory transport, and is null in production.- The constructor (lines 93-110) null-checks the options (line 100), records
ApiSettings.SameOriginApiEndpoint(line 106), and builds_hubUrlfrom that endpoint, falling back toApiSettings.ApiEndpointand throwing when neither is set (line 107), trimmed of its trailing slash plus/hubs/notifications(line 109). That path is hardcoded: the comment at line 108 names it as the default PushNotificationSettings.HubPath(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:25), whose doc states that this client has no setting to follow a move, so a host that changes the server path must also change the client, the gateway route,RateLimiting:HubPathPrefixesand the same-origin proxy exemption (PushNotificationSettings.cs:17-23).UsesSameOriginProxy(line 116) reports which path was taken. The same-origin path serves a WebAssembly client of an opted-in host: the hub is reached through the UI host's/apiproxy, which attaches the bearer from the HttpOnly session cookie on the WebSocket upgrade (the only request, since negotiation is skipped), so the connection carries no client-held token (comment at lines 102-105). StartAsync(lines 160-168) bails when disposed and otherwise callsStartForLifetimeAsyncwith the current lifetime token (CurrentLifetime, lines 537-551).StartForLifetimeAsync(lines 178-216) returnstruewhen the lifetime is over, waits on_startSyncwith the lifetime token (toleratingObjectDisposedExceptionandOperationCanceledException, both treated as "nothing left to start"), re-checks the lifetime under the gate, runsStartCoreAsync, and releases in afinallythat tolerates the disposal race. Itsboolresult isfalseonly when the server refused authentication.BuildConnection(lifetime)(lines 218-250) builds theHubConnectionfromConnectionFactorywhen set or from aHubConnectionBuilderconfigured byConfigureConnectionwith the unbounded reconnect policy fed byJitterSample(lines 220-223). It registersReceiveNotification, which appliesNotificationFilterand thenNotificationCallback(lines 225-236), andReceiveChannelEventtoDispatchChannelEventAsync(line 238), wires the reconnect re-join and restored signal throughRejoinAndRaiseAsync(line 242) and the close-with-error restart bound to this connection's lifetime (line 247).StartCoreAsync(lifetime)(lines 252-327) returnstrueimmediately unless the existing connection is null orDisconnected(line 257), discards a dead one (lines 262-265), builds a connection (line 267), then runs the retry loop: each attempt first checks the lifetime (lines 272-276), starts the connection under the lifetime token (line 280), and on success replays any channel joins requested before the connection came up (line 284). It raises no restored signal: a first start is not a restoration. A failure while the lifetime is over is not a failure (lines 291-296); a refused authentication returnsfalse(lines 298-305); the last attempt logs and discards (lines 307-316); any earlier attempt waits a jittered delay and doubles the base (lines 318-321).ConfigureConnection(options)(lines 588-606) applies the transport options. Both modes skip negotiation and use WebSockets only (lines 592-593): negotiate and connect are separate requests, and behind a non-sticky ingress with several hub replicas the connect can land on a replica that never issued the connection id, so WebSockets are required and there is no Server-Sent Events or long-polling fallback (doc lines 566-571). Through the same-origin proxy it returns early, sending no token and no extra header (lines 595-598). On a direct gateway connection it bindsAccessTokenProvidertoITokenStorageService.GetAccessTokenAsync(line 600) and, outside the browser, installsConnectWebSocketAsyncas the socket factory (lines 602-605).ConnectWebSocketAsync(lines 632-672) opens aClientWebSocket, copies the configured headers and the bearer, and connects. The bearer is held in a local declared before thetry(line 635) so the refusal path can still see it. When the server answered the upgrade with a non-101 status it first awaitsReportRefusedHandshakeAsync(statusCode, accessToken)(line 661), then rethrows anHttpRequestExceptioncarrying that status (lines 655-666), which is what letsUnboundedReconnectPolicy.IsAuthenticationRefusedrecognise a 401 or 403; a bareWebSocketExceptionwould not carry it.ReportRefusedHandshakeAsync(lines 684-687) isinternal: only a401with a non-empty bearer callsAuthDelegatingHandler.ReportRejectedAsync(accessToken, _tokenStorageService); anything else returns a completed task.JoinChannelAsync(channelKey)(lines 339-367) counts the join before starting the connection so the replay insideStartAsyncsees it (lines 343-346), then invokes the serverJoinChannelonly when connected and while the key is held but not confirmed joined on this connection (NeedsServerJoin, line 352), and recordsMarkJoinedonce the invoke succeeds (line 357). That is normally the first join; a later join of a key whose first join the hub refused invokes again, while a key the start's rejoin replay just joined is skipped (comment at lines 348-350). A failure is logged, and the next join of the key or the next reconnect retries it (line 360).LeaveChannelAsync(channelKey)(lines 378-399) is the mirror: it invokesLeaveChannelonly whenReleasereports the last outstanding leave (lines 382-398).RejoinChannelsAsync(lines 838-868) first callsResetJoined(line 842), because a new or restored connection holds no server group membership, then snapshots the distinct held keys (line 845) and, when connected, invokesJoinChannelfor each, marking each confirmed join (line 858) and logging each failure without stopping the rest.OnChannelEvent(channelKey, handler)(lines 410-428) creates a ChannelSubscription and appends it to the channel's handler list under the lock, returning the subscription as the unsubscribe token. Subscribing deliberately does not join the channel; the doc says to callJoinChannelAsyncas well (lines 404-405).OnConnectionRestored(handler)(lines 442-453) null-checks the handler, creates a ConnectionRestoredSubscription and adds it to_connectionRestoredSubscriptionsunder_channelSync, returning it as the unsubscribe token.RaiseConnectionRestoredAsync(lines 807-828) snapshots that list under the lock (line 812) and awaits each handler one after another, logging a failure throughLogConnectionRestoredHandlerFailedso one throwing handler neither stops the others nor reaches the connection callback that raised the signal (lines 821-826).DispatchChannelEventAsync(lines 758-785) snapshots the subscriber list under the lock (line 768), then invokes each handler in isolation, logging (never rethrowing) a failure so one bad subscriber cannot starve the rest (lines 772-784).StopAsync(line 463) is a no-op once disposed and otherwise callsStopCoreAsync(lines 489-535), which swaps in a freshCancellationTokenSourceunder_lifetimeSync, cancels and disposes the ended one, then takes_startSyncso no start can build anything after the stop returns, disposes and clears the connection, and clears the_restoredConnectionlatch (line 522).DisposeAsync(lines 466-487) sets_disposed, stops, disposes the semaphore, and cancels and disposes the final lifetime. The comment at lines 476-477 records why that is safe: the stop already canceled any start in flight and waited for it to release the gate.RestartAfterCloseAsyncalso checks the lifetime first (lines 707-710), so a close during teardown starts nothing.
- Constants and fields: the four hub method names (lines 48-51),
- Why it's built this way: sealed and scoped per circuit, because a connection and its channel
membership are per-user-session. Best-effort semantics (join, leave and handler failures are logged,
not thrown) match the reality that live updates are a convenience layered over the authoritative API,
not a correctness guarantee, and isolating handler invocations protects the fan-out. Binding every
start and restart to a lifetime token is what makes an unbounded retry safe: without it a loop that
never gives up could outlive a logout or a disposed circuit. The restored signal exists because a
rejoin restores membership but not the events missed while down, so a live page has to re-read once
per restoration, and the latch keeps that to exactly once when the reconnect handler and a restart
loop both see the same connection. Jittering every wait matters because an unbounded schedule shared
by every client would otherwise turn one replica restart into synchronized retry waves, and tracking
confirmed joins separately from the count keeps a refused first join recoverable without a reconnect.
The overall shape is the client half of
ADR-039, with push notifications
themselves covered by
ADR-024. Choosing the transport
once in the constructor, and keeping the token-or-no-token decision in
ConfigureConnection, is what lets the same service run either directly against the gateway or behind the same-origin API proxy of ADR-131 without a client-held token. - Where it's used: registered as a scoped service by
AddNotificationUI()(MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/DependencyInjection.cs:36); started after login and stopped on logout; its notification callback drives NotificationState and MudBlazor snackbars, and its channel API is what LiveEventListener and the HappeningNow page use. LiveChannelSubscription subscribes toOnConnectionRestoredfor its resync callback (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/SessionLive/LiveChannelSubscription.cs:59). The server side is NotificationHub.
PushNotificationService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/PushNotificationService.cs:15· Level 5 · class (sealed)
- What it is: the HTTP implementation of the admin push contract: send a notification and read
paginated send history against the
notificationsWebAPI resource, stamping a send with the application's current scope key when the caller did not name one. - Depends on:
EntityServiceBase<TEntityDTO, TIdentifierType>
(its base, typed on
PushNotificationDTO/PushNotificationIdentifierType, which suppliesEndpointand the Result-returningSendRequestAsync), IPushNotificationUIService (the contract), ITokenStorageService, INotificationScopeProvider, Result, PagedCollectionResult<T>, PushNotificationDTO, and SendPushNotificationRequest. - Concept reinforced, the base-class HTTP service pattern at its cleanest
(
[Rubric §18, UI Architecture & Component Design]). Where NotificationInboxService hand-builds each request because its resource is not CRUD-shaped, this one leans on EntityServiceBase'sSendRequestAsync, so each method reduces to one send that already returns a Result.[Rubric §9, API & Contract Design]appears in the scope precedence rule: an explicit caller choice outranks the ambient one, which is the difference between a default and an override. - Walkthrough:
- The primary constructor passes the resource name
"notifications"plus the factory and token service to EntityServiceBase and keepsscopeProvider(PushNotificationService.cs:15-21). SendAsync(request, ct)(lines 23-52) null-guards the request (line 28), then applies scoping conditionally: a request that already carries aScopeKeyis sent unchanged, and only an unscoped one picks up the ambient key via arecord withexpression (lines 32-40, rationale at lines 30-31). It then POSTs throughSendRequestAsync<PushNotificationDTO>with a freshidempotencyKey: NewIdempotencyKey()(lines 45-51). The send is retried on a transient failure, so without a key an attempt that reached the server before failing would broadcast twice; the key rides on every attempt so the[Idempotent]endpoint collapses the duplicate (comment at lines 42-44).NewIdempotencyKey()is a GUID inNformat (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:65), and the base sets it as a default header on the one client that serves every retry attempt (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:236-243).GetHistoryAsync(pageNumber = 1, pageSize = 10, ct)(lines 54-64, a non-asyncmethod that returns theSendRequestAsynctask directly) builds an invariant-culturepageNumber/pageSizequery (line 60) and sends a GET through the same helper (lines 61-63), with no idempotency key since a read is safe to repeat. Note it does not send a scope: history is the admin's full send log.
- The primary constructor passes the resource name
- Why it's built this way: delegating transport, auth, retry and error translation to
EntityServiceBase keeps this class down to two short
methods, matching the framework's "UI services are typed HTTP clients, never raw
HttpClient" convention. Reading the scope through the same INotificationScopeProvider the inbox service uses is what makes a send and the reads that follow it resolve to one scope (PushNotificationService.cs:9-14); the wire-levelScopeKeyon the request is recorded in ADR-024. - Where it's used: registered against
IPushNotificationUIService as scoped by
AddNotificationUI()(MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/DependencyInjection.cs:27); injected into the admin pages NotificationList and NotificationSend. - Caveats / not-in-source:
SendAsyncdoes not readGetCurrentScopeDisplayNameAsync; that member exists for the send page's caption and is consumed by NotificationSend directly (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Notifications/NotificationSend.razor.cs:78), not by this service.
IUserPreferenceWriter
MMCA.Common.UI ·
MMCA.Common.UI.Services.Preferences·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/IUserPreferenceWriter.cs:9· Level 0 · interface
- What it is: the write half of cross-device UI preferences. It persists the signed-in user's culture and theme choice to the backend so the choice follows them to their next browser or device.
- Depends on: nothing. Implemented by ApiUserPreferenceWriter; the read half is IUserPreferenceReader.
- Concept introduced, best-effort persistence over a local source of truth.
[Rubric §19, State Management & Data Flow]assesses where state lives and which copy wins; the doc comment (IUserPreferenceWriter.cs:3-8) answers both. The cookie and localStorage remain the runtime channel, this interface is a roaming convenience, and a failed or skipped persist must never break the in-page switch. Implementations must no-op for anonymous users. Anullfield means "leave unchanged" (IUserPreferenceWriter.cs:11-13), which is what lets the theme toggle and the culture switcher share one method without either clobbering the other's value. - Walkthrough
SaveAsync(string? culture, string? theme, CancellationToken cancellationToken = default)(IUserPreferenceWriter.cs:18). Both value arguments are nullable by design, per the null-means-unchanged rule stated atIUserPreferenceWriter.cs:15-16.
- Why it's built this way:
ADR-027 and
ADR-028. Keeping it an interface is
what lets a host with no
auth/preferencesendpoint (the Helpdesk seed is the named example atApiUserPreferenceWriter.cs:11-12) simply not register it: the callers resolve it withGetService<T>and skip the persist when it is absent. - Where it's used: the theme toggle resolves it optionally and saves only the theme
(
MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/ThemeToggle.razor:23-27); the culture switcher does the same for culture before handing off to the applier (CultureSwitcher.razor:38-42).
OfflineWriteOptions
MMCA.Common.UI ·
MMCA.Common.UI.Services.Offline·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteOptions.cs:4· Level 0 · record (sealed)
- What it is: the optional per-write settings a caller passes to
IOfflineWriteQueue
.EnqueueAsync: the idempotency key, the row version the write was based on, and a coalesce key. - Depends on: nothing first-party at compile time; its values are copied onto PendingWrite.
- Concept introduced: nothing new here; the queue it configures is taught under
OfflineWriteQueue.
[Rubric §29, Resilience & Business Continuity]applies in the small: the idempotency key is what makes a replayed write safe to send twice. - Walkthrough
IdempotencyKey(OfflineWriteOptions.cs:7):nullmeans the queue generates a new GUID in"N"form (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteQueue.cs:151).BasedOnRowVersion(OfflineWriteOptions.cs:11), abyte[]?carrying the EF rowversion in its wire shape, with aCA1819suppression justified as the same exemption DTOs get (line 10). The replay sends it asIf-Matchthrough PendingWrite.IfMatch.CoalesceKey(OfflineWriteOptions.cs:14): pairs writes that cancel each other out, used byIOfflineWriteQueue.CancelPendingAsync.
- Why it's built this way: an options record with
initmembers keepsEnqueueAsyncto one optional parameter, so a caller that needs none of the three passes nothing. ADR-144 (Website/docs-src/adr/144-offline-writes-and-delta-reads.md) records the offline-write design. - Where it's used: ADC's SessionBookmarkUIService
sets
IdempotencyKeyandCoalesceKeyfor a create and onlyCoalesceKeyfor a delete (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/Bookmarks/SessionBookmarkUIService.cs:202,207).
OfflineWriteOutcome
MMCA.Common.UI ·
MMCA.Common.UI.Services.Offline·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteOutcome.cs:4· Level 0 · enum
- What it is: how a queued offline write left the queue:
Completed,Conflict,RejectedorExpired(OfflineWriteOutcome.cs:7,10,13,16). - Depends on: nothing.
- Concept introduced: nothing new; it is the vocabulary of the settle step taught under OfflineWriteQueue.
- Walkthrough
Completed: the replay succeeded.Conflict: the server refused because the item changed (for example a 412).Rejected: any other permanent refusal.Expired: the write was older than OfflineWriteQueueOptions.MaxAgeand was discarded unsent.- There is deliberately no "transient" member: a transient failure keeps the write queued, so it never
settles. The queue's private
ClassifyreturnsOfflineWriteOutcome?and usesnullfor that case (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteQueue.cs:263).
- Why it's built this way: an
Expiredwrite has no handler result at all (OfflineWriteSettledEventArgs.Resultisnullfor it), so a bare Result could not describe every way a write leaves the queue; the enum names each terminal state for the subscriber. See ADR-144. - Where it's used: carried by OfflineWriteSettledEventArgs, which
Common's
OfflineWriteNotifiercomponent subscribes to (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Capabilities/OfflineWriteNotifier.razor:46) and by ADC's bookmark replay tests.
OfflineWriteQueueOptions
MMCA.Common.UI ·
MMCA.Common.UI.Services.Offline·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteQueueOptions.cs:4· Level 0 · class (sealed)
- What it is: the options-pattern settings of OfflineWriteQueue: where the queue is stored, how old a write may get, and how many writes it holds.
- Depends on: nothing first-party; bound through
Microsoft.Extensions.Options. - Concept introduced: nothing new.
[Rubric §29, Resilience & Business Continuity]applies: theMaxAgedefault is tied to the server's idempotency window, so the queue never replays a write the server could no longer deduplicate. - Walkthrough
StorageKey(OfflineWriteQueueOptions.cs:7), default"mmca.offline-writes": the single local store key the whole queue lives under.MaxAge(OfflineWriteQueueOptions.cs:14), defaultTimeSpan.FromHours(24). The doc comment (lines 9-13) states the reason: 24 hours is the window in which the server replays an idempotency key, so an older write could otherwise run twice. Older writes settle as OfflineWriteOutcome.Expired.MaxPendingWrites(OfflineWriteQueueOptions.cs:17), default200: beyond it an enqueue fails withOfflineWrites.QueueFull(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteQueue.cs:163,187).
- Why it's built this way: mutable
setproperties soAddOfflineWriteQueue(configure)can apply anAction<OfflineWriteQueueOptions>(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:420-429). See ADR-144. - Where it's used: injected as
IOptions<OfflineWriteQueueOptions>into OfflineWriteQueue (OfflineWriteQueue.cs:96); configured by DependencyInjection.
UserPreferences
MMCA.Common.UI ·
MMCA.Common.UI.Services.Preferences·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/UserPreferences.cs:9· Level 0 · record (sealed)
- What it is: the two-field result of reading a user's stored UI preferences, their culture and their theme.
- Depends on: nothing. Returned by IUserPreferenceReader and its implementation ApiUserPreferenceReader.
- Concept introduced: nothing new. It reuses the null-means-unset convention introduced by
IUserPreferenceWriter: the doc comment (
UserPreferences.cs:3-6) states that anullfield means the user never chose that preference, so the request default or the OS preference applies.[Rubric §19, State Management & Data Flow]applies in the small, because "no stored value" and "stored value that happens to be the default" stay distinguishable, which is what lets the login reconciliation skip a redundant culture round-trip. - Walkthrough
- A positional record with two members,
CultureandTheme, bothstring?(UserPreferences.cs:9). There is no factory and no validation: the values are whatever the backend returned.
- A positional record with two members,
- Why it's built this way: a positional record is the smallest thing that deserializes cleanly from
the
auth/preferencespayload and compares by value. - Where it's used: returned by ApiUserPreferenceReader, including its
static
Emptyinstance (ApiUserPreferenceReader.cs:26); consumed by the login page's preference reconciliation (Login.razor:228-247).
UserPreferencesRequest
MMCA.Common.UI ·
MMCA.Common.UI.Services.Preferences·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/ApiUserPreferenceWriter.cs:36· Level 0 · record (private sealed, nested)
- What it is: the request body the writer PUTs to
auth/preferences, the same culture and theme pair in the write direction. - Depends on: nothing. It is declared inside ApiUserPreferenceWriter and used only there.
- Concept introduced: nothing new; it is the wire-facing twin of
UserPreferences.
[Rubric §9, API & Contract Design]applies in the small: the request type is kept separate from the response type even though the two currently have identical members, so the directions can diverge without a breaking change, and it is declaredprivateso it never becomes part of the package's public surface. - Walkthrough
private sealed record UserPreferencesRequest(string? Culture, string? Theme)(ApiUserPreferenceWriter.cs:36). It is instantiated once, inline in thePutAsJsonAsynccall (ApiUserPreferenceWriter.cs:100).
- Why it's built this way: nesting it privately keeps a serialization detail from leaking into the package API, and a positional record needs no mapper.
- Where it's used: only in
ApiUserPreferenceWriter.SaveAsync(ApiUserPreferenceWriter.cs:98-101).
IUserPreferenceReader
MMCA.Common.UI ·
MMCA.Common.UI.Services.Preferences·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/IUserPreferenceReader.cs:9· Level 1 · interface
- What it is: the read half of cross-device preferences. It fetches the signed-in user's stored culture and theme, used at login to reapply a returning user's choices on a new device.
- Depends on: UserPreferences (its return type); implemented by ApiUserPreferenceReader. The write half is IUserPreferenceWriter.
- Concept introduced: nothing new; it mirrors the best-effort contract the writer introduced. The
doc comment (
IUserPreferenceReader.cs:3-8) pins the failure mode: implementations return an emptyUserPreferences(both fields null) for anonymous users or on any error, so a failed read never blocks login.[Rubric §19, State Management & Data Flow]applies, since this is the moment the roaming copy is reconciled against the local one. - Walkthrough
GetAsync(CancellationToken cancellationToken = default)returningTask<UserPreferences>(IUserPreferenceReader.cs:13). There is no failure channel in the signature at all, which is the contract making itself unmistakable.
- Why it's built this way:
ADR-027 and
ADR-028. A
Result<T>here would invite a caller to surface an error the user cannot act on during a login they just completed successfully. - Where it's used: injected by the login page (
Login.razor:14) and read once inApplyStoredPreferencesAndNavigateAsync(Login.razor:228-230), which applies the theme through ThemeService (Login.razor:232-235) and the culture through ICultureApplier (Login.razor:243), skipping the culture round-trip when the stored value already matches the current one (Login.razor:237-238).
PendingWrite
MMCA.Common.UI ·
MMCA.Common.UI.Services.Offline·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/PendingWrite.cs:22· Level 1 · record (sealed)
- What it is: one entry of the offline write queue, exactly as it is persisted to the device's local store: what to replay, with which payload, for which user, and how often it has failed.
- Depends on: ConcurrencyETag (formats
IfMatch, line 47);System.Text.Json(JsonSerializerOptions.Web,[JsonIgnore]). - Concept introduced: nothing new beyond the queue taught under
OfflineWriteQueue.
[Rubric §19, State Management & Data Flow]applies: the record is the durable state, so everything a later replay needs (including the user it belongs to) travels inside it rather than in memory. - Walkthrough
- Identity and routing:
Id(PendingWrite.cs:25) andKind(line 18), the handler key, for exampleEngagement.Bookmark.Create.v1. - Replay safety:
IdempotencyKey(line 21) so a write the server already ran is not run twice, andBasedOnRowVersion(line 25), abyte[]?with aCA1819suppression justified by the record being persisted locally, not a domain type (line 24). - Payload:
PayloadJson(line 28), serialized withJsonSerializerOptions.Web, and the genericReadPayload<TPayload>()(line 52) that deserializes it with the same options. - Scoping and bookkeeping:
CoalesceKey(line 31),UserScope(line 34, the signed-in user's id ornullfor an anonymous user),EnqueuedOn(line 37) andAttempts(line 40), the count of transient replay failures so far. IfMatch(line 47) is computed, not stored ([JsonIgnore], line 46): the weak ETag ofBasedOnRowVersionviaConcurrencyETag.Format, ornullwhen no row version was given.
- Identity and routing:
- Why it's built this way:
required+initmembers keep an entry immutable; the queue changesAttemptswith awithexpression (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteQueue.cs:545-557). Storing the payload as JSON text keeps the list one homogeneous type in the local store whatever the payload type. See ADR-144. - Where it's used: built by
OfflineWriteQueue.EnqueueAsync(OfflineWriteQueue.cs:147), handed to every IOfflineWriteHandler, and carried by OfflineWriteSettledEventArgs. ADC's BookmarkCreateReplayHandler and BookmarkDeleteReplayHandler read it.
ReplayVerdict
MMCA.Common.UI ·
MMCA.Common.UI.Services.Offline·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteQueue.cs:418· Level 1 · record struct (private, readonly, nested in OfflineWriteQueue)
- What it is: the private answer to "what does this pass do with this entry now that its handler
answered".
Classifyreturns one per handler result: settle the entry with an outcome, or keep it with one more attempt and either stop the pass or go on to the next entry (doc comment,OfflineWriteQueue.cs:411-417). - Depends on: OfflineWriteOutcome.
- Concept introduced: nothing new; the replay pass that consumes it is taught under OfflineWriteQueue.
- Walkthrough
- Two positional members (
OfflineWriteQueue.cs:418):Outcome, anOfflineWriteOutcome?whosenullmeans "keep the entry", andStopsPass, which only matters for a kept entry. - Three named constructors carry every legal combination:
KeepAndStop(line 421,nulloutcome, stops the pass),KeepAndContinue(line 424,nulloutcome, the pass goes on) andSettle(outcome)(line 427, an outcome, never stops).
- Two positional members (
- Why it's built this way: the pass has three moves, not two. A bare nullable outcome can say
"settle" or "keep", but not whether a kept entry should also stop the pass (a failure every later
write would meet too) or let the pass continue (an unexpected error about this write only). A
readonly record structadds the second bit without an allocation per entry, and the factories keep a settled verdict from ever claiming to stop the pass. - Where it's used: only inside OfflineWriteQueue:
Classifybuilds it (OfflineWriteQueue.cs:276-301) andReplayPassAsyncacts on it (lines 391-405). Nothing outside the defining file sees it.
IOfflineWriteHandler
MMCA.Common.UI ·
MMCA.Common.UI.Services.Offline·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/IOfflineWriteHandler.cs:9· Level 3 · interface
- What it is: the per-kind replay strategy. A module registers one handler per write kind; the queue hands it a PendingWrite and gets back the server's answer.
- Depends on: PendingWrite, Result.
- Concept introduced: nothing new; the queue that drives it is taught under
OfflineWriteQueue.
[Rubric §1, SOLID]applies: the framework queue knows no endpoint, and each module adds a write kind by adding a handler, not by editing the queue. - Walkthrough
Kind(IOfflineWriteHandler.cs:12): the key the handler answers to, for exampleEngagement.Bookmark.Create.v1.ReplayAsync(PendingWrite, CancellationToken)returningTask<Result>(line 25). The doc comment (lines 14-21) fixes the contract: send the write with itsIdempotencyKey(andIfMatchwhen set), and report the answer as aResult. A transport failure, a timeout, or an unavailable, too-many-requests or unauthorized error keeps the write for a later replay and ends the pass; an unexpected error keeps it and the pass goes on to the next write; a commit with an unknown outcome (CommitOutcomeUnknown), a conflict or any other failure discards it.
- Why it's built this way: returning a
Resultrather than an outcome lets a handler reuse the normal HTTP-to-Resultpath, and the queue alone decides what is kept, what stops the pass and what settles (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteQueue.cs:276-310). - Where it's used: registered with
AddOfflineWriteHandler<THandler>()as a scopedTryAddEnumerableentry (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:440-443); implemented in ADC by BookmarkCreateReplayHandler (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/Bookmarks/BookmarkCreateReplayHandler.cs:24) and BookmarkDeleteReplayHandler (BookmarkDeleteReplayHandler.cs:19). - Caveats: when two handlers share a
Kind, the first one registered wins (OfflineWriteQueue.cs:111usesTryAdd).
OfflineWriteSettledEventArgs
MMCA.Common.UI ·
MMCA.Common.UI.Services.Offline·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteSettledEventArgs.cs:9· Level 3 · class (sealed)
- What it is: the payload of
IOfflineWriteQueue.WriteSettled: which write left the queue, how, and with what handler result. - Depends on: PendingWrite, OfflineWriteOutcome,
Result; derives from
EventArgs. - Concept introduced: nothing new.
- Walkthrough: a primary-constructor class (
OfflineWriteSettledEventArgs.cs:9) exposingWrite(line 12),Outcome(line 15) andResult(line 18), which isnullfor OfflineWriteOutcome.Expiredbecause an expired write is never sent. - Why it's built this way: the standard
EventHandler<TEventArgs>shape, raised byOfflineWriteQueue.SettleAsynconly after the store no longer holds the write (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteQueue.cs:499-543). - Where it's used: Common's
OfflineWriteNotifier(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Capabilities/OfflineWriteNotifier.razor:46) and ADC'sSessionBookmarkReplayTests.
IOfflineWriteQueue
MMCA.Common.UI ·
MMCA.Common.UI.Services.Offline·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/IOfflineWriteQueue.cs:11· Level 4 · interface
- What it is: the contract of the opt-in durable offline write queue: queue a write now, replay it when the device is back online, and tell subscribers how each write settled.
- Depends on: PendingWrite, OfflineWriteOptions, OfflineWriteSettledEventArgs, Result.
- Concept introduced: the queue itself is taught under OfflineWriteQueue; this
is its surface.
[Rubric §29, Resilience & Business Continuity]applies: the interface lets a UI service accept a write while offline instead of failing it. - Walkthrough
IsAvailable(IOfflineWriteQueue.cs:18): false only with the defaultNullLocalCacheStore; a host that callsAddBrowserDeviceCapabilities(Blazor Server and WebAssembly) or the MAUI capabilities has a store (doc comment, lines 13-17). See NullLocalCacheStore.- Two events:
WriteSettled(line 21), raised once per write that left by a replay after the store no longer holds it, andPendingChanged(line 24), raised after every persisted change. EnqueueAsync<TPayload>(kind, payload, options, cancellationToken)(line 33) returnsResult<PendingWrite>: the queued write, or theOfflineWrites.Unavailable/OfflineWrites.QueueFullfailure (doc, line 32).GetPendingAsync(line 38) lists the current user's writes oldest first;CancelPendingAsync(coalesceKey)(line 44) removes every write of the current user with that key (ordinal) without raisingWriteSettled.ReplayAsync(line 52) returns the number of writes that settled, and does nothing (returns 0) when the store is unavailable, the device is offline, or another replay is running (lines 46-49).
- Why it's built this way: ADR-144 (
Website/docs-src/adr/144-offline-writes-and-delta-reads.md). Failures a caller can act on (no store, queue full) come back as aResult; replay outcomes, which arrive later, come back as events. - Where it's used: registered scoped by
AddOfflineWriteQueue(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:422), which no framework code calls (doc comment, line 425); injected into ADC's SessionBookmarkUIService (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/Bookmarks/SessionBookmarkUIService.cs:40) and drained by Common'sOfflineWriteNotifier(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Capabilities/OfflineWriteNotifier.razor:54).
OfflineWriteQueue
MMCA.Common.UI ·
MMCA.Common.UI.Services.Offline·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteQueue.cs:58· Level 5 · class (sealed, partial)
- What it is: the default IOfflineWriteQueue. It keeps the whole queue as one
List<PendingWrite>under one key of the device's ILocalCacheStore, scoped per signed-in user, and replays it through per-kind IOfflineWriteHandlers on reconnect, on demand, and on its own backoff timer. - Depends on: ILocalCacheStore,
IConnectivityStatusService,
IOfflineWriteHandler, OfflineWriteQueueOptions,
PendingWrite, OfflineWriteOutcome,
ReplayVerdict (nested), HttpResultExecutor (its transport and
timeout error codes), CommitOutcomeUnknown,
Error and ErrorType.
Externals:
AuthenticationStateProvider,TimeProvider,IOptions<T>,ILogger<T>,System.Text.Json. - Concept introduced, a durable client-side outbox for writes. A write the user makes while offline
is persisted on the device with an idempotency key, then replayed in order once the device is online.
It is the client-side counterpart of the server outbox idea (ADR-003): durability first, delivery later,
and idempotency so a delivery that happens twice is harmless.
[Rubric §29, Resilience & Business Continuity]assesses whether the system degrades gracefully when a dependency is down; here a lost network becomes a delayed write rather than a failed one.[Rubric §19, State Management & Data Flow]applies because the queue's state is the device store, re-read on every change rather than cached.[Rubric §13, Observability & Operability]applies through the four[LoggerMessage]warnings (OfflineWriteQueue.cs:664-674). - Walkthrough
- Retry timing constants:
InitialRetryDelay5 seconds (OfflineWriteQueue.cs:61) andMaxRetryDelay5 minutes (line 64). Fields include an ordinal handler dictionary (line 68), aSemaphoreSlim(1, 1)_gate(line 73) for store edits, and aLock_scheduleSync(line 74) for the timer. - The constructor (line 90) indexes handlers by
KindwithTryAdd, so the first registered wins (line 111), and subscribes toConnectivityChanged(line 114).IsAvailableis the store's own flag (line 124). EnqueueAsync(line 133) fails with anError.UnexpectedcodedOfflineWrites.Unavailablewhen there is no store (lines 143-144), builds the PendingWrite (line 147, a new"N"GUID when no idempotency key was given, line 151, and the current user asUserScope), and adds it throughMutateAsyncunlessMaxPendingWritesis reached (line 163), else anError.TooManyRequestscodedOfflineWrites.QueueFull(lines 186-187). When the kind has a handler it bumps_replayableEnqueuesand schedules a retry (lines 173-182).GetPendingAsync(line 191) andCancelPendingAsync(line 204) filter by the current user's scope;InScope(line 265) orders oldest first.ReplayAsync(line 222) returns 0 unless the store is available, the device is online and no other replay holds theInterlocked.CompareExchangeflag (line 224). Itsfinallyalways callsCompletePass(line 242), so a pass that threw still schedules the next attempt.ReplayPassAsync(line 331) walks a snapshot: it skips an entry that left the store since the snapshot (line 346, so a write cancelled meanwhile is not sent), expires one older thanMaxAgeunsent (line 351), keeps an entry whose kind has no handler in this app (line 358), and otherwise calls the handler (line 367). A thrown handler exception is logged and counts an attempt (lines 377-378); a transport throw (IsTransportThrow, line 319:HttpRequestExceptionorIOException) stops the pass (lines 379-382), and any other throw keeps the entry and goes on (lines 387-388). AResultgoes throughClassify(line 391): a settle verdict removes the entry (lines 392-397); otherwise the entry counts an attempt (line 399) and either stops the pass (lines 400-403) or is marked kept while the pass continues (line 405). The pass returns(settled, kept)(line 408), so a kept entry still owes a retry.Classify(line 276) returns a ReplayVerdict, and its order is the contract (doc comment, lines 270-275): success settles asCompleted(line 280); a CommitOutcomeUnknown result settles asRejectedbefore anything could keep it (lines 283-286), because the write may already be durable and a resend would run it again (remarks, lines 34-38); an error thatStopsThePasskeeps the entry and stops (lines 288-291); anErrorType.Unexpectedkeeps it and continues (lines 293-296); anything else settles asConflictfor anErrorType.Conflict, otherwiseRejected(lines 298-300).StopsThePass(line 307) is the transport or timeout code ofHttpResultExecutor, orErrorType.Unavailable,TooManyRequestsorUnauthorized(line 310): a failure every later write would meet too.- Backoff:
CompletePass(line 436) resets the delay to the initial value after a pass that settled something and otherwise doubles it viaNextDelay(line 322) up to the 5-minute cap, reschedules when a replayable write was queued during the pass, and cancels the timer otherwise.ScheduleRetryLocked(line 458) keeps at most one one-shot timer on the injectedTimeProvider, and never while offline or disposed; a per-schedule token object letsOnRetryTimer(line 480) ignore a stale callback. - Persistence:
MutateAsync(line 564) re-reads the list, applies the edit and writes it back under the semaphore, then raisesPendingChanged;SettleAsync(line 499) removes the entry and then raisesWriteSettled;CountAttemptAsync(line 545) bumpsAttempts. Both events go out throughRaiseWriteSettled(line 510) andRaisePendingChanged(line 528), which invoke one subscriber at a time, log a throwing one throughLogSubscriberFailed(line 668) and carry on, so a faulty subscriber cannot end a pass after its entry already left the store. OnConnectivityChanged(line 616) cancels the timer when the device goes offline and starts a background replay, not awaited, when it comes back;ReplayInBackgroundAsync(line 637) catches and logs every fault so no unobserved task escapes.Dispose(line 248) removes the timer and unsubscribes.
- Retry timing constants:
- Why it's built this way: ADR-144 (
Website/docs-src/adr/144-offline-writes-and-delta-reads.md). One list under one key with a read-edit-write under one semaphore means concurrent callers of the same instance never lose a write; the class remarks say plainly that two instances over one store (two tabs, two circuits) are not coordinated (OfflineWriteQueue.cs:15-21). Splitting "keep and stop" from "keep and continue" means a connection-level failure does not spend the writes behind it, while one write the server keeps failing never holds the others back; nothing is discarded by attempt count, andMaxAgebounds a kept write (remarks, lines 27-34). User scoping means one device can hold writes for several accounts, and signing out clears the local store and the queue with it (remarks, line 55). - Where it's used: registered scoped, together with
TimeProvider.Systemand the options, byAddOfflineWriteQueue(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:420-429); exercised byOfflineWriteQueueTestsandOfflineWriteQueueRetryTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Offline/) and by ADC's bookmark tests. ADC's SessionBookmarkUIService is the one consumer. - Caveats: the scope is "scoped" because the browser connectivity service and store it reads are
scoped (
DependencyInjection.cs:410-411), so each Blazor Server circuit has its own queue instance over the same browser store, which is exactly the uncoordinated two-instances case the remarks name.
ApiUserPreferenceReader
MMCA.Common.UI ·
MMCA.Common.UI.Services.Preferences·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/ApiUserPreferenceReader.cs:22· Level 6 · class (sealed)
- What it is: the default IUserPreferenceReader. It GETs
auth/preferenceswith the signed-in user's bearer token and hands back the culture and theme the user chose on some other device, or empty preferences when there is nothing to read. - Depends on: IUserPreferenceReader (the contract,
ApiUserPreferenceReader.cs:24), UserPreferences (the two-nullable-field record it returns, constructed at line 26), ITokenStorageService (primary-constructor parameter, line 24), JwtTokenInfo (the freshness check and its shared skew, line 36);IHttpClientFactoryandSystem.Net.Http.Json(BCL) for the named"APIClient". - Concept introduced, a best-effort read that cannot fail its caller.
[Rubric §6, CQRS & Event-Driven Design]assesses whether a secondary concern is prevented from changing the outcome of the primary operation. Applying a stored preference is a nicety attached to login; a network hiccup while reading it must not turn a successful sign-in into an error page. This class encodes that as a type-level promise:GetAsyncreturnsUserPreferencesrather than a Result, and there is no path out of it that reports a failure. That is the posture ADR-096 records for side effects generally (Website/docs-src/adr/096-best-effort-side-effects.md), applied on the read side.[Rubric §26, Front-End Security]also applies, in a small but real way: the class refuses to spend a round trip on a token it can already see is stale. - Walkthrough
- One static carries the class's own configuration:
Emptyis a single sharednew UserPreferences(null, null)(line 26), so the failure paths allocate nothing. The expiry skew is not a local copy: the guard passesJwtTokenInfo.DefaultExpirySkew, the one 30-second margin the token storages also apply (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/JwtTokenInfo.cs:24), so the reader and the layer that does the refreshing cannot disagree about when a token is still usable. GetAsync(CancellationToken)(line 29) reads the access token (line 31) and gates onJwtTokenInfo.IsFresh(token, JwtTokenInfo.DefaultExpirySkew)(line 36). The comment (lines 33-35) spells out the two cases this covers: an expired or unreadable token buys a guaranteed 401, andIsFreshalso covers the anonymous (null) case. Both returnEmpty(line 38).- The request is built by hand: resolve the named
"APIClient"(line 43), which already carries the culture and auth handlers (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:180-181), then anHttpRequestMessageGET to the relative URIauth/preferenceswith the token it already read set as theAuthorization: Bearerheader on that request (lines 44-45). The reader sets it itself because in Blazor ServerAuthDelegatingHandlerresolves in a separate DI scope whose token store is empty, which would send the read anonymous; the handler leaves an existing header alone, so WASM and MAUI see no change (class doc comment). Before sending it callsAuthDelegatingHandler.TrackTokenOwner(token!, tokenStorageService)(line 49, the helper atMMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthDelegatingHandler.cs:82); the comment (lines 47-48) explains that the handler's own storage is another instance, so it is told which storage this bearer came from and a 401 renews (or ends) this session.SendAsync(line 50) is followed by a non-success short-circuit toEmpty(lines 51-54), and only thenReadFromJsonAsync<UserPreferences>(line 56). - Null-coalescing on the deserialized value (line 57) means a body of literal
nullis the same as no preference. - Two catch blocks,
HttpRequestException(line 59) andTaskCanceledException(line 63), both returnEmpty. Note what is not caught: anything else, including aJsonExceptionfrom a malformed body, still escapes, so a contract break is loud while a transport failure is quiet.
- One static carries the class's own configuration:
- Why it's built this way: ADR-027 (
Website/docs-src/adr/027-multi-locale-i18n.md) and ADR-028 make the stored culture and theme a per-user server-side value so the choice follows a user between devices, and login is the one moment where reading it is worth a round trip. Catching narrowly and returning a shared empty record is what makes the reconciliation safe to await unconditionally in the login flow. It is the read half of a pair: ApiUserPreferenceWriter is the write half, and the two are registered together (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:248-249). - Where it's used: registered by
AddUISharedwithTryAddScoped(DependencyInjection.cs:249) and injected by exactly one page, the framework's login page (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor:19). ItsApplyStoredPreferencesAndNavigateAsync(Login.razor:387) callsGetAsync, applies a stored theme through ThemeService, and, when the stored culture differs from the current one, hands the rest of the navigation to ICultureApplier, which owns the head-specific switch. - Caveats: the reader is pinned by
ApiUserPreferenceReaderTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Preferences/ApiUserPreferenceReaderTests.cs) andServerSignInPreferenceReadTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Services/ServerSignInPreferenceReadTests.cs), alongside its sibling writer's ApiUserPreferenceWriterTests. BecauseTaskCanceledExceptionis caught unconditionally, a caller that cancels its own token receivesEmptyrather than anOperationCanceledException, which is the opposite of the convention HttpResultExecutor enforces elsewhere in this package; the single caller passes no token (Login.razor:389), so the difference is invisible in current use.
ApiUserPreferenceWriter
MMCA.Common.UI ·
MMCA.Common.UI.Services.Preferences·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/ApiUserPreferenceWriter.cs:30· Level 6 · class (sealed)
- What it is: the default IUserPreferenceWriter. It PUTs the
culture/theme choice to
auth/preferencesthrough the shared"APIClient", and it declines to make the call at all when the request is already known to be doomed. - Depends on: IUserPreferenceWriter (implemented),
ITokenStorageService, JwtTokenInfo and the nested
UserPreferencesRequest. Externals:
IHttpClientFactoryandSystem.Net.Http.Json. - Concept introduced, best-effort writes still have a cost.
[Rubric §13, Observability & Operability]assesses whether the system's own traffic keeps its signals meaningful; the class comment (ApiUserPreferenceWriter.cs:21-26) makes the argument explicitly. Because the caller never learns the write failed, a doomed request cannot help the user and still lands in failed-request telemetry, and at low traffic one 401 per theme or culture toggle is enough on its own to trip a failed-request alert rule. Both guards below therefore exist for the alerting story, not the user's story.[Rubric §11, Security]also touches this: the writer never inspects the token's claims itself: it asksJwtTokenInfowhether one is usable, then attaches it as theAuthorization: Bearerheader of the request message (ApiUserPreferenceWriter.cs:110), the same explicit per-request bearer the reader attaches. - Walkthrough
- The primary constructor takes
IHttpClientFactoryandITokenStorageService(ApiUserPreferenceWriter.cs:30-32)._rejectedToken(ApiUserPreferenceWriter.cs:44) holds the token the API last refused, for the lifetime of this scoped writer. - Saves are serialized in call order.
SaveAsync(ApiUserPreferenceWriter.cs:63) is notasync: under aSystem.Threading.Lockgate (ApiUserPreferenceWriter.cs:34,65) it chains the new save onto_lastSave(ApiUserPreferenceWriter.cs:47), stores the new task as the latest, and returns it (ApiUserPreferenceWriter.cs:67-69). The remarks (ApiUserPreferenceWriter.cs:56-62) give the reason: a theme toggle followed quickly by a language switch used to send two concurrent PUTs, and the switcher force-reloads as soon as its own save returns, so the reload either cut off the theme PUT (WASM) or the two raced on the user row's concurrency token and the server kept the old theme. Serializing means the switcher's existing await also drains the earlier save. SaveAfterAsync(ApiUserPreferenceWriter.cs:73) waits for the previous save withWaitAsync(PreviousSaveWait, cancellationToken)underConfigureAwaitOptions.SuppressThrowing(ApiUserPreferenceWriter.cs:77-78), so a fault, timeout or cancellation of the earlier save only ends the wait (comment,ApiUserPreferenceWriter.cs:75-76).PreviousSaveWaitis aninternalinit property defaulting to 5 seconds (ApiUserPreferenceWriter.cs:53), bounded so a hung earlier request delays the next save, and the culture reload behind it, by a few seconds at most (ApiUserPreferenceWriter.cs:49-52). It then callsPutAsync(ApiUserPreferenceWriter.cs:80).PutAsync(ApiUserPreferenceWriter.cs:83) reads the access token (ApiUserPreferenceWriter.cs:85), then applies guard one:JwtTokenInfo.IsFresh(token, JwtTokenInfo.DefaultExpirySkew)(ApiUserPreferenceWriter.cs:90, the helper atMMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/JwtTokenInfo.cs:44). The skew is the shared 30-secondDefaultExpirySkew(JwtTokenInfo.cs:24), documented as the one margin every token storage and every direct bearer reader applies, so the storages and the preference calls can never disagree about when a token is still usable. The comment (ApiUserPreferenceWriter.cs:87-89) notes thatIsFreshalso covers null and unreadable tokens, which makes this the anonymous-user guard as well.- Guard two compares the current token against
_rejectedTokenwithStringComparison.Ordinal(ApiUserPreferenceWriter.cs:98); the comment (ApiUserPreferenceWriter.cs:95-97) explains why expiry alone is not enough, since a token can be unexpired and still rejected (revoked session, rotated signing key, a user the API now treats as gone). - The call itself is a hand-built PUT
HttpRequestMessagewith a JSON body, sent throughSendAsync, to the relativeauth/preferences(ApiUserPreferenceWriter.cs:105-115), and a401 Unauthorizedlatches_rejectedToken(ApiUserPreferenceWriter.cs:117-120). Just beforeSendAsyncit callsAuthDelegatingHandler.TrackTokenOwner(token!, tokenStorageService)(ApiUserPreferenceWriter.cs:114, the helper atMMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthDelegatingHandler.cs:82). The comment (ApiUserPreferenceWriter.cs:112-113) gives the reason: the handler's own token storage is a different instance, so it is told which storage this bearer came from, and a 401 then renews (or ends) this session rather than the handler's. The helper records the owner weakly and only when it is an ISessionAwareTokenStorage (AuthDelegatingHandler.cs:84), so AuthDelegatingHandler can route the 401; the comment namesCreateAuthenticatedClientAsyncas the path that already does the same. - Both
HttpRequestException(ApiUserPreferenceWriter.cs:122) andTaskCanceledException(ApiUserPreferenceWriter.cs:126) are swallowed, each with a comment noting that the cookie already holds the choice for this device.
- The primary constructor takes
- Why it's built this way:
ADR-027 and
ADR-028 make the local cookie the
runtime channel and this write a roaming extra. Storing the rejected token rather than setting a
boolean latch is the deliberate detail (
ApiUserPreferenceWriter.cs:38-43): a fresh sign-in produces a different token, so writing resumes with no reset step and no staleness of its own. - Where it's used: registered with
TryAddScopedin DependencyInjection (MMCA.Common.UI/DependencyInjection.cs:248); resolved optionally by the theme toggle (ThemeToggle.razor:23-27) and the culture switcher (CultureSwitcher.razor:38-42). Pinned byApiUserPreferenceWriterTests, including the ordering and the bounded wait (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Preferences/ApiUserPreferenceWriterTests.cs:146,173).
BrandColors
MMCA.Common.UI ·
MMCA.Common.UI.Theme·MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/BrandColors.cs:10· Level 0 · class (static)
- What it is: the single C# source of truth for every hex value in the theme. It holds the two brand triads (primary and secondary), the app-chrome colors shared by both modes, and the full light and dark palettes, so every hex value MMCATheme assigns in either MudBlazor variant is one of these constants (doc comment,
MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/BrandColors.cs:4-5). - Depends on: nothing first-party. Part of it is mirrored by CSS custom properties in
wwwroot/app.css; the doc comments name--mmca-primary,--mmca-primary-dark,--mmca-primary-light,--mmca-secondary,--mmca-secondary-dark(BrandColors.cs:12,15,18,22,28), plus--mmca-sidebar-bgonChromeBackground(line 36) and--mmca-divideronLightDivider(line 80). - Concept introduced, a fitness-tested duplication.
[Rubric §20, Design System & Theming]assesses whether visual tokens are centralized rather than scattered as literals; here the whole palette lives in exactly one C# class, and the theme carries no hex literal of its own.[Rubric §34, Architecture Governance & Documentation]assesses whether necessary duplication is monitored: C# cannot read CSS at build time, so the brand colors must exist in bothBrandColorsandapp.css, andBrandColorTokenTestsin MMCA.Common.UI.Tests asserts the two stay in sync so the copy cannot silently drift (BrandColors.cs:6-8). The test pins the five brand tokens, oneInlineDatarow each (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Theme/BrandColorTokenTests.cs:35-39); the--mmca-sidebar-bgand--mmca-dividermirrors are named in the doc comments but have no row there.[Rubric §21, Accessibility]lands here rather than only in the theme: theSecondaryconstant carries its own contrast math in source, Teal 700#00796Bholding about 5.3:1 on light surfaces, replacing the Teal 600#00897Bthat measured about 4.0:1 and sat under the WCAG 2.1 AA 4.5:1 floor for normal text (BrandColors.cs:21-26). The contrast reasoning forLightWarningandDarkErroris deliberately not here: their summaries point at MMCATheme, where the math sits beside the assignment (lines 56, 116, 122).
- Walkthrough:
public const stringfields in four commented groups.- The primary triad:
Primary = "#1565C0"(line 13),PrimaryDark = "#0D47A1"(line 16),PrimaryLight = "#42A5F5"used for accents and dark-mode contrast (line 19). The secondary triad:Secondary = "#00796B"(line 26, with the contrast rationale immediately above it at lines 21-25),SecondaryDark = "#00695C"(line 29), andSecondaryLight = "#4DB6AC"(line 32). - Shared chrome, identical in both palettes (line 34):
ChromeBackground = "#1A2035"for the app bar and sidebar (line 37),ChromeText = "#FFFFFF"(line 40), andChromeTextMuted = "#FFFFFFB3", white at 70% alpha for sidebar text and icons (line 43). - The light palette (lines 45-84):
LightTertiaryPurple 700,LightInfoBlue 700,LightSuccessGreen 800,LightWarning = "#A85D00"withLightWarningContrastText = "#FFFFFF",LightErrorRed 800, thenLightBackground = "#FAFBFC",LightSurface, the two text tones,LightActionDefault, and the two dividers. - The dark palette (lines 86-154):
DarkPrimaryLightenBlue 200,DarkPrimaryDarken = "#1E88E5"(Blue 600, the hover, focus and active fill of a filled primary control, whose dark label still reaches 5.14:1 on it, line 96),DarkSecondaryDarken = "#00897B"(Teal 600, the same value the lightSecondarywas moved off for contrast, line 99),DarkSecondaryLighten,DarkTertiary,DarkInfo,DarkSuccess,DarkWarningOrange 400,DarkError = "#FF8A80"(line 117), then the four state fillsDarkInfoDarken = "#64B5F6"(Blue 300, line 124),DarkSuccessDarken = "#81C784"(line 127),DarkWarningDarken = "#FFB74D"(line 130) andDarkErrorDarken = "#EF9A9A"(line 133), each the text colour of a text or outlined alert and the hover, focus and active fill of the matching filled control, thenDarkBackground = "#1A2027",DarkSurface = "#27303A", text, action and divider tones. NoteDarkInfoandPrimaryLightshare#42A5F5, andDarkTextSecondaryandDarkActionDefaultshare#B0BEC5: each keeps its own name so a role can change without dragging the other.
- The primary triad:
- Why it's built this way:
constrather thanstatic readonlymeans the values can appear in contexts that require compile-time constants; the governance is the fitness test, not the language keyword. Keeping every palette value in one class means a rebrand or a contrast fix touches one file plus the mirrored CSS, and the theme reads as a mapping of roles to names rather than a wall of hex. - Where it's used: every palette entry of MMCATheme that is not an
rgba(...)literal (MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/MMCATheme.cs:18-54,60-139);BrandColorTokenTests; the doc comment ofBrandColorTokenTestsBase, the per-host stylesheet check that consumer repos subclass (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Ui/BrandColorTokenTestsBase.cs:6-13); any component that references a brand color programmatically.
IInitialThemeModeSource
MMCA.Common.UI ·
MMCA.Common.UI.Theme·MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/IInitialThemeModeSource.cs:16· Level 0 · interface
- What it is: an optional hook that lets a head tell the theme providers the stored Day/Dark mode without JavaScript, so the first render already has the right palette instead of light-then-dark (ADR-028). Its one member,
bool? IsDarkMode(line 21), istruefor dark,falsefor light, andnullwhen nothing is stored yet, which leaves the first render unchanged. - Depends on: nothing.
- Concept introduced, an optional capability probed with
GetService.[Rubric §20, Design System, Theming & UI Consistency]covers theming that works from the first paint. The provider asks the container for the interface and treats absence andnullidentically (MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/MmcaThemeProviders.razor:43-50), so web heads register nothing and still behave as before, while the JS path inOnAfterRenderAsyncstays the source of truth for them. - Why it's built this way: the MAUI head can read its stored mode synchronously from device preferences, which a Blazor circuit cannot do with a cookie before the first render. A nullable bool keeps "unknown" distinct from "light".
- Where it's used: implemented by
MauiInitialThemeModeSource(MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/Theme/MauiInitialThemeModeSource.cs:12) and registered as a singleton (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/DependencyInjection.cs:91); consumed byMmcaThemeProviders.razor:47; pinned byMmcaThemeProvidersInitialModeTests.
TwoFactorPageRequirement
MMCA.Common.UI ·
MMCA.Common.UI.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/TwoFactor/TwoFactorPageRequirement.cs:14· Level 0 · class (internal sealed)
- What it is: the authorization requirement behind the policy the two-factor account page declares
instead of a bare
[Authorize]. Its one member is the policy name,PolicyName = "mmca:two-factor-pages"(TwoFactorPageRequirement.cs:17). - Depends on:
Microsoft.AspNetCore.Authorization.IAuthorizationRequirement(ASP.NET Core). The doc comment names TwoFactorPageGate and TwoFactorPageAuthorizationHandler (TwoFactorPageRequirement.cs:5-13). - Concept introduced: none new. This is the two-factor copy of the "signed in, unless the page is
hidden for this host" policy first taught at NotificationPageRequirement;
the doc comment says the notification pages' policy follows the same rule (
TwoFactorPageRequirement.cs:10-11).[Rubric §25, Navigation & IA]assesses whether a route answers consistently with what the host actually offers: a host that never registered the two-factor UI answers the page with a 404 rather than a sign-in challenge for a page that does not exist for it (TwoFactorPageRequirement.cs:6-10). - Walkthrough: a marker class with no state; the requirement means "an authenticated caller, exactly
as
[Authorize]asks, except when the host never calledAddTwoFactorUI(), in which case every caller passes" (TwoFactorPageRequirement.cs:6-9). The decision itself lives in TwoFactorPageAuthorizationHandler. - Why it's built this way: authorization runs before the router, so a plain
[Authorize]would send an anonymous visitor of a host without the feature to sign-in for a page that will then 404. Letting the request through to the router hands the answer to TwoFactorPageGate. - Where it's used:
AddUISharedregisters the policy unconditionally, so the page's attribute resolves in every host (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:95-101); the TwoFactorAccount page references it with[Authorize(Policy = TwoFactorPageRequirement.PolicyName)](MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/TwoFactor/TwoFactorAccount.razor:4). Pinned byTwoFactorRoutesTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/TwoFactor/TwoFactorRoutesTests.cs:26).
ThemeInterop
MMCA.Common.UI ·
MMCA.Common.UI.Theme·MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/ThemeInterop.cs:9· Level 1 · class (internal static)
- What it is: a one-method guard,
TryAsync(Func<Task>)(ThemeInterop.cs:18), that runs a best-effort JS interop call and returnsfalseinstead of throwing when it fails. - Depends on: JsInteropFailure, whose
IsUnavailablepredicate is the whole catch filter (ThemeInterop.cs:25;MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/JsInteropFailure.cs:27). - Concept introduced, theme interop failure must not escape the component lifecycle.
[Rubric §18, UI Architecture & Component Design]covers resilient component lifecycles. The filter delegates to the shared JsInteropFailure set rather than listing exception types itself, so it catches the same four cases every best-effort interop caller in the UI tolerates: interop is unavailable on this renderer (InvalidOperationException: SSR prerender, a render-mode transition, a disposed dispatcher), the circuit was torn down mid-call (JSDisconnectedException), the asset is missing or the browser call failed (JSException), and the call outlived the host's JS interop timeout or its token was cancelled (OperationCanceledException, which coversTaskCanceledException) (JsInteropFailure.cs:18-31; doc comment,ThemeInterop.cs:13-17). Any other exception still propagates. - Why it's built this way: theming is cosmetic, so a failed or timed-out cookie read or write degrades to "the page keeps its current mode" rather than killing the circuit from the root layout. Sharing the predicate keeps this guard from drifting away from the other interop callers; the timeout case is the one a hand-written three-type filter missed.
- Where it's used:
MmcaThemeProviders.razor:68,97andThemeToggle.razor:22(all underMMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/); ThemeService names it in theBL0016justifications of its three unguarded JS calls (ThemeService.cs:52,89,101), and ColorModeStamp refers to it as the set it matches inline (comment,ColorModeStamp.cs:31). Pinned directly byJsInteropFailureTests, which asserts aTaskCanceledExceptionreports failure instead of throwing and a successful call reports success (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Common/JsInteropFailureTests.cs:29-38), and exercised through the provider and toggle component tests.
ThemeService
MMCA.Common.UI ·
MMCA.Common.UI.Theme·MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/ThemeService.cs:23· Level 1 · class (sealed)
- What it is: the single owner of the Day/Dark preference (ADR-028). It holds the current mode for
the circuit, persists a change through a small JS module to a cookie plus
localStorage, and raises an event so every subscriber re-renders together. - Depends on: LazyJsModule (single-flight importer for its JS module,
ThemeService.cs:26);Microsoft.JSInterop.IJSRuntime(ASP.NET Core, primary-constructor parameter at line 23); an optional IInitialThemeModeSource, the second primary-constructor parameter, defaulting tonull(line 23); the asset it imports,MMCA.Common/Source/Presentation/MMCA.Common.UI/wwwroot/theme.js, which owns the cookie andlocalStorageaccess (theme.js:5,23,33).IAsyncDisposable(BCL) is implemented so the module reference is released with the circuit. - Concept introduced, one scoped service as the theme's single source of truth.
[Rubric §20, Design System, Theming & UI Consistency]assesses whether theming is a first-class, centrally owned concern rather than per-page CSS toggling. Here exactly one scoped service holdsIsDarkMode(line 32); the toggle button, theMudThemeProviderwrapper and, on MAUI, the native chrome all read from it and all subscribe toOnChange(line 38). Nothing else stores a copy.[Rubric §19, State Management & Data Flow]is the same fact viewed as state: an event-plus-property service is the framework's pattern for cross-component UI state that is not routed, and the cost of that pattern is unsubscription discipline in every consumer. - Concept introduced, JS interop is not available during prerender.
[Rubric §18, UI Architecture & Component Design]covers the render-mode contract a Blazor component must respect (ADR-056,Website/docs-src/adr/056-blazor-render-mode-strategy.md). Reading a cookie orlocalStoragerequires a live browser, soInitializeAsynccan only run after the first interactive render; the class documents that requirement on itself (ThemeService.cs:11-14) rather than guarding it internally, and the component that owns the lifecycle calls it fromOnAfterRenderAsync(firstRender)(MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/MmcaThemeProviders.razor:59-69). - Walkthrough
ModulePathis the_content/MMCA.Common.UI/theme.jsstatic-web-asset path (line 25), wrapped in a LazyJsModule field (line 26). Two components resolving the same scoped service therefore share one import rather than racing two.IsDarkMode(line 32) andIsInitialized(line 35) are public with a private setter: subscribers read the state, only this class writes it.OnChange(line 38) is a plainEventHandler?.IsDarkModeis seeded from the constructor'sinitialModeSource?.IsDarkMode ?? false(line 32), so on a head with a native store (MAUI registers one) every reader, the app-bar toggle's icon and label among them, starts in the mode the page is painted in rather than light until initialization runs (doc comment, lines 17-22); a web head passes no source and starts atfalse.InitializeAsync()(line 44) is idempotent by an early return onIsInitialized(lines 46-49). It imports the module (line 51), asksgetfor the stored value (line 53), and resolves the mode: a stored value wins by an ordinal case-insensitive compare against"dark"(lines 54-55), otherwise it falls back to the OS setting throughsystemPrefersDark(line 56), which readsprefers-color-scheme(theme.js:33-35). Only then does it setIsInitializedand raiseOnChange(lines 59-60), so the first notification carries the resolved answer, not the default.InitializeAtStartupAsync(bool?)(line 72,internal) is the entry pointMmcaThemeProviderscalls on first render, passing the mode of an optional IInitialThemeModeSource it resolved inOnInitialized(MmcaThemeProviders.razor:50,69). Anullfalls through toInitializeAsync; a known native value takesInitializeFromNativeAsync(lines 75-92), which is also idempotent onIsInitialized(lines 77-80), adopts the value, setsIsInitializedand raisesOnChange(lines 82-84), and only then reseeds the cookie andlocalStoragethroughset(lines 88-90), so a stale WebView value can neither win now nor be mirrored back over the native one. The reseed is last on purpose: a failure leaves the native value in force and surfaces to the caller's best-effort guard (comment, lines 86-87).- Each of the three JS calls that can fail sits inside a
#pragma warning disable BL0016block whose justification names why the failure must propagate rather than be caught here: the caller observes it through ThemeInterop (lines 52-57, 89-91, 101-103). SetDarkModeAsync(bool)(line 96) persists first, throughset(line 102), then writes the field (line 104) and notifies (line 105): a failed import or JS call leavesIsDarkModeand every subscriber on the mode that is actually stored (comment,ThemeService.cs:98-99). The JS side writes a non-HttpOnly cookie with a one-yearmax-ageandsamesite=laxand mirrors it tolocalStorage, guarding the mirror in atrybecause private browsing can refuse storage (theme.js:23-31). The cookie is deliberately readable by the server, which is how SSR can paint the right theme on the first response (theme.js:1-2).ToggleAsync()(line 109) isSetDarkModeAsync(!IsDarkMode), the entire body of the app-bar toggle's click handler.DisposeAsync()(line 114) forwards to the module wrapper, which is where the guarded release of a torn-down circuit'sIJSObjectReferencelives.
- Why it's built this way: ADR-028 (
Website/docs-src/adr/028-dark-theme-mode.md) requires the preference to survive a reload and to be visible to the server for a no-flash first paint, which is why the value goes to a cookie andlocalStoragerather than to component state, and why the service holds noMudThemeof its own: it publishes a boolean and lets the theme providers decide what that means visually. Not gatingInitializeAsynconRendererInfois also deliberate and pinned: the prerender test uses thegetinvocation as proof that the first render ran at all (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Theme/MmcaThemeProvidersPrerenderTests.cs:29-33). - Where it's used: registered by
AddUISharedas scoped (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:229) and consumed byMmcaThemeProviders, which subscribes inOnInitialized, initializes on first render and unsubscribes on dispose (MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/MmcaThemeProviders.razor:56,69,147), byThemeToggle(MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/ThemeToggle.razor:2,7), by the MAUI head'sNativeThemeSync, which mirrors the in-app choice onto the native chrome (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/Components/NativeThemeSync.razor:17,41,52), and by the login flow, which applies a returning user's stored theme (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor:393). Hosts that compose their own DI register it directly, for example MMCA.Helpdesk (MMCA.Helpdesk/Source/Hosts/UI/MMCA.Helpdesk.UI.Web/Program.cs:23). Behavior is pinned through the two components that drive it, MmcaThemeProvidersTests and ThemeToggleTests, and end to end byDarkModeE2ETests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.E2E.Tests/Layout/DarkModeE2ETests.cs:54). - Caveats: no test file in
MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Servicesis named for this type; its behavior is covered only through those components, so a change toInitializeAsyncsurfaces as a component-test failure rather than a direct one.OnChangeis a plain event with no weak-reference handling, so a subscriber that fails to unsubscribe outlives its component for the life of the circuit; both in-framework subscribers unsubscribe on dispose and both have a test asserting it.SetDarkModeAsyncsetsIsDarkModeonly after the JS write succeeds, so a failedsetthrows out of the call with the in-memory mode, the persisted mode and the subscribers still in agreement and noOnChangeraised. The native-first path orders it the other way on purpose:InitializeFromNativeAsyncadopts the native value and raisesOnChangebefore thesetreseed, so a failed reseed throws with the in-memory mode already the native one. The exception is not swallowed here: the callers that must not take down the circuit wrap the call in ThemeInterop (ThemeToggle.razor:22).
ColorModeStamp
MMCA.Common.UI ·
MMCA.Common.UI.Theme·MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/ColorModeStamp.cs:15· Level 1 · class (internal static)
- What it is: the opt-in colour-mode hook of
MmcaThemeProviders. When the host setsLayout:StampColorModeOnDocument, it mirrors the Day/Dark mode onto<html data-mmca-color-mode="light|dark">so an app's own stylesheet can follow it; with the setting off (the default) it does nothing (doc comment,ColorModeStamp.cs:9-14). - Depends on: LayoutSettings (its
StampColorModeOnDocumentflag,MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Settings/LayoutSettings.cs:51), and thestampColorModeexport ofMMCA.Common/Source/Presentation/MMCA.Common.UI/wwwroot/theme.js:103, and JsInteropFailure for its catch filter (ColorModeStamp.cs:38). Externals:Microsoft.JSInterop.IJSRuntimeandMicrosoft.Extensions.Options.IOptions<T>. - Concept introduced, an opt-in styling hook that cannot break theming.
[Rubric §20, Design System, Theming & UI Consistency]covers whether app CSS can follow the theme:MudThemeProvideronly swaps its palette variables, which gives CSS nothing to select on (LayoutSettings.cs:41-50), so this hook gives a host an attribute to key its own rules on. The attribute is deliberately notdata-mmca-theme, which belongs to the MAUI head's pre-paint script and its rules inapp.css(theme.js:83-84).[Rubric §18, UI Architecture & Component Design]applies too: the stamp is best-effort because, like the interactivity marker, an app's styling hook must never break theme initialisation (comment,ColorModeStamp.cs:30). It tolerates exactly the failures ThemeInterop tolerates, but catches them inline so the guard is visible at the call (comment,ColorModeStamp.cs:31). - Walkthrough
- One method,
ApplyAsync(IJSRuntime js, IServiceProvider services, bool isInteractive, bool isDarkMode)(ColorModeStamp.cs:23). It returns early unless the render is interactive (JS interop is unavailable otherwise) and the scope resolvesIOptions<LayoutSettings>with the flag set totrue(ColorModeStamp.cs:25-28); a head with no layout settings registered therefore never stamps. - Otherwise it imports
./_content/MMCA.Common.UI/theme.jsand callsstampColorModewith"dark"or"light", disposing the module reference withawait using(ColorModeStamp.cs:32-37). Thetryis filtered withcatch (Exception ex) when (JsInteropFailure.IsUnavailable(ex))(ColorModeStamp.cs:38), the same predicate ThemeInterop uses, so an unavailable renderer, a torn-down circuit, a browser-side failure and an interop timeout are all absorbed (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/JsInteropFailure.cs:27-31); on any of them the stamp is skipped and the theme stays as it is (comment,ColorModeStamp.cs:40). Any other exception propagates. - On the JS side
stampColorModerecords the last mode, sets the attribute, and attaches oneenhancedloadlistener that re-stamps it, because enhanced navigation resynchronises<html>'s attributes from the new document (theme.js:85-86,103).
- One method,
- Why it's built this way:
ADR-028 makes ThemeService
the single owner of the mode; this class only reflects it outward and owns no state. Keeping it
opt-in and off by default means a host adopting nothing sees no change to its document. Being
interactive-only, a prerendered page carries no attribute until the page is interactive
(
LayoutSettings.cs:44-45). - Where it's used: called only by
MmcaThemeProviders, after its first interactive render (MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/MmcaThemeProviders.razor:75) and after every theme change (MmcaThemeProviders.razor:126). Pinned byMmcaThemeProvidersColorModeTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Theme/MmcaThemeProvidersColorModeTests.cs:21,29,49).
MMCATheme
MMCA.Common.UI ·
MMCA.Common.UI.Theme·MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/MMCATheme.cs:9· Level 2 · class (static)
What it is: the single application-wide MudBlazor
MudThemeinstance, defining the brand palette (light and dark), typography, and layout radius, applied once viaMudThemeProviderin the root layout.Depends on: BrandColors (the palette source of truth); MudBlazor (NuGet:
MudTheme,PaletteLight,PaletteDark,Typography,LayoutProperties).Concept introduced, one theme, accessibility-justified, with contrast math for both text and non-text UI.
[Rubric §20, Design System & Theming]assesses whether an app has a single coherent theme rather than per-page overrides;MMCATheme.Instanceis that one object (line 11).[Rubric §21, Accessibility]is unusually visible here, because most non-default color choices carry inline WCAG 2.1 AA/1.4.11 contrast math in a comment immediately above the value:- light
Warning = BrandColors.LightWarning(#A85D00) /WarningContrastText = BrandColors.LightWarningContrastText(#FFFFFF) (lines 35-36): the palette color is used as text and as a border as often as it is a fill (Color.WarningonMudText/MudLink/MudIconand on outlined chips/buttons), and MudBlazor's default#F57F17is only about 2.65:1 on Surface, failing the 4.5:1 floor everywhere it is text;#A85D00is 4.96:1 on Surface and 4.79:1 on Background, and is dark enough that white becomes the correct on-color label (comment, lines 29-34); - light
LinesInputs = "rgba(0,0,0,0.45)"(line 42): outlined-field borders answer to the 3:1 non-text floor (WCAG 1.4.11); MudBlazor's default is only 3.03:1/3.01:1, passing with no margin, so any host that darkens Background drops it below (comment, lines 38-41); - dark
PrimaryDarken = BrandColors.DarkPrimaryDarken(#1E88E5, line 66): MudBlazor repaints a filled primary control withPrimaryDarkenon hover, focus-visible and active while the label keepsPrimaryContrastText, so the darken has to carry the dark label too; the brand#1565C0left it at about 3.4:1, under the 4.5:1 floor, while Blue 600 holds 5.14:1 and still reads as a darker state than#42A5F5, andPrimaryFillContrastTestspins both fills (comment, lines 61-65); - dark
PrimaryContrastText = "rgba(0,0,0,0.87)"(line 71), because white on the lightened dark-mode primary#42A5F5is about 2.65:1 fill-on-fill while dark text is about 6.6:1 (comment, lines 68-70); - dark
SecondaryContrastText/TertiaryContrastText/InfoContrastText/SuccessContrastText(lines 81, 83, 85, 87): every lightened dark-mode accent takes the same Material treatment, white is 2.36-2.65:1 as a fill across the four colors whilergba(0,0,0,0.87)lands at 6.96-7.70:1, and each accent stays legible as text on Surface too (comment, lines 75-80); - dark
WarningContrastText(line 90), white on#FFA726being about 2.0:1 against about 10.8:1 (line 89); - dark
Error = BrandColors.DarkError(#FF8A80) /ErrorContrastText = "rgba(0,0,0,0.87)"(lines 95, 98): the previous#EF5350was only 3.84:1 as text on Surface, below the 4.5:1 floor whereverColor.Erroris a label rather than a fill (inline validation copy, outlined error chips);#FF8A80reads 5.86:1 on Surface, with the white-vs-dark label question resolved the same way as Primary (comments, lines 91-94, 96-97); - dark
InfoDarken/SuccessDarken/WarningDarken/ErrorDarkenfromBrandColors.DarkInfoDarkenand its three siblings (lines 109-112): a text (default-variant) or outlined alert paints its message in the*Darkencolour over the base colour atHoverOpacity(0.06) composited on Surface, and left unset MudBlazor darkens each accent, which on a dark surface moves the text towards the background (Info#2094F3is 3.82:1 on its tint, Success#4DAC524.23:1, Error#FF695C4.31:1, all under the 4.5:1 floor); the Material 300-level tints clear it (tint / Surface: Info 5.49 / 6.04, Success 6.01 / 6.65, Warning 6.93 / 7.73, Error 5.66 / 6.22, with Red 200 for Error because its base is already lighter than Red 300), the same values are the hover, focus and active fill of filled Info/Success/Warning/Error buttons, chips and FABs whose dark label reads 8.2:1 or better, andAlertTextContrastTestspins all eight ratios (comment, lines 99-108); - dark
LinesInputs = "rgba(255,255,255,0.5)"(line 117): the dark defaultrgba(255,255,255,0.3)is only 2.6:1 on Surface, effectively invisible to a low-vision user, while0.5is 4.59:1/5.10:1 (comment, lines 113-116); - dark
TableStriped = "rgba(0,0,0,0.2)"/TableHover = "rgba(0,0,0,0.32)"(lines 126-127): the row overlays darken rather than lighten, because a link sits on the composited row and MudBlazor's default white striping turns Surface#27303Ainto aboutrgb(82,89,97), where the link colour#42A5F5is only about 2.66:1 (any white overlay above roughly 3% already drops under 4.5:1); the black overlays read 5.77:1 (striped) and 6.15:1 (hover) on Surface and 6.61:1 / 6.87:1 on Background while staying visibly distinct from the plain row and from each other, andLinkContrastTestspins both (comment, lines 118-125).
The
Secondary(light) contrast rationale is deliberately not repeated here: line 21 points at BrandColors, where the value and its justification live together. The reverse holds forWarningandError: their constants live in BrandColors, whose summaries point back here for the math.- light
Walkthrough: a single
static MudTheme Instance { get; }(line 11) initialized with four blocks. Every hex value in both palettes is a BrandColors constant (comment, lines 15-17); the only literals left are thergba(...)on-color labels and input lines, each justified by the contrast comment above it.PaletteLight(lines 13-55) reads its primary and secondary triads from BrandColors (lines 18-24), sets the semantic colors from theLight*constants (Tertiary,Info,Success,Warning,Error, lines 25-37, including the WCAG-drivenWarningandLinesInputsvalues above), and then fixes app chrome:AppbarBackgroundandDrawerBackgroundfromBrandColors.ChromeBackground,DrawerText/DrawerIconfromChromeTextMuted, and background, surface, text, action and divider values from the matchingLight*constants (lines 43-54).PaletteDark(lines 56-140) lightens the primary for contrast on dark surfaces (Primary = BrandColors.PrimaryLight, line 60), pairs it with a Blue 600PrimaryDarken(line 66) and*Darkenstate colours for Info, Success, Warning and Error (lines 109-112, above), darkens the table row overlays (lines 126-127, above), takes the sameChrome*constants for app bar and drawer so the shell reads identically in both modes (lines 128-134), and darkens the surface stack (Background = BrandColors.DarkBackground,Surface = BrandColors.DarkSurface, lines 130-131) with theDark*text and divider tones.Typography(lines 141-219).Defaultsets the font stackInter, Segoe UI, Helvetica Neue, Arial, sans-serif; the comment above it records that Inter is self-hosted by this RCL (wwwroot/fontsplus an@font-faceblock inwwwroot/app.css) and that before those faces existed the stack silently fell through to Segoe UI, so the two must stay in step.H1throughH4use display weights 800/800/700/700 with slight negative letter spacing, which the comment explains is how Inter is meant to be set at large sizes;H5andH6stay at weight 600 with no negative tracking.Subtitle1/Subtitle2sit at weight 500,Body1/Body2set line heights 1.6 and 1.5, andButtonsetsTextTransform = "none", because MudBlazor's default uppercasing wrecks localized strings (German compounds, accented capitals) and reads dated; weight 600 keeps the label as prominent as the shouting did.LayoutPropertiessetsDefaultBorderRadius = "6px"(lines 220-223).
Why it's built this way: a static get-only property means the theme is constructed once and shared by every
MudThemeProvider. Sourcing every hex value from BrandColors rather than re-typing it is what letsBrandColorTokenTestspolice C# versus CSS drift and keeps this class a mapping of roles to named colors, and the per-color contrast comments turn accessibility decisions into reviewable source rather than tribal knowledge, now covering both text-on-fill (4.5:1) and non-text UI like input borders (3:1, WCAG 1.4.11) rather than text alone. The button-casing override is a small but instructive case of[Rubric §27, Internationalization & Localization]reaching into theming: a purely visual default became a localization problem.Where it's used: applied in the root layout of the Blazor Web and MAUI hosts via
MudThemeProvider Theme="MMCATheme.Instance".
TwoFactorUIModule
MMCA.Common.UI ·
MMCA.Common.UI.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/TwoFactor/TwoFactorUIModule.cs:16· Level 3 · class (sealed)
- What it is: the two-factor authentication module descriptor. Registering it is what gives a host
the account page's navigation item and the layout listener that sends a session refused for want of a
second factor to that page; a host that never registers it has no page (the router answers 404), no
nav item and no listener (doc comment,
TwoFactorUIModule.cs:10-15). - Depends on: IUIModule (the contract it implements), NavItem,
NavSection, SharedResource (the localization resource for the nav
label), MultiFactorRequiredListener (its layout component), and
MudBlazor's
Icons.Material.Filled.Security. - Concept introduced: none new; it is a framework-owned instance of the UI module descriptor taught
at IUIModule (ADR-067),
shaped like NotificationUIModule.
[Rubric §25, Navigation & IA]assesses whether navigation reflects the features a host actually has: the nav item exists only when the module is registered. - Walkthrough
AccountPath = "/profile/two-factor"(TwoFactorUIModule.cs:19), the single route constant the listener uses to build its redirect and to recognise that it is already on the page (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/MultiFactorRequiredListener.cs:47,83).NavItems(TwoFactorUIModule.cs:22-25): one item, key"Nav.TwoFactor", the security icon, resolved againstSharedResource, placed inNavSection.User.LayoutComponentTypes(TwoFactorUIModule.cs:28):[typeof(MultiFactorRequiredListener)], so the shell renders the listener only in a host that registered the module.Assembly(TwoFactorUIModule.cs:31) returns this class's own assembly,MMCA.Common.UI.
- Why it's built this way: a module descriptor is the existing switch the shell already reads for nav, layout components and router presence, so making two-factor a module gives the feature an all-or-nothing opt-in without new shell code. TwoFactorPageGate keys on the presence of this type.
- Where it's used: registered by
AddTwoFactorUI()in this namespace's DependencyInjection (MMCA.Common/Source/Presentation/MMCA.Common.UI/TwoFactor/DependencyInjection.cs:31); probed by TwoFactorPageGate (TwoFactorPageGate.cs:25); pinned byTwoFactorUIModuleTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/TwoFactor/TwoFactorUIModuleTests.cs:21).
DependencyInjection
MMCA.Common.UI ·
MMCA.Common.UI.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/TwoFactor/DependencyInjection.cs:13· Level 5 · class (static, with oneextension(IServiceCollection)block)
- What it is: the two-factor UI opt-in (ADR-116).
One method,
AddTwoFactorUI(), registers the account page atTwoFactorUIModule.AccountPath, its navigation item and the listener; a host that does not call it gets none of them (doc comment,DependencyInjection.cs:8-12). This is theMMCA.Common.UI.TwoFactorclass of that name, not the shared-UI composition rootAddUISharedlives in. - Depends on: ITwoFactorUIService / TwoFactorUIService,
IUIModule / TwoFactorUIModule; externals
Microsoft.Extensions.DependencyInjectionand itsExtensionsnamespace (TryAddScoped,TryAddEnumerable). - Concept introduced: none new; it uses the
extension(IServiceCollection services)block (DependencyInjection.cs:15) taught in the primer.[Rubric §33, Developer Experience]assesses how few calls a host needs to adopt a feature: here one call, placed next toAddUISharedin every UI head (web server, WebAssembly client, MAUI) whose API hosts theauth/two-factorendpoints (doc comment,DependencyInjection.cs:17-21). - Walkthrough:
AddTwoFactorUI()(DependencyInjection.cs:24) does two things and returns the collection for chaining (line 33).TryAddScoped<ITwoFactorUIService, TwoFactorUIService>()(line 27):TryAdd, so an app (or the gallery) that registered its own client keeps it (comment, line 26).TryAddEnumerable(ServiceDescriptor.Singleton<IUIModule, TwoFactorUIModule>())(line 31): calling the method from two places still registers the module once, because a second module would render the nav item and the listener twice (comment, lines 29-30).
- Why it's built this way: the authorization pieces (the policy and
TwoFactorPageAuthorizationHandler) are registered by
AddUISharedunconditionally (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:95-106), so the page attribute resolves in every host; this method only adds what makes the page reachable. The module's presence is then the single fact the router gate and the handler both read. - Where it's used: the three Store UI heads
(
MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:71,MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web.Client/Program.cs:43,MMCA.Store/Source/Hosts/UI/MMCA.Store.UI/MauiProgram.cs:65); no ADC host calls it. In Common the component gallery calls it over a canned client (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Gallery/GalleryHost.cs:130), and the opt-in is pinned byTwoFactorOptInRenderTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/TwoFactor/TwoFactorOptInRenderTests.cs:39,61). - Caveats: the group already has a
### DependencyInjectionsection for the shared-UI root (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs), so the two headings share one anchor in the assembled chapter and#dependencyinjectionresolves to whichever comes first.
TwoFactorPageGate
MMCA.Common.UI ·
MMCA.Common.UI.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/TwoFactor/TwoFactorPageGate.cs:12· Level 7 · class (internal static)
- What it is: the router-side check that answers the two-factor account page with the not-found
page when the host never registered the two-factor UI, because that page needs a client such a host
does not have and an API with no two-factor endpoints (doc comment,
TwoFactorPageGate.cs:6-11). - Depends on: IUIModule, TwoFactorUIModule and the TwoFactorAccount page type.
- Concept introduced: none new; it is the two-factor sibling of NotificationPageGate,
and the two sit in the same router condition.
[Rubric §25, Navigation & IA]applies as at TwoFactorPageRequirement. - Walkthrough
Hides(Type pageType, IEnumerable<IUIModule> modules)(TwoFactorPageGate.cs:18-19): true only when the matched page isTwoFactorAccountand the host hides two-factor pages.HidesTwoFactorPages(IEnumerable<IUIModule> modules)(TwoFactorPageGate.cs:24-25):!modules.Any(m => m is TwoFactorUIModule), so the module's presence is the whole switch.
- Why it's built this way: the page lives in
MMCA.Common.UI, an assembly every host routes, so it is always discoverable by the router; hiding it has to be an explicit check at render time rather than an absent assembly. ExposingHidesTwoFactorPagesseparately lets TwoFactorPageAuthorizationHandler reuse the same decision. - Where it's used: the shared router's
Foundbranch, beside the notification gate (MMCA.Common/Source/Presentation/MMCA.Common.UI/Routes.razor:15), and TwoFactorPageAuthorizationHandler (TwoFactorPageAuthorizationHandler.cs:23). Pinned byTwoFactorPageGateTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/TwoFactor/TwoFactorPageGateTests.cs:13,31) and, end to end,TwoFactorPageHiddenRoutingTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.E2E.Tests/Auth/TwoFactorPageHiddenRoutingTests.cs:14).
TwoFactorPageAuthorizationHandler
MMCA.Common.UI ·
MMCA.Common.UI.TwoFactor·MMCA.Common/Source/Presentation/MMCA.Common.UI/TwoFactor/TwoFactorPageAuthorizationHandler.cs:12· Level 8 · class (internal sealed)
- What it is: the handler that evaluates TwoFactorPageRequirement: an
authenticated caller passes, and every caller passes while the host hides the two-factor page (doc
comment,
TwoFactorPageAuthorizationHandler.cs:6-10). - Depends on: TwoFactorPageRequirement,
TwoFactorPageGate, IUIModule (the primary-constructor
IEnumerable<IUIModule> modules, line 12), and ASP.NET Core'sAuthorizationHandler<TRequirement>. - Concept introduced: none new; it mirrors
NotificationPageAuthorizationHandler.
[Rubric §11, Security]assesses that relaxing a check is narrow and deliberate: the bypass applies only when the page cannot be served at all, so it never exposes a working page to an anonymous caller. - Walkthrough:
HandleRequirementAsync(TwoFactorPageAuthorizationHandler.cs:16-30) null-guards both arguments (lines 20-21), then callscontext.Succeed(requirement)whenTwoFactorPageGate.HidesTwoFactorPages(modules)holds or any identity on the user is authenticated (lines 23-27). Otherwise it does nothing, which leaves the requirement unmet, the standard way an ASP.NET Core handler fails a requirement. - Why it's built this way: checking
Identities.Any(identity => identity.IsAuthenticated)rather than only the primary identity matches what[Authorize]accepts, so the policy is[Authorize]plus exactly one exception. - Where it's used: registered transient through
TryAddEnumerablebyAddUIShared(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:105-106); pinned byTwoFactorRoutesTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/TwoFactor/TwoFactorRoutesTests.cs:26) andTwoFactorPageAuthorizationTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/TwoFactor/TwoFactorPageAuthorizationTests.cs:64).
AbsoluteUrlAttribute
MMCA.Common.UI ·
MMCA.Common.UI.Validation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Validation/AbsoluteUrlAttribute.cs:26· Level 0 · class (sealed,ValidationAttribute)
- What it is: a DataAnnotations rule that a string property must be an absolute
httporhttpsURL. It is the client-side twin of the server'sAbsoluteUrlRulesin MMCA.Common.Application, so a form gives the same verdict the API would (doc comment,AbsoluteUrlAttribute.cs:6-8). - Depends on: nothing first-party. Externals:
System.ComponentModel.DataAnnotations(ValidationAttribute,ValidationResult,ValidationContext,RequiredAttribute), BCLUri. It is consumed by DataAnnotationsModelValidator, which is the thing that actually runs it on a MudBlazor field. - Concept introduced, validation parity as a security control, not just a UX nicety.
[Rubric §24, Forms, Validation & UX Safety]assesses whether the rules a form enforces match the rules the server enforces. Most parity gaps cost only a wasted round trip. This one is different, and the doc comment says why (lines 8-11): the values this rule guards get rendered straight into an imagesrcor a linkhref, so acceptingjavascript:ordata:on the client and rejecting it on the server means the only thing between a pasted script URL and the rendered page is a network hop.[Rubric §26, Front-End Security]assesses browser-side hardening. Restricting the accepted schemes to exactlyhttpandhttps(lines 44-46) is the narrow allowlist that keeps ajavascript:URL out of an anchor target in the first place.- Optionality is the caller's decision. Null, empty, and whitespace all pass (line 39). The attribute deliberately does not imply "required": a mandatory field pairs this with
[Required], which is what keeps a blank required field showing one clear message instead of two (lines 12-16). - The message is a resource key channel.
ErrorMessageis returned unchanged rather than run throughstring.Format(line 52), which is what lets a model declareErrorMessage = "Validation.AbsoluteUrl"; DataAnnotationsModelValidator resolves every message it receives against the page's localizer and passes an unknown key through untouched, so a plain-English message still renders as written (lines 17-23). See ADR-027 for the localization model.
- Walkthrough
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)](line 25): properties only, once each.- The parameterless constructor (lines 29-32) passes the default English message
"The value must be an absolute http or https URL."to theValidationAttributebase, so a model that declares noErrorMessagestill says something useful. IsValid(object?, ValidationContext)(lines 35-53) null-guards the context (line 37), then returnsValidationResult.Successfor anything that is not a non-blank string (lines 39-42). That single guard is what implements the "optional by default" contract above.- The accept path (lines 44-49):
Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)combined with an ordinal scheme comparison againstUri.UriSchemeHttpandUri.UriSchemeHttps.UriKind.Absolutealone is not enough, because plenty of non-web schemes parse as absolute URIs; the scheme equality check is the actual gate. - The reject path (lines 51-52) builds the member-name array from
validationContext.MemberNamewhen one is present and returnsnew ValidationResult(ErrorMessage, members), so MudBlazor can attribute the failure to the right field.
- Why it's built this way: expressing the rule as an attribute means it travels with the model property rather than with a page, so every form that binds that property inherits it, and the same model can be validated on the server by
Validator.TryValidateProperty. Comparing withStringComparison.Ordinalagainst the BCL scheme constants avoids the culture-sensitive comparison trap and matches howUrinormalizes schemes to lowercase. - Where it's used: applied to URL-bearing properties on shared form and request models, and executed by DataAnnotationsModelValidator through the ModelValidation bridge.
- Caveats / not-in-source: the exact set of consumer models carrying this attribute is not visible from this file; the server-side
AbsoluteUrlRulesit mirrors lives in MMCA.Common.Application and is only named in the doc comment (line 7).
IModelValidator
MMCA.Common.UI ·
MMCA.Common.UI.Validation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Validation/IModelValidator.cs:13· Level 0 · interface
- What it is: a one-method contract that validates a single property of a form model and returns that property's error messages. It is the pluggable rule engine behind ModelValidation
.For. - Depends on: nothing. Its in-box implementation is DataAnnotationsModelValidator (named in the doc comment, line 8); its only caller is ModelValidation.
- Concept introduced, the shape MudBlazor forces and the abstraction that exploits it. MudBlazor hands a field's
Validationdelegate two arguments: the form model and the dotted path of the member being edited. That is exactly the shape a rule engine needs, so the interface simply names it:IEnumerable<string> Validate(object model, string propertyPath)(line 27).[Rubric §1, SOLID]assesses dependency direction and interface size. This is a one-method, dependency-free interface, and the doc comment (lines 8-10) states the payoff plainly: a consumer that keeps its rules in FluentValidation supplies its own implementation, so MMCA.Common.UI never has to reference a validation library. The abstraction exists to keep a NuGet dependency out of a shipped UI package, not to satisfy a pattern.[Rubric §24, Forms, Validation & UX Safety]assesses where form rules live. By making the engine pluggable, the framework can offer a default (attributes on the model) without forcing it on a consumer whose rules already live somewhere else.- Two contract details are load-bearing and documented rather than typed. The
propertyPathis dotted and relative to the model, for example"Title"or"Address.City"(lines 19-23), which is what MudBlazor derives from a field'sForexpression. And the return value is never null (line 25): an empty sequence means valid, so no caller has to null-check.
- Walkthrough: a single member,
Validate(object model, string propertyPath)(line 27), returningIEnumerable<string>.objectrather than a generic type parameter is deliberate: MudBlazor'sValidationparameter is itself untyped at that position, so a generic interface would only add a cast at the boundary. - Why it's built this way: the smallest possible extension point that still matches the host framework's calling convention. Anything wider (a "validate the whole model" method, a result type) would be unused by the one thing that calls it.
- Where it's used: accepted by ModelValidation
.For(ModelValidation.cs:43), which wraps it in the delegate a MudBlazor field'sValidationparameter expects; implemented by DataAnnotationsModelValidator.
OidcProviderFlags
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.ClientConfig·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigOAuthSection.cs:55· Level 0 · record (private sealed, nested inClientConfigOAuthSection)
- What it is: the served shape of one generic OIDC provider inside the
oAuthsection of/client-config:Enabled,DisplayNameandUsesDomains, and nothing else (ClientConfigOAuthSection.cs:55). - Depends on: nothing first-party; it is a positional record of a
bool, astringand abool. Its values are copied from an OidcProviderOption by ClientConfigOAuthSection.Build(ClientConfigOAuthSection.cs:41). - Concept: an allowlist expressed as a type. The record has no member for a client id, a secret,
an authority or a domain list, so a provider's sensitive settings cannot reach the anonymous
document through it; the class remarks state that rule (
ClientConfigOAuthSection.cs:13-16). See ClientConfigOAuthSection for the[Rubric §26, Front-End Security]reasoning. - Walkthrough: three positional members (
ClientConfigOAuthSection.cs:55).Enabledis alwaystruewhen the server builds it (:41), because only providers the server lists get an entry; the member exists because the WebAssembly client's ConfigurationOAuthUISettings lists anOAuth:Oidc:<Name>section only when it is flaggedEnabledor carries aClientId(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/ConfigurationOAuthUISettings.cs:60-61), and the served document never carries the client id.UsesDomainsis the server's computed answer (aDomainslist with entries), which the client reads back through the sameUsesDomainskey (ConfigurationOAuthUISettings.cs:63-65), so the domain values themselves stay on the server. - Why it's built this way: the member names match the keys the client's configuration reader looks for, so serializing this record and binding it back is the whole round trip; no mapper sits on the client.
- Where it's used: only as the dictionary value type of OAuthFlags
.Oidc(ClientConfigOAuthSection.cs:52); it is private to ClientConfigOAuthSection.
DataAnnotationsModelValidator
MMCA.Common.UI ·
MMCA.Common.UI.Validation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Validation/DataAnnotationsModelValidator.cs:21· Level 1 · class (sealed)
- What it is: the in-box IModelValidator, backed by
System.ComponentModel.DataAnnotations. It validates one property against the attributes declared on the model and localizes every message it produces, so the rules a shared request or form model already carries are the only place those rules are written and markup stops repeatingRequired/MaxLengthper field. - Depends on: first-party: IModelValidator (the contract it implements, line 21), and it executes rules such as AbsoluteUrlAttribute. Externals:
System.ComponentModel.DataAnnotations(Validator,ValidationContext,ValidationResult),System.Reflection(PropertyInfo,BindingFlags,AmbiguousMatchException),Microsoft.Extensions.Localization(IStringLocalizer,LocalizedString). - Concept introduced, message-as-resource-key with pass-through fallback.
[Rubric §27, Internationalization & Localization]assesses whether user-facing text resolves per culture from one catalog. Every message this validator produces is looked up against the injectedIStringLocalizer(line 149) and returned as the raw message whenlocalized.ResourceNotFound(line 150). That single line is what makes the design safe to adopt incrementally: a model can declareErrorMessage = "Some.Resource.Key"and get a localized string, or declare plain English and get plain English, with no flag to set. See ADR-027 for the localization model this plugs into.[Rubric §24, Forms, Validation & UX Safety]assesses single-declaration rules; the model's attributes are the declaration and this class is the only executor.- Reflection that fails silently, on purpose.
TryResolveOwnerreturns false when a link in a dotted path is null or the member does not exist (lines 95-98, 106-110). The comment (lines 77-79) gives the reasoning: an unreachable path carries no rules, so it cannot fail, and a partially built model never throws mid-keystroke. A validator that threw while the user was typing would be worse than one that says nothing. - A real reflection edge case is handled rather than ignored.
FindProperty(lines 118-129) catchesAmbiguousMatchExceptionand retries withBindingFlags.DeclaredOnly, because anew-shadowed property matches twice underFlattenHierarchy; the comment (line 126) records the tie-break rule, the most-derived declaration is the one bound in markup.
- Walkthrough
PropertyLookup(lines 23-24) is the sharedBindingFlagsset:Public | Instance | FlattenHierarchy.- The constructor (lines 36-41) requires an
IStringLocalizerand null-guards it. The parameter doc (lines 31-35) tells callers to pass the page's ownIStringLocalizer<TResource>precisely so that unknown keys fall through unchanged. Validate(object model, string propertyPath)(lines 44-55) is the IModelValidator implementation: guard, resolve the owner andPropertyInfo, return an empty array when unresolvable (line 51), then validate the value the model currently holds viaproperty.GetValue(owner)(line 54).ValidateValue(object model, string propertyPath, object? value)(lines 66-74) is the sibling used when the candidate value has not been written to the model yet, which is the case for the single-field bridge ModelValidation.ForProperty.TryResolveOwner(lines 81-116) isinternal staticso ModelValidation.IsRequiredcan reuse it (ModelValidation.cs:97). It splits the path on.withRemoveEmptyEntries(line 90) and walks segment by segment, returning the last segment'sPropertyInfoplus the object that declares it (lines 100-104).[NotNullWhen(true)]on bothoutparameters (lines 84-85) is what lets callers dereference them without a null check after a true return.ValidateResolved(lines 131-140) builds aValidationContext(owner) { MemberName = property.Name }, callsValidator.TryValidateProperty(line 135), and projects the results throughLocalize, dropping empties (lines 137-139).Localize(lines 142-151) is the resource-key resolution described above.
- Why it's built this way: reusing the BCL validator rather than writing a rule interpreter means every DataAnnotations attribute (in-box or custom, such as AbsoluteUrlAttribute) works with no registration. Splitting
ValidatefromValidateValueis the difference between "check what the model holds" and "check what the user just typed", and both are needed because MudBlazor's two binding styles deliver the value at different times. - Where it's used: constructed inline on a page over that page's localizer and handed to ModelValidation
.For, exactly as NotificationSend does (NotificationSend.razor.cs:77).
ClientConfigUiSections
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.ClientConfig·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigUiSections.cs:34· Level 1 · class (internal static)
- What it is: the helper that copies Common.UI's own
Layout,Registration,SignInandLegalsettings from the server head's configuration into the anonymous/client-configdocument, so a value set where production values are set (an environment variable, Key Vault,appsettings.Production.jsonon the UI container) renders the same after WebAssembly hydration as in the prerender, with no second copy in the WebAssembly bundle (class summary,ClientConfigUiSections.cs:8-13). - Depends on: LayoutSettings, RegistrationSettings,
SignInSettings and LegalSettings (each one's
SectionNameand type,ClientConfigUiSections.cs:39-42). Externals:Microsoft.Extensions.Configuration(IConfiguration, binderGet(Type)),System.Text.Json(JsonNamingPolicy.CamelCase) andSystem.Reflection(PropertyInfo,BindingFlags). - Concept introduced, forward only what the settings class declares and what the server sets.
[Rubric §26, Front-End Security]assesses what reaches the browser. The remarks (ClientConfigUiSections.cs:14-33) give two rules. Each section is bound to its Common.UI settings type and only that type's settable properties are written, so an unrelated or secret key that happens to sit under the same section name in the server configuration never reaches the anonymous document; every forwarded value is already rendered on public pages. And a section absent from the server configuration, or a property whose key is absent, is skipped, so the WebAssembly client's own defaults hold for everything the server leaves unset.[Rubric §20, Design System & Theming]applies becauseLayout(brand, footer) is one of the forwarded sections, so the theme a head configures survives hydration. - Walkthrough
Forwarded(ClientConfigUiSections.cs:37-43) is the fixed list of(SectionName, SettingsType)pairs, in the order they are written.Build(IConfiguration)(ClientConfigUiSections.cs:51) loops the list (:53), skips a section that does not exist (:55-59) or binds tonull(:61-65), then builds a dictionary keyed by the camelCased property name over the declared settable properties whose key is present in that section (section.GetSection(property.Name).Value is not null,:67-72), reading each value from the bound instance so the binder's type conversion applies. A section with no present key yields nothing; otherwise it yields the camelCased section name and the map (:74-77).DeclaredSettableProperties(Type)(ClientConfigUiSections.cs:88-91) keeps public instance properties with a public setter or init accessor and no index parameters, which is what configuration binding writes; computed members such asLegalSettings.HasFooterLinksare excluded (doc:81-87). It isinternalso the tests can reach it.
- Why it's built this way: forwarding from the server's bound configuration means one place sets a
production value; binding then reading back through the settings type keeps the document to the
public shape the class declares. The host's extras win: a head that still adds one of these
sections through its
ClientConfigcallback replaces the forwarded copy (remarks:28-32), because ClientConfigEndpointExtensions writes these sections before the extras. - Where it's used: called once per request by
ClientConfigEndpointExtensions
.MapClientConfigEndpoint(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:111-114); pinned byClientConfigEndpointTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/ClientConfig/ClientConfigEndpointTests.cs).
OAuthFlags
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.ClientConfig·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigOAuthSection.cs:48· Level 1 · record (private sealed, nested inClientConfigOAuthSection)
- What it is: the whole served value of the
oAuthsection of/client-config: the three built-in provider flags plus one OidcProviderFlags entry per configured OIDC provider (ClientConfigOAuthSection.cs:47-52). - Depends on: OidcProviderFlags (the dictionary value type, line 52); BCL
IReadOnlyDictionary<TKey, TValue>. - Concept: same allowlist-as-a-type idea as OidcProviderFlags, one level up; taught on ClientConfigOAuthSection.
- Walkthrough: four positional members (
ClientConfigOAuthSection.cs:48-52).GoogleEnabled,GitHubEnabledandAppleEnabledcarry the server's resolved IOAuthUISettings flags;Oidcis keyed by provider name withStringComparer.OrdinalIgnoreCase(ClientConfigOAuthSection.cs:39-42). Serialized with camelCase members, the section readsgoogleEnabled,gitHubEnabled,appleEnabledandoidc, the keys the WebAssembly client's ConfigurationOAuthUISettings reads back case-insensitively asOAuth:GoogleEnabledandOAuth:Oidc:<Name>(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/ConfigurationOAuthUISettings.cs:38-49). - Why it's built this way: a private nested record rather than an anonymous object gives the
served shape one named, documented place (summary,
ClientConfigOAuthSection.cs:47) while keeping it out of the package's public API. - Where it's used: constructed only by ClientConfigOAuthSection
.Build(ClientConfigOAuthSection.cs:44), whose return value ClientConfigEndpointExtensions writes into the document.
ClientConfigOAuthSection
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.ClientConfig·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigOAuthSection.cs:20· Level 2 · class (internal static)
- What it is: the helper that builds the
OAuthsection of the anonymous/client-configdocument from the server head's registered IOAuthUISettings, in exactly the shape ConfigurationOAuthUISettings reads on the WebAssembly client, so the sign-in page lists the same external providers after hydration as in the prerender (class summary,ClientConfigOAuthSection.cs:6-11). - Depends on: IOAuthUISettings (resolved from the request's services, line 33),
OidcProviderOption (the items of
OidcProvidersit projects, line 39), and its two private records OAuthFlags and OidcProviderFlags. Externals:Microsoft.Extensions.DependencyInjection(GetService<T>), BCL LINQToDictionaryandStringComparer.OrdinalIgnoreCase. - Concept introduced, forward availability, never credentials.
[Rubric §26, Front-End Security]assesses what reaches the browser. On the server, ConfigurationOAuthUISettings decides a provider is available because itsClientIdis set (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/ConfigurationOAuthUISettings.cs:45-49,60-61), so the configuration it reads also holds client ids, secrets, authorities and domain lists. This class forwards only the resolved verdicts: the three built-in flags and, per OIDC provider,Enabled,DisplayNameandUsesDomains(remarks,ClientConfigOAuthSection.cs:12-16). The client's own reader accepts a pre-computed{Provider}Enabledflag or anOidc:<Name>:Enabledflag in place of a client id (ConfigurationOAuthUISettings.cs:47,60-61), so the browser learns which buttons to draw and nothing it could use to impersonate the app.[Rubric §18, UI Architecture]applies for the same reason as ClientConfigUiSections: the prerender and the hydrated client read one source of truth, the server head's configuration. - Walkthrough
SectionName(ClientConfigOAuthSection.cs:23) is"OAuth", the configuration section the client binds; the endpoint camelCases it tooAuthon the wire.Build(IServiceProvider)(ClientConfigOAuthSection.cs:31-45) resolvesIOAuthUISettingswithGetServiceand returnsnullwhen the head registers none (lines 33-37), which the endpoint reads as "write no section". Otherwise it projectsOidcProvidersinto a case-insensitive dictionary keyed byName, each value anew OidcProviderFlags(Enabled: true, DisplayName, UsesDomains)(lines 39-42), and returns a new OAuthFlags with the three built-in flags and that dictionary (line 44). The return type isobject?because both records are private.- OAuthFlags (lines 47-52) and OidcProviderFlags (lines 54-55) are the served shape, documented on their own sections.
- Why it's built this way: the framework, not each host, writes this section, because a host
hand-writing it would have to know the OIDC sub-shape too. The remarks spell out the consequence for
hosts (
ClientConfigOAuthSection.cs:16-18): anOAuthsection added through the host'sClientConfigextras replaces this one whole and would drop the OIDC providers, so a host must not add it. ReadingIOAuthUISettingsrather than raw configuration means a head that registers a custom implementation is projected through the same interface the sign-in page uses. - Where it's used: called once per request by
ClientConfigEndpointExtensions
.MapClientConfigEndpoint, after the Common.UI sections and before the host's extras (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:116-121). Pinned byClientConfigEndpointTests:ProjectsTheHeadsSignInProviders_IntoTheShapeTheClientReadsbinds the served document into a client-sideConfigurationOAuthUISettings, asserts the OIDC list matches the server's in order, and asserts no client id, secret, authority or domain appears (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/ClientConfig/ClientConfigEndpointTests.cs:309-336);WithNoOAuthSettingsRegistered_ServesNoOAuthSectionpins thenullpath (:338-347). - Caveats / not-in-source: the class summary also names the shape as what
ConfigurationOAuthUISettingsreads; nothing at compile time ties the record member names to the client's configuration keys, so that agreement is held by the round-trip test above rather than by the type system.
LocalizedDataAnnotationsValidator
MMCA.Common.UI ·
MMCA.Common.UI.Validation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Validation/LocalizedDataAnnotationsValidator.cs:29· Level 2 · class (sealed,ComponentBase,IDisposable)
- What it is: a drop-in replacement for the stock
<DataAnnotationsValidator />inside anEditForm. It runs the same DataAnnotations rules, but through DataAnnotationsModelValidator, so everyErrorMessageis resolved as a resource key and fields bound withForshow the translated message; a message that is not a known key passes through unchanged, exactly as with the stock validator (doc comment,LocalizedDataAnnotationsValidator.cs:9-15). - Depends on: DataAnnotationsModelValidator (the localizing rule engine it constructs, line 54) and SharedResource (the resource marker behind the injected
IStringLocalizer<SharedResource>, lines 30-31). Externals:Microsoft.AspNetCore.Components(ComponentBase,[CascadingParameter],[Inject]),Microsoft.AspNetCore.Components.Forms(EditContext,ValidationMessageStore,FieldIdentifier,FieldChangedEventArgs,ValidationRequestedEventArgs),Microsoft.Extensions.Localization,System.Reflection. - Concept introduced, one localizing path for both form styles.
[Rubric §27, Internationalization & Localization]assesses whether user-facing text, validation messages included, resolves per culture from one catalog. The MudForm pages already localize through ModelValidation and DataAnnotationsModelValidator; theEditFormpages used the stock validator, which rendersErrorMessageverbatim, so a model declaring a resource key would show the key. This component closes that gap by feeding the same engine into theEditContextinstead of a MudBlazorValidationdelegate (doc comment, lines 11-14). See ADR-027 for the localization model.[Rubric §24, Forms, Validation & UX Safety]assesses single-declaration rules and consistent feedback timing. The rules stay on the model; this class only decides when they run: per field on change, and for every public property on submit (doc comment, lines 16-19).
- Walkthrough
- State is three nullable fields, the attached
EditContext, itsValidationMessageStore, and the validator (lines 23-25).CurrentEditContextis a private[CascadingParameter](lines 27-28) and the localizer a private[Inject](lines 30-31), so the markup takes no parameters at all:<LocalizedDataAnnotationsValidator />. OnParametersSet(lines 37-57) throwsInvalidOperationExceptionwhen no cascadingEditContextexists, naming the fix ("Place it inside an EditForm", lines 39-43). It returns early when the context is the one already attached (lines 45-48); otherwise it detaches from any previous context (line 50), then creates the message store and anew DataAnnotationsModelValidator(Localizer)and subscribes toOnFieldChangedandOnValidationRequested(lines 52-56). Re-attaching on a swapped context is what keeps a form that replaces its model working.HandleFieldChanged(lines 59-70) clears the changed field's messages, adds_validator.Validate(field.Model, field.FieldName), and callsNotifyValidationStateChanged(lines 66-69).HandleValidationRequested(lines 72-94) clears every message (line 79), reflects the model's public instance properties, drops indexers, and de-duplicates names ordinally (lines 82-86), then validates each one into its ownFieldIdentifier(lines 88-91) before notifying once (line 93).Detach(lines 96-109) unsubscribes both handlers, clears the store and nulls all three fields;Disposeis exactlyDetach()(line 34), so the component never leaves a handler on a context that outlives it.
- State is three nullable fields, the attached
- Why it's built this way: reusing DataAnnotationsModelValidator rather than re-implementing resolution means the
EditFormand MudForm paths cannot disagree about which keys resolve. InjectingIStringLocalizer<SharedResource>rather than taking a page localizer as a parameter keeps the drop-in property: swapping the tag is the whole migration, and the auth forms'Auth.Field.*keys live in that shared catalog (MMCA.Common/CHANGELOG.md:36). - Where it's used: the four auth
EditFormpages, Login (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor:40), Register (Register.razor:33), ForgotPassword (ForgotPassword.razor:39) and ResetPassword (ResetPassword.razor:43); their models, LoginModel, RegisterModel, ForgotPasswordModel and ResetPasswordModel, name it in their doc comments as the reason theirErrorMessagevalues are keys (LoginModel.cs:10,RegisterModel.cs:11,ForgotPasswordModel.cs:10,ResetPasswordModel.cs:12). It is public API of the package (PublicAPI.Shipped.txt:1193-1195). - Caveats: submit validation walks top-level properties only and calls the per-property path, so it does not run class-level attributes or
IValidatableObject.Validate, which the stock validator's whole-object pass does; a model relying on either loses that check when it switches. Messages always resolve againstSharedResource, so a key that exists only in a page's own resource file passes through untranslated. No file underMMCA.Common/Testsnames this type, so its attach, re-attach and submit behavior is unpinned except through whatever the auth-page E2E runs exercise.
ModelValidation
MMCA.Common.UI ·
MMCA.Common.UI.Validation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Validation/ModelValidation.cs:26· Level 2 · class (static)
- What it is: the bridge that turns a form model's declared rules into the delegate MudBlazor's field
Validationparameter expects, so a page declares its rules once (on the model) instead of scatteringRequiredandMaxLengthacross the markup and re-checking them by hand. - Depends on: first-party: IModelValidator (the pluggable engine taken by
For) and DataAnnotationsModelValidator (taken concretely byForProperty, and reused via itsinternal staticTryResolveOwnerinIsRequired, line 97). Externals:System.Linq.Expressions(Expression<Func<,>>,MemberExpression,UnaryExpression,ParameterExpression),System.ComponentModel.DataAnnotations(RequiredAttribute),System.Reflection(PropertyInfo). - Concept introduced, adapting a model's rules onto a UI library's callback shape.
[Rubric §24, Forms, Validation & UX Safety]assesses whether validation is declared once and enforced consistently. MudBlazor's contract is a delegate; DataAnnotations' contract is attributes on a type. This class is the two-line adapter between them, and the usage block in the doc comment (lines 14-24) is the canonical example a page copies:_validate = ModelValidation.For(_model, new DataAnnotationsModelValidator(L))inOnInitialized, thenValidation="@_validate"on every field.- One delegate serves the whole form.
Forreturns a closure that ignores nothing and dispatches on the path MudBlazor passes (line 48), so a fifteen-field form still assigns the same single delegate to every field. The fallbackinstance ?? modelon that line is the small robustness detail: MudBlazor normally passes its ownMudForm.Modelback, and the captured instance covers the case where it does not, so a field still validates outside a form (parameter doc, lines 33-36). [Rubric §15, Best Practices & Code Quality]assesses rename safety.ForPropertynames the property by expression rather than by string (line 71), so a rename becomes a compile error instead of a silently dead rule.[Rubric §21, Accessibility]:IsRequiredexists so a field'sRequiredparameter (the asterisk and thearia-requiredaffordance) can be read off the same model that supplies the rules, rather than being typed a second time in markup where it can drift from the rule (doc, lines 83-87). It is explicitly not a second rule: MudBlazor's own required message is unused when aValidationdelegate is present, so the localized message from the model is the one shown.
- One delegate serves the whole form.
- Walkthrough
For(object model, IModelValidator validator)(lines 43-49): null-guards both arguments, then returns(instance, propertyPath) => validator.Validate(instance ?? model, propertyPath)(line 48). This is the model-wide bridge, and it is what almost every page wants.ForProperty<TModel, TValue>(TModel model, Expression<Func<TModel, TValue>> property, DataAnnotationsModelValidator validator)(lines 69-81): resolves the dotted path once at setup viaGetPropertyPath(line 79) and returnsvalue => validator.ValidateValue(model, path, value)(line 80). Note the parameter type is the concrete validator, not the interface: the doc (lines 55-58) says why, the value being validated has not necessarily been written to the model yet, so the rules must come from DataAnnotations directly rather than from an arbitrary engine reading the model's current state.IsRequired(object model, string propertyPath)(lines 92-99): resolves the property through DataAnnotationsModelValidator.TryResolveOwnerand reportsproperty.IsDefined(typeof(RequiredAttribute), inherit: true)(line 98).GetPropertyPath<TModel, TValue>(lines 109-133) renders an expression as the dotted path MudBlazor'sForwould produce. It first unwraps theConvertnode the compiler inserts whenTValueis a value type boxed to object (lines 114-116, with the comment saying so), then walksMemberExpressionlinks pushing each name onto aStack<string>(lines 118-123), which reversesm => m.Address.CityintoAddress.Cityonstring.Join(line 132). Anything that is not a chain of property accesses rooted at the lambda parameter throwsArgumentExceptionwith a message showing the expected shape (lines 125-130).
- Why it's built this way: a static class with no state, because the bridge is pure translation. Offering both a model-wide and a single-field entry point matches the two ways MudBlazor fields actually bind, and pushing the expensive part (expression parsing) into setup rather than into the per-keystroke delegate keeps validation cheap on the typing path.
- Where it's used: NotificationSend builds its
_validatedelegate withFor(NotificationSend.razor.cs:77) and reads its twoRequiredaffordances withIsRequired(NotificationSend.razor:47,58). It is public API ofMMCA.Common.UI, so consumer app forms use the same bridge.
ClientConfigBuilder
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.ClientConfig·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigBuilder.cs:19· Level 3 · class (sealed)
- What it is: the accumulator a host's own
extrasdelegate writes into when it wants extra data served on the anonymous/client-configdocument, one named section perAddcall. - Depends on: ClientConfigEndpointExtensions (its
ApiSectionNameandModulesSectionNameconstants, checked as the two reserved names,ClientConfigBuilder.cs:51-52);Microsoft.AspNetCore.Http(HttpContext, BCL) andMicrosoft.Extensions.DependencyInjection/Microsoft.Extensions.Configurationfor the two convenience accessors it republishes. - Concept, a builder with an internal constructor.
[Rubric §26, Front-End Security]covers what this type prevents: the constructor isinternal(line 23), so the only place aClientConfigBuildercan come into existence is insideMapClientConfigEndpoint's own request delegate, which is also the one place a host'sextrascallback runs. A host cannot construct one ahead of time and stash arbitrary state in it outside the request it belongs to. - Walkthrough
_sections(line 21) is aDictionary<string, object?>keyed withStringComparer.OrdinalIgnoreCase(a collection expression withwith(...)), so"Support"and"support"collide as the same section.HttpContext(line 26) and the two accessors built on it,Services(line 29, readsHttpContext.RequestServices) andConfiguration(line 32, resolvesIConfigurationfrom those services), let anextrasdelegate reach DI and configuration without the endpoint having to pass them separately.Add(string name, object? value)(line 47) blank-checksname(ArgumentException.ThrowIfNullOrWhiteSpace, line 49), rejects the reserved framework sectionsClientConfigEndpointExtensions.ApiSectionNameandModulesSectionNamecase-insensitively, with a message naming the offending section (lines 51-57), then adds through_sections.TryAdd(line 59) so a second call with the same name throws rather than silently overwriting the first (lines 59-62). It returnsthisfor chaining (line 64). The Common.UI settings sections (Layout,Registration,SignIn,Legal) are not reserved: adding one replaces the copy ClientConfigUiSections forwarded.OAuthis not reserved either, but the parameter doc tells a host not to add it, because the framework writes it fromIOAuthUISettings(line 41) through ClientConfigOAuthSection, and a host copy would replace that section whole. The class remarks limit what belongs here to values the public site renders anyway, for example public contact details and public feature URLs (lines 15-17).Sections(line 34) isinternal, anIReadOnlyDictionary<string, object?>view the endpoint reads back after the delegate returns; nothing outside this package can enumerate a builder's contents.
- Why it's built this way: the reserved-name and duplicate-name guards live on the builder rather
than being left to the endpoint's own loop, so every caller of
Add, present or future, gets the same two checks for free. The internal constructor and internalSectionsgetter keep the type's read side as narrow as its write side: a host can only add, never inspect what a different extras call already added. - Where it's used: constructed once per request inside
ClientConfigEndpointExtensions
.MapClientConfigEndpoint's handler and handed to the caller'sextrasdelegate (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:97-98); itsSectionsare then read back to assemble the response document (ClientConfigEndpointExtensions.cs:123-126). A head reaches it through theClientConfigoption of MmcaBlazorWebPipelineOptions (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/MmcaBlazorWebPipelineOptions.cs:23); the ADC UI head'sAddAdcClientConfigadds itsSupportandMcpsections that way (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:162-167). Exercised directly byClientConfigEndpointTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/ClientConfig/ClientConfigEndpointTests.cs).
ClientConfigEndpointExtensions
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.ClientConfig·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:19· Level 3 · class (static)
- What it is: the extension that maps
GET /client-config, the anonymous document a WASM client's bootstrap fetches to learn the browser-reachable API base address before it can hold a session, plus the head's module switches, Common.UI settings and sign-in providers, and whatever extra sections the host contributes. - Depends on: ClientConfigBuilder (constructed per request, line 97),
ApiSettings (
IOptions<ApiSettings>, read forWasmApiEndpoint, line 87), ApiEndpointUrl (IsAbsoluteHttp, line 88), UIModuleConfiguration (IsModuleEnabled, line 141), ClientConfigUiSections (Build, line 111), ClientConfigOAuthSection (BuildandSectionName, lines 118-120), and, only in a host running the same-origin API proxy, SameOriginApiProxyMarker (probed from request services, line 153) and SameOriginApiProxySettings (read forPathPrefix, line 158); externalsMicrosoft.AspNetCore.Routing(IEndpointRouteBuilder,RouteHandlerBuilder),Microsoft.AspNetCore.Http(HttpContext),IConfiguration,System.Text.Json(JsonNamingPolicy.CamelCase), and the ASP.NET Core minimal-APIResultstype. - Concept introduced, fail-closed instead of falling back.
[Rubric §13, Observability & Operability]assesses whether a misconfigured host fails loudly and diagnosably rather than silently degrading. The endpoint's remarks (lines 41-49) state the rule directly: it servesApi:WasmApiEndpoint, the browser-reachable gateway URL, and never falls back toApi:ApiEndpoint, the server head's own service-discovery name, because a browser cannot resolve that name and serving it would hand the client a silently broken base address. A host whose value is missing, or is not an absolute http(s) URL (a deployment placeholder, for one), answers every request with a server error naming the key and the expected shape (lines 88-95), which surfaces as a failed client start instead of a client quietly pointed at the wrong API. This is the client-config instance of ADR-070. - Concept introduced, anonymous by declared necessity.
[Rubric §11, Security]covers why this endpoint is one of the few that must allow anonymous access on purpose: the WASM client fetches this document before it can hold a session (remarks, lines 73-78), and a host's fallback authorization policy would otherwise gate it like any other endpoint that states nothing. The endpoint therefore declaresAllowAnonymous()itself (line 130) rather than relying on an ambient default, and the remarks warn that only values the public site renders anyway belong inextras(lines 76-77). - Concept introduced, the head's module switches and UI settings travel with the document.
[Rubric §18, UI Architecture]assesses how the render modes of one app stay consistent. Themodulessection lists every entry of the head'sModulesconfiguration with ONLY its resolved enabled flag, never its other settings, so a module the head disables does not come back after the WebAssembly client hydrates (remarks, lines 50-57; see ADR-059). Thelayout,registration,signInandlegalsections carry the head's Common.UI settings, limited to declared properties and keys the server sets (remarks, lines 58-65), through ClientConfigUiSections. TheoAuthsection projects the head's IOAuthUISettings (the Google, GitHub and Apple flags, and each OIDC provider's name, display name and whether it uses email domains, never a client id or secret) through ClientConfigOAuthSection, so the sign-in providers a prerender lists survive hydration too; a host must not add its ownOAuthextra, which would replace this section and drop the OIDC providers (remarks, lines 66-72). - Concept introduced, an additive key for the same-origin proxy. A host that runs the same-origin
API proxy (ADR-131) gets one
extra member in the
Apisection,sameOriginApiEndpoint, the proxy's origin-relative base (for example/api/) that the WASM bootstrap resolves against the page's own origin, whileapiEndpointstays the gateway for full-page navigations (doc, lines 144-150). The proxy's presence is detected from DI (the marker service), not from configuration, so every host without the proxy serves the section exactly as before and an existing client sees no change. - Walkthrough
- Three public constants:
ClientConfigPath = "/client-config"(line 22),ApiSectionName = "Api"(line 25) andModulesSectionName = "Modules"(line 31), the two section names ClientConfigBuilder treats as reserved. - The
extension(IEndpointRouteBuilder endpoints)block (line 33, see primer) holds the single memberMapClientConfigEndpoint(Action<ClientConfigBuilder>? extras = null)(line 84). - The handler (lines 85-129) takes the request's
HttpContextplusIOptions<ApiSettings>, readsapiSettings.Value.WasmApiEndpoint(line 87), throwsInvalidOperationExceptionnaming the key whenApiEndpointUrl.IsAbsoluteHttprejects it (lines 88-95), builds a ClientConfigBuilder for the request and invokesextrason it (lines 97-98), and seeds the response with the camelCasedApisection fromBuildApiSection(context, wasmApiEndpoint)and the camelCasedModulessection fromBuildModulesSection(builder.Configuration)(lines 102-106). It then writes the forwarded Common.UI sections from ClientConfigUiSections (lines 111-114) BEFORE the host's extras, so a head that still adds one of them replaces the forwarded copy rather than colliding with it (comment, lines 108-110). Next, when ClientConfigOAuthSection.Build(context.RequestServices)returns a value, it is written under the camelCasedSectionName(oAuth), also before the extras (lines 116-121); a head that registers noIOAuthUISettingsgets nooAuthsection. Finally it overlays every builder section, each name run through the sameJsonNamingPolicy.CamelCasepolicy the web JSON defaults apply to members (lines 123-126), so the document's shape matches what an anonymous-object payload would have produced anyway. - The route is finished with
.AllowAnonymous().ExcludeFromDescription()(lines 130-131): anonymous for the reason above, and excluded from the OpenAPI description because it is not a data endpoint a client integrates against, it is bootstrap plumbing. - The private
BuildModulesSection(IConfiguration)(lines 138-142) maps each child of theModulessection, keyed as spelled there (case-insensitive dictionary), tonew { Enabled = UIModuleConfiguration.IsModuleEnabled(configuration, module.Key) }; a head with noModulessection serves an empty object. - The private
BuildApiSection(HttpContext, string)(lines 151-160) returnsnew { ApiEndpoint }whenGetService<SameOriginApiProxyMarker>()is null (lines 153-156); otherwise it readsIOptions<SameOriginApiProxySettings>.Value.PathPrefix(line 158) and returnsnew { ApiEndpoint, SameOriginApiEndpoint = prefix + "/" }(line 159).
- Three public constants:
- Why it's built this way: putting the base-address selection, the reserved-name policy and the
camelCase conversion all in one mapped endpoint means every host that calls
MapClientConfigEndpointgets the identical fail-closed contract; a host only supplies the pieces specific to it throughextras. The same-origin key is decided here too, from the proxy's own DI marker, so a host that adds the proxy does not have to remember a second client-config change. - Where it's used: mapped by the shared Blazor web pipeline, which passes the head's
MmcaBlazorWebPipelineOptions
.ClientConfigcallback asextras(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:211); its handler constructs ClientConfigBuilder per request. Pinned byClientConfigEndpointTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/ClientConfig/ClientConfigEndpointTests.cs) and exercised through the pipeline byBlazorWebPipelineTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Hosting/BlazorWebPipelineTests.cs). - Caveats / not-in-source: the
extrasparameter doc still gives "sign-in provider flags" as an example of a host section (line 81), which contradicts theoAuthremarks (lines 66-72); the remarks and ClientConfigBuilder.Add's parameter doc are the current rule.
OptionalEmailAttribute
MMCA.Common.UI ·
MMCA.Common.UI.Validation·MMCA.Common/Source/Presentation/MMCA.Common.UI/Validation/OptionalEmailAttribute.cs:26· Level 4 · class (sealed,ValidationAttribute)
- What it is: a DataAnnotations rule that a string property, when it has a value, must be a valid email address by the same format rule the server applies. A blank value passes, so the attribute never makes a field required.
- Depends on: first-party: EmailInvariants from
MMCA.Common.Shared.ValueObjects.Contact(OptionalEmailAttribute.cs:2), whoseEnsureEmailIsValidandMaxLengthit calls; the class doc (:7-11) names it as the check the Email value object runs and the one behind the server'sEmailRules. Externals:System.ComponentModel.DataAnnotations(ValidationAttribute,ValidationResult,ValidationContext). Like its sibling AbsoluteUrlAttribute, it is run on a MudBlazor field by DataAnnotationsModelValidator through the ModelValidation bridge, or in anEditFormby LocalizedDataAnnotationsValidator. - Concept introduced, client validation that calls the server's own rule instead of copying it.
[Rubric §24, Forms, Validation & UX Safety]assesses whether the client enforces what the server enforces. Rather than restating the format rule, the privateIsValidEmailFormat(OptionalEmailAttribute.cs:62-67) callsEmailInvariants.EnsureEmailIsValid(MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/EmailInvariants.cs:23) on the trimmed value and accepts onIsSuccess(:64-66). That method's format test is the generated regex^[^@\s]+@[^@\s]+\.[^@\s]+$(EmailInvariants.cs:55): exactly one@, no whitespace, and a dot in the domain part. Because the UI package referencesMMCA.Common.Shared, the form and the API run the same code, so the form neither rejects an address the API would accept nor accepts one it would refuse. See ADR-068 for the value-object invariants this reuses.- Length is not this attribute's verdict. A trimmed value longer than
EmailInvariants.MaxLength(256,EmailInvariants.cs:14) is accepted here (OptionalEmailAttribute.cs:65); the doc comment (:54-58) says it is left to a length rule, as the server leaves it. Without that short-circuit the invariant's ownEmail.TooLongfailure (EmailInvariants.cs:34-41) would surface as an "invalid email" message. - Optionality is the caller's decision. A non-string, null, empty or whitespace value returns
ValidationResult.Success(OptionalEmailAttribute.cs:39-42), the same contract asAbsoluteUrlAttribute: a mandatory field pairs this with[Required](class doc,:13-15).
- Length is not this attribute's verdict. A trimmed value longer than
- Walkthrough
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)](:25).- The parameterless constructor (
:29-32) passes the default English message"Enter a valid email address."to the base class. The class doc (:18-22) notes the message is emitted unformatted, so a model may setErrorMessageto a resource key such as"Auth.Field.Email.Invalid"and DataAnnotationsModelValidator resolves it, while a plain-English message renders as written. IsValid(object?, ValidationContext)(:35-51) null-guards the context (:37), lets blanks through, then callsIsValidEmailFormat(:44). On failure it builds the member-name array fromvalidationContext.MemberNamewhen present and returnsnew ValidationResult(ErrorMessage, members)(:49-50), so the failure attaches to the right field.IsValidEmailFormat(string)(:62-67): trims the value (:64), returns true when it is overMaxLength, otherwise returns whetherEnsureEmailIsValid(trimmed, nameof(OptionalEmailAttribute))succeeded (:65-66). Thesourceargument only labels the discardedError; theResultitself is reduced to a boolean.
- Why it's built this way: delegating to the shared invariant means there is one email format rule in the framework, so the client verdict cannot drift from the server's. The stock
EmailAddressAttributecannot express an optional field the user may clear back to blank (class doc,:13-15), which is why the attribute exists at all. - Where it's used: exercised by
OptionalEmailAttributeTestsin MMCA.Common.UI.Tests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Validation/OptionalEmailAttributeTests.cs), the only usage site found. - Caveats / not-in-source: which consumer models carry this attribute is not visible from this file.
BlazorCircuitLimitSettings
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Hardening·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hardening/BlazorCircuitLimitSettings.cs:17· Level 0 · class (sealed)
- What it is: the bound options type for a Blazor Server host's circuit hardening, three numbers under the
BlazorCircuitLimitsconfiguration section: a ceiling on concurrently active circuits, a ceiling on disconnected circuits retained for reconnect, and how long a disconnected circuit is retained. - Depends on: nothing first-party;
System.ComponentModel.DataAnnotations.RangeAttributeon all three properties (BlazorCircuitLimitSettings.cs:37,:45,:56) is what makes the settings self-validating. The class doc (:9-15) states it is deliberately separate from UiRateLimitingSettings: the rate limiter bounds how fast requests arrive, while a circuit is state that stays resident on the server for as long as the connection lives, so a caller opening circuits slowly enough to stay inside the rate window still accumulates them without this ceiling. - Concept introduced, sizing an abuse ceiling from the container rather than from traffic. The doc comment on
MaxActiveCircuits(:26-36) derives 200 from the container a Blazor UI host typically runs in (0.25 vCPU, 0.5 GiB): roughly 200 MiB of that half-gibibyte is the runtime, the framework and the static assets the host also serves, leaving on the order of 300 MiB for circuit state, and a MudBlazor page's server-side render tree costs a few hundred kilobytes up to about a megabyte, so 200 fits with headroom on memory and is already generous on the 0.25 vCPU side, where render throughput binds first. It sits far above real demand for a host rendering Interactive Auto, where a returning visitor's session moves to the WebAssembly runtime after the first render and holds no circuit at all: the number is an abuse ceiling, not a capacity plan. [Rubric §29, Resilience & Business Continuity] assesses exactly this: a documented, container-derived ceiling rather than an arbitrary round number. [Rubric §11, Validation] applies through the[Range]attributes that fail startup on an out-of-range value (see BlazorCircuitLimitExtensions). - Walkthrough
SectionName => "BlazorCircuitLimits"(:20) is the configuration section this type binds from.MaxActiveCircuits(:37-38),[Range(1, 100_000)], defaults to200.DisconnectedCircuitMaxRetained(:45-46),[Range(0, 10_000)], defaults to25, tighter than the Blazor framework default of 100 because a retained circuit holds the same state an active one does while serving nobody (:41-43).DisconnectedCircuitRetentionSeconds(:56-57),[Range(5, 3600)], defaults to60, tighter than the framework's three minutes: a visitor who really did drop off Wi-Fi reconnects within seconds, and everything beyond that is memory held for someone who is gone (:49-54). The doc comment says a host whose audience sits on a flaky shared network (a conference venue, where someone walking between rooms should come back to the state they left) raises this back towards the framework's 180 and leans onDisconnectedCircuitMaxRetainedto bound the memory.
- Why it's built this way: the three numbers are kept in one bound, validated options type instead of inline literals so the ceiling can be tuned per environment through configuration without a code change, and so an out-of-range value fails fast at startup via BlazorCircuitLimitExtensions's
ValidateOnStart()rather than silently at runtime. See ADR-088 for the edge-hardening posture this settings type is part of. - Where it's used: bound and registered by BlazorCircuitLimitExtensions's
AddBoundedBlazorCircuits(); read by BoundedCircuitHandler for the active-circuit ceiling and byBlazorCircuitLimitExtensions.RetentionFromfor the disconnected-circuit settings.
UiRateLimitingSettings
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Hardening·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hardening/UiRateLimitingSettings.cs:33· Level 0 · class (sealed)
- What it is: the bound options type for a Blazor Web host's own edge rate limiting, under the
UiRateLimitingconfiguration section: an on/off switch, a per-client-IP request budget and window, and a replica-wide concurrency ceiling. - Depends on: nothing first-party;
RangeAttributeonPermitLimit,WindowSeconds, andGlobalConcurrencyLimit(UiRateLimitingSettings.cs:57,:61,:75). - Concept introduced, a Blazor host's own edge limiter because it is a separate origin from the Gateway. The class doc (
:9-32) states why a UI host needs one at all: the Blazor UI is a separate externally reachable origin from the Gateway (its own FQDN), so the ADR-088 Gateway edge limiter never sees a request to it, and every page load on this origin opens an interactive Server circuit against a typically 0.25 vCPU / 0.5 GiB container. It is shaped like the Gateway's limiter (same per-IP-plus-global-concurrency pairing, anonymous traffic included) but shipped as a distinct kit rather than referenced fromMMCA.Common.Gateway, because a Blazor host is not a reverse proxy and its exemptions differ (it serves/_frameworkand/_contentitself). Both counts are per replica, in memory, the same deliberate trade the Gateway kit makes: an edge limiter answers in microseconds on every request, and a shared counter would put a network round trip in front of the whole site. [Rubric §29, Resilience & Business Continuity] and [Rubric §11, Validation] apply as with BlazorCircuitLimitSettings: a documented, traffic-shape-derived number behind[Range]validation. - Walkthrough
SectionName => "UiRateLimiting"(:36).Enabled(:43), defaulttrue; the doc comment (:39-42) calls out its escape hatch use, a load or capacity proof driven from one runner IP that the per-IP window cannot tell from a flood.PermitLimit(:57-58),[Range(1, 1_000_000)], default300, which no real visitor approaches (a page load costs a handful of requests once static assets are exempt, and Interactive Auto hands the session to WebAssembly after the first render). The doc comment (:48-56) sets it well above a single visitor on purpose because an office or mobile-carrier NAT presents many visitors as one IP, and tells a host whose audience sits behind one address (a venue's wifi, a single corporate egress) to raise it, since the whole crowd arrives as a single partition key. Its "static assets are exempt" claim points at theIsExempt(HttpContext, PathString)overload of UiRateLimitingExtensions (:51), the one that exempts a request whose matched endpoint is a real static asset rather than any path with a file extension.WindowSeconds(:61-62),[Range(1, 3600)], default60.GlobalConcurrencyLimit(:75-76),[Range(1, 1_000_000)], default200: a ceiling rather than a rate, guarding against a slow downstream backing up threads on this replica; excess requests are rejected with 429 immediately rather than queued (:64-74), and unlike the per-IP window it needs no widening for a shared-address audience because in-flight concurrency is bounded by what the container can render, not by how many people share an address. The doc comment (:71-73) also records that the Blazor circuit transport (/_blazor) is excluded from this ceiling: a circuit WebSocket would hold one permit for its whole lifetime, so open circuits are bounded byBlazorCircuitLimits:MaxActiveCircuits(BlazorCircuitLimitSettings) instead.
- Why it's built this way: same rationale as BlazorCircuitLimitSettings, a bound, validated, environment-tunable options type rather than inline literals in UiRateLimitingExtensions. See ADR-088 and ADR-124 for the split between the request concurrency ceiling and the circuit ceiling.
- Where it's used: bound and read by UiRateLimitingExtensions's
AddUiRateLimiting(), which closes over a resolved instance rather thanIOptions<T>per request (see that section).
AuthenticatedNoStoreExtensions
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Hosting·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/AuthenticatedNoStoreExtensions.cs:8· Level 0 · class (static)
- What it is: one middleware,
UseAuthenticatedNoStore(), that marks every HTML response sent to a signed-in user as not storable, so the browser's back-forward cache (bfcache) never restores a logged-in page after sign-out. - Depends on: nothing first-party. Externals: ASP.NET Core
IApplicationBuilder,HttpContext.Response.OnStartingand the typedHeaders.CacheControl/Headers.Pragmaproperties. - Concept introduced, opting authenticated pages out of the bfcache. A browser keeps a frozen snapshot of recently left pages and restores it on Back without asking the server. For a server-rendered app that snapshot is one user's personalized HTML, so a visitor who signs out and presses Back would see the previous session's page. A
Cache-Control: no-storeresponse is not eligible for that cache. The summary (AuthenticatedNoStoreExtensions.cs:12-18) names both effects: a logged-out user never sees the previous logged-in HTML, and authenticated back-navigation always triggers a fresh server render.[Rubric §26, Front-End Security]assesses what a browser retains of sensitive content; here retention is refused for exactly the responses that carry it, while anonymous pages keep the cache's speed. - Walkthrough
UseAuthenticatedNoStore()(:24), in anextension(IApplicationBuilder app)block (:10): registers an inlineapp.Usemiddleware (:26) that does not touch the response itself but registers aResponse.OnStartingcallback (:28), so the decision is made when the headers are about to be sent and the final content type is known.- The condition (
:30-32): the user is authenticated (context.User.Identity?.IsAuthenticated is true) and the response content type starts withtext/html, compared ordinally ignoring case. Only then does it setCache-Controltono-store, no-cache, must-revalidate, max-age=0(:34) andPragma: no-cache(:35). JSON, static assets and anonymous pages pass through untouched. - It calls
next()(:40) and returns the builder for chaining (:43).
- Why it's built this way: gating on
IsAuthenticatedkeeps public pages bfcache-eligible (the remarks at:19-23); theOnStartinghook is what lets one middleware placed early in the pipeline read a content type that is only set later by the component renderer. The remarks require it to run beforeMapRazorComponentsso it wraps every page response. It also has to sit after authentication has populatedHttpContext.Userby the time the response starts, whichOnStartinggives for free. - Where it's used: BlazorWebHostExtensions calls it in
UseMmcaBlazorWebPipelineright afterUseAntiforgery()(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:202), so every composed Blazor head (MMCA.ADC.UI.Web among them) gets it without a line of its own.
E2eRenderMode
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Hosting·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/E2eRenderMode.cs:14· Level 0 · class (static)
- What it is: the single render-mode selector a Blazor head's
App.razorcalls, so every head honors the two E2E switches the AppHost forwards with the same precedence (class doc,E2eRenderMode.cs:9-13). - Depends on: nothing first-party at compile time. Externals:
IConfiguration.GetValue<bool>, Blazor'sRenderMode/IComponentRenderMode, andHttpContext.AcceptsInteractiveRouting()(Microsoft.AspNetCore.Components.Routing). The switches themselves are written by the AppHost helpers in MMCA.Common.Aspire.Hosting (Extensions), which only forward the value (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:501-506). - Concept introduced, one render mode per head, overridable for tests. Production and local development run InteractiveAuto (a Server circuit first, WebAssembly once the bundle is cached); an E2E run sometimes needs to pin one path so that path is what the browser suite exercises. Putting the precedence in one shared class means two heads cannot disagree about which flag wins. See ADR-056 for the render-mode strategy.
[Rubric §28, Front-End Testing]assesses whether the UI can be tested along each of its execution paths; this class is the switch that makes both interactive paths reachable from the same suite. - Walkthrough
ForceWebAssemblyKey(:20):"E2E:ForceWebAssembly"(the AppHost writesE2E__ForceWebAssembly); documented as winning over the server key (:16-19).ForceServerKey(:26):"E2E:ForceServer".Resolve(IConfiguration)(:35): throws on a null configuration, returnsRenderMode.InteractiveWebAssemblywhen the WebAssembly key istrue(:39-42), otherwiseInteractiveServerwhen the server key istrue, otherwiseInteractiveAuto(:44-46). A missing key reads asfalse.Resolve(IConfiguration, HttpContext)(:60): returnsnull(static server rendering) whenhttpContext.AcceptsInteractiveRouting()is false, that is, when the matched page carriesExcludeFromInteractiveRoutingAttribute, otherwise the one-argument result (:65). The doc (:49-56) gives the reason: the framework/Errorpage opts out, and handing it to an interactive router that does not know it answered it with the not-found page.
- Why it's built this way: the request-aware overload exists so a head applies one expression to both its routes and its head outlet and still keeps opt-out pages static. Both overloads are pure functions of configuration (plus the request), which is why
E2eRenderModeTestscan pin the precedence without a host. - Where it's used: MMCA.ADC.UI.Web's
App.razorexposesPageRenderMode => E2eRenderMode.Resolve(Configuration, HttpContext)(MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Components/App.razor:81); the comment above it records that the WebAssembly flag is for local runs only and that CI pins Server mode. Tests:MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Hosting/E2eRenderModeTests.cs.
RazorComponentsEndpointExtensions
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Hosting·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/RazorComponentsEndpointExtensions.cs:10· Level 0 · class (static)
- What it is: endpoint conventions for a head's
MapRazorComponentschain (class doc,RazorComponentsEndpointExtensions.cs:7-9); today one:AllowHead(), which lets every page endpoint answerHEADas well as the methods it already accepts. - Depends on: nothing first-party. Externals:
RazorComponentsEndpointConventionBuilder.Finally,IHttpMethodMetadata/HttpMethodMetadataandHttpMethods.Head. - Concept introduced, an endpoint
Finallyconvention. Endpoint conventions normally run in registration order; aFinallyconvention runs after all of them, so it sees the metadata the endpoint ended up with. The doc (:12-18) states the problem it solves: on .NET 10 a Razor component endpoint listsGETandPOSTexplicitly withoutHEAD, so an uptime probe, link checker or crawler sendingHEAD /gets a 404 for a page aGETrenders; the .NET 11 endpoint already listsHEAD, so there the call changes nothing.[Rubric §9, API & Contract Design]assesses whether HTTP semantics are honored; this restores the rule that a resource answeringGETalso answersHEAD. - Walkthrough
AllowHead(this RazorComponentsEndpointConventionBuilder)(:28): a classicthisextension (not anextension(T)block). It throws on a null builder and registers a staticFinallylambda (:32).- Inside, it takes the last
IHttpMethodMetadataon the endpoint (:34). An endpoint with none, or with an empty method list, already matches every method includingHEAD, so it returns (:35-38). IfHEADis already listed (case-insensitive) it returns (:40-43). - Otherwise it appends a new
HttpMethodMetadatanaming the existing methods plusHEAD, carrying overAcceptCorsPreflight(:45). The remarks (:20-25) note routing honors the last method metadata, so appending is enough and a form page keeps itsPOST. - Returns the builder for chaining (
:48). The server answers theHEADwith theGETresponse's status and headers and no body (:17-18).
- Why it's built this way: reading the final metadata instead of hard-coding
GET, HEADis what keeps form-handling pages'POST, and the no-op on .NET 11 means one call serves both framework lines. - Where it's used: the last call on MMCA.ADC.UI.Web's
MapRazorComponents<App>()chain (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:158); the composed pipeline in BlazorWebHostExtensions leaves theMapRazorComponentschain to the head, so each head adds it there. Tests:MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Hosting/RazorComponentsEndpointExtensionsTests.cs. - Caveats / not-in-source: the "Store manual test Run 4, O9" provenance in the doc (
:16) is a test-log reference, not verifiable from source.
ServiceWorkerEndpointExtensions
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Pwa·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Pwa/ServiceWorkerEndpointExtensions.cs:15· Level 0 · class (static)
- What it is: the one endpoint mapping that turns a Blazor Web host into an installable web app with an offline page:
MapCommonServiceWorker()serves the framework's service worker script at/service-worker.js. The class doc (ServiceWorkerEndpointExtensions.cs:10-14) splits the work three ways: this endpoint is the worker, the browser half is the static asset_content/MMCA.Common.UI.Web/pwa-register.js, and the host itself supplies the app identity (manifest.webmanifest, icons,theme-color). - Depends on: nothing first-party. Externals: ASP.NET Core routing (
IEndpointRouteBuilder,MapGet,RouteHandlerBuilder,Results.Text),IConfiguration, andSystem.Reflectionfor the embedded scripts and the assembly version. The two scripts it serves,Pwa/service-worker.jsandPwa/service-worker-retired.js, are compiled into the assembly as embedded resources under the logical nameMMCA.Common.UI.Web.Pwa.{file}(MMCA.Common.UI.Web.csproj:53). - Concept introduced, a service worker that never caches what a server render personalizes. A service worker is a browser-side script, scoped to the path it was served from, that can intercept every fetch the page makes; that is what makes a site installable and lets it answer offline. It is also a liability on a server-rendered app, because a cached page is a cached copy of one signed-in user's data. The
<remarks>(:38-58) state the three rules this worker is built on.- Never caches pages or data (
:40-46): the worker handles GET navigations only, sends each one to the network with the request's cookies as usual, and falls back to the offline page only when the network fails; API calls, the Blazor circuit, hubs and framework files reach its fetch handler and are left to the browser's default network handling.[Rubric §26, Front-End Security]assesses browser-side data exposure; here the exposure is closed by declining to cache rather than by trying to scope a cache per user. - Updates with every release (
:48-51): the package version is written into the script, so a new framework version is a byte change the browser installs on its next update check, and the new worker deletes the previous version's offline cache. - Kill switch (
:53-57): settingPwa:ServiceWorker:Enabledtofalseserves a worker with no fetch handler that deletes the offline cache. A bad worker stays on a visitor's device until a newer one replaces it, so retiring it is a configuration change rather than a release.[Rubric §29, Resilience & Business Continuity]assesses whether a faulty client-side component can be withdrawn without a deploy; this is that lever.
- Never caches pages or data (
- Walkthrough
ServiceWorkerPath(:18):"/service-worker.js", served from the root so the worker's scope covers the whole site.EnabledKey(:24):"Pwa:ServiceWorker:Enabled", the kill-switch key (:20-23).VersionToken(:26): the placeholder__MMCA_SW_VERSION__replaced with the version at read time.ActiveScriptandRetiredScript(:28,:30):Lazy<string>fields, so each script is read from the manifest and version-stamped once per process.MapCommonServiceWorker()(:60-70), anIEndpointRouteBuilderextension (theextension(IEndpointRouteBuilder)block at:32): mapsGETonServiceWorkerPath, setsCache-Control: no-cacheso the browser revalidates the worker on every update check (:63), readsEnabledKeywith a default oftrueon every request and picks the active or retired script (:64-66), and returns it astext/javascriptin UTF-8 (:67). The endpoint is.AllowAnonymous()(:69), so a host with a fallback authorization policy still serves it to a signed-out visitor, and.ExcludeFromDescription()(:70), so it does not appear in the OpenAPI description. It returns theRouteHandlerBuilderfor further conventions.ReadScript(string)(:73-84): opens the embedded resourceMMCA.Common.UI.Web.Pwa.{fileName}and throwsInvalidOperationExceptionnaming the file and assembly when it is missing (:76-77); resolves the version fromAssemblyInformationalVersionAttribute, thenAssemblyName.Version, then"0"(:80-82); and replaces the token ordinally (:83).
- Why it's built this way: serving the script from an endpoint rather than as a static file is what lets the version be stamped in and the kill switch be read from configuration at request time. Because the setting is read per request rather than at startup, flipping it in configuration retires the worker without rebuilding the image. See ADR-136 for the installable-web-app decision and ADR-106 for the
extension(T)block as the public surface. - Where it's used: MMCA.ADC.UI.Web maps it right after
MapStaticAssets()(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:216), and the UI gallery host does the same (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Gallery/GalleryHost.cs:177).ServiceWorkerEndpointTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Pwa/ServiceWorkerEndpointTests.cs) pins the content type, the no-cache header, the retired script underEnabledKey=falseand the route. - Caveats / not-in-source: the fetch-handler and cache-deletion behavior lives in the two embedded
.jsfiles, which this section describes from the C# doc comment rather than from the scripts themselves.
BoundedCircuitHandler
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Hardening·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hardening/BoundedCircuitHandler.cs:43· Level 1 · class (sealed, partial,CircuitHandler)
- What it is: a Blazor
CircuitHandlerthat refuses a new circuit once this replica already holds BlazorCircuitLimitSettings.MaxActiveCircuitsactive circuits, and counts circuits back down as they close. - Depends on:
CircuitHandler(base class),IOptions<BlazorCircuitLimitSettings>andILogger<BoundedCircuitHandler>(primary-constructor parameters,BoundedCircuitHandler.cs:43-45). - Concept introduced, a singleton counter guarding a per-circuit-scoped hook. The class doc (
:9-40) states why a handler rather thanCircuitOptions:DisconnectedCircuitMaxRetainedbounds only circuits that already dropped their connection, and since every page load on a public Blazor origin opens one (a host rendering Interactive Auto makes the first render a Server circuit), the handler is the documented extension point that sees a circuit being opened and closed. It also states why the class throws rather than returning a refusal value:OnCircuitOpenedAsyncreturnsTaskwith no "refuse" return, so an exception is the only way to stop a circuit starting, one of the few places in the framework where the Result pattern does not apply because the contract belongs to ASP.NET Core. Finally (:31-39) it explains the one piece of per-circuit state on a singleton: the set of admitted circuits, keyed by reference, which exists because a refused circuit is still torn down throughOnCircuitClosedAsync, and without the set that close would release a permit some other circuit holds. [Rubric §29, Resilience & Business Continuity] assesses this directly: an explicit admission-control decision at the point circuits are opened, rather than letting an unbounded flood of circuits exhaust a replica's memory. [Rubric §14, Testability] applies throughActiveCircuits(:55), a public read-only counter the doc comment (:51-54) says exists so a consuming host can assert the ceiling behaves and a diagnostic endpoint can report saturation;BoundedCircuitHandlerTestsreads it to assert the increment, decrement and floor behavior without inspecting private state. - Walkthrough
_admitted(:47): aConcurrentDictionary<Circuit, byte>constructed withReferenceEqualityComparer.Instance, used as a set of the circuits this handler admitted._activeCircuits(:49) andActiveCircuits => Volatile.Read(ref _activeCircuits)(:55): the live count, read withVolatile.Readbecause it is written fromInterlockedcalls on possibly-concurrent circuit-open/close callbacks.Order => int.MaxValue(:61): runs LAST among registered handlers on the way in, so a refusal happens after cheaper handlers have already done their work rather than in the middle of it (:57-60).OnCircuitOpenedAsync(:64-85): guardscircuitagainst null (:66), then increments first and rolls back on refusal (:70-75) rather than checking-then-incrementing, because two simultaneous opens could otherwise both observe the last free slot and both take it; over the ceiling it decrements, logs viaLogCircuitRefused, and returns a faultedTaskcarrying anInvalidOperationExceptiontelling the caller to retry (:75-80). Only an admitted circuit is added to_admitted(:83).OnCircuitClosedAsync(:88-109): guardscircuitagainst null (:90), then returns without touching the count unless_admitted.TryRemovefinds the circuit (:92-98), because the framework's teardown calls every handler's close unconditionally, including for a circuit this handler refused, and that close must not release a permit another circuit holds. An admitted circuit decrements the count, which then floors at zero (:100-106) as a last line of defence against a count driven negative handing out permits forever.LogCircuitRefused(:111-114): a[LoggerMessage]-generated warning logger, partial method paired with thepartial classdeclaration.
- Why it's built this way: see BlazorCircuitLimitSettings for why 200 is the number; this handler is the enforcement point for that ceiling. See ADR-088 and ADR-124.
- Where it's used: registered as a singleton
CircuitHandlerby BlazorCircuitLimitExtensions'sAddBoundedBlazorCircuits(), called from MMCA.ADC.UI.Web's Blazor Server host composition (Program.cs).
MmcaBlazorWebHostOptions
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Hosting·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/MmcaBlazorWebHostOptions.cs:12· Level 1 · class (sealed)
- What it is: the options object for
AddMmcaBlazorWebHost: the values and callbacks that differ between Blazor heads; everything else the composed call registers is shared and fixed (class doc,MmcaBlazorWebHostOptions.cs:8-11). - Depends on: FallbackAuthorizationOptions. Externals:
WebApplicationBuilder,IRazorComponentsBuilder, MudBlazor'sMudServicesConfiguration. - Concept introduced: the "callback at a fixed position" options shape is taught on the consumer, BlazorWebHostExtensions. Each property here is an
init-only hook that runs at one named point of a fixed registration order, so a head customizes without being able to reorder. - Walkthrough
LogFilePath(:18,required): the rolling log path passed toAddCommonSerilog(for examplelogs/MMCAStoreUIWeb.txt); the file sink is skipped in Production (:14-17).ConfigureConfigurationSources(:24): adds configuration sources (Key Vault, for example) and runs first, so every value it adds is seen by the service defaults and the composed call's own reads (:20-23).AfterServiceDefaults(:30): runs immediately afterAddServiceDefaults(), the place for exporters that must follow it (the Azure Monitor exporter) and the shared DataProtection key ring (:26-29).ConfigureRazorComponents(:36): runs on the Razor components builder right after the interactive server components are added; a head with a WebAssembly client passesrc => rc.AddInteractiveWebAssemblyComponents()(:32-35).ConfigureMudServices(:42): configures MudBlazor;nullregisters it with defaults.ConfigureFallbackAuthorization(:48): extends the fallback authorization policy (extra exempt path prefixes, for example);nullkeeps the framework defaults.
- Why it's built this way:
sealedwithinitproperties and onlyLogFilePathrequired, so a head states the one value every host must choose and opts into the rest. - Where it's used: read by
AddMmcaBlazorWebHost(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:75). MMCA.ADC.UI.Web setsLogFilePath,ConfigureConfigurationSources(Key Vault),AfterServiceDefaults(Azure Monitor exporter and DataProtection),ConfigureRazorComponents(WebAssembly components) andConfigureMudServices(snackbar position and cap), and leavesConfigureFallbackAuthorizationunset (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:27-65). Tests:BlazorWebHostExtensionsTestsand theBlazorWebHostHarnessunderMMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Hosting/.
BlazorCircuitLimitExtensions
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Hardening·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hardening/BlazorCircuitLimitExtensions.cs:19· Level 2 · class (static)
- What it is: the registration wiring for BlazorCircuitLimitSettings and BoundedCircuitHandler: an
IServiceCollectionextension that registers the bounded-circuit handler, and a factory method that builds theCircuitOptionsretention callback from configuration. - Depends on: BlazorCircuitLimitSettings, BoundedCircuitHandler; ASP.NET Core's
IServiceCollection,IConfiguration, and Blazor'sCircuitOptions/CircuitHandler. - Concept introduced, a singleton handler counting a state that is really per-circuit. The class doc (
:12-17) states why the two halves are deliberately separate calls: the disconnected-circuit retention isCircuitOptionsonAddInteractiveServerComponents, while the active-circuit ceiling is aCircuitHandlersingleton in the container, and both read the same section so the two numbers cannot drift apart.AddBoundedBlazorCircuits's own doc (:45-49) states why registration isAddSingletonand not scoped: circuit handlers are resolved from each circuit's own scope, so a scoped registration would count to one and cap nothing. [Rubric §29, Resilience & Business Continuity] applies to the retention tightening described under BlazorCircuitLimitSettings; [Rubric §1, SOLID] applies to keeping registration wiring separate from both the settings type and the handler's own logic. - Walkthrough
RetentionFrom(IConfiguration)(:28-41): reads BlazorCircuitLimitSettings from configuration (falling back tonew BlazorCircuitLimitSettings()if the section is absent), and returns anAction<CircuitOptions>that copiesDisconnectedCircuitMaxRetainedand convertsDisconnectedCircuitRetentionSecondsto aTimeSpanforDisconnectedCircuitRetentionPeriod(:37-39).AddBoundedBlazorCircuits()(:51-61), anIServiceCollectionextension: binds and validates BlazorCircuitLimitSettings (:55-58), then registers BoundedCircuitHandler as a singletonCircuitHandler(:60).
- Why it's built this way: keeps circuit-limit registration next to the retention-callback factory, both consumers of the same BlazorCircuitLimitSettings, while the enforcement logic itself stays in BoundedCircuitHandler. See ADR-088.
- Where it's used:
AddBoundedBlazorCircuits()andRetentionFromare both called from MMCA.ADC.UI.Web's Blazor Server host composition (Program.cs).
UiRateLimitingExtensions
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Hardening·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hardening/UiRateLimitingExtensions.cs:27· Level 2 · class (static)
- What it is: the registration and pipeline wiring for a Blazor Web host's edge rate limiter, an
IServiceCollectionextension that builds a chained per-IP-and-global limiter from UiRateLimitingSettings, and anIApplicationBuilderextension that adds it to the pipeline. Every rejection is a 429, carrying aRetry-Afterheader whenever the rejecting limiter can say when to come back. - Depends on: UiRateLimitingSettings; SameOriginApiProxySettings (its
PathPrefix, read through the proxy's own options); RetryAfterRejection fromMMCA.Common.RateLimiting(the sharedOnRejectedwrapper that writesRetry-After,:215); ClientAddressKey fromMMCA.Common.RateLimiting(the per-IP partition key,:135); RemainingWindowFixedWindowRateLimiter fromMMCA.Common.RateLimiting(the per-IP window,:146-154). Externals:System.Threading.RateLimiting(RateLimitPartition,FixedWindowRateLimiterOptions,ConcurrencyLimiterOptions,PartitionedRateLimiter,MetadataName); ASP.NET Core'sAddRateLimiter/RateLimiterOptions/OnRejectedContextandUseRateLimiter;StaticAssetDescriptorfromMicrosoft.AspNetCore.StaticAssets(:6, read off the matched endpoint). The class carries a[SuppressMessage("Naming", "CA1708", ...)]attribute (:23-26) whose justification records why: with multipleextension(T)blocks in one static class, CA1708 flags the compiler-generated grouping members as case-colliding even though no user-visible identifier differs only by case. - Concept introduced, exempting probes and static assets from a per-IP window, and long-lived connections from the concurrency ceiling. The exemption rule has two overloads.
IsExempt(PathString, PathString proxyPathPrefix)(:80-82) is the prefix rule alone: a fixed prefix list (/health,/alive,/_framework,/_content,/hubs,:58) plus the proxied hub path{proxyPathPrefix}/hubs(:82), all matched on whole segments so/healthzis not caught by/health.IsExempt(HttpContext, PathString proxyPathPrefix)(:100-106) adds the static-asset rule: a request is also exempt when the endpoint routing matched carries aStaticAssetDescriptorin its metadata (:105), that is, a real asset mapped byMapStaticAssets. A file extension alone exempts nothing: the doc comment (:66-74) notes that a path such as/missing.pngthat maps to no asset renders the not-found page and is counted like any page route. The second overload's remarks (:92-99) explain why the limiter can see the endpoint at all: aWebApplicationinsertsUseRoutingahead of the whole user pipeline. The ExemptPrefixes doc comment (:46-57) explains the/hubsentry mirrors the Gateway's ownGatewayRateLimiting:BypassPathPrefixesbypass for long-lived SignalR traffic, so a host that ever fronts a hub on this origin is covered by declaration rather than by accident, and that the same hub traffic arriving through the same-origin API proxy (SameOriginApiProxyEndpoint) is exempt at whatever prefix the host configured, not a hard-coded/api/hubs: without it every open hub WebSocket would hold a concurrency lease for its whole lifetime and exhaust the ceiling./_blazoris treated differently on each limiter (:71-74): it has no exemption from the per-IP window, because the negotiate endpoint is exactly what opens a circuit, butBlazorTransportPrefix(:38-44) keeps it out of the concurrency ceiling, because the same prefix carries the circuit WebSocket, whose lease would otherwise be held for the whole circuit lifetime; open circuits are bounded by BlazorCircuitLimitSettings and BoundedCircuitHandler instead. [Rubric §29, Resilience & Business Continuity] applies to the chained limiter design; [Rubric §1, SOLID] applies toIsExempt(HttpContext, PathString)being the single decision both partitions delegate to (:129,:177), so the shared exemption rule cannot drift between the two limiters, with the concurrency partition adding only the transport prefix on top.- A rejection tells the client when to retry.
AddUiRateLimitingassignsRateLimiterOptions.OnRejectedthrough the shared RetryAfterRejection.WithRetryAfterHeader(:215;MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:42-52), so a 429 carriesRetry-Afterin whole seconds rounded up (RetryAfterRejection.cs:27-31) whenever the rejecting lease exposes aMetadataName.RetryAfterhint (RetryAfterRejection.cs:46-49). The per-IP window supplies one; a concurrency rejection does not, so it sends no header (RetryAfterRejection.cs:36-37). That wrapper is one source file compiled as an internal type into each package that registers a limiter (MMCA.Common.API,MMCA.Common.Aspire,MMCA.Common.UI.WebandMMCA.Common.Gateway,RetryAfterRejection.cs:12-18), so this host and the API and Gateway limiters answer a 429 the same way. The per-IP window is a RemainingWindowFixedWindowRateLimiter rather than the framework'sRateLimitPartition.GetFixedWindowLimiter, because, as the comment at:143-145records, the framework limiter's hint is always the whole window, while the wrapper reports the time actually left in it. [Rubric §9, API & Contract Design] assesses whether error responses give a client enough to react correctly; the header turns a bare 429 into a back-off instruction a well-behaved client can follow.
- A rejection tells the client when to retry.
- Walkthrough
ExemptPartitionKey,UnknownIpPartitionKey,ConcurrencyPartitionKey(:30,:33,:36): the three partition keys the limiter buckets requests into.BlazorTransportPrefix(:44):"/_blazor", the Blazor circuit transport (negotiate, the circuit WebSocket and its long-polling fallback), excluded from the concurrency ceiling only.ExemptPrefixes(:58),IsExempt(PathString, PathString)(:80-82) andIsExempt(HttpContext, PathString)(:100-106): the shared exemption rule, detailed above; internal so it is unit-testable viaInternalsVisibleTo(:75-78). TheHttpContextoverload null-guards the context (:102) and delegates the prefix check to thePathStringoverload (:104).ClientIpPartition(HttpContext, UiRateLimitingSettings, PathString, TimeProvider?)(:120-155): no limiter for an exempt request (:129-132); otherwise the partition key isClientAddressKey.For(RemoteIpAddress)(:134-135), the shared key that unmaps an IPv4-mapped address to IPv4 and masks an IPv6 address to its /64 prefix, so a client rotating addresses inside one /64 is still one client (ClientAddressKey,MMCA.Common/Source/Build/RateLimiting/ClientAddressKey.cs:31). No limiter when there is no address to key on (fail open,:136-141, so an in-processTestServeris never collapsed into one shared bucket), otherwiseRateLimitPartition.Getkeyed on that client key, building aRemainingWindowFixedWindowRateLimiteroverFixedWindowRateLimiterOptionswithQueueLimit = 0(rejected immediately, not queued,:146-154). The optionaltimeProvider(:124) is the clock for the remaining-time hint;null, the production value, is the system clock. The options set noAutoReplenishment: the comment (:143-145) records that the partitioned limiter drives replenishment on its own timer either way.ConcurrencyPartition(HttpContext, UiRateLimitingSettings, PathString)(:168-185): the replica-wideConcurrencyLimiter, one bucket for the whole process withQueueLimit = 0, exempt for every requestIsExempt(HttpContext, PathString)matches plus any path underBlazorTransportPrefix(:177).AddUiRateLimiting(IConfiguration)(:196-241), anIServiceCollectionextension: binds and validatesUiRateLimitingSettings(:201-204), then resolves a plain instance from configuration to close over in the partition callbacks (:206-210) rather than resolvingIOptions<T>per request, because the partition callback runs on the hot path of every request and an out-of-range value has already failedValidateOnStart(). Its ownAddRateLimitercall (:212-216) setsRejectionStatusCodeto 429 and wrapsOnRejectedwithRetryAfterRejection.WithRetryAfterHeader(:215); both apply even whenEnabledis false, in which case the method returns early with noGlobalLimiterconfigured (:218-221). Otherwise it configuresRateLimiterOptionsthroughConfigure<IOptions<SameOriginApiProxySettings>>(:226-238), reading the proxy'sPathPrefixfrom the proxy's own options (:229) so the limiter and the proxy cannot disagree, and chains the client-IP and concurrency partitions withPartitionedRateLimiter.CreateChained(:233-237), so a request must satisfy both. The production chain passes noTimeProvider, so the window uses the system clock (:235).UseUiRateLimiting()(:250-254), anIApplicationBuilderextension: calls the framework'sUseRateLimiter().
- Why it's built this way: see UiRateLimitingSettings for the tuning rationale. See ADR-088 for the edge-hardening split between this host and the Gateway, ADR-124 for why circuits are bounded by their own ceiling rather than by this limiter, ADR-131 for the same-origin proxy behind the proxied-hub exemption, and ADR-070 for the
ValidateOnStart()contract the hot-path settings instance relies on. - Where it's used:
AddUiRateLimitingandUseUiRateLimitingare called by BlazorWebHostExtensions (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:96,:187), which MMCA.ADC.UI.Web'sProgram.csreaches throughAddMmcaBlazorWebHost(MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:27); the extension methods live on theIServiceCollection/IApplicationBuilderextension blocks (:187,:244). In MMCA.Common.UI.Web.Tests,UiRateLimitingTestsexercises the exemption rule and the partitions,UiRateLimitingRetryAfterTeststheRetry-Afterheader, andUiRateLimitingStaticAssetPipelineTeststhe static-asset exemption (all underMMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Hardening/).
MmcaBlazorWebPipelineOptions
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Hosting·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/MmcaBlazorWebPipelineOptions.cs:10· Level 3 · class (sealed)
- What it is: the options object for
UseMmcaBlazorWebPipeline: the parts of the request pipeline that differ between Blazor heads (class doc,MmcaBlazorWebPipelineOptions.cs:6-9). - Depends on: ClientConfigBuilder. Externals:
IApplicationBuilder. - Concept introduced: none new; the sibling of MmcaBlazorWebHostOptions for the request pipeline instead of the registration list.
- Walkthrough
DevelopmentPipeline(:17): runs in Development only, at the exception-handler position (outside Development that position isUseExceptionHandler("/Error")). A net10.0 head with a WebAssembly client passesa => a.UseWebAssemblyDebugging(); a net11.0 head passes nothing (:12-16).ClientConfig(:23): adds the head's own sections to the client-config document, the extras callback ofMapClientConfigEndpoint(ClientConfigEndpointExtensions).
- Why it's built this way: both properties are optional and the whole object is optional (
UseMmcaBlazorWebPipeline(MmcaBlazorWebPipelineOptions? options = null)), so a head with no extra client-config sections and no debug proxy passes nothing. TheDevelopmentPipelinesplit follows the dual-framework line: .NET 11 debugs WebAssembly without the debug proxy middleware. - Where it's used: MMCA.ADC.UI.Web passes only
ClientConfigunder#if NET11_0_OR_GREATERand addsDevelopmentPipeline = a => a.UseWebAssemblyDebugging()in the#elsebranch (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:117-127). Tests:MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Hosting/BlazorWebPipelineTests.cs.
BlazorWebHostExtensions
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Hosting·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:44· Level 6 · class (static)
- What it is: the composed Blazor web host: the shared registration list, the shared request pipeline and the shared additional-assembly list every Blazor Server + WebAssembly head repeats, as three calls (class doc,
BlazorWebHostExtensions.cs:32-39). What differs arrives through MmcaBlazorWebHostOptions and MmcaBlazorWebPipelineOptions. - Depends on: ApiEndpointUrl, BlazorCircuitLimitExtensions, UiRateLimitingExtensions, SessionCookieAuthenticationHandler, IForbiddenReExecutionDetector / HttpContextForbiddenReExecutionDetector, ITokenRefresher / SameOriginProxyTokenRefresher, SameOriginApiProxyServiceExtensions, SameOriginApiProxyEndpointExtensions, JwtAuthenticationStateProvider, AuthenticatedNoStoreExtensions, ClientConfigEndpointExtensions, ServiceWorkerEndpointExtensions, IUIModule, and
AddCommonSerilog(SerilogHostExtensions). Externals: MudBlazorAddMudServices, Microsoft.Extensions.Http.ResilienceResilienceHandler, ASP.NET Core antiforgery, authentication and static assets. - Concept introduced, the composed host. A Blazor head's host setup is a long registration and middleware list whose ordering matters (configuration sources before anything reads configuration, the proxy refresher after token storage, the rate limiter ahead of the exception handler, antiforgery after authentication). Holding that list in one framework call fixes the order once and leaves the head only the values that genuinely differ, passed as callbacks that run at named positions. Render-mode registration deliberately stays per head (
ConfigureRazorComponents,DevelopmentPipelineand the head's ownMapRazorComponentschain), so the package takes no WebAssembly server dependency (:36-38).[Rubric §33, Developer Experience]assesses how much a team repeats to stand up a component; here a head's host is three calls plus options.[Rubric §18, UI Architecture]assesses whether UI composition is consistent across apps; the shared pipeline and assembly list are that consistency. See ADR-079 and ADR-067. - Walkthrough
ApiEndpointKey(:46):"Api:ApiEndpoint".AddMmcaBlazorWebHost(MmcaBlazorWebHostOptions)(:75), inextension(WebApplicationBuilder builder)(:48). In order:ConfigureConfigurationSources(:82, first so a vault value is visible to everything below);AddCommonSerilog(options.LogFilePath)(:84);AddServiceDefaults()(:85);AfterServiceDefaults(:86);AddRazorComponents().AddInteractiveServerComponents(...)with the circuit retention read from configuration, thenConfigureRazorComponents(:91-93); bounded circuits and the UI rate limiter (:95-96, ADR-124, ADR-019); MudBlazor with or without the callback (:98-105);AddUIShared, then the private resilience-handler removal, then browser device capabilities (:107-109).- The API endpoint guard (
:114-121):Api:ApiEndpointmust be an absolute http(s) URL or an Aspire service-discovery name (ApiEndpointUrl.IsAbsoluteHttpOrServiceDiscovery), otherwiseInvalidOperationException, so a deployment placeholder fails at boot rather than at the first call. - Auth and session (
:123-130): the server and client session-cookie pair, the trusted-caller header, session-cookie authentication as the default scheme (ADR-022) and the authorization policies with the head's fallback callback. - Token flow (
:134-142): server token storage, thenAddHttpContextAccessorand aReplaceofIForbiddenReExecutionDetectorwith the request-readingHttpContextForbiddenReExecutionDetector(only this server host can see a 403 re-executed to/not-found,:136-139), thenITokenRefresherasSameOriginProxyTokenRefresherand the same-origin API proxy. The proxy is registered after token storage because it replaces the circuit'sITokenRefresherandISessionCookieSync(:132-133); the summary (:63-66) warns a head not to register either afterward, sinceMapCommonSameOriginApiProxyfails the boot when displaced (ADR-051). - Tail (
:144-157):JwtAuthenticationStateProvider, cascading auth state, the distributed memory cache, antiforgery withCookieSecurePolicy.SameAsRequest(:153; the comment at:148-152explains why notAlways: it would refuse tokens on any request seen as http, such as a local container or a probe), then the dynamic Blazor CSP before the security headers whose static default is a TryAdd (:156-157, ADR-023). UseMmcaBlazorWebPipeline(MmcaBlazorWebPipelineOptions? = null)(:181), inextension(WebApplication app)(:163): forwarded headers, security headers, the UI rate limiter (ahead of the exception handler so a throttled request answers 429 without re-rendering a page,:166-168) (:185-187); the Development callback orUseExceptionHandler("/Error", createScopeForErrors: true)(:189-196);UseStatusCodePagesWithReExecute("/not-found")(:198);MapDefaultEndpoints, HTTPS redirection, request localization,UseAuthenticatedNoStore, cookie session refresh, authentication, authorization (:199-205), then antiforgery (:209), placed after authentication because an antiforgery token is bound to the signed-in user, so validating it before the principal is established would refuse every form a signed-in user posts (:207-208); then the client-config endpoint with the head's extras, session-cookie endpoints, the same-origin proxy, the culture endpoint,MapStaticAssets().AllowAnonymous()and the service worker (:211-216).GetMmcaRazorComponentAssemblies(Assembly clientAssembly)(:228): MMCA.Common.UI, MMCA.Common.UI.Web (the shared SSR error page) and the client assembly (:233-238), concatenated with theAssemblyof every registeredIUIModuleand de-duplicated keeping the first occurrence (:243-244).RemoveApiClientResilienceHandler(:263, private): walks the"APIClient"handler list backward throughConfigureAdditionalHttpMessageHandlersand removes everyResilienceHandler(:267-272). The remarks (:255-262) give the reason: the standard handler's 30 s attempt timeout with POST never retried cut large uploads off in Server mode, where the body streams from the browser over the circuit; removing it leaves oneHttpClient.TimeoutofHttpResilienceDefaults.TotalRequestTimeout(90 s, set byAddUIShared) as in WebAssembly and MAUI.RemoveAllResilienceHandlers()is avoided because it is still EXTEXP0001 (experimental).
- Why it's built this way: the order comments in the body are the reason the call exists: each "X before Y" rule is enforced once in the framework instead of in every head. Callbacks rather than overridable registrations keep a head from reordering. The
CA1708suppression on the class (:40-43) is a documented false positive from having twoextension(T)blocks in one static class (ADR-106). - Where it's used: MMCA.ADC.UI.Web's
Program.csis the three calls:builder.AddMmcaBlazorWebHost(new() { ... })(MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:27),app.UseMmcaBlazorWebPipeline(...)(:120,:122) and.AddAdditionalAssemblies(app.GetMmcaRazorComponentAssemblies(...))on its ownMapRazorComponents<App>()chain (:157), with its app-association endpoints mapped in between as the pipeline summary prescribes (BlazorWebHostExtensions.cs:174-177). Tests:BlazorWebHostExtensionsTests,BlazorWebPipelineTestsandBlazorWebHostHarnessunderMMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Hosting/. - Caveats / not-in-source: whether MMCA.Store's head also uses the composed calls is not determinable from this unit's evidence (only MMCA.Common and MMCA.ADC were searched; the
LogFilePathdoc example names a Store log file). TheAddMmcaBlazorWebHostsummary still lists "the web form factor" among the registrations (:60), but the body registers none and noAddCommonWebFormFactorremains in MMCA.Common's source; the registration list above follows the body.
HandoffBody
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SessionHandoffEndpoints.cs:92· Level 0 · record
- What it is: the JSON body both session-handoff endpoints exchange,
{ "handoff": "..." }: a single nullableHandoffstring (SessionHandoffEndpoints.cs:91-92). It is a nestedinternal sealed recordofSessionHandoffEndpoints. - Depends on: nothing first-party.
- Concept: a wire DTO for an opaque, Data-Protection-sealed token; the sealing is taught on
SessionHandoffProtector. - Walkthrough: the token endpoint returns it with a protected access token (
SessionHandoffEndpoints.cs:48); the cookie endpoint binds it from the request body and unprotectsbody.Handoff(SessionHandoffEndpoints.cs:55,62). - Why it's built this way: the property is nullable so a missing or empty body binds instead of failing model binding; the protector then treats null or whitespace as "no handoff" (
SessionHandoffProtector.cs:59-62) and the endpoint answers 400invalid_handoff(SessionHandoffEndpoints.cs:68-71). - Where it's used: only inside
SessionHandoffEndpoints.cs.
ProxyResponseMode
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginProxyTransformer.cs:17· Level 0 · enum
- What it is: how the same-origin proxy treats the upstream response of one forwarded request:
Forward(copy as is),TokenIssuing(a sign-in: move the token pair into the session cookies and strip it from the body),Revoke(a sign-out: copy, then clear the session cookies),ViewAsGrant(a view-as grant, ADR-137: move the token into the overlay cookie and strip it from the body, leaving the session cookies alone) andViewAsEnd(end of a view-as session: copy, then delete the overlay cookie) (SameOriginProxyTransformer.cs:20,23,26,32,35). - Depends on: nothing first-party.
- Concept: a strategy selector passed into the per-request
SameOriginProxyTransformer; see that section for each mode's mechanism. - Walkthrough:
SameOriginApiProxyEndpointpicks the mode inResolveMode(SameOriginApiProxyEndpoint.cs:315-349): every non-POST isForward; a POST to the refresh path yieldsnull(the proxy answers it itself); a POST to a token-issuing path isTokenIssuing; a POST to either sign-out path (RevokePathorRevokeCurrentPath) isRevoke(:330-335); a POST toViewAsEndPathisViewAsEnd(:337-340); a POST whose last segment isview-asisViewAsGrant(:342-346); any other POST isForward. - Why it's built this way: the endpoint decides once per request and the transformer branches on it (
SameOriginProxyTransformer.cs:83,108,115,120), so the request path matching stays in one class and the body rewriting in another. - Where it's used:
SameOriginApiProxyEndpointandSameOriginProxyTransformeronly; it isinternal.
SameOriginApiProxyMarker
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyServiceExtensions.cs:88· Level 0 · class
- What it is: an empty
internal sealed classregistered as a singleton only byAddCommonSameOriginApiProxy(SameOriginApiProxyServiceExtensions.cs:77,88), so other code can ask the container "did this host opt in to the proxy?". - Depends on: nothing.
- Concept: a DI marker service: presence in the container is the signal, the instance carries no state.
- Walkthrough: no members.
- Why it's built this way: checking a private marker type is cheaper and more precise than probing for a public service a host could register for other reasons (for example the options type, which binding alone would create).
- Where it's used:
SameOriginApiProxyEndpointExtensionsthrows when it is absent, naming the missing call (SameOriginApiProxyEndpointExtensions.cs:38-42);ClientConfigEndpointExtensionsreads it to decide whether to publish the proxy's path prefix to the client (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:153,158).
SameOriginApiProxySettings
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxySettings.cs:22· Level 0 · class
- What it is: the options class for the same-origin API proxy, bound from configuration section
SameOriginApiProxy(SameOriginApiProxySettings.cs:25) and validated at startup. - Depends on:
SameSiteMode(ASP.NET Core); first-party only by reference: the gateway address falls back toApiSettings'sApiEndpoint. - Concept: options pattern with fail-fast validation, same shape as the other settings classes in this group (for example
BlazorCspSettingswithBlazorCspSettingsValidator).[Rubric §33, Developer Experience]assesses whether misconfiguration surfaces early and clearly; every knob here has a default, so a host opts in with no configuration at all. - Walkthrough:
DefaultTokenIssuingPaths=auth/login,auth/register,auth/oauth/exchange,auth/sign-in-link/redeem,auth/passkeys/signin(SameOriginApiProxySettings.cs:33): the endpoints whose successful response carries a token pair; sign-in links and passkey sign-in are included because script may not seed the cookies (:27-32).PathPrefix=/api(:40): a request to{PathPrefix}/orders/5is forwarded to{gateway}/orders/5.GatewayAddress(:48): null by default;AddCommonSameOriginApiProxyfills it fromApi:ApiEndpointwhen unset (SameOriginApiProxyServiceExtensions.cs:57-64), so an Aspire discovery name such ashttps+http://gatewayresolves as it does for the host's API clients.AdditionalTokenIssuingPaths(:54): empty; a host adds paths such asauth/2fa/verify.MaxRequestBodySizeByPath(:77): an empty, case-insensitiveIDictionary<string, long>of per-endpoint request body caps in bytes that replace the server default (Kestrel's 30,000,000 bytes). Each key is a gateway-relative path shaped likeRefreshPath(for exampleuploads/file); it covers that path and everything below it on a whole-segment boundary (uploads/filecoversuploads/file/5, notuploads/files), the longest matching key wins, and every other path keeps the server default (:56-76). Without an entry, an upload over the default is refused 413 by this host before a byte reaches the gateway. A key containing/cannot be set from an environment variable, so use a JSON file or another provider that accepts arbitrary keys (:73-75). Enforced bySameOriginApiProxyEndpointand checked bySameOriginApiProxySettingsValidator.RefreshPath=auth/refresh(:84): answered by the proxy itself from the refresh cookie.RevokePath=auth/revoke(:91): forwarded, then the cookies are cleared whatever upstream answered.RevokeCurrentPath=auth/revoke/current(:99): the this-device sign-out the everyday Logout calls, treated exactly likeRevokePath.ViewAsEndPath=auth/view-as/end(:108, ADR-137): forwarded with the view-as overlay's bearer, then the overlay cookie is deleted whatever upstream answered. A POST to any path whose last segment isview-asis a view-as grant whose token goes into the overlay cookie and never reaches script (:101-107).SessionCookieSameSite=SameSiteMode.Strict(:116);Laxis the only other accepted value.
- Why it's built this way: recorded in ADR-131: a WebAssembly client calling the gateway cross-origin cannot carry the HttpOnly session cookie, so tokens end up script-readable; a same-origin proxy on the UI host lets the cookie authenticate data calls instead.
- Where it's used:
SameOriginApiProxyServiceExtensions(binding, and copyingSessionCookieSameSiteontoSessionCookieSettings,SameOriginApiProxyServiceExtensions.cs:69-70),SameOriginApiProxySettingsValidator,SameOriginApiProxyEndpoint,SameOriginApiProxyEndpointExtensionsandClientConfigEndpointExtensions.cs:158.
SameOriginProxyInvoker
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginProxyInvoker.cs:19· Level 0 · class
- What it is: an
IDisposableholder for the oneHttpMessageInvokerYARP's forwarder sends every proxied request through (SameOriginProxyInvoker.cs:19,37). - Depends on:
IServiceDiscoveryHttpMessageHandlerFactory(Microsoft.Extensions.ServiceDiscovery),SocketsHttpHandler, YARP'sReverseProxyPropagator. - Concept: YARP's
IHttpForwarderexpects a long-lived invoker with a transport tuned for proxying, not a pooledHttpClient.[Rubric §12, Performance & Scalability]assesses connection reuse and resource lifetime: one singleton transport is shared by all requests. - Walkthrough:
- The public ctor resolves the optional discovery factory and builds the handler (
SameOriginProxyInvoker.cs:24-31); the invoker is created withdisposeHandler: falseand the class keeps_ownedHandlerto dispose itself (:22,39-43). - An
internalctor takes a test-supplied handler, for example a TestServer's (:34-35); that handler is not owned or disposed. CreateHandler(:45-69) configuresSocketsHttpHandler:UseProxy = false,AllowAutoRedirect = false, no automatic decompression,UseCookies = false, multiple HTTP/2 connections,ConnectTimeout15 s, and aReverseProxyPropagatoroverDistributedContextPropagator.Current(:50-59). When discovery is registered it wraps the transport (:61) sohttps+http://gatewayresolves. The null-out-then-finallypattern disposes the transport only if wrapping throws.
- The public ctor resolves the optional discovery factory and builds the handler (
- Why it's built this way: redirects, cookies and decompression must pass through to the browser untouched, which is why they are all off; the propagator keeps the trace context flowing to the gateway.
- Where it's used: injected into
SameOriginApiProxyEndpoint(SameOriginApiProxyEndpoint.cs:32,430), registered bySameOriginApiProxyServiceExtensions.cs:74, and built from a handler in the test harnessMMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/SameOriginProxy/ProxyTestHarness.cs.
TokenPair
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SessionHandoffProtector.cs:75· Level 0 · record
- What it is: a private nested record
(AccessToken, RefreshToken)ofSessionHandoffProtector(SessionHandoffProtector.cs:75), the plaintext shape serialized to JSON before it is sealed. - Depends on: nothing first-party;
System.Text.Json. - Walkthrough: serialized in
ProtectTokenPair(SessionHandoffProtector.cs:33-34) and deserialized inUnprotectTokenPair, which rejects a null pair or either token blank (:46-49). - Where it's used: only inside
SessionHandoffProtector.cs; callers see a value tuple instead.
ViewAsOverlayTreatment
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginProxyTransformer.cs:39· Level 0 · record struct
- What it is: an
internal readonly record structdescribing what one forwarded request does with the view-as overlay cookie (ADR-137):OverlayPresent,ForwardsOverlayBearer,DeleteOverlayand theSameSitemode to write or delete the cookie with (SameOriginProxyTransformer.cs:38-39). - Depends on:
SameSiteMode(ASP.NET Core); nothing first-party. - Concept: a per-request decision computed once by the endpoint and handed to the transformer, the same split as
ProxyResponseMode. The overlay itself, a short-lived cookie holding a read-only view-as token, isViewAsOverlayCookie. - Walkthrough:
- Built by
ResolveOverlayinSameOriginApiProxyEndpoint(SameOriginApiProxyEndpoint.cs:410-422):OverlayPresentwhen the cookie exists;ForwardsOverlayBearerwhen the overlay is live (unexpired) and the mode is neitherTokenIssuingnorRevoke, in which case the overlay's token replaces the session bearer;DeleteOverlaywhen the cookie is present but no longer live;SameSitecopied fromSameOriginApiProxySettings.SessionCookieSameSite. - Read by
SameOriginProxyTransformerinShouldDeleteOverlay(SameOriginProxyTransformer.cs:164-169) and when writing or deleting the cookie (:103,210);default(all false) means "no overlay", which is the transformer's parameter default (:56). ForwardsOverlayBeareralso turns off the endpoint's 401 capture (SameOriginApiProxyEndpoint.cs:238-239), so a view-as bearer is never refreshed or replayed.
- Built by
- Why it's built this way: the endpoint owns cookie reading and the clock; the transformer stays free of both and only acts on four precomputed values.
- Where it's used:
SameOriginApiProxyEndpointandSameOriginProxyTransformeronly; it isinternal.
SameOriginApiProxySettingsValidator
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxySettingsValidator.cs:16· Level 1 · class
- What it is: the
IValidateOptions<SameOriginApiProxySettings>that fails the boot on an unusable proxy configuration, collecting every failure into one result (SameOriginApiProxySettingsValidator.cs:16,21-69). - Depends on:
SameOriginApiProxySettings;SearchValues<char>,ValidateOptionsResult. - Concept: startup validation via
ValidateOnStart, cross-referenced toBlazorCspSettingsValidator.[Rubric §11, Security]applies to theSameSitecheck: onlyStrictorLaxpass, because the cookie now authenticates data calls (:42-45). - Walkthrough:
ForbiddenPathCharacters={}*?#\(:18): route syntax, query, fragment and backslash.PathPrefixmust passIsValidPrefix(:28-33,71-77): non-blank, longer than one char, starts with/, does not end with/, no whitespace, no forbidden char. It becomes a route pattern, hence the literal-path rule.GatewayAddressmust be an absolute URI with a host (:35-40); the message names theApi:ApiEndpointfallback.RefreshPath,RevokePath,RevokeCurrentPath,ViewAsEndPathand everyAdditionalTokenIssuingPathsentry must passIsValidRelativePath(:47-51,79-84): not blank after trimming/, no whitespace, no forbidden char, no://.- Every
MaxRequestBodySizeByPathentry (:53-66): the key must pass the sameIsValidRelativePath, and the limit must be positive (limit <= 0fails), because a zero or negative cap would refuse every body on that path. Both failures are collected, not short-circuited.
- Why it's built this way: an invalid prefix would otherwise surface as a route-pattern exception or a silently unmatched route at request time; naming the setting at boot is cheaper to diagnose.
- Where it's used: registered with
TryAddEnumerablebySameOriginApiProxyServiceExtensions.cs:66-67.
SessionHandoffProtector
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SessionHandoffProtector.cs:16· Level 1 · class
- What it is: seals tokens with ASP.NET Core Data Protection so the Blazor Server circuit can pass them through browser script without script being able to read or replay them later (
SessionHandoffProtector.cs:16). - Depends on:
IDataProtectionProvider/ITimeLimitedDataProtector(Microsoft.AspNetCore.DataProtection); nestedTokenPair. - Concept introduced, the protected handoff. With the proxy enabled the HttpOnly cookies are the only session store, but a Server circuit runs over a WebSocket where it cannot read cookies on demand, and it may need to seed the cookies after a sign-in. The handoff hops through JS interop carrying an opaque blob that only this server can open, valid for one minute.
[Rubric §26, Front-End Security]assesses keeping credentials out of script-reachable storage: the browser holds ciphertext with a 1-minute lifetime, never a usable bearer. - Walkthrough:
Lifetime= 1 minute, "one fetch plus one interop hop" (:19).- Two purpose-isolated protectors under the root
MMCA.Common.UI.Web.SameOriginProxy.SessionHandoff, one forAccessToken, one forTokenPair(:21-27), so a blob minted for one cannot be opened as the other. ProtectAccessToken/UnprotectAccessToken(:29,31);ProtectTokenPairserializes aTokenPairto JSON (:33-34);UnprotectTokenPairreturns a tuple or null on a missing, blank or malformed pair (:36-55).TryUnprotect(:57-73) maps null or whitespace input, andCryptographicExceptionorFormatException(tampered, expired, wrong purpose, retired key), to null.
- Why it's built this way: see ADR-131. Returning null instead of throwing lets each endpoint answer a clean 401 or 400.
- Where it's used:
SessionHandoffEndpoints,HandoffTokenRefresher,HandoffSessionCookieSync; registered as a singleton atSameOriginApiProxyServiceExtensions.cs:76; tested inMMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/SameOriginProxy/SameOriginApiProxyAuthFlowTests.csandSessionHandoffServicesTests.cs. - Caveats / not-in-source: whether the host's Data Protection key ring is persisted and shared across replicas is host configuration;
AddDataProtection()here (SameOriginApiProxyServiceExtensions.cs:73) adds no persistence. Not determinable from this source.
HandoffSessionCookieSync
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/HandoffSessionServices.cs:53· Level 2 · class
- What it is: the proxy-mode
ISessionCookieSyncfor the Blazor Server circuit: after a sign-in it hands the browser a protected token pair to post back, instead of the raw tokens (HandoffSessionServices.cs:53). - Depends on:
IJSRuntime,SessionHandoffProtector. - Concept: cross-reference
SessionHandoffProtector; it replaces the default sync (compareJsFetchSessionCookieSync). - Walkthrough:
SyncAsynccallsmmcaAuthHandoff.setCookiewithProtectTokenPair(...)(:55-65); the script posts it to/auth/session-cookie/handoff(seeSessionHandoffEndpoints).ClearAsynccallsmmcaAuthCookie.clear(:67-77). Both returnfalsewhen interop is unavailable, as decided by the sharedJsInteropFailure.IsUnavailablefilter (:61,73; the set isInvalidOperationException,JSDisconnectedException,JSException,OperationCanceledException,MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/JsInteropFailure.cs:27-30). - Where it's used: registered with
Replaceas scoped (SameOriginApiProxyServiceExtensions.cs:81) and verified at map time bySameOriginApiProxyEndpointExtensions. - Caveats / not-in-source: the
mmcaAuthHandoff/mmcaAuthCookieJavaScript is not in this C# source and was not read.
HandoffTokenRefresher
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/HandoffSessionServices.cs:15· Level 2 · class
- What it is: the proxy-mode
ISessionAwareTokenRefresher(anITokenRefresher) for the Blazor Server circuit: it gets an access token from the cookie session through a protected handoff (HandoffSessionServices.cs:15). - Depends on:
IJSRuntime,SessionHandoffProtector. - Concept: cross-reference
SessionHandoffProtector; it replaces the default refresher (compareDirectApiTokenRefresher). - Walkthrough:
AcquireAccessTokenAsyncis a thin wrapper that returns theAccessTokenofTryAcquireAccessTokenAsync(:17-18). The latter callsmmcaAuthHandoff.getToken(:25), whose script calls/auth/session/handoffand answers null only for the endpoint's 401. A null handoff yieldsTokenAcquisition.NoSession(:26-29). Otherwise the blob is unprotected server-side (:33): a non-empty token yieldsAcquired, while an empty result (expired handoff, or a key this host does not hold) yieldsUnavailablebecause it says nothing about the session itself (:33-35). Any failure the sharedJsInteropFailure.IsUnavailablefilter accepts (SSR prerender, a disconnected circuit, a cancelled call, or a transient endpoint failure surfacing as aJSException) also yieldsUnavailable(:37-42). - Where it's used: registered with
Replaceas scoped (SameOriginApiProxyServiceExtensions.cs:80); tested inSessionHandoffServicesTests.cs. - Caveats / not-in-source: the JavaScript side is not in this C# source.
SameOriginProxyTransformer
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginProxyTransformer.cs:51· Level 4 · class
- What it is: the per-request YARP
HttpTransformerthat rewrites the outbound request (path, bearer, cookies) and treats the response according to itsProxyResponseModeand itsViewAsOverlayTreatment(SameOriginProxyTransformer.cs:51-58). - Depends on:
ISessionCookieStore,SessionCookieEndpoints(cookie names),ViewAsOverlayCookie,SessionClaimsToken,AuthClaimTypes,SameOriginProxyHeaders; YARPHttpTransformerandRequestUtilities,JwtSecurityTokenHandler, ASP.NET Core Data ProtectionIDataProtectionProvider(passed to the overlay cookie write,:57,212), andTimeProvider.System, whose current instant the overlay cookie's lifetime is measured from (:212). - Concept:
[Rubric §26, Front-End Security](credentials kept out of script): neither the token pair from a sign-in nor the token from a view-as grant reaches the browser body, and the cookie jar's token copies never reach the upstream. - Walkthrough:
TransformRequestAsync(:66-88): runs YARP's default, strips the prefix to build the destination URI (:74-77), setsAuthorization: Bearerfrom the bearer it was given (the session's or the view-as overlay's) or removes it (:79), drops the CSRF header (:80), removes the session and overlay cookies (:81), and inTokenIssuingorViewAsGrantmode clearsAccept-Encodingso the body arrives as plain JSON (:83-87).TransformResponseAsync(:90-127): whencaptureUnauthorizedis on and upstream answered 401, setsUnauthorizedCapturedand copies nothing so the endpoint can replay (:95-99); deletes the overlay cookie whenShouldDeleteOverlaysays so (:103-106); inRevokeclears the session cookies whatever upstream said (:108-113); inTokenIssuingon success hands off toCompleteTokenIssuingAsync(:115-118); inViewAsGranton success rewrites the body into the overlay (:120-124).CompleteTokenIssuingAsync/IssuedSession(:135-157): only a 200 or 201 opened a session and has its body rewritten; any other success (a 202 for a registration that awaits confirmation) is copied through withno-storeand no cookie written (:147-149).ShouldDeleteOverlay(:164-169): only when an overlay is present, and then when the endpoint marked it for deletion (expired, or a value that does not unprotect), onViewAsEndorRevoke, on a sign-in that opened a session, or on an upstream 401 to the overlay's bearer. A view-as token is never refreshed or replayed.RewriteViewAsResponseAsync/TryMoveViewAsTokenToOverlay(:177-215): writes the token to the overlay cookie through the Data Protection provider with its JWT expiry and the current instant fromTimeProvider.System(:212), so the cookie lives for the time the token has left and is not written at all when that is zero or less (ViewAsOverlayCookie.cs:131-143), and replacesaccessTokenwith its claims-only form, leaving the session cookies alone so the staff user's own session survives the view.TryReadViewAsExpiry(:269-288) accepts only a readable JWT carrying both the view-as actor and grant claims; anything else passes through with no cookie written.RewriteTokenResponseAsync/TryMoveTokensToCookies(:223-262): parses the JSON case-insensitively, writes both tokens to the cookie store (:258), replacesaccessTokenwith its claims-only form and emptiesrefreshToken(:259-260), and setsno-store(:230-234). A body without a token pair passes through unchanged.RemoveSessionCookies(:299-317): filters only the access, refresh and overlay cookie pairs (:60-61) from theCookieheader; other cookies pass.
- Why it's built this way: the browser-facing JSON keeps its shape, so a client written for the non-proxy mode still parses a well-formed response (
:218-221). - Where it's used: created per request by
SameOriginApiProxyEndpoint(SameOriginApiProxyEndpoint.cs:424-425).
SameOriginApiProxyEndpoint
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:30· Level 5 · class
- What it is: the request handler behind
{PathPrefix}/{**path}: gates the request, resolves the session from the cookies, forwards to the gateway with a bearer, and refreshes and replays once on an unexpected 401 (SameOriginApiProxyEndpoint.cs:30-37,73-122); it also raises or lowers the request body cap per path fromSameOriginApiProxySettings.MaxRequestBodySizeByPathbefore the forward (:92,375-392), and swaps in the view-as overlay's bearer while a read-only view-as session (ADR-137) is live (:101,410-422). - Depends on: YARP
IHttpForwarder, ASP.NET Core Data ProtectionIDataProtectionProvider(reads the protected overlay cookie and hands the provider to the transformer,:35,413,425,449),SameOriginProxyInvoker,ICookieSessionRefresherwithSessionRefreshOutcome/SessionRefreshStatus,ISessionCookieStore,ViewAsOverlayCookie,SameOriginApiProxySettings,SameOriginProxyTransformer,ViewAsOverlayTreatment,SessionClaimsToken. - Concept introduced, a Backend-for-Frontend proxy. The UI host forwards same-origin calls to the gateway, so the browser's cookie authenticates them and the bearer is attached server-side.
[Rubric §26, Front-End Security]assesses CSRF and origin defenses: a same-origin gate and a CSRF header gate run before anything is forwarded.[Rubric §29, Resilience & Business Continuity]assesses graceful degradation: an undecided refresh answers 503 withRetry-Afterand keeps the session. - Walkthrough:
- Config:
RequestConfiguses a 100 s activity timeout and HTTP/1.1 withRequestVersionOrLower(:48-53), which lets YARP turn an HTTP/2 WebSocket into an HTTP/1.1 upgrade;DefaultRetryAfter5 s (:56);_tokenIssuingPathsmerges the defaults and additions case-insensitively (:59-63);_bodySizeLimitsholds the configured(PathString, long)caps ordered longest path first, so the most specific entry wins (:65-71);ViewAsGrantSegment=view-asnames the last path segment of the view-as grant action (:42-43). InvokeAsync(:73-122): disables status code pages so a proxied empty 401/404 is not replaced by an HTML page (:77-82); runsTryAnswerBeforeForwardingAsync; normalizes the gateway-relative path and callsApplyBodySizeLimit(:89-92), safe because nothing above has read the body and the forward is the first read; resolves the mode, withnullmeaningRefreshLocallyAsync(:94-99); callsResolveOverlay(:101), and only when the overlay's bearer is not forwarded, for non-sign-in requests that carry a session cookie, callsValidateOrRefreshAsyncand fails viaFailRefreshAsyncwhen no session results (:102-113); forwards with 401 capture decided byCapturesUnauthorized(:115-116); replays on capture (:118-121).ResolveOverlay(:410-422): builds theViewAsOverlayTreatment. The overlay counts as live only whenViewAsOverlayCookie.TryReadunprotects it with the Data Protection provider and it has not expired (:413). A live overlay's token replaces the session bearer for every mode exceptTokenIssuing(anonymous) andRevoke(which signs the staff user's own session out); an overlay that is present but not live (expired, or a value that does not unprotect, such as one planted by the browser) is marked for deletion and the session takes over (:420).CapturesUnauthorized(:238-239): only a session bearer on a replayable request earns one refresh-and-replay; a view-as bearer refused upstream is never refreshed or replayed (the transformer drops the overlay instead).ApplyBodySizeLimit(:375-392): returns untouched when no limits are configured orIHttpMaxRequestBodySizeFeatureis absent or read-only (the body has started being read); otherwise the first entry whose path covers the request on a whole segment, case-insensitively, setsMaxRequestBodySize. This is what stops an upload the API accepts being refused 413 by the UI host first.- Gates, in order (
TryAnswerBeforeForwardingAsync,:254-283):CrossOriginRejection(403cross_origin_rejected);OPTIONSanswered 204 locally, never forwarded, so no preflight reaches the gateway and no CORS grant is made (:267-272); the other methods are forwarded with the browser'sOriginintact becauseSameOriginProxyTransformerkeeps YARP's default header copy, so the gateway's CORS middleware still sees them; unsafe methods other than an HTTP/2 WebSocket CONNECT need the CSRF header (403csrf_header_required).HasCsrfHeaderrequires exactly one header value equal toSameOriginProxyHeaders's value (:127-130). CrossOriginRejection(:148-154):OriginRejectionrefuses a foreignOriginand an upgrade with noOrigin(:197-205);IsOwnOrigincompares scheme and server against the request as seen after forwarded headers, refusing paths, user info and thenullorigin (:163-177);FetchSiteRejectionallowssame-origin, andnoneonly on a non-upgrade GET or HEAD (:207-224).IsWebSocketExtendedConnectdetects RFC 8441 CONNECT (:186-189).IsReplayable(:232-234): GET, HEAD or OPTIONS and not an upgrade, so nothing with a body is re-sent.FailRefreshAsync(:298-309):Rejectedends the session (clear cookies, 401session_expired,:286-290); anything else answers 503session_refresh_unavailablewithRetry-Afterfrom upstream or 5 s.RefreshAndReplayAsync(:356-367): resets status to 200, forcesRefreshAsync, forwards again without capture.RefreshLocallyAsync(:444-479): under a live view-as overlay (one that unprotects and has not expired) answers with the overlay's claims-only token and expiry and rotates nothing, since the overlay is never renewed (:449-461); otherwise rotates from the refresh cookie and answers the sign-in shape with a claims-only access token, empty refresh token and the expiry,no-store.- Four
[LoggerMessage]warnings (:481-491);ForwardAsynclogs a forward error only if the client did not abort (:427-437).
- Config:
- Why it's built this way: ADR-131 records the decision; the gateway stays the API edge and authorizes the forwarded bearer.
- Where it's used: mapped by
SameOriginApiProxyEndpointExtensions; itsHasCsrfHeaderis reused bySessionHandoffEndpoints(SessionHandoffEndpoints.cs:32,62); registered as a singleton atSameOriginApiProxyServiceExtensions.cs:76.
SameOriginApiProxyServiceExtensions
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyServiceExtensions.cs:37· Level 6 · class
- What it is: the opt-in registration,
services.AddCommonSameOriginApiProxy(configuration)(SameOriginApiProxyServiceExtensions.cs:52), written as a C#extension(IServiceCollection)block (see C#extension(T)types). - Depends on: every proxy type above;
ApiSettings,SessionCookieSettings,ITokenRefresher,ISessionCookieSync; YARPAddHttpForwarder, Data Protection. - Walkthrough:
- Binds
SameOriginApiProxySettings, post-configures the gateway fromApi:ApiEndpointwhen unset,ValidateOnStart(:56-66), and adds the validator (:67-68). - Configures
SessionCookieSettings: onlySameSite, taken from the proxy settings (:70-71). Nothing else on the cookie settings is set here. AddHttpForwarder,AddDataProtection(:73-74); singletons for the invoker, endpoint, protector andSameOriginApiProxyMarker(:75-78).Replaces the scopedITokenRefresherandISessionCookieSyncwithHandoffTokenRefresherandHandoffSessionCookieSync(:80-81).
- Binds
- Why it's built this way: opt-in per host; a host that never calls it is unchanged (ADR-131).
Replacemeans call order matters, whichMapCommonSameOriginApiProxychecks. - Where it's used: paired with
SameOriginApiProxyEndpointExtensions; exercised inMMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/SameOriginProxy/SameOriginApiProxyOptInTests.cs. - Caveats / not-in-source: which consumer hosts call it is not determinable from this source (no call site under
MMCA.Common/Sourceother than its own pairing).
SessionHandoffEndpoints
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SessionHandoffEndpoints.cs:17· Level 6 · class
- What it is: maps the two Blazor Server circuit handoff endpoints,
POST /auth/session/handoffandPOST /auth/session-cookie/handoff(SessionHandoffEndpoints.cs:19-20,22). - Depends on:
ICookieSessionRefresher,ISessionCookieStore,ViewAsOverlayCookie,SessionHandoffProtector,SameOriginApiProxyEndpoint(HasCsrfHeader),HandoffBody,SessionCookieSettings(theSameSitemode the overlay is deleted with); ASP.NET Core Data ProtectionIDataProtectionProvider, injected into the token handoff handler (:29), andIOptions<SessionCookieSettings>, injected into the cookie handoff handler (:60). - Walkthrough:
- Token handoff (
:24-52): requires the CSRF header (else 403,:32-35); while a live view-as overlay (ADR-137) is present, answers aHandoffBodywith the overlay's protected token so the circuit holds what the page is viewing as, never refreshed (:37-43); otherwise callsGetOrRefreshAsyncon the cookie session and answers 401no_sessionor aHandoffBodywith a protected access token (:45-48). An overlay that has expired, or whose value does not unprotect with the Data Protection provider, falls through to the session (:40). - Cookie handoff (
:54-88): requires the CSRF header (:62-65), unprotects the token pair (400invalid_handoffon failure,:67-71), writes the cookies (:73), deletes a view-as overlay cookie when one is present (:79-82), and answers 204 (:84). The new session replaces the one the overlay was taken under, as the proxy's token-issuing responses do: an overlay left in place would still win for prerender,session/tokenand the token handoff, and open the new session on the viewed account (:75-78). - Both are
ExcludeFromDescription,AllowAnonymous,DisableAntiforgery; the CSRF header is the gate.
- Token handoff (
- Where it's used: called from
MapCommonSameOriginApiProxy(SameOriginApiProxyEndpointExtensions.cs:54); reached from the browser byHandoffTokenRefresherandHandoffSessionCookieSyncthrough their JS interop.
SameOriginApiProxyEndpointExtensions
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.SameOriginProxy·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpointExtensions.cs:15· Level 15 · class
- What it is:
endpoints.MapCommonSameOriginApiProxy()(SameOriginApiProxyEndpointExtensions.cs:33), which maps{PathPrefix}/{**path}for every method (WebSocket upgrades included) plus the handoff endpoints, after checking the registrations. - Depends on:
SameOriginApiProxyMarker,SameOriginApiProxySettings,SameOriginApiProxyEndpoint,SessionHandoffEndpoints,HandoffTokenRefresher,HandoffSessionCookieSync. - Concept: fail-fast wiring checks.
[Rubric §33, Developer Experience]: a wrong registration order fails the boot with a message naming the fix rather than silently leaking tokens. - Walkthrough:
- Throws
InvalidOperationExceptionif the marker is absent (:38-42). VerifyCircuitRegistrations(:64-69) resolvesITokenRefresherandISessionCookieSyncin a scope; a resolved type other than the handoff implementation throws, telling the host to callAddCommonSameOriginApiProxyafter every such registration (:71-92). A missing dependency such asIJSRuntime(no interactive Server circuit) skips the check (:79-83).- Maps the proxy route to
proxy.InvokeAsyncasExcludeFromDescription,AllowAnonymous,DisableAntiforgery(:49-52), thenSessionHandoffEndpoints.Map(:54).
- Throws
- Why it's built this way: a later
ITokenRefresherregistration would put the access token back in the page on every Server-circuit hydration (:59-63); the doc comment asks hosts to map it afterUseAuthorization(:19-26). - Where it's used: by consumer hosts that opted in. Not determinable from this source which hosts do.
ApiEndpointUrl
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Security·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Security/ApiEndpointUrl.cs:12· Level 0 · class (internal, static)
- What it is: the one shared test for whether a configured API endpoint value is usable, applied by the Content-Security-Policy provider, the
/client-configendpoint and the Blazor Web host registration, so a deployment placeholder such asSET-VIA-ENVIRONMENT-VARIABLEis refused the same way everywhere instead of booting a client against a non-URL (class doc,ApiEndpointUrl.cs:5-11). - Depends on: nothing first-party. Externals: BCL
Uri(Uri.TryCreate,Uri.UriSchemeHttp,Uri.UriSchemeHttps),System.Diagnostics.CodeAnalysis(NotNullWhenAttribute). - Concept introduced, one definition of "a usable endpoint" for every consumer of the same keys. The fail-fast configuration contract of ADR-070 asks that a misconfigured setting be caught at startup or at its first use, with one meaning. Three call sites read
Api:ApiEndpointandApi:WasmApiEndpoint; when each wrote its own check they could disagree about what a placeholder is. This class is the single answer, and it is strict about scheme: a value only qualifies whenUri.TryCreate(..., UriKind.Absolute, ...)succeeds AND the scheme is http or https (ApiEndpointUrl.cs:37-39), because on Linux a rooted path such as/relative/pathparses as an absolutefile://URI (doc, lines 27-30).[Rubric §26, Front-End Security]assesses browser-side hardening: the CSP'sconnect-srcorigin is derived from a value this class has already accepted, so a non-http(s) string never becomes a policy source.
- Walkthrough
TryParseAbsoluteHttp(string? value, out Uri? uri)(lines 35-47) rejects null or whitespace, then requires an absolute parse with an http(s) scheme; on success it hands back the parsedUri([NotNullWhen(true)], line 35), otherwiseuriis null.IsAbsoluteHttp(string? value)(line 52) is the boolean form of the same test.IsAbsoluteHttpOrServiceDiscovery(string? value)(lines 63-74) accepts everythingIsAbsoluteHttpdoes, plus an Aspire service-discovery URL whose scheme is a+-joined list made only of http and https, such ashttps+http://gateway(lines 70-73). The doc (lines 54-60) scopes it: that form is valid only for the server head'sApi:ApiEndpoint, whichIHttpClientFactoryclients resolve through the service-discovery handlerAddServiceDefaults()adds; a browser cannot, soApi:WasmApiEndpointusesIsAbsoluteHttp.IsHttpScheme(lines 76-78) compares the scheme toUri.UriSchemeHttpandUri.UriSchemeHttpswithStringComparison.OrdinalIgnoreCase.
- Why it's built this way: a static, internal helper keeps the rule in one place without widening the package's public API, and splitting the browser form from the server form encodes the real difference (who can resolve a service-discovery name) instead of letting the looser test leak into the browser configuration.
- Where it's used: BlazorCspPolicyProvider calls
TryParseAbsoluteHttpto pinconnect-src(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Security/BlazorCspPolicyProvider.cs:55); ClientConfigEndpointExtensions.MapClientConfigEndpointthrows whenApi:WasmApiEndpointfailsIsAbsoluteHttp(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:88-95); BlazorWebHostExtensions throws at registration whenApi:ApiEndpointfailsIsAbsoluteHttpOrServiceDiscovery(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:114-121). Pinned byApiEndpointUrlTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Security/ApiEndpointUrlTests.cs).
TrustedCallerHandler
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Security·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Security/TrustedCallerHandler.cs:35· Level 0 · class (sealed,DelegatingHandler)
- What it is: an outgoing
HttpClienthandler that stamps a shared-secret header onto a request only when the request targets the configured gateway origin, so the gateway can trust that the call came from this app rather than from an arbitrary caller. - Depends on: nothing first-party. Externals:
System.Net.Http(DelegatingHandler,HttpRequestMessage,HttpResponseMessage), BCLUri. - Concept introduced, an edge-trust header scoped to origin match, not applied blindly.
[Rubric §11, Security]assesses whether a trust signal is bounded to the audience it is meant for. The constructor takes a header name, a shared secret, and the gateway origin (TrustedCallerHandler.cs:39), andSendAsynconly stamps the header when the outgoing request's scheme, host, and port match that origin (TrustedCallerHandler.cs:57-63); a request to any other destination goes out unmodified, so the secret cannot leak to a third-party origin the sameHttpClienthappens to call. ADR-088 is the policy this enforces on the client side. - Walkthrough
- The constructor (
TrustedCallerHandler.cs:39-48) null/blank-guardsheaderNameandsecretand null-guardsgatewayOrigin, storing all three as readonly fields. SendAsync(TrustedCallerHandler.cs:51-72) null-guards the request, then comparesrequest.RequestUriagainst_gatewayOriginwithUri.CompareoverUriComponents.Scheme | UriComponents.HostAndPort, case-insensitive (TrustedCallerHandler.cs:57-63). On a match it removes any existing value for the header and adds exactly one viaTryAddWithoutValidation(TrustedCallerHandler.cs:67-68); the comment (TrustedCallerHandler.cs:65-66) explains the replace-not-append choice, the gateway compares one header value in constant time, so a second value would silently fail the comparison. It then callsbase.SendAsyncunconditionally.
- The constructor (
- Why it's built this way: a
DelegatingHandlercomposes into the existingHttpClientpipeline without every call site having to remember to add the header itself, and gating on origin means the same registered handler is safe to reuse on a client that also talks to other hosts. - Where it's used: registered in
MMCA.Common.UI.Web's DependencyInjection (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/DependencyInjection.cs); its behavior is pinned byTrustedCallerHandlerTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Security/TrustedCallerHandlerTests.cs).
BlazorCspSettings
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Security·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Security/BlazorCspSettings.cs:18· Level 0 · class (sealed)
- What it is: the bindable options type for an opt-in
frame-srcallowance on the Blazor host's Content-Security-Policy, one string list of origins a page may embed in an<iframe>(BlazorCspSettings.cs:23-35). - Depends on: nothing first-party. It is read by BlazorCspPolicyProvider through
BuildFrameSrcand validated at startup by BlazorCspSettingsValidator. Externals:Microsoft.Extensions.Optionsbinding conventions (BCLIList<string>). - Concept introduced, an empty default that changes nothing.
[Rubric §26, Front-End Security]assesses whether a security-relevant default stays strict until a deployment explicitly opts out.SectionName = "BlazorCsp"(line 28) names the configuration section;FrameSources(line 42) initializes to an empty list, so an unconfigured host emits noframe-srcdirective at all and the policy stays byte-identical to the pre-existing baseline (comment, lines 30-33). Only a deployment that needs to embed a specific third-party origin (the doc comment's example is a map provider's embed endpoint, lines 30-31) adds entries.- The doc comment (lines 33-40) states the origin shape a configured entry must satisfy: an absolute
httpsorigin with no path, query, fragment, user info, wildcard, quote, semicolon, comma or whitespace, so the field carries the contract BlazorCspSettingsValidator enforces rather than leaving it implicit.
- The doc comment (lines 33-40) states the origin shape a configured entry must satisfy: an absolute
- Walkthrough: two members:
SectionName(line 28, apublic const string) andFrameSources(line 42,public IList<string>initialized to[]). - Why it's built this way: a settings class bound through
IOptions<BlazorCspSettings>fits the same registration and validation pipeline every other options type in the host uses, so addingframe-srcsupport did not need a new configuration mechanism, only a new section. - Where it's used: bound and validated in
MMCA.Common.UI.Web's DependencyInjection (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/DependencyInjection.cs), consumed by BlazorCspPolicyProvider's constructor asIOptions<BlazorCspSettings>.
BrowserOriginHandler
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Services/BrowserOriginHandler.cs:32· Level 0 · class (internal sealed,DelegatingHandler)
- What it is: an outgoing
HttpClienthandler that stamps the visitor's browser origin (X-Forwarded-Forwith its address,User-Agentwith its user-agent) on the server-side"APIClient"calls a Blazor Server host makes for that visitor (BrowserOriginHandler.cs:5-11). Without it the API would see this host's own address for every visitor, and the host's HTTP client sends no user-agent at all. - Depends on: nothing first-party. Externals:
Microsoft.AspNetCore.Http(IHttpContextAccessor,ConnectionInfo.RemoteIpAddress),System.Net.Http(DelegatingHandler,HttpRequestMessage). - Concept introduced, per-client policy keyed on the visitor rather than the host.
[Rubric §11, Security]assesses whether a trust or rate-limit signal is attributed to the right principal. The API keys the registration rate limit, the session's recorded IP and the recorded device on the caller; behind a Blazor Server host every caller would collapse onto the host's address. The handler copies two values from the HTTP request that carries the work (the page request during prerender, the connection the circuit was established on afterwards,BrowserOriginHandler.cs:14-17). The address isRemoteIpAddress, which has already passed through this host's forwarded-headers middleware, so it is only as far back as the host trusts its own proxies, and a client-suppliedX-Forwarded-Foris never copied verbatim (BrowserOriginHandler.cs:16-19). - Walkthrough
- The primary constructor (line 32) takes
IHttpContextAccessor, an async-local that crosses the handler's own DI scope (parameter doc, lines 30-31). Two internal constants name the headers:ForwardedForHeaderName(line 35) andUserAgentHeaderName(line 38). SendAsync(lines 41-55) null-guards the request, readshttpContextAccessor.HttpContext(line 47) and, only when a request is in scope, callsReplacefor the connection's remote address (line 50) and the request'sUser-Agent(line 51), then callsbase.SendAsyncunconditionally (line 54). With no visitor behind the call (a background job) nothing is sent.Replace(lines 57-68) returns early on a null or blank value (lines 59-62), so a blank user-agent is not forwarded; otherwise it removes any existing header (line 66) and adds exactly one value viaTryAddWithoutValidation(line 67). The comment (lines 64-65) gives the reason for skipping validation: a real browser user-agent does not always parse as a strict product-token list, and neither value needs parsing on this side.
- The primary constructor (line 32) takes
- Why it's built this way: a
DelegatingHandlercomposes into the named client's pipeline without any call site remembering to add the headers, and replace-not-append keeps each header single-valued so a caller cannot smuggle a second value in. It is the same shape as TrustedCallerHandler, but unconditional on origin because the target is always this app's own API. - Where it's used: registered transient and attached to the
"APIClient"named client byAddCommonServerTokenStorage()in theMMCA.Common.UI.WebDependencyInjection (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/DependencyInjection.cs:46-47); only a Blazor Server host calls that, because the WebAssembly client reaches the API through the same-origin proxy, which forwards the browser's own headers (BrowserOriginHandler.cs:23-28). Pinned byBrowserOriginHandlerTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Services/BrowserOriginHandlerTests.cs).
BlazorCspSettingsValidator
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Security·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Security/BlazorCspSettingsValidator.cs:13· Level 1 · class (internal, sealed)
- What it is: the startup
IValidateOptions<BlazorCspSettings>that rejects aframe-srcorigin the moment it is misshapen, so a bad entry fails fast rather than silently reaching the CSP header. - Depends on: first-party: BlazorCspSettings (the options type it validates). Externals:
Microsoft.Extensions.Options(IValidateOptions<T>,ValidateOptionsResult), BCLSearchValues<char>,Uri. - Concept introduced, an explicit character denylist plus a shape check, not a regex. The fail-fast configuration contract of ADR-070 (Website/docs-src/adr/070-fail-fast-configuration-contract.md) assesses whether a misconfigured setting is caught at startup instead of at request time.
Validate(lines 21-31) runs every configuredFrameSourcesentry throughIsValidOriginand fails the whole registration with one message per bad entry (lines 26-30) rather than starting the host on a policy it cannot honor.ForbiddenCharacters(line 18, aSearchValues<char>over*'";,@?#) is the set that could either break out of a CSP source expression or widen it, plus the URL delimiters (user info, query, fragment) a plain origin never carries.IsValidOrigin(lines 21-25 of the walkthrough below) rejects on that set before it ever callsUri.TryCreate, so a value crafted to look like a URL but carrying a CSP metacharacter never reaches the parser.[Rubric §26, Front-End Security]assesses browser-side hardening; this validator is what keeps BlazorCspSettings's contract (an absolute https origin, no path, wildcard, or delimiter) a checked invariant instead of a comment.
- Walkthrough
Validate(string? name, BlazorCspSettings options)(lines 21-31) null-guardsoptions, projects every entry that failsIsValidOrigininto a message naming the section, the entry, and the shape it must satisfy (lines 26-30), and returnsValidateOptionsResult.Successonly when that list is empty.IsValidOrigin(string? source)(lines 34-49),internal static: rejects null, whitespace-only, any entry containing whitespace, anything matchingForbiddenCharacters, or anythingUri.TryCreatecannot parse as absolute (lines 36-41). What remains must behttps(ordinal case-insensitive), have a non-empty host, and havePathAndQueryequal to exactly"/"(lines 46-48); the comment (lines 44-45) notes the forbidden set already rules out user info, a query, and a fragment, so a root-only path is the last thing separating an origin from a full URL.ToOrigin(string source)(lines 55-56),internal static:new Uri(source, UriKind.Absolute).GetLeftPart(UriPartial.Authority), the canonicalscheme://host[:port]form used to splice a validated entry into the CSP header, lower-cased host, default port dropped, no trailing slash.
- Why it's built this way: an explicit character denylist checked before parsing is stricter than trusting
Urialone, becauseUriwill happily parse strings a CSP source expression cannot safely contain; failing every bad entry at once (rather than the first) gives a deployment the whole list of what to fix in one pass. - Where it's used: registered alongside BlazorCspSettings in
MMCA.Common.UI.Web's DependencyInjection (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/DependencyInjection.cs);ToOriginis reused by BlazorCspPolicyProvider'sBuildFrameSrcto canonicalize an already-validated entry.
HttpContextForbiddenReExecutionDetector
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Services/HttpContextForbiddenReExecutionDetector.cs:18· Level 1 · class (internal, sealed)
- What it is: the Blazor Web host's IForbiddenReExecutionDetector. It reads the status code of the request being rendered, so the shared not-found page can tell a 403 that status-code-pages re-executed to
/not-foundfrom a genuine missing page and render the Access Denied view instead of "Page Not Found" (class doc,HttpContextForbiddenReExecutionDetector.cs:6-10). - Depends on: first-party: IForbiddenReExecutionDetector (the contract, line 18,
MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/IForbiddenReExecutionDetector.cs:17). Externals:Microsoft.AspNetCore.Http(IHttpContextAccessor,StatusCodes). - Concept introduced, a status only the server render can see. Status-code-pages re-execution keeps the original status on the response, so a 403 re-executed to
/not-foundis still 403 while that page renders (lines 8-9). Only a host with a live request can read it, which is why the shared UI package registers an always-false default (NoForbiddenReExecutionDetector,TryAddSingletonatMMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:262) and this server-side reader replaces it. During static server renderingIHttpContextAccessorreturns the request being rendered; with no request in scope the answer isfalse, and an interactive circuit's connection request never carries a 403 (a refused connection opens no circuit), so an interactive render keeps rendering Page Not Found (lines 11-16).[Rubric §11, Security]assesses whether an authorization refusal is reported honestly: a user denied a page sees that access was denied rather than being told the page does not exist.
- Walkthrough
- The constructor (lines 24-28) null-guards and stores the
IHttpContextAccessor. IsForbiddenReExecution(lines 31-32) is_httpContextAccessor.HttpContext?.Response.StatusCode == StatusCodes.Status403Forbidden: a null context compares asfalse.
- The constructor (lines 24-28) null-guards and stores the
- Why it's built this way: the page lives in
MMCA.Common.UI, which depends on Shared only and must run under WebAssembly and MAUI, so it cannot touchHttpContext; an interface with a false default there and anHttpContextreader in the server host keeps the page head-agnostic. - Where it's used: registered by BlazorWebHostExtensions with
services.Replace(ServiceDescriptor.Singleton<IForbiddenReExecutionDetector, HttpContextForbiddenReExecutionDetector>())right afterAddHttpContextAccessor()(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:136-139); read by the shared not-found page (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/NotFound.razor:6,:55). Pinned byHttpContextForbiddenReExecutionDetectorTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Services/HttpContextForbiddenReExecutionDetectorTests.cs).
BlazorCspPolicyProvider
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Security·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Security/BlazorCspPolicyProvider.cs:28· Level 2 · class (internal, sealed)
- What it is: the Content-Security-Policy provider for a Blazor Web host. It computes one CSP string at construction, pinning
connect-srcto'self'plus the configured API or Gateway origin (https and its matching WebSocket origin), optionally adding an opt-inframe-srcdirective, and hands the result to the shared security-headers middleware on every request. - Depends on: first-party: ICspPolicyProvider (the contract it implements, line 28), CspPolicy (the value it returns, a policy string plus an
Enforceflag), SecurityHeadersMiddleware (its only consumer, named in the class doc at line 12), ApiSettings (the endpoint source, injected asIOptions<ApiSettings>, line 34), ApiEndpointUrl (the shared endpoint test,TryParseAbsoluteHttp, line 55), and BlazorCspSettings (the frame-src source, injected asIOptions<BlazorCspSettings>, line 35) whose entries it canonicalizes with BlazorCspSettingsValidator.ToOrigin(line 90). Externals:Microsoft.Extensions.Options(IOptions<T>),Microsoft.AspNetCore.Hosting(IWebHostEnvironment),Microsoft.AspNetCore.Http(HttpContext), BCLUri. - Concept introduced, a computed CSP that fails closed.
[Rubric §26, Front-End Security]assesses whether the browser is told which origins may load scripts and open connections. A static CSP cannot express "this deployment's API origin", because that origin is configuration, so the policy is built rather than hard-coded. The two directives that matter for exfiltration are locked:script-src 'self' 'wasm-unsafe-eval'(line 102, where the WASM allowance is what lets the Blazor WebAssembly runtime instantiate) and the computedconnect-src(line 65). The load-bearing decision is what happens when the origin cannot be determined. The provider narrowsconnect-srcto'self', keeps the rest of the policy unchanged, and stays enforced (Enforce: true, line 59). A misconfigured endpoint therefore surfaces immediately as blocked API calls in the browser console rather than as a permissive header that protects nothing and that nobody notices, and the class doc states the reasoning outright: a security response header that quietly stops being enforced is the worse failure mode (lines 16-20).[Rubric §11, Security]assesses the wider defense posture; this class is one control in a chain that also includes the session-cookie auth design and the security-headers middleware, and it is deliberatelyinternal(line 28) so the only supported way to get it is the registration call, not a hand-wirednew.frame-srcis opt-in and null-safe. BlazorCspSettings's default is an emptyFrameSourceslist, andBuildFrameSrc(line 82) returnsnullwhen it is empty (lines 84-87), which keeps the policy byte-identical to the baseline for every deployment that has not opted in (comment, lines 79-81; class doc, lines 21-24).
- Walkthrough
_policy(line 31) is a singleCspPolicyfield computed once. The constructor (lines 33-42) null-guardsapiOptions,cspOptions, andenvironmentand callsBuildCsp(apiOptions.Value, BuildFrameSrc(cspOptions.Value), environment.IsDevelopment())(line 41). Because the type is registered as a singleton, this runs exactly once per process.GetPolicy(HttpContext context)(line 45) ignores the context and returns the cached policy, so the per-request cost is a field read.BuildCsp(lines 49-77) takes the pre-computedframeSrcas a parameter and resolves the endpoint asapi.WasmApiEndpoint ?? api.ApiEndpoint(line 51). The guard on line 55 delegates to ApiEndpointUrl.TryParseAbsoluteHttp, the same test/client-configandAddMmcaBlazorWebHostapply to those keys (comment, lines 53-54): it rejects a blank value, a non-absolute URI, and any scheme that is not http or https, which matters on Linux, where a rooted path such as/relative/pathparses as an absolutefile://URI. A rejected endpoint returns the enforcedconnect-src 'self'policy, still carryingframeSrc(line 59).- With a valid endpoint it derives
originviaapiUri.GetLeftPart(UriPartial.Authority)(line 63,scheme://host:port), pickswssorwsto match (line 64), and composesconnect-src 'self' {origin} {wsScheme}://{authority}(line 65). The WebSocket origin is there for the SignalR notification hub, so the live push channel is allowed without openingconnect-srcto the world. - Development only (lines 71-74) appends
http://localhost:*andws://localhost:*for Visual Studio Browser Link and Hot Reload, whose ports change per run (comment, lines 67-70); the production policy is untouched. BuildFrameSrc(BlazorCspSettings settings)(lines 82-94) returnsnullon an emptyFrameSources(lines 84-87), so the directive is omitted entirely rather than emitted empty; otherwise it maps every entry through BlazorCspSettingsValidator.ToOrigin, de-duplicates withStringComparer.OrdinalIgnoreCase(lines 89-91), and joins the result into"frame-src 'self' {origins}"(line 93). The comment (lines 79-81) notes every entry already passed the startup validator, so canonicalization here cannot fail.BuildPolicy(lines 100-110) takesframeSrcas a parameter and assembles the directive list:default-src 'self', thescript-srcabove plus'unsafe-inline'in Development only (line 102, for the injected Hot Reload bootstrap),style-src 'self' 'unsafe-inline',img-src 'self' data: https:(line 104, deliberately open because profile pictures and content images come from arbitrary external hosts, per the comment on lines 96-99),font-src 'self', the computedconnect-src, theframe-srcdirective when non-null (line 107, spliced in with its own trailing"; "so a null value leaves the rest of the policy unchanged),base-uri 'self',form-action 'self', andframe-ancestors 'none'(line 110, clickjacking protection).
- Why it's built this way: computing once and caching keeps the hot path free, and returning a CspPolicy record rather than writing a header directly keeps the provider testable and lets one middleware own header emission. Registering it with
AddSingleton(notTryAdd) is what makes it replace the default static provider, which is why the ordering rule in the class doc (lines 25-26) matters: callAddCommonBlazorCsp()beforeAddCommonSecurityHeaders.frame-srcis threaded through as a plainstring?parameter rather than read a second time insideBuildPolicy, so the policy string is built from one pass over its inputs. Delegating the endpoint test to ApiEndpointUrl means the CSP cannot accept a value the host registration or/client-configwould refuse. - Where it's used: registered by
AddCommonBlazorCsp()in theMMCA.Common.UI.WebDependencyInjection withAddSingleton<ICspPolicyProvider, BlazorCspPolicyProvider>(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/DependencyInjection.cs:66-76, whose XML doc, lines 53-58, describes the enforcedconnect-src 'self'fallback); the policy it returns is emitted by SecurityHeadersMiddleware. The class doc notes it was hoisted out of the app Blazor Web hosts where it had been byte-identical (line 25). Pinned byBlazorCspPolicyProviderTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Security/BlazorCspPolicyProviderTests.cs).
ServerTokenStorageService
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web.Services·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Services/ServerTokenStorageService.cs:48· Level 5 · class (sealed)
- What it is: the Blazor Server implementation of ISessionAwareTokenStorage, the ITokenStorageService that can also report a held session ending and renew a token the API rejected: a cookie-only token store with no
localStorage. During SSR prerender it reads the access token from the HttpOnly session cookie; on the live interactive circuit it holds the access token in memory only and re-acquires it from those cookies through the registered refresher (the same-origin/auth/session/tokenendpoint, or the protected/auth/session/handoffwhen the same-origin API proxy is enabled, class doc lines 14-15). The refresh token is never readable from JavaScript. - Depends on: first-party: ISessionAwareTokenStorage (the contract, line 53; it extends ITokenStorageService with the
SessionEndedevent and the defaultedRenewRejectedAccessTokenAsync,MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/ISessionAwareTokenStorage.cs:12-37), CookieTokenReader (reads the access and refresh cookies off the request), ISessionCookieSync (seeds and clears the HttpOnly cookies, and reports whether the write succeeded), ITokenRefresher (acquires a fresh access token from the session cookies), JwtTokenInfo (client-side freshness check, and the shared 30-secondDefaultExpirySkew,MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/JwtTokenInfo.cs:24), and ISessionAwareTokenRefresher with its TokenAcquisition result (AccessToken,IsUnavailable), the optional refresher capability that tells a definitive "no session" from an unavailable one (ServerTokenStorageService.cs:260-270). Its WASM sibling is WasmTokenStorageService (named in the class doc, line 17). Externals:Microsoft.AspNetCore.Http(IHttpContextAccessor,HttpContext),Microsoft.AspNetCore.SignalR(HubMetadata), BCLLock,TimeProvider,Interlocked,Volatile,Task,TimeSpan,EventHandler,InvalidOperationException. - Concept introduced, the two-world token store (SSR request versus interactive circuit). A Blazor Web page runs twice: first as a server-side prerender inside a live HTTP request, where an
HttpContextexists and JS interop does not, and then as a stateful circuit whoseHttpContextis not null but is only the request that opened the hub connection, sent before any sign-in on that circuit and never updated, so its cookie is stale by construction (class doc, lines 29-41). One store has to serve both worlds, and this class decides which source of truth applies inTryAnswerFromCookie(lines 306-334, called at line 90), which looks at whether anHttpContextexists and whether memory has yet become authoritative.- Cookie-first answer (
TryAnswerFromCookie, lines 306-334): when anHttpContextexists and memory is not yet authoritative, the request's HttpOnly cookie is read viacookieTokenReader.ReadAccessToken()(line 315). On a page request being prerendered (notIsHubConnection, line 319) the cookie wins outright, because the middleware may have just refreshed it in place on this navigation. On the request that opened the Blazor Server hub connection (IsHubConnection, lines 341-343, recognized by SignalRHubMetadataor a WebSocket request) the cookie is only the session the circuit started with: a cookie token there marks the session as held (lines 328-331), and the cookie answers only when absent or still fresh (JwtTokenInfo.IsFreshwithJwtTokenInfo.DefaultExpirySkew, line 333); an expired one is never handed back, since it would 401 every call for the life of the circuit, and the refresher re-acquires instead. - Interactive circuit (lines 95-133): the token lives in the
_accessTokenfield (line 61). IfJwtTokenInfo.IsFresh(_accessToken, JwtTokenInfo.DefaultExpirySkew)(line 96) says it survives the 30-second skew (the one shared value,JwtTokenInfo.cs:24, so the storages and the preference calls that read the bearer themselves never disagree), it is returned as is; otherwise it is re-acquired, unless a recent definitive "no session" answer is still remembered (the anonymous grace, below). [Rubric §26, Front-End Security]assesses how credentials are held in the browser. This is a deliberate XSS-hardening design: the long-lived refresh token stays in an HttpOnly cookie unreachable from script, the access token exists only in circuit memory and is never persisted, and the refresh token transits JS exactly once, for the same-origin POST that seeds the cookies at login, as protected handoff ciphertext when the same-origin API proxy is enabled (SetTokensAsync, comment lines 192-196).[Rubric §11, Security]assesses the wider auth model; this store is one edge of the browser session-cookie design (ADR-022) and of the client token lifecycle (ADR-051), the piece that decides where a bearer token is read on each side of the prerender boundary.- Login fails loudly, logout stays best-effort. The two cookie writes are deliberately asymmetric.
SetTokensAsyncthrowsInvalidOperationException("The session cookie could not be written.")whenSyncAsyncreturnsfalse(lines 197-200), after the in-memory token is already set, so AuthUIService reportsAuth.TokenStorageUnavailableinstead of a login that looks successful and then silently signs out at the first access-token expiry, when no cookie exists to refresh from (comment above the sync call).ClearTokensAsyncdiscards the boolean (_ = await sessionCookieSync.ClearAsync(), line 214), because logout is best-effort by contract (IAuthUIService.LogoutAsyncnever fails); a caller that needs proof the session ended usesIAuthUIService.RevokeAllSessionsAsync(comment above it). - Anonymous grace, so a signed-out visitor costs one token round trip, not one per API call.
AnonymousGraceis a 15-secondstatic readonly TimeSpan(line 56). When a hydrate returns no token and the refresher did not report itself unavailable,HydrateAsyncsets_anonymousUntil = now + AnonymousGrace(line 283);GetAccessTokenAsyncthen answers null from memory while_accessToken is nulland the clock is before_anonymousUntil(line 101).SetTokensAsyncresets_anonymousUntil(line 188) so a login right after anonymous browsing does not wait out the grace, and a session created in another tab is seen within the window (class doc, lines 19-28). Only a DEFINITIVE answer starts it: a refresher implementingISessionAwareTokenRefresherreports a 429, a 5xx, a dropped connection or unavailable interop as unavailable (comment, lines 248-251), so the next read hydrates again instead of treating a signed-in user as anonymous; a refresher without that capability keeps the earlier reading, where null means "no session" (lines 267-270). - Session ended on the server, so the circuit signs out (A-34). The
volatile_sessionHeldflag (line 83) records whether the circuit holds a session: it is set by a login (line 191), by a hydrate that acquired a token (lines 286-289), by a hub-connection cookie that carried one (lines 328-331) and by a rejected-token renewal (line 167), and cleared by a logout (line 210). When a hydrate gets a definitive "no session" (definitiveNoSession, line 265, only possible from anISessionAwareTokenRefresherwhose answer is null and not unavailable) while_sessionHeldis true, it clears the flag and raisesSessionEnded(lines 290-296, event declared at line 86). A plain refresher's null still starts the grace but is not proof enough to sign a held session out (comment, lines 254-255), and a transient failure leaves the flag alone (field doc, lines 78-82). - A 401 renews the rejected token once. A still-fresh token can be refused by the API (a locked account, a revoked session), and without a renewal path the circuit would stay signed in behind 401s until the token expired (
ISessionAwareTokenStorage.cs:31-36). AuthDelegatingHandler reports the rejected token toRenewRejectedAccessTokenAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthDelegatingHandler.cs:391); this store drops it and runs one hydrate through the same single-flight a stale token takes, so a definitive "no session" ends the session exactly as an expired token's refresh does (remarks, lines 136-143).
- Cookie-first answer (
- Walkthrough
- The primary constructor (lines 48-53) takes
IHttpContextAccessor, CookieTokenReader, ISessionCookieSync, and ITokenRefresher, and a nullableTimeProviderwith no default value (a null falls back toTimeProvider.System, line 59). It is the type's only constructor. The type issealedand carries no app-specific state, which is why it could be hoisted out of the app Blazor Web hosts (class doc, lines 16-17). - Fields:
AnonymousGrace(line 56, astatic readonly TimeSpanof 15 seconds), theLock _hydrateSync(line 58, the .NET 9+ dedicated lock object),_timeProvider(line 59,timeProvider ?? TimeProvider.System), the in-memory_accessToken(line 61),_hydrateInFlight(line 62, the shared acquisition task),_anonymousUntil(line 63, the end of the remembered "no session" answer),_tokenVersion(line 70, bumped by every login and logout so a stale hydrate can be recognized), thevolatile_memoryIsAuthoritative(line 76, set once this instance has stored, cleared or hydrated a token, which only happens on the circuit, so from then on memory wins over the connection request's stale cookie) and thevolatile_sessionHeld(line 83). The class holds no expiry-skew field of its own: both freshness checks (lines 96 and 333) pass the sharedJwtTokenInfo.DefaultExpirySkew(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/JwtTokenInfo.cs:24). The publicSessionEndedevent (line 86) implements the ISessionAwareTokenStorage member. GetAccessTokenAsync(lines 88-133): the cookie-first branch (TryAnswerFromCookie, line 90), the freshness check (line 96), the anonymous-grace short-circuit (line 101), then the single-flight guard._hydrateInFlight ??= HydrateAsync()executes insidelock (_hydrateSync)(lines 111-115) and the resulting task is copied to a local before the lock is released, because two callers could otherwise each start a hydrate and the later completion would overwrite the other's token;HydrateAsyncreaches its first await immediately, so nothing slow runs under the lock. Thefinally(from line 121) clears_hydrateInFlightonly when it is still reference-equal to the task this caller awaited (line 127), so a newer hydrate started after this one completed is not dropped, which would split the next set of callers again.RenewRejectedAccessTokenAsync(string rejectedAccessToken)(lines 144-173): throws on a null or blank argument (line 146), then, under_hydrateSync(lines 149-170), works out which token the store holds: the cookie's while anHttpContextexists and memory is not authoritative, otherwise_accessToken(lines 152-153). A held token that differs from the rejected one (already replaced, or never held here) is returned unchanged (lines 154-157), and so is a rejection during the SSR prerender, where no JS interop exists to refresh with (lines 159-162). Otherwise it nulls the token, clears_anonymousUntil, marks memory authoritative so the stale cookie never answers again, marks the session held (lines 164-167), joins or starts the shared hydrate (lines 168-169), and awaits it throughAwaitHydrateAsync(line 172).GetRefreshTokenAsync(lines 175-182): returnscookieTokenReader.ReadRefreshToken()(line 180) whenever anHttpContextexists, the live request during SSR and, on the circuit, the hub-connection request whose cookie can be as stale as the class remarks describe; otherwisenull. The refresh token is never held in memory. It wraps the value inTask.FromResultrather than beingasync.SetTokensAsync(lines 184-201): bumps_tokenVersion(line 187), resets_anonymousUntil(line 188), caches the access token in memory, marks memory authoritative (line 190) and the session held (line 191), then awaitssessionCookieSync.SyncAsync(accessToken, refreshToken)and throws when it reports failure (lines 197-200).ClearTokensAsync(lines 203-221): bumps_tokenVersion(line 205), nulls the in-memory token, marks memory authoritative (line 209) so a logout is not undone by the connection request's cookie, clears_sessionHeld(line 210) so the logout itself never raisesSessionEnded, awaitssessionCookieSync.ClearAsync()with its result explicitly discarded (line 214), then bumps the version a second time (line 219) and nulls the token again, so a hydrate that started during the clear and read the session being removed has its answer discarded, or dropped if it already landed.AwaitHydrateAsync(Task<string?> inFlight)(lines 228-244): the renewal path's copy of the guarded await, clearing_hydrateInFlightunder the lock only when it is still reference-equal to the awaited task (line 238).HydrateAsync(lines 246-299): snapshots_tokenVersion(line 256), then, when the refresher is anISessionAwareTokenRefresher, callsTryAcquireAccessTokenAsync()(line 262) and keeps the token, theIsUnavailableflag and the deriveddefinitiveNoSession(line 265); otherwise it callsAcquireAccessTokenAsync()(line 269). If the version moved while the acquisition was in flight (a login or logout landed), the stale answer and its grace are discarded and the current_accessTokenis returned (lines 272-275). Otherwise the token is cached, memory is marked authoritative (line 279), a null token withunavailablefalse starts the grace (lines 281-284), and the session-held bookkeeping runs (lines 286-296): a token marks the session held, a definitive "no session" for a held session raisesSessionEnded. Every await on the hydrate path usesConfigureAwait(false)(lines 119, 232, 262, 269), the library posture the cookie-write awaits do not take.
- The primary constructor (lines 48-53) takes
- Why it's built this way: Blazor Server's split lifecycle breaks the naive "read a token from storage" store, which would either fail during prerender (no JS) or leak the refresh token to script if it used
localStorage. Branching onHttpContextpresence and keeping the refresh token cookie-only resolves both. The locked single-flight is the correction of a real concurrency defect in the simpler??=version, and it is worth reading as a small case study in why "good enough" atomicity on a circuit is not good enough; the 401 renewal reuses that same single-flight rather than opening a second refresh path. Surfacing a failed cookie write at login, while tolerating one at logout, puts the failure where the user can still act on it. The 15-second anonymous grace trades a short staleness window for not paying a token round trip on every API call of a signed-out visitor, and it never remembers a transient failure.SessionEndedexists so a session that ended on the server does not leave the circuit rendering as signed in; only a definitive answer for a session the circuit actually held raises it, so neither an anonymous visitor nor a transient outage signs anyone out. See ADR-022. - Where it's used: registered as the scoped ITokenStorageService by
AddCommonServerTokenStorage()in theMMCA.Common.UI.WebDependencyInjection (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/DependencyInjection.cs:40-49); consumer hosts call that instead of shipping their own copy, and BlazorWebHostExtensions calls it for every host built withAddMmcaBlazorWebHost(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:134). The same call registers BrowserOriginHandler on the"APIClient"pipeline (lines 47-48). JwtAuthenticationStateProvider subscribes toSessionEndedwhen the registered storage is session-aware (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/JwtAuthenticationStateProvider.cs:52, handlerOnSessionEndedat line 145) to sign the circuit out. Pinned byServerTokenStorageServiceTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Services/ServerTokenStorageServiceTests.cs). - Caveats / not-in-source: the cookie names, lifetimes, and the
/auth/session/tokenand/auth/session/handoffendpoints themselves are not in this file; they live in theMMCA.Common.APIsession-cookie plumbing and the same-origin proxy referenced by the doc comment (lines 9-47).
AppLockInertBackground
MMCA.Common.UI ·
MMCA.Common.UI.Components.Capabilities·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Capabilities/AppLockInertBackground.cs:15· Level 1 · class (internal sealed)
- What it is: the small JS-interop helper that makes everything outside the app-lock overlay inert while BiometricGate is locked, and lifts that again on unlock. It wraps one lazily imported module,
./_content/MMCA.Common.UI/app-lock.js(ModulePath,AppLockInertBackground.cs:18), and remembers whether its last apply landed (IsApplied,:23). - Depends on:
IJSRuntime(primary constructor,:15),ElementReference,IAsyncDisposable, and the internal LazyJsModule import wrapper (:20). The JS side exportsinertOutsideandrelease(wwwroot/app-lock.js:12,:32). - Concept introduced, a modal that blocks the page behind it, not only the Tab key.
[Rubric §21, Accessibility]assesses whether a modal surface really is the only thing a keyboard or assistive-technology user can reach. A focus trap keeps Tab inside the panel, but programmatic focus and a screen reader's virtual cursor can still reach the page underneath; the script header (app-lock.js:1-8) records that theinertattribute removes that page from both, while leaving the lock root itself live. It also leaves an element that was already inert alone and never releases it later, so the helper never undoes someone else'sinert. - Walkthrough
ApplyAsync(ElementReference lockRoot)(AppLockInertBackground.cs:28-44) imports the module throughGetOrImportAsync(:32), callsinertOutsidewith the overlay wrapper (:33) and only then setsIsApplied(:34).JSDisconnectedException(circuit gone) andJSException(the browser refused) are both swallowed (:36-43): the comment at:42notes the focus trap still holds Tab inside the panel when the inert call fails.ReleaseAsync()(:48-69) returns at once when nothing was applied (:50-53), clearsIsAppliedbefore the call (:55), invokesrelease(:59) and tolerates the same two exceptions (:61-68).DisposeAsync()(:72-87) releases, then disposes the module (:76-77), again tolerating a disconnected circuit or a shutdown-time interop race (:79-86).
- Why it's built this way: every call is best effort and never throws, which is what lets BiometricGate call it from
OnAfterRenderAsync, from unlock and sign-out, and fire and forget its disposal from a synchronousDispose(bool)(BiometricGate.razor.cs:103-108). KeepingIsAppliedmeans a release with nothing applied costs no interop call at all. - Where it's used: only BiometricGate, which creates it lazily through its
InertBackgroundproperty (BiometricGate.razor.cs:48); pinned throughBiometricGateTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Capabilities/BiometricGateTests.cs).
ViewAsBanner
MMCA.Common.UI ·
MMCA.Common.UI.Components.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/ViewAsBanner.razor.cs:23· Level 1 · class (partial component)
- What it is: the banner the shared layout shows while a support user is viewing the app as another account (ADR-137,
Website/docs-src/adr/137-read-only-view-as-support-access.md). It names the viewed account, counts down the time left on the view-as token, and ends the session when the countdown reaches zero.MainLayout.razor:87renders it unconditionally; it renders its content only when the principal is a view-as principal. - Depends on: the cascading
Task<AuthenticationState>(ViewAsBanner.razor.cs:36),IStringLocalizer<SharedResource>(SharedResource,:38),IJSRuntime(:39), theIsViewAsextension on ClaimsPrincipalExtensions (ClaimsPrincipalExtensions.cs:170), and ComponentLifetimeExtensions forLifetimeToken()(ViewAsBanner.razor.cs:104,:134). Externals:PeriodicTimer,CancellationTokenSource. - Concept introduced, a time-boxed elevated session that ends itself.
[Rubric §11, Security]assesses whether delegated or impersonated access is visible to the person using it and bounded in time. The banner reads the remaining lifetime straight from the token'sexpclaim, so the countdown shows the same deadline the server enforces, and it calls the end endpoint itself once that deadline passes rather than waiting for the next refused request. - Walkthrough
ApiPathPrefix(ViewAsBanner.razor.cs:34) is the same-origin proxy prefix,/apiwhen unset (:134).Remaining(ClaimsPrincipal?, DateTimeOffset)(:48-58) is public and static, so it is testable without rendering: it parsesexpas invariant Unix seconds (:50-51), returnsnullwhen the claim is missing or unreadable (:53), and clamps a past expiry toTimeSpan.Zero(:56-57).OnParametersSetAsync(:70-76) sets_viewAsfromIsViewAs()(:73), takes the display name fromIdentity.Nameor theClaimTypes.Nameclaim (:74), and turns the remaining time into an absolute_expiresAt(:75).OnAfterRender(:79-87) starts a one-secondPeriodicTimeron the first render, only for a view-as principal and only whenRendererInfo.IsInteractive(:82); the comment (:81) records that a prerender shows the starting value only.FormatRemaining(:89-98) renders the time left asmm:ss(:97), never negative.TickAsync(:100-122) re-renders every tick (:106) and, once_expiresAthas passed, dispatchesEndAsyncand stops (:107-111). Cancellation and anObjectDisposedExceptionbetween ticks both end the loop quietly (:114-121).EndAsync(:124-141) is guarded by_ending(:126-131) and calls themmcaViewAs.endscript with{prefix}/auth/view-as/end(:134). Any failure that JsInteropFailure.IsUnavailableclassifies as interop being unavailable (anInvalidOperationException,JSDisconnectedException,JSExceptionorOperationCanceledException,JsInteropFailure.cs:27-31) resets_ending(ViewAsBanner.razor.cs:136-140): the comment records that the page is reloading or the circuit is gone and the overlay expires on its own.DisposeAsync(:61-67) cancels the token source, disposes the timer and the source.
- Why it's built this way: computing the deadline once and re-rendering against the clock keeps the countdown honest across a slow render, and the guard on
_endingkeeps a late tick from posting the end request twice. - Where it's used: the shared
MainLayout(MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/MainLayout.razor:87); pinned byViewAsComponentTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/ViewAsComponentTests.cs). Its sibling ViewAsButton starts the session it describes. - Caveats / not-in-source: where the
mmcaViewAsscript object is defined, and what it does after the end request, is not shown in this code-behind.
ViewAsButton
MMCA.Common.UI ·
MMCA.Common.UI.Components.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/ViewAsButton.razor.cs:24· Level 1 · class (partial component)
- What it is: the admin control that starts a read-only view-as session for one account (ADR-137,
Website/docs-src/adr/137-read-only-view-as-support-access.md). It shows only to a caller holding the view-as permission, asks for a written reason, and posts the start request through a small script that reloads the app on success. - Depends on: the cascading
Task<AuthenticationState>(ViewAsButton.razor.cs:48),IStringLocalizer<SharedResource>(SharedResource,:50),IJSRuntime(:51), AdministrationPermissions.ViewAsUsersand theHasPermissionClaimandIsViewAsextensions on ClaimsPrincipalExtensions (ViewAsButton.razor.cs:59;ClaimsPrincipalExtensions.cs:128,:137), and JsInteropFailure for the interop-failure filter (ViewAsButton.razor.cs:97). The default route names the app's UsersAdminControllerBase<TUserDto> subclass (doc comment,ViewAsButton.razor.cs:41-44). - Concept introduced, an elevated action that must state its purpose.
[Rubric §11, Security]assesses whether privileged support access is gated by a permission and leaves an accountable trail. The button is hidden from anyone withoutViewAsUsersand from a caller already in a view-as session (:59), so view-as cannot be chained; and the request carries a reason of 10 to 500 characters after trimming (ReasonIsValid,:53), which the start call refuses to send otherwise (:77-80). - Walkthrough
- Parameters:
UserIdis[EditorRequired]and typed through theUserIdentifierTypealias (:32-35);ApiPathPrefixdefaults to/apiandUsersRoutetoAdmin/Userswhen unset (:39,:46, applied at:86-88). OnParametersSetAsync(:56-60) computes_canViewAsfrom the permission claim and the not-already-viewing check (:59).Open(:62-66) shows the reason form and clears any error;Cancel(:68-73) closes it and clears the reason and the error.StartAsync(:75-105) returns when the reason is invalid or a start is already running (:77-80), builds{prefix}/{route}/{UserId}/view-aswith an invariantstring.Create(:86-88), and awaitsmmcaViewAs.startwith the trimmed reason (:91). The comment (:90) records that the script reloads the app on success, so only a refusal comes back: any status outside 2xx (:92-95), or any exceptionJsInteropFailure.IsUnavailableaccepts (anInvalidOperationException,JSDisconnectedException,JSExceptionorOperationCanceledException, which covers aTaskCanceledException;:97-100,JsInteropFailure.cs:27-31), shows the localizedAuth.ViewAs.Refusedtext._startingclears infinally(:101-104).
- Parameters:
- Why it's built this way: the reload on success replaces the admin's whole client state with the viewed account's, so no cached data of the admin's session survives into the view; the component only has to handle the refusal path.
- Where it's used: ADC's user detail page (
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserDetail/UserDetail.razor:127); pinned byViewAsComponentTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/ViewAsComponentTests.cs) and ADC'sViewAsTestsE2E workflow (MMCA.ADC/Tests/E2E/MMCA.ADC.E2E.Tests/Workflows/Identity/Administration/ViewAsTests.cs). The session it starts is shown by ViewAsBanner.
SignInHistoryTable
MMCA.Common.UI ·
MMCA.Common.UI.Components.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/SignInHistoryTable.razor.cs:22· Level 2 · class (partial component)
- What it is: a read-only table of an account's sign-ins, newest first, including ones that have
ended. It takes the rows as a parameter and only formats them: a device label, an IP address, a
status, and viewer-local times. It is the history counterpart of UserSessionsTable,
which shows only the live sessions (ADR-097,
Website/docs-src/adr/097-multi-device-refresh-sessions.md). - Depends on: SignInSummaryResponse (the row shape,
SignInHistoryTable.razor.cs:30), SignInHistoryEntryKind (:72), SignInEndReasons (:82-87), ViewerTimeZone (:33), UserAgentSummary (:74), SharedResource for theIStringLocalizer(:32) and ComponentLifetimeExtensions forLifetimeToken()(:46). - Concept introduced, a status read from why a session ended.
[Rubric §11, Security]assesses whether an account holder can see suspicious access. Each row's status comes from its end reason, so a refresh-token reuse, a session-cap eviction or an account deletion reads differently from an ordinary sign-out (DescribeStatus,:79-89). A view-as row (ADR-137) shows who looked, not a device of the account holder's (comment:70,:71-74). - Walkthrough
SignInsis an[EditorRequired]parameter defaulting to an empty list (:28-30).OnAfterRenderAsync(:43-50) resolves the viewer's time zone on first render only, skips it once disposed, and callsStateHasChangedwhen the lookup resolved a zone (:46-49); the comment (:45) records that the zone is only readable once JS is available.- Row helpers:
DescribeDevicereturns the localizedAuth.SignIns.ViewedBySupporttext for aViewAsrow and otherwiseUserAgentSummary.Describe(signIn.Device, signIn.UserAgent, L)(:71-74);DescribeIpAddressfalls back toAuth.Sessions.IpUnknownwhen the address is blank (:76-77). DescribeStatus(:79-89) maps a row with no end reason and noEndedAtto "Active", eachSignInEndReasonsconstant (SignedOut,ReuseDetected,SessionCapExceeded,AccountDeleted,Expired) to its own localized text, andViewAsEndedand any unknown reason to the generic "Ended" text (:87-88).FormatInstantcallsViewerTime.Format(:91).- Disposal:
IDisposablewith an idempotent protectedDispose(bool)that cancels and disposes theCancellationTokenSourcebounding the zone lookup (:36-40,:54-68).
- Why it's built this way: the table owns no data fetching, so the account's own sessions page and the admin user-detail page share it, and the default arm of the status switch keeps a reason added on the server later rendering as "Ended" instead of blank.
- Where it's used: the shared
Sessionspage (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor:125) and ADC's user detail page (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserDetail/UserDetail.razor:136); pinned bySignInHistoryTableTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/SignInHistoryTableTests.cs) and ADC'sUserDetailTests.
UserSessionsTable
MMCA.Common.UI ·
MMCA.Common.UI.Components.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/UserSessionsTable.razor.cs:21· Level 2 · class (partial component)
- What it is: a read-only table of an account's live (signed-in) sessions, newest first. It takes the
rows as a parameter and only formats them: a device label, an IP address and viewer-local times. The
admin user-detail page feeds it from
IUserAdminUIService.GetSessionsAsync(IUserAdminUIService<TUserDto>). - Depends on: RefreshSessionSummaryResponse (the row
shape,
UserSessionsTable.razor.cs:29), ViewerTimeZone (UserSessionsTable.razor.cs:32), UserAgentSummary (UserSessionsTable.razor.cs:69), SharedResource for theIStringLocalizer(UserSessionsTable.razor.cs:31) and ComponentLifetimeExtensions forLifetimeToken()(UserSessionsTable.razor.cs:45). - Concept introduced, times shown on the viewer's clock.
[Rubric §24, Forms, Validation & UX Safety]covers presenting data the way the user will read it. The viewer's time zone is only readable once JS interop is available, so the component resolves it after the first render and re-renders once it is known (UserSessionsTable.razor.cs:42-49); until then the instants format on the default zone. - Walkthrough
Sessionsis an[EditorRequired]parameter defaulting to an empty list (UserSessionsTable.razor.cs:27-29).OnAfterRenderAsyncruns the zone lookup on first render only, skips it once disposed, and callsStateHasChangedwhen the lookup resolved a zone (UserSessionsTable.razor.cs:42-49).- Row helpers:
DescribeDevicepasses the session's recordedDeviceand itsUserAgenttoUserAgentSummary.Describe(:69),DescribeIpAddressfalls back to the localizedAuth.Sessions.IpUnknowntext when the address is blank (:71-72), andFormatInstantcallsViewerTime.Format(:74). - Disposal: the component implements
IDisposablewith the usual protectedDispose(bool); it cancels and disposes theCancellationTokenSourcethat bounds the zone lookup (:35-67).
- Why it's built this way: the table owns no data fetching, so the same component serves any page that holds a session list, and the cancel-on-dispose token keeps a navigation away from leaving the zone lookup running. Its history counterpart SignInHistoryTable follows the same shape and the same device description.
- Where it's used: ADC's user detail page
(
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserDetail/UserDetail.razor:112), and pinned byUserSessionsTableTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/UserSessionsTableTests.cs) and ADC'sUserDetailTests.
AuditHistoryPanel
MMCA.Common.UI ·
MMCA.Common.UI.Components.Auditing·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auditing/AuditHistoryPanel.razor.cs:22· Level 3 · class (partial component,IDisposable)
- What it is: the opt-in "who changed what, and when" panel of a detail page. It renders an
entity's recorded changes (ADR-075) as one table row per change, with when, who, operation, field,
the value before and the value after
(
MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auditing/AuditHistoryPanel.razor:13-30), newest first, paged by a "Load more" button while a page comes back full. - Depends on: AuditHistoryEntryDTO (the row type,
AuditHistoryPanel.razor.cs:24),Result<T>(the fetch delegate's return), and SharedResource throughIStringLocalizer(line 34) for every heading, column, operation name and the "System" label. The markup reuses the framework'sListNoRecordsContent(retry on failure) andEmptyState(empty history) components (AuditHistoryPanel.razor:39,43). Externals: MudBlazor (MudPaper,MudSimpleTable,MudProgressLinear,MudButton). - Concept introduced, a fetch-delegate panel that owns its own paging and cancellation.
[Rubric §18, UI Architecture]assesses whether components stay presentational and receive data through clear contracts. The panel never knows a URL or a service: it takes aFetchPagedelegate (page number, page size, token in; aResultof entries out, line 42), so the page that hosts it decides where the history comes from.[Rubric §19, State Management & Data Flow]assesses how async state survives overlapping requests. A generation counter plus a per-fetchCancellationTokenSourcemeans a superseded or disposed fetch can never write rows into the panel. - Walkthrough:
- Parameters:
FetchPageis[EditorRequired](lines 40-42),PageSizedefaults to 20 (line 45),Titlefalls back to the sharedAuditHistory.Titletext (line 48; markup line 6), andUserLabel,PropertyLabelandDisplayTimeZone(lines 51-57) map a user id, a property name and the display zone, each falling back to the raw value or UTC when null. OnParametersSetthrowsInvalidOperationExceptionwhen noFetchPagewas supplied (lines 100-106).OnInitializedAsyncloads page 1 only whenRendererInfo.IsInteractive(line 110), so nothing is fetched during prerender.LoadPageAsync(line 117) bumps_generationfirst (line 126), swaps in a fresh token source and cancels the previous one (line 133), then callsFetchPage(page, PageSize, token)(line 147). A result whose generation is stale is dropped; a failure records_failedPage(line 153 onward), which the markup turns into a retry; a success appends rows, sets_hasMorewhen the page came back full (line 161) and_firstPageEmptyfor an empty page 1 (line 162). A cancellation caused by its own token is swallowed (line 164).LoadMoreAsyncasks for the next page (line 113),RetryAsyncre-fetches the failed page (line 115), and the publicReloadAsync(line 64) clears every row and state flag and fetches page 1 again.- Formatting helpers:
WhenTextconvertsChangedOnfrom UTC intoDisplayTimeZoneand appends the zone name (line 181),WhoTextshowsAuditHistory.Systemfor a change with no user (lines 188-192), andFieldTextblanks a row with no property name (line 198). Dispose(bool)cancels and disposes the in-flight token source (lines 83-96).
- Parameters:
- Why it's built this way: the audit trail is opt-in per app (ADR-075,
Website/docs-src/adr/075-audit-trail.md), so the panel is a plain component a detail page places inside its ownAuthorizeViewon the app's audit permission (class docs, lines 10-15), and the delegate keeps it independent of which host route serves the history. - Where it's used: fed by IAuditHistoryUIService on ADC's
EventDetail and
SessionDetail pages
(
MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Events/EventDetail.razor.cs:42-45). Pinned by AuditHistoryPanelTests.
FieldRefusal
MMCA.Common.UI ·
MMCA.Common.UI.Components.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/ChangePasswordCard.razor.cs:198· Level 3 · record struct (private, nested in ChangePasswordCard)
- What it is: a server message for one form field, held against the exact value it was raised for, so
it clears itself the moment the user edits that field (doc comment,
ChangePasswordCard.razor.cs:194-197). - Depends on:
Result(Result) and itsErrors(ChangePasswordCard.razor.cs:202); the target and code of each error. - Concept introduced, a refusal bound to a value.
[Rubric §24, Forms, Validation & UX Safety]assesses whether a server rejection is shown where the user can act on it. Holding the value beside the message means no timer or event is needed to dismiss a stale message:MessageForcompares the field's current value to the stored one and returnsnullonce they differ. - Walkthrough
- The positional record struct carries
ValueandMessage(ChangePasswordCard.razor.cs:198); thedefaultinstance carries neither, so an unset refusal never matches. From(result, field, value, matchCode)picks the first error whose target names the field or whose code equalsmatchCode, and returnsdefaultwhen there is none or its message is blank (:200-209).MessageFor(value)returns the message only on an ordinal match with the stored value (:211-212).TargetsFieldreturns false for an empty target, then compares the last dotted segment of the error target to the field name, case-insensitively (:216-225). The segment start is found withAsSpan().LastIndexOf('.')(:223). The comment (:214-215) records why only the last segment counts: a validator over the request yieldsNewPassword, one over the command yieldsRequest.NewPassword, in either casing once it crossed the wire.
- The positional record struct carries
- Why it's built this way: it is a
readonly record struct, so the two fields on the card (_currentPasswordRefusal,_newPasswordRefusal,ChangePasswordCard.razor.cs:43-44) cost no allocation and compare by value. - Where it's used: only ChangePasswordCard:
ShowFieldRefusalsAsyncbuilds the two refusals (ChangePasswordCard.razor.cs:185-186) and the validators read them (:103,:121).
MultiFactorRequiredListener
MMCA.Common.UI ·
MMCA.Common.UI.Components.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/MultiFactorRequiredListener.cs:24· Level 3 · class (internal sealed component)
- What it is: a markup-less layout component that sends the user to the two-factor page when the
API refuses a request because the session lacks a second factor. TwoFactorUIModule
contributes it to the layout through
LayoutComponentTypes(TwoFactorUIModule.cs:28), so a host that opts into two-factor gets the redirect with no page changes (ADR-067,Website/docs-src/adr/067-ui-module-shell-composition.md). - Depends on:
ComponentBaseandIDisposable(MultiFactorRequiredListener.cs:24), ITokenStorageService (:28),NavigationManager(:30), MultiFactorRequiredSignal for the subscription (:41), ReturnUrlProtector (:93) andTwoFactorUIModule.AccountPath(:51,:95;"/profile/two-factor"atTwoFactorUIModule.cs:19). - Concept introduced, a step-up redirect that cannot become an open redirect or a loop.
[Rubric §11, Security]assesses whether a second-factor requirement is enforced consistently and whether a return URL can be abused. The listener sanitizes the current location throughReturnUrlProtector.Sanitizewith/as the fallback before putting it inreturnUrl(:93-95), and never redirects away from the two-factor page or the sign-in page (IsExempt,:50-52), so the refusal that brought the user there cannot bounce them again. The exemption compares whole segments, so a sibling route that only shares the leading letters (login-help,profile/two-factor-faq) is still redirected (:43-47). - Walkthrough
OnInitialized(:40-41) subscribes throughMultiFactorRequiredSignal.Subscribe(TokenStorage, OnRequired);Dispose(:33-37) disposes and clears the subscription.OnRequired(:62) discardsRedirectAsync, which dispatchesRedirectthroughInvokeAsyncand swallowsObjectDisposedExceptionandInvalidOperationException, the two shapes of a circuit that ended between the refusal and the dispatch (:64-78).Redirect(:80-96) does nothing outside an interactive renderer (:82-85), reads the base-relative path (:87), returns for an exempt path (:88-91), and navigates to{AccountPath}?required=true&returnUrl=...with the escaped, sanitized path (:93-95).IsExempt(:50-52,internal static) is true when the path is at or below the trimmedAccountPathorlogin.IsAtOrBelow(:58-60) requires an ordinal, case-insensitive prefix match and that the path either ends there or continues with/,?or#.
- Why it's built this way: listening at the layout rather than in each page means every refused call,
whichever page made it, takes the user to the same place, and the internal visibility keeps it a
detail of the two-factor module rather than a component consumers place by hand.
IsExemptisinternalrather thanprivateso the segment rule can be pinned directly by a unit test. - Where it's used: registered by
TwoFactorUIModule(MMCA.Common/Source/Presentation/MMCA.Common.UI/TwoFactor/TwoFactorUIModule.cs:28); pinned byMultiFactorRequiredListenerTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/MultiFactorRequiredListenerTests.cs, includingARaise_OnASiblingRouteSharingThePrefix_Redirectsat:80andIsExempt_ComparesWholeSegmentsat:100),TwoFactorOptInRenderTestsandTwoFactorUIModuleTests.
StaleToastSweeper
MMCA.Common.UI ·
MMCA.Common.UI.Components.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Notifications/StaleToastSweeper.cs:24· Level 3 · class (sealed, component, implementsIDisposable)
- What it is: a markup-less component that removes toasts left over from the page being left, so a toast about that page ("Item added") does not follow the user onto the next one (
StaleToastSweeper.cs:9-13). It renders nothing itself. - Depends on:
NavigationManagerandLocationChangedEventArgs(Microsoft.AspNetCore.Components), MudBlazor'sISnackbarandSnackbar, the BCLTimeProviderandLock, and the first-party IToastService and MudToastService (asked which toasts are pinned); the four services are injected (lines 33-39). - Concept introduced, a toast belongs to the page that raised it, with a grace window.
[Rubric §19, State Management & Data Flow](assesses whether transient UI state is scoped to the context it describes) and[Rubric §14, Testability](assesses whether time-dependent behavior can be driven deterministically). A blanket "clear on navigate" would also erase the toast an action raises in the same moment it navigates ("Order created, taking you to it"), which is about the page being opened. The remarks (lines 14-23) name the rule instead: only a toast that had been on screen for longer thanGracebefore the navigation is removed.Graceis a public staticTimeSpanof 750 milliseconds (line 27). "Leaving the page" is also defined precisely: a location change that keeps the path and rewrites only the query string or fragment (a grid sort, filter or page change mirrored into the URL) removes nothing (lines 19-20). A pinned toast (IToastService.ShowPersistent, orShowActionwithrequireInteraction) is never removed, because it is promised to stay until the user dismisses it (lines 21-22). Every timestamp comes from the injectedTimeProvider, so a test advances a fake clock instead of waiting. - Walkthrough:
- State (lines 29-31): a
Dictionary<Snackbar, DateTimeOffset> _firstSeenthat records when each toast was first observed, guarded by aLock _sync, and_currentPath, the absolute path of the page currently shown. OnInitialized(lines 49-55) records the starting path fromNavigation.ToAbsoluteUri(Navigation.Uri).AbsolutePath(line 51), subscribes toNavigation.LocationChangedandSnackbar.OnSnackbarsUpdated, then callsOnSnackbarsUpdated()once (line 54) so toasts already on screen when the layout renders get a first-seen time.OnSnackbarsUpdated(lines 58-75) stamps every currently shown toast withTryAdd(snackbar, now)(line 67), which keeps the first stamp, and drops entries for toasts no longer shown (lines 70-73). The comment at line 57 records why the lock exists: snackbar updates arrive on timer threads when a toast expires.OnLocationChanged(lines 77-104) first compares the new absolute path with_currentPath, case-insensitively, and returns when they match (lines 79-83), so a query-string-only change sweeps nothing. Otherwise it records the new path (line 85), computescutoff = now - Grace(line 86), collects and forgets, under the lock, every entry stamped at or before the cutoff that is not pinned (lines 89-98, the filter at lines 91-93), and then callsSnackbar.Removeon each outside the lock (lines 100-103), so the MudBlazor callback never runs while the sweeper holds its own lock.IsPinned(lines 111-112) answers true only when the injectedIToastServiceis aMudToastServiceand that service reports the snackbar as pinned (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/MudToastService.cs:182). The comment (lines 106-110) explains the indirection: MudBlazor keeps a snackbar's options internal, so the facade that raised the toast is the only place that knows it is pinned.Dispose(lines 42-46) unsubscribes both handlers.
- State (lines 29-31): a
- Why it's built this way: tracking first-seen time from the snackbar's own update event, rather than wrapping the toast service, means the sweeper sees every toast regardless of which service raised it (
MudToastServiceor a directISnackbarcall). It is a layout component rather than a behavior of the toast service, andAddCommonUiFacadesdocuments it as the one framework type outside the Mud-backed facades that names MudBlazor'sISnackbardirectly, askingMudToastServicewhich toasts are pinned (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:277-279). Comparing paths rather than full URLs keeps the sweeper from erasing the toast a list page raises while it mirrors its grid state into the query string. - Where it's used: rendered unconditionally by
MainLayout, so it runs on every head (MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/MainLayout.razor:151-152; the shell composition is ADR-067). Covered byStaleToastSweeperTests. - Caveats / not-in-source: there is no setting to turn it off; a host that wants toasts to follow the user across pages has no switch in this source. A host that registers its own
IToastServicein place ofMudToastServiceloses pin recognition, so its persistent toasts are swept like any other (comment, lines 109-110).
ChangePasswordCard
MMCA.Common.UI ·
MMCA.Common.UI.Components.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/ChangePasswordCard.razor.cs:23· Level 4 · class (partial component)
- What it is: the shared change-password form for a signed-in user: three password fields inside a
MudForm, client-side length and confirmation checks, and a submit that calls the auth service and reports the outcome through toasts. A consumer app drops it into its profile page instead of re-implementing the form (ADC does so with a bare<ChangePasswordCard />,MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/Profile.razor:83). - Depends on: IAuthUIService (
@inject AuthService,ChangePasswordCard.razor:2), IToastService (ChangePasswordCard.razor:3),IStringLocalizer<ChangePasswordCard>(ChangePasswordCard.razor:4) with the plural helper StringLocalizerPluralExtensions, ResultUiExtensions forLocalizedErrorMessage(ChangePasswordCard.razor.cs:165), ComponentLifetimeExtensions forLifetimeToken()(ChangePasswordCard.razor.cs:149), PasswordComplexity and ChangePasswordRequest (ChangePasswordCard.razor.cs:30-31,:59,:120), AuthFieldMessages for the complexity message (ChangePasswordCard.razor.cs:122), and the nested FieldRefusal (:43-44). Externals:MudFormandMudTextFieldfrom MudBlazor. - Concept introduced, a form that reports the server's reason, not its own guess.
[Rubric §24, Forms, Validation & UX Safety]assesses whether validation feedback is honest and where it is raised. Two layers are visible here. The client checks only what it can know cheaply: the new password meetsMinLength(ChangePasswordCard.razor.cs:113-116), satisfies the sharedPasswordComplexityrule the server's strong-password rules also evaluate (:118-122), and the confirmation matches (:125-128); the server still enforces its own rules (doc comment,ChangePasswordCard.razor.cs:46-49). A server refusal is shown with the server's own message when it has one, falling back to a fixedChangePassword.Failedtext only when the failure carries none (commentChangePasswordCard.razor.cs:162-165). When the refusal names the current or the new password field, it is also shown under that field via FieldRefusal (ChangePasswordCard.razor.cs:166,:180-192). - Walkthrough
- Parameters:
MinLengthdefaults to8, the framework's password policy minimum, and also feeds the helper text (ChangePasswordCard.razor.cs:51;ChangePasswordCard.razor:18).MaxLengthis anint?that defaults toPasswordComplexity.MaximumLength, the bound the server's password rules enforce;nullleaves the field unbounded (ChangePasswordCard.razor.cs:53-59); the razor falls back to the privateNoMaxLengthconstant524288, MudTextField's own default (ChangePasswordCard.razor.cs:25-26;ChangePasswordCard.razor:20).AdditionalActions(RenderFragment?) renders extra actions, such as a device-management link, after the submit button (ChangePasswordCard.razor.cs:66;ChangePasswordCard.razor:38). - Callbacks:
OnChangedfires after success, once the toast has been shown (ChangePasswordCard.razor.cs:70);OnFailedcarries the failedResultafter the failure toast, and is not raised for a client-side validation failure, which the form itself reports (ChangePasswordCard.razor.cs:77). - Validators: all three return
nullfor valid or empty input and leave theRequiredcheck to report a missing value (commentChangePasswordCard.razor.cs:100-102).ValidateCurrentPassword(:103) only echoes a server message held for the exact value still in the field.ValidateNewPassword(:106) checks length first, plural-aware throughL.Plural(:115), thenPasswordComplexity.Evaluate: a failing value getsAuthFieldMessages.PasswordComplexity(:122), a passing one gets any held server message (:121). The mismatch usesValidation.PasswordsDoNotMatch(:128), and the confirmation comparison is ordinal (:126). SavePasswordAsync(ChangePasswordCard.razor.cs:130) opens with a re-entrancy guard before the first await: it returns when the@ref-set form is absent or a save is already running (:135), because a second click before the disabled render would resend the stale current password, which the server refuses and counts toward lockout (comment:132-134). It then sets_isSaving(:140) and, inside thetry, validates the form and stops on invalid (:143-147) before callingAuthService.ChangePasswordAsync(current, new, _cts.LifetimeToken())(:149). On success it resets the form, clears the three fields, toastsChangePassword.Successand raisesOnChanged(:151-158). On failure it toasts (:165), callsShowFieldRefusalsAsync(:166) and raisesOnFailed(result)(:167). A cancelled call is swallowed (:170-173), and_isSavingalways clears infinally(:176).ShowFieldRefusalsAsync(ChangePasswordCard.razor.cs:183) builds a FieldRefusal for the current-password field (matching the wrong-password codeAuth.InvalidCurrentPassword,:32) and for the new-password field, then re-validates the form so the message lands under the field and in the summary (:185-191).- Disposal: the component implements
IDisposable(ChangePasswordCard.razor:5).Dispose(bool)is idempotent, sets_disposed, then cancels and disposes theCancellationTokenSource(ChangePasswordCard.razor.cs:88-98). TheMudFormreference is not disposed here because the renderer owns it (commentChangePasswordCard.razor.cs:36).
- Parameters:
- Why it's built this way: the cancel-on-dispose token is what makes a navigation away, or an
InteractiveAuto render-mode transition, harmless: the in-flight request is cancelled and the
OperationCanceledExceptionis expected (commentChangePasswordCard.razor.cs:172). TakingMinLengthandMaxLengthas parameters lets a consumer tighten the form without forking it, while the server remains the authority. Localization follows ADR-027 (Website/docs-src/adr/027-multi-locale-i18n.md). - Where it's used: ADC's profile page renders it (
Profile.razor:83), and PasskeysPanel mirrors its card layout (Profile.razor:106). Its behavior is pinned byChangePasswordCardTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/ChangePasswordCardTests.cs) andChangePasswordCardErrorSummaryTests, andFormsConventionTestsBase(MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Ui/FormsConventionTestsBase.cs:33) references it by its<ChangePasswordCardtag.
PasskeySignInButton
MMCA.Common.UI ·
MMCA.Common.UI.Components.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/PasskeySignInButton.razor.cs:25· Level 4 · class (partial component)
- What it is: the sign-in page's passkey entry point (the opt-in passkey sign-in of ADR-139,
Website/docs-src/adr/139-passkeys-webauthn-opt-in-sign-in.md). It offers a "sign in with a passkey" button and, where the browser supports it, starts passkey autofill so a saved passkey is suggested in the sign-in form without a click. - Depends on: IPasskeyUIService for the server half of the ceremony
(
PasskeySignInButton.razor.cs:40), IPasskeyCapability for the platform half (:42), PasskeySignInRequest (:133), ResultUiExtensions forLocalizedErrorMessage(:145), SharedResource (:44) and ComponentLifetimeExtensions forLifetimeToken()(:73). - Concept introduced, no server challenge until the browser can use it.
[Rubric §11, Security]assesses whether an authentication ceremony issues only what it can redeem. Autofill checksIsAutofillAvailableAsyncbefore asking the server for options, because the options store a server challenge that a browser without conditional mediation could never redeem (comment:71-72,:73). An explicit click cancels any running autofill first (:104) so the two ceremonies never overlap. - Walkthrough
- Parameters:
OnSignedInis raised once the passkey signed the user in and the tokens are stored (:33-34);EnableAutofilldefaults to true (:37-38). OnAfterRenderAsync(:62-91) runs on the first render only, when autofill is enabled and the component is not disposed (:64): it checks support (:73), begins a sign-in flow (:78) and on success starts autofill with a callback that completes the flow on the renderer's context (:81-84). AnOperationCanceledExceptionis swallowed only when disposed (:87).SignInAsync(:93-129) guards on_isBusy(:95), clears the error, cancels autofill (:104), begins a flow (:105) and shows the failure message when that fails (:106-110), then asks the platform for an assertion (:112); anullcredential shows the localizedAuth.Login.PasskeyCancelledtext (:113-117), otherwise it completes the flow (:119)._isBusyclears infinally(:125-128).CompleteAsync(:131-142) posts aPasskeySignInRequest(flowId, assertion)(:133); a failure sets the message and re-renders (:134-139), a success raisesOnSignedIn(:141).FailureMessage(:144-145) prefers the result's localized message and falls back toAuth.Login.PasskeyFailed.DisposeAsync(:47-59) is idempotent, cancels and disposes the token source and cancels any running autofill (:57).
- Parameters:
- Why it's built this way: splitting the ceremony between a UI service (server) and a device capability (platform) lets the same button run in a browser and in a native head without a branch.
- Where it's used: the shared sign-in page
(
MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor:170). - Caveats / not-in-source: no test file references the type by name outside its defining file; its coverage, if any, runs through the sign-in page.
PasskeysPanel
MMCA.Common.UI ·
MMCA.Common.UI.Components.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/PasskeysPanel.razor.cs:21· Level 4 · class (partial component)
- What it is: the signed-in user's passkey manager (ADR-139,
Website/docs-src/adr/139-passkeys-webauthn-opt-in-sign-in.md): it lists the account's passkeys with their added and last-used dates, adds a new one with an optional name, renames one in place, and deletes one after a confirmation. - Depends on: IPasskeyUIService (
PasskeysPanel.razor.cs:39), IPasskeyCapability (:41), IAppDialogService (:43), IToastService (:45), ViewerTimeZone (:49),IStringLocalizer<PasskeysPanel>(:51), PasskeyResponse (:27), PasskeyRegisterRequest (:129), ResultUiExtensions (:241) and ComponentLifetimeExtensions (:74). - Concept introduced, a refusal the user can fix gets its own words.
[Rubric §24, Forms, Validation & UX Safety]assesses whether an error tells the user what to do. Most refusals show the server's own reason (the last-passkey rule, a name that is too long; comment:221-222), but a step-up refusal, codePasskeys.StepUpRequiredrestated asStepUpRequiredCodebecause UI references Shared only (:23-24), shows the localizedPasskeys.SignInAgaintext instead, the one refusal with an action the user can take (FailureMessage,:236-241).[Rubric §11, Security]applies to the delete path: it asks for a destructive confirmation first (:194-199). - Walkthrough
OnInitializedAsync(:68) callsLoadAsync(:80-102), which lists the passkeys (:84), toasts a failure (:91) and clears_isLoadinginfinally(:98-101).OnAfterRenderAsync(:71-78) resolves the viewer's time zone on first render, so the dates render as the viewer's local date rather than the UTC date (comment:47-48);DescribeLastUsed(:243-246) formats with the shortdpattern (:245) or showsPasskeys.NeverUsed.AddAsync(:104-145) begins registration (:114), asks the platform to create a credential (:121), toastsPasskeys.AddCancelledas info when the user backs out (:122-126), completes the registration with the trimmed name ornull(:128-130), and clears the name field on success (:132-135).- Rename:
StartRenameandCancelRenamehold the row being renamed and its draft (:147-157);SaveRenameAsync(:159-185) posts the new name (:169) and leaves edit mode on success. DeleteAsync(:187-219) confirms throughDialogs.ConfirmAsync(..., destructive: true)(:194-199) before deleting (:208).AfterChangeAsync(:223-234) toasts a failure, or toasts the success key, re-reads the list so the rows are the server's, and raisesOnChanged(:232-233).- Every mutating method guards on
_isBusyand swallowsOperationCanceledExceptiononly when disposed;DisposeAsync(:54-65) is idempotent and cancels and disposes the token source.
- Why it's built this way: re-reading the list after every change, rather than patching the local copy, keeps the rows identical to what the server holds.
- Where it's used: ADC's profile page
(
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/Profile.razor:114); pinned byPasskeysPanelTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/PasskeysPanelTests.cs) and ADC'sProfilePasskeysTests.
NotificationBell
MMCA.Common.UI ·
MMCA.Common.UI.Components.Notifications·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Notifications/NotificationBell.razor.cs:34· Level 6 · class (partial, component)
- What it is: the code-behind for the app-bar notification bell. It renders an unread badge from the scoped NotificationState, and exactly one instance at a time holds the single active-poller slot, so a bell placed in two layout slots never doubles the API traffic.
- Depends on: first-party: NotificationState (badge value, change and refresh events, staleness clock, and the poller slot), INotificationInboxUIService (the unread-count call), NotificationBellOptions (the two intervals), NotificationRoutePaths (the inbox route), ComponentLifetimeExtensions (the
LifetimeToken()read of the component's token source), and SharedResource (the resx anchor for the injected localizer). Externals:Microsoft.AspNetCore.Components([Inject],NavigationManager,LocationChangedEventArgs,OnAfterRenderAsync,InvokeAsync,StateHasChanged),Microsoft.Extensions.Options(IOptions<T>),Microsoft.Extensions.Localization(IStringLocalizer<T>), BCLTimeProvider,PeriodicTimer,CancellationTokenSource,IDisposable. - Concept introduced, a poller slot with symmetric registration and handover.
[Rubric §19, State Management & Data Flow]assesses how shared UI state is coordinated. The bell is a component, so a responsive layout can legitimately render it twice at once (desktop app bar and mobile drawer). Without coordination each copy would start its own timer and its own navigation refresh, doubling the unread-count endpoint's load for no user benefit. The design is a slot held by an owner object, not a bare counter:State.TryRegisterPoller(this)(line 63) takes the slot only when it is free or already this instance's (NotificationState.cs:111-124), andState.UnregisterPoller(this)releases it only when this instance actually holds it and then raisesOnPollerSlotFreed(NotificationState.cs:133-149).- Why owner identity matters here. The class remarks (lines 26-33) name the real scenario: hosts render the bell inside
<AuthorizeView>, which tears the children down and rebuilds them on every authentication-state change, including a routine access-token refresh. Registration is therefore strictly symmetric (every instance unregisters on dispose, whether or not it was polling, line 334), and the surviving instance claims the freed slot throughOnPollerSlotFreed(subscribed at line 60), so the circuit never ends up with a badge that nobody refreshes. [Rubric §23, Front-End Performance]assesses avoidable network work. Three mechanisms cut it. The slot removes an entire duplicate polling stream in dual-placement layouts, and it owns every refresh trigger, not just the timer: the push-refresh subscriptionState.OnRefreshRequested += HandleRefreshRequestedis made insideBecomeActivePollerAsync(line 88), next to the navigation hook, because subscribing every bell made each push read the API once per placement (comment, lines 85-87); a takeover runs that method again, so the surviving bell picks the subscription up with the slot. And the navigation trigger is throttled by staleness rather than firing per click:OnLocationChangedreads only whenState.IsStale(Options.Value.NavigationRefreshMaxAge)(line 200), because navigation is an ambient trigger, not evidence that the count moved (doc, lines 188-193). The defaults are 30 seconds for both the poll interval and the navigation max age (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Settings/NotificationBellOptions.cs:23,30), and both are configuration, not constants. A zero or negativePollIntervalswitches the periodic backstop off entirely (lines 120-123) while push and navigation refresh keep working; the comment (lines 118-119) records thatPeriodicTimerrejects such a period and throwing there faulted the circuit.- The staleness policy has exactly three tiers, and they are deliberate. The first read and every periodic tick are unconditional; a navigation reads only past the configured window; a real-time push calls
State.MarkStale()first and then reads regardless (lines 216-220), because the server has just said the data changed, so the age of the number carries no information any more (doc, lines 210-214). That is the one path that must never be throttled. - Reads are ordered, and a dead session stops the timer. The poll, navigation and push reads overlap freely, so each read takes a ticket from
_readSequence(line 230) and only the newest may write the badge (checks at lines 237 and 265); an older answer would otherwise overwrite the authoritative one and re-stamp it as fresh.[Rubric §29, Resilience, Reliability & Business Continuity]assesses graceful behavior when a dependency is gone: anUnauthorizedread (line 247) stops the unattended backstop viaStopPollTimer(line 254) instead of re-reading, and re-trying the token refresh, every interval for as long as the tab stays open. The class summary (lines 22-23) states the contract: the periodic tick runs only while the session is accepted, and the next successful navigation or push read starts it again throughStartPollTimerIfStopped(line 271). [Rubric §14, Testability]assesses whether time-dependent behavior can be driven deterministically. Both the timer and the age comparison run off the injectedTimeProvider Clock(line 41), and thePeriodicTimeris constructed with theTimeProvideroverload (line 127) precisely so a test drives the loop instead of waiting out a real interval (comment, lines 125-126).[Rubric §21, Accessibility]: the bell button carries an explicit localizedaria-label="@L["Notif.Bell.Aria"]"in the markup (NotificationBell.razor:10), which is what the injectedIStringLocalizer<SharedResource> L(line 39) is for.- Fire-and-forget from a synchronous event handler.
HandlePollerSlotFreed(lines 143-144),OnLocationChanged(lines 198-204), andHandleRefreshRequested(lines 216-220) are allEventHandler-shaped, so they cannot beasync Task. Rather thanasync void(which turns an unobserved exception into a process crash, VSTHRD100, per the comments at lines 141-142 and 194-197), they discard the task with_ =and rely on the callee observing its own failures.
- Why owner identity matters here. The class remarks (lines 26-33) name the real scenario: hosts render the bell inside
- Walkthrough
- Injected members (lines 36-41):
State,InboxService,NavigationManager,L,IOptions<NotificationBellOptions> Options, andTimeProvider Clock. Fields (lines 43-46, 50): a per-componentCancellationTokenSource _cts, thePeriodicTimer? _pollTimer, the two flags_isActivePollerand_disposed, and theint _readSequencecounter that orders overlapping reads. OnAfterRenderAsync(bool firstRender)(lines 52-67) returns immediately on subsequent renders (lines 54-57), subscribes every instance to two state events,OnChangeandOnPollerSlotFreed(lines 59-60), then tries for the slot and, on success, callsBecomeActivePollerAsync()(lines 63-66).BecomeActivePollerAsync(lines 75-99) is the double-start-guarded start: it bails on_disposed || _isActivePoller(lines 77-80), latches_isActivePoller, hooksLocationChanged(line 83) andOnRefreshRequested(line 88), then does the unconditional first read and keeps its result (var sessionRejected = await RefreshUnreadCountAsync(), line 91). The periodic backstop starts after that read even following a transient failure, because retrying is its job, but not when the server rejected the session:if (!sessionRejected)gatesStartPollTimerIfStopped()(lines 93-98), so a dead session never starts a timer at all. The method doc (lines 69-74) notes it always runs on the renderer's synchronization context, which is what makes the simple_isActivePollerguard sufficient rather than needing an interlocked operation.StartPollTimerIfStopped(lines 108-129) is the one place a timer is created, and it is idempotent: it returns when_disposed, when this bell no longer holds the slot, or when_pollTimeris already set (line 113). The comment (lines 110-112) explains the_disposedhalf:Disposemay have run during a read, having already disposed the then-null timer and the token source, so starting the loop now would leak aPeriodicTimernothing disposes and fault the discarded task on a disposed_cts. It returns without a timer whenPollInterval <= TimeSpan.Zero(lines 120-123). Otherwise it creates the timer fromOptions.Value.PollIntervaland the injected clock (line 127) and launchesPollLoopAsync(_pollTimer)with an explicit discard (line 128). It is called after the first read and after every successful one, which is what restarts polling once a navigation or push read proves the session is back (doc, lines 101-107).StopPollTimer(lines 135-139) disposes the timer and nulls the field. Disposing makes the loop's pendingWaitForNextTickAsyncanswer false, so the loop ends on its own (doc, lines 131-134).TryTakeOverPollingAsync(lines 150-166) is the handover path: it re-checks the guards and claims the slot (line 152), then marshals the actual start onto this component's renderer withInvokeAsync(BecomeActivePollerAsync)(line 159), because the event was raised synchronously from the disposing bell's thread (doc, lines 146-149). If that dispatch hitsObjectDisposedExceptionit hands the slot straight back (lines 161-165) so another bell can claim it.PollLoopAsync(PeriodicTimer pollTimer)(lines 168-186) takes the timer as a parameter rather than reading the field, awaitspollTimer.WaitForNextTickAsync(_cts.LifetimeToken())in a loop (line 172) and refreshes each tick. Holding its own reference means aStopPollTimerthat nulls the field cannot null-reference the loop. The token comes from ComponentLifetimeExtensions (ComponentLifetimeExtensions.cs:26), which returns an already-cancelled token instead of throwing once the source is cancelled or disposed, so a late read stops through the normal cancellation path. It still catchesOperationCanceledException(the expected disposal exit) andObjectDisposedException(disposed between timer creation and the first wait, where reading the token off the disposed source throws rather than cancelling, comment lines 182-183).RefreshUnreadCountAsync(lines 223-294) now returnsTask<bool>, answering true only when the server rejected the session (doc, line 222). It is the one place that touches the network: it bails with false when_disposed(lines 225-228), takes a ticket withInterlocked.Increment(ref _readSequence)(line 230), and callsInboxService.GetUnreadCountAsync(_cts.LifetimeToken())(line 233). After the await it drops a superseded read: ifsequence != Volatile.Read(ref _readSequence)a newer read started while this one was in flight, so its answer is authoritative and this older one would overwrite it and re-stamp it as fresh (lines 235-240). On a failed result it leaves the badge untouched (lines 242-258): the comment (lines 244-246) records that zeroing the badge on an unknown count is what used to erase a push increment, and that a failed read is silent by design because the bell has no surface to report it on. The one exception iscount.IsUnauthorized()(line 247): the service has already tried a forced token refresh and replay before answering Unauthorized, so the session is gone, and the bell stops the unattended backstop withInvokeAsync(StopPollTimer)(line 254) and returns true. Navigation and push reads keep running, and the first one that succeeds restarts polling. On success it re-checks_disposedand marshals back onto the renderer withInvokeAsync(lines 261-274); inside that callback it re-checks the sequence (line 265), then callsState.SetUnreadCount(unread),StartPollTimerIfStopped()(line 271) andStateHasChanged(). Three catch tiers follow (lines 278-292): cancellation, disposal during the async gap, and a barecatchfor network or deserialization failures where the badge keeps its last value, under a scoped CA1031 waiver (lines 286-288); every path past them returns false (line 293). That catch-all is what makes the discards above safe.HandleStateChanged(lines 296-297) discards intoRerenderSafeAsync(lines 299-314), which re-renders throughInvokeAsync(StateHasChanged)and tolerates a dispose landing between the event firing and the render dispatch.NavigateToInbox(line 316) sends the click toNotificationRoutePaths.NotificationInbox.Dispose(bool disposing)(lines 318-339) sets_disposedfirst (line 325), unsubscribes all three state events andLocationChanged(lines 326-329; removing a handler that a non-poller never added is a no-op), then callsState.UnregisterPoller(this)unconditionally (line 334). The comment (lines 331-333) states both halves of why that is safe: a bell that claimed the slot but was torn down before it started polling still frees it, and a bell that never held it cannot evict the live poller, because the state object checks owner identity. It then disposes the timer and cancels and disposes the_cts(lines 336-338).Dispose()(lines 341-345) is the public half withGC.SuppressFinalize.
- Injected members (lines 36-41):
- Why it's built this way: a live unread badge is a genuinely useful affordance, but a naive implementation is a request amplifier (one timer and one push read per rendered copy, per circuit) and a fragile one under
<AuthorizeView>churn. Owner-identity registration plus a freed-slot event keeps the affordance, removes the amplification, and survives the teardown-rebuild cycle that a plain counter would leave stuck. Making both intervals options and both clocks injected turns the polling policy into something a host can tune and a test can drive. - Where it's used: contributed to the shell as an app-bar component by NotificationUIModule (
NotificationUIModule.cs:23); it reads the same NotificationState that NotificationInbox writes after a mark-read, so the badge stays consistent with the inbox without either component knowing about the other.
EmailConfirmationResendPrompt
MMCA.Common.UI ·
MMCA.Common.UI.Components.Auth·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/EmailConfirmationResendPrompt.razor.cs:21· Level 5 · class (sealed partial component)
- What it is: the "resend the confirmation link" prompt shown when a sign-in or a registration is waiting on email confirmation. It sends one resend request for the given address and then reports it as sent.
- Depends on: IEmailConfirmationUIService
(
EmailConfirmationResendPrompt.razor.cs:39), SharedResource (:41), ResultUiExtensions (:82) and ComponentLifetimeExtensions (:74). - Concept introduced, a one-shot action.
[Rubric §24, Forms, Validation & UX Safety]assesses whether a form protects against duplicate submissions.ResendAsyncreturns while a send is in flight or after one succeeded (:58), so repeated clicks cannot queue a burst of emails. - Walkthrough
- Parameters:
Emailis[EditorRequired](:31-33);OnSentruns after the request was accepted (:36-37). ResendAsync(:56-92) clears the error, trims the address (:64) and shows the localizedAuth.Confirm.EmailRequiredtext for an empty one (:65-69). It then sets_isSending(:71) and callsResendEmailConfirmationAsync(:74); success sets_sentand raisesOnSent(:75-80), a failure shows the localized message orAuth.Confirm.GenericError(:82). A cancellation is swallowed only when disposed (:84), and_isSendingclears infinally(:88-91).Dispose(:44-54) is idempotent and cancels and disposes the token source.
- Parameters:
- Why it's built this way: taking the address as a parameter lets the sign-in page and the registration page each pass the address they already hold, with no lookup in the component.
- Where it's used: the shared sign-in page (
MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor:87) and registration page (Register.razor:52); pinned byEmailConfirmationResendPromptTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/EmailConfirmationResendPromptTests.cs),LoginResendPromptTestsandRegisterPendingTests.
BiometricGate
MMCA.Common.UI ·
MMCA.Common.UI.Components.Capabilities·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Capabilities/BiometricGate.razor.cs:18· Level 7 · class (partial, component code-behind)
- What it is: a hybrid-head app-lock gate. It locks the UI behind a biometric prompt whenever the
app returns from the background having sat there longer than
ReLockAfter, so a device handed to someone else, or simply left unattended, does not reopen straight into a signed-in session. While locked, the page behind the overlay is made inert and focus is held on the Unlock button. - Depends on: injected services resolved by the component (
AppLifecycle'sResumedevent with AppResumedEventArgs,Preferences(IDevicePreferences) read with DevicePreferenceKeys.AppLockEnabled,TokenStorage,SignOutNavigator(SignOutNavigator, used only to sign out),Biometrics,Logger,JS, the page's localizerL; injected inBiometricGate.razor:6-14); AppLockInertBackground for the inert page behind the overlay (BiometricGate.razor.cs:32,:48); MudBlazor'sMudButtonfor the focus target (_unlockButton, line 30). - Concept introduced, a discarded lifecycle task that cannot afford to throw.
[Rubric §11, Security]assesses whether a re-auth control actually re-arms on every qualifying event, not just the first one. The class subscribes toAppLifecycle.Resumedon first render regardless of the current preference, because app lock can be switched on later in the same session (comment, lines 76-77), and every resume re-reads the preference.[Rubric §18, UI Architecture & Component Design]covers the handler shape itself:OnResumed(line 125) is a plainEventHandler<AppResumedEventArgs>, so it cannot beasync; it firesReLockAsyncwith an explicit discard, and the comment (lines 119-124) states why that discard is safe here:ReLockAsyncobserves its own failures with a catch-all, which avoids the async-void crash-the-process mode (VSTHRD100), and the catch-all comment (lines 160-161) records that nothing else would observe a failed re-lock. - Concept introduced, a precondition read that fails open before opt-in and closed after it.
[Rubric §11, Security]also assesses which way a control fails when its own inputs are unreadable.ShouldLockAsyncdocuments both halves (lines 166-171): if theAppLockEnabledpreference itself cannot be read, nothing says the owner opted in, so the gate stays open rather than forcing a biometric prompt on a device that may have none enrolled; if the preference reads as on but the stored session cannot be read, the session state is unknown and the gate locks. Either way the method never throws, which matters because it runs from both the first render and the resume path. - Concept introduced, a lock that owns focus and the page behind it.
[Rubric §21, Accessibility]assesses whether a modal surface is the only thing a keyboard or screen-reader user can reach. Every lock goes throughEngageLock(lines 206-215), which sets_lockedand queues both the focus move onto Unlock and the inert background, whichever path locked the gate (start-up or resume), so focus never stays on the page behind the overlay (field comment, lines 34-39). - Walkthrough
ReLockAfter(lines 25-26) is a[Parameter]TimeSpandefaulting to 30 seconds; the comment (lines 20-24) explains the default is deliberately short, a device handed off is usually away from its owner longer than a glance at a notification.- State:
_lockRootis the overlay wrapper the inert boundary is measured from (line 31),_inertBackgroundthe lazily created helper behind theInertBackgroundproperty (lines 32, 48), and_focusUnlockPendingand_inertPendingthe two flags acted on after render (lines 40, 46). OnAfterRenderAsync(firstRender)(lines 51-89): first focuses the Unlock button if_focusUnlockPendingand the button reference now exists (lines 53-57), because that flag can only be acted on once the locked branch has actually rendered. Then, if_inertPendingand still locked, it applies the inert background to_lockRoot(lines 59-62) and releases it again at once when an unlock landed while the call was in flight (lines 64-68). OnfirstRenderit subscribes toAppLifecycle.Resumed(lines 78-79), then callsShouldLockAsyncand, if it returns true, callsEngageLockand awaitsUnlockAsync(lines 81-88).ReLockAsync(lines 127-164) returns early if already locked or if the background duration was underReLockAfter(line 131), otherwise dispatches the check,EngageLockand unlock sequence throughInvokeAsync(lines 136-146). It catchesObjectDisposedExceptionandInvalidOperationExceptionas expected teardown races (lines 148-155), and a generalExceptionlast under a scopedCA1031suppression, logged rather than rethrown (lines 156-163).ShouldLockAsync(lines 172-204) wraps the preference read in its owntry(lines 175-185): a failure is logged as a warning and returns false. A preference that is off also returns false (lines 187-190). Otherwise a secondtry(lines 192-203) returns whether a refresh token is still stored, nothing to protect without a session, and a failure there is logged and returns true (line 202). Both catch-alls carry a scopedCA1031suppression naming their disposition.UnlockAsync(lines 217-238) callsBiometrics.AuthenticateAsyncwith a localized prompt reason; success clears_lockedand both pending flags and lifts the inert background throughReleaseBackgroundAsync(lines 219-224); failure re-queues_focusUnlockPendingfor the next render (line 234). Both paths callStateHasChangedunder aBL0012suppression, becauseUnlockAsyncalso runs fromOnAfterRenderAsyncandReLockAsync, where nothing re-renders automatically (lines 225-227, 235-237).FocusUnlockAsync(lines 244-258) toleratesJSDisconnectedException(circuit gone) andInvalidOperationException(prerendering, or the element already removed).SignOutAsync(lines 268-275) callsSignOutNavigator.SignOutAsync("/login")(line 270;SignOutNavigator.cs:47), then clears_lockedand both pending flags and releases the inert background. The doc (lines 260-267) states why it is the app's own logout and never a bare token clear: clearing the tokens alone left Blazor's auth state signed in and the previous session's read cache and offline snapshots on the device. It also records why the sign-out runs through SignOutNavigator: when the page behind the overlay is[Authorize], it cannot send the next person to sign in back to the previous owner's page throughRedirectToLogin'sreturnUrl, and the one navigation is a full load that discards everything the signed-out session held in memory.ReleaseBackgroundAsync(lines 277-279) releases only when a helper exists, otherwise returns a completed task.Dispose(bool)(lines 93-110) unsubscribes fromAppLifecycle.Resumedif subscribed, guarded so it is safe to call more than once, then fires and forgets the helper'sDisposeAsyncso a gate torn down while locked does not leave the page behind it inert (lines 103-109); the publicDispose()(lines 113-117) forwards to it and suppresses finalization.
- Why it's built this way: the re-lock decision is driven entirely by wall-clock background
duration rather than any UI state, so it behaves the same whether the app was backgrounded for a
phone call or for the rest of the day. Catching broadly inside
ReLockAsyncbut narrowly insideFocusUnlockAsyncreflects the difference between an operation whose caller cannot observe a failure at all (the lifecycle event) and one whose failure just means "skip the focus this time". The two catches insideShouldLockAsyncresolve in opposite directions on purpose: before opt-in the safe default is "no lock", after opt-in it is "lock". Routing every lock throughEngageLockkeeps the start-up and resume paths from drifting apart on focus and inertness. - Where it's used: MMCA.ADC's
DeviceUIModule(MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/DeviceUIModule.cs) andApp.xaml.cs(MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/App.xaml.cs); referenced by TermsAcceptanceGate (TermsAcceptanceGate.razor.cs); pinned byBiometricGateTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Capabilities/BiometricGateTests.cs). Its place in the UI module shell is described in ADR-067 (Website/docs-src/adr/067-ui-module-shell-composition.md).
HttpResultExecutor
MMCA.Common.UI ·
MMCA.Common.UI.Services.Api·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/HttpResultExecutor.cs:35· Level 3 · class (static)
- What it is: the wrapper every UI service call runs inside. It converts the faults that survive
after a response has been handled, a refused connection, a DNS failure, a broken stream, a client
timeout, into failed Result values, so a service method
typed as returning a
Resultreally does return one. - Depends on: Result and its generic sibling
Result<T>, plus Error for the failure it mints (HttpResultExecutor.cs:2,133,136);System.Text.JsonandSystem.Net.Http(BCL) plusPolly(HttpResultExecutor.cs:3) for the fault set it recognizes. It isstaticand holds no state, so anything can call it, including services that derive from none of this package's bases. - Concept introduced, the two halves of "a client call never throws".
[Rubric §9, API & Contract Design]assesses whether the error channel between client and server is explicit and typed. The framework's answer has two pieces and this is the second one. The first, ProblemDetailsResultReader, converts a response: it reads the server's ProblemDetails body back into errors with the original ErrorType intact. This class converts the absence of a response, and the class comment states the split outright (lines 12-17). Only with both does a page get to branch on aResultinstead of writing acatch, which is what ADR-013 asks for (Website/docs-src/adr/013-result-pattern.md) and what ADR-094 records as the client contract (Website/docs-src/adr/094-client-entity-data-access.md:82-94).[Rubric §29, Resilience, Reliability & Business Continuity]applies because this is the boundary where an infrastructure fault stops being an exception and becomes something the UI can render. - Concept introduced, cancellation is not a failure.
[Rubric §24, Forms, Validation & UX Safety]assesses whether the user-facing outcome of an interaction is honest. A page cancels its own work all the time: a disposed component, a grid fetch superseded by the next keystroke. Reporting that back as an error would paint a message for something the user never did. The class therefore distinguishes two identically typed exceptions by inspecting the token, and documents the rule on itself (lines 18-24). - Walkthrough
- Two public constants name the failures it can mint,
TransportErrorCode = "Http.TransportFailure"(line 38) andTimeoutErrorCode = "Http.Timeout"(line 41). They are public because they are the branch a page uses when it needs different wording; the two English messages areinternalconstants (lines 43-47), internal rather than private so that ResultUiExtensions can recognize the executor's own sentence (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ResultUiExtensions.cs:411-416). ExecuteAsync(Func<Task<Result>>, CancellationToken)(line 56) and its generic twinExecuteAsync<T>(Func<Task<Result<T>>>, CancellationToken)(line 91) are the whole public surface. Both are structurally identical, and both start withArgumentNullException.ThrowIfNull(lines 58,- and
cancellationToken.ThrowIfCancellationRequested()(lines 63, 98). The pre-check is explained in the source (lines 60-62): an already-abandoned call must never reach the network, and the propagation contract has to hold even for an operation that would complete without ever observing the token.
- and
- The
trysimply awaits the caller's operation (lines 67, 102). Everything interesting is in the three catch clauses, and their order is the design. catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)rethrows (lines 69-72, 104-107). This filter is the entire mechanism: the caller's token being cancelled is what identifies the exception as the caller's own.- The unfiltered
catch (OperationCanceledException)(lines 73, 108) is therefore the other case:HttpClientgave up on its own timeout, which raises the same exception type with the token not cancelled. That one becomes a failure carryingTimeoutError()(lines 75, 110). catch (Exception exception) when (IsTransportFault(exception))(lines 77, 112) filters rather than catching broadly, so nothing outside the recognized set is swallowed.IsTransportFault(line 127) admits four types:HttpRequestException,IOException,JsonExceptionand Polly'sExecutionRejectedException(line 128), the base ofTimeoutRejectedExceptionandBrokenCircuitException, so a client resilience pipeline that refuses to run or finish the call also becomes a failure (HttpResultExecutor.cs:3importsPolly). The comment above it draws the line explicitly (lines 118-126): anything else is a programming fault and keeps travelling as an exception.TransportError(line 130) puts the exception's own text on the error'sSourcerather than itsMessage(lines 131-133), because that text is diagnostic detail: not localizable, and not safe to render verbatim.TimeoutError(line 135) carries no detail at all.
- Two public constants name the failures it can mint,
- Why it's built this way: the class comment records the third consequence of the split (lines
25-33): a transport failure never reached a server, so nothing localized it on the way back, which is
why the two messages are English literals and why the codes are public. A page that needs translated
wording does not read the synthesized message:
ResultUiExtensions.LocalizedErrorMessagetranslates these two by their code, first through the localizer the page passes and then, when that has no such key, through the framework's ownSharedResourcepair for the current UI culture, and a page can also branch on the code or override the translation with the same key in its own resource pair. Keeping the type static and dependency-free is what lets services outside this package's hierarchy, including a consumer app's hand-written client, adopt the same contract with one call. - Where it's used: it wraps every dispatch in this package,
EntityServiceBase<TEntityDTO, TIdentifierType>
(through the inherited
SendRequestAsyncoverloads,MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:179,209), ChildEntityServiceBase (directly inDeleteByIdAsync,MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/ChildEntityServiceBase.cs:75, and through the same inheritedSendRequestAsyncoverloads for bothPostAsyncoverloads,:45,61), AuthUIService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:242,255,301,315,342,453) and NotificationInboxService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NotificationInboxService.cs:46,64,84,101). Outside the framework it is called directly by services that sit outside the base hierarchy: Store's cart and lookup services (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.UI/Services/ShoppingCarts/CartStateService.cs:93,140,174,206,260,297,MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.UI/Services/Lookups/CustomerLookupService.cs:27,73,MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.UI/Services/Lookups/ProductVariantLookupService.cs:29,94) and Helpdesk's single API client (MMCA.Helpdesk/Source/Hosts/UI/MMCA.Helpdesk.UI.Web/Services/HelpdeskApiClient.cs:30,50,64,84,95,109,122,138,149). Its own behavior is pinned by HttpResultExecutorTests, including the code literals (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Api/HttpResultExecutorTests.cs:29-30), the timeout-versus-cancellation split (:150,164,178) and the rethrow paths (:192,206,219,230,240). - Caveats: a
JsonExceptionis classified as a transport fault, so a server that answers 200 with a body the client cannot deserialize produces the same generic "check the connection" message as a refused socket; the distinction is available in the error'sSourcebut not in its code. The two user-facing messages are hard-coded English at the source; they reach a localized UI only when the page renders them throughLocalizedErrorMessage, which replaces the sentence only while the error still carries the executor's own text (ResultUiExtensions.cs:378-381,409-416), so a page that displaysError.Messagedirectly still shows English.
PagedReadAll
MMCA.Common.UI ·
MMCA.Common.UI.Services.Api·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/PagedReadAll.cs:18· Level 3 · class (static)
- What it is: a helper that reads every row of an entity controller's
/pagedendpoint by requesting page after page until the server's reported total is reached, for hand-written services that need the whole set in one list (class summary, lines 7-10). - Depends on: Result and
Result<T>for the return shape, Error for the truncation failure (Error.Unexpected, line 100), and PagedCollectionResult<T> with its PaginationMetadata for each page (all imported throughMMCA.Common.Shared.Abstractions, line 3). Externals: BCLCultureInfo,string.Create,System.Diagnostics.CodeAnalysis(lines 1-2). - Concept introduced, a single read truncates silently.
[Rubric §19, State Management & Data Flow]assesses whether the data a page holds is the data the server has. The remarks (lines 11-17) record the trap: the API clamps any requested page size to its own maximum (ApplicationSettings.MaxPageSize, 500 by default), and the GET-all endpoint ignorespageSizeand always returns that maximum, so rows past it vanish with nothing to say so. Paging untilPaginationMetadata.TotalItemCountis reached is the only unbounded route.[Rubric §29, Resilience, Reliability & Business Continuity]applies to the loop bound: a server that misreports its total cannot make the client spin forever, and when the bound is what stops the read the caller gets a named failure, not a partial list presented as a complete one. - Walkthrough
PageSize(line 21) is a publicconst intof 500, the API's default maximum, so no request is clamped (summary, line 20).TruncatedCode(line 27) is a publicconst stringof"PagedReadAll.Truncated", theError.Codeof the failure the runaway guard produces (summary, lines 23-26).MaxPages(line 33) is a privateconstof 40, the guard of 20,000 rows (summary, lines 29-32).LookupPageUrl(string entity, int pageNumber)(line 48) builds{entity}/paged?pageNumber=...&pageSize=500&sortColumn=Id&sortDirection=asc&includeFKs=false&includeChildren=falsewithstring.Create(CultureInfo.InvariantCulture, ...)(lines 49-51). Sorting byIdascending keeps consecutive pages from skipping or repeating a row, and the doc comment (lines 35-40) makes the exact text part of a contract: a host that warms its output cache by replaying these URLs must replay them byte for byte. TheCA1055suppression (lines 44-47) keeps the return a string for that reason, since callers both compose it as text and wrap it as a relativeUri.ReadAllAsync<T>(Func<int, Task<Result<PagedCollectionResult<T>>>> fetchPage, CancellationToken)(line 66) null-guards the delegate (line 70) and loopspageNumberfrom 1 toMaxPages(line 74). Each iteration checks cancellation first (line 76), fetches the page (line 78), and returns the first failure unchanged asResult.Failure<List<T>>(result.Errors)(lines 79-82). An empty page returnsResult.Success(accumulated)(lines 85-88); otherwise the items are accumulated (line 90) and the method returns success once the count reachesTotalItemCount(lines 92-95).- Falling out of the loop means 40 pages were read with the total still unreached, so the method
returns
Result.Failure<List<T>>(Error.Unexpected(TruncatedCode, ...))with a message naming the page cap and the rows read (lines 100-104). The comment (lines 98-99) states the reason: a partial list returned as a success is exactly the silent truncation this type exists to prevent.
- Why it's built this way: the fetch is a delegate rather than an
HttpClient, so each caller keeps its own transport choice (an authenticatedSendRequestAsync, or an anonymous IdempotentReadRetry GET) and its own filters, while the paging rule lives once. Returning aResultrather than throwing keeps it inside the framework's client contract that a page branches on failures instead of catching them, and the publicTruncatedCodelets a caller (or a test) tell the guard apart from a server error. - Where it's used: inside the framework,
EntityServiceBase<TEntityDTO, TIdentifierType>
.GetAllAsyncfalls back to it when the GET-all answer was cut at the page cap (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:83), and its page URL reusesPagedReadAll.PageSize(EntityServiceBase.cs:265). ADC UI servicesSpeakerLookupService(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Speakers/SpeakerLookupService.cs:57),EventLookupService(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Events/EventLookupService.cs:58),CategoryItemLookupService(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Categories/CategoryItemLookupService.cs:60),OrganizerFeedbackService(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Feedback/OrganizerFeedbackService.cs:26,68), and in EngagementSessionLookupService(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/Lookups/SessionLookupService.cs:26) andQuestionLookupService(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/Lookups/QuestionLookupService.cs:31). The ADC Conference service'sSelfHttpOutputCacheWarmupTaskreplays URLs in theLookupPageUrlshape (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/SelfHttpOutputCacheWarmupTask.cs:42). Pinned byPagedReadAllTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Api/PagedReadAllTests.cs).OrganizerFeedbackServicecomposes its own filtered/pagedURLs withPagedReadAll.PageSizerather thanLookupPageUrl(OrganizerFeedbackService.cs:31,73), since it needs anEventIdorSessionIdfilter.
ScopedMemo<T>
MMCA.Common.UI ·
MMCA.Common.UI.Services.Api·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/ScopedMemo.cs:31· Level 3 · class (sealed, generic)
- What it is: a per-scope, single-flight memo for one lookup read: the primitive a Scoped UI lookup service (an id-to-name dictionary every grid needs) composes so a user walking several pages pays one round trip per time-to-live instead of one per page (class summary, lines 5-9).
- Depends on: Result through its generic sibling
Result<T>, imported fromMMCA.Common.Shared.Abstractions(line 1), for the fetch's return shape and itsIsSuccesstest (line 110). Externals: BCLTimeProvider(line 35),TaskandDateTimeOffset. - Concept introduced, memoize the task, not the value.
[Rubric §19, State Management & Data Flow]assesses whether the data a page holds is fetched and shared deliberately rather than re-read on every render. The remarks (lines 12-15) make the cached unit the TASK, so concurrent callers within one scope share a single in-flight fetch instead of starting one each, and keep only a successfulResult<T>for the time-to-live: a faulted task, a canceled one and a failed result all expire at once, so a transient outage heals on the next read rather than being remembered.[Rubric §14, Testability]assesses whether time-dependent behavior can be driven deterministically: every timestamp comes from the injectedTimeProvider(lines 82, 112), so a test advances a fake clock instead of waiting. - Walkthrough
ScopedMemo(Func<Task<Result<T>>> fetch, TimeSpan timeToLive, TimeProvider timeProvider)(line 61) null-guards the fetch and the clock and rejects a time-to-live of zero or less (lines 63-65). The fetch is called with no caller token, since it is shared, and should return a failure rather than throw for a server answer (parameter doc, lines 55-58).- The state is three fields:
_cached, the shared fetch, in flight or completed (line 38);_cachedUntil, left atDateTimeOffset.MinValueuntil a fetch actually succeeds, which is what makes a non-answer expire immediately (lines 40-44); and_generation, bumped byInvalidate(lines 46-50). GetAsync(CancellationToken cancellationToken = default)(line 78) reuses the entry unless there is none, or it has completed and the clock has reached_cachedUntil(line 82); only then does it reset the expiry and start a new fetch (lines 84-86). A fetch still in flight is always reused. When the token can be canceled the shared task is wrapped inWaitAsync(line 89), so a page disposing mid-load abandons only its own await, never the fetch the other pages share (remarks, lines 18-19).Invalidate()(line 96) bumps the generation, drops the entry and resets the expiry (lines 98-100); the remarks (lines 20-21) say to call it from the scope's own write services.FetchAsync()(line 103) captures the generation (line 105), awaits the fetch (line 106), and stamps_cachedUntilas now plus the time-to-live only when the result is a success and the generation is unchanged (lines 110-113). The time-to-live therefore measures the age of the data rather than the age of the attempt (comment, lines 108-109), and a fetch superseded byInvalidatecompletes unobserved without stamping the entry that replaced it.
- Why it's built this way: no lock guards the state (remarks, lines 24-27). The rule is one instance per Scoped service: Blazor's renderer dispatches every component callback for one scope (a server circuit, or the WASM app) on a single logical thread, so the read-modify-write never interleaves with itself. A Singleton holder would share one user's lookup with every other user and would need its own synchronization.
- Where it's used: no production code in Common, ADC or Store constructs it at the documented
commits. It is pinned by ScopedMemoTests
(
MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Api/ScopedMemoTests.cs:15), whose summary (lines 8-14) records that it was lifted from the ADCEventLookupServiceandSpeakerLookupServicecopies. Those ADC services still carry their own inline memo fields (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Events/EventLookupService.cs:46,53,MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Speakers/SpeakerLookupService.cs:42). - Caveats: an in-flight fetch never expires (the expiry test applies only to a completed entry, line 82), so a fetch that hangs is shared by every caller in the scope until it completes; each caller can still bail out through its own token.
IAuditHistoryUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auditing·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auditing/IAuditHistoryUIService.cs:11· Level 3 · interface
- What it is: the UI client contract for an audit-history endpoint
(AuditHistoryControllerBase, ADR-075):
one page of an entity's recorded changes, newest first (
IAuditHistoryUIService.cs:6-10). - Depends on:
Result<T>and AuditHistoryEntryDTO (IAuditHistoryUIService.cs:1-2). - Concept introduced: none new; it follows the same "no failure throws" client contract taught at ILegalAcceptanceUIService. The returns doc states the method never throws for a server answer (line 23).
- Walkthrough: one member,
GetPageAsync(routePrefix, entityAlias, entityKey, page, pageSize, cancellationToken)(line 24), reading{routePrefix}/{entityAlias}/{entityKey}?page={page}&pageSize={pageSize}(lines 13-16). The route prefix is the host's (for exampleAdmin/Catalog/AuditHistory), the alias is the name the endpoint knows the entity by, and the key is the entity id as an invariant string (lines 17-19). - Why it's built this way: the route prefix is a parameter rather than configuration because each
module host mounts its own audit-history controller, so one registered client serves every module.
Its signature lines up with AuditHistoryPanel's
FetchPagedelegate once a page binds the first three arguments. - Where it's used: implemented by AuditHistoryService and registered by
AddAuditHistoryUIwithTryAddScoped(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:402-404); resolved by ADC's EventDetail (route prefixAdmin/Conference/AuditHistory,MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Events/EventDetail.razor.cs:37,44) and SessionDetail.
ILegalAcceptanceUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Legal·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Legal/ILegalAcceptanceUIService.cs:16· Level 3 · interface
- What it is: the UI-side contract for Terms of Service acceptance: read the signed-in user's
standing, and record an acceptance of the version the user was shown. It is the dependency behind
TermsAcceptanceGate (
TermsAcceptanceGate.razor.cs:61). - Depends on:
Result<T>(ILegalAcceptanceUIService.cs:1) andLegalAcceptanceDTO(MMCA.Common.Shared.Legal,ILegalAcceptanceUIService.cs:2); both calls targetLegalAcceptanceRoutes.Path(ILegalAcceptanceUIService.cs:11). - Concept introduced, no failure should block the user.
[Rubric §9, API & Contract Design]assesses whether the client treats the API's error channel as a typed contract. The remarks say every member returns aResultcarrying the API's own errors, including a 404 for a host that serves no such endpoint, and nothing throws for a server answer or a transport fault, so a caller can treat any failure as "do not block" (ILegalAcceptanceUIService.cs:10-15). - Walkthrough:
GetAsync(cancellationToken)reads the standing viaGET Users/me/legal-acceptance(:21).AcceptAsync(version, cancellationToken)records an acceptance viaPOST Users/me/legal-acceptanceand returns the standing after acceptance (:27). - Why it's built this way: an interface keeps the gate component testable and lets a host swap the
transport. The framework registers the default with
TryAddScoped(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:220), so a consumer's own registration wins. - Where it's used: implemented by LegalAcceptanceUIService; consumed
by TermsAcceptanceGate and by ADC's
LegalAndDataCard(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/LegalAndDataCard.razor.cs).
AuthenticatedServiceBase
MMCA.Common.UI ·
MMCA.Common.UI.Services.Api·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:21· Level 4 · class (abstract)
- What it is: the base class every UI-side HTTP service inherits. It supplies one shared Polly
retry policy, two ways to get an
HttpClientwith a bearer token already attached, and the idempotency-key generator that makes those retries safe. - Depends on: ITokenStorageService, imported from the token namespace
MMCA.Common.UI.Services.Auth.Tokens(AuthenticatedServiceBase.cs:6); its documentation also names AuthDelegatingHandler as the thing it deliberately bypasses andAuth.Tokens.ITokenRefresher, that is ITokenRefresher, as the source of the replay token. FromMMCA.Common.Shared.Resilience(AuthenticatedServiceBase.cs:5) it reads RetryAfterHeader and theMaxRetryAfterWaitceiling on HttpResilienceDefaults. It also tests its storage for ISessionAwareTokenStorage (AuthenticatedServiceBase.cs:106), tells AuthDelegatingHandler which storage a bearer came from (AuthDelegatingHandler.TrackTokenOwner,AuthenticatedServiceBase.cs:88), and reads the header name from IdempotencyHeaders (AuthenticatedServiceBase.cs:242). FromMMCA.Common.Shared.Http(AuthenticatedServiceBase.cs:4) it also asks CommitOutcomeUnknown whether a response marks a commit with an unknown outcome (AuthenticatedServiceBase.cs:285). Externals:IHttpClientFactory,TimeProvider,PollyandPolly.Retry. - Concept introduced, why a base class and not just the handler pipeline.
[Rubric §29, Resilience & Business Continuity]assesses whether transient failures are absorbed rather than surfaced; the retry policy is that. The sharper teaching is in theCreateAuthenticatedClientAsyncdoc comment (AuthenticatedServiceBase.cs:67-72):IHttpClientFactorycreates its handlers in a separate DI scope from the Blazor circuit, so aDelegatingHandlercannot reach the circuit'sIJSRuntimeto read the in-memory access token. The base class works around that by reading the token from the circuit-scoped storage service itself and setting the header directly.[Rubric §9, API & Contract Design]covers the idempotency half: retrying a POST is only safe if the server can recognize the repeat, which is what ADR-017 provides. - Walkthrough
RetryPolicyis aprotected static readonly AsyncRetryPolicy<HttpResponseMessage>built once from the shipped backoff (AuthenticatedServiceBase.cs:41), so one policy instance serves the whole app rather than one per service instance per circuit.ApiClientNamepins the named client to"APIClient"(AuthenticatedServiceBase.cs:43), and both constructor arguments are null-checked into private fields (AuthenticatedServiceBase.cs:45-46).SharedRetryPolicy(AuthenticatedServiceBase.cs:52) is aninternal staticgetter that returns that sameRetryPolicyinstance. Its doc comment (AuthenticatedServiceBase.cs:48-51) names the only reader, IdempotentReadRetry, which reuses the exact policy object without inheriting from this class, so the anonymous read path and the authenticated one cannot drift apart.NewIdempotencyKey()(AuthenticatedServiceBase.cs:65) returns a compactGuid.NewGuid().ToString("N"), and its remarks (AuthenticatedServiceBase.cs:57-63) carry the load-bearing rule: the value is generated once per logical operation and reused across every retry attempt, because the server-side idempotency filter keys its cached response off it. Generating a new key per attempt would defeat the dedup entirely and let a retry create a duplicate record.CreateAuthenticatedClientAsync()(AuthenticatedServiceBase.cs:73) resolves the"APIClient"(AuthenticatedServiceBase.cs:75), reads the token (AuthenticatedServiceBase.cs:79), setsAuthorization: Bearerwhen non-blank (AuthenticatedServiceBase.cs:80-83), and catchesInvalidOperationExceptionto proceed without a token during SSR prerender, when JS interop is unavailable (AuthenticatedServiceBase.cs:91-94). When it attaches a bearer it also callsAuthDelegatingHandler.TrackTokenOwner(token, _tokenStorageService)(AuthenticatedServiceBase.cs:88): the handler in the client's pipeline holds a different storage instance (its own DI scope), so it is told which instance the bearer came from, and a 401 to it reaches the storage the component's auth state listens to (comment,:85-87).StorageRenewsRejectedTokens(AuthenticatedServiceBase.cs:106) is aprotectedflag that is true when the storage is an ISessionAwareTokenStorage. Its doc comment (AuthenticatedServiceBase.cs:99-105) states the contract: such storage has already had the ONE renewal a 401 earns made on it by AuthDelegatingHandler before the 401 reaches the caller, so a caller replaying the request reads the renewed token instead of refreshing a second time.ReadRenewedAccessTokenAsync(string? rejectedToken)(AuthenticatedServiceBase.cs:117) is that read: it returnsnullwhen no bearer was sent (:119-122), and otherwise re-reads storage (:124) and returns the value only when it is non-blank and differs ordinally from the refused token (:125-127), so a session the renewal ended, or a storage still holding the refused token, yields nothing to replay with.CreateClientWithToken(string accessToken)(AuthenticatedServiceBase.cs:138) is the replay path. Its doc comment (AuthenticatedServiceBase.cs:130-136) explains why it exists: after the API answers401, the stored token still looks fresh by the client clock, so re-reading storage would just resend the token the server has already rejected. The caller passes the token it acquired straight from ITokenRefresher; the method rejects a blank one (AuthenticatedServiceBase.cs:140) and stamps the header unconditionally (AuthenticatedServiceBase.cs:143).IsRetryableResponse(HttpResponseMessage, TimeProvider)(AuthenticatedServiceBase.cs:278) is the retry predicate. It first excludes501 Not Implementedand505 HTTP Version Not Supported(AuthenticatedServiceBase.cs:280-283) because, as the remarks say (AuthenticatedServiceBase.cs:264-277), those are permanent verdicts and retrying only burns the budget and delays the error the caller needs to see. It then refuses any responseCommitOutcomeUnknown.Isrecognizes (AuthenticatedServiceBase.cs:285-288): a response carrying theX-Commit-Outcome: unknownheader (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/CommitOutcomeUnknown.cs:34-37, checked atCommitOutcomeUnknown.cs:59-62). The remarks (AuthenticatedServiceBase.cs:272-276) give the reason: the write may already be durable, and the server stores no idempotency record for a non-2xx, so a resend under the same key would run it again. This refusal applies whatever the request, so even a keyed POST is not retried. It next refuses any response for whichRetryAfterHeader.ExceedsRetryBudgetis true (AuthenticatedServiceBase.cs:290-293;MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/RetryAfterHeader.cs:75): a 429 whoseRetry-Afterasks for longer thanHttpResilienceDefaults.MaxRetryAfterWait, 8 seconds (MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/HttpResilienceDefaults.cs:40), means the rate-limit window will not reset within any wait worth holding the user for, so the refusal surfaces at once. It then asksIsReplaySafewhether the request may be sent again and gives up if not (AuthenticatedServiceBase.cs:295-298). Only then does it accept anything>= 500plus408 Request Timeoutand429 Too Many Requests(AuthenticatedServiceBase.cs:300-301), the two codes where the server is explicitly inviting a later attempt.IsReplaySafe(HttpRequestMessage? request)(AuthenticatedServiceBase.cs:314) is the gate that keeps a retry from duplicating a write. Its doc comment (AuthenticatedServiceBase.cs:304-311) states the rule: GET, HEAD, PUT, DELETE and the other idempotent verbs are always safe to re-send, while a POST or PATCH is safe only when it carries a non-blankIdempotency-Keyheader, which an[Idempotent]endpoint deduplicates on. Without a key, a failed attempt may still have run server-side, and a retry can hit a rate limit and replace the server's real failure with a 429. A response with no request attached is treated as safe (AuthenticatedServiceBase.cs:316-319). The method isinternal staticso a test can pin it directly, and the doc comment onRetryPolicy(AuthenticatedServiceBase.cs:25-40) carries the same POST/PATCH caveat.- The exception arm of the policy sees no response, so it learns replay safety another way.
MarkReplaySafety(HttpRequestException, HttpRequestMessage)(AuthenticatedServiceBase.cs:347) storesIsReplaySafe(request)inexception.Dataunder theinternal const ReplaySafeDataKey(:336); AuthDelegatingHandler, the outermost handlerAddUISharedadds to the API client, calls it (doc comment:338-344, which notes that on a host callingAddServiceDefaultsthe service-discovery handler wraps it, and so does the standard resilience handler unless the host removes it, asAddMmcaBlazorWebHostdoes).IsRetryableException(:358) then retries a transport failure unless it was marked not replay-safe (a POST or PATCH without anIdempotency-Key) AND failed after the request may have been sent: onlyNameResolutionError,ConnectionErrorandSecureConnectionError(failures before send, the rule the gRPC client applies) still retry (:359-362, doc:350-357). An unmarked exception keeps the retry (Data[...] is not false,:359). DefaultBackoff(int attempt)(AuthenticatedServiceBase.cs:372-374) is the shipped schedule:500 * 2^(attempt - 1)milliseconds (0.5s, 1s, 2s for retries 1, 2 and 3) plus up to 250 ms of random jitter, so a fleet of clients does not re-converge on the same instant. It isinternalso a test can pin the schedule (doc:366-371). TheRetryPolicydoc comment (AuthenticatedServiceBase.cs:25-40) explains why the schedule is short: a read that fails fast spends at most about 4.25 seconds waiting between attempts before it surfaces, a backend that accepts the request and then hangs is cut off by the client's own timeout instead (HttpResilienceDefaults.TotalRequestTimeout, which the comment gives as 90 seconds, set where the API client is registered) and that cancellation is not retried, and a 429 that names aRetry-Afteris outside the 4.25-second bound because each such retry can wait up to the cap. TheCA5394suppression around it (AuthenticatedServiceBase.cs:364) documents that the randomness only spaces retries and feeds no security decision.RetryDelay(int attempt, HttpResponseMessage? response, Func<int, TimeSpan> backoff, TimeProvider timeProvider)(AuthenticatedServiceBase.cs:387-395, doc:377-386) picks the wait before each retry. For a429 Too Many RequestswhoseRetry-Afterparses throughRetryAfterHeader.TryGetDelay(MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/RetryAfterHeader.cs:43) it waits exactly the named delay; everything else, including a 5xx and a transport failure with no response, keeps the backoff. The predicate has already refused a 429 overMaxRetryAfterWait, so the delay used here is bounded. TheTimeProvideris the clock a date-formRetry-Afteris measured against.BuildRetryPolicy(Func<int, TimeSpan> backoff, TimeProvider? timeProvider = null)(AuthenticatedServiceBase.cs:414-430) isinternaland backoff- and clock-injectable so a test can exercise the disposal andRetry-Aftercontracts without waiting out the real delays; a null clock falls back toTimeProvider.System(AuthenticatedServiceBase.cs:418). It retries 3 times (AuthenticatedServiceBase.cs:422-423), withsleepDurationProviderrouted throughRetryDelay(AuthenticatedServiceBase.cs:424). ItsonRetryAsyncdisposes the retried attempt's response (AuthenticatedServiceBase.cs:425-429); the remarks (AuthenticatedServiceBase.cs:401-408) explain that Polly hands the caller only the final outcome (the policy handlesHttpRequestExceptionthroughIsRetryableException,:420, and responses throughIsRetryableResponse,:421), so without this every intermediate 5xx, 408 or 429 response leaks its content buffer and keeps its connection out of the handler pool until finalization, exactly under the sustained backend failure the retries exist to survive. A retriedHttpRequestExceptioncarries no result, hence the null-conditional, and the final response is not disposed here because the caller owns it.
- Why it's built this way: the DI scope mismatch is a real Blazor Server constraint, not a preference, so the workaround has to live somewhere every service shares. The retry ceiling and jitter line up with the resilience posture in ADR-009.
- Where it's used: inherited by
EntityServiceBase<TEntityDTO, TIdentifierType>
(
MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:38), ChildEntityServiceBase (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/ChildEntityServiceBase.cs:23), AuditHistoryService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auditing/AuditHistoryService.cs:24) and NotificationInboxService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NotificationInboxService.cs:34), and through them by every module-level UI service in the consumer apps. The members show up asNewIdempotencyKey()on creates and updates (EntityServiceBase.cs:180andEntityServiceBase.cs:204),RetryPolicy.ExecuteAsyncaround each call inside this class's ownSendRequestAsyncoverloads (AuthenticatedServiceBase.cs:185andAuthenticatedServiceBase.cs:213), which everyEntityServiceBaserequest goes through (EntityServiceBase.cs:177,EntityServiceBase.cs:201,EntityServiceBase.cs:226andEntityServiceBase.cs:252), andCreateClientWithTokenon the 401 replay (NotificationInboxService.cs:154). The policy itself is also reached without inheritance by IdempotentReadRetry (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/IdempotentReadRetry.cs:24), which gives anonymous lookup services the same retries on GETs.
IdempotentReadRetry
MMCA.Common.UI ·
MMCA.Common.UI.Services.Api·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/IdempotentReadRetry.cs:18· Level 2 · class (static)
- What it is: the retry that AuthenticatedServiceBase applies, made
reachable without inheriting from it, so a service that makes anonymous reads (a lookup service that
creates a plain
APIClient) gets three retries instead of a single attempt (class summary, lines 5-8). - Depends on: AuthenticatedServiceBase for the policy instance, read
through its
internalSharedRetryPolicy(line 24,MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:52). Externals:Polly.Retry(AsyncRetryPolicy<HttpResponseMessage>, line 1) and BCLHttpClient. - Concept introduced, retry is only safe for an idempotent verb.
[Rubric §29, Resilience, Reliability & Business Continuity]assesses whether transient failures are absorbed rather than surfaced on every call path, not just the inherited one.[Rubric §9, API & Contract Design]covers the limit: the class remarks (lines 9-16) state that the policy re-sends on anHttpRequestException, a 5xx other than 501/505, 408 or 429, up to three times with 2s, 4s, 8s backoff plus jitter, and that re-sending is only safe when doing the operation twice is the same as doing it once. That is why the only entry point is a GET; a write that needs retries goes through EntityServiceBase<TEntityDTO, TIdentifierType>, whose creates carry anIdempotency-Keythe server deduplicates on. - Walkthrough
Policy(line 24) is aninternal staticgetter returningAuthenticatedServiceBase.SharedRetryPolicy. Its doc comment (lines 20-23) stresses that it is the same object, not a copy built from the same settings, so the two paths cannot drift.GetAsync(HttpClient httpClient, Uri requestUri, CancellationToken cancellationToken)(line 35) null-guards both arguments (lines 40-41) and returnsPolicy.ExecuteAsync(token => httpClient.GetAsync(requestUri, token), cancellationToken)(line 43), so the token is honored between attempts and by each send. The doc comment (lines 26-34) sets the ownership rule: every retried response is disposed by the policy, the caller owns and disposes the final one, andHttpRequestExceptionescapes only when every attempt failed without a response.
- Why it's built this way: sharing the instance rather than re-declaring the policy keeps one
definition of "retryable" and one backoff schedule for the whole UI layer, including the
response-disposal behavior of
AuthenticatedServiceBase.BuildRetryPolicy. Exposing a GET-only surface instead of a generalExecuteAsyncis the guardrail: the type cannot be used to retry a non-idempotent write by accident. - Where it's used: ADC lookup services that read anonymously, for example
SpeakerLookupService(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Speakers/SpeakerLookupService.cs:62),EventLookupService(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Events/EventLookupService.cs:63),CategoryItemLookupService(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Categories/CategoryItemLookupService.cs:77),SessionLookupService(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/Lookups/SessionLookupService.cs:27,58) andNowNextService(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/HappeningNow/NowNextService.cs:26). Several of them pass it as the per-page fetch inside PagedReadAll. Pinned byIdempotentReadRetryTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Api/IdempotentReadRetryTests.cs).
AuditHistoryService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Auditing·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auditing/AuditHistoryService.cs:21· Level 4 · class (sealed)
- What it is: the default HTTP implementation of IAuditHistoryUIService, built on the shared authenticated client.
- Depends on: AuthenticatedServiceBase (base class, line 24), ITokenStorageService (constructor parameter, line 23), HttpResultExecutor (line 43) and ProblemDetailsResultReader (line 51).
- Concept introduced: none new; it is the
FeatureFlagAdminService shape the remarks name (lines 13-18): non-2xx
answers come back through the problem-details reader with the API's own
ErrorType, transport faults become failures through the executor, and the GET retries through the base's sharedRetryPolicy. - Walkthrough:
GetPageAsync(line 27) rejects a null or blank route prefix, alias or key (lines 35-37), builds the relative URL withstring.Createunder the invariant culture, trimming a trailing slash from the prefix and escaping the alias and key withUri.EscapeDataString(lines 39-41), then insideHttpResultExecutor.ExecuteAsynccreates the authenticated client (line 46), sends the GET throughRetryPolicy(lines 47-49) and reads the body asIReadOnlyList<AuditHistoryEntryDTO>(lines 51-52). - Why it's built this way: the audit trail is opt-in (ADR-075), so the client is registered only
when a host calls
AddAuditHistoryUI(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:402-404), and it reuses the client data-access conventions of ADR-094 (Website/docs-src/adr/094-client-entity-data-access.md) rather than inventing its own error handling. - Where it's used: resolved through IAuditHistoryUIService by the
pages that host an AuditHistoryPanel. Pinned by
AuditHistoryServiceTests and
ApiClientRegistrationTests.
ChildEntityServiceBase
MMCA.Common.UI ·
MMCA.Common.UI.Services.Api·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/ChildEntityServiceBase.cs:20· Level 5 · class (abstract)
- What it is: the two-verb service base for join entities, the many-to-many rows a UI can create
and delete but never lists or edits on their own. It offers
PostAsync(in two shapes) andDeleteByIdAsyncover the named"APIClient", and nothing else. - Depends on: AuthenticatedServiceBase (base class, supplying the
authenticated client factory,
ChildEntityServiceBase.cs:23), ITokenStorageService (constructor parameter, passed straight through, line 22), HttpResultExecutor and ProblemDetailsResultReader (both reached only through the inheritedSendRequestAsyncoverloads, which all three methods now call, lines 45, 61 and 83), Result and ErrorType (line 1;ErrorType.NotFoundis named in the delete's summary, line 68);IHttpClientFactoryandSystem.Net.Http.Json(BCL). - Concept introduced, a base class shaped by the resource rather than by convention.
[Rubric §18, UI Architecture & Component Design]assesses whether the presentation layer talks to the backend through typed services rather than rawHttpClientcalls in components. The interesting design choice here is what is absent: a join row likeSessionSpeakerhas no list page, no edit form and no lookup, so this base deliberately does not implement IEntityService<TEntityDTO, TIdentifierType>. Giving join services the full CRUD surface would hand pages six operations of which four have no endpoint behind them.[Rubric §1, SOLID Principles]reads this as interface segregation applied at the service-base level: the smaller base cannot promise what the API does not serve. - Walkthrough
- The primary constructor takes
IHttpClientFactory,ITokenStorageServiceand astring endpoint, forwarding the first two toAuthenticatedServiceBase(lines 20-23). The endpoint is captured as a primary-constructor parameter rather than exposed as a property, so subclasses cannot rewrite it; contrast EntityServiceBase<TEntityDTO, TIdentifierType>, which surfacesprotected string Endpoint { get; }because its own methods build sub-paths from it. PostAsync<TResponse>(object request, CancellationToken)(line 44) is for an endpoint that answers with the created DTO. It hands a one-line POST-as-JSON lambda to the inheritedAuthenticatedServiceBase.SendRequestAsync<TResponse>(lines 45-46) together with a freshly mintedidempotencyKey: NewIdempotencyKey()(line 48), so the call takes the same dispatch as an entity create: the executor outside,RetryPolicyin the middle,ProblemDetailsResultReaderinnermost (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:171-189), with the key set once on the client every attempt shares (AuthenticatedServiceBase.cs:236-243). Therequestparameter is typedobjecton purpose, and the doc comment explains why (lines 29-33). The three protected methods return a task directly (protected Task<...>, notasync) (lines 44, 60, 80). Join payloads are anonymous objects,System.Text.Jsonserializes the runtime type for anobjectdeclaration, and a generic request parameter would force a caller to name a type it cannot spell.PostAsync(object request, CancellationToken)(line 60) is the same call for an endpoint that answers 204, routed through the body-lessSendRequestAsyncoverload (lines 61-64) with its own fresh key (line 64). The two overloads exist because the reader treats a missing body as a failure on the generic path.DeleteByIdAsync(string id, CancellationToken)(line 80) builds"{endpoint}/{id}"(line 82) and hands a one-line DELETE lambda to the body-less inheritedSendRequestAsyncoverload (lines 83-85) with noidempotencyKey, so the removal takes the same dispatch asEntityServiceBase.DeleteAsync: the executor outside,RetryPolicyin the middle, the reader innermost. The remarks (lines 74-79) give the reason: a DELETE is replay-safe, so a transient failure or a 429 is retried instead of failing the remove, and it carries noIdempotency-Key. A join row that is not there answers 404, which arrives as anErrorType.NotFoundfailure rather than a barefalse, so a caller can still separate "nothing to remove" from "the remove failed" (documented at lines 67-69).- The id parameter is a
string, not a typed identifier: subclasses format their own key before calling. ADC's four join services route it through one helper that also appends the parent key as a query parameter,ChildEntityDeletePath.For(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Common/ChildEntityServices.cs:62-73), which is why the whole difference between a removal that works and one the API answers 404 to sits in a single place.
- The primary constructor takes
- Why it's built this way: join endpoints sit behind
[Authorize]exactly like their parent CRUD endpoints, so they need the same bearer plumbing and the same error contract, but none of the paging, filtering or lookup machinery. Deriving from AuthenticatedServiceBase rather than from EntityServiceBase<TEntityDTO, TIdentifierType> reuses the auth path while keeping the surface honest. The join adds follow the sibling's retry rule: the join creates are[Idempotent]endpoints, so eachPostAsyncmints oneIdempotency-Keyper call and holds it across every attempt ofRetryPolicy(class summary, lines 14-16; remarks, lines 37-43). An attempt that landed and only lost its response is then replayed by the server's idempotency filter instead of being refused as a duplicate join row, while a manual retry by the user is a new call with a new key (ADR-017,Website/docs-src/adr/017-request-idempotency.md). The removal is retried through the same policy but stays keyless, since a DELETE is replay-safe on its own (lines 74-85). ADR-094's risk list still describes both join POSTs as keyless and every join call as unretried (Website/docs-src/adr/094-client-entity-data-access.md:473-477), which the source no longer matches. - Where it's used: three ADC Conference join services derive from it, all in one file,
SessionSpeakerService on
sessionspeakers, SessionCategoryItemService onsessioncategoryitemsand SpeakerCategoryItemService onspeakercategoryitems(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Common/ChildEntityServices.cs:22,35,48). Each adds a typedAddAsync/DeleteAsyncpair over the two protected methods and implements its own module interface (for example:24-28). The base is pinned by ChildEntityServiceBaseTests. - Caveats: the base's behavior is pinned by tests for a fresh key per call and the same key on a
retried attempt for both overloads, for no key on the delete, and for the delete retrying through
the shared policy
(
MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Api/ChildEntityServiceBaseTests.cs:109,127,148,165,181). NeitherPostAsyncoverload exposes the response headers, so an endpoint answering201 Createdwith aLocationheader gives the caller no way to read it.
EntityServiceBase<TEntityDTO, TIdentifierType>
MMCA.Common.UI ·
MMCA.Common.UI.Services.Api·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:35· Level 4 · class (abstract)
- What it is: the CRUD workhorse of the UI layer. It implements IEntityService<TEntityDTO, TIdentifierType> against a REST endpoint by turning each operation into a URL plus a one-line HTTP lambda, and funnels every one of them through two dispatch methods that own retry, idempotency, conditional writes, error translation and deserialization (class summary, lines 11-28). Reads go straight to the API: there is no client read cache.
- Depends on: AuthenticatedServiceBase (base class, line 38),
IEntityService<TEntityDTO, TIdentifierType> (implemented
interface, line 38),
IBaseDTO<TIdentifierType> (the
TEntityDTOconstraint, line 39), BaseLookup<TIdentifierType> (line 138), CollectionResult<T> and PagedCollectionResult<T> with its PaginationMetadata (lines 71, 78, 129, 143), PagedReadAll (lines 83, 265), IConcurrencyAware and ConcurrencyETag (lines 216-218, andAuthenticatedServiceBase.cs:253in the inherited dispatch), IdempotencyHeaders (AuthenticatedServiceBase.cs:242), ProblemDetailsResultReader (AuthenticatedServiceBase.cs:186,214), HttpResultExecutor (AuthenticatedServiceBase.cs:179,209) and ITokenStorageService (constructor parameter, line 38); Polly through the inheritedRetryPolicy, andSystem.Net.Http.Json(BCL). - Concept introduced, one dispatch point for every cross-cutting HTTP concern.
[Rubric §29, Resilience, Reliability & Business Continuity]assesses whether retry, auth and error handling are applied in one place instead of repeated per call: the six public methods contain only URL construction, and the twoSendRequestAsyncoverloads inherited from AuthenticatedServiceBase (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:171,201), reached directly or throughSendGetAsync<T>(line 248), contain all of the policy.[Rubric §19, State Management & Data Flow]applies because components never touchHttpClient: they inject the typed interface and receive DTOs wrapped in aResult.[Rubric §29, Resilience, Reliability & Business Continuity]applies through the inherited three-retry exponential-backoff-with-jitter policy (class summary, line 15;MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:41), whose predicate never retries 501 or 505 (AuthenticatedServiceBase.cs:280). - Concept introduced, retry safety for a non-idempotent verb.
[Rubric §9, API & Contract Design]assesses whether client and server share an explicit protocol for duplicate writes. A retry policy that re-issues a POST is a correctness hazard: if the first attempt reached the server and only the response was lost, the retry creates a second record.AddAsyncandUpdateAsyncboth pass a key (lines 180 and 204), minted byAuthenticatedServiceBase.NewIdempotencyKey()as a compact GUID (AuthenticatedServiceBase.cs:65); the class summary states the rule (line 16). The key is set as a default request header on the client (AuthenticatedServiceBase.cs:242) rather than per request, and that one client instance serves every retry attempt, so all attempts carry the identical value (the comment atAuthenticatedServiceBase.cs:238-241says exactly that). The retry predicate enforces the same rule from the other side: a POST or PATCH response is retried only when its request carried a non-blank key (AuthenticatedServiceBase.IsReplaySafe,AuthenticatedServiceBase.cs:295,314), so a keyless write is sent once. On an update the key does a second job (comment, lines 197-200): a PUT whose first attempt landed and only lost its response is replayed by the server from the stored 204 instead of being re-run against the version it just replaced, which would answer 412 and tell the user someone else changed the item. The server side is the opt-in IdempotencyFilter, and both ends read the header name from the shared IdempotencyHeaders constant. Reads andDeleteAsync(lines 226-229) send no key. - Concept introduced, the conditional write.
[Rubric §24, Forms, Validation & UX Safety]assesses whether the UI protects a user from silently overwriting somebody else's work.UpdateAsyncsends the DTO's concurrency token as anIf-Matchentity tag (line 205), and that header is the only route the token travels (remarks at lines 185-190). A DTO carrying no token sends no header, and the server answers428 Precondition Requiredrather than accepting a blind write.ConcurrencyTagOf(line- is the whole rule: a DTO that implements
IConcurrencyAware with a non-empty
RowVersionis formatted byConcurrencyETag.Format, anything else yieldsnull(lines 216-218). This is ADR-035 (Website/docs-src/adr/035-optimistic-concurrency.md) seen from the client.
- is the whole rule: a DTO that implements
IConcurrencyAware with a non-empty
- Concept introduced, "get all" means all.
[Rubric §19, State Management & Data Flow]assesses whether the list a page holds is the list the server has. The GET-all endpoint answers with only its firstApplicationSettings.MaxPageSizerows (500 by default) and reports the full count in the paging metadata (remarks, lines 52-58).GetAllAsyncchecks that count and, when rows are missing, re-reads the whole set through PagedReadAll, so the list returned is every entity or a failure, never a silent first page. - Walkthrough
- The primary constructor takes
endpoint,IHttpClientFactoryandITokenStorageService(lines 35-38); note the parameter order differs from ChildEntityServiceBase. Both type parameters are constrained,TEntityDTO : IBaseDTO<TIdentifierType>andTIdentifierType : notnull(lines 39-40).Endpointis republished as a protected property (line 42) because the read methods append sub-paths to it. PagedIncludeFKs(line 49) is aprotected virtual boolthat defaults tofalse, so the paged URL is unchanged by default; a service whose list grid shows a foreign-key name (a product's category) overrides it totrue, andGetPagedAsyncthen appendsincludeFKs=True(lines 110-113). Only the paged read has this hook:GetAllAsynctakesincludeFKsas an argument (line 60).GetAllAsync(includeFKs, includeChildren, ct)(line 59) builds a two-parameter query string (lines 64-70) and reads the paged envelope (line 71), passing a failure through unchanged (lines 72-75). When the first answer already holdsTotalItemCountrows it returns them (lines 77-81), so a set within one page costs one request. Otherwise it callsPagedReadAll.ReadAllAsyncover the privateAllPagesUrl(lines 83-86) and maps the list (line 88).AllPagesUrl(line 262) targets{Endpoint}/pagedwithPagedReadAll.PageSize,sortColumn=Id&sortDirection=ascand the caller's include flags (lines 263-265).GetPagedAsync(filters, pageNumber, pageSize, sortColumn, sortDirection, includeChildren, ct)(line 92) formats page numbers withstring.Create(CultureInfo.InvariantCulture, ...)(lines 103-104) so a comma-decimal locale cannot corrupt the query, and every sort value, filter property, operator and value goes throughUri.EscapeDataString(lines 105-106, 121, 123). Filters serialize asfilters[Property].operator=plus an optionalfilters[Property].value=(lines 121-123), and a filter whose operator is blank is skipped entirely (line 119), which is how a grid clears a column filter. It targets{Endpoint}/paged(line 128) and maps the envelope to the(Items, TotalItems)tuple a server-side data grid binds to (lines 133-134).GetAllForLookupAsync(nameProperty, ct)(line 138) hits{Endpoint}/lookup(line 142) and maps aCollectionResult<BaseLookup<TIdentifierType>>to its items (lines 143-145), the lightweight id-plus-name shape that feeds dropdowns and autocompletes.GetByIdAsync(id, includeChildren, ct)(line 149) returnsSendGetAsync's task directly (line 164). A missing entity is aNotFoundfailure, not a null, so the caller can tell it apart from a transport failure via ResultUiExtensions.IsNotFound(comment, lines 161-163).AddAsync(entity, ct)(line 168) POSTs with an idempotency key (lines 177-181).UpdateAsync(entity, ct)(line 191) PUTs to{Endpoint}/{GetEntityId(entity)}(line 195) with both an idempotency key and theIf-Matchtag (lines 201-206).DeleteAsync(id, ct)(line 221) DELETEs{Endpoint}/{id}(lines 225-229).GetEntityId(entity)(lines 232-233) isprotected virtualand returnsentity.Id, the hook a subclass overrides when the route key is not the DTO's own id.SendGetAsync<T>(url, ct)(line 248) is protected so a derived service's own read takes the same path (summary, lines 235-239): it guards the url (line 250) and issues the GET throughSendRequestAsync<T>(lines 252-254). TheCA1054suppression (lines 244-247) keeps the url a string, since the read methods already build the exact relative path plus escaped query.AsReadOnlyList(line 271) presents a deserializedItemscollection without assuming the JSON reader produced a list (lines 272-277).- The dispatch itself is inherited, not declared here:
SendRequestAsync<T>(AuthenticatedServiceBase.cs:171) andSendRequestAsync(AuthenticatedServiceBase.cs:201) are structurally identical and both return the executor's task directly rather than awaiting it (protected Task<...>, noasync): null-guard the lambda (AuthenticatedServiceBase.cs:177,207), wrap everything in HttpResultExecutor (:179,209), build a client for this one logical operation (:184,212), execute the caller's lambda throughRetryPolicywith the cancellation token threaded in so a cancelled operation does not sleep out its backoff (:185,213), and hand the response to ProblemDetailsResultReader (:186,214). The generic overload fails a 2xx with no body via the reader'sEmptyResponseCode, which is why the body-less overload exists at all (documented atAuthenticatedServiceBase.cs:166-170). The client is kept in scope across the read on purpose (comment atAuthenticatedServiceBase.cs:182-183). CreateRequestClientAsync(idempotencyKey, ifMatch)(AuthenticatedServiceBase.cs:232), also inherited, starts fromCreateAuthenticatedClientAsync(AuthenticatedServiceBase.cs:234) and is where both conditional headers are attached (AuthenticatedServiceBase.cs:236-254), each with a comment stating the retry property it preserves: the same key on every attempt (:238-241), and the same precondition on every attempt so a write that lost the race fails consistently instead of succeeding on a later attempt against a version the caller never saw (:247-252). That comment also ties the two together: when the first attempt landed and only its response was lost, the key sent besideIf-Matchlets the server replay the stored outcome instead of re-checking the precondition against the version that attempt just wrote.
- The primary constructor takes
- Why it's built this way: passing the HTTP call as a
Func<HttpClient, Task<HttpResponseMessage>>lets each verb stay a two-line method while every policy decision lives once. The composition inside the dispatch is the load-bearing part, and ADR-094 records it as the client contract (Website/docs-src/adr/094-client-entity-data-access.md:172): the executor outside, the retry policy in the middle, the reader innermost. Nothing here throws for a server answer, so a 404, a validation rejection and a 500 are all failures a page can branch on; the only exception that still escapes is the caller's own cancellation (class comment, lines 23-28). All six public methods arevirtual, so a module service overrides only the one that needs domain-specific behavior and inherits the rest. - Where it's used: it is the base of essentially every module CRUD service. ADR-094's inventory as
of 2026-11-23 counts twenty production subclasses: eleven in ADC (ten in Conference, including
EventService and
SessionService, plus Identity's
UserListService), eight in Store, and one inside the
framework itself, PushNotificationService
(
Website/docs-src/adr/094-client-entity-data-access.md:265-284). The consumer on the page side is DataGridListPageBase<TDto>, which is handed aGetPagedAsynccall as its fetch delegate. Behavior is pinned by EntityServiceBaseTests, EntityServiceBaseIdempotencyRetryTests (the key's presence and its constancy across attempts) and EntityServiceBaseValueLessFilterTests. - Caveats: when the GET-all answer is short, the full set is read again from page 1 through
/paged, so the first 500 rows are fetched twice; and a set larger than PagedReadAll's 40-page guard (20,000 rows) comes back as aPagedReadAll.Truncatedfailure rather than a list. The class holds no client-side read cache: the constructor takes only the endpoint, the client factory and the token store (lines 35-38), and ADR-094 records the cache's removal (Website/docs-src/adr/094-client-entity-data-access.md:95).GetPagedAsyncaccepts afiltersdictionary that the signature does not declare nullable (line 93), yet the body null-checks it (line 115): defensive against a caller the signature says cannot exist.
LegalAcceptanceUIService
MMCA.Common.UI ·
MMCA.Common.UI.Services.Legal·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Legal/LegalAcceptanceUIService.cs:22· Level 4 · class (sealed)
- What it is: the default ILegalAcceptanceUIService: a small HTTP service that reads and records the signed-in user's Terms acceptance against the framework's legal-acceptance route.
- Depends on: AuthenticatedServiceBase (base class,
:26) for the bearer-token client andRetryPolicy, ITokenStorageService (constructor,:24-25), HttpResultExecutor and ProblemDetailsResultReader for the error contract, plusLegalAcceptanceRoutes.Path,LegalAcceptanceDTOandAcceptLegalTermsRequestfrom the Shared project. - Concept introduced, the same dispatch recipe, minus the generic base.
[Rubric §29, Resilience, Reliability & Business Continuity]applies through the shared pipeline shape ADR-094 records (Website/docs-src/adr/094-client-entity-data-access.md): executor outside, reader innermost. The class does not derive from EntityServiceBase<TEntityDTO, TIdentifierType> because the route is not CRUD, so each method composes the pieces itself. - Walkthrough
GetAsync(:29) is notasyncitself: it returns theHttpResultExecutor.ExecuteAsynctask directly (:30), creates the authenticated client (:33), sends the GET throughRetryPolicy.ExecuteAsync(:34) and reads the response withProblemDetailsResultReader.ReadAsync<LegalAcceptanceDTO>(:38).AcceptAsync(:44, likewise a plainTask-returning method) rejects a blankversionsynchronously (:46), then returns the executor task the same way (:48) but posts anAcceptLegalTermsRequest(version)straight through the client (:52-55) withoutRetryPolicy, so the write is sent once. This fits the replay rule: the retry predicate would not retry a keyless POST anyway (AuthenticatedServiceBase.cs:295-298).
- Why it's built this way: keeping it
sealedand thin leaves the gate component with one mockable interface, and the executor guarantees the "any failure means do not block" contract the interface documents. - Where it's used: registered as the scoped default for the interface
(
MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:220) and exercised byLegalAcceptanceUIServiceTests(MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Legal/LegalAcceptanceUIServiceTests.cs).
MoneyExtensions
MMCA.Common.UI ·
MMCA.Common.UI.Extensions·MMCA.Common/Source/Presentation/MMCA.Common.UI/Extensions/MoneyExtensions.cs:14· Level 5 · class (static)
- What it is: the presentation-layer formatter for money, turning a
Moneyvalue object into$12.50 USDand a collection of them into a per-currency range such as$10.00 - $25.00 USD, formatted under a caller-chosen or ambient culture. - Depends on:
Moneyand itsCurrency(bothMMCA.Common.Shared.ValueObjects), plusCultureInfo.CurrentCultureandStringComparer.Ordinal(BCL). - Concept introduced, formatting lives in the UI layer, not the value object.
[Rubric section 3, Clean Architecture](assesses whether presentation concerns stay out of the inner layers:Moneyknows amounts and currencies, it does not know what a price looks like) and[Rubric section 20, Design System and Theming](assesses consistent presentation of a recurring data shape; one formatter means every price on every page reads the same). It also shows the C#extension(T)preview syntax used for something other than DI: two blocks, one onMoneyand one onIReadOnlyCollection<Money>, sit in a single static class so both spellings (price.ToDisplayString()andprices.ToDisplayRange()) are available from oneusing. - Walkthrough:
- The class carries a file-level
[SuppressMessage("Naming", "CA1708")](lines 10-13): with two or moreextension(T)blocks in one static class, CA1708 flags the compiler-generated grouping members as case-colliding. The justification records that no user-visible identifier differs only by case, a known analyzer trap of the preview syntax. extension(Money price)(lines 16-31) exposesToDisplayString(CultureInfo? culture = null)(lines 29-30), which delegates toFormatGroup(price.Amount, price.Amount, price.Currency.Code, culture): passing the same value as both bounds is what makes the shared helper render a single price rather than a degenerate range. Left unset,cultureresolves insideFormatGrouptoCultureInfo.CurrentCulture, the request's culture as already set by its culture provider; a caller passes one explicitly only when rendering off the reader's thread (a background job, an export, a test).extension(IReadOnlyCollection<Money> prices)(lines 33-64) exposesToDisplayRange(CultureInfo? culture = null)(lines 47-63): returnsstring.Emptyfor an empty collection (lines 49-52), resolvesculture ?? CultureInfo.CurrentCultureonce intoresolved(line 54, ahead of the grouping), then groups byCurrency.CodewithStringComparer.Ordinaland formats each group from its own min and max underresolved(lines 58-60), joining the groups with", "(line 62). Grouping is the load-bearing detail: a mixed-currency collection renders one range per currency, each with its own symbol, instead of collapsing unrelated amounts under whichever currency appeared first. The inline comment notesGroupBypreserves first-appearance order, so the single-currency case (every collection in practice today) is unchanged. Resolving the culture once outside theSelectand passing it into everyFormatGroupcall is what keeps a one-element range and the single price it holds reading identically: the two paths must not drift.Symbol(string code)(lines 71-76), a private switch mapping"USD"to$and"EUR"to the escaped euro sign (line 74, escaped to keep the source file ASCII-only). Every other code, including the empty code of theCurrency.Nonesentinel behindMoney.Zero()(MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Financial/Currency.cs:25,Money.cs:186), renders with no symbol rather than falsely claiming dollars.FormatGroup(decimal min, decimal max, string code, CultureInfo? culture)(lines 88-97), the single formatting path: resolvesculture ?? CultureInfo.CurrentCulture(line 90), then renders a single price whenmin == maxand a hyphen-separated range otherwise, each bound throughFormatAmount(lines 92-94), and appends the trailing code only when it is non-empty (line 96). Only the digit grouping and decimal separator follow the culture; the currency symbol and the trailing ISO code always come from the money itself, so a USD price stays USD in every locale.FormatAmount(decimal amount, string symbol, CultureInfo culture)(lines 103-106) formats one amount with"N2"under the resolved culture, so an English reader gets$1,234.56and a Spanish reader gets$1.234,56. A negative amount puts the sign before the symbol (-$5.00, not$-5.00) by formattingMath.Abs(amount)behind a leading-, which keeps the culture's digit grouping intact (lines 99-102).
- The class carries a file-level
- Why it's built this way: presentational formatting belongs above the domain, so
Moneystays display-agnostic and the same value can be rendered differently by a different head. The move from a hardcodedCultureInfo.InvariantCultureto a caller-optional, request-defaultedCultureInfo.CurrentCulturelets the number format follow the reader's culture (a Spanish reader's thousands and decimal separators) while the currency symbol and ISO code stay tied to the money's own currency, so the price never implies a currency the data does not carry. The optional parameter keeps every existing call site source-compatible while opening a path for a background job, an export, or a test to format under an explicit culture instead of the ambient one. - Where it's used: Store's Sales and Catalog UIs.
ToDisplayString()renders order totals and line amounts (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.UI/Pages/Orders/OrderLinesPanel.razor:63,:39,:51;Pages/Order/OrderSummaryPanel.razor:54;Pages/Order/OrderList.razor:36,:102) and the cart's order-created snackbar (Pages/ShoppingCart/ShoppingCartDetail.razor.cs:354);ToDisplayRange()renders the price span across a product's variants in catalog browse (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.UI/Pages/Catalog/CatalogBrowse.CardFormatting.razor.cs:38, with the single-price helper alongside it at:41) and on the catalog product detail page (Pages/Catalog/CatalogProductDetail.razor.cs:266,:269). None of these call sites pass acultureargument, so all of them format under the ambientCultureInfo.CurrentCulture. Covered byMoneyExtensionsTests. - Caveats / not-in-source: only
USDandEURhave symbols; adding a currency means editingSymbol, there is no configuration-driven table. The"N2"format assumes a two-minor-unit currency, so a zero-decimal currency (JPY) would render two spurious decimals; no code guards that today.
AnonymousApiRequest
MMCA.Common.UI ·
MMCA.Common.UI.Services.Api·MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AnonymousApiRequest.cs:14· Level 4 · class (internal, static)
- What it is: the framework-internal builder for a request to an anonymous API endpoint (sign-in,
registration, password reset, email confirmation, the passkey sign-in options) that the
"APIClient"pipeline sends without a bearer header (class summary, lines 5-13). - Depends on: AuthDelegatingHandler for its
SkipBearerrequest-option key (imported at line 1, set at line 34; the key is declared atMMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthDelegatingHandler.cs:45). Externals: BCLHttpRequestMessage,HttpMethodandJsonContent(System.Net.Http.Json). - Concept introduced: none new; it applies the per-request bearer opt-out that AuthDelegatingHandler already honors for the token-refresh POST. The summary (lines 7-12) gives both reasons the opt-out matters on an anonymous call: the handler does not read the token storage, so on WebAssembly and MAUI an expired stored token cannot trigger a refresh round trip before the user has even signed in, and a 401 is not reported to the storage as a rejected session, so a wrong password does not end the session the device may still hold.
- Walkthrough
PostJson<TBody>(string relativeUrl, TBody body)(line 21) serializes the payload withJsonContent.Create(body)and delegates toPost(line 22).Post(string relativeUrl, HttpContent? content)(line 28) creates aPOSTHttpRequestMessageagainst a relativeUri(line 30) with the given content,nullmeaning an empty POST (line 32), setsrequest.Options.Set(AuthDelegatingHandler.SkipBearer, true)(line 34) and returns it. The caller sends and disposes the request (returns docs, lines 20 and 27).
- Why it's built this way: the opt-out travels on the request rather than through a second named
client, so anonymous and authenticated calls share one
"APIClient"pipeline (base address, culture and the other handlers) and differ only by an option the auth handler reads. Keeping the classinternal(line 14) leaves it a helper of the framework's own auth clients rather than public surface. - Where it's used: AuthUIService for forgot-password
(
MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:261), the sign-in-link request (AuthUIService.cs:277), the passkey sign-in options with an empty body (AuthUIService.cs:422) and two further anonymous posts (AuthUIService.cs:305,457); and EmailConfirmationUIService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/EmailConfirmationUIService.cs:46).
TermsAcceptanceGate
MMCA.Common.UI ·
MMCA.Common.UI.Components.Legal·MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Legal/TermsAcceptanceGate.razor.cs:29· Level 7 · class (partial, component)
- What it is: the code-behind for the blocking consent dialog a signed-in user sees when the current terms version is one they have not accepted. It listens to the authentication state, reads the user's standing once per identity, and shows a modal whose only exits are accepting or signing out.
- Depends on: first-party: ILegalAcceptanceUIService (
GetAsyncandAcceptAsync), SignOutNavigator (SignOutAsync(destination)for the sign-out exit), LegalSettings (the bound options the dialog body reads), LegalAcceptanceDTO (the standing:CurrentVersion,AcceptedVersion,IsCurrent), SharedResource (the localizer anchor), and ClaimsPrincipalExtensions (IsViewAs(),MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:170, read atTermsAcceptanceGate.razor.cs:139). Externals:Microsoft.AspNetCore.Components.Authorization(AuthenticationStateProvider),MudBlazor(DialogOptions,MaxWidth),Microsoft.Extensions.Options,Microsoft.Extensions.Localization,Microsoft.Extensions.Logging(ILogger<T>),System.Security.Claims(ClaimsPrincipal), BCLCancellationTokenSource,IDisposable. - Concept introduced, a gate that cannot be dismissed by the framework and re-asks only when the identity or the version changes.
[Rubric §19, State Management & Data Flow]assesses how per-user UI state is coordinated across navigation and authentication changes. Three pieces of state keep this honest, all private fields (lines 47-55): the cached_standing, the_checkedUserKeyit belongs to, and the_visibleflag.- Not dismissible, on purpose.
DialogOptions(lines 37-45) turns offBackdropClick,CloseOnEscapeKey,CloseOnNavigationandCloseButton. The summary (lines 31-36) records the real failure behindCloseOnNavigation = false: the dialog provider dismisses every open dialog onLocationChanged, and a list page rewrites its own URL (page, sort, filter) right after loading, which closed the gate for the rest of the session while consent was still owed. - Identity-keyed evaluation.
UserKey(lines 131-132) is the user-id claim, else the identity name, else empty.EvaluateAsync(lines 134-184) returns early when the key equals_checkedUserKey(lines 147-151), so a token refresh that re-raises the authentication event does not re-read the standing; only a change of key (sign-in, account switch) does. An unauthenticated principal clears the key and hides the dialog (lines 139-145). - Out of the way under view-as. The same early exit fires when
user.IsViewAs()is true (line 139). The comment (lines 136-138) gives the reason: under view-as the principal is the viewed user, whose standing is not the staff user's to accept, and the accept POST is a write view-as refuses, so the dialog could be neither satisfied nor dismissed. Clearing_checkedUserKeymeans the standing is read again once the view ends. - Stale-response guard. After the awaited read, the method compares the key again and drops the result if the user changed while it was in flight (lines 165-169), because the newer evaluation owns the outcome. The dialog shows only when the read succeeded and
CurrentVersionis non-null andIsCurrentis false (line 171); any failed read hides it, so a transport fault never locks a user out of the app. [Rubric §15, Best Practices and Code Quality]assesses precedent reuse: the discarded-task event handler and its exhaustive catch follow theBiometricGateprecedent named in the comments (lines 248-249, 271-272), see BiometricGate. The sign-out exit reuses the shared SignOutNavigator rather than hand-rolling a logout plus navigation (comment lines 232-233).
- Not dismissible, on purpose.
- Walkthrough
- Injected members (lines 57-73):
AuthStateProvider,LegalAcceptance,SignOutNavigator,LegalOptions,L, andLogger.Heading(lines 78-80) picks the "first" title whenAcceptedVersionis null and the "updated" title when the user accepted an earlier version. OnAfterRenderAsync(bool firstRender)(lines 90-102) returns on later renders, subscribes toAuthenticationStateChanged(line 97), sets_subscribed, then evaluates the current principal (lines 100-101).AcceptAsync(lines 186-230) requires a version, the agreement checkbox, and!_busy(lines 188-192). On success it hides the dialog (lines 199-203). If the server refuses withLegalAcceptanceErrorCodes.VersionNotCurrent, the version moved while the dialog was open, so it clears the cached key and re-evaluates (lines 207-213), showing the version that is current now instead of retrying a stale one. Any other failure sets the error text: a validation refusal uses the server-phrased message, everything else (transport fault, timeout, server error) uses the gate's own localizedLegal.Gate.AcceptFailed(lines 218-220, comment lines 215-217). Cancellation is swallowed (lines 222-225) and_busyis cleared infinally(lines 226-229).SignOutAsync(lines 234-238) sets_busyand returnsSignOutNavigator.SignOutAsync("/login")(line 237): one sign-out and one forced navigation to the login page. The comment (lines 232-233) records why: the gate sits over whatever page the user is on, and a plain logout followed by a navigation on a protected page was raced byRedirectToLogin's own navigation; the navigator makesRedirectToLoginstand down while its sign-out is in flight (MMCA.Common.UI/Services/Navigation/SignOutNavigator.cs:7-30).OnAuthenticationStateChanged(line 250) discards intoReevaluateAsync(lines 252-275), which awaits the new state, marshalsEvaluateAsyncthroughInvokeAsync, and catchesObjectDisposedException,InvalidOperationException, and finally a bareExceptionthat is logged (lines 259-274); the last tier exists because the event handler discards the task, so nothing else would observe a fault.Dispose(bool)(lines 106-125) unsubscribes only if subscribed, cancels_disposalCtsonce, and disposes it; the token source is passed to both service calls (lines 158, 198), so teardown mid-request ends through the cancellation path.
- Injected members (lines 57-73):
- Why it's built this way: consent is owed, so the gate must survive everything that normally closes a dialog (navigation, Escape, backdrop) and must not nag when nothing changed (token refresh) or when it cannot know (failed read). Keying the cache on identity and re-reading on a version-conflict code keeps it correct across account switches and mid-dialog version bumps. Routing the sign-out exit through one navigator guarantees the user lands on
/loginrather than on whatever redirect the page underneath would issue. See ADR-116 for the identity-completions context. - Where it's used: contributed as a layout component by the ADC
IdentityUIModule(LayoutComponentTypes = [typeof(TermsAcceptanceGate)],MMCA.ADC.Identity.UI/IdentityUIModule.cs:49); the client it calls, ILegalAcceptanceUIService, is registered for every host (MMCA.Common.UI/DependencyInjection.cs:220), as is SignOutNavigator (MMCA.Common.UI/DependencyInjection.cs:199).
DependencyInjection
MMCA.Common.UI.Web ·
MMCA.Common.UI.Web·MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/DependencyInjection.cs:19· Level 6 · class (static)
- What it is: the registration extensions for the server-side Blazor Web host pieces this package ships: three
IServiceCollectionmethods a host calls fromProgram.csinstead of registering app-local copies of the token store (which also forwards the visitor's origin on server-side API calls), the CSP provider (including its options and their startup validation), and the trusted-caller rate-limit exemption. - Depends on: first-party: ServerTokenStorageService + ITokenStorageService, BrowserOriginHandler (the
"APIClient"message handler), BlazorCspPolicyProvider + ICspPolicyProvider, BlazorCspSettings (the bound"BlazorCsp"options) + BlazorCspSettingsValidator (itsIValidateOptions<BlazorCspSettings>), TrustedCallerHandler (the delegating handlerAddTrustedCallerHeadercomposes), GatewayRateLimitingSettings (the shared configuration section for both ends) and ApiSettings (the server-side endpoint the origin gate is built from). Externals:Microsoft.Extensions.DependencyInjection(IServiceCollection,AddScoped,AddSingleton,AddHttpContextAccessor,ConfigureAll<HttpClientFactoryOptions>),Microsoft.Extensions.DependencyInjection.Extensions(TryAddEnumerable),Microsoft.Extensions.Options(AddOptions,BindConfiguration,ValidateOnStart),Microsoft.Extensions.Configuration(IConfiguration). - Concept: the same
extension(IServiceCollection services)block idiom used package-wide (line 21, see primer). What is worth studying here is that the XML docs carry operational rules the compiler cannot enforce, and they are the only place those rules are written down next to the code.[Rubric §15, Best Practices and Code Quality]assesses idiom consistency; everyMMCA.Common.*package registers services through the same extension shape, so a reader who has seen one registrar has seen them all.[Rubric §26, Front-End Security]assesses browser hardening wiring;AddCommonBlazorCsp()is what actually puts BlazorCspPolicyProvider in front of the default static provider, and its doc (lines 55-57) encodes the ordering rule: call it beforeAddCommonSecurityHeaders, because the default is registered withTryAddand would otherwise win.[Rubric §22, Configuration and Secrets Management]assesses whether a bad configuration value is caught before it can silently degrade a live host;ValidateOnStart()(line 70) is what turns a badBlazorCsp:FrameSourcesentry into a boot failure instead of a policy that quietly omits the frame source.[Rubric §19, Rate Limiting and Throttling]assesses whether a legitimate internal caller can be told apart from the anonymous crowd it is partitioned with;AddTrustedCallerHeaderis that opt-in exemption for this host's own server-to-server calls.
- Walkthrough
AddCommonServerTokenStorage()(lines 40-50): callsservices.AddHttpContextAccessor()(line 42), the accessor ServerTokenStorageService needs to tell SSR from circuit. It then registers BrowserOriginHandler as a transient and appends it to the named"APIClient"client withAddHttpClient("APIClient").AddHttpMessageHandler<BrowserOriginHandler>()(lines 46-47). The doc (lines 30-38) says each server-side request then carriesX-Forwarded-Forset to the remote IP andUser-Agentset to the browser's user-agent of the HTTP request behind the render (the page request during prerender, the circuit's connection afterwards), so per-client limits such as the registration rate limit key on the visitor rather than on this host, and a sign-in records the visitor's device; nothing is sent when no request is in scope. The comment (lines 44-45) notes a secondAddHttpClientwith the same name appends to the client registered byAddUIShared, whichever runs first. Finally it registers ServerTokenStorageService as the scoped ITokenStorageService (line 49). Scoped is the right lifetime: a circuit is a DI scope, so the in-memory access token is per-session state. The doc (lines 23-29) names the two companions this registration assumes,AddServerAuthSessionCookieandUseCookieSessionRefreshfromMMCA.Common.API, plus a registered ITokenRefresher.AddCommonBlazorCsp()(lines 66-77) does three things. It binds BlazorCspSettings from the"BlazorCsp"configuration section and callsValidateOnStart()(lines 68-70); it registers BlazorCspSettingsValidator as anIValidateOptions<BlazorCspSettings>throughTryAddEnumerable, so calling this method twice never runs the same validation twice (comment at line 72, registration lines 73-74); and it registers BlazorCspPolicyProvider as a singleton ICspPolicyProvider (line 76), matching the provider's compute-once constructor.AddSingleton(notTryAdd) is what makes the replacement deterministic. The doc (lines 59-63) states the configuration contract:BlazorCsp:FrameSourceslists the https origins the host's pages may frame, emitted asframe-src 'self' <origins>; an absent or empty list leaves the policy unchanged, and an invalid entry fails the boot rather than being silently dropped.AddTrustedCallerHeader(IConfiguration configuration)(lines 112-150) is opt-in: it reads GatewayRateLimitingSettings and, whenTrustedCallerSecretis blank (the local/CI default), orTrustedCallerHeaderNameis blank, or the server-sideApiSettings.ApiEndpointis missing or not an absolute URI, registers nothing at all (lines 124-129). The remarks (lines 86-109) give three reasons in full: opt in, no secret means every call stays rate limited exactly as today, and the gateway must read the sameGatewayRateLimitingsection so one section configures both ends; server only, the secret must reach this SSR host alone (GatewayRateLimiting__TrustedCallerSecret) and never the WebAssembly client or a rendered page; and why every client, the cookie-session token-refresh client is created under a name a host cannot reach, so the composition targets everyHttpClientthis host builds viaservices.ConfigureAll<HttpClientFactoryOptions>(...)(lines 143-147) rather than one named client. When it does register, it inserts TrustedCallerHandler atAdditionalHandlers.Insert(0, ...)(lines 145-147), notAdd: the comment (lines 134-142) explains that index 0 is the outermost handler, so the origin gate judges the authority the caller configured rather than the authority Aspire's service-discovery handler rewrites mid-pipeline, and that ordering holds regardless of whether a host callsAddServiceDefaultsbefore or after this method.
- Why it's built this way: all three pieces are host-level infrastructure that carry no app-specific state, so they were hoisted into
MMCA.Common.UI.Weband exposed as one-line registrations. Binding and validating BlazorCspSettings insideAddCommonBlazorCsp()itself, rather than leaving it to the host, means a host that opts intoframe-srcgets the fail-fast contract for free instead of having to know to add its ownValidateOnStart().AddTrustedCallerHeaderfollows the deployment's gateway rate-limiting policy: a per-client-IP partition that a trusted internal caller would otherwise collapse into, exempted only when the deployment explicitly configures a shared secret. That keeps every consumer'sProgram.csfree of duplicated token-store, CSP and rate-limit-exemption wiring, which is the reusable-building-blocks charter of this group. See ADR-022 for the session design the first method plugs into, and ADR-070 for the fail-fast-on-boot postureValidateOnStart()follows. - Where it's used: called from the
Program.csof the server-interactive Blazor Web hosts in the consumer apps (MMCA.ADC, MMCA.Store). - Caveats / not-in-source: the doc comment and the provider's fail-closed
connect-src 'self'fallback now agree (BlazorCspPolicyProvider.cs:57-59); which host binds aBlazorCsp:FrameSourceslist, if any, is not visible from this file.
⬅ Module System, Composition & Configuration • Index • Aspire Orchestration & Service Defaults ➡