↑↓ to navigate Enter to open "…" all these words ANDOR to combine

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:manage into 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) and NameFor(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's perm:: the API's policy provider, which a web host may install by replacement, intercepts every perm: name, while a page-perm: name falls through to the default provider and so reaches the policy AddUIShared registered. 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 referencing Prefix, 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 permission claim equal to Permission.
  • 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(...).Assembly handle on the shared UI assembly.
  • Depends on: nothing.
  • Concept introduced, the assembly-marker type. Reflection over an assembly needs an Assembly instance, 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. CommonArchitectureMap registers the assembly as the framework's UI layer with Framework(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; AnonymousEndpointTests includes it in the assemblies it scans (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Api/AnonymousEndpointTests.cs:19); and NavigationContractTests enumerates its types with typeof(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>() passes typeof(TModule).Assembly to AddAssignableTypes (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's RequiredPermission check the claim with the same HasPermissionClaim (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 at MMCA.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 from AuthorizeAttribute, 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 passes PagePermissionPolicy.NameFor(permission) to the base as the policy name and keeps the raw permission (HasPagePermissionAttribute.cs:23-24), exposed as Permission (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, because AddUIShared registers one policy per permission declared on a component in MMCA.Common.UI or 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 its Permission value (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, HasPermissionClaim from ClaimsPrincipalExtensions (PagePermissionAuthorizationHandler.cs:2); AuthorizationHandler<TRequirement>.
  • Concept: cross-reference NotificationPageAuthorizationHandler, which uses the same HasPermissionClaim for 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), calls context.Succeed(requirement) only when context.User.HasPermissionClaim(requirement.Permission) (:22-25), and returns Task.CompletedTask (:27). It never calls Fail, so a missing claim simply leaves the requirement unmet.
  • Why it's built this way: the doc comment (PagePermissionAuthorizationHandler.cs:6-11) calls HasPermissionClaim the 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 adds RequireAuthenticatedUser() (PagePermissionPolicyConfigurator.cs:39), so an unauthenticated principal never passes.
  • Where it's used: registered by AddUIShared through TryAddEnumerable as a transient IAuthorizationHandler (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.Reflection and Microsoft.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 whether AddUIShared was called before or after the Add{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's Assembly (:25), plus the framework's own UI assembly (:26), deduplicated (:27), flattened to their types through LoadableTypes (:28), each type's HasPagePermissionAttributes read with inherit: true (:29), projected to Permission (:30) and deduplicated ordinally (:31). For each permission it computes the policy name (:35) and, only when options.GetPolicy(name) is null (:36), adds a policy that requires an authenticated user and a PagePermissionRequirement (:38-40). LoadableTypes (:47-57) returns assembly.GetTypes() and, on a ReflectionTypeLoadException, 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 the TryAdd convention 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 AddUIShared through TryAddEnumerable as a transient IConfigureOptions<AuthorizationOptions> (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:111-112); its module list comes from the AddSingleton<IUIModule, TModule>() that AddUIModule<TModule>() performs (DependencyInjection.cs:499).
  • Caveats / not-in-source: the framework assembly is scanned too (:26), but no .razor or .cs file under MMCA.Common/Source/Presentation applies 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 one extension(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 through using MMCA.Common.DependencyInjection (DependencyInjection.cs:7). Externals: MudBlazor, and Microsoft.AspNetCore.Authorization plus Microsoft.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 inside extension(IServiceCollection services) (DependencyInjection.cs:38) rather than as classic this-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 other DependencyInjection classes 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) and TryAddEnumerable registers the source-generated ApiSettingsValidator as its IValidateOptions<ApiSettings> (:52); the comment (:46-48) records why: the validator checks the data annotations with no reflection and no Options.DataAnnotations package on a WebAssembly client. A missing ApiEndpoint therefore 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 the TryAdd (:77-79): a host that already registered one, as AddInfrastructure does, keeps it, and a test substitutes a FakeTimeProvider.
      • Page policies. One AddAuthorizationCore call (:86-102) registers three policies: NotificationPageRequirement.PolicyName carrying a plain NotificationPageRequirement (:88-90), NotificationPageRequirement.ManagePolicyName carrying one built with NotificationPermissions.Manage (:91-93), the policy for the history and compose pages, and TwoFactorPageRequirement.PolicyName carrying a TwoFactorPageRequirement (:99-101). TryAddEnumerable adds the transient NotificationPageAuthorizationHandler and TwoFactorPageAuthorizationHandler (:103-106). The comments state the shared rule: [Authorize] semantics (plus notifications:manage for the history and compose pages), except that a host without the notification UI (no AddNotificationUI) 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 without AddTwoFactorUI, and its policy is registered unconditionally so the page's attribute resolves in every host (:95-98). Then the page permission guards: TryAddEnumerable registers PagePermissionPolicyConfigurator as a transient IConfigureOptions<AuthorizationOptions> (:111-112) and PagePermissionAuthorizationHandler as a transient IAuthorizationHandler (: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) for IStringLocalizer<T>, then DecorateWith<IStringLocalizerFactory, PseudoStringLocalizerFactory>() (:124), the framework's own decoration helper on ServiceCollectionDecoration, which throws when no IStringLocalizerFactory is 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 why TryAdd is authoritative regardless of host registration order, namely that AddMudServices registers no MudLocalizer of 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 calls AddMudServices in.
      • Interceptor. AddLocalizationInterceptor<InvariantMudLocalizationInterceptor>() (:144) follows: MudBlazor's own default interceptor reads its built-in English strings by assigning CultureInfo.CurrentUICulture (invariant, then the previous value back), which writes an AsyncLocal culture 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 whether AddMudServices ran 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, usesSameOriginProxy is computed from the raw configuration (:154-155): it is true only when Api:SameOriginApiEndpoint carries 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 in apiClient (:158) so a handler can be appended afterwards. Its factory resolves IOptions<ApiSettings> (:165) and sets client.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 .Value runs the ApiSettingsValidator registered above, so a missing [Required] endpoint already fails as an OptionsValidationException, and a second check would only give the same failure a different, less informative exception. client.Timeout is 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 one AddServiceDefaults() 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 and Accept: application/json added (: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 as Accept-Language (:146-147). When usesSameOriginProxy is 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, every Authorization header the outer handlers or a service's DefaultRequestHeaders attached, 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 TryAdd so several composing hosts cannot double-register: IAuthUIService to AuthUIService (:196); SignOutNavigator (:199, signing out and landing on a chosen page in one navigation without RedirectToLogin racing it, per :198); IEmailConfirmationUIService to EmailConfirmationUIService (:203, the /confirm-email page's client per ADR-116; a separate interface rather than new IAuthUIService members, so a consumer's own IAuthUIService implementation keeps compiling, per the comment at :201-202); ISignInLinkUIService (:207) and IPasskeyUIService (:212, ADR-139), both mapped onto the framework's AuthUIService so 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 through SignIn:OfferPasskeys or 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 behind TermsAcceptanceGate, 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 to AddUIShared, 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 with TryAdd before the call or with AddSingleton after (:251-256), and TryAddSingleton<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).
    • AddCommonUiFacades() (:289-295): three TryAddScoped calls, IToastService to MudToastService (:291), IAppDialogService to MudAppDialogService (:292) and IPendingToastService to PendingToastService (:293), the toast that survives a forceLoad navigation and is injected by the shared layout's PendingToastHost. 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 the ConfirmationDialog they open), the only framework type that names MudBlazor's ISnackbar is StaleToastSweeper, which injects it to remove toasts a navigation left behind, asking MudToastService which of them are pinned (:276-278); pages, other components and the Result helpers 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 by AddUIShared and 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): one TryAddScoped<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, after AddUIShared, 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 unlike AddUserAdministrationUI<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 the MachineClientAdmin page reads and writes the app's Admin/MachineClients endpoints through (:357-364).
    • AddSupportAccessLogUI() (:383-388), the ADR-137 opt-in: IViewAsGrantsUIService to ViewAsGrantsService (:385), the client the SupportAccessLog page reads the app's Admin/ViewAsGrants endpoint through (:372-382).
    • AddAuditHistoryUI() (:402-407), the ADR-075 opt-in: IAuditHistoryUIService to AuditHistoryService (:404), the HTTP client an AuditHistoryPanel's FetchPage delegate reads an AuditHistoryControllerBase endpoint 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.System unless one is registered (:423), and OfflineWriteQueueOptions with the optional callback applied (:425-429). The doc comment (:409-419) notes that Common's MainLayout already hosts the OfflineWriteNotifier that drains and reports the queue.
    • AddOfflineWriteHandler<THandler>() (:440-446), constrained to THandler : class, IOfflineWriteHandler (:441): one TryAddEnumerable of 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: guards sources (: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's FeatureFlagsControllerBase (for example Admin/Conference/FeatureFlags), so a multi-service host lists every service's flags in one table (:454-456).
    • AddUIModule<TModule>() (:490-500), constrained to TModule : class, IUIModule (:491): an assembly scan through the framework's internal AddAssignableTypes helper (ServiceCollectionDecoration) over typeof(TModule).Assembly, registering every IEntityService<TEntityDTO, TIdentifierType> implementation scoped under each of its implemented interfaces (ScanRegistration.ImplementedInterfaces) (:493-497), then AddSingleton<IUIModule, TModule>() (:499). The doc comment (:472-485) records the deliberate boundary: this is the two-step prologue every module's Add{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 same IUIModule registration is what PagePermissionPolicyConfigurator enumerates to find guarded pages.
  • Why it's built this way: TryAdd throughout is both a safety property (several composing hosts calling AddUIShared cannot 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/set endpoint that a MAUI hybrid head does not have, so hybrids override it after AddUIShared (: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 when Api:SameOriginApiEndpoint is 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 is TryAdded 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.Client and MAUI MMCA.ADC.UI, plus the three Store equivalents), each followed by the per-module Add{Module}UI() calls, which are usually one-liners over AddUIModule<TModule>(), for example MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs:24 and MMCA.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, after AddUIShared (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 AddUIModule call sites and the bUnit caller were re-read in this pass. The extension block registers no form-factor service, and no IFormFactor or WasmFormFactor type exists under MMCA.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 at BreakpointConstants.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 returns breakpoint is Breakpoint.Xs or Breakpoint.Sm. That pattern is the whole rule: Md and 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 sets IsMobile from it at line 414 and, on a desktop-to-mobile transition, resets MobileCurrentPage to 1 and re-requests the mobile data (DataGridListPageBase.cs:454-458). That single assignment is what swaps a desktop MudDataGrid for 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, CancellationToken and ObjectDisposedException (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. Reading CancellationTokenSource.Token after Dispose() throws ObjectDisposedException, 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. A null source, or one whose IsCancellationRequested is already true, returns new CancellationToken(canceled: true) (:28-31). Otherwise it returns source.Token (:35) inside a try; an ObjectDisposedException (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 _cts field and writes _cts.LifetimeToken() where it used to write _cts.Token. null is 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 the ResultUiExtensions examples show _cts.LifetimeToken() as the call-site shape (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ResultUiExtensions.cs:48, :63). The convention is enforced by ArchitectureRules.ComponentsReadTheirTokenThroughLifetimeToken (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Ui/ArchitectureRules.LifetimeTokens.cs:28), which fails the build on a direct _cts.Token read, wrapped for subclassing by LifetimeTokenConventionTestsBase (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.JSInterop for JSDisconnectedException and JSException (JsInteropFailure.cs:1); InvalidOperationException and OperationCanceledException (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-written catch list 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), returning true for 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 the TaskCanceledException an interop call throws when it exceeds the host's JS interop timeout or its token is cancelled.

    Anything else (a FormatException, a NullReferenceException) returns false, 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 try and writes catch (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. Folding OperationCanceledException in means a caller that must let its own cancellation propagate has to say so: the doc comment (:24-25) prescribes adding !cancellationToken.IsCancellationRequested to the filter, and BrowserPasskeyCapability does exactly that (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Capabilities/Auth/BrowserPasskeyCapability.cs:113). It is internal, not on the public API surface; the sibling packages reach it through InternalsVisibleTo entries for MMCA.Common.UI.Tests, MMCA.Common.UI.Maui and MMCA.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 reports false instead 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 by JsInteropFailureTests (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 unrelated FormatException is not (:24-26), and two facts pin that ThemeInterop.TryAsync reports false on an interop timeout and true on 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.CancellationTokenSource and ObjectDisposedException.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; LatestLoadGuard is 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 current CancellationTokenSource?, the int _generation, and a _disposed flag.
    • Begin() (:50-59) is the entry point. It throws if the guard is disposed (:52), cancels and disposes the previous load through the private CancelAndDisposeCurrent() (: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 later Begin() 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 _disposed early 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): a private readonly LatestLoadGuard _load = new(); field, var (token, generation) = _load.Begin(); at the top of OnParametersSetAsync, an if (!_load.IsCurrent(generation)) { return; } immediately after the await, and public 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 DetailPageBase exposes one as protected 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. RoleAdminEdit holds its own _load and runs the Begin() / 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 and SessionCreate also 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 covering Begin cancelling the prior token, generation advance, IsCurrent after supersession, and behavior after disposal) [Rubric §28, Front-End Testing]; DetailPageBaseTests covers 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 DetailPageBase inheritance or by hand, as RoleAdminEdit does.

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 Group string: 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 same Group key, 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 the Key resolved against the first item's TitleResource (NavGroup.cs:14-17, ADR-027).
  • Walkthrough: a positional record on one line (NavGroup.cs:23) with four parameters, three optional.
    • string Key: the NavItem.Group value the description applies to.
    • string? Icon = null: null keeps 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.OnInitializedAsync collects every module's NavGroups with TryAdd, which is the first-registered-wins rule (MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor.cs:77-81), and the private Arrange groups a section by key in first-appearance order, applies the description's Icon ?? Icons.Material.Filled.Folder, Expanded ?? false and Order ?? 0 to each NavUnit, then stable-sorts the units by Order (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's ConferenceUIModule is 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 by NavMenuOrderingTests (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.

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 is RequiredRole / RequiredClaim on 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.cs relies on when it partitions the flattened item list into three sections with i.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 Section parameter of NavItem (NavItem.cs:16, defaulting to General), and the three-way partition at NavMenu.razor.cs:128-130. NotificationUIModule shows both non-default values in one file: its inbox item is Section: NavSection.User (MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationUIModule.cs:19) and its push-management item is Section: 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 *RoutePaths class RoutePaths itself points to.
  • Walkthrough: three public static readonly string members.
    • 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 in RoutePaths, static readonly is enough because the strings feed navigation calls and nav entries, not attribute arguments, so the pages' @page directives 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), and NotificationBell.razor.cs:316 (NavigateToInbox). NotificationUIModule builds its two NavItem entries from NotificationInbox and Notifications (MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationUIModule.cs:19-20). In ADC, AppActionRouteMap maps the notifications app action to NotificationRoutePaths.NotificationInbox (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/Services/AppActionRouteMap.cs:60), and AppActionRouteMapTests asserts 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 in PublicAPI.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 PersistentComponentState and the UTF-8 JSON bytes they add up to.
  • Depends on: HashSet<string> and StringComparer.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 ordinal HashSet<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 PersistAsJson has accepted it (PrerenderStateBudget.cs:95-99). A key PersistAsJson rejects (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 through PrerenderStateBudgetTests (see PrerenderStateBudget), including ARejectedRepeatKey_InOnePass_KeepsTheRunningTotal (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Common/PrerenderStateBudgetTests.cs:51), which persists a 10 KB key, catches the ArgumentException from 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 in PrerenderStateBudgetTests.cs (:64) is rejected by PersistAsJson before Add runs.

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 *RoutePaths classes.
  • 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 by ConferenceRoutePaths, EngagementRoutePaths and IdentityRoutePaths in the consumer modules.
  • Walkthrough: two public static readonly string members.
    • 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 readonly rather than const is sufficient because these strings are consumed in navigation and Href expressions, not in attribute arguments. That has one consequence worth knowing: a @page directive still needs its own literal, so Home.razor:1 writes @page "/" directly and this constant covers only the linking and navigating side. Sessions shows the cost of the convention: the route literal appears in the page's own @page directive and again here, and only the tests hold the two together.
  • Where it's used: RoutePaths.Home backs 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.Sessions backs 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:76 pins that the link renders inside .nav-auth-section, :75 pins its position, :88 pins that it is absent for an anonymous user, and MMCA.Store/Tests/Modules/Identity/MMCA.Store.Identity.UI.Tests/Pages/Users/Profile/ProfileTests.cs:67 pins that the profile page links to it.
  • Caveats / not-in-source: Sessions is still listed in PublicAPI.Unshipped.txt (MMCA.Common/Source/Presentation/MMCA.Common.UI/PublicAPI.Unshipped.txt:339) while Home is baselined in PublicAPI.Shipped.txt:916, so the two members sit at different points in the public-API baseline cycle.

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's NavItems, 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 through TitleResource (ADR-027). [Rubric §11, Security] and ADR-020 apply through RequiredPermission.
  • Walkthrough: a positional record (NavItem.cs:20) with nine parameters, five of them optional, plus one init property 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): Title and Group are resource keys, resolved against TitleResource at 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. NavMenu implements exactly that, calling LocalizerFactory.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 = null and string? RequiredClaim = null: render gates. The menu applies them as item.RequiredRole is null || _user?.IsInRole(item.RequiredRole) == true and 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 as item.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 collapsible MudNavGroup; the menu's private Arrange groups each section by it with GroupBy(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. Arrange sorts each unit's items with a stable OrderBy(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 NavItems read as a small declarative list. Making TitleResource a 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). RequiredPermission is a third, independent gate rather than folded into RequiredClaim, so a caller can express "hide by permission" without hand-building the permission claim type/value pair itself. Order sits 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 NavItems property 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) and new("Nav.PushNotifications", NotificationRoutePaths.Notifications, Icons.Material.Filled.NotificationsActive, typeof(SharedResource), RequiredPermission: NotificationPermissions.Manage, Section: NavSection.Admin, Group: "Nav.Group.Notifications") (:20). ADC's ConferenceUIModule shows Order in 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 a StubUiModule(IReadOnlyList<NavItem> navItems) (:308), and by NavMenuOrderingTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Layout/NavMenuOrderingTests.cs:138) for item ordering with ties.
  • Caveats / not-in-source: RequiredRole and RequiredClaim control 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) and ConditionalWeakTable (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's MaximumReceiveMessageSize (32 KB by default) closes the connection, so the page reconnects, sends the same state again and never becomes interactive, with only a Debug-level InvalidDataException as 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 options PersistAsJson and TryTakeFromJson use, 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): a ConditionalWeakTable<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-guards state (:77), serializes once to UTF-8 (:79) and returns false over the per-key cap (:80-83). It then fetches or creates the state's tally (:85), locks it (:86) and returns false if the bytes do not fit what is left of MaxTotalJsonBytes (:88-91). Otherwise it parses the measured bytes into a JsonDocument and persists its RootElement (:97-98), because PersistentComponentState takes no raw bytes publicly and a JsonElement is written token for token without serializing TValue again (:93-94). Only then does it add the key to the tally (:99) and return true (:100); the comment at :95-96 records why: a throw leaves the tally untouched, since Fits only reads and the repeat-key restart happens in Add (see PersistedTally).
  • Why it's built this way: an extension method, so a page calls it where it would have called PersistAsJson and no service is injected. The remarks (:58-64) state the boundaries honestly: a larger maxJsonBytes does not raise the page-wide budget, and a small fixed-size value persisted with PersistAsJson directly 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 by PrerenderStateBudgetTests (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 from MMCA.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.NotNullWhenAttribute and SuppressMessageAttribute (: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 whose Message is 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 generic Http.Status format, Http.TransportFailure, Http.Timeout, Http.MalformedResponse. A code the supplied localizer does not hold resolves from the framework's own SharedResource pair for the current UI culture, so a consumer page passing its own IStringLocalizer<PageType> (which holds no Http.* keys) still shows the translated sentence; the English message is the last resort. The class holds a private ResourceManager SharedResources = new(typeof(SharedResource)) (:85) and the format key HttpStatusFallbackKey = "Http.Status" (:79) for this.
    • Severity-ordered deduplication (:37-40): messages are made distinct with StringComparer.Ordinal and 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 once Result.Combine aggregates 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 into Shared (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 old try / catch (Exception ex) shape with if (result.TryGetValue(out var dto)) { ... } else { result.NotifyOnFailure(Toast, L); }, both reading the token as _cts.LifetimeToken() (ComponentLifetimeExtensions). The TryGetValue in 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).

  • 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 by IsFailure alone and returns true for any success, so when T is itself nullable the value stays nullable on the success branch (Result.cs:202). This class adds only the three-argument overload TryGetValue<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, so errors comes back empty. The framework's own services never produce that shape (a 2xx with no value fails with Http.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 by ErrorTypeSeverity.Rank descending, localizes each error through the private LocalizeError (: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 returns null for a success. LocalizeDistinct(IEnumerable<string>?, IStringLocalizer?) (:173-185) gives the same treatment to a plain message list, specifically the MudForm.Errors shape whose entries are resource keys produced by the model's DataAnnotations; it preserves original order rather than re-ranking, since those entries carry no ErrorType.
    • Rendering. OnFailureSetError(this Result, Action<string?> setError, IStringLocalizer?) (:215-222) hands the composed message to the page's own error field, the one an inline MudAlert or the PageErrorState component renders (its doc comment names it by its current home, MMCA.Common.UI.Components.PageState.PageErrorState, at :188-189, matching the file at MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/PageState/PageErrorState.razor:1), and clears it on success by passing the composed message, which is null for 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, calling toast.Show(message, severity) only when the chosen message is non-null (:280-283). With no fallback the message is the composed one; with a fallback it is ActionErrorMessage(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 blank fallback (:320), returns null for a success, returns fallback when any error is ErrorType.Unexpected (a 500, a transport failure, a timeout, whose own text is diagnostic), and otherwise the composed message, falling back to fallback again when that composes to nothing (:327-329). Both rendering methods return the same result instance so the call can sit inline, and both have a Result<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) and IsUnauthorized() (: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 own Http.{status} code, then the Http.Status format 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), while ProblemDetailsResultReader.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 to Localize. LookUpByCode (:389) asks the caller's localizer first and then the framework's SharedResources, and FormatByCode (: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 returns localized.ResourceNotFound ? message : localized.Value (:430).
  • Why it's built this way: extension methods on Result rather 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 nullable IStringLocalizer? 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 names ResultUiExtensions; the client data-access half is ADR-094. Whether that ADR revision's member list already includes ActionErrorMessage and the fallback parameter 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 ConfirmAsync method in three overloads (plain, with a destructive flag, and with a destructive flag 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 using directives at all). Implemented by MudAppDialogService over MudBlazor's IDialogService.
  • 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's IDialogService / ISnackbar (MudAppDialogService at MMCA.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 prompt DeleteConfirmation is built on top of it rather than growing this contract (it injects the service at MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/DeleteConfirmation.razor:2 and calls ConfirmAsync at :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: true when 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-chosen data-testid on the confirming button so an end-to-end test can target that specific prompt (:47-51); DeleteConfirmation passes confirm-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 touches IStringLocalizer, 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 on true.
    • 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 own ConfirmationDialog through its internal ShowAsync (MudAppDialogService.cs:20-25; MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/ConfirmationDialog.razor:65), whose confirmTestId parameter defaults to confirm-action when the caller names none (ConfirmationDialog.razor:21, :72). That helper collapses every non-answer to false with return result is { Canceled: false, Data: true }; (ConfirmationDialog.razor:92). The dialog is deliberately not MudMessageBox, 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 button Color.Error when Destructive is set, Color.Primary otherwise, stamping its data-testid from ConfirmTestId on the same line (:15).
  • Why it's built this way: a four-string method with a bool answer 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 by AddCommonUiFacades() 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), the DeleteConfirmation component (DeleteConfirmation.razor:2), and the UnsavedChangesGuard component. 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's Services.AddCommonUiFacades() call (MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Infrastructure/BunitComponentTestBase.cs:54), which uses TryAdd semantics 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.razor declares @page "/" once (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Home.razor:1), injects IEnumerable<IHomePageContent> (Home.razor:3), and renders <DynamicComponent Type="_contentType" /> when a provider resolved (Home.razor:8-11). Because the component arrives as a runtime Type rather 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 the System.Type of the Razor component to render as the home-page body. PageTitle (IHomePageContent.cs:14) is the browser-tab title, bound by Home.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 Type or an Assembly and 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 ADCHomePageContent as 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 with StoreHomePageContent (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 by Home.razor's selection code (Home.razor:23 onward), 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.Severity as 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 to MudBlazor.Severity lives in one private method inside MudToastService, so swapping renderers is a change to one switch.
  • 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 from Info, and not more, because there is no shape beyond these that the framework raises. Info is the default parameter value on both ShowPersistent and ShowAction (:72, :100), which is the neutral choice for an unprompted message.
  • Where it's used: the severity parameter of IToastService.Show, ShowPersistent and ShowAction; the severity parameter of ResultUiExtensions.NotifyOnFailure, where it defaults to ToastSeverity.Error (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ResultUiExtensions.cs:271); and MudToastService, the one type that maps it to MudBlazor.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 the Microsoft.Extensions.Options binder 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: a public static readonly string SectionName naming the configuration section (line 12), init-only properties with compiled-in defaults, and one services.AddOptions<T>().Bind(configuration.GetSection(T.SectionName)) call in AddUIShared (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 take IOptions<LayoutSettings> and read .Value, so nothing in the shell parses configuration itself.
  • Walkthrough:
    • SectionName = "Layout" (line 12).
    • BrandName (line 15) defaults to "MMCA". NavMenu renders 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 to string.Empty. MainLayout renders the footer block when the text is non-blank, when LegalSettings has footer links, or when a module contributes FooterComponentTypes (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, NavMenu emits an img beside the brand text with alt="" and aria-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 a string and not a Uri: the value is usually a host-relative path such as /img/logo.svg, which System.Uri cannot represent without RelativeOrAbsolute round-tripping.
    • SessionsNavRequiredRole (line 39) is nullable and unset by default, which shows the "signed-in devices" nav entry to every signed-in user. NavMenu computes _showSessionsLink as 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/sessions itself stays available to any signed-in account whether or not the link is shown (lines 32-38).
    • StampColorModeOnDocument (line 51) defaults to false, which sets nothing. When true, ColorModeStamp writes data-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 loads theme-prepaint.js with data-stamp-color-mode on its script tag gets the value before the first paint instead. The attribute is distinct from the MAUI head's pre-paint data-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 decision NotificationPageGate takes from the registered UI modules alone (MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/NotificationPageGate.cs:20-21, :26). And MainLayout renders StaleToastSweeper unconditionally 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.json also means a deployment can rebrand without a rebuild.
  • Where it's used: injected as IOptions<LayoutSettings> by Layout/NavMenu.razor:13 and Layout/MainLayout.razor:13, read in Layout/NavMenu.razor.cs:120, and resolved by ColorModeStamp (Theme/ColorModeStamp.cs:24). Forwarded to the WebAssembly client through /client-config as one of the shared UI sections (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigUiSections.cs:39). Configured by the UI hosts, for example MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/appsettings.json:33 and MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/appsettings.json:14. Covered by NavMenuTests, MainLayoutFooterTests, PublicAppBarComponentTests and MmcaThemeProvidersColorModeTests.

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 the Microsoft.Extensions.Options binder 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 as LayoutSettings: a public static readonly string SectionName = "Legal" (line 22) and init-only properties with compiled-in defaults. Here the default doubles as the feature toggle: an unset URL is string.Empty, and each consumer tests string.IsNullOrWhiteSpace before 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) and CodeOfConductUrl (line 34) are string properties defaulting to string.Empty. The doc comment on TermsUrl states 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 one UrlJustification constant (lines 18-19): the value is bound from configuration and emitted straight into an href, and the empty default is not a valid System.Uri, the same precedent as LayoutSettings.BrandLogoUrl.
    • HasFooterLinks (lines 44-47) is true when any of the three footer documents (Terms, Privacy, Code of Conduct) is non-blank. DeleteAccountUrl is 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 HasFooterLinks once 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(...) in MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:60-61. Layout/MainLayout.razor injects it (line 13), renders the footer when footer text or HasFooterLinks is present (line 87), and emits one ExternalLink per configured document (lines 104-114). Components/Legal/TermsAcceptanceGate.razor.cs reads it through IOptions<LegalSettings> (lines 70, 78) and the gate markup checks Legal.HasFooterLinks (TermsAcceptanceGate.razor:17). Pages/Auth/Register.razor injects it (line 17) and shows the Terms checkbox only when a Terms URL is configured (line 143; Pages/Auth/RegisterModel.cs:46). ADC's LegalAndDataCard.razor.cs on the profile page reads it too. Covered by MainLayoutFooterTests and RegisterTermsTests in MMCA.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 shape LayoutSettings introduces.
  • 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, so PollInterval is 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. NotificationBell builds its PeriodicTimer from 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 when PollInterval <= TimeSpan.Zero (NotificationBell.razor.cs:96-99), because PeriodicTimer rejects 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, via State.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 as IOptions<NotificationBellOptions> by NotificationBell (Components/Notifications/NotificationBell.razor.cs:36). Covered indirectly by NotificationBellTests.

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.Options binder 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). CollectAddress defaults to true (line 18), so a host that never configures the Registration section (SectionName, line 11) keeps the address block it always had; only a host that sets false changes 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. true shows the optional address block; false hides 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.razor injects IOptions<RegistrationSettings> (line 18) and wraps the address block in @if (CollectAddress) (line 107); Pages/Auth/Register.razor.cs exposes CollectAddress from the options (line 13) and branches on it at line 24. Covered by RegisterAddressOptionTests in MMCA.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.Options binder at registration time.
  • Concept introduced: none new. It follows the bound-options shape LayoutSettings introduces (SectionName = "SignIn", line 16) and the "default to the existing behavior" switch of RegistrationSettings: both offers default to false, 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), default false. The doc comment (lines 18-22) ties it to the server's Authentication:SignInLinks:Enabled: turned on alone, the button sends requests the API ignores. Pages/Auth/Login.razor:154 shows the button only when it is on and the page is not waiting on a second factor.
    • OfferPasskeys (line 31), default false, paired with the server's Passkeys: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:201 reads it.
    • SignInLinkLandingPath (line 37), default "/". Pages/Auth/SignInLinks/SignInLink.razor.cs:189 passes it through ReturnUrlProtector.Sanitize(..., "/") before the full-page navigation, which is what enforces the "local path only" rule.
    • Unlike LayoutSettings, the properties are get; set; rather than init.
  • 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-config forwards the server head's SignIn section, 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 by MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigUiSections.cs:41, injected by Pages/Auth/Login.razor:23 and Pages/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 in MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/appsettings.json:51 and MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/appsettings.json:25. Covered by LoginSignInLinkTests, LoginPasskeyTests and LoginSecondFactorTests in MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests, and by the shipped SignInLinkPageTestsBase (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 its Enabled is not false.
  • 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 registers IModule implementations in topological order; the UI side has its own analogue, IUIModule, registered by each module's AddXUI() extension (ADR-067). This helper is the gate in front of those calls: a head that switches a module off never calls AddXUI(), so no IUIModule descriptor 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) and IsModuleEnabled(IConfiguration configuration, string moduleName) (lines 28-35). It guards both arguments (ThrowIfNull and ThrowIfNullOrWhiteSpace, lines 30-31), walks two section levels, Modules then the module name (line 33), and returns section.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 missing Enabled key 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 the modules section 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, inside Program.cs/MauiProgram.cs before the service provider exists. Keeping the check in the framework rather than hand-rolling builder.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-config endpoint applies it when it serves the modules section (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs). The corresponding configuration blocks start at MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/appsettings.json:9 and MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/appsettings.json:8. Covered by UIModuleConfigurationTests (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 Modules section 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 take IOptions<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-generated ApiSettingsValidator (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, and ValidateOnStart runs that validator during host startup rather than lazily on first resolution, so a missing Api:ApiEndpoint surfaces as an OptionsValidationException naming the key before the host accepts traffic (ADR-070). That is what licenses the null-forgiving apiSettings.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 internal ApiEndpoint (faster, no public DNS) while the browser uses the external URL, and it falls back to ApiEndpoint when null (lines 19-24). The fallback is applied by each reader, for example api.WasmApiEndpoint ?? api.ApiEndpoint in the CSP builder (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Security/BlazorCspPolicyProvider.cs:51), while /client-config refuses to serve without it (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:87-91).
    • SameOriginApiEndpoint { get; init; } (line 39) is null everywhere except on a WebAssembly client whose Server host opted in with AddCommonSameOriginApiProxy (lines 27-38). The host serves it as an origin-relative path in /client-config and MmcaClientConfigBootstrap.LoadAsync resolves it to an absolute address. When it is set, the "APIClient" and the notification hub target it instead of ApiEndpoint, send no Authorization header (the proxy attaches the bearer from the HttpOnly session cookie server-side) and add the proxy's CSRF header; ApiEndpoint keeps 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 is client.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: sealed plus init gives 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 the HttpClient factory keeps one failure mode with one message: the comment at MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:160-164 records 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" HttpClient factory to set BaseAddress (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:158-170, alongside the 90-second total-request timeout at :172-176); read by ApiFileDownloadButton for its browser download URL, SameOriginApiEndpoint ?? WasmApiEndpoint ?? ApiEndpoint (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/ApiFileDownloadButton.razor.cs:132-142); read by NotificationHubService and BlazorCspPolicyProvider; and served to the WebAssembly client by each Server head's /client-config endpoint, both routed through the shared MapClientConfigEndpoint (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:84-95; mapped by UseMmcaBlazorWebPipeline at MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:211, which the hosts call at MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:120-126 and MMCA.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*\$?", at MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Ui/ArchitectureRules.LocalizedText.cs:14, with the comment at :12-13 recording that it is the same guard that previously watched direct ISnackbar use at :9).
  • Walkthrough: seven members, in three tiers.
    • The four named severities, Success (IToastService.cs:41), Info (:45), Warning (:49) and Error (:53), each taking one already-localized message. MudToastService implements each as a one-line snackbar.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: true pins the toast open until the user dismisses it or takes the action, and the MudBlazor implementation additionally renders it filled, following the same emphasis convention ShowPersistent uses, "because a toast that waits for the user has to look like it is waiting" (:90-95).
  • 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 by AddCommonUiFacades() (DependencyInjection, MMCA.Common.UI/DependencyInjection.cs:291) to match the lifetime of the MudBlazor ISnackbar it 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 the UnsavedChangesGuard, SharePageButton, ApiFileDownloadButton and NotificationListener components. 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-51 records that without it a consumer's component test fails to resolve IToastService and 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: the message is 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 with forceLoad: 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 pass CancellationToken.None (or nothing) there.
    • TakeAsync(CancellationToken ct = default) (:48) reads and removes the parked toast, returning a (ToastSeverity Severity, string Message)? that is null when nothing is waiting or storage is unavailable (:47). It is called by PendingToastHost; 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 ValueTask keep the contract free of any storage type, so the sessionStorage choice 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 in TakeAsync at :62-65). It is registered scoped with TryAddScoped<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.cs covers 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), with ProfileDeleteAccountTests and the AccountDeletionTests E2E 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 annotations ValidateDataAnnotations would, without reflection, so it also runs on a trimmed WebAssembly client that carries no Microsoft.Extensions.Options.DataAnnotations (ApiSettingsValidator.cs:5-9).
  • Depends on: ApiSettings (the type it validates) and IValidateOptions<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 the Validate method from the annotations on ApiSettings. [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 AddUIShared right after the options binding, AddOptions<ApiSettings>().Bind(...).ValidateOnStart() (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:49-51), with services.TryAddEnumerable(ServiceDescriptor.Singleton<IValidateOptions<ApiSettings>, ApiSettingsValidator>()) (line 52). TryAddEnumerable keeps a repeated AddUIShared call from registering the validator twice; ValidateOnStart is 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 internal generated 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 of ApiEndpoint relies on it (comment, DependencyInjection.cs:161).
  • Where it's used: only in AddUIShared (DependencyInjection.cs:52), and named in the ApiSettings doc comment (Common/Settings/ApiSettings.cs:8). Covered by ApiClientRegistrationTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/ApiClientRegistrationTests.cs).
  • Caveats / not-in-source: the generated Validate body 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-config document (served by ClientConfigEndpointExtensions.MapClientConfigEndpoint) into a stream AddJsonStream can 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 its SectionName and the SameOriginApiEndpoint property name when rewriting the document; otherwise System.Net.Http.HttpClient, System.Text.Json.Nodes and System.Text.Encoding (BCL). Nothing it touches needs a service provider, which is deliberate, since it runs before builder.Services exists.
  • 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, in Program.cs, fetching the very document that will configure the rest of the client. A Polly-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 own HttpClient and its own Timeout.
  • Walkthrough:
    • ClientConfigPath = "client-config" (line 31), the relative path both overloads fetch, matching the endpoint's own route.
    • DefaultTimeout (line 34, 15 seconds) and DefaultRetryDelay (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-lived HttpClient scoped to baseAddress with DefaultTimeout, 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 on HttpRequestException or a caller-uncancelled timeout (IsTimeout, lines 83, 142-143) wait retryDelay then fetch once more (lines 85-86) with no further retry. IsTimeout (lines 142-143) is the detail that makes the retry precise: HttpClient reports its own per-request timeout as TaskCanceledException, 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 ResolveSameOriginApiEndpoint against the client's BaseAddress and is wrapped in a non-writable MemoryStream (line 89), the shape AddJsonStream expects.
    • ResolveSameOriginApiEndpoint(byte[], Uri?) (lines 98-128, internal) exists because a host running the same-origin API proxy serves Api:SameOriginApiEndpoint as 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 (a JsonException is left for configuration binding to report, lines 110-114), an Api object holding a non-blank string SameOriginApiEndpoint that is not already an http(s) URL (lines 116-124). Only then does it replace the value with new Uri(baseAddress, path).AbsoluteUri and re-serialize (lines 126-127). Parsing is case-insensitive on property names (line 108).
    • IsHttpAbsolute(string) (lines 136-138, internal) accepts only an absolute http or https URI. A bare absolute-Uri.TryCreate check is not enough: on Unix-like runtimes, browser WebAssembly included, "/api/" parses as the absolute file:///api/, so the relative path would be left unresolved and every client call would go to file:///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 of ApiSettings on the client sees an absolute address (ADR-131).
  • Where it's used: MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web.Client/Program.cs calls LoadAsync to populate the WASM client's configuration before any service is registered. The endpoint it fetches from is ClientConfigEndpointExtensions (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs). Covered by MmcaClientConfigBootstrapTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Common/Settings/MmcaClientConfigBootstrapTests.cs) and SameOriginProxyClientTests (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 own App / 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 is IEnumerable<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 by MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor.cs:122 with .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 with TryAdd, so the first registered description of a key wins, the same rule as NotFoundContentType (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 as AdditionalAssemblies="UIModules.Select(m => m.Assembly)" (MMCA.Common/Source/Presentation/MMCA.Common.UI/Routes.razor:13), which is what makes a module's @page routes 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 an AuthorizeView (MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/MainLayout.razor:51-58, gathered at :192; the mobile quick-actions row does the same at MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor:50-56, gathered at NavMenu.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 at NavMenu.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). MainLayout gathers them at MainLayout.razor:195 and renders them in the block documented at :88-93.
    • IReadOnlyList<Type> FooterComponentTypes => [] (:61): components rendered inside the layout's one contentinfo footer, after the configured footer text and legal links (MainLayout.razor:144-149, gathered at :196). Any contribution renders the footer even with no LayoutSettings.FooterText and 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, FirstOrDefault over 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 Assembly rather 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's ConferenceUIModule (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-only DeviceUIModule (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/DeviceUIModule.cs:19), plus Store's CatalogUIModule (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) and MauiUIModule (MMCA.Store/Source/Hosts/UI/MMCA.Store.UI/MauiUIModule.cs:14). The optional members earn their keep in practice: ADC's ConferenceUIModule describes 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); NotificationUIModule contributes NotificationBell to the signed-in app bar and NotificationListener to the layout (NotificationUIModule.cs:23-25); Store's SalesUIModule contributes CartButton to the public app bar, CartDrawer to the layout and OrphanOrderRecovery to the content header (SalesUIModule.cs:33-40); Store's CatalogUIModule contributes StoreSearchBox to the public app bar, StoreFooterLinks to the footer and StoreNotFound as the not-found content (CatalogUIModule.cs:31-37); ADC's EngagementUIModule contributes LiveEventListener (EngagementUIModule.cs:45), ADC's IdentityUIModule contributes TermsAcceptanceGate (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/IdentityUIModule.cs:49), and ADC's DeviceUIModule contributes five native-integration layout components at once (DeepLinkListener, BiometricGate, PushRegistrationListener, NativeThemeSync, AppActionTitleRefresher; DeviceUIModule.cs:33). Registration goes through AddUIModule<TModule>() (see DependencyInjection), which each module's own one-line Add{Module}UI() delegates to, for example MMCA.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 the TEntityDTO constraint (:21) and BaseLookup<TIdentifierType> as a return type (:41), both from MMCA.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 original ErrorType intact". 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.UI may reference MMCA.Common.Shared only, which is why both constraints come from Shared and never from Application or Domain [Rubric §3, Clean Architecture].
  • Walkthrough: two generic constraints (:21-22) bind TEntityDTO to IBaseDTO<TIdentifierType> and require TIdentifierType : notnull. Then seven members, every one ending in a defaulted CancellationToken:
    • GetAllAsync(bool includeFKs, bool includeChildren, CancellationToken) (:25-28) returns Result<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) returns Result<(IReadOnlyList<TEntityDTO> Items, int TotalItems)>. The TotalItems half 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 lightweight Id + Name BaseLookup<TIdentifierType> items for dropdowns and autocompletes, so a picker never pulls whole entities.
    • GetByIdAsync(TIdentifierType id, bool includeChildren, CancellationToken) (:50-53) returns Result<TEntityDTO>, and the doc comment (:45-49) pins the contract that used to be ambiguous: a missing entity is an ErrorType.NotFound failure, never a success carrying null. That is what lets a detail page write if (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) and DeleteAsync(TIdentifierType id, CancellationToken) (:66-68) return the non-generic Result, 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 Result return is deliberate rather than convenient: mixing nullable returns for reads with bool for writes forces each call site to invent its own error story, whereas returning Result everywhere 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 over AuthenticatedServiceBase that takes only the endpoint, the IHttpClientFactory and the ITokenStorageService, 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 own AddAssignableTypes scan over the module's assembly, which picks up every class assignable to IEntityService<,> and registers it scoped as its implemented interfaces (DependencyInjection, MMCA.Common.UI/DependencyInjection.cs:493-497). The (Items, TotalItems) shape of GetPagedAsync is 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 own ECCLevel keeps 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-line switch in Components/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) and High = 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: QrCodeImage takes it as a parameter defaulting to Medium (Components/QrCodeImage.razor:36) and maps it to QRCodeGenerator.ECCLevel before encoding (:77-82); QrCodeButton defaults to Quartile (Components/QrCodeButton.razor:65). ADC passes Medium explicitly 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 by QrCodeImageTests.

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 double value on a 0-5 scale, rendering full, half, or empty stars per position.
  • Depends on: MudBlazor's Size enum and Icons.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 same Value always paints the same five icons regardless of interaction history. The single required AriaLabel parameter 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 of Value.
    • Value (line 127) is a double on the 0-MaxValue scale. The doc comment (lines 121-125) states the intended caller pattern explicitly: a caller holding a decimal average casts it to double, 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 to Size.Small.
    • FillFor(int star) (lines 145-153) is the per-position logic: a star index at or below Value is FullStar; otherwise it is HalfStar when Value is within half a star of that position (Value >= star - 0.5), else EmptyStar. IconFor(string fill) (lines 138-143) maps those three string constants to the three MudBlazor icon glyphs through a switch, 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 of Value with 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 rendering Product.RatingSummary on 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, NotFound or Failed. It is the state a DetailPageBase page exposes and the DetailLoadStateContent component 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: DetailPageBase starts in Loading (Pages/Common/DetailPageBase.cs:52), BeginLoad resets to Loading while superseding the load in flight through LatestLoadGuard (:59-64), and CompleteLoad sets Loaded on success and result.IsNotFound() ? NotFound : Failed otherwise, 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: DetailLoadStateContent takes it as its State parameter and renders PageLoadingState, PageErrorState or the Retry alert per member, falling through to ChildContent for Loaded (Components/PageState/DetailLoadStateContent.razor:10-34). ADC detail pages built on DetailPageBase branch on LoadState != DetailLoadState.Loaded (for example MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Events/EventDetail.razor:19, Pages/Speakers/SpeakerDetail.razor:20, Pages/Sponsors/SponsorDetail.razor:18); SpeakerDashboard keeps its own _loadState field of this type and applies the same IsNotFound() split by hand (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Speakers/SpeakerDashboard.razor.cs:51, :139). Covered by DetailPageBaseTests and DetailLoadStateContentTests.

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 tells ListPageShell<TItem> whether the page owning its ServerData callback has learned its viewport and chosen grid or card list. The shell reads it only when the page does not pass ListPageShell.IsLayoutKnown itself (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 own LoadServerData method as ServerData, so the delegate's Target is 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 it internal keeps 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 as bool IListLayoutSource.IsLayoutKnown => IsLayoutKnown; (:90) over its own protected IsLayoutKnown (:87), which the first viewport notification sets to true (:451-452).
  • Why it's built this way: an explicit implementation over a protected property 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 by ListPageShell's LayoutKnown (Components/Lists/ListPageShell.razor.cs:167). Exercised through ListPageShellLayoutGateTests (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 MudBlazor MudRating wrapped in a role="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 (its MaxValue constant is the default scale, line 31), MudBlazor's MudRating, MudText, Size and Typo (NuGet), and EventCallback<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: MudRating renders 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 the radiogroup role with aria-labelledby pointing at the caption (RatingInput.razor:8-9) and sets aria-describedby to 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), alongside data-testid="rating-input" (RatingInput.razor:12).
  • Walkthrough:
    • Ids: _labelId and _errorId (lines 14-15) are per-instance rating-label-{guid} and rating-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) and ValueChanged (lines 27-28) for two-way binding, MaxValue (lines 31-32, defaults to RatingStars.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 to Size.Large as a comfortable touch target), LabelTypo (lines 50-51, defaults to Typo.subtitle2) and Class (lines 54-55, extra classes on the group element).
    • HasError (line 57) is !string.IsNullOrEmpty(ErrorText); the markup renders the error as a caption with role="alert" only when it is true (RatingInput.razor:19-22).
    • OnSelectedValueChangedAsync(int value) (lines 59-63) stores the value locally and invokes ValueChanged, the handler the markup wires to MudRating.SelectedValueChanged (RatingInput.razor:13-17).
  • Why it's built this way: wrapping MudRating rather than forking it keeps MudBlazor's star rendering and keyboard handling, and adds only the missing ARIA structure. Making Label required means a rating can never ship without an accessible name, the same choice RatingStars makes with its required AriaLabel.
  • 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:69 and MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Pages/Feedback/EventFeedback.razor:58. Covered by MMCA.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.js for the two infinite-scroll components. It owns a per-instance observer id, a lazily imported JS module, the DotNetObjectReference back to its owner, and an IsObserving flag (lines 25-40). Its owner (a component exposing a [JSInvokable] callback) constructs it as new InfiniteScrollObserver<TOwner>(JS, this) and calls ObserveAsync, UnobserveAsync and DisposeAsync from its lifecycle.
  • Depends on: IJSRuntime, ElementReference, DotNetObjectReference<TOwner>, IAsyncDisposable, and the internal LazyJsModule import wrapper (line 35). Nothing else first-party; consumed by InfiniteScrollSentinel and MobileInfiniteScrollList<TItem> (the TOwner constraint is class, 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 serialize OnAfterRenderAsync, 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 the DotNetObjectReference once (line 66), calls observe with the reference, the element and the id (line 67), and sets IsObserving (line 68). JSDisconnectedException and JSException are 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), calls unobserve with the id (line 92), tolerates both exceptions, and clears IsObserving (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 the DotNetObjectReference in a finally (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) and MobileInfiniteScrollList.razor.cs; exercised through InfiniteScrollSentinelTests.

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 OnVisible when 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's MudProgressCircular in the markup; first-party, only InfiniteScrollObserver<TOwner>, which owns the shared JS module _content/MMCA.Common.UI/infinite-scroll.js (wwwroot/infinite-scroll.js). It is a sibling of MobileInfiniteScrollList<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 from DataGridListPageBase<TDto> cannot hook async disposal because its DisposeAsync is 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, and LoadingLabel (line 32), the localized accessible name for that row.
    • State (lines 34-41): the _sentinelRef element reference (line 34), the _observer field (line 35, an InfiniteScrollObserver<TOwner> that now owns the observer id, the imported JS module, the DotNetObjectReference and the observing flag), _wasLoading (line 40, the previous render's IsLoading), 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 with InvokeAsync before invoking OnVisible.
    • OnAfterRenderAsync (lines 52-63) attaches the observer on the first render, and re-attaches it on the render where a load has just finished: loadJustFinished is _wasLoading && !IsLoading && _observer?.IsObserving == true (line 54), _wasLoading is then updated (line 55), and either condition lazily creates the observer helper (line 59) and calls ObserveAsync(_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, the observe/unobserve calls and the swallowed JSDisconnectedException/JSException live in the shared helper, not here; see InfiniteScrollObserver<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 the DotNetObjectReference disposal happen in the helper.
    • The markup (Components/InfiniteScrollSentinel.razor:4-13) is a single div carrying the element reference, with the progress row rendered only while IsLoading. That row is role="status" aria-live="polite" aria-busy="true" (line 9), matching PageLoadingState's politeness so a screen reader hears that more items are loading without the announcement interrupting reading.
    • The JS side is deliberately tiny: observe disconnects any prior observer for the id, creates an IntersectionObserver with rootMargin: '200px' and invokes OnSentinelVisible on intersection (wwwroot/infinite-scroll.js:3-14); unobserve disconnects 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.
  • 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 OnVisible to 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, inside PublicSpeakerList). Covered by InfiniteScrollSentinelTests.

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: Result and its generic form (the fetch delegate's return type), SharedResource through IStringLocalizer<SharedResource>, ResultUiExtensions.LocalizedErrorMessage, the EmptyState component, the ClickableCard component each row's card is wrapped in, and, through InfiniteScrollObserver<TOwner>, the shared _content/MMCA.Common.UI/infinite-scroll.js module it shares with InfiniteScrollSentinel. 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 its CancellationToken entirely, 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 _generation counter (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 _currentPage only 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 raise OnCardClick.
  • Walkthrough:
    • Injected services (lines 22-23: IJSRuntime and the localizer, no toast service) and parameters (lines 25-62). CardTemplate is an [EditorRequired] RenderFragment<TItem> (line 27); CardActionsTemplate is the optional RenderFragment<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) returning Result<(IReadOnlyList<TItem> Items, int TotalItems)>, which is IEntityService<TEntityDTO, TIdentifierType>.GetPagedAsync minus the filter and sort arguments. PageSize defaults to 10 (line 49), EmptyIcon to SearchOff (line 55), MaxRenderedItems to 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 shared InfiniteScrollObserver<TOwner> that owns the module, the DotNetObjectReference and 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 an InvalidOperationException when FetchPageResult is 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 shared InfiniteScrollObserver<TOwner> (line 125) and calls ObserveAsync(_sentinelRef) (line 126); the helper tolerates JSDisconnectedException and JSException on both paths.
    • OnSentinelVisible() (lines 130-143), the [JSInvokable] entry point, returns a completed task when already loading, exhausted or disposed (lines 133-136), otherwise the InvokeAsync task 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 _isLoadingMore and 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 _isLoadingMore holds (comment, lines 158-159). It then snapshots the generation and publishes a fresh CancellationTokenSource (lines 165-169), computes targetPage (line 174), and awaits the delegate (line 178). After the await it checks disposal and generation (line 183), unwraps the Result with TryGetValue and routes a failure to SetLoadFailed (lines 188-194), and only then commits: advance the page (line 198), append the items through AppendNew and keep the count of new rows (line 200), record the total (line 201), set _hasMore from HasMoreAfter(appended) (line 202), which is where the DOM cap and the empty-append guard stop the loop, and call MarkReobserveAfterAppend(isInitial) (line 204). OperationCanceledException is swallowed as a normal supersession (lines 206-209); any other exception, caught under a scoped CA1031 suppression, raises the generic failure, again only for the current generation (lines 210-220). The finally (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-current CancellationTokenSource is 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.Contains while adding (line 251), so a row repeated inside the same page is caught too; records compare by value, the same equality @key uses. HasMoreAfter(int appended) (lines 262-263) is appended > 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; ResetAsync starts over (lines 256-261).
    • MarkReobserveAfterAppend(bool isInitial) (lines 269-275) sets _reobservePending after 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 stall InfiniteScrollSentinel guards 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 from failure?.LocalizedErrorMessage(L) (line 290); a raw exception passes null, 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. When OnCardClick has a delegate it returns an EventCallback.Factory.Create wrapping the invoke; when it does not, it returns default, deliberately not EventCallback.Empty, because EventCallback.Empty wraps a no-op Action so its HasDelegate is still true and every card would present as interactive. default is the only value ClickableCard reads 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 to CardActionsTemplate, or returns null when the consumer supplied none, which keeps ClickableCard on its original one-element markup (lines 305-308). RetryAsync (line 311) is a plain LoadNextPageAsync(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 _isLoadingMore explicitly (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 the DotNetObjectReference.
    • The markup (Components/Lists/MobileInfiniteScrollList.razor:1-66) renders one of four shapes: an indeterminate progress bar inside a role="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); EmptyState when the list came back empty (lines 23-26); or a MudStack of ClickableCard wrappers around the caller's template, each keyed by item and wired to CardCallback(item) and CardActions(item) (lines 29-36). Below the cards it renders the sentinel div only 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 one RenderFragment, LoadFailedAlert, carrying role="alert" with the message and a Retry button (lines 62-65).
  • 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 raw Task<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 at Components/Lists/ListPageShell.razor:47 once the page's layout is known (the ADC conference admin lists such as SessionList.razor, SpeakerList.razor and RoomList.razor, and Store's CategoryList.razor, ProductList.razor and ShoppingCartList.razor). Pages that render it directly: ADC's PublicEventList.razor:25, PublicSessionListView.razor:6 and the check-in AttendeeSearchPanel.razor:28, and Store's MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.UI/Pages/Orders/OrderList.razor:39. Covered by MobileInfiniteScrollListTests. 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: MaxRenderedItems bounds 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 its CancellationToken still 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 PageHeader with 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's MudDataGrid<TItem>, MudDataGridPager and MudProgressLinear (ListPageShell.razor:58, :81, :41), the PageHeader, ListNoRecordsContent and DeleteConfirmation components (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: SearchAriaLabel defaults 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. IsMobile starts 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-high role="status" placeholder and fetches nothing while LayoutKnown is 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), CancelLabel and CancelAriaLabel, which default to the shared Common.Button.Cancel and List.Aria.CancelLoading texts (:41, :44), and HeaderActions (:47).
    • Search row: ShowSearch defaults to true (:50), SearchText to empty (:53), SearchTextChanged is raised debounced (:56), SearchPlaceholder defaults to List.Search.Placeholder (:59), and Filters renders after the search box (:69).
    • Layout: IsMobile (:72) and IsLayoutKnown, a bool? that defaults to null (:74-84). The private LayoutKnown (:161-167) is IsLayoutKnown ?? (ServerData?.Target as IListLayoutSource)?.IsLayoutKnown ?? true: the explicit value when passed, otherwise the page that owns ServerData (bound as the page's own method, so the delegate's Target is the page), otherwise open. A shell driven by anything other than a DataGridListPageBase therefore 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] MobileFetch and CardTemplate (:87-89, :92-94), CardActionsTemplate for controls beside the card body (:96-101), OnCardClick (:104) and MobilePageSize, default 10 (:107).
    • Grid branch: the [EditorRequired] ServerData callback (:110-112), CurrentPage with CurrentPageChanged for @bind-CurrentPage (:115, :118), RowsPerPage default 10 (:121), Dense default true (:124), the [EditorRequired] Columns (:127-129) and PageSizeOptions, whose null offers 5, 10, 25, 50 and 100 (:132, :169).
    • States: LoadFailed, EmptyConfirmed and EmptyMessage (:135-141), OnRetry (:144), ShowDeleteConfirmation default true and DeleteEntityType (:147, :150).
    • Exposed references: Grid is null on a phone (:153), MobileList is null on desktop (:156) and DeleteDialog is null when the confirmation is not rendered (:159), so a page cannot act on the branch that is not showing.
    • RetryAsync (:171-179) invokes OnRetry when a delegate is wired and otherwise reloads the grid's server data.
  • 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 ServerData delegate'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 by ListPageShellTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Lists/ListPageShellTests.cs), ListPageShellLayoutGateTests (same folder) for the layout gate, and the ProbeListPage conformance page, and referenced by PageHeadingTestsBase and DataGridListPageTestsBase.

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 with RequiresAuthentication, and the browser then fetches through the same API client and saves the bytes through the browser saver. Every client-side fetch is capped by MaxBytes (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: IExternalLinkService and ISensitiveFileSaver (the device-capability abstractions), IHttpClientFactory, ApiSettings through IOptions<ApiSettings>, IToastService, and IStringLocalizer<ApiFileDownloadButton> over the component's own .resx pair, all injected in the markup file (Components/Forms/ApiFileDownloadButton.razor:5-10). The code-behind also injects IServiceProvider (ApiFileDownloadButton.razor.cs:120-121) so it can resolve ITokenStorageService optionally, and it calls AuthDelegatingHandler.TrackTokenOwner on the authenticated fetch (:230). The file name goes through the package's static SafeFileName helper (Services/Capabilities/Files/SafeFileName.cs:14). Externals: HttpCompletionOption, MemoryStream, AuthenticationHeaderValue, and MudBlazor's MudIconButton.
  • 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 on ExternalLink.InterceptsLinks || RequiresAuthentication (ApiFileDownloadButton.razor:21). The first branch is a button whose click runs DownloadThroughClientAsync (:23-28); the second is the plain link (:32-36). Both render the same MudIconButton with 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's ISensitiveFileSaver: 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 through SafeFileName.Reduce before 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 past MaxBytes.
  • Walkthrough:
    • DefaultMaxBytes (line 23) is the public default for MaxBytes, 25L * 1024 * 1024 (25 MiB).
    • Parameters (lines 25-114). Three are [EditorRequired]: RelativeApiPath (line 28), FileName (line 39) and ShareTitle (line 44). ContentType defaults to application/octet-stream (line 52) and is what the share sheet uses to pick target apps. Icon defaults to the generic download glyph (line 56), Size to Size.Small (line 60). AriaLabel, UnavailableMessage and FailureMessage (lines 68, 75, 82) are nullable overrides over localized defaults. HttpClientName defaults to "APIClient" (line 89), the framework's bearer-token plus culture-header client. RequiresAuthentication (line 103) defaults to false: 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, while true fetches 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 to DefaultMaxBytes and bounds what the client-side fetch (a native head, or a browser with RequiresAuthentication) 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 injected IServiceProvider, used only to resolve ITokenStorageService optionally: 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) resolves AriaLabel ?? L["Button.Download.Aria"].Value, and the markup binds it to BOTH aria-label and title on either branch (ApiFileDownloadButton.razor:25-26, :34-35), so an icon-only control always carries a name (WCAG 4.1.2, per the AriaLabel doc 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's Href. The anchor is a plain top-level navigation, so it carries cookies but never an Authorization header (lines 125-131), and the base is chosen in that light as SameOriginApiEndpoint ?? 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 prefers WasmApiEndpoint over ApiEndpoint because the browser needs the externally reachable gateway URL: on the Server head ApiEndpoint may be a container-internal name, and on the WASM head ApiEndpoint is 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 _isExporting and an empty path (lines 149-152), reduces FileName through SafeFileName.Reduce before the fetch so an unusable name costs no download (lines 157-163), pulls the bytes through FetchAsync (line 165) and toasts the failure when that returns null for an over-cap payload (lines 166-170), then hands them to FileSaver.SaveAsync with the sanitized name, ContentType and ShareTitle (line 172), toasting UnavailableMessage or 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 through WarnDownloadFailed (line 274) rather than throwing: HttpRequestException (line 179), OperationCanceledException (line 183, which here is the HttpClient timeout, not a disposal, since no token is passed), and a bare Exception (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 an OnClick callback where an unhandled exception is fatal to a native host (lines 193-195). The finally clears the guard (line 200).
    • FetchAsync (lines 218-248) creates the named client and builds a GET for the relative path (lines 220-221). With RequiresAuthentication set it resolves ITokenStorageService from the component's own scope (line 223); when that yields a non-blank access token it sets the Bearer header on the request (line 229) and calls AuthDelegatingHandler.TrackTokenOwner(token, tokenStorage) (line 230). It then sends with HttpCompletionOption.ResponseHeadersRead (line 236), so the size cap runs before the body is buffered (the default completion option would read the whole body inside SendAsync, per the comment at lines 234-235), and calls EnsureSuccessStatusCode (line 237, so a non-success status becomes the HttpRequestException the caller catches). A Content-Length above MaxBytes returns null before any body byte is read (lines 238-241); otherwise the body stream goes through ReadCappedAsync (lines 243-247). The doc comment (lines 204-217) gives the reason for setting the header here: IHttpClientFactory builds AuthDelegatingHandler in 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 existing Authorization header 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 pattern AuthenticatedServiceBase and ApiUserPreferenceWriter follow. Without RequiresAuthentication, 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 a MemoryStream in 81,920-byte chunks (line 259) and returns null as 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 no Content-Length and a length header that understates the body.
    • The sanitizer is not a private method of the component: it is the public static SafeFileName.Reduce in the same package (Services/Capabilities/Files/SafeFileName.cs:23-32), which trims the name, reduces it to a bare name with Path.GetFileName and rejects an empty result, . and .. (lines 25-31), returning null when nothing usable remains. Its remarks (lines 7-13) state the exact hazard: Path.Combine discards 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 ISensitiveFileSaver puts 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 understate Content-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 supplies ContentType="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 with RequiresAuthentication="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 by ApiFileDownloadButtonTests and ApiFileDownloadButtonAuthenticatedTests.
  • Caveats / not-in-source: with RequiresAuthentication the browser holds the whole payload in memory before saving it, which the plain link avoids (lines 91-101); MaxBytes bounds that buffer but does not stream it. No ADC caller in this source sets MaxBytes. ADC's personal-data export on the profile page does not use this component: LegalAndDataCard hands the file to ISensitiveFileSaver directly (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 the mmca-exports folder named at MMCA.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 a MudButton that 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 InputFile and InputFileChangeEventArgs (Microsoft.AspNetCore.Components.Forms) and MudBlazor's MudButton, Variant, Color, Size and Icons.
  • 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 the hidden attribute 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 the InputFile keeps its tab stop under the visually-hidden class (FilePickerButton.razor:17-24), and the visible control is a MudButton rendered with HtmlTag="label" and for pointing 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-within ring and the keyboard path stays visible (WCAG 2.4.7, :1-6).
  • Walkthrough:
    • Text (line 19) and OnChange (line 24) are [EditorRequired]: the visible text (also the accessible name) and the callback that receives the picked files, bound straight to the InputFile (FilePickerButton.razor:18).
    • InputId (line 31) is optional. EffectiveInputId (line 84) falls back to a per-instance GeneratedInputId of file-picker-{Guid:N} (line 82), so the label's for and the input's id always match; set it when a test or page selects the input by id, such as Playwright's SetInputFilesAsync("#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 from Text; unset, the markup emits no aria-label and 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's multiple.
    • Presentation: Icon defaults to the upload glyph (line 57), Variant to Variant.Outlined (line 61), Color to Color.Default (line 65), Size to Size.Medium (line 69), and Class (line 73) adds wrapper classes.
    • InputAttributes (lines 79-80) captures unmatched attributes and splats them on the InputFile, not the button (FilePickerButton.razor:24), so a data-testid lands 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 by FilePickerButtonTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Forms/FilePickerButtonTests.cs) and listed in EditorRequiredParameterConventionTests.
  • Caveats / not-in-source: the :focus-within ring 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, implements IStringLocalizer)

  • What it is: a private class nested inside InvariantMudLocalizationInterceptor that resolves MudBlazor's own built-in English strings straight from its embedded resource file, instead of MudBlazor's generated LanguageResource class, which is internal to the MudBlazor assembly and therefore unreachable directly.
  • Depends on: System.Resources.ResourceManager and System.Globalization.CultureInfo (BCL); reads the manifest resource named "MudBlazor.Resources.LanguageResource" off typeof(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 private constructor and a static Instance property, lines 79-83).
  • Walkthrough: this[string name] (85-92) calls Resources.GetString(name, CultureInfo.InvariantCulture) (89) and returns a LocalizedString whose resourceNotFound flag is set when that lookup returns null. this[string name, params object[] arguments] (94-104) does the same lookup, then formats the resolved string with CultureInfo.CurrentCulture when it was found, or falls back to the bare name when it was not (98-101). GetAllStrings(bool includeParentCultures) (106-122) enumerates the invariant-culture ResourceSet (108) and yields a LocalizedString per entry, or nothing if the set cannot be created (109-112).
  • Why it's built this way: private and sealed, nested inside its only consumer, because it exists solely to give InvariantMudLocalizationInterceptor an IStringLocalizer it can pass as the English fallback to the base AbstractLocalizationInterceptor constructor; 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 Instance and passed as the built-in localizer argument to InvariantMudLocalizationInterceptor'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.StringBuilder and char.IsLetter (BCL). Nothing first-party. It is consumed by PseudoStringLocalizer.
  • 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 = " !!]", and CombiningAcute (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 a StringBuilder with slack for the padding (line 37) and appends the open sentinel (line 38); then walks each character in a switch (lines 42-66) tracking an insidePlaceholder flag 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 a letters counter (lines 54-64); finally computes the pad length as Math.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).
  • 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 corrupt string.Format, so pseudo-loc must accent the template and only then substitute arguments (see the two-step in PseudoStringLocalizer).
  • Where it's used: called by PseudoStringLocalizer on 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 by PseudoLocalizationTests.

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 to IStringLocalizer, resolving the count-appropriate resource key (a .One suffix for a count of exactly one, .Other for 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 standard IStringLocalizer indexer, rather than pulling in a full CLDR plural-rules library. OneSuffix (".One", line 23) and OtherSuffix (".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's LangVersion: preview setting enables, in place of a classic this IStringLocalizer localizer first parameter.
  • Walkthrough: Plural(string key, int count, params object[] args) (lines 40-52) validates its arguments (42-44), picks pluralKey as key + OneSuffix when count == 1 or key + OtherSuffix otherwise (46), resolves it through the localizer's indexer (47), and if that lookup's ResourceNotFound is true, falls back to the base key itself (51): the comment at 49-50 records why the fallback matters, ResourceNotFound is how a ResourceManager-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 key means a resx file that has not yet been split into .One/.Other entries 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 ComponentBase whose 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; calling NavigationManager.NotFound() is the framework signal that sets the 404 status.
  • Walkthrough
    • Navigation (lines 14-15) is an [Inject]ed private NavigationManager.
    • 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; internal because 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 IAuthorizationRequirement behind the two policies the notification pages declare instead of a bare [Authorize]: mmca:notification-pages (the inbox, any signed-in caller) and mmca:notification-manage-pages (history and compose, a signed-in caller who also holds notifications: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 the notifications:manage permission 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: PolicyName is "mmca:notification-pages" (line 29, any signed-in caller). ManagePolicyName is "mmca:notification-manage-pages" (line 35, signed in and holding NotificationPermissions.Manage). Permission (line 41) is the constructor's permission argument, null when 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: PolicyName with new NotificationPageRequirement() and ManagePolicyName with new 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, implements IDisposable)

  • What it is: a wrapper around Blazor's built-in FocusOnNavigate that 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, LocationChangedEventArgs and the FocusOnNavigate component (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's h1 tells assistive technology that the page changed. The markup comment (Layout/FocusOnInAppNavigate.razor:1-4) records why the stock component is not used directly: FocusOnNavigate also fires on the first render, which put focus on the h1 of 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 injected NavigationManager.
    • Parameters: RouteData (lines 21-23) is [EditorRequired] and passed through to FocusOnNavigate; 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 to LocationChanged (line 36).
    • OnLocationChanged (lines 39-49) returns early when the component has already flipped, or when the new location's absolute path equals _initialPath under OrdinalIgnoreCase (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 with InvokeAsync(StateHasChanged) (line 48). From that render on, FocusOnNavigate is in the tree and handles every later navigation itself.
    • Dispose (line 30) unsubscribes from LocationChanged.
  • 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:52 with Selector="h1", so every host that uses the shared Routes gets it. Covered by MMCA.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's MudLocalizer like 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 optional MudLocalizer constructor 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 through MudLocalizer like any other culture, falling back to the built-in string only if that lookup reports ResourceNotFound.
  • Walkthrough: the primary constructor (line 37) takes an optional MudLocalizer? mudLocalizer and passes it, alongside BuiltInStrings.Instance, to the base AbstractLocalizationInterceptor. Handle(string key, params object[] arguments) (lines 41-61) validates its arguments (43-44), computes isEnglish by comparing CultureInfo.CurrentUICulture.Parent.TwoLetterISOLanguageName to "en" with OrdinalIgnoreCase (49-52), and returns straight from BuiltIn(key, arguments) (56) when MudLocalizer is null or the culture is English (54-57); otherwise it tries MudLocalizer[key, arguments] (59) and falls back to BuiltIn when that translation reports ResourceNotFound (60). The private BuiltIn(string key, object[] arguments) helper (65-66) is a no-argument-indexer call when arguments is 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 default DefaultLocalizationInterceptor for 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 by MMCA.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 IStringLocalizer decorator 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 (its IsPseudoLocale from MMCA.Common.Shared.Globalization), and IStringLocalizer/LocalizedString/CultureInfo (BCL and NuGet). Constructed with an inner IStringLocalizer via 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 implements IStringLocalizer and forwards to inner, it can be slid underneath every IStringLocalizer<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 returns SupportedCultures.IsPseudoLocale(CultureInfo.CurrentUICulture.Name), the single gate every member checks.
    • this[string name] (lines 20-29): resolves inner[name] (line 24), then, if pseudo is active, returns a new LocalizedString whose value is PseudoLocalizer.Transform(localized.Value) while preserving ResourceNotFound/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 to inner[name, arguments] (lines 36-39); when active it does the two-step that makes placeholders survive, transform the raw template first (lines 43-44), then string.Format the 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 PseudoStringLocalizerFactory around every localizer the inner factory creates, so it transparently wraps IStringLocalizer<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 MudLocalizer implementation that resolves the library's built-in component text from the MudTranslations resource 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), and MudTranslations (Level 0). Nothing else first-party.
  • Concept introduced, adapting a third-party localization hook. [Rubric §2, Design Patterns] (this is an Adapter, bridging MudBlazor's MudLocalizer contract to the ASP.NET Core IStringLocalizer world) and [Rubric §27, Internationalization]. MudBlazor exposes exactly one extension point for translating its built-in strings: subclass MudLocalizer and override its indexer. This adapter routes that indexer straight to IStringLocalizer<MudTranslations>. MudBlazor's own DefaultLocalizationInterceptor consults this localizer only for non-English cultures and falls back to its built-in English whenever the returned LocalizedString.ResourceNotFound is 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 single public override LocalizedString this[string key] => localizer[key]; (line 19). The doc comment (lines 13-15) also notes that because resolution flows through the DI IStringLocalizerFactory, the PseudoStringLocalizerFactory decorator applies here too, so under the development-only qps-Ploc culture MudBlazor's chrome pseudo-localizes alongside the application text.
  • Why it's built this way: internal because it is pure host wiring no consumer needs to name; delegating to the injected IStringLocalizer<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 MudLocalizer in AddUIShared via services.TryAddTransient<MudBlazor.MudLocalizer, ResxMudLocalizer>() (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:130). TryAdd is authoritative because AddMudServices does not register a MudLocalizer of its own (guarded by a DI-resolution test, per the comment at DependencyInjection.cs:126-129), regardless of host registration order. Covered by ResxMudLocalizerTests.

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 IStringLocalizerFactory decorator that wraps every localizer the inner factory produces in a PseudoStringLocalizer, so decorating this one factory pseudo-localizes every IStringLocalizer<T> and IStringLocalizer in the host at once (ADR-027 §8).
  • Depends on: PseudoStringLocalizer (Level 1) and IStringLocalizerFactory/IStringLocalizer (Microsoft.Extensions.Localization, NuGet). Constructed with the inner factory 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). Because StringLocalizer<T> resolves its backing localizer through the IStringLocalizerFactory, 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 by IStringLocalizer<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) in AddUIShared (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:124), after services.AddLocalization() (line 117). Its reach includes MudBlazor chrome through ResxMudLocalizer, which resolves its IStringLocalizer<MudTranslations> through this same factory.

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 (its Items list) and System.Type for the resource that localizes the heading. It is built from a NavGroup description 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), Icon and Expanded (from the described NavGroup, defaulting to the folder icon and collapsed), Order (the unit's sort key, 0 when undescribed) and Items (the group's items already sorted by NavItem.Order). All six are filled in NavMenu.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 sealed keeps it an implementation detail of the menu.
  • Where it's used: only inside NavMenu: DisplayGroup (NavMenu.razor.cs:37-46) localizes its heading, and the SectionUnits render fragment (MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor:131-152) draws a MudNavGroup for a unit with a key and flat MudNavLinks 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 Manage gate), plus the NotificationBell and NotificationListener components 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 through IModule; 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 shared MainLayout.razor or a central menu file.
    • [Rubric §18, UI Architecture & Component Design] applies to the two component collections: AppBarComponentTypes and LayoutComponentTypes are Type handles, 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 carries RequiredPermission: NotificationPermissions.Manage (line 20) on the nav item itself, so the authorization fact lives next to the thing it protects rather than in a layout if.
    • [Rubric §27, Internationalization & Localization]: the nav labels are resource keys plus a resource type, "Nav.NotificationInbox" and "Nav.PushNotifications" with typeof(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 immutable IReadOnlyList<NavItem> with two entries: the inbox key Nav.NotificationInbox to NotificationRoutePaths.NotificationInbox with the Inbox icon in NavSection.User (line 19, no role, so any authenticated user sees it), and Nav.PushNotifications to NotificationRoutePaths.Notifications with the NotificationsActive icon, gated on NotificationPermissions.Manage, in NavSection.Admin and 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) returns typeof(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 is sealed and 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 (Hides and HidesNotificationPages) 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 (no AddNotificationUI(), 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.Type and 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 the MMCA.Common.UI assembly itself, so they are routable in every host whether or not it called AddNotificationUI(); 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 static Type[] of typeof(NotificationList), typeof(NotificationInbox) and typeof(NotificationSend), the routable pages that need the services AddNotificationUI() registers.
    • Hides(Type pageType, IEnumerable<IUIModule> modules) (lines 20-21) is NotificationPages.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 is public so NotificationPageAuthorizationHandler can ask the same question without a page type.
  • Why it's built this way: keeping the decision in a small internal static predicate, with the page type and module list passed in, keeps Routes.razor to 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 renders Pages.NotFound inside MainLayout when either returns true (TwoFactorPageGate is the two-factor twin of this gate); also referenced from the doc comments of NotificationPageNotFoundStatus and NotificationPageRequirement; pinned by NotificationPageGateTests (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 on IServiceCollection that 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) and Microsoft.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 several DependencyInjection classes in the UI packages: this one is specifically the Notifications registrar, the sibling of the MMCA.Common.UI.Web host 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's Program.cs beyond the single line.
    • TryAdd versus Add is a deliberate signal. The scope provider is registered with TryAddScoped (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 plain AddScoped/AddSingleton because this package owns those contracts.
  • Walkthrough: inside the extension block (line 14), AddNotificationUI() (line 20) registers, in order, INotificationScopeProvider to NullNotificationScopeProvider via TryAddScoped (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 returns services for 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.cs of each consuming host (Blazor Web and MAUI) that opts into the notification UI; it complements the main MMCA.Common.UI registration 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 the NotificationBell configuration 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-pages and mmca: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 calls Succeed, 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) guards context and requirement with ArgumentNullException.ThrowIfNull (lines 21-22), then calls context.Succeed(requirement) (line 27) when NotificationPageGate.HidesNotificationPages(modules) is true (line 24) or IsSignedInWithPermission is true (line 25), and returns Task.CompletedTask (line 30).
    • IsSignedInWithPermission (lines 35-39): true when any identity IsAuthenticated and either requirement.Permission is null or context.User.HasPermissionClaim(requirement.Permission). It is the same check the pages run themselves, so the policy and the in-page gate cannot disagree.
  • Why it's built this way: delegating the "hidden" question to NotificationPageGate.HidesNotificationPages means 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 IAuthorizationHandler with TryAddEnumerable in AddUIShared (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 by NavItemGuardContractTestsBase (MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Navigation/NavItemGuardContractTestsBase.cs, 1 reference).

MMCA.Common.UI · MMCA.Common.UI.Layout · MMCA.Common/Source/Presentation/MMCA.Common.UI/Layout/NavMenu.razor.cs:14 · Level 8 · class (partial component, implements IDisposable)

  • 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> and IStringLocalizerFactory. Works over NavItem, NavGroup, NavSection and its own nested NavUnit, and uses HasPermissionClaim from ClaimsPrincipalExtensions. MudBlazor supplies MudNavMenu, MudNavGroup, MudNavLink and 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 contributes NavItems, NavGroups and app-bar component types through IUIModule, 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 at NavMenu.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, _groupDescriptions keyed by group key, the three arranged section lists (_generalUnits, _userUnits, _adminUnits), _showSessionsLink and the _subscribed flag.
    • Display(NavItem) (lines 29-33) creates a localizer for the item's TitleResource through the factory and returns the raw Title when 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 by Group in first-appearance order, builds a NavUnit per group with the described icon (default Icons.Material.Filled.Folder, line 60), expansion (default collapsed, line 61) and order (default 0, line 62), sorts items inside the unit by NavItem.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 via TryAdd (78-81), builds the sections from the current auth state (83), then subscribes to AuthenticationStateChanged (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 of RefreshFromAuthStateAsync (lines 97-111), which rebuilds and re-renders inside InvokeAsync and swallows the ObjectDisposedException raised when the renderer is torn down between the event and the dispatch (107). The comment at 92-93 explains the discard as avoiding an async void handler (VSTHRD100).
    • RebuildFromAuthStateAsync (lines 113-131) stores the user, shows the Sessions link when LayoutSettings.SessionsNavRequiredRole is blank or the user is in that role (118-119), keeps each item whose RequiredRole, RequiredClaim and RequiredPermission are each either unset or satisfied (121-126), and arranges the survivors per NavSection (128-130).
    • HandleLogoutAsync (line 70) delegates to SignOutNavigator.SignOutAsync("/login") (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Navigation/SignOutNavigator.cs:47), which runs IAuthUIService.LogoutAsync and 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 by RedirectToLogin's own navigation, and while the navigator's sign-out is in flight RedirectToLogin stands down (SignOutNavigator.cs:16-21). The log-out link binds it at NavMenu.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 because NavItem.RequiredRole defaults to null, so an admin item registered without a role would otherwise disclose its URL to anonymous visitors.
  • 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 by NavMenuTests and NavMenuOrderingTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Layout/), the sign-out path by LayoutSignOutTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Navigation/LayoutSignOutTests.cs), and the NavItemGuardContractTestsBase contract in MMCA.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 the IStringLocalizer<FeatureFlagAdminResources> that FeatureFlagAdmin falls back to.
  • Depends on: nothing; no members.
  • Concept reinforced: the app-localizer-first fallback RoleAdminEditResources introduces. [Rubric §27, Internationalization]. FeatureFlagAdmin injects it as L (FeatureFlagAdmin.razor.cs:72) and its T(key, args) helper (:120-132) consults the app's Localizer parameter 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, including MMCA.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 RoleAdminEditResources introduces. [Rubric §27, Internationalization]. Injected as L in MachineClientAdmin.razor.cs:52 and reached through its T(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) and MMCA.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 RoleAdminEdit that groups the permissions filed under one area:capability prefix, 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") and Permissions (that area's permissions, ordered). Built by RoleAdminEdit.Group(IEnumerable<string>) (RoleAdminEdit.razor.cs:317-329), which groups the catalog's permissions by RoleAdminEdit.AreaOf and orders both the groups and each group's members with StringComparer.Ordinal, so the checkbox layout is stable across loads.
  • Why it's built this way: private and sealed because it exists only to shape one component's markup loop; nothing outside RoleAdminEdit needs it.
  • Where it's used: the _groups field of RoleAdminEdit (RoleAdminEdit.razor.cs:131), populated by Group(...) 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 an IStringLocalizer<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. RoleAdminEdit injects IStringLocalizer<RoleAdminEditResources> as L (RoleAdminEdit.razor.cs:160) and its private T(key, args) helper (:205-217) checks the caller-supplied Localizer parameter first, falling through to L (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.resx beside the class) has something to key against.
  • Walkthrough: no members.
  • Why it's built this way: sealed because nothing subclasses a resource marker; kept as a distinct class per component (paired with RoleAdminListResources, 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 injected L property, the T fallback call, and the DI registration type argument) and 2 more, including MMCA.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 to RoleAdminList instead.
  • Depends on: nothing; no members.
  • Concept reinforced: the app-localizer-first fallback RoleAdminEditResources introduces. [Rubric §27, Internationalization].
  • Walkthrough: no members.
  • Why it's built this way: kept distinct from RoleAdminEditResources so 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, including MMCA.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 RoleAdminEditResources introduces. [Rubric §27, Internationalization]. Injected as L in SupportAccessLog.razor.cs:69; that component's T(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, including MMCA.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 RoleAdminEditResources introduces. [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, including MMCA.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 in FeatureFlagAdmin: 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: Source is the route prefix the row came from, which is where a later set or clear must be sent; Flag is the server's status for that flag. Rows are built in LoadAsync (FeatureFlagAdmin.razor.cs:156) and replaced with a with expression after a save (:213) or a clear (:237).
  • Why it's built this way: carrying Source on 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 as Flags, line 70), FeatureFlagAdminUIOptions (ConfiguredSources, 74), IStringLocalizer<FeatureFlagAdminResources> (L, 72, see FeatureFlagAdminResources), the shared contracts FeatureFlagStatusResponse, SetFeatureFlagOverrideRequest, FeatureFlagOverrideMode, FeatureFlagLifetime and FeatureFlagValueKind, Result, and its nested FlagRow. Externals: Blazor's ComponentBase, 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: the Sources parameter (56) when supplied, otherwise the sources AddFeatureFlagAdministrationUI configured (EffectiveSources, 76). LoadAsync (141-171) walks every source in order, appends each source's flags as FlagRows, 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) fallback RoleAdminEdit introduces (120-132 here, same shape). [Rubric §27, Internationalization]. Enum values are localized by key composition: LifetimeText (134, Lifetime.{value} or Lifetime.Unknown), ValueText (137), ModeText (139).
  • Walkthrough:
    • State (32-50): Modes, every FeatureFlagOverrideMode value for the mode picker (32), the component-scoped CancellationTokenSource (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) runs LoadAsync once; 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 to Off, users and groups joined with ", ") and always clears _reason (183): the reason belongs to this change, not the previous one.
    • SaveAsync (193-226): builds a SetFeatureFlagOverrideRequest (203) with the comma lists split by SplitList (114, trimmed, empties dropped), calls Flags.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 _saveResult inside the editor.
    • ClearAsync(row) (228): calls Flags.ClearOverrideAsync (230); a failure goes to _loadResult, a success replaces the row locally with no override and Effective set back to Configured (237), without a reload.
    • Replace (240): swaps a row by reference index in _rows.
  • 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 from MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/DependencyInjection.cs, and both MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/FeatureFlags/AdminFeatureFlagsController.cs and MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/AdminFeatureFlagsController.cs reference it. Tested by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/FeatureFlagAdminTests.cs; covered by the heading fitness base MMCA.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, see MachineClientAdminResources), the shared contracts MachineClientResponse, MachineClientSecretResponse and CreateMachineClientRequest, and Result. Externals: Blazor's ComponentBase, IStringLocalizer.
  • Concept introduced, a 404 read as "feature off". [Rubric §18, UI Architecture & Component Design]. Every machine-client route answers 404 while MachineClients:Enabled is false on the server, so NotEnabled (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 a MachineClientSecretResponse; the component keeps it in _issued (26) only until DismissSecret (196) clears it, and adds or replaces the client row from issued.Client (148, 170).
  • Concept reinforced: the app-localizer-first T(key, args) fallback (92-104), as introduced in RoleAdminEdit. [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.Revoked when RevokedOn is set, Status.RotationPending while a secondary secret exists, otherwise Status.Active.
    • LoadAsync (113): one Clients.GetAllAsync call, unwrapped with TryGetValue.
    • CreateAsync (137): posts CreateMachineClientRequest(_name, _role) (143); on success records the secret, appends the client, and clears the form.
    • PromoteAsync (178) and RevokeAsync (181) share ApplyRowResult (184): replace the row on success, put the failure in _loadResult otherwise. Replace (198) matches by ClientId.
    • Dispose(bool) (75): the idempotent cancel-and-dispose shape.
  • 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 in MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs. Tested by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/MachineClientAdminTests.cs and MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/Pages/Users/MachineClientsPageTests.cs; covered by MMCA.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 as Roles, line 80), IToastService (Toast, 82), IStringLocalizer<RoleAdminEditResources> (L, 84, see RoleAdminEditResources), LatestLoadGuard (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/LatestLoadGuard.cs:38, held as _load, line 42), its own nested PermissionGroup record, and AdministrationPermissions.ManageRoles (MMCA.Common.Shared.Auth.Administration). Externals: Microsoft.Extensions.Localization.IStringLocalizer, Blazor's ComponentBase.
  • 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 the PermissionGrant table. 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 is AdministrationPermissions.ManageRoles itself (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 private T(key, args) helper (141-153) checks the caller-supplied Localizer parameter first via its indexer (overridden.ResourceNotFound), falling back to L (an IStringLocalizer<RoleAdminEditResources>) only when the app's localizer does not carry the key; the same shape repeats verbatim in RoleAdminList and UserAdminList<TUser>.
  • Walkthrough:
    • State (39-59): GeneralAreaKey const "Group.General" (39, the resource key for an ungrouped permission), a component-scoped CancellationTokenSource (41), the LatestLoadGuard _load (42, supersedes an in-flight load), _compiled/_stored as HashSet<string>(StringComparer.Ordinal) (47-48, IDE0028 suppressed because a collection expression cannot carry the comparer), _groups (51, the display-ready PermissionGroup list), _loadResult/_saveResult (52-53, the last load/save outcome for inline rendering), _loadedRole (54, guards a redundant reload), _isDirty (58, whether _stored has 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 when Role actually changed (string.Equals(_loadedRole, Role, Ordinal)), so a parent re-render does not throw away an operator's half-made edits. A Role change 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 _cts and also disposes _load (127).
    • LoadAsync (160-217): opens a generation with _load.Begin() (162), capturing (token, generation), and snapshots Role into requestedRole (163). It loads the role with that token, then the catalog; after each await it returns silently unless _load.IsCurrent(generation) still holds (174, 187), so a superseded load never touches the form. Each result is unwrapped with TryGetValue (role.TryGetValue(out var loadedRole), 179; catalog.TryGetValue(out var permissionCatalog), 192), so no null-forgiving .Value! read remains; either failure sets _loadResult and calls Reset() (219) and returns early. It clears _isDirty (169) up front, since a fresh load has nothing unsaved yet. On success it repopulates _compiled from loadedRole.RegisteredPermissions (200) and _stored from loadedRole.StoredPermissions (202), then builds _groups from permissionCatalog.Permissions via Group(...) (204). An OperationCanceledException is swallowed only when the load is no longer current (206), and finally clears IsLoading only for the current generation (212), so the newer load owns the spinner.
    • Group(permissions) (233): groups by AreaOf (243, the text before the first : or the localized GeneralAreaKey), orders groups and, within each, members, both with StringComparer.Ordinal, so the rendered layout is deterministic across loads.
    • ReadOnlyHint(permission) (265): the reason text beside a locked checkbox, Hint.Compiled when the code grants it, Hint.ManageRoles for the self-lockout case, empty otherwise.
    • Toggle(permission, granted) (277-289): adds or removes the permission from _stored only, a compiled permission is never touched because it is not a member of _stored to begin with, and sets _isDirty = true (288) unconditionally, since either direction of a toggle is an edit worth protecting.
    • SaveAsync (291-335): captures savedRole = Role before the await (303, the save-side twin of the load guard) and posts _stored, ordered, via Roles.SetStoredPermissionsAsync(savedRole, permissions, _cts.LifetimeToken()) (304). Afterwards formStillShowsSavedRole (305) compares savedRole with the current Role: when Role changed 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 _compiled and _stored from the server's response, saved.RegisteredPermissions and saved.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 PermissionGroup record (340) closes the file.
  • 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 Sessions applies after a revoke; locking ManageRoles unconditionally 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 in MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs. Tested by MMCA.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 base MMCA.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 object MMCA.Common/Source/Hosting/MMCA.Common.Testing.E2E/PageObjects/RoleAdminPage.cs; the UI gallery stubs it through MMCA.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 RoleAdminEdit for each, loaded whole in one call rather than through a paged grid.
  • Depends on: IRoleAdminUIService (Roles, 49), IStringLocalizer<RoleAdminListResources> (L, 51, see RoleAdminListResources). Externals: same ComponentBase/IStringLocalizer shape as its sibling.
  • Concept reinforced: the app-localizer-first T(key, args) fallback RoleAdminEdit introduces (100-112 here, identical shape). [Rubric §27, Internationalization].
  • Walkthrough:
    • State (30-33): _cts (30), _roles as IReadOnlyList<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) calls LoadRolesAsync once.
    • LoadRolesAsync (114): calls Roles.GetAllAsync(_cts.LifetimeToken()) (121), stores the whole Result in _loadResult (59, private field) for inline failure rendering, and sets _roles through result.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 as RoleAdminEdit and Sessions.
  • Why it's built this way: unlike UserAdminList<TUser>, which pages through MudDataGrid's server-data contract, this component loads the entire roster in one GetAllAsync call: 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 in MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs. Tested by MMCA.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 base MMCA.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 object MMCA.Common/Source/Hosting/MMCA.Common.Testing.E2E/PageObjects/RoleAdminPage.cs; the UI gallery stubs it through MMCA.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, see SupportAccessLogResources), the shared contracts ViewAsGrantListRequest, ViewAsGrantSummaryResponse and ViewAsGrantStatus, and Result. Externals: Blazor's ComponentBase, MudBlazor's Color.
  • 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, so StartOfViewerDayUtc(date, addDays) (133-142) converts a local midnight to UTC through ViewerTime.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.Zone is UTC; OnAfterRenderAsync (86) awaits EnsureResolvedAsync (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 to ViewAsGrantListRequest.DefaultPageSize; the server clamps it to MaxPageSize).
    • StatusColor (116): Live is Warning, Ended is Success, Expired and anything else Default. StatusText (164), StatusFilterText (166) and Display (169, Display.NotOnRecord for a missing email) localize the cells.
    • ApplyFiltersAsync (171): builds a new ViewAsGrantListRequest from 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) through Grants.GetPageAsync (219), stores the result for inline rendering, and computes _totalPages from the server's TotalItemCount (227), at least 1.
    • Dispose(bool) (100): the idempotent cancel-and-dispose shape.
  • 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 from MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IViewAsGrantsUIService.cs, and wired by MMCA.ADC in MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs. Tested by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/SupportAccessLogTests.cs; covered by MMCA.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, constrained where 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, see UserAdminListResources), MudDataGrid<TUser>/MobileInfiniteScrollList<TUser> (148-149), DeleteConfirmation (150), and IUserAdminDTO as the TUser bound. Its class declaration (UserAdminList.razor.cs:44-46) shows no base in this partial; the base is DataGridListPageBase<TDto>, declared by @inherits MMCA.Common.UI.Pages.Common.DataGridListPageBase<TUser> in the paired UserAdminList.razor:4, which is why Title, GridRef, OnParametersSet, OnInitializedAsync, SaveFilters and RestoreFilters are protected override. Two base helpers carry the layout plumbing: ReloadActiveLayoutAsync(mobileList) (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DataGridListPageBase.cs:1879) and MobilePageFetcher(...) (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 through FetchPage (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 no IUserAdminUIService<TUser> fallback: OnParametersSet (165) throws a directive InvalidOperationException when FetchPage is 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) and MobileFetch (252) both go through that one delegate. The three account actions (lock/unlock/role-change) go through IUserAdminActionsUIService.
  • Concept introduced (2), hiding an operator's destructive power over their own row. [Rubric §11, Security]. CanAdminister(user) (219) is false when _currentUserId (set from AuthenticationStateProvider in OnInitializedAsync, 178-186, read once per load with BL0013 suppressed at 182-184 because subscribing would need a dispose hook the base's non-virtual DisposeAsync does not offer) equals the row's Id, 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 above AssignableRoles), 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 behind FetchPage honors 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 _searchString under the "search" key, the list-page filter-persistence contract DataGridListPageBase<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 its MobileFilters choice changes. It goes through the private ReloadActiveLayoutAsync() (237), which hands _infiniteList to the base's ReloadActiveLayoutAsync(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's MobilePageFetcher(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 plain Email key 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 via IAppDialogService, marking the dialog destructive: locking (287) so a lock reads as destructive and an unlock does not, then calls Actions.LockAsync/UnlockAsync with user.Id, toasts, and reloads the active layout on success.
    • ChangeRoleAsync (308-332): confirms, calls Actions.SetRoleAsync(user.Id, role), toasts, and reloads.
    • DeleteUserAsync (335): routes through ListPageActions.DeleteWithConfirmationAsync, the shared delete-confirm-toast-reload sequence, calling OnDelete!(user) (the null-forgiving operator is safe here because the Delete button only renders when OnDelete is non-null).
  • Why it's built this way: a single required FetchPage replaces 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's GetPagedAsync.
  • 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 in MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs, and referenced from RoleAdminEdit.razor.cs and RoleAdminList.razor.cs. Tested by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/UserAdminListTests.cs (8 tests) and MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/Pages/Users/UserListTests.cs, with prerender coverage in MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Administration/UserAdminListPrerenderTests.cs; its [EditorRequired] parameters are checked by MMCA.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 ConfirmEmail moves through while redeeming an email-confirmation link: Working, Form, Confirmed and PasswordProof (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), when ConfirmAsync finds 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. ShowPasswordProof sets it (:303) when the plain redeem answers AuthErrorCodes.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 / _linkSent fields (not the enum) distinguishing which of those happened. PasswordProof is 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 into Form.
  • Where it's used: only inside ConfirmEmail, which stores it in _state and 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 email and token pairs in the URL fragment or, as a fallback, in the query string, for the two pages whose links share that shape: ConfirmEmail and ResetPassword (doc comment, EmailedLinkReader.cs:5-10). It holds no page state.
  • Depends on: NavigationManager and its GetUriWithQueryParameters extension (Microsoft.AspNetCore.Components); BCL Uri, 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 same email / token link 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 one internal static class makes both pages answer them identically. The replace flag (doc, :16-21) names the two situations: false on the first render, where only empty values are filled so the query string and the first pair win; true for 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 pair TryReadLinkPair rejects (:37-40), and in replace mode clears both values on the first recognized pair only (:42-46). Every recognized pair then goes through FillEmpty (:49), so within one fragment the first email and the first token win. 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 when MergeLinkFragment recognizes an email or token pair in it (:64-67), otherwise null.
    • ScrubLinkQuery(navigation, location) (:77-80): navigates with replace: true to the same location with the email and token query parameters set to null, 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 names email and token exactly with ordinal comparison (:131-135), and returns the value through Uri.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) and ResetPassword (ResetPassword.razor.cs:54, :60, :92). SignInLink does 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 SignInLink moves 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 a Ready state between reading the link and acting on it, because this page never redeems on its own (see SignInLink).
  • Walkthrough: Reading is the initial value (:42) while the fragment is read on first render. Ready means both the address and the token are present and the page is waiting for a tap on Continue (:112). Failed covers 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 Failed because the way on is the same in both cases: request a new link; the _errorMessage field carries which one happened.
  • Where it's used: only inside SignInLink, which stores it in _state and 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 ValidationAttribute that 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-party PasswordComplexity rule in MMCA.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 subclasses ValidationAttribute and overrides IsValid, 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 calls PasswordComplexity.Evaluate (PasswordComplexity.cs:52), the single Unicode-aware definition the server's StrongPasswordRules also 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 ErrorMessage with 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 an ErrorMessageResourceType / ErrorMessageResourceName pair that points at AuthFieldMessages.PasswordComplexity (see RegisterModel).
    • IsValid(object?, ValidationContext) (lines 22-36): one guard (line 24) returns ValidationResult.Success for a non-string, a null/empty input, or a password for which PasswordComplexity.Evaluate is true. Deferring the empty case to RequiredAttribute keeps the field to one message rather than two. On failure it returns a ValidationResult scoped 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-free IsValid(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 raw ErrorMessage property (comment, lines 31-33): FormatErrorMessage also resolves an ErrorMessageResourceType / ErrorMessageResourceName pair, which is how the auth models localize inside the attribute, and it returns a plain ErrorMessage or 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.MaximumLength is 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 to ResetPasswordModel.NewPassword (ResetPasswordModel, ResetPasswordModel.cs:26); evaluated by the LocalizedDataAnnotationsValidator in Register.razor (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Register.razor:33) and ResetPassword.razor (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ResetPassword.razor:43). Unit-tested in MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/PasswordComplexityAttributeTests.cs:12; its agreement with the server rule is pinned by the architecture test MMCA.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 EditForm backing model for the Forgot Password page: one Email string 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-party AuthFieldMessages resource 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 naming ErrorMessageResourceType = typeof(AuthFieldMessages) with ErrorMessageResourceName = nameof(AuthFieldMessages.EmailRequired) / nameof(AuthFieldMessages.EmailInvalid), and defaults to string.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 the For property'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: sealed and mutable (set, not init) because EditForm two-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 _model by ForgotPassword.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 wired For="@(() => _model.Email)" (line 41) so the message attaches to that input. On valid submit HandleRequestAsync (lines 80-97) calls IAuthUIService.RequestPasswordResetAsync(_model.Email) (line 86, contract at MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/IAuthUIService.cs:55) inside a try whose catch is empty on purpose (lines 88-91) and whose finally sets _isSubmitted = true unconditionally (line 95), so the confirmation renders for every submitted address whether the call succeeded, failed, or threw.
  • Caveats / not-in-source: RequestPasswordResetAsync returns a Result and 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 EditForm backing model for the Login page: two string properties (Email, Password) carrying DataAnnotations for field-level validation, plus an unvalidated TwoFactorCode for the second-factor step.
  • Depends on: System.ComponentModel.DataAnnotations (BCL): [Required], [EmailAddress]. The only first-party reference is AuthFieldMessages, 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 Blazor EditForm binds 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 through AuthFieldMessages inside 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 with ErrorMessageResourceType = typeof(AuthFieldMessages) and the name EmailRequired / EmailInvalid, defaulting to string.Empty.
    • Password (line 22), [Required] with the name PasswordRequired (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: sealed and mutable because EditForm two-way-binds each input; each attribute names one AuthFieldMessages entry 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 bound For="@(() => _model.Email)" and For="@(() => _model.Password)" at lines 99 and 106 so each MudTextField shows its own message, and the code field bound to _model.TwoFactorCode at line 115. On valid submit the Login code-behind builds a LoginRequest from it (Login.razor.cs:152, :162) and the page sends it through IAuthUIService (Login.razor:361). Sibling of RegisterModel; its shape rules are unit-tested alongside the other auth models in MMCA.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 EditForm backing 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-party PasswordComplexityAttribute, AuthFieldMessages for every message, and PasswordComplexity for the shared length cap.
  • Concept reinforced, multi-field form validation with a cross-field compare. [Rubric §24, Forms, Validation & UX Safety]. This builds on the LoginModel shape with three richer rules: [PasswordComplexity] on the password (paired with a [StringLength(PasswordComplexity.MaximumLength)] cap, 128 at MMCA.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 through AuthFieldMessages inside 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 an ErrorMessageResourceName = 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), entries EmailRequired / 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).
    • AddressLine1 plus nullable AddressLine2/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 _model and bound by Register.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 a RegisterRequest (Register.razor:250-251), folding the address fields into an Address through BuildAddressResult() (defined in the Register code-behind, Register.razor.cs:88, called at Register.razor:237), which returns null when address collection is off (Register.razor.cs:90-93) or all six fields are blank (lines 95-103) and otherwise calls Address.Create(...) (line 105). Its password block is mirrored by ResetPasswordModel; the accepted password is hashed server-side per ADR-032. Shape rules are unit-tested in MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/AuthModelValidationTests.cs:11; rendering and validation behavior are covered by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/RegisterFormTests.cs:23 and 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 EditForm backing 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-party PasswordComplexityAttribute, AuthFieldMessages for every message, and PasswordComplexity for 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 shape RegisterModel introduced, which is the payoff of expressing the complexity rule as an attribute rather than page code. What is new is the top half: Email and Token are 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 through AuthFieldMessages inside the attribute (doc comment, lines 12-14, ADR-027).
  • Walkthrough: four get; set; properties, each defaulting to string.Empty; every attribute names ErrorMessageResourceType = typeof(AuthFieldMessages) plus an ErrorMessageResourceName entry.
    • Email (line 21), [Required] plus [EmailAddress] (lines 19-20), entries EmailRequired / EmailInvalid.
    • Token (line 24), [Required] with entry TokenRequired (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 at NewPassword.
  • Why it's built this way: the doc comment (lines 7-10) records the load-bearing choice, that Email and Token arrive 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 _model by ResetPassword.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] Email and Token properties (lines 99-103) and copies them in OnParametersSet (lines 112-123, blank checks at 114 and 119). Second, OnAfterRenderAsync (lines 130-177) reads the URL fragment once on first render through the locationHashTake JS call (line 143), which also scrubs it from the address bar, and fills email / token from 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) calls IAuthUIService.ResetPasswordAsync(_model.Email, _model.Token, _model.NewPassword) (line 186, contract at MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/IAuthUIService.cs:62), flips _isCompleted on success, and on failure renders result.LocalizedErrorMessage(L) or the generic Auth.Reset.GenericError string (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 Token to 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 @code block 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 _model field, ResetPassword.razor:108); externals: NavigationManager.LocationChanged and LocationChangedEventArgs (Microsoft.AspNetCore.Components.Routing), BCL IAsyncDisposable, 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 to LocationChanged and 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): subscribes OnLocationChanged and records _locationHandlerRegistered (field at ResetPassword.razor:113).
    • OnLocationChanged (:42-64): ignored once disposed or before the first-render read has run (_fragmentRead, :44-47; set at ResetPassword.razor:143). A location with a non-empty fragment (:49-50) is read through TakeFragmentAsync, which also scrubs it, and handed to PrefillNewLink (:52). Otherwise, when EmailedLinkReader.LinkQueryOf finds an email or token pair in the query (:54), the page calls EmailedLinkReader.ScrubLinkQuery (:60) and prefills from that query (:61). Both run through InvokeAsync, because the event is raised outside the renderer's context.
    • PrefillNewLink(link) (:68-78): merges with replace: true (:70) and, only when the link carried a recognized pair, resets _isCompleted and _errorMessage and re-renders (:75-77), so a page that showed "password changed" for the previous link returns to the form.
    • TakeFragmentAsync() (:81-87): resolves CapabilitiesJsModule from Services and calls locationHashTake, returning null when the module is absent.
    • ApplyFragment(fragment, replace) (:90-100): calls EmailedLinkReader.MergeLinkFragment with 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 with replace: false (ResetPassword.razor:144), so a value the query string already put in the form wins.
    • DisposeAsync() (:16-27): sets _disposed and 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 EmailedLinkReader is what makes this page and ConfirmEmail behave identically.
  • Where it's used: routed at /reset-password in any host that maps the framework's Auth pages; the model it fills is described under ResetPasswordModel. Covered by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/Recovery/ResetPasswordFragmentTests.cs and ResetPasswordQueryLinkTests.cs in the same folder, and by MMCA.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 @code block, not in this file; HandleResetAsync (ResetPassword.razor:150-175) is not cancellable, since ResetPasswordAsync is 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 _model field, Login.razor:295), LoginRequest (Login.razor.cs:152, :162), LoginRefusals and LoginRefusal (:125-134), AuthEmailPrefill (:182, :211), ISignInLinkUIService (:231), IOidcDiscoveryUIService (:285), OidcProviderOption (:45), IPasskeyCapability and IPasskeyUIService (:202-203), SignInSettings (as SignInOptions, Login.razor:23), IExternalAuthBroker (Login.razor:22), OAuthFlowStateStore (Login.razor:15), ReturnUrlProtector (:207), IStringLocalizer<SharedResource> as L (see SharedResource), Result and its LocalizedErrorMessage extension, ComponentLifetimeExtensions.LifetimeToken (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/ComponentLifetimeExtensions.cs:26); externals: [SupplyParameterFromQuery] and NavigationManager (Microsoft.AspNetCore.Components), MudBlazor MudTextField<string>, BCL IDisposable, 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}, and Error (Login.razor.cs:82-83, bound by [SupplyParameterFromQuery(Name = "error")]) receives it. ExternalSignInErrorMessage (:326-332) maps null or empty to no message, oauth_failed and missing_claims to their own resources, and any other code to RefusalMessage (:334-338). That helper looks up Auth.Login.ExternalError.{code} and, when the resource is missing (ResourceNotFound), falls back to the generic Auth.Login.ExternalError.Refused text. 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 code LoginRefusals.Classify recognizes (: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 returns true for SecondFactorRequired, so no error shows the first time the step appears, and false for SecondFactorInvalid, so a wrong code keeps the step and shows the message. An EmailNotConfirmed refusal 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:
    • _cts and _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 an InteractiveAuto render-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), _signInLinkSentTo and _isSendingLink (:40-42), _oidcProviders (:45), _offersOrganizationSignIn and _isDiscovering (:48-50), _offersPasskeys (:53), _awaitingSecondFactor (:59), _codeField and _focusCode (:61-64), _unconfirmedEmail (:67).
    • Reason (:74-75, bound to ?reason=): two-factor-enabled or two-factor-required shows its notice; any other value is ignored (doc :69-73). Error (:82-83) is described above.
    • Dispose() (:86-90) and Dispose(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 _cts and 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 plain LoginRequest (:152), so a first attempt never carries a stale code. In the step, an empty code sets Auth.Login.SecondFactor.CodeRequired and returns null (:155-160); otherwise the request carries the trimmed TwoFactorCode (:162). The markup returns early on null (Login.razor:350) and passes _cts.LifetimeToken() to AuthService.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 through AuthEmailPrefill.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 when SignInSettings.OfferPasskeys is on, the head's IPasskeyCapability reports IsAvailable, and an IPasskeyUIService is 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-password with 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 shows Auth.Login.EmailMeLink.EnterEmail (:223-227); ISignInLinkUIService is 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 or Auth.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 when ExternalAuthBroker.IsAvailable, otherwise through the web redirect (Login.razor:265 for the per-provider buttons).
    • SignInWithOrganizationAsync() (:272-315, doc :267-271): the email-first organization step. It resolves IOidcDiscoveryUIService at the click (:285), asks which provider claims the address's domain (:294), shows Auth.Login.SignInWithOrganization.NotFound when none does (:297), and otherwise starts that provider (:301). An HttpRequestException becomes 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 in L (: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 generic Auth.Login.InvalidCredentials wording 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 awaits OAuthFlowState.BeginAsync(_cts.LifetimeToken()) (:378) into a local oauthState. An OperationCanceledException raised while _disposed is set (:380-384) means the page went away mid-write, so it returns with nothing to navigate from. If the store throws InvalidOperationException (:385), because storage accepted the write without keeping it (storage full, site data blocked, private mode), it sets _externalSignInUnavailable, shows Auth.Login.ExternalSignInStorageUnavailable, and returns without navigating (:387-389); the page re-renders on its own as the handler completes. Otherwise it calls Navigation.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 through LifetimeToken() rather than _cts.Token matters because the work can resume after Dispose: on a disposed source the raw Token throws ObjectDisposedException, while LifetimeToken returns an already-cancelled token so the work stops through its normal cancellation path (ComponentLifetimeExtensions.cs:3-10). The when (_disposed) filter keeps a cancellation the page did not cause from being silently swallowed.
  • Where it's used: the Login.razor provider buttons call SignInWithRedirectAsync("apple"), ("google") and ("github") (Login.razor:207, :229, :251), and BuildOAuthUrl (Login.razor:313) appends the state to the provider redirect query. The second-factor step is covered by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/SecondFactor/LoginSecondFactorTests.cs, the passkey offer by Passkeys/LoginPasskeyTests.cs, the OIDC starts by Oidc/LoginOidcTests.cs, the sign-in link request by SignInLinks/LoginSignInLinkTests.cs and the resend prompt by EmailConfirmation/LoginResendPromptTests.cs (all under the same Pages/Auth/ test folder). Error mapping is covered by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/LoginErrorQueryTests.cs, the attempt flow by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/LoginOAuthAttemptTests.cs, the in-flight cancellation by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/Lifetime/AuthSubmitLifetimeTests.cs, and the form models by LoginModel. 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; summary ConfirmEmail.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 as ConfirmationService, :90), CapabilitiesJsModule (the optional JS interop module that takes the URL fragment, resolved through IServiceProvider at :221), EmailedLinkReader (:172, :176, :180, :234), AuthErrorCodes.EmailConfirmationPasswordRequired (:266), ConfirmEmailRequest (:329-331), Result and its LocalizedErrorMessage extension (:275, :294-295), SharedResource (as IStringLocalizer<SharedResource>, :96), ComponentLifetimeExtensions.LifetimeToken (:259, :337, :379), the private nested ConfirmationState (:67-80); externals: [SupplyParameterFromQuery], [Inject], NavigationManager and its LocationChanged event, LocationChangedEventArgs (Microsoft.AspNetCore.Components.Routing), BCL IDisposable, 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 and Referer headers, and locationHashTake scrubs 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: on AuthErrorCodes.EmailConfirmationPasswordRequired the 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 (_cts through _newPassword, :51-64, including _locationHandlerRegistered, _claimWithNewPassword, _currentPassword and _newPassword), and two query-bindable properties (EmailFromQuery, :83-84; TokenFromQuery, :87-88).
    • Dispose() (:99-114): idempotent through _disposed; unsubscribes from Navigation.LocationChanged when it was registered (:107-110), then cancels and disposes _cts.
    • OnInitialized() (:122-126): subscribes to Navigation.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/_token from 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 calls RedeemOrShowFormAsync (: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 through InvokeAsync.
    • RedeemNewLinkAsync(link) (:189-200): does nothing once disposed or when the link carries no recognized pair (:191-194); otherwise clears _linkSent and _errorMessage, returns to Working (:196-198) and redeems as a fresh tab does (:199).
    • RedeemOrShowFormAsync() (:202-214): with the address or the token blank it goes straight to Form and re-renders without posting (:204-211); otherwise it calls ConfirmAsync (:213).
    • TakeFragmentAsync() (:216-226): resolves CapabilitiesJsModule from Services and calls locationHashTake, returning null when the module is absent (SSR prerender, a component test, a host without the capabilities module, comment :218-220).
    • ApplyFragment(fragment, replace) (:232-238): delegates to EmailedLinkReader.MergeLinkFragment (:234) and returns whether a pair was recognized.
    • ConfirmAsync() (:240-292): with either value blank it shows Auth.Confirm.EmailAndTokenRequired in Form (:245-250). Otherwise it sets _isBusy and re-renders (:252-255), posts ConfirmEmailAsync(_email.Trim(), _token.Trim(), _cts.LifetimeToken()) (:259), and moves to Confirmed on success (:260-264), to PasswordProof through ShowPasswordProof on the password-required code (:266-270), or to Form with the API's own wording or Auth.Confirm.GenericError on any other refusal, which the server collapses into one indistinguishable error (:272-276). A cancellation is swallowed as expected during disposal or an InteractiveAuto transition (:278-281), and the finally re-renders unless disposed (:282-291).
    • HasErrorCode(result, code) (:294-295): an ordinal match over result.Errors.
    • ShowPasswordProof() (:297-304): clears the message, resets the toggle to "current password" and empties both password fields, then sets PasswordProof.
    • 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 shows Auth.Field.Password.Required (:322-327). It builds a ConfirmEmailRequest carrying NewPassword or CurrentPassword by the toggle (:329-331) and posts it through ConfirmEmailWithPasswordAsync (:337). Success clears both password fields and moves to Confirmed (:338-344). A refusal sets the API's message (:346); only the invalid-token code clears the passwords and returns to Form for 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 shows Auth.Confirm.EmailRequired (:369-373); otherwise it calls ResendEmailConfirmationAsync(_email.Trim(), _cts.LifetimeToken()) (:379) and sets _linkSent on 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 the ForgotPasswordModel flow 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 Form state keeps _state purely about which panel renders, while _errorMessage and _linkSent carry 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 that IEmailConfirmationUIService ultimately 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 shared MMCA.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 _model field the markup declares), RegistrationSettings (read through RegistrationOptions.Value.CollectAddress, Register.razor.cs:33, injected at MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Register.razor:18), and the first-party Address value object plus Result (Register.razor.cs:88, :67); BCL IDisposable and CancellationTokenSource.
  • 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) returns Result<Address>? with three outcomes. With address collection off (CollectAddress, :20) it returns null, because there is no block to type into (:52-55). With collection on and all six fields blank (:57-65) it also returns null: no address is legitimate. Otherwise it calls Address.Create(...) (:67) and returns that Result, 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.
    • _cts and _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 an InteractiveAuto render-mode transition tears the page down, stops instead of completing into a component that is gone. The markup passes _cts.LifetimeToken() (see ComponentLifetimeExtensions) to AuthService.RegisterAsync (Register.razor:256).
    • CollectAddress (:20).
    • Dispose() (:22-27) and Dispose(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 a RegisterRequest (Register.razor:248-256), as described under RegisterModel.
  • Why it's built this way: returning a nullable Result rather than a bare Address? is what lets "nothing entered" (null) stay distinct from "entered and invalid" (a failed Result), which a plain null could not express. The lifetime pair is the same shape as Login, so both auth pages stop cleanly on teardown.
  • Where it's used: bound by Register.razor; behavior is covered by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/RegisterFormTests.cs, RegisterAddressOptionTests.cs and RegisterTermsTests.cs in the same folder, and the in-flight cancellation by MMCA.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.

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 as SignInLinks, :77), SignInSettings (as SignInOptions, :81, for SignInLinkLandingPath), LegalSettings (as LegalOptions, :83), CapabilitiesJsModule (resolved optionally, :211), EmailedLinkReader (:227), ReturnUrlProtector (:251), SharedResource as IStringLocalizer<SharedResource> (:87), Result and its LocalizedErrorMessage extension (:292), ComponentLifetimeExtensions.LifetimeToken (:246, :285), the private nested LinkState (:65-75), and the framework's ExternalLink component (:200); externals: [Inject], NavigationManager and its LocationChanged event, LocationChangedEventArgs (Microsoft.AspNetCore.Components.Routing), RenderFragment, IOptions<T>, MudBlazor Underline, BCL IDisposable, 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 on ConfirmEmail: a browser never sends a fragment to a server, so the live token stays out of access logs, telemetry and Referer headers, and locationHashTake scrubs 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 in LinkState.Ready and 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 at LinkState.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 in LegalSettings, the same rule the register page uses (comment, :91).
    • Dispose() (:95-106): idempotent through _disposed; unsubscribes from Navigation.LocationChanged (:103), then cancels and disposes _cts.
    • OnInitialized() (:109-113): records _ownPath from the current URI's absolute path and subscribes to Navigation.LocationChanged.
    • OnAfterRenderAsync(firstRender) (:116-126): runs once (_attempted, :118-123), passes the taken fragment to ShowLink (: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 marshals ShowNewLinkAsync with the fragment minus its hash onto the renderer through InvokeAsync (:143). Before the first read the pending OnAfterRenderAsync picks 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 calls TakeFragmentAsync only 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 through ShowLink (:165).
    • ShowLink(fragment) (:174-188, summary :169-173): parses the fragment into _email and _token (:176) and moves to Failed with Auth.SignInLink.Incomplete when either is missing (:178-182), otherwise clears any earlier message and moves to Ready (:183-187).
    • LegalDocument(url, name) (:192-205): renders a document name in the consent sentence as an ExternalLink when the host published that document, plain text when it did not; the markup shows the sentence only when RequiresTerms holds (SignInLink.razor:31-41).
    • TakeFragmentAsync() (:207-216): resolves CapabilitiesJsModule from Services and calls locationHashTake, returning null when 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 calling EmailedLinkReader.MergeLinkFragment(fragment, replace: true, email: null, token: null) (:227). It goes through the same emailed-link parser EmailedLinkReader the 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 calls RedeemSignInLinkAsync(_email.Trim(), token, RequiresTerms, _cts.LifetimeToken()) (:246), so the tap carries the Terms acceptance. On success it does a full-load navigation to the sanitized SignInLinkLandingPath, 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 from RefusalMessage and moves to Failed (:256-258). A cancellation is swallowed as expected during disposal or an InteractiveAuto transition (:260-263).
    • RequestNewLinkAsync() (:270-302): an empty address shows Auth.Confirm.EmailRequired (:275-279); otherwise it calls RequestSignInLinkAsync(_email.Trim(), _cts.LifetimeToken()) (:285) and sets _linkSent on success, or shows the localized error or Auth.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 generic Auth.SignInLink.GenericError (:321). The raw code is never rendered, the same rule as Login.
  • 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 Failed panel 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-link in any host that maps the framework's Auth pages; the emailed link is composed server-side by MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/SendSignInLinkHandlerBase.cs. The Login page requests the same links from its "email me a link" button. Covered by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/SignInLinks/SignInLinkPageTests.cs and the shared conformance base MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Pages/SignInLinkPageTestsBase.cs; MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Api/AnonymousEndpointTests.cs also references it. Shell composition is ADR-067.
  • Caveats / not-in-source: the markup half was read only for the cited lines. Whether ISignInLinkUIService is 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), SharedResource as IStringLocalizer<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), UserAgentSummary and DeviceMetadata (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's BreadcrumbItem / 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 _revokingSessionId doubles as the per-row spinner selector (Sessions.razor:84). Both revoke handlers check IsBusy twice, 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 _loadResult that carries the last load outcome for inline rendering (line 46), _signIns and the nullable _signInsResult for the history, null while its read is in flight (lines 48-51), _revokingSessionId, IsLoading (line 59), IsBusy (line 65), and IsRevokingAll (line 68). LoginRoute is a const (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, awaits ViewerTime.EnsureResolvedAsync(_cts.LifetimeToken()) and calls StateHasChanged when 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. See ViewerTimeZone.
    • LoadSessionsAsync (lines 93-122): stores the whole Result in _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 at Sessions.razor:15-16 explains why: an empty table and a failed load look identical once a toast expires). On failure it empties _sessions deliberately (lines 107-112), so a stale device list can never be left on screen for a user to act on. OperationCanceledException is swallowed as expected-on-disposal (lines 114-117) and IsLoading clears in the finally.
    • LoadSignInsAsync (lines 128-140, doc comment lines 124-127): reads IAuthUIService.GetSignInsAsync (line 132, contract at MMCA.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 _signInsResult is null, the failure in place of the table, or the rows through SignInHistoryTable (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 through IAppDialogService.ConfirmAsync with a message naming the device via DescribeDevice (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 calls StateHasChanged (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 answers Auth.SessionAlreadyRevoked after 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 through result.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 on IsBusy (line 218), confirms through ConfirmAsync (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 runs IAuthUIService.RevokeAllSessionsAsync (contract at MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/IAuthUIService.cs:98), the account-wide revoke followed, on success, by the local sign-out, through SignOutNavigator.SignOutAsync(signOut, LoginRoute) (line 246; the internal overload at MMCA.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 into RedirectToLogin, 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 through result.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. OperationCanceledException is swallowed as expected-on-disposal (lines 252-255) and IsRevokingAll clears in the finally (lines 256-259).
    • DescribeDevice(session) (line 267, doc comment lines 262-266): a one-line delegate to UserAgentSummary.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 (Parse is at UserAgentSummary.cs:86). [Rubric §27, Internationalization]. The same label feeds the per-row confirmation message and aria-label.
    • FormatInstant(DateTime) (line 274, doc comment lines 269-273): delegates to ViewerTime.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.ToLocalTime would 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.
  • 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 reasoning DataGridListPageBase<TDto> encodes in its LoadFailed flag. 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/sessions behind [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 RevokeAllSessionsAsync completes the local sign-out when the server call succeeds but token clearing fails is a property of IAuthUIService, not of this file; any exception other than OperationCanceledException still propagates out of both handlers with no toast (SignOutNavigator releases its claim and rethrows, SignOutNavigator.cs:79-83). LoadSignInsAsync has no IsLoading-style flag of its own; the null _signInsResult is its in-flight signal. The accessibility markers the page relies on (the text-variant "this device" chip at Sessions.razor:58-59, chosen so the marker does not depend on color alone, and the per-button aria-labels at :83 and :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 inside OfflineFirstPageSnapshot<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, whose SetAsync/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 a private sealed record inside 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 by RememberAsync, 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 by TryReadAsync as store.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 record gives value semantics and a positional constructor for free, which is all a serialization payload needs; List<TItem> rather than IReadOnlyList<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 by MMCA.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) and string.Format with CultureInfo.CurrentCulture (BCL). No first-party types at all. The localizer it is handed is an IStringLocalizer<SharedResource> (doc comment, ErrorMessages.cs:32), so it shares the SharedResource .resx keys.
  • 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 is static, so any page can call ErrorMessages.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 private Localize(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 a Result and is rendered by ResultUiExtensions (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's Message is 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 nullable IStringLocalizer?, 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 _localizer is set and the lookup's ResourceNotFound is false it returns localized.Value (lines 37-44); otherwise string.Format(CultureInfo.CurrentCulture, fallbackFormat, args) (line 46).
    • LoadError/SaveError/DeleteError (lines 56-57, 60-61, 64-65), the three CRUD failure paths, keyed Common.Error.Load/Save/Delete. Each passes the entity name and ex.Message as 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, key Common.Error.DeleteFailed), the "the call returned but the delete did not happen" case, distinct from DeleteError, which carries an exception.
    • NotFound(string entityName, object id) (lines 70-71, key Common.Error.NotFound), interpolating the entity name and the missing id.
    • ValidationError (lines 73-74, key Common.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 Configure indirection adds localization without a signature change anywhere. The uniform "template only" answer is what makes the class safe to call from any catch: 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 by DataGridListPageBase<TDto> on the two non-Result failure paths (DataGridListPageBase.cs:1497 paged, :665 virtualized, :767 mobile), by NotificationSend (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Notifications/NotificationSend.razor.cs:127), and by the Store entity pages for NotFound and ValidationError (for example MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.UI/Pages/Products/ProductDetail.razor.cs:86 and :200).
  • Caveats / not-in-source: the .resx payloads (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 a DomainInvariantViolationException gets 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 interactive ServerData call can answer instantly instead of re-hitting the API.
  • Depends on: Microsoft.AspNetCore.Components.PersistentComponentState (the Blazor mechanism that serializes it). Nested privately inside DataGridListPageBase<TDto>.
  • Concept introduced, PersistentComponentState to 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's PersistentComponentState serializes chosen data into the pre-rendered HTML and rehydrates it in the interactive circuit; PersistedGridState is 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 in OnInitialized writes new PersistedGridState([.. _lastSuccessfulGridData.Items], _lastSuccessfulGridData.TotalItems) (line 189) under the key grid:{GetType().FullName} (built at line 171), and only when a successful fetch has actually happened (line 187). On the restoring side, the synchronous OnInitialized calls ApplicationState.TryTakeFromJson<PersistedGridState>(persistKey, out var restored) (line 172) and, when present, rebuilds a GridData<TDto> into _persistedGridData (line 174) that the first LoadServerDataAsync returns directly (lines 513-522).
  • Why it's built this way: private because the persistence is purely an implementation detail of the base class; a sealed record for JSON friendliness and value semantics; the items are materialized into a fresh List<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 synchronous OnInitialized, 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 ComponentBase that owns one page-scoped CancellationTokenSource, exposes its token as PageToken, and carries the dispose pattern around it (class CancellablePageBase : ComponentBase, IDisposable, line 16). The class summary (lines 6-11) names its two derivations, DetailPageBase and CreatePageBase, so every page base shares one cancellation contract instead of repeating the source and its dispose method (ADR-146).
  • Depends on: Microsoft.AspNetCore.Components.ComponentBase and IDisposable, plus ComponentLifetimeExtensions for LifetimeToken(). 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. Under InteractiveAuto a 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). Handing PageToken to 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 _cts created at construction and a _disposed idempotency flag, both private, 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 normal OperationCanceledException path.
    • Dispose() (lines 30-34): the public entry point, delegating to Dispose(true) and calling GC.SuppressFinalize(this).
    • Dispose(bool) (lines 41-55): protected virtual, returning at once when _disposed is set; when disposing it 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.
  • 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) and CreatePageBase (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/CreatePageBase.cs:21), and exercised through both by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/CreatePageBaseTests.cs and DetailPageBaseTests.cs beside 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 a sealed record with three init properties (line 8), so a create page that needs none of them passes nothing.
  • Depends on: Microsoft.Extensions.Localization.IStringLocalizer only.
  • 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; null lets it continue.
    • ToastOnFailure (line 20): bool, defaulting to true. A page that shows a failed save some other way passes false.
    • Localizer (line 26): IStringLocalizer?, passed to NotifyOnFailure (ResultUiExtensions) so the failure toast resolves each error message through it; null shows 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 of SubmitAsync.
  • 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 example MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Events/EventCreate.razor.cs, SessionCreate.razor.cs, SpeakerCreate.razor.cs and RoomCreate.razor.cs. Covered by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/CreatePageBaseTests.cs.
  • Caveats / not-in-source: what each ADC page puts in its PreCheck is 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) and Enabled (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 _state field (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: Loading while the status is read, LoadFailed when it could not be read (a retry is offered), NotEnrolled when the second factor is off (setting it up is offered), Enrolling while the new secret is shown and a code is asked for, RecoveryCodes while a new set of codes is shown once, and Enabled when the second factor is on.
  • Why it's built this way: private because 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) and DisableAsync (:263) set it.
  • Caveats / not-in-source: which markup each state renders lives in TwoFactorAccount.razor, not verifiable from the .cs file.

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: ILocalCacheStore and IConnectivityStatusService, both taken through the primary constructor along with a string cacheKey and an optional string? userScope = null (lines 29-33), plus the private nested CachedPage payload. 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 because ILocalCacheStore reports itself unavailable there. The class comment states exactly that contract.
  • Walkthrough: three public members over a primary constructor, plus a computed field.
    • The _scopedKey field (lines 35-37): string.IsNullOrWhiteSpace(userScope) ? cacheKey : $"{cacheKey}.u{userScope}", computed once at construction and used by every store call in place of the bare cacheKey.
    • 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 when page == 1 && store.IsAvailable (line 54), materializing a CachedPage and handing it to store.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): returns null immediately unless CanServe(page) (lines 71-74), then reads store.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.
  • Why it's built this way: it is a plain class constructed by the consuming service rather than a DI-registered singleton, because the cacheKey is 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. The userScope parameter 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 _scopedKey is the defense in depth for the paths that never reach sign-out, an app killed mid-session or a token that simply expired. Returning null rather 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: RememberAsync on every success (:42), a snapshot read when the live query returns a failed Result (:49-50), and CanServe as the exception filter on the guarded catch (:52-59) so a throw from the store itself is rethrown when there is nothing cached to answer with. Behavior is pinned by MMCA.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 ILocalCacheStore and of the head's storage, not of this file. The class is best-effort by design: a store write failure inside RememberAsync is 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 called AddTwoFactorUI(): 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 responses TwoFactorStatusResponse, TwoFactorSetupResponse and TwoFactorRecoveryCodesResponse, its private TwoFactorPageState, and the child panels TwoFactorEnrollmentPanel and RecoveryCodesPanel. Externals: AuthenticationState, MudBlazor's BreadcrumbItem.
  • 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 its Result, the transient _setup and _codes, _codesFromEnrollment, the action code and error, _recentSignInRequired, _hasMultiFactor, _isBusy and _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 cascading AuthState (line 86); five injected services (lines 88-96).
    • Dispose (lines 99-117): Dispose() delegates to a protected virtual Dispose(bool) that cancels and disposes _cts once.
    • OnInitializedAsync (lines 120-135): builds the localized breadcrumbs (in the method, not a field initializer, so the injected localizer is available), reads HasMultiFactor() from the user (line 131), then LoadStatusAsync (line 137), which sets Enabled or NotEnrolled from the status, or LoadFailed.
    • Enrollment: BeginAsync (line 162) calls BeginEnrollmentAsync and moves to Enrolling. The panel's callbacks land in OnEnrollmentConfirmed (line 191, dropping the secret before the codes are shown), OnEnrollmentCancelled (line 200) and OnRecentSignInRequired (line 206). OnCodesSavedAsync (line 217) then either signs out and back in after an enrollment, with LoginRefusals.TwoFactorEnabledReason, or re-reads the status after a regeneration.
    • Code-proved actions: RegenerateAsync (line 229) and DisableAsync (line 260) both take the trimmed code from ActionCode() (line 339) and claim the busy flag through TryStartAction() (line 324). Disable first asks a destructive confirm through IAppDialogService.ConfirmAsync (lines 269-274). A refusal goes through ShowRefusal (line 353): a refusal carrying AuthErrorCodes.TwoFactorRecentSignInRequired (line 355; the shared code at MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthErrorCodes.cs:66) shows the sign-in-again notice, any other shows LoginRefusals.Describe(...).
    • Sign out and back in: SignInAgainAsync (line 302) and SignOutAndSignInAgainAsync (lines 310-320) build /login?reason=..., append a returnUrl only when ReturnUrlProtector.Sanitize (line 313) yields something other than /, and hand the target to SignOutNavigator.SignOutAsync (line 319), which calls LogoutAsync and then navigates with forceLoad: 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 into RedirectToLogin, whose own /login?returnUrl=... navigation dropped the notice.
  • 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 SignOutNavigator keeps 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 by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Auth/TwoFactor/TwoFactorAccountTestsBase.cs and TwoFactorAccountEnabledTests.cs, and by TwoFactorPageGateTests.cs, TwoFactorRoutesTests.cs and TwoFactorPageAuthorizationTests.cs under MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/TwoFactor/.
  • Caveats / not-in-source: the page's markup (TwoFactorAccount.razor), including the route directive and how Required, _hasMultiFactor and _recentSignInRequired render, is not verifiable from the .cs file; the route is taken from the class summary. How AddTwoFactorUI() 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 TwoFactorAccount for the RecoveryCodes state (ADR-116).
  • Depends on: IToastService, IClipboardService (resolved at the click, not injected), IServiceProvider, and IStringLocalizer<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 _saved check, and a _focused one-shot flag.
    • Parameters: Codes (line 24, [EditorRequired], in the order the API issued them), ContinueText (line 28, defaulting to the localized "Continue"), and the OnContinue callback (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): resolves IClipboardService through Services.GetService at 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 toasts Auth.TwoFactor.RecoveryCodes.Copied on success (line 64) or Auth.TwoFactor.GenericError when the clipboard is missing or the copy failed (line 68).
  • Why it's built this way: GetService rather 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 TwoFactorAccount in its markup for both a first enrollment and a regeneration (the page sets _codes at TwoFactorAccount.razor.cs:195 and :245).
  • Caveats / not-in-source: how _saved gates the continue button, and where ContinueText is shown, are markup in RecoveryCodesPanel.razor, not verifiable from the .cs file.

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 failed Result for 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 of PageToken), IToastService, CreateSubmitOptions, ErrorMessages (ValidationError), ResultUiExtensions (NotifyOnFailure), and Result / Result<T>. External: MudBlazor's MudForm.
  • 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", feed SaveResult to <ErrorSummary>, read IsDirty in the unsaved-changes guard, call MarkDirty from each field's @bind-Value:after, and put the success toast and navigation in the onCreated callback.
  • Walkthrough:
    • Surface (lines 24-39): the injected Toast (line 24, protected), the Form ref (line 27), and three protected properties with private set: IsSaving (line 30), IsDirty (line 33) and SaveResult (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 returns false when Form is unbound or a save is already in flight (line 61), which is the double-submit guard. It defaults options (line 66), clears SaveResult (line 67) and validates (line 68); an invalid form toasts ErrorMessages.ValidationError as a warning and stops (lines 69-73). A non-null PreCheck message toasts as a warning and stops (lines 75-80).
    • The save (lines 82-109): sets IsSaving, awaits saveAsync(PageToken) (line 85), and on success clears SaveResult and IsDirty before calling onCreated (lines 86-92), so the navigation in that callback is not stopped by the unsaved-changes guard. On failure it keeps the result in SaveResult (line 94) and, when ToastOnFailure, calls result.NotifyOnFailure(Toast, options.Localizer) (lines 95-98). An OperationCanceledException returns false (line 102), and the finally always clears IsSaving (lines 106-109). The return value is true only when the save succeeded and onCreated ran.
  • Why it's built this way: the order inside SubmitAsync is the part each page used to get subtly wrong (the dirty flag cleared after navigation, a missing finally, 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 CreateSubmitOptions to it (for example MMCA.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 by MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Ui/FormsConventionTestsBaseTests.cs. Behavior is covered by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/CreatePageBaseTests.cs.
  • Caveats / not-in-source: whether a given ADC create page inherits through @inherits in its .razor or in its code-behind is not visible from the usage scan; ErrorSummary is a Razor component, so what it renders from SaveResult is not verifiable here. An exception other than OperationCanceledException from saveAsync or onCreated propagates to the page after IsSaving is 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 LatestLoadGuard for route-driven reloads, the load outcome (LoadState, set through BeginLoad / CompleteLoad), and the inline edit-mode lifecycle (IsEditing / IsDirty plus 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 sibling LatestLoadGuard it exposes through LoadGuard (line 34), DetailLoadState (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/PageState/DetailLoadState.cs:8, values Loading, Loaded, NotFound, Failed), Result, and ResultUiExtensions.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 inherited PageToken is handed to every awaited call the page makes outside the guarded load (class remarks, lines 17-20), so navigating away, or an InteractiveAuto render-mode transition swapping the component out, cancels the in-flight work. LoadGuard (line 34) is the companion for the route-driven load itself, and BeginLoad / CompleteLoad wrap 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 on LoadState, lines 36-40). [Rubric §24, Forms, Validation & UX Safety] applies to that split and to the dirty flag.
  • Walkthrough:
    • LoadGuard (line 34): a protected LatestLoadGuard property, disposed with the page. Begin() at the start of each load cancels the load it supersedes, and IsCurrent(generation) after each await tells a stale response to leave the page state alone.
    • LoadState (line 41): protected with private set, starting at DetailLoadState.Loading. A page renders DetailLoadStateContent for every state but Loaded.
    • BeginLoad() (lines 48-53): calls LoadGuard.Begin(), puts LoadState back to Loading, and returns the (CancellationToken Token, int Generation) pair the load passes to its awaited calls and completes with.
    • CompleteLoad(generation, result) (lines 67-84): returns false without touching anything when LoadGuard.IsCurrent(generation) is false (a newer load superseded it); otherwise sets LoadState to Loaded and returns true on success, or to NotFound when result.IsNotFound() and Failed for every other failure, returning false. A true return is the page's permission to adopt the value.
    • IsEditing / IsDirty (lines 87, 90): both protected with private 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) and EndEdit() (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; when disposing it disposes LoadGuard (idempotent, so a second dispose stays a no-op) and then calls base.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 IsDirty directly 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 the Result's error type, instead of each page collapsing both into one empty body. The cancellation source moved down into CancellablePageBase so this base and CreatePageBase share one copy of it (ADR-146). Adding a new detail page costs an @inherits line and a BeginLoad / CompleteLoad pair.
  • Where it's used: MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/DetailPageBaseTests.cs, the conformance probe MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/Conformance/ProbeDetailPage.cs driven by the packaged DetailPageLoadStateTestsBase (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) and PublicSessionDetail (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: DetailLoadStateContent is 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 .cs file. Whether a given page inherits this base through an @inherits directive in .razor markup 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 the DeleteConfirmation dialog 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 on DataGridListPageBase<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 as ReloadActiveLayoutAsync (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's DeleteConfirmation ref, the entity display name, a Func<Task<Result>> delete call, the toast service, a localized success message, a Func<Result, string> error mapper, and a reload callback. It guards every reference argument with ArgumentNullException.ThrowIfNull (lines 41-45), shows the dialog, and returns immediately when it answers false (lines 47-50): DeleteConfirmation.ShowAsync returns a plain Task<bool> (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/DeleteConfirmation.razor:24), and Escape backs out with false (the component comment at line 6), so a dismissal is a cancel, not a confirm. On confirm it awaits the delete and branches on the Result (lines 54-59): a failure toasts the mapped error and returns without reloading, a success toasts and awaits reloadAsync (lines 61-62). The single catch (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 errorMessage delegate is what lets a page choose between a fixed sentence and the API's own wording via result.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 pages ActivityList, ConferenceCategoryList, EventList, PartnerList, QuestionList, RoomList, SessionList, SpeakerList and SponsorList (under MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/). Covered by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/ListPageActionsTests.cs.
  • Caveats / not-in-source: DeleteWithConfirmationAsync catches only OperationCanceledException; any other throw from the caller's deleteAsync or reloadAsync delegate 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 declaration public 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 (as IStringLocalizer<SharedResource>), ListPageState and its ColumnFilterState entries, ListPageStateService, ListPageQueryStateService, BreakpointConstants, ErrorMessages, ResultUiExtensions (NotifyOnFailure), ComponentLifetimeExtensions (LifetimeToken), MobileInfiniteScrollList<TItem>, IListLayoutSource (implemented explicitly), QueryFilterKeys (Alias, SearchTag), Result, and the nested PersistedGridState. Externals: MudBlazor's MudDataGrid<T>, GridState<T>, GridStateVirtualize<T>, GridData<T>, FilterDefinition<T>, IBrowserViewportObserver / IBrowserViewportService, and Blazor's PersistentComponentState, 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 every Result failure message resolve through SharedResource. [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, and EmptyConfirmed (lines 66-68), true only when the NEWEST load completed with TotalItems == 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.cs unless the column-filter file is named):
    • Abstract and virtual surface: derived pages supply the abstract Title (line 72) and may override SaveFilters / 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 knobs VirtualizeGrid (line 227, default false), VirtualizedGridHeight (line 235, default 70vh) and VirtualizedItemSize (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 explicit IListLayoutSource member at line 90), the mobile card-view block MobileItems / MobileTotalItems / MobileCurrentPage / MobilePageSize (lines 93-96), the bindable CurrentPageState (line 103, 0-indexed), RowsPerPageState (line 113, defaulting to 10 to match MudDataGrid v9's own default), and DenseGrid (line 122). IsLoading is computed as field || !RendererInfo.IsInteractive (line 44): always true during the non-interactive SSR prerender pass, because the grid fetches from OnAfterRenderAsync, which a static render never reaches. EmptyConfirmed is its mirror image, field && RendererInfo.IsInteractive (line 68). IsLayoutKnown stays false until the first viewport notification sets IsMobile: 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), so ListPageShell<TItem> renders a viewport-high placeholder and fetches nothing until it is true.
    • Constants (lines 128, 132): PrerenderFetchTimeoutMs = 5000 bounds the SSR fetch, and VirtualizedScrollContainerSelector = ".mud-table-container" records where a virtualized grid actually scrolls.
    • Private fields (lines 134-182): the nullable CTS, the _disposed guard, the scroll module and its DotNetObjectReference, 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 / _setupWaitsForLayoutRender pair 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's Id and ResizeOptions (a 250 ms report rate) sit at lines 185 and 188.
    • OnInitialized (from line 252), synchronously: restores any PersistedGridState under the key grid:{GetType().FullName} (line 258); registers the persisting callback with an explicit RenderMode.InteractiveAuto (line 284); pins _ownRoutePath to this page's route (line 291); reads the URL through ListPageQueryStateService, falling back to the in-memory ListPageStateService snapshot; primes the pager, sort, density and page filters, and takes the restored column filters (RestoreColumnFilters, line 317) so the grid's first ServerData call 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 (an Ordinal path compare, line 357), re-reads the URL (including column filters, line 380), and hands off to ReloadActiveLayoutAfterNavigationAsync (line 401): on a phone with a card list it reloads the way a filter change does, through ReloadActiveLayoutAsync; 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): recomputes IsMobile from BreakpointConstants and, on the first notification, sets IsLayoutKnown (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) awaits RunFirstRenderSetupAsync (line 554) on the first render and OnLaterRenderAsync (line 532) after that. The setup subscribes to the viewport first (SubscribeToViewportAsync, line 679), because that first notification picks the layout a ListPageShell holds back; when the notification queued a layout render, the setup parks (_setupWaitsForLayoutRender, line 571) and OnLaterRenderAsync resumes it once the grid or card list has mounted. ContinueFirstRenderSetupAsync (line 582) then hydrates session state (ApplyHydratedStateAsync, line 638), checks _disposed after each interop round trip, starts scroll tracking (StartScrollTrackingAsync, line 695, importing ./_content/MMCA.Common.UI/list-page-scroll.js at line 701), restores the grid state and awaits OnRestoredStateAppliedAsync. OnLaterRenderAsync also puts the saved pager and sort on a grid that has just been created when _restoreGridWhenRendered is set. ReleaseLateFirstRenderSetupAsync (line 763) and ReleaseScrollTrackingAsync (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 v9 RowsPerPage setter that resets CurrentPage. ApplyRestoredState (line 882) feeds the column filters too (line 895). RestoreGridStateAsync (line 905) is the single entry point for the pager-restore machinery, then ApplyRestoredSortOrReloadAsync (line 955) puts the restored column filters on the grid (line 964) and the restored sort through RestoreSort (line 974) and ApplyRestoredSortToGridAsync (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=desc link 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 (URL c: keys, in-memory state and sessionStorage) 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, the restorePendingAtLoadStart parameter) it builds the restored definitions against the rendered grid, otherwise it uses the grid's own. ApplyRestoredColumnFiltersToGrid (line 75) replaces the grid's FilterDefinitions directly rather than through AddFilterAsync, so the filter panel stays closed and no load starts. SnapshotColumnFilters (line 92) writes values in the invariant culture through FormatFilterValue, and BuildColumnFilterDefinitions drops a saved filter whose column the grid does not render or allow filtering on, or whose value no longer parses (TryParseFilterValue and TryParseDateOrNumber: string, bool, enum, Guid, DateOnly, DateTime round-trip, then numbers through Convert.ChangeType).
    • Paged loads: LoadServerDataAsync (line 1051, remarks at lines 1041-1050) starts LoadPagedAsync (line 1137), records it in _newestPagedLoad before anything yields, and returns NewestPagedResultAsync (line 1187), so overlapping calls end on the NEWEST call's rows, never a superseded call's empty cancelled page (MudDataGrid applies whichever ServerData call completes last). FetchPagedAsync (line 1204) holds the fetch, awaiting OnBeforeFetchAsync and sending the resolved column filters; FetchWithinRangeAsync (line 1265) fetches the last page instead when the requested page lies past the end, and MovePagerToRows / MovePagerTo (lines 1307, 1321) put the pager on the page the returned rows belong to.
    • OnBeforeFetchAsync (line 1077): a protected virtual hook awaited by every loader and by every delegate MobilePageFetcher builds, 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 the FetchPageResult delegate a MobileInfiniteScrollList<TItem> takes, so one fetch method serves the grid and the phone list. It applies an optional default sort and an optional afterFetchAsync step, and returns the Result unchanged (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 through ComputeVirtualWindow (line 1538, internal static so the tests drive it directly). LoadMobileDataAsync (line 1577) is the card-list equivalent, with ClearMobileItems (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 the try so a throw from page code cannot strand IsLoading, and toasts the localized Grid.Snackbar.LoadCancelled (line 1481) only for a current, undisposed load. FailedFetch<TResult> (line 1516) is the Result-branch counterpart, and EmptyGridData (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) is ReferenceEquals(loadSource, _cts), and ThrowIfSuperseded (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 through EffectiveColumnFilters (line 1715); ApplyAdditionalFilters (line 1733) runs the page's callback without letting it overwrite a grid key, moving a clashing value to QueryFilterKeys.Alias(key, QueryFilterKeys.SearchTag). ExtractSortParameters (line 1757) and ResolveSortParameters (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, and ReloadActiveLayoutAsync(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 reloads GridRef. ToggleDensity / PersistDensity (lines 1895, 1916) and ResolvePagerState (line 1907) complete the persistence.
    • Route pinning, leaving and teardown: _ownRoutePath (line 1939), GetRoutePath() (line 1941) and IsOwnRouteCurrent() (line 1967, false once _navigatingAway is set, line 1968, then an OrdinalIgnoreCase compare at line 1969) drop a stale write after navigation. NavigateAway(uri, forceLoad, replace) (line 1987) is what a derived page calls instead of NavigationManager.NavigateTo when 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) and Dispose (line 2057) release the subscription, the scroll module and the CTS, _disposed-idempotent. PersistedGridState closes the file at line 2067.
  • 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 mirrors IEntityService<TEntityDTO, TIdentifierType>.GetPagedAsync exactly (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 from ListPageActions because 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 PublicSessionListView and PublicSessionList (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Public/Sessions/), ADC's EventFilteredListPageBase (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Common/EventFilteredListPageBase.cs), and Engagement's AttendeeSearchPanel (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Pages/CheckIns/AttendeeSearchPanel.razor.cs); Common's ListPageShell and InfiniteScrollSentinel (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Lists/) reference it. Covered by bUnit tests at MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/Common/DataGridListPageBaseTests.cs and, beside it, DataGridListPageBaseLifecycleTests.cs, DataGridListPageBaseFilterStateTests.cs and DataGridListPageBaseMobileFetchTests.cs, plus the conformance probe Conformance/ProbeListPage.cs.
  • Caveats / not-in-source: three BL0005-related members set grid.CurrentPage from 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. The list-page-scroll.js module and ListNoRecordsContent are referenced here only by name, so their behavior is not verifiable from these .cs files. The route comparison is Ordinal in OnLocationChanged (line 357) but OrdinalIgnoreCase in IsOwnRouteCurrent (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 Enrolling state of TwoFactorAccount: 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), TwoFactorSetupResponse and TwoFactorRecoveryCodesResponse, ComponentLifetimeExtensions, and IStringLocalizer<SharedResource>. External: MudBlazor's MudTextField<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, _focused and _disposed flags.
    • Parameters: Setup (line 31, [EditorRequired]), and the callbacks OnConfirmed (line 35, carrying the recovery codes), OnCancelled (line 39) and OnRecentSignInRequired (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 sets Auth.Login.SecondFactor.CodeRequired and stops (lines 86-90); otherwise it calls ConfirmEnrollmentAsync(code, _cts.LifetimeToken()) (line 95). Success raises OnConfirmed with the codes (line 98); a refusal carrying the shared AuthErrorCodes.TwoFactorRecentSignInRequired code (line 102) raises OnRecentSignInRequired (line 104); any other failure clears the code and shows LoginRefusals.Describe(...) with Auth.TwoFactor.GenericError as the fallback (line 109). A cancellation is swallowed only when (_disposed) (line 111), and the finally clears _isBusy (line 117).
  • Why it's built this way: keeping the confirm call in the panel and the state machine in the page means the page's TwoFactorPageState transitions 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 in OnEnrollmentConfirmed, OnEnrollmentCancelled and OnRecentSignInRequired (TwoFactorAccount.razor.cs:191, :200, :206).
  • Caveats / not-in-source: how the QR code and GroupedKey render, and how _isBusy disables the form, are markup in TwoFactorEnrollmentPanel.razor, not verifiable from the .cs file.

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 .resx resource 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 own LanguageResource keys (v9.6.0) with the English values copied verbatim so en-US behavior is unchanged, and from ResxMudLocalizer, which injects IStringLocalizer<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's IStringLocalizer<T> resolves keys against the .resx whose base name matches T, so a dedicated empty class becomes the name of a shared string table. MudTranslations is 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 an es UI 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 MudTranslations in this namespace, with sibling .resx files whose keys match MudBlazor's LanguageResource". 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 own SharedResource chrome. This is the ADR-027 way to translate a dependency you do not own.
  • Where it's used: injected as IStringLocalizer<MudTranslations> by ResxMudLocalizer, which AddUIShared registers as MudBlazor's MudLocalizer via TryAddTransient (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:130). Because resolution flows through the DI IStringLocalizerFactory, the PseudoStringLocalizerFactory decorator registered at MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:124 reaches these strings too.
  • Caveats / not-in-source: the .resx files and their per-key match to MudBlazor v9.6.0's LanguageResource are 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 the Icons.Material.Filled string 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. Text is the finished sentence, built by AddPhoneDeliveryLine from the localized Notif.Phone.Line or Notif.Phone.LineNoUnit format (NotificationList.razor.cs:95-97) or, for an unattributed failure, from Notif.Phone.StatusOnly (line 74). Color and Icon come from PhoneDeliveryStatus (lines 101-111): Success with CheckCircle when every attempted unit was delivered, Warning with Warning when some were, Error with Error when 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.PhoneDeliveryLines and AddPhoneDeliveryLine (NotificationList.razor.cs:67-99) and consumed only by the Phone cell of the history table, which renders one outlined MudChip per 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 .resx files, 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 resources SharedResource.resx (the English default) and SharedResource.es.resx (Spanish), named in the doc comment (line 7), and from the ASP.NET Core localization stack that binds IStringLocalizer<T> to the .resx named after T.
  • 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's IStringLocalizer<T> convention resolves keys against the resource file whose base name matches the type T, so a dedicated empty class becomes the name that ties many components to one shared string table: injecting IStringLocalizer<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 is MudTranslations.
  • Walkthrough: there are no members. The whole contract is "be a public sealed type named SharedResource in this namespace, with sibling .resx files". 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> by DataGridListPageBase<TDto> for its cancellation toast and its Result error rendering (DataGridListPageBase.cs:27), by Sessions for every label on the devices page (Sessions.razor.cs:35), by the auth pages for their field labels and messages, and handed to ErrorMessages.Configure from 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 .resx files 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: SharedResource only, as the type that names the .resx table; it builds a ResourceManager over typeof(SharedResource).FullName and typeof(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 a ResourceManager on demand. Each property is a one-line Get("Auth.Field.<Field>.<Rule>") call (lines 24-42): FirstNameRequired, LastNameRequired, EmailRequired, EmailInvalid, PasswordRequired, PasswordMaxLength, PasswordComplexity, ConfirmPasswordRequired, ConfirmPasswordMismatch and TokenRequired. [Rubric §27, Internationalization] assesses that user-facing copy is externalized to per-culture resources.
  • Walkthrough: Get (line 44) calls Resources.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 reads CurrentUICulture on 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 SharedResource table as the rest of the chrome means one .resx pair per locale (ADR-027) rather than a second resource file just for validation text. The type is internal, 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) and ForgotPasswordModel.cs (3), all under MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/.
  • Caveats / not-in-source: the Auth.Field.* keys live in the SharedResource .resx files, 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 through ErrorMessageResourceType) 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) and MaxLength(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]: each ErrorMessage is 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 string properties, both initialized to string.Empty so a fresh model binds cleanly. Title (line 24) carries [Required] with key Notif.Send.Field.Title.Required (line 22) and [MaxLength(200)] with key Notif.Send.Field.Title.MaxLength (line 23). Body (line 29) carries the matching pair, Notif.Send.Field.Message.Required (line 27) and Notif.Send.Field.Message.MaxLength with the 2000-character cap (line 28).
  • Why it's built this way: a settable class rather than a record with init accessors, 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: an ErrorSummary bound 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 NotifyOnFailure helper), SharedResource (the resx anchor for the localizer), ViewerTimeZone (the viewer's clock for sent times, resolved after first render), and ComponentLifetimeExtensions (the LifetimeToken read). Externals: MudBlazor (IScrollManager, ScrollBehavior, BreadcrumbItem, Icons), Microsoft.AspNetCore.Components ([Inject], [Parameter], OnInitializedAsync, OnParametersSet, OnAfterRenderAsync, InvokeAsync, StateHasChanged), Microsoft.Extensions.Localization (IStringLocalizer<T>), BCL CancellationTokenSource, IDisposable, Math.Ceiling, CultureInfo.InvariantCulture.
  • Concept introduced, the Blazor code-behind page pattern (.razor plus .razor.cs partial class). The three notification pages in this unit are authored as partial classes split across two files: the .razor holds declarative MudBlazor markup and the routes, the .razor.cs holds the C# (public partial class NotificationInbox, line 28), the injected services, the view state, and the handlers. The framework constructs the component, calls OnInitializedAsync (line 79, which returns the load task directly rather than being async) 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. A readonly 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 .Token off a disposed source throws ObjectDisposedException, so LifetimeToken returns an already-cancelled token instead and the work stops through the normal OperationCanceledException path (ComponentLifetimeExtensions.cs:3-10,26-31). Dispose(bool) (lines 358-370) cancels and disposes it behind the classic _disposed guard (line 356). Every async handler swallows OperationCanceledException silently (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 on TryGetValue (line 229) and routes the failure through result.NotifyOnFailure(Toast, L) (line 248). A failure now has two surfaces: the toast, and the last outcome kept in _loadResult (line 62) for an inline ErrorSummary plus 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. IsLoading and IsSaving (lines 54-55) are protected with private setters; the markup shows progress while loading and sets Disabled="IsSaving" on the action controls (NotificationInbox.razor:18) so a double click cannot double-post.
    • Push-driven refresh via an event subscription. OnInitializedAsync subscribes to NotificationState.OnRefreshRequested (line 89) and Dispose(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 @page directive 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 :int route constraint is the validation boundary, so a malformed id never reaches the component (the router renders NotFound instead), 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 localized aria-label (NotificationInbox.razor:66).
    • [Rubric §27, Internationalization & Localization]: this page holds no literal English. The injected IStringLocalizer<SharedResource> L (line 34) resolves the title (line 50), the breadcrumbs, and every toast (L["Notif.AllMarkedRead"], line 344). The breadcrumb trail is built inside OnInitializedAsync (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).
  • Walkthrough
    • PageSize (line 30) is const int 20: fixed-size server-side pagination, not infinite scroll. Injected InboxService, NotificationState, Toast, L, MudBlazor's ScrollManager, and ViewerTime (lines 32-37).
    • [Parameter] public int? Id (line 46) is the deep-link route parameter. The doc (lines 39-45) explains the type choice: UserNotificationIdentifierType is an int alias, and a route parameter's type must be written out for the :int constraint to bind, so the parameter is declared int? 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 (the Id the state was last computed for, to detect a re-navigation).
    • OnParametersSet (lines 100-109) clears the _scrolledId latch when _appliedId != Id and then recomputes the target. The doc (lines 94-99) records the bug this prevents: navigating from /notifications/inbox/5 to /notifications/inbox/9 reuses 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 awaits ViewerTime.EnsureResolvedAsync(_cts.LifetimeToken()) and calls StateHasChanged when 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 _pendingScrollId and sets _scrolledId before the await (comment, line 125, so a re-entrant render cannot queue the same scroll twice), and calls ScrollManager.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, formatting notification-{id} with CultureInfo.InvariantCulture because it becomes a DOM id) and CardSelector (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, read or unread, plus deep-linked). The chrome those classes select lives in wwwroot/app.css (.notification-card.unread and .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 above CardClass). [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) is EventHandler-shaped so it cannot be async Task; it discards into InvokeAsync(RefreshFromPushAsync) (line 196). RefreshFromPushAsync (lines 199-216) sets _refreshPending = true and 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) returns Task<bool> (true when the page loaded) and starts by setting IsLoading (line 223). It clears _loadResult, calls GetInboxAsync(_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 materializes page.Items, computes _totalPages from page.PaginationMetadata.TotalItemCount with Math.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 through result.NotifyOnFailure(Toast, L) (line 248). The tail (from line 263) drains _refreshPending with one more RefreshFromPushAsync; 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): calls MarkReadAsync(notification.Id, _cts.LifetimeToken()) (line 291), returns early on failure after a toast, then optimistically patches local state, locating the row with FindIndex (line 299) and replacing it via a record with-expression, notification with { IsRead = true, ReadOn = DateTime.UtcNow } (line 302). It then refetches the authoritative unread count (line 306) and pushes it into NotificationState.SetUnreadCount only 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), then SetUnreadCount(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) with GC.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-mounted NotificationListener raises the OnRefreshRequested signal 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 the notifications:manage permission 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, AppleFailed plus NativeDeliveryUnit, 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), same readonly CancellationTokenSource _cts plus dispose pattern (lines 34, 192-211), same IsLoading gate (line 45), same cancellation-swallowing load, same result.NotifyOnFailure(Toast, L) failure surface (line 162), same Task<bool> load plus revert-on-failure OnPageChangedAsync, and the same inline _loadResult outcome. 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 (NavigateToSend targets NotificationRoutePaths.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 up L[$"Notif.Status.{status}"] and falls back to the raw wire value when localized.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 as Notif.Phone.Unit.{unit}.One or .Other, chosen by whether the attempted count is 1, and an unknown unit name drops the word (the Notif.Phone.LineNoUnit format) 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 cascading AuthenticationState (line 32); Title reads L["Notif.List.Title"].Value (line 41); _breadcrumbs (line 43) is built Home to Push Notifications in OnInitializedAsync (lines 126-130), with the leaf crumb disabled: true to mark the current page (line 129).
    • _notifications is an IReadOnlyCollection<PushNotificationDTO> initialized empty (line 47), alongside the paging state _currentPage and _totalPages (lines 48-49) and the last outcome _loadResult (line 52).
    • PhoneDeliveryLines(PushNotificationDTO) (lines 67-79) builds the phone cell for one row: it calls AddPhoneDeliveryLine for Android and then Apple with that platform's sent and failed counts and the row's NativeDeliveryUnit (lines 70-71), and when neither produced a line but a unit was recorded it adds the single error line from Notif.Phone.StatusOnly (lines 72-76). An empty list renders as - (NotificationList.razor:100-103). AddPhoneDeliveryLine (lines 81-99) returns when both counts are null, takes delivered = sent ?? 0 and attempted = 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.Delivered when attempted == delivered, otherwise Notif.Phone.PartlyFailed when anything was delivered and Notif.Phone.Failed when 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 awaits LoadNotificationsAsync (line 132). OnAfterRenderAsync (lines 136-143) resolves the viewer's time zone on the first render through ViewerTime.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) returns Task<bool> and loads one server page: GetHistoryAsync(_currentPage, PageSize, _cts.LifetimeToken()) (line 153) with PageSize 20 (line 24). It stores the outcome in _loadResult (line 154) for inline rendering, copies history.Items into _notifications on success and sets _totalPages to Math.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 _currentPage when 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).
  • 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 /notifications for accounts holding the notifications:manage permission (the nav entry from NotificationUIModule carries RequiredPermission: 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 on pageSize is 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 SendAsync call), NotificationSendModel (the form model), ModelValidation + DataAnnotationsModelValidator (the validation bridge), INotificationScopeProvider (the targeting caption), SendPushNotificationRequest (the wire contract), PushNotificationDTO (the result carrying RecipientCount), Result, NotificationRoutePaths, ErrorMessages, IToastService, ResultUiExtensions, and SharedResource. The markup also composes an UnsavedChangesGuard bound to IsDirty (NotificationSend.razor:12). Externals: MudBlazor (MudForm, BreadcrumbItem, Icons), Microsoft.AspNetCore.Components (NavigationManager, OnInitialized, OnInitializedAsync), Microsoft.Extensions.Localization.
  • Concept introduced, MudForm validation 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 set For, 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, Required drives the asterisk and aria-required while its message still comes from the model, MaxLength caps the input, and Counter shows 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 no OnValidSubmit, 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, an IsSaving flag (line 44) bound to Disabled on 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 toast ErrorMessages.ValidationError on 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 shared ErrorSummary component (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 fed MudForm.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, the ErrorSummary is deliberately not fed them, so the snackbar stays the summary cue. _sendResult is 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 the ErrorSummary: 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 through IStringLocalizer<SharedResource> L (line 28), including the success message L.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 synchronous OnInitialized (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-send NavigateTo) and IsDirty (true whenever Sent is false and either field is non-blank) feed the markup's UnsavedChangesGuard, so leaving with typed-but-unsent text prompts, while the send's own redirect never does. The comment on the Sent setter records the ordering: it is set before the navigation call, because the guard reads the live accessor.
  • Walkthrough
    • Injected NotificationService, NavigationManager, Toast, L, and ScopeProvider (lines 25-29), plus a cascading AuthenticationState (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 via NotificationRoutePaths.Notifications (line 72) and the leaf is disabled: true (line 73).
    • _model (line 46) is a readonly NotificationSendModel created with the component; _validate (line 57) is the single Func<object, string, IEnumerable<string>> MudBlazor calls with (model, member path), wired in OnInitialized as ModelValidation.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 _form is null or a send is already in flight (lines 109-113), sets IsSaving (line 115), and inside the try clears _sendResult (line 118) and validates, warning on failure (lines 122-129), so a failed validation also releases the flag in finally; then builds new SendPushNotificationRequest(_model.Title, _model.Body) (line 131) and awaits SendAsync(request, _cts.LifetimeToken()) (line 132), storing the result for the summary (line 133). On a non-null PushNotificationDTO it raises the success toast with sent.RecipientCount (line 137), sets Sent = true (line 141), and navigates back to the list; otherwise result.NotifyOnFailure(Toast, L) (line 148). The cancellation catch (lines 151-154) additionally names the InteractiveAuto render-mode transition, the case where the WebAssembly runtime takes over mid-call; IsSaving is cleared in finally (lines 155-158).
    • NavigateToList (line 161) is the Cancel button's handler, back to NotificationRoutePaths.Notifications.
    • Sent (a private bool property) and IsDirty (!Sent && (Title or Body non-whitespace)) are declared just after NavigateToList, immediately above the disposal members; Sent is 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).
  • 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/IsDirty pair 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/send for accounts holding the notifications:manage permission (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 through sessionStorage JSON 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 is null for an operator that takes no value (is empty).
  • Walkthrough
    • Operator is the MudDataGrid operator text, for example contains or >= (ColumnFilterState.cs:4-5, parameter doc at ColumnFilterState.cs:8).
    • Value is the invariant-culture value or null (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 to null (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 sessionStorage tier with no custom converter. Keeping the value a string (not an object) 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 ColumnFilters member of ListPageState (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/ListPageStateService.cs:60), the saved dictionary in DataGridListPageBase<TDto> (DataGridListPageBase.ColumnFilters.cs:22) and the c: codec in ListPageQueryStateService (ListPageQueryStateService.cs:193-222). Pinned by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/ListPageQueryStateServiceTests.cs and Pages/Common/DataGridListPageBaseFilterStateTests.cs under 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 .NET System.Threading.Lock type. 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; deferring import() 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 IJSRuntime and the module path (LazyJsModule.cs:20). State is three fields: a Lock (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, since ImportAsync reaches 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 through WaitAsync(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 finally block 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 actual js.InvokeAsync<IJSObjectReference>("import", CancellationToken.None, modulePath) (LazyJsModule.cs:79-81) and assigns _module (LazyJsModule.cs:84). The call sits inside a #pragma warning disable BL0016 pair (LazyJsModule.cs:78 and LazyJsModule.cs:82), and the justification on the disable line is the design point: a failed import must fault the shared task, so GetOrImportAsync evicts 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 swallows JSDisconnectedException (LazyJsModule.cs:102-105), since a torn-down circuit is the normal end of life for a scoped UI service.
  • 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 an await 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 by MMCA.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.ParseQuery and QueryHelpers.AddQueryString without taking the Microsoft.AspNetCore.WebUtilities package (QueryStringCodec.cs:7-11).
  • Depends on: BCL only: StringBuilder, UrlEncoder.Default, Uri.UnescapeDataString and StringValues from Microsoft.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 a StringValues, 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 #fragment first (QueryStringCodec.cs:74-76) so the pairs land before it, starts with ? unless the URI already has a query (QueryStringCodec.cs:77 and QueryStringCodec.cs:87), skips a pair whose value is null (QueryStringCodec.cs:82-85), and encodes both key and value with UrlEncoder.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 what Uri.Query already gives ListPageQueryStateService. The parse walks the input as a ReadOnlySpan<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) and BuildPath (ListPageQueryStateService.cs:157). Pinned by MMCA.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 at SnackbarDefaults.cs:21), MudBlazor's SnackbarConfiguration and Defaults.Classes.Position, and IServiceCollection / ServiceDescriptor for the registration helper (usings at SnackbarDefaults.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 against SnackbarConfiguration.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 after AddUIShared, MmcaBlazorWebHostOptions.ConfigureMudServices, or a plain services.Configure<SnackbarConfiguration>) runs after it and wins; a parameterless AddMudServices() 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
    • MaxDisplayedSnackbars is an internal const int of 3 (SnackbarDefaults.cs:24), and PositionClass returns Defaults.Classes.Position.TopCenter (SnackbarDefaults.cs:27). Both are internal so 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 whose ImplementationType is SnackbarDefaults already exists (SnackbarDefaults.cs:44-47), otherwise it inserts a singleton IConfigureOptions<SnackbarConfiguration> at index 0 of 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 often AddUIShared runs.
  • Why it's built this way: inserting at the front instead of using TryAdd or Configure is what lets the call sit inside AddUIShared without caring whether the host called AddMudServices earlier 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 by MMCA.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 own IConfigureOptions<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 init members, all with defaults, so new 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 a double of 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 the SortBy property 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 an IReadOnlyDictionary<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 an IReadOnlyDictionary<string, ColumnFilterState> keyed by the column's property name, also defaulting to empty. Its doc comment (ListPageStateService.cs:55-59) draws the contrast with Filters: 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.
  • 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-empty ColumnFilters also counts as restorable state, and DataGridListPageBase.cs:882); serialized to sessionStorage as JSON and encoded into the query string. The column-filter half is read back by RestoreColumnFilters (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 ConfirmationDialog component and reduce the answer to a single bool.
  • Depends on: IAppDialogService (implemented), MudBlazor's IDialogService and the internal ConfirmationDialog component (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/ConfirmationDialog.razor:65), per the usings at MudAppDialogService.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's ISnackbar, StaleToastSweeper, plus the ConfirmationDialog this 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 is internal, 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 with destructive: 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 to ConfirmationDialog.ShowAsync. destructive is 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-chosen data-testid for the confirming button through to ConfirmationDialog.ShowAsync, so an end-to-end test can target one specific prompt (IAppDialogService.cs:47-59). Without it the button carries DefaultConfirmTestId, "confirm-action" (ConfirmationDialog.razor:21 and ConfirmationDialog.razor:15); DeleteConfirmation passes "confirm-delete" (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/DeleteConfirmation.razor:9).
    • ConfirmationDialog.ShowAsync (ConfirmationDialog.razor:65-93) returns result is { Canceled: false, Data: true } (ConfirmationDialog.razor:92), so Cancel, Escape and a backdrop dismissal all answer false (ConfirmationDialog.razor:53-56) and callers never branch on three outcomes. Escape is wired to Cancel through CloseOnEscapeKey = 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:6 and ConfirmationDialog.razor:14). Every overload opens that one Cancel-first shape, and DeleteConfirmation goes through this service too (MudAppDialogService.cs:10-11), so the interface can promise it to every prompt (IAppDialogService.cs:8-11).
  • 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 DeleteConfirmation a localized delete prompt built on it (IAppDialogService.cs:3-7). Keeping the implementation internal and registered by AddUIShared means 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 at DependencyInjection.cs:271-288). Consumers resolve the interface: the shared DeleteConfirmation component, through the confirmTestId overload (DeleteConfirmation.razor:33), the shared UnsavedChangesGuard component (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Forms/UnsavedChangesGuard.razor:14 and UnsavedChangesGuard.razor:57) and the Helpdesk seed's ticket pages (MMCA.Helpdesk/Source/Hosts/UI/MMCA.Helpdesk.UI.Web/Components/Pages/Tickets.razor:175 and Components/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 from sessionStorage.
  • 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 into PendingToast? on the read path (PendingToastService.cs:48).
  • 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 on IPendingToastService.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.cs and Components/Notifications/PendingToastHostTests.cs under 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 NavigationManager and StringValues.
  • 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 (desc only, since ascending is the default), d (1 only, since comfortable density is the default), q (free-text search), f:<name> for any other named filter and c:<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 to q by convention, the c: prefix and its : separator (ListPageQueryStateService.cs:39-40), and the desc/1 markers. A separate MaxPageSize constant (ListPageQueryStateService.cs:49) caps the page size a URL may ask for. It is not a literal: it is defined as KeysetPageRequest.MaxPageSize, which is 1000 (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 injected NavigationManager and hands the query to the parser.
    • ParseQueryString (ListPageQueryStateService.cs:65) is deliberately static and public, documented as a pure helper exposed for unit testing without a NavigationManager (ListPageQueryStateService.cs:60-64). It parses through QueryStringCodec.Parse (ListPageQueryStateService.cs:67), then reads the three integers through TryGetInt (ListPageQueryStateService.cs:275-285, which parses with CultureInfo.InvariantCulture and 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 at 0, the mobile page at 1, and a page size outside 1..1000 collapses to 0, the page default, through ClampPageSize (ListPageQueryStateService.cs:273). The inline comment states the reason: a hand-edited or stale link with p=-3 or ps=5000 must not leave the list stuck on a failing fetch. It then treats a blank sort value as no sort (ListPageQueryStateService.cs:76-83), matches desc case-insensitively (ListPageQueryStateService.cs:88) but the dense marker 1 ordinally (ListPageQueryStateService.cs:94), then hands the rest to ParseFilters (ListPageQueryStateService.cs:97, body at ListPageQueryStateService.cs:193-222), which skips empty values, folds q into the search filter, strips the f: prefix off named filters and turns each c: 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 a null value for an operator that takes none, such as is 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), sd only when a sort column exists and is descending (ListPageQueryStateService.cs:139-146), d only when dense (ListPageQueryStateService.cs:148-151). Filters go through AddFilterParameters (ListPageQueryStateService.cs:153, body at ListPageQueryStateService.cs:225-251), which writes q, the f: keys and one c:<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 with QueryStringCodec.AddQueryString (ListPageQueryStateService.cs:155-157).
    • ReplaceState (ListPageQueryStateService.cs:176) writes the URL back using NavigationOptions { ReplaceHistoryEntry = true } (ListPageQueryStateService.cs:189) so filter changes do not pollute the back stack.
  • 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 owning basePath. The remarks (ListPageQueryStateService.cs:166-175) record the diagnosed defect: a grid-state write is inherently deferred (a debounced search, a late ServerData completion), 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:293 and DataGridListPageBase.cs:371) and writes it back after a grid or filter change (DataGridListPageBase.cs:1853 and DataGridListPageBase.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 sessionStorage so the state survives things a circuit-scoped dictionary cannot.
  • Depends on: ListPageState and LazyJsModule; externals IJSRuntime, IJSObjectReference and the nav-interop.js module shipped in the package's wwwroot.
  • 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: true navigations and the SSR to WASM render-mode transition. The synchronous dictionary matters just as much, because it is safe to read from OnInitialized during 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 the mmca.lps: session-key prefix (ListPageStateService.cs:74). State is a plain Dictionary<string, ListPageState> (ListPageStateService.cs:76) plus one LazyJsModule (ListPageStateService.cs:77).
    • GetState (ListPageStateService.cs:84-85) is a GetValueOrDefault and 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 a with expression 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 the internal RecoverFromSessionAsync (ListPageStateService.cs:122), which invokes sessionGet on the JS module (ListPageStateService.cs:132, the export at MMCA.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), or null when 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 through sessionSet (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 calls sessionRemoveByPrefix with the mmca.lps: prefix (ListPageStateService.cs:196, the export at nav-interop.js:45), leaving the tab's other sessionStorage keys alone. Its summary (ListPageStateService.cs:176-183) gives the reason: the search and filters belong to the account that typed them, sessionStorage outlives 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:169 and ListPageStateService.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 matches InvalidOperationException (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) and OperationCanceledException, which covers an interop timeout or cancellation (JsInteropFailure.cs:17-26). PendingToastService uses the same filter. The catch in PersistToSessionAsync (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 a null module 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.
  • 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 through RecoverFromSessionAsync (DataGridListPageBase.cs:588) and applies the returned entry rather than re-reading the dictionary (DataGridListPageBase.cs:654 and DataGridListPageBase.cs:666), records scroll offsets (DataGridListPageBase.cs:821), and saves plus persists after grid and density changes (DataGridListPageBase.cs:1832-1859 and DataGridListPageBase.cs:1925-1934). JwtAuthenticationStateProvider takes it as an optional dependency (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/JwtAuthenticationStateProvider.cs:43) and calls ClearAsync on sign-in and sign-out (JwtAuthenticationStateProvider.cs:141, JwtAuthenticationStateProvider.cs:149 and JwtAuthenticationStateProvider.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 a Show parameter at line 56 and switched over at lines 205-210); MudBlazor's ISnackbar (held in a private field, line 35), Snackbar, Severity, Variant, Color and SnackbarOptions, and Microsoft.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 and Result helper in both applications depends on IToastService; apart from this class and MudAppDialogService (and the ConfirmationDialog the latter opens), the only framework type that names MudBlazor's ISnackbar is 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.NotifyOnFailure can 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: MmcaThemeProviders hosts MudBlazor's MudSnackbarProvider inside a role="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 ISnackbar in 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, a List<Snackbar> (_pinned, line 38) and a Lock (_pinnedSync, line 39).
    • Four one-liners cover the common levels: Success, Info, Warning and Error (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 a RenderTreeBuilder (a bolded title, a line break, then the body, lines 63-69) and sets RequireInteraction = true with Variant.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 whole Add call is wrapped in AddPinned(...) (line 60) so the toast is tracked and capped.
    • ShowAction(message, actionText, onAction, severity, requireInteraction) (line 80) is the undo-style toast. A local Configure function (line 96) sets Action and ActionColor (lines 98-99) and adapts MudBlazor's click signature to the caller's parameterless delegate by discarding the Snackbar instance MudBlazor passes (line 103). It also sets DuplicatesBehavior = 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). requireInteraction is 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 through AddPinned (line 89) and Configure states both RequireInteraction and Variant.Filled outright 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 most SnackbarConfiguration.MaxDisplayedSnackbars at 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 subscribes ForgetPinned to its OnClose (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 from add() 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 its OnClose fires, 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 from ShownSnackbars is gone and is pruned (lines 166-170).
    • IsPinned(Snackbar) (line 182) is internal and 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:92 and StaleToastSweeper.cs:111-112).
    • Map(ToastSeverity) (line 203) projects the neutral enum onto MudBlazor's with an explicit switch over all five members plus a Normal default (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 a SnackbarConfiguration with MaxDisplayedSnackbars = 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.
  • 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 returns void: a toast is fire-and-forget by design, and MudBlazor's ISnackbar.Add is 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 AddCommonUiFacades with TryAddScoped (DependencyInjection.cs:291), which AddUIShared calls for every host (DependencyInjection.cs:193). Consumers resolve IToastService, never this type: the framework's NotificationListener raises an incoming push as a persistent toast (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Notifications/NotificationListener.razor:49), ResultUiExtensions.NotifyOnFailure turns 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 fresh SnackbarOptions carrying 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: ShowPersistent renders 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, Success and the rest pass the caller's string straight to MudBlazor, so any localization has to happen before the call; the facade does not touch IStringLocalizer. 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 before NavigateTo(url, forceLoad: true) dies with the page; this service parks it instead.
  • Depends on: IPendingToastService (implemented) and IAsyncDisposable (PendingToastService.cs:14), IJSRuntime via 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 the nav-interop.js module (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 calls sessionSet with a new PendingToast (lines 33-34).
    • TakeAsync(ct) (line 43) reads with sessionGet (line 48), returns null when nothing is parked, and removes the entry with sessionRemove before 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 as null (lines 58-60), so a tampered entry cannot reach the toast host.
    • Both methods swallow interop failure through the shared JsInteropFailure.IsUnavailable filter (lines 36 and 62; the definition at MMCA.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 covers TaskCanceledException). 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 sessionStorage rather 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 AddCommonUiFacades with TryAddScoped<IPendingToastService, PendingToastService>() (DependencyInjection.cs:293). The shared layout renders PendingToastHost (Layout/MainLayout.razor:19), which calls TakeAsync on its first interactive render (Components/Notifications/PendingToastHost.razor:18) and shows the result through IToastService. ADC's Profile page 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 Sources list 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 settable IReadOnlyList<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: EffectiveSources is the page's own Sources parameter 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 by FeatureFlagAdminTests.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 source route 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 gives Admin/FeatureFlags as 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) returns IReadOnlyList<FeatureFlagStatusResponse>. SetOverrideAsync(source, name, request, ...) (lines 32-36) returns the flag's state afterwards. ClearOverrideAsync(source, name, ...) (line 43) returns a bare Result.
  • Why it's built this way: the opt-in UI half of reloadable feature flags (ADR-031); an app that calls no AddFeatureFlagAdministrationUI registers 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 in FeatureFlagAdminTests.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 plain Guid (lines 27, 33, 39). Its sole implementation is MachineClientAdminService.
  • Concept, a secret shown once. CreateAsync and RotateAsync return MachineClientSecretResponse and their docs say the secret comes back once (lines 17, 23); every other member returns the secret-free MachineClientResponse. Rotation is two-step: RotateAsync issues a secondary secret and PromoteAsync makes 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 in MachineClientAdminTests.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) and GetAsync(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 by RoleAdminEdit.razor.cs and RoleAdminList.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 SetRolesAsync and a single-role convenience SetRoleAsync.
  • 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 over SetRolesAsync that 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. Declaring SetRoleAsync as 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) and UnlockAsync(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.cs for the lock/unlock/role actions on the user-admin grid, and pinned by UserListTests.cs (ADC) and UserAdminListTests.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) returns Result<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 in SupportAccessLogTests.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 UserAdminList as its FetchPage delegate (type doc comment).
  • Depends on: extends IUserAdminActionsUIService (line 17); its read is generic over TUserDto, the consumer-supplied user row shape. UserIdentifierType names the account parameter of GetAsync (line 23), GetSessionsAsync (lines 32-34), which returns RefreshSessionSummaryResponse rows (line 32), and GetSignInsAsync (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, from GET Admin/Users/{userId}. GetSessionsAsync(userId, ...) (lines 32-34) reads the account's live (signed-in) sessions, newest first, from GET 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 from GET 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 TUserDto rather 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.cs and ADC's UserDetail.razor.cs (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserDetail/UserDetail.razor.cs), and pinned by UserAdminListTests.cs (Common) and UserDetailTests.cs (ADC). ADC's UserDetail renders 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; IHttpClientFactory and 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) guards source with ThrowIfNullOrWhiteSpace (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 bare Result. The private FlagUrl(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/MachineClients endpoint 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 GetAllAsync runs inside the inherited RetryPolicy (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, PromoteAsync and RevokeAsync (lines 64-65, 68-69, 72-73) are one-line calls into the private generic PostAsync<TResponse>(clientId, action, ...) (lines 81-91), which POSTs an empty body to {Endpoint}/{clientId}/{action} (lines 86-87) with rotate, promote or revoke as 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/Roles endpoint 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); IHttpClientFactory and 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 inherited RetryPolicy, read the body or the Problem Details. GetAllAsync, GetAsync(role, ...) and GetCatalogAsync are 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 (a RolePermissionsResponse rather than a bare success) and whose HTTP verb is PUT.
  • 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-checks role then appends Uri.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 not async methods themselves.
  • Why it's built this way: matches the composition every other service in this package uses, HttpResultExecutor outside, RetryPolicy in 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 StringBuilder and CultureInfo.InvariantCulture build the URL.
  • Concept, the query string is the contract. The controller binds ViewAsGrantListRequest from 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; BuildUrl is internal 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 inherited RetryPolicy (line 44). BuildUrl(request) (lines 60-72) always appends pageNumber and pageSize (line 63), then staff, viewed, from, to and status (lines 65-69); from and to go through ToUniversalTime().ToString("O", ...) (lines 67-68). The private Append (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); BuildUrl is pinned by MMCA.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/Users endpoint 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); UserIdentifierType names every account parameter; System.Globalization.CultureInfo.InvariantCulture formats 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 is async (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}/sessions through the same retry and reads an IReadOnlyList<RefreshSessionSummaryResponse>, which feeds UserSessionsTable. GetSignInsAsync(userId, ...) (lines 76-94) has the identical shape against {Endpoint}/{userId}/sign-ins and reads an IReadOnlyList<SignInSummaryResponse>, which feeds SignInHistoryTable. LockAsync and UnlockAsync (lines 97-102) both delegate to the private PostLockChangeAsync(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 calls SetRolesAsync, 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 TUserDto so 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's UserDetail.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 JsFetchSessionCookieSync and, on a Blazor Server host that enabled the same-origin proxy, by HandoffSessionCookieSync (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/HandoffSessionServices.cs:53); consumed by WasmTokenStorageService and by ServerTokenStorageService (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 Authorization header 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 /login even 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 than localStorage.
    • [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>: true when the cookie jar was updated, false when 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) and ClearAsync() removes it (line 20). The two callers treat the answers differently on purpose. A failed sync is surfaced: WasmTokenStorageService throws InvalidOperationException when SyncAsync returns false (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/WasmTokenStorageService.cs:141-144), so AuthUIService reports Auth.TokenStorageUnavailable instead 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; ServerTokenStorageService does the same at ServerTokenStorageService.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_refresh HttpOnly cookie pair and the /auth/session/token hydration 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, which WasmTokenStorageServiceTests does (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/WasmTokenStorageServiceTests.cs:30).
  • Where it's used: registered by the dedicated extension AddClientAuthSessionCookieSync(), which TryAddScopeds JsFetchSessionCookieSync (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) and CsrfHeaderValue = "1" (line 17).
  • Depends on: nothing. It lives in MMCA.Common.UI rather than MMCA.Common.UI.Web so 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 OPTIONS itself with no CORS grant and refuses any request whose Origin or Sec-Fetch-Site names 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 string members and no behavior. Being const, 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 by NotificationHubService on the SignalR connection options (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NotificationHubService.cs:389); checked by SameOriginApiProxyEndpoint in HasCsrfHeader, which demands exactly one value equal to CsrfHeaderValue (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:127-130); stripped before forwarding by SameOriginProxyTransformer (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginProxyTransformer.cs:80). Covered by SameOriginProxyClientTests (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 ISessionCookieSync implementation, 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-side fetch, so the clearing Set-Cookie lands 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 the mmcaAuthCookie object defined in the package's static web asset MMCA.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-Cookie in 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. SyncAsync sends 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 a false answer, 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) is Task.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) returns InvokeAsync<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). The catch is filtered by JsInteropFailure.IsUnavailable(ex) (line 33), which names the four types that mean "there is no live JS runtime right now": InvalidOperationException, JSDisconnectedException, JSException and OperationCanceledException (JsInteropFailure.cs:27-31). Such a failure returns false because 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 JsInteropFailure rather 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 (see ISessionCookieSync). The cookie contract itself belongs to ADR-022.
  • Where it's used: TryAddScoped behind ISessionCookieSync by AddClientAuthSessionCookieSync(), 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 by WasmTokenStorageService and ServerTokenStorageService. Covered by JsFetchSessionCookieSyncTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/JsFetchSessionCookieSyncTests.cs).
  • Caveats / not-in-source: the mmcaAuthCookie.clear JS implementation lives in mmca-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 any Authorization header and stamps the proxy's CSRF header on every request (SameOriginProxyRequestHandler.cs:3-10).
  • Depends on: SameOriginProxyHeaders for the header name and value; external DelegatingHandler.
  • 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 Authorization header the outer handlers (such as AuthDelegatingHandler) or a service's DefaultRequestHeaders attached 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) guards request with ArgumentNullException.ThrowIfNull (line 16), sets request.Headers.Authorization = null (line 18), removes any existing CSRF header and adds exactly one with TryAddWithoutValidation (lines 19-20), then delegates to base.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:SameOriginApiEndpoint is 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: AddTransient and AddHttpMessageHandler inside AddUIShared() behind the usesSameOriginProxy check (DependencyInjection.cs:183-189), after the auth and culture handlers (lines 180-181). The proxy side that reads the CSRF header is SameOriginApiProxyEndpoint.

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 in AuthDelegatingHandler)

  • 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> Storage and long TrackedAt.
  • Depends on: ISessionAwareTokenStorage (the storage it points at); externals WeakReference<T> and Environment.TickCount64 (the clock TrackedAt is 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 static Owners dictionary (line 56). They are read three ways: HasLiveOwner (lines 102-103) and the two report paths resolve Storage.TryGetTarget to find a live owner (lines 237, 318), and IsStale (lines 178-179) treats an entry as droppable when TrackedAt is older than RetentionMs or 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 internal test 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 AuthenticationStateProvider that turns the stored JWT into the ClaimsPrincipal Blazor's AuthorizeView and [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 to null) and ISessionAwareTokenStorage (an optional capability it probes the storage for); externals Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider, System.Security.Claims and JwtSecurityTokenHandler.
  • Concept introduced, Blazor's auth-state contract. Blazor does not know about JWTs; it asks an AuthenticationStateProvider for an AuthenticationState and re-renders every CascadingAuthenticationState consumer 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 static AuthenticationState over an empty ClaimsIdentity (JwtAuthenticationStateProvider.cs:26-27). Because a ClaimsIdentity with no authentication type reports IsAuthenticated == 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 _tokenStorageService and _listPageState (fields at lines 29-30), and, when the storage is an ISessionAwareTokenStorage, subscribes OnSessionEnded to its SessionEnded event (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 to sessionStorage, 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 a ClaimsIdentity from 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 identity IsAuthenticated. A bare catch under an annotated CA1031 suppression ("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 base NotifyAuthenticationStateChanged (line 106). It does not consult storage, because the caller has just been handed the token.
    • NotifyUserLogout() (lines 112-113) pushes AnonymousState back out.
    • SignOutAsync() (line 121, internal) is the sign-out every AuthUIService path ends in: it awaits the list-state clear, then calls NotifyUserLogout(). It is awaited so the sessionStorage removal lands before the caller's forceLoad navigation 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 calls NotifyUserAuthentication(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 without SessionEnded, 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 calls NotifyUserLogout() (line 150). Per MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/ISessionAwareTokenStorage.cs:3-10,14-18 the 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) is Task.CompletedTask when 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 internal SignInAsync / SignOutAsync pair is what lets AuthUIService drive the state transition at the exact moment tokens change; it does so behind an is JwtAuthenticationStateProvider type 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 implement ISessionAwareTokenStorage behaves 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 by JwtAuthenticationStateProviderTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/JwtAuthenticationStateProviderTests.cs:16), whose WhenTheStorageReportsTheSessionEnded_NotifiesAnonymous (line 137) and WhenTheStorageReportsTheSessionEnded_ForgetsTheListPageStateAndNotifiesAnonymous (line 152) drive the session-ended path through a fake session-aware storage (its EndSession, line 178). AuthUIServiceTests constructs 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: Result and the passkey contracts PasskeyOptionsResponse, PasskeyResponse, PasskeyRegisterRequest and PasskeySignInRequest, plus AuthenticationResponse. Implemented by AuthUIService.
  • 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 new IAuthUIService members, so a consumer's own IAuthUIService implementation keeps compiling, following the ISignInLinkUIService precedent (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, and CompleteRegistrationAsync(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}) and DeleteAsync(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) and SignInAsync(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).
  • Why it's built this way: implementing it on AuthUIService means a passkey sign-in stores its tokens through the password sign-in's path (lines 11-12, and the registration comment at MMCA.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>() in AddUIShared() (DependencyInjection.cs:212); injected by PasskeySignInButton (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/PasskeySignInButton.razor.cs:40) and PasskeysPanel (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/PasskeysPanel.razor.cs:39), and probed by Login to 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-link landing page (ISignInLinkUIService.cs:6-9).
  • Depends on: Result and AuthenticationResponse. Implemented by AuthUIService.
  • 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 new IAuthUIService members, so a consumer's own IAuthUIService implementation keeps compiling, the IEmailConfirmationUIService precedent (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). acceptedTerms carries whether the visitor accepted the Terms of Service on the page (line 33).
  • Why it's built this way: implementing it on AuthUIService means 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 at MMCA.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>() in AddUIShared() (DependencyInjection.cs:207); injected by the landing page SignInLink (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/SignInLinks/SignInLink.razor.cs:77) and resolved optionally by Login for 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 returning Result so 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 via POST 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 with EmailConfirmation.PasswordRequired, and carries either the request's CurrentPassword or its NewPassword as 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 via POST 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 reasoning IAuthUIService documents: 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 new IAuthUIService members keeps a consumer's own IAuthUIService implementation compiling (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:201-202).
  • Where it's used: implemented by EmailConfirmationUIService; injected by ConfirmEmail, which calls ConfirmEmailAsync and then ConfirmEmailWithPasswordAsync (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ConfirmEmail.razor.cs:259,337), by EmailConfirmationResendPrompt (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/EmailConfirmationResendPrompt.razor.cs), by ADC's EmailConfirmationReminder (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Components/EmailConfirmationReminder.razor.cs) and by MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Pages/ConfirmEmailPageTestsBase.cs; registered TryAddScoped in AddUIShared() (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 DelegatingHandler that attaches the stored JWT as a Bearer header on every outgoing API request, so no UI service ever sets an Authorization header 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 the SkipBearer request option.
  • Depends on: ITokenStorageService (its only constructor parameter), ISessionAwareTokenStorage (the renewal capability a 401 is reported to), TokenOwner (its owner-map entry), MultiFactorRequiredSignal and AuthErrorCodes (the coded 403 path), and AuthenticatedServiceBase (replay-safety marking); externals System.Net.Http.Headers.AuthenticationHeaderValue, DelegatingHandler, ConcurrentDictionary, StrongBox<long>, Interlocked and System.Text.Json.JsonDocument.
  • Concept introduced, the HTTP message-handler pipeline. HttpClient composes 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 at AuthDelegatingHandler.cs:21-28).
  • Walkthrough:
    • SkipBearer (AuthDelegatingHandler.cs:45) is a public static HttpRequestOptionsKey<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), and ProblemJsonMediaType = "application/problem+json" (line 61). Three static fields hold the cross-request state: the ordinal ConcurrentDictionary maps Owners (token to TokenOwner, line 64) and RenewedTokens (token to the tick it was renewed at, line 67), and LastSweepAt, a readonly StrongBox<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 an ISessionAwareTokenStorage (lines 84-87) and otherwise stores a weak reference stamped with Environment.TickCount64 (line 89). The reason is in the class doc: the handler resolves its own storage in the IHttpClientFactory handler 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) and MarkRenewedAt (line 107) write the maps directly and are the hooks tests use to age entries; HasLiveOwner (line 116), IsTrackedOwner (line 122) and IsMarkedRenewed (line 127) read them.
    • Both writers end with SweepIfDue() (lines 101 and 110), which sweeps at most once per SweepIntervalMs whatever the call rate (line 157). It asks TryClaimSweep(ref lastSweepAt, now, intervalMs) (line 149, internal static), which reads the last tick with Interlocked.Read and claims the sweep with Interlocked.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-locks Count read, and once the maps pass SweepThreshold with nothing removable (live circuits holding recent tokens), a full scan per call (lines 53-57). The winner runs SweepIfLarge() (line 133): SweepOwners (line 190) and SweepRenewed (line 204) still do nothing until a map holds more than SweepThreshold entries, then drop the owner entries that are stale (older than RetentionMs or whose storage is gone, IsStale, lines 217-218) and the renewal entries older than RetentionMs (IsExpired, line 220).
    • SendAsync(request, cancellationToken) (line 166) is a thin wrapper: it awaits the private SendWithBearerAsync inside a try, and on an HttpRequestException calls AuthenticatedServiceBase.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. When SkipBearer is set to true the request passes straight to base.SendAsync without touching token storage at all (lines 226-229). A request that already carries an Authorization header also gets no stored token (the Authorization is null check 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 awaits GetAccessTokenAsync() (line 233), and only when the result is non-blank sets request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token) (lines 234-237). It then reads the bearer it is about to send with BearerOf (line 241; the helper at lines 183-188 accepts only a non-blank Bearer scheme), before the call, because the same-origin proxy handler further in strips the header (comment at line 240). After base.SendAsync (line 242) a 401 to a request that carried a bearer goes to ReportRejectedAsync (lines 244-247) and a 403 goes to ReportMultiFactorRequiredAsync (lines 248-261). That 403 call sits in a try whose bare catch disposes 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 a MultiFactorRequiredSignal subscriber and the body is application/problem+json (lines 290-294), so a host that never called AddTwoFactorUI() 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 annotated CA1031 suppression that lets only a cancellation propagate (lines 302-309). It raises the signal when CarriesMultiFactorRequired (line 320) finds AuthErrorCodes.MultiFactorRequired under errors[*].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 in RenewedTokens is skipped, since refreshing again would loop (lines 375-379). Otherwise it resolves the live owner or the fallback as an ISessionAwareTokenStorage (lines 381-387) and awaits RenewRejectedAccessTokenAsync(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 annotated CA1031 suppression (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 lifetime AddHttpMessageHandler expects.
  • 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). NotificationHubService calls ReportRejectedAsync for a refused hub handshake (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NotificationHubService.cs:686). The SkipBearer option is set by DirectApiTokenRefresher on its refresh request (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/DirectApiTokenRefresher.cs:67) and by AnonymousApiRequest on 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, SameOriginProxyRequestHandler sits inside this handler and strips whatever header it attached (DependencyInjection.cs:187-188). Covered by AuthDelegatingHandlerTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/AuthDelegatingHandlerTests.cs:18, including the sweep pacing at lines 214 and 225), by SessionBearerRenewalTests (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: Result and its generic form from MMCA.Common.Shared.Abstractions; the MMCA.Common.Shared.Auth contracts LoginRequest, RegisterRequest, AuthenticationResponse, RefreshSessionSummaryResponse and SignInSummaryResponse; and ErrorType for the failure kinds it documents. Implemented by AuthUIService.
  • 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 a Result carrying the server's own errors, so the failure arrives with the call rather than on a LastError property that the next call would overwrite. Pages render it through MMCA.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 bare Task), 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) and RegisterAsync(RegisterRequest, ct) both return Result<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 through auth/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). codeVerifier is 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), null for a flow started without one (lines 31-34).
    • LogoutAsync() (line 45) is the deliberate no-Result member: it signs out this device only, revoking this device's server-side refresh session through auth/revoke/current and 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) hits auth/password.
    • RequestPasswordResetAsync(email, ct) (line 55) hits the anonymous auth/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 anonymous auth/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) returns Result<IReadOnlyList<RefreshSessionSummaryResponse>> from auth/my-sessions, newest first, and documents that exactly one row can carry IsCurrent, resolved server-side from the access token's sid claim (lines 64-69).
    • GetSignInsAsync(ct) (line 79) returns Result<IReadOnlyList<SignInSummaryResponse>> from auth/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 carrying IsCurrent (lines 72-78).
    • RevokeSessionAsync(sessionId, ct) (line 88) signs one device out via auth/revoke/{sessionId}; another account's session id (or a nonexistent one) answers 404 and arrives as an ErrorType.NotFound failure, and revoking an already-revoked session answers the same 404 (lines 81-85).
    • RevokeAllSessionsAsync(ct) (line 98) signs out of every device via auth/revoke and, unlike LogoutAsync, returns the server's answer as a Result. 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-out LogoutAsync does (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 the AuthDelegatingHandler 401 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 TryAddScoped against AuthUIService by AddUIShared() (DependencyInjection.cs:196, the comment at line 195 noting TryAdd prevents duplicate registration when several hosts call in); injected by the shipped auth pages, including Login (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), and Sessions, which lists devices and sign-ins and whose sign-out-everywhere action calls RevokeAllSessionsAsync (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor.cs:100,132,246). SignOutNavigator wraps LogoutAsync for 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 IEmailConfirmationUIService implementation. It posts to the two confirmation endpoints and translates the response through the shared HttpResultExecutor / ProblemDetailsResultReader path used across the auth services.
  • Depends on: IEmailConfirmationUIService (the contract it implements); IHttpClientFactory (its only constructor parameter, EmailConfirmationUIService.cs:22); ConfirmEmailRequest and SendEmailConfirmationRequest (the payloads); HttpResultExecutor and ProblemDetailsResultReader (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 own async state 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 a ConfirmEmailRequest(email, token) to auth/confirm-email.
    • ConfirmEmailWithPasswordAsync (lines 31-32) posts the caller's own ConfirmEmailRequest, the one carrying a password proof, to the same auth/confirm-email.
    • ResendEmailConfirmationAsync (lines 35-36) posts a SendEmailConfirmationRequest to auth/send-email-confirmation.
    • PostOnceAsync<TRequest>(relativeUrl, body, cancellationToken) (line 38) creates a fresh HttpClient from the factory (line 42), builds the request with AnonymousApiRequest.PostJson(relativeUrl, body) (line 46), sends it with SendAsync (line 47) and reads the result with ProblemDetailsResultReader.ReadAsync (line 49), all wrapped in HttpResultExecutor.ExecuteAsync (line 39) for the shared transport-fault translation. AnonymousApiRequest sets AuthDelegatingHandler.SkipBearer on 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 fresh HttpClient per 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 against IEmailConfirmationUIService in AddUIShared() (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, so AuthorizeView and [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 an HttpResponseMessage.
  • Depends on: first-party ITokenStorageService (token persistence, AuthUIService.cs:51), JwtAuthenticationStateProvider (injected as the framework AuthenticationStateProvider base type at AuthUIService.cs:52 and pattern-matched back down), IPushRegistrationService (native push cleanup, AuthUIService.cs:53), ILocalCacheStore (optional device-local document cache, defaulted to null, AuthUIService.cs:54, wiped on sign-out), IDeviceMetadataReporter (optional per-session device reporter, AuthUIService.cs:55) run through DeviceMetadataReporting, an optional ILogger<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, and Microsoft.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. LogoutAsync is deliberately local-first and ends this device only: the local sign-out runs in a finally, 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). RevokeAllSessionsAsync is 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" returning Result, 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-only init timeout: AuthUIServiceTests drives the whole class through a stub HttpMessageHandler.
  • 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), and MissingAccessTokenCode = "Auth.MissingAccessToken" (AuthUIService.cs:68) covers a 2xx whose body carried no access token, which means the response shape drifted. Both are const string, so tests and pages branch on them without duplicating literals. The private constants ApiClientName = "APIClient", RevokeCurrentPath = "auth/revoke/current" and ViewAsEndPath = "auth/view-as/end" follow (AuthUIService.cs:70-72), and the internal LogoutStepTimeout property (line 78, an init settable 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) and RegisterAsync (lines 90-91) are one-liners over the private AuthenticateAsync, differing in the relative URL (auth/login, auth/register) and in RegisterAsync passing allowConfirmationPending: true: behind the email gate the API answers 202 Accepted (account created, confirmation pending, no session), which comes back as a success carrying RegistrationOutcome.ConfirmationPending with 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 returns Error.Validation("Auth.OAuth.MissingCode", ...) without a round trip (AuthUIService.cs:96-100), then it hands an OAuthCodeExchangeRequest with CodeVerifier set to AuthenticateAsync against auth/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 with AnonymousApiRequest.PostJson(relativeUrl, request) (line 457), which sets AuthDelegatingHandler.SkipBearer so 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 with SendAsync (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 reads ProblemDetailsResultReader.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 with MissingAccessTokenCode if it is not (lines 474-479). Only then does it call tokenStorageService.SetTokensAsync (line 483) inside a try that converts an InvalidOperationException into a TokenStorageUnavailableCode failure 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 a false from 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 through TryRevokeAsync(authentication.AccessToken, ...) (line 492) and then clears the stored tokens (line 495, swallowing a second InvalidOperationException, 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 injected AuthenticationStateProvider down to JwtAuthenticationStateProvider and awaits its SignInAsync (lines 511-514), which forgets the previous account's list-page state before publishing the new identity (comment at lines 509-510). The is test rather than a cast is what lets a host register a different provider without breaking sign-in. Last it runs ReportDeviceAsync (line 517), after the tokens are stored so the report's bearer names the new session.
    • ReportDeviceAsync (lines 527-533) calls DeviceMetadataReporting.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 a try and the local sign-out in the finally (SignOutLocallyAsync(), line 139), so the local half runs whatever the remote half did, a throwing refresh included (comment at lines 112-117). First the private UnregisterPushAsync() (line 110). Second it reads the bearer through ReadAccessTokenForRevokeAsync() (line 118): that read may refresh a stale token, so the revoke is not refused as a 401, and it is bounded by LogoutStepTimeout with a WaitAsync (line 153) and answers null on any failure or timeout, which skips the revoke (lines 143-160). With a token in hand it opens a CancellationTokenSource of LogoutStepTimeout (line 121), bounded rather than left to the client's 90 s HttpClient.Timeout so a hung backend cannot hold the sign-out. A view-as token (tested by IsViewAsToken, line 127) is refused on auth/revoke/current and must never revoke a session of the viewed account, so it posts ViewAsEndPath instead, ending the view before the local sign-out clears the cookies and the overlay (lines 123-130); any other token goes to TryRevokeAsync (line 133).
    • TryRevokeAsync (lines 169-170) is the shared best-effort revoke, a one-line forward to TryPostWithBearerAsync(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 bare catch that ignores every failure (lines 185-190). IsViewAsToken (line 197) reads the JWT with JwtSecurityTokenHandler and looks for the AuthClaimTypes.ViewAsActor claim (lines 201-203); a token that does not parse is simply not a view-as token (lines 205-210).
    • RevokeAllSessionsAsync (AuthUIService.cs:214) posts auth/revoke through HttpResultExecutor on an authenticated client, reading it with the non-generic reader (lines 216-224). Only when the result is a success does it run UnregisterPushAsync() then SignOutLocallyAsync(), in the same order as LogoutAsync so the push unregister still holds a valid access token (lines 226-232); either way it returns the server's Result (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 and PUTs it to auth/password (lines 247-248). RequestPasswordResetAsync (line 254) and ResetPasswordAsync (line 296) deliberately send no Bearer header, building their POSTs with AnonymousApiRequest.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-password answers 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 anonymous auth/sign-in-link through AnonymousApiRequest.PostJson (line 277) and reads it with the non-generic reader (line 280). RedeemSignInLinkAsync (line 285) hands a RedeemSignInLinkRequest carrying the email, token and acceptedTerms flag to AuthenticateAsync against auth/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) GETs auth/my-sessions and reads it with the generic reader into IReadOnlyList<RefreshSessionSummaryResponse> (lines 321-322); GetSignInsAsync (line 327) does the same for auth/my-sign-ins into IReadOnlyList<SignInSummaryResponse> (lines 335-336). RevokeSessionAsync (line 341) posts auth/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 with AnonymousApiRequest.Post at line 422, so a stale session cannot ride along, comment at line 420) and SignInAsync (lines 429-430), which goes through AuthenticateAsync against auth/passkeys/signin.
    • Private helpers close the class. UnregisterPushAsync (line 541) calls pushRegistration.UnregisterAsync(timeout.Token).WaitAsync(timeout.Token) under a LogoutStepTimeout source (lines 543-546) inside a bare catch (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() under catch (InvalidOperationException) for the interop-unavailable case (lines 563-570), then ClearLocalCacheAsync() (line 572), then the provider's SignOutAsync() behind the type test (lines 574-577), which forgets the list-page state and notifies logout. The four #pragma warning disable CA1031 blocks (lines 155-157 in ReadAccessTokenForRevokeAsync, 185-187 in TryPostWithBearerAsync, 205-207 in IsViewAsToken, 548-550 in UnregisterPushAsync) are deliberate and annotated in place: catching everything is the correct policy for a best-effort step. CreateAuthenticatedClientAsync (line 586) creates the APIClient, sets DefaultRequestHeaders.Authorization from the stored token (line 593) and registers that token's owner with AuthDelegatingHandler.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) swallows InvalidOperationException from the store and returns null, so an SSR prerender proceeds tokenless and lets the API answer 401 like any other failure (lines 609-614). ClearLocalCacheAsync (line 620) no-ops when localCache is null (lines 622-625), otherwise calls localCache.ClearAsync() (line 629) inside a catch (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.
  • 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 gives GetSessionsAsync, RevokeSessionAsync and the this-device-only auth/revoke/current something 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 shares AuthenticateAsync, so token storage, the storage-failure revoke, the provider sign-in and the device report cannot drift between flows (registration comments at MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:205-211). Returning Result instead 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(), as TryAddScoped<IAuthUIService, AuthUIService>(), TryAddScoped<ISignInLinkUIService, AuthUIService>() and TryAddScoped<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 calls LogoutAsync (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 calls ChangePasswordAsync (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.razor discards the Result of 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: CreateAuthenticatedClientAsync sets a DefaultRequestHeaders Bearer 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 an Authorization header (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. The SignOutLocallyAsync doc still names "an unrefreshable session" among its callers (AuthUIService.cs:557-558), but no such caller remains in this class: only LogoutAsync and RevokeAllSessionsAsync call 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-Agent header value a native MMCA app sends, in the shape Name/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. Build therefore 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 the MmcaApp marker.
    • [Rubric §15, Best Practices & Code Quality] shows in the single Sanitize routine 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, and TokenSymbols (line 19) lists the punctuation an RFC 9110 token may hold.
    • Build(appName, appVersion, platform, osVersion) (line 29) rejects a blank appName with ArgumentException.ThrowIfNullOrWhiteSpace (line 31), tokenizes the name (falling back to App, lines 33-37) and the version, joins them as name/version or just name (lines 39-40), then builds the comment from the normalized platform and OS version (lines 42-44). The result is product (system; MmcaApp), or product (MmcaApp) when both system parts are empty (lines 46-48).
    • NormalizePlatform (line 55) renames MAUI's UI-stack names to OS names: WinUI becomes Windows and MacCatalyst becomes macOS (lines 59-64).
    • ToToken (line 71) and ToCommentText (line 77) call Sanitize (line 79): it folds accents with FormD and 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 and TokenSymbols; 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: UserAgentSummary matches on AppUserAgent.Marker rather than a literal. Sanitizing at the writer keeps the reader's parse trivially simple.
  • Where it's used: called once by MauiAppUserAgentHandler to build its cached header (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/Services/MauiAppUserAgentHandler.cs:21); read back by UserAgentSummary.ParseApp (UserAgentSummary.cs:185, 161). Pinned by AppUserAgentTests (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 DeviceMetadataReporting keeps 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 Volatile and Interlocked only.
  • Walkthrough: two int fields, _reported and _running (DeviceMetadataReporting.cs:97-98). TryBegin (lines 100-101) returns true only when _reported still reads 0 and a CompareExchange flips _running from 0 to 1, so a concurrent refresh that loses the race skips rather than waits. End (line 103) releases _running; MarkReported (line 105) sets _reported for good, after which TryBegin always refuses.
  • Why it's built this way: an int pair with Volatile/Interlocked is 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 by Gates.GetValue (DeviceMetadataReporting.cs:47, 75), opened by TryBegin (line 76), released in a finally (line 87) and closed by MarkReported after 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 by MauiDeviceMetadataReporter on native heads; the metadata it sends is the server-side DeviceMetadata record.
  • 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 returns bool instead 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. ReportAsync documents both answers (IDeviceMetadataReporter.cs:28-32): true when the server recorded the report or there is nothing to report, false when 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 is DeviceMetadataReporting.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 with AddSingleton (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/DependencyInjection.cs:102). Called through DeviceMetadataReporting by AuthUIService after each sign-in (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:531) and by SecureStoreTokenStorageService after a refresh (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/SecureStoreTokenStorageService.cs:141). Pinned by AuthUIServiceDeviceReportTests and SecureStoreDeviceBackfillTests (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) and UsesDomains (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 by ConfigurationOAuthUISettings (ConfigurationOAuthUISettings.cs:51-58). The Login page 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 has UsesDomains (line 304). Pinned by LoginOidcTests and ConfigurationOAuthUISettingsOidcTests (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 optional CodeVerifier (the RFC 7636 proof-key verifier a native head starts its attempt with, null for 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 in ReadLiveAttemptsAsync (OAuthFlowStateStore.cs:160-164), matched by State in FindCodeVerifierAsync and TryCompleteAsync (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 nullable IReadOnlyList<PendingAttempt> named Attempts (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. BeginCoreAsync writes it and reads it back to confirm the new attempt was kept (OAuthFlowStateStore.cs:105, 109-110); ReadLiveAttemptsAsync reads it, tolerating a missing value, a null list or a null entry (OAuthFlowStateStore.cs:162-163); WriteAttemptsAsync writes 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 IDeviceMetadataReporter for 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: IDeviceMetadataReporter and its own nested BackfillGate; externals ConditionalWeakTable, CancellationTokenSource, Task.WaitAsync and the [LoggerMessage] source generator.
  • Concept introduced, bounding a call you do not control. A cancellation token only works if the callee honors it. ReportAsync therefore applies the bound twice: it links the caller's token to a CancelAfter(Timeout) source and passes that to the reporter, and it also wraps the returned task in WaitAsync(Timeout, cancellationToken), so a reporter that ignores cancellation still cannot hold the caller past the bound (comment and call at DeviceMetadataReporting.cs:41-43).
    • [Rubric §13, Observability & Operability] assesses whether swallowed failures stay visible. The broad catch is deliberate (the CA1031 suppression at lines 52-54 names the reason, best-effort) and still logs through a generated LogReportFailed at Warning level (lines 58, 91-92).
  • Walkthrough:
    • Timeout = 3 seconds (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 a ConditionalWeakTable<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 into false (lines 53-62).
    • ReportOncePerProcessAsync(reporter, logger) (line 73) is the refresh backfill. It gets the gate, returns immediately when TryBegin refuses (lines 75-79: already reported, or a report is already running), otherwise runs ReportAsync with CancellationToken.None and releases the gate in a finally (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 AuthUIService and SecureStoreTokenStorageService to a one-line call each. Keying the gate by instance is what makes the "register as a singleton" requirement on IDeviceMetadataReporter load-bearing.
  • Where it's used: ReportAsync from AuthUIService.ReportDeviceAsync (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:531); ReportOncePerProcessAsync from the native token storage after a refresh, deliberately after the hydrate slot is cleared because the report authenticates through the APIClient pipeline 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 of OidcProviders). Implemented in the framework by ConfigurationOAuthUISettings, which is also the default registration; consumed by the shared Login page.
  • Concept introduced, default interface members as a safe-off baseline. All four members carry a body: the three flags return false and 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 touches IConfiguration, 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) and AppleEnabled (line 19), each declared as bool X => false, and IReadOnlyList<OidcProviderOption> OidcProviders => [] (line 22), documented as the providers configured under OAuth: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() registers ConfigurationOAuthUISettings as the default with a TryAddSingleton factory, 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 in OnInitialized folds everything into one _hasExternalProviders value (lines 305-306) that decides whether the whole external-login block renders (line 180). MMCA.ADC registers ConfigurationOAuthUISettings on 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 or null when no provider claims the domain (line 14).
  • Where it's used: registered with TryAddScoped to OidcDiscoveryUIService (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). The Login page resolves it at the click with GetService rather 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 by LoginOidcTests.

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: IDeviceMetadataReporter only.
  • Concept reinforced, the Null Object as a registration default (the same move NullNotificationScopeProvider makes for notification scoping). [Rubric §2, Design Patterns] assesses whether a pattern removes branching. The detail that matters is the answer: ReportAsync returns Task.FromResult(true) (NullDeviceMetadataReporter.cs:11), "nothing to report", so the first sign-in closes the backfill gate in DeviceMetadataReporting and 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 with MauiDeviceMetadataReporter.

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-Agent reader 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 (its Marker constant, UserAgentSummary.cs:185), DeviceMetadata (the reported name, model and platform); externals IStringLocalizer (for Describe) and string.Contains with StringComparison.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 reports null from Parse, and Describe supplies 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. Describe formats them through localizer resources (Auth.Sessions.Device.Format, Auth.Sessions.Device.AppFormat, Auth.Sessions.Device.Unknown, UserAgentSummary.cs:114-124, and Auth.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", so Edg/, EdgiOS/ and EdgA/ come before OPR/, which comes before CriOS/ and Chrome/, which come before Safari/.
    • Platforms, ten pairs with the same rule (UserAgentSummary.cs:47-59): Windows Phone before Windows, Mac OS X and Macintosh before Linux, 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 (WinUI to Windows, MacCatalyst to macOS).
    • 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's Chrome/ token is still the app (lines 107-115). Otherwise a switch over the Parse pair covers all four null combinations: both present uses the Format resource, 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 through Blank (line 163), takes the device name, and builds a detail from the model and platform with DescribeHardware (line 154), which reuses the same Format resource so the word order stays a resource (comment at line 153). Name and detail together use NamedFormat (line 146), either one alone is returned bare, and with neither it falls back to the header-only Describe (line 149), which is every browser session.
    • ParseApp (line 169) finds the first ( and the ) after it (searching only from the ( on, through AsSpan(commentStart).IndexOf(')'), lines 182-183), splits the comment on ;, and returns (null, null) unless the parts contain AppUserAgent.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 by MatchAppPlatform (lines 198-201).
    • MatchAppPlatform (line 208) checks AppPlatforms case-insensitively, then falls back to the browser Platforms table, 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, or null.
  • 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 internal because nothing outside the package should treat it as a UA parser, and Describe lives 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 admin UserSessionsTable.DescribeDevice (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/UserSessionsTable.razor.cs:69) and SignInHistoryTable (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/SignInHistoryTable.razor.cs:74). Pinned by UserAgentSummaryTests (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 state value, 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 to TimeProvider.System, OAuthFlowStateStore.cs:20, 37) for the expiry check, System.Security.Cryptography.RandomNumberGenerator to 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: BeginAsync mints the value with RandomNumberGenerator.GetHexString(32, lowercase: true) (OAuthFlowStateStore.cs:101), a cryptographically strong source, not Guid.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") and AttemptLifetime = 10 minutes (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) reports store.IsAvailable: false only 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 at 39-43).
    • BeginAsync (OAuthFlowStateStore.cs:56) and BeginWithCodeVerifierAsync (OAuthFlowStateStore.cs:70, which first rejects a null or blank verifier, line 72) both delegate to BeginCoreAsync (OAuthFlowStateStore.cs:94). That returns null immediately when storage is unavailable (96-99), otherwise mints the state, reads the live attempts, keeps the newest MaxPendingAttempts - 1 of them plus the new PendingAttempt and stores them as one PendingAttempts value under StorageKey (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 at 107-108); if the attempt was not kept (storage full, site data blocked, private mode) it throws InvalidOperationException (112-113, documented at 51-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 matches returnedState, or null when 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 calling TryCompleteAsync (doc at 76-82).
    • TryCompleteAsync (OAuthFlowStateStore.cs:132) returns false when 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 inside AttemptLifetime (141), finds the one whose state matches a non-empty returnedState exactly, 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 at 143-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 at 119-128).
    • ReadLiveAttemptsAsync (OAuthFlowStateStore.cs:160) drops null entries and anything older than AttemptLifetime, 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 the Login page (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Login.razor.cs:378, BeginAsync); the native flow begins in MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/Capabilities/Auth/MauiExternalAuthBroker.cs:91 (BeginWithCodeVerifierAsync, the store injected at line 43). Both complete on the OAuthComplete page, which reads the verifier and then consumes the attempt (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/OAuthComplete.razor:77, 79). Pinned by OAuthFlowStateStoreTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/OAuthFlowStateStoreTests.cs), with the page wiring covered by LoginOAuthAttemptTests and OAuthCompleteTests.

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 the OAuth configuration 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) and OidcReservedProviderNames (the names an OIDC section may not take); externally Microsoft.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:ClientId is populated. A WASM client must never receive a client id, so it is handed pre-computed OAuth:GoogleEnabled flags through its runtime configuration endpoint instead (ConfigurationOAuthUISettings.cs:9-12). The class accepts either signal. Generic OIDC providers follow the same two shapes under OAuth:Oidc:<Name>: a server lists a section whose ClientId is set, a WASM client lists a section flagged Enabled (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) and OidcProviders (line 32, "in configuration order"), set in the constructor (line 34), which null-guards the configuration (line 36), takes the OAuth section (line 38), evaluates each built-in provider through the shared helper (lines 39-41) and reads the Oidc child section (line 42).
    • IsProviderEnabled(oauth, provider) (line 45) is the built-in rule: parse {provider}Enabled as a bool (line 47), and return true when that flag is set or when {provider}:ClientId is 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 an OidcProviderOption with the section key as Name, a trimmed DisplayName falling back to the key (line 56), and UsesDomains (lines 51-58). The reserved check is OidcReservedProviderNames.IsReserved (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ExternalProviders/OidcReservedProviderNames.cs:22), a case-insensitive set of google, github, apple, complete, exchange and discover (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 on Enabled and ClientId; UsesDomains (line 63) is true for a UsesDomains flag or any non-blank Domains entry.
    • Because the values are read once into properties, a render pass never re-walks configuration.
  • 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}:ClientId keys the API reads are what this class reads for its GoogleEnabled / GitHubEnabled answers (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 AddUIShared with TryAddSingleton<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 at 251-256: a head that configures no OAuth keys needs no registration of its own, and a head with its own rule registers it with TryAdd before that call or AddSingleton after). MMCA.ADC registers no implementation of its own. On the server head, ClientConfigOAuthSection projects the resolved settings into the OAuth section of /client-config in exactly the shape this class reads on the WASM client: the three built-in flags plus, per OIDC provider, Enabled, DisplayName and UsesDomains, never a client id (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigOAuthSection.cs:31-44, written into the document at MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:118-121). Pinned by ConfigurationOAuthUISettingsOidcTests, OAuthUISettingsRegistrationTests and ClientConfigEndpointTests.

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 IOidcDiscoveryUIService over the API's anonymous GET auth/oauth/discover endpoint, through the named "APIClient" HttpClient (OidcDiscoveryUIService.cs:6-10).
  • Depends on: IOidcDiscoveryUIService, OidcDiscoveryResponse; externals IHttpClientFactory and System.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 to null and lets every other failure throw (the HttpRequestException is documented at OidcDiscoveryUIService.cs:16).
  • Walkthrough: ApiClientName = "APIClient" (line 13). DiscoverAsync (line 17) null-guards the address (line 19), creates the named client (line 21), sends auth/oauth/discover?email=... with the address escaped through Uri.EscapeDataString (lines 22-24), returns null on 404 Not Found (lines 28-31, reason in the comment at 26-27), calls EnsureSuccessStatusCode (line 33) and deserializes the response body (line 34).
  • Why it's built this way: internal because hosts swap the interface, not this class, and a named client from IHttpClientFactory reuses the APIClient registration 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 through IOidcDiscoveryUIService from the Login page.

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 MauiSecureTokenStore over OS SecureStorage; consumed by DirectApiTokenRefresher and by SecureStoreTokenStorageService.
  • 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 on ITokenRefresher; 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 or null (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 into DirectApiTokenRefresher (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/DirectApiTokenRefresher.cs:27) and mocked directly in DirectApiTokenRefresherTests (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 SameOriginProxyTokenRefresher on the browser heads and DirectApiTokenRefresher on MAUI; consumed by WasmTokenStorageService, ServerTokenStorageService, SecureStoreTokenStorageService and AuthUIService.
  • 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/token endpoint, 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-origin auth/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: null means 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 try around 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) and AddScoped<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 ISessionAwareTokenRefresher implementations (SameOriginProxyTokenRefresher, DirectApiTokenRefresher) and read by WasmTokenStorageService.
  • 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 definitive NoSession lets 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 is NoSession, but a 409 on a superseded token is Unavailable (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); AccessToken is null and IsUnavailable is false.
    • Unavailable (line 38), for an attempt that failed without saying anything about the session; IsUnavailable is true, so the next read should try again (lines 43-47).
    • Acquired(accessToken) (line 52) calls ArgumentException.ThrowIfNullOrWhiteSpace (line 54) and returns an outcome carrying the token, so a blank token can never masquerade as success.
    • AccessToken (line 41) is null for 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 TryAcquireAccessTokenAsync in both refreshers, and consumed in WasmTokenStorageService.HydrateAsync (WasmTokenStorageService.cs:200-202) and the handoff session services (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/HandoffSessionServices.cs). Covered through WasmTokenStorageServiceTests (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, ServerTokenStorageService and SecureStoreTokenStorageService.
  • 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 names SecureStorage, 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, never localStorage; 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), and ClearTokensAsync() 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) and NotificationHubService for the SignalR access-token provider. Test hosts substitute StubTokenStorageService and NullTokenStorageService (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, plus DefaultExpirySkew, 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.Globalization and DateTime.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 the exp claim straight from the payload segment, allocates no token handler and decodes the token once (remarks, lines 12-16), a cost tracked by JwtTokenInfoBenchmarks (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 that TryReadExpiry could read, and expiresAt > 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 returns false, biasing toward refreshing.
    • TryReadExpiry (line 55, internal so the tests can read the parsed instant) rejects a token longer than MaximumTokenLength or with no payload segment (lines 58-61). A payload whose maximum decoded length fits in 1024 bytes is decoded into a stackalloc buffer (lines 63-68); a larger one rents from ArrayPool<byte>.Shared and returns the buffer in a finally (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 the OperationStatus overload of Base64Url.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) and Skip()s every other value (line 127), so an exp nested inside another claim is never read; a JsonException is 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 past DateTimeOffset.MaxValue (lines 153-156), and floors the seconds onto DateTime.UnixEpoch (line 158). A payload with no exp at all returns false.
  • 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) and ApiUserPreferenceWriter (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/ApiUserPreferenceWriter.cs:90). Covered by JwtTokenInfoTests, which pins the 30-second value and the nested-exp case (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) and Microsoft.Extensions.Logging.ILoggerFactory, both pulled from the host's root IServiceProvider (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 whichever APIClient call 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 at Debug, not Warning (TokenHydrationWarmup.cs:52).
  • Walkthrough
    • WarmAsync(IServiceProvider services) (TokenHydrationWarmup.cs:37) null-guards services (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 resolves ITokenStorageService and calls GetAccessTokenAsync(), 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, CA1031 suppressed with a comment explaining the design) logs through the source-generated LogWarmupFailed (lines 54, 59-60) and returns normally.
  • Why it's built this way: a static partial class with 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 after MmcaCultureBootstrap.SetBrowserCultureAsync and before host.RunAsync(); the surrounding comment (Program.cs:73-77) records the cost it replaces, about 2.4s added to the first cold-start APIClient call under the old inline hydration. Covered by TokenHydrationWarmupTests (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 ITokenRefresher that can say why it returned no token. It adds one method that reports a TokenAcquisition instead of a bare nullable string.
  • Depends on: ITokenRefresher (base interface) and TokenAcquisition (the return type). Implemented by SameOriginProxyTokenRefresher and DirectApiTokenRefresher; consumed by WasmTokenStorageService and ServerTokenStorageService (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 every ITokenRefresher implementation, 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 null means "no session" (WasmTokenStorageService.cs:205-208).
  • Where it's used: the two refreshers above implement it, and WasmTokenStorageService.HydrateAsync type-tests for it (WasmTokenStorageService.cs:198). Covered by DirectApiTokenRefresherTests (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 ITokenStorageService that 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: the SessionEnded event (ISessionAwareTokenStorage.cs:18) and RenewRejectedAccessTokenAsync, which carries a default implementation (line 37).
  • Depends on: ITokenStorageService (base interface); the "ended" signal is the definitive TokenAcquisition.NoSession outcome. Implemented by WasmTokenStorageService (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 MAUI SecureStoreTokenStorageService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/SecureStoreTokenStorageService.cs:59); consumed by JwtAuthenticationStateProvider (the event) and AuthDelegatingHandler (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 as ISessionAwareTokenRefresher. 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 returning null (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). RenewRejectedAccessTokenAsync closes 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 raises SessionEnded, 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, or null (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: JwtAuthenticationStateProvider type-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); its OnSessionEnded handler forgets the list-page state and calls NotifyUserLogout (lines 145-151). AuthDelegatingHandler reports a 401 to the storage that owns the bearer: ReportRejectedAsync falls 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 calls RenewRejectedAccessTokenAsync (line 328), skipping a token that is itself the product of a renewal (lines 312-316). AuthenticatedServiceBase reads the same capability as StorageRenewsRejectedTokens, so a replaying caller does not refresh a second time (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:106). SessionEnded is raised by WasmTokenStorageService.HydrateAsync (WasmTokenStorageService.cs:231), by ServerTokenStorageService (ServerTokenStorageService.cs:295) and by SecureStoreTokenStorageService.RaiseSessionEnded (SecureStoreTokenStorageService.cs:236). Pinned by WhenTheStorageReportsTheSessionEnded_NotifiesAnonymous and WhenTheStorageReportsTheSessionEnded_ForgetsTheListPageStateAndNotifiesAnonymous (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/JwtAuthenticationStateProviderTests.cs:137,152); the renewal contract by the shared ApiUnauthorized_* cases (MMCA.Common/Tests/Shared/UI/TokenStorageServiceTestsBase.cs:327,347,378) and end to end by SessionBearerRenewalTests (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/token endpoint and reports what comes back as a TokenAcquisition.
  • Depends on: ISessionAwareTokenRefresher (the contract), TokenAcquisition, IJSRuntime and JsInteropFailure for the catch filter, plus the mmcaAuthSession helper in MMCA.Common/Source/Presentation/MMCA.Common.UI/wwwroot/mmca-auth-cookie.js:32, whose getToken issues the fetch (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 is SessionCookieEndpoints, which maps POST /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) invokes mmcaAuthSession.getToken through interop (line 28) and maps a blank result to TokenAcquisition.NoSession, anything else to Acquired (line 29). The remarks (lines 12-16) record the script contract: it answers null only 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 on JsInteropFailure.IsUnavailable (line 31), the framework's one shared definition of "interop could not do its job": InvalidOperationException, JSDisconnectedException, JSException or OperationCanceledException (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/JsInteropFailure.cs:27-31). Any of those is reported as Unavailable, 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=Lax plus Sec-Fetch-Site check 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 plain string? shim still satisfies the ITokenRefresher contract.
  • 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 by WasmTokenStorageService and ServerTokenStorageService. Covered by SameOriginProxyTokenRefresherTests (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 the ISessionAwareTokenStorage capability (SecureStoreTokenStorageService.cs:59). It is the freshness-checking layer over a persistent ISecureTokenStore, the device counterpart of WasmTokenStorageService (class doc, lines 7-12).
  • Depends on: ISecureTokenStore and ITokenRefresher (required constructor parameters, lines 56-57); optionally IDeviceMetadataReporter and ILogger<SecureStoreTokenStorageService> (lines 58-59); JwtTokenInfo for the freshness check, ISessionAwareTokenRefresher through a runtime type test (line 249), DeviceMetadataReporting for the backfill report; externals System.Threading.Lock, Interlocked and Volatile.
  • 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 are static (lines 61-74), and the class doc gives the reason (lines 30-38): the service is scoped, and the AuthDelegatingHandler built by IHttpClientFactory resolves 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: StateManagementConventionTests lists them as the only allowed mutable statics of the class, with the rationale that only AddCommonMauiTokenStorage() 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: HydrateSync and SessionEndedSync (lines 61, 63), the two Locks; _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: add and remove (lines 81-107) write the static list under SessionEndedSync and 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 same APIClient pipeline, 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) and ClearTokensAsync (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 under HydrateSync with ??= (line 217); ClearHydrateIfCurrent (line 225) clears it only on ReferenceEquals (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, its null passed 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), calls TryAcquireAccessTokenAsync (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 returns null without touching it (lines 265-270). Only then does it clear the store, bump the version and raise SessionEnded (lines 272-274).
  • 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 that DirectApiTokenRefresher posts through the APIClient pipeline and opts out with AuthDelegatingHandler.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 of MauiSecureTokenStore. Covered by SecureStoreTokenStorageServiceTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/SecureStoreTokenStorageServiceTests.cs:18), including the cleared pair with one SessionEnded (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 by SecureStoreDeviceBackfillTests (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 RenewRejectedAccessTokenAsync path never runs the device report, which only GetAccessTokenAsync triggers (lines 139-142). Because the statics are process-wide, every test class that drives it joins the SecureStoreTokenStorageCollection (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 the ISessionAwareTokenStorage capability (WasmTokenStorageService.cs:30). The access token lives in memory only and is hydrated on demand from the HttpOnly cookies; there is no localStorage anywhere in it.
  • Depends on: ISessionCookieSync and ITokenRefresher (constructor parameters, WasmTokenStorageService.cs:27-30), plus JwtTokenInfo for the freshness check; optionally ISessionAwareTokenRefresher (a runtime type test in HydrateAsync, line 198); externals System.Threading.Lock and TimeProvider.
  • Concept introduced, single-flight hydration. Several callers can ask for a token in the same instant: the AuthDelegatingHandler on an outgoing request, the JwtAuthenticationStateProvider during a render, and NotificationHubService'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-flight Task, 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 null from memory for AnonymousGrace, 15 seconds (line 33), checked in GetAccessTokenAsync (lines 66-69). A transient failure is never remembered, and SetTokensAsync resets 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 by SetTokensAsync and twice by ClearTokensAsync. HydrateAsync captures 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 raises SessionEnded (line 57) so the auth state goes anonymous (class doc, lines 20-21). A plain refresher's null still 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.
  • Walkthrough:
    • AnonymousGrace, 15 seconds (WasmTokenStorageService.cs:33). The class holds no skew of its own: the freshness check passes JwtTokenInfo.DefaultExpirySkew, 30 seconds, to JwtTokenInfo.IsFresh (line 61).
    • _hydrateSync (line 35), the Lock; _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 the volatile _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 the ISessionAwareTokenStorage event.
    • 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 (or null) 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 returns null without 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 because HydrateAsync reaches its first await immediately so nothing slow runs under the lock (lines 71-74). It then awaits the shared task (line 84) and, in a finally, clears _hydrateInFlight only 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), the ISessionAwareTokenStorage renewal: it throws on a blank token (line 108), then under _hydrateSync returns 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 same ReferenceEquals guard (line 176), so concurrent 401s for one token share one refresh, and a definitive "no session" raises SessionEnded through HydrateAsync (remarks, lines 101-105).
    • GetRefreshTokenAsync() (line 128) returns null unconditionally, 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 through ISessionCookieSync.SyncAsync (line 141); the comment records that the refresh token transits JS only for that same-origin POST (lines 137-140). A false from the cookie write throws InvalidOperationException (lines 141-144), after the in-memory token is set, so AuthUIService reports Auth.TokenStorageUnavailable instead 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 a false from ClearAsync is discarded; the comment points a caller that needs proof the session ended at IAuthUIService.RevokeAllSessionsAsync (lines 152-154). A logout therefore never raises SessionEnded.
    • HydrateAsync() (line 184) captures _tokenVersion first (line 194), then branches on the refresher's capability. When it is an ISessionAwareTokenRefresher (line 198) it calls TryAcquireAccessTokenAsync, keeps AccessToken in a local, reads IsUnavailable and computes definitiveNoSession as a null token that is not unavailable (lines 200-203); otherwise it falls back to ITokenRefresher.AcquireAccessTokenAsync, where a null means "no session" for the grace but never counts as definitive (line 207). If the version moved meanwhile it returns the current _accessToken and 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 _sessionHeld is set clears it and raises SessionEnded, the token already gone from memory (lines 226-232). See TokenAcquisition.
  • 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 ServerTokenStorageService in MMCA.Common.UI.Web. The two share the skew (both pass JwtTokenInfo.DefaultExpirySkew), the Lock, and the same single-flight shape; the server one adds an HttpContext branch for the prerender pass, and both implement ISessionAwareTokenStorage. The cookie-only storage model is ADR-022; the token lifecycle is ADR-051. The MAUI head's counterpart is SecureStoreTokenStorageService, 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 by WasmTokenStorageServiceTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Auth/WasmTokenStorageServiceTests.cs:16), which inherits the shared TokenStorageServiceTestsBase cases: 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). SessionBearerRenewalTests drives 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 an ITokenRefresher). It reads the token pair out of OS SecureStorage, exchanges it against the API's cross-origin auth/refresh endpoint, and writes the rotated pair back, reporting the outcome as a TokenAcquisition.
  • Depends on: ISecureTokenStore (deliberately, not ITokenStorageService), AuthDelegatingHandler (for its SkipBearer request option), RefreshTokenRequest and AuthenticationResponse from MMCA.Common.Shared.Auth; externals IHttpClientFactory, System.Net.Http.Json and System.Text.Json (for JsonException).
  • 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 to SameOriginProxyTokenRefresher, 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; taking ITokenStorageService instead 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 APIClient carries AuthDelegatingHandler, which reads the storage service for a bearer. The refresh POST therefore sets AuthDelegatingHandler.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 NoSession to 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) is Unavailable, as SameOriginProxyTokenRefresher reports 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 over TryAcquireAccessTokenAsync (line 52) that returns only .AccessToken, which keeps the plain ITokenRefresher contract intact. The Try method is a straight line of early returns, each producing a TokenAcquisition rather than an exception:
    • read both tokens from the store (lines 54-55), and return NoSession when 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 an HttpRequestMessage POSTing a RefreshTokenRequest carrying both tokens as JsonContent to the relative auth/refresh (lines 62-66), mark it SkipBearer (line 67), and send it inside a try (lines 69-82);
    • return Unavailable when the send throws HttpRequestException (line 74) or an OperationCanceledException the caller did not request, meaning an HttpClient.Timeout (lines 78-82), then hold the response in a using var (line 84);
    • on HttpStatusCode.Conflict (lines 86-89) delegate to ReadSupersededOutcomeAsync (line 123), which re-reads the store: if another refresh in this process already stored a different non-blank pair it returns Acquired with that access token, otherwise Unavailable with the pair left as it was (lines 125-132);
    • on any other non-success status (lines 91-96) return NoSession only for 400, 401 or 403, which is how a revoked or reused refresh token arrives, and Unavailable for the rest;
    • deserialize an AuthenticationResponse inside a try (lines 98-108): a 2xx whose body is not the token document (a proxy or portal page, a truncated or version-skewed body) throws JsonException or NotSupportedException, which is caught and answered Unavailable, because such a body says nothing about the session and the pair is kept for a later retry (lines 103-107);
    • return NoSession when the access token came back blank (lines 110-113);
    • persist the rotated pair through ISecureTokenStore.SetTokensAsync and return TokenAcquisition.Acquired with the new access token (lines 115-116).
  • 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 HttpRequestMessage rather than PostAsJsonAsync is what gives the call an Options bag to carry SkipBearer. The using var httpClient (line 62) and the relative Uri both lean on the named client configured once in AddUIShared, 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 by DirectApiTokenRefresherTests (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 the SkipBearer mark 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 DelegatingHandler that stamps the active UI culture onto every outgoing API call as an Accept-Language header, 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, and System.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 SendAsync override (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() before Add(...) (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.
  • 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/set endpoint 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 treat ApplyAsync as 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.All is ignored by the underlying mechanism rather than throwing (ICultureApplier.cs:19-22), and an empty returnPath falls 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 Router renders the not-found page. The interface lets one shared component serve both heads.
  • Where it's used: injected by the shared CultureSwitcher component, 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:6 and CultureSwitcher.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:15 and Login.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) and EmailNotConfirmed (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), only SecondFactorRequired counts as fully handled with no message (Login.razor.cs:131), and EmailNotConfirmed records 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/set endpoint, 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 by MapCultureEndpoint() (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationExtensions.cs:83, the MapGet("/culture/set", ...) at WebApplicationExtensions.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 with ArgumentException.ThrowIfNullOrWhiteSpace (EndpointCultureApplier.cs:23).
    • It falls back to "/" for an empty return path (EndpointCultureApplier.cs:25) and builds the URL with Uri.EscapeDataString on 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 returns Task.CompletedTask (EndpointCultureApplier.cs:31): the method is synchronous in substance and Task-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/set through the Blazor Router, match no page and render the not-found page, which is exactly why MAUI heads register their own applier after AddUIShared.
  • 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.js module in the package's wwwroot. Externals: IJSRuntime and CultureInfo.
  • 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 with allowPseudoLocale: false, so the pseudo locale is never accepted through it. The real work is in SetBrowserCultureAsync(IJSRuntime jsRuntime, bool allowPseudoLocale) (MmcaCultureBootstrap.cs:57), null-guarded at MmcaCultureBootstrap.cs:59. A Development host passes builder.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.js under an await 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 / restore pair (MmcaCultureBootstrap.cs:61 and MmcaCultureBootstrap.cs:67). The suppression comment gives the reason: the code runs in the WASM Program.cs before 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). First getCulture, whose JS side parses the .AspNetCore.Culture cookie's uic= 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, getBrowserLanguages returns navigator.languages (or [navigator.language]), the list the browser turns into the Accept-Language header the server falls back to (culture.js:29). Third, SupportedCultures.Default.
    • MatchFirst (MmcaCultureBootstrap.cs:79) tries at most MaxBrowserLanguagesToTry browser languages, the constant 3 at MmcaCultureBootstrap.cs:30, chosen to equal the server's AcceptLanguageHeaderRequestCultureProvider.MaximumAcceptLanguageHeaderValuesToTry default 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 via ParentOf (MmcaCultureBootstrap.cs:106, which strips the last - subtag), returning the first that SupportedCultures.IsSupported accepts, or that SupportedCultures.IsPseudoLocale matches when allowPseudoLocale is true (MmcaCultureBootstrap.cs:95-96). So es-ES resolves to es, but only parents count, never siblings: en-GB does not resolve to en-US, exactly as on the server. The predicate is at MMCA.Common/Source/Core/MMCA.Common.Shared/Globalization/SupportedCultures.cs:35, the pseudo-locale check at SupportedCultures.cs:76, the "qps-Ploc" constant at SupportedCultures.cs:28, the allowlist at SupportedCultures.cs:18, and the "en-US" default at SupportedCultures.cs:12.
    • It then assigns only CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture (MmcaCultureBootstrap.cs:70-71), never CurrentCulture/CurrentUICulture directly: setting the defaults makes every subsequently created thread inherit the culture, which is what a later switch needs in order to take effect.
  • 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 passing false on any host that serves a WebAssembly client (WebApplicationExtensions.cs:89-95), and the suppression comment above the cookie write (WebApplicationExtensions.cs:109) names MmcaCultureBootstrap.SetBrowserCultureAsync as 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 after builder.Build() and before host.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:69 and MMCA.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 Subscriptions table. Implements IDisposable.
  • 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 nullable Action? 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 later Subscribe replaced leaves the successor in place.
  • 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 Subscription identifiers 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's IJSRuntime in the constructor, ViewerTimeZone.cs:30) and the time-zone.js module named at ViewerTimeZone.cs:24. Implements IAsyncDisposable.
  • 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-side ToLocalTime() would use the server's zone; this service asks the browser instead.
  • Walkthrough
    • Zone (ViewerTimeZone.cs:36) defaults to TimeZoneInfo.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 invokes getTimeZone (ViewerTimeZone.cs:64-65). JS side: MMCA.Common/Source/Presentation/MMCA.Common.UI/wwwroot/time-zone.js:6 returns the Intl.DateTimeFormat zone id, or null when the browser cannot say.
    • Failure handling is split by whether a retry could help. InvalidOperationException (SSR prerender, no interop yet), JSDisconnectedException and OperationCanceledException return false without marking resolved (ViewerTimeZone.cs:67-80); a JSException means 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, assigns Zone through the private ResolveZone, and returns true (ViewerTimeZone.cs:87-89). It returns true even when the zone stays UTC, because the first resolution is what turns Format output 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) reads Utc and Unspecified kinds as UTC (a deserialized value often arrives unspecified) and normalizes Local first, then calls TimeZoneInfo.ConvertTimeFromUtc. Format (ViewerTimeZone.cs:118) returns string.Empty while IsResolved is false (prerender, and the first interactive render before EnsureResolvedAsync ran); once resolved it formats the converted value with CultureInfo.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 EnsureResolvedAsync keeps the service free of render coupling: the page calls it from OnAfterRenderAsync on its first render and decides whether to call StateHasChanged. 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 by NotificationList.razor.cs:30, NotificationInbox.razor.cs:37 and Sessions.razor.cs:36 under MMCA.Common.UI/Pages/ and by Components/Auth/UserSessionsTable.razor.cs:32, plus ADC pages such as MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Pages/Points/MyPoints.razor.cs. Covered by MMCA.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 IHttpClientFactory handler 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: the ConditionalWeakTable key 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 static ConditionalWeakTable<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 with AddOrUpdate (MultiFactorRequiredSignal.cs:33), so a later subscription replaces an earlier one (MultiFactorRequiredSignal.cs:15-17), and returns it as an IDisposable (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 unless HasSubscriber is true and the response is Problem Details (AuthDelegatingHandler.cs:290-293), buffers the body, and calls Raise when 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 by MMCA.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 own IAuthUIService implementation 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) and DisableAsync(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 LocalizedErrorMessage extension 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) and TwoFactorRequiredReason "two-factor-required" (LoginRefusals.cs:35), the reason query values the two-factor page sends to the sign-in page. The class holds no error-code constants of its own: callers pass the shared AuthErrorCodes values, such as AuthErrorCodes.TwoFactorRecentSignInRequired (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthErrorCodes.cs:66).
    • Classify(Result) (LoginRefusals.cs:40) returns Other unless there is exactly one error (list pattern [var error], LoginRefusals.cs:44-46), then maps TwoFactorRequired, TwoFactorInvalid and EmailNotConfirmed to 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 with AuthErrorCodes.TwoFactorRecentSignInRequired (TwoFactorAccount.razor.cs:355, TwoFactorEnrollmentPanel.razor.cs:102).
    • ReasonNoticeKey(reason) (LoginRefusals.cs:71) maps the two reasons to Auth.Login.TwoFactorEnabledNotice and Auth.Login.TwoFactorRequiredNotice and 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).
  • 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 uses HasCode/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:102 and TwoFactorEnrollmentPanel.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-factor endpoints (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 through ProblemDetailsResultReader with the API's error codes intact, and transport faults become failures through HttpResultExecutor. [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
    • Endpoint is "auth/two-factor" (TwoFactorUIService.cs:29).
    • GetStatusAsync (TwoFactorUIService.cs:32) is the only call wrapped in RetryPolicy.ExecuteAsync (TwoFactorUIService.cs:37).
    • BeginEnrollmentAsync (TwoFactorUIService.cs:47) POSTs enrollment with no body (TwoFactorUIService.cs:52-53).
    • ConfirmEnrollmentAsync (TwoFactorUIService.cs:61-62) and RegenerateRecoveryCodesAsync (TwoFactorUIService.cs:65-66) share the private PostCodeAsync (TwoFactorUIService.cs:92), which rejects a blank code (TwoFactorUIService.cs:94) and posts a trimmed TwoFactorCodeRequest, reading back the recovery codes (TwoFactorUIService.cs:100-106).
    • DisableAsync (TwoFactorUIService.cs:69) applies the same blank-code guard (TwoFactorUIService.cs:71) and posts to disable, reading a non-generic Result (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>() by AddTwoFactorUI() (MMCA.Common/Source/Presentation/MMCA.Common.UI/TwoFactor/DependencyInjection.cs:27). Covered by MMCA.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 Uri and string. 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 a Uri rather than a string, so callers that need text do the ToString() themselves, and the doc comment gives /sessions/42 as 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:BaseUrl key pinned in the head's embedded configuration (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/Services/MauiPublicLinkBuilder.cs:17 and MauiPublicLinkBuilder.cs:28-32), and throws InvalidOperationException at construction when the key is missing, so a misconfigured head fails at startup instead of shipping unusable links.
  • 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 calls AddCommonMauiPublicLinkBuilder() after AddUIShared (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/DependencyInjection.cs:174-175, invoked at MMCA.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 SharePageButton component (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Sharing/SharePageButton.razor:4 and SharePageButton.razor:43), the shared QrCodeButton component (QrCodeButton.razor:1 and QrCodeButton.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:26 and SpeakerQr.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's tryGoBack() 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). Handled is true when the WebView's history stack contained a previous entry and history.back() fired (MauiBackNavigationBridge.cs:9-13); AtRoot is true when 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 record buys 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 host ContentPage.OnBackButtonPressed handlers.

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 returnUrl query 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.com so the victim lands on an attacker site after authenticating, a classic phishing amplifier. Sanitize rejects 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 returning fallback on failure:
    • null or empty (lines 20-23);
    • must start with /, which rules out scheme-prefixed absolutes such as http:// and javascript: (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.com in 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 returnUrl they read from the query string; SignOutNavigator.SignOutAsync also runs its destination through it before navigating (SignOutNavigator.cs:71), and RedirectToLogin.LoginPathFor sanitizes 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.NavigationManager and NavigationOptions (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 the Referer header of any outbound request; NavigationOptions.HistoryEntryState travels 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) calls NavigateTo(path, new NavigationOptions { HistoryEntryState = prefix + email }).
    • Read(navigation, out bool existingAccount) (AuthEmailPrefill.cs:33-52) reads navigation.HistoryEntryState, returns null when there is none (:38-41), sets existingAccount and strips the prefix when the existing-account tag matches (:43-47), strips the plain prefix otherwise (:49-51), and returns null for any state it did not write. Both comparisons are StringComparison.Ordinal. NonEmpty (:54) turns a blank remainder into null, so a page never prefills an empty string over its own default.
  • 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 internal holds 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, and MMCA.Common.UI must 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 answer false whenever there is no request to read (:19-22).
  • Why it's built this way: the same head-override composition used across the UI layer. AddUIShared registers the always-false default with TryAddSingleton (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:259-262), and the Blazor Web host's AddMmcaBlazorWebHost replaces it with the request-reading one (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:139), which compares HttpContext.Response.StatusCode to 403 (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Services/HttpContextForbiddenReExecutionDetector.cs:31-32).
  • Where it's used: injected by the shared NotFound page (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/NotFound.razor:6), which renders the Forbidden view when it answers true and the not-found content otherwise (NotFound.razor:16-28). MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Pages/NotFoundTests.cs covers both branches, and HttpContextForbiddenReExecutionDetectorTests covers 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.RangeAttribute and Microsoft.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 to DefaultCapacity; when the buffer is full each new entry drops the oldest (:15-18).
    • MinimumLevel (:26), defaulting to LogLevel.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, BCL DateTimeOffset and CultureInfo.
  • Concept introduced: none; a positional record used as an immutable value.
  • Walkthrough: the five positional members (InAppLogEntry.cs:15-20), where Exception is a string? rather than an Exception object, so the buffer holds no live exception graph. The ToString() override (:27-33) is the text that is copied and shared (:22-26): an invariant-culture line of the UTC timestamp as yyyy-MM-dd HH:mm:ss.fff with a Z suffix, 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.InvariantCulture and 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 InAppDiagnosticsLog component.

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/42 into 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, so NavigationManager.BaseUri is 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 from BaseUri there 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 shared SharePageButton and QrCodeButton stay 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 a NavigationManager.
  • Walkthrough
    • One readonly field, _navigationManager (line 13), assigned by an expression-bodied constructor (lines 17-18). The class is sealed and holds no other state, so a scoped instance costs a reference.
    • BuildAbsolute(string relativePath) (line 21) rejects a blank path outright with ArgumentException.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 inner Uri forces 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 to http://localhost/sessions/42 against 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).
  • Why it's built this way: AddUIShared registers this implementation with TryAddScoped (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, SharePageButton and QrCodeButton, 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: BuildAbsolute performs no allow-list check on relativePath, 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 the nav-interop.js module 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, from ContentPage.OnBackButtonPressed via BlazorWebView.TryDispatchAsync, so the call runs on the renderer thread with access to the WebView's IJSRuntime (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 an await using module reference (line 47) and invokes its tryGoBack() 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 value new BackNavigationResult(Handled: false, AtRoot: true): InvalidOperationException when Blazor is not yet hydrated (lines 51-55), JSDisconnectedException (lines 56-59, which also covers a dispose on a torn-down circuit), and JSException (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 its OnBackButtonPressed override (MainPageBase.cs:216); the returned BackNavigationResult tells the host whether to exit the app.
  • Caveats / not-in-source: the nav-interop.js tryGoBack() implementation and the MainPageBase dispatch 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 ValidateDataAnnotations would, without reflection (InAppDiagnosticsOptionsValidator.cs:5-8).
  • Depends on: InAppDiagnosticsOptions; [OptionsValidator] and IValidateOptions<T> from Microsoft.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)] on Capacity (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/InAppDiagnosticsOptions.cs:19).
  • Where it's used: registered by AddInAppDiagnostics with TryAddEnumerable, 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 NotFound page renderable on every head without a server dependency, and registering it with TryAddSingleton (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:262) leaves the Blazor Web host free to Replace it 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 what AddUIShared resolves (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>); BCL System.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): a Lock gate, the entry array, _next (the write index) and _count.
    • The constructor (:20-26) reads Capacity from options, rejects anything below 1 with ArgumentOutOfRangeException.ThrowIfLessThan (:24) and allocates the array once.
    • Capacity (:29) is the array length; Count (:32-41) reads _count under the lock.
    • Add (:45-58) writes at _next, advances it modulo the length, and increments _count only 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 with Environment.NewLine, using each entry's ToString().
  • 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 shared InAppDiagnosticsLog component (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 ILogger that 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
    • BeginScope returns null (InAppLoggerProvider.cs:46-47): scopes are not recorded.
    • IsEnabled (:49-50) is true for any level other than None at 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 with TimeProvider.GetUtcNow(), the category, the formatted message and, when present, a described exception (:66-71).
    • DescribeException (:74-88) walks the InnerException chain, 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 ILoggerProvider that records log entries at or above InAppDiagnosticsOptions.MinimumLevel into 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.Logging and Microsoft.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 every ILogger call out to each registered ILoggerProvider, 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 reads MinimumLevel once (: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).
  • 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 AddInAppDiagnostics with TryAddEnumerable (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Diagnostics/DependencyInjection.cs:46); covered by MMCA.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 forced NavigateTo", which races.
  • Depends on: IAuthUIService (the sign-out it runs) and NavigationManager through the primary constructor (SignOutNavigator.cs:30); ReturnUrlProtector sanitizes the destination (:71); Result from MMCA.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 into RedirectToLogin, 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, RedirectToLogin stands down and this navigator issues the one navigation itself (:16-17). The component resolves the navigator optionally and returns early when IsSigningOut is 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), internal with a private setter: the claim, readable only inside the package, by RedirectToLogin.
    • SignOutAsync(string destination) (:47-54), the public entry point, wraps authService.LogoutAsync() in a delegate that answers Result.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 with ReturnUrlProtector.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 failure Result releases it and returns the failure with no navigation (:85-89). On success it calls NavigateTo(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 TryAddScoped by AddUIShared (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:199). The shared layout and menu sign-outs call SignOutAsync("/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 over RevokeAllSessionsAsync (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor.cs:246). SignOutNavigatorTests pins 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 IsSigningOut stands 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 one extension(IServiceCollection) block)

  • What it is: the opt-in registration for the in-app diagnostics log, one method, AddInAppDiagnostics (DependencyInjection.cs:27). This is the Services.Diagnostics class of that name, separate from the MMCA.Common.UI composition root that holds AddUIShared.
  • Depends on: InAppDiagnosticsOptions, InAppDiagnosticsOptionsValidator, InAppLogBuffer, InAppLoggerProvider; Microsoft.Extensions.DependencyInjection.Extensions and Microsoft.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>(), applying configure when 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 ILoggerProvider through TryAddEnumerable (:46). The comment (:43-45) explains why no ILoggingBuilder is needed: the logger factory takes every ILoggerProvider in the container, which is all AddProvider does, and the enumerable TryAdd keeps 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 of AddUIShared because 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, a Dictionary<string, int> and a HashSet<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 watching event: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, because Snapshot() is the replay list the hub service re-joins after a reconnect, and ResetJoined() marks every held key as needing that re-join.
    • [Rubric §14, Testability] shows in the visibility choice: the type is internal with an InternalsVisibleTo for 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, since JoinChannelAsync starts a real HubConnection, 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-join Dictionary<string, int> (line 31, whose default string comparer is ordinal, matching the hub's group-name semantics, lines 29-30), and the _joined HashSet<string> of held keys the server confirmed joining on the current connection (line 34).
    • AddRef(channelKey) (line 41) reads the current count, writes current + 1, and returns current == 0, so only the 0-to-1 transition reports true (lines 45-47). Whether the server must be invoked is no longer read from that result; NeedsServerJoin answers it.
    • Release(channelKey) (line 60) returns false for a key that was never joined (lines 64-67), removes both the count entry and the joined flag and returns true when the decrement reaches zero or below (lines 70-75), and otherwise stores the decremented value and returns false (lines 77-78). The count therefore never goes negative and an unpaired leave is a no-op.
    • NeedsServerJoin(channelKey) (line 88) is true when 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 _joined only 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/LeaveChannel mapping 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 on Reconnected because 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. AddRef in JoinChannelAsync (NotificationHubService.cs:344, its result discarded, deliberately counted before the connection is started at line 346 so the replay inside StartAsync sees it), NeedsServerJoin gating the server invoke there (line 352) and MarkJoined after it succeeds (line 357); Release in LeaveChannelAsync (line 382); and ResetJoined, Snapshot and MarkJoined in RejoinChannelsAsync (lines 842, 845, 858). Covered directly by ChannelReferenceCounterTests (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 _channelSubscriptions dictionary 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-375 states 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 a CancellationToken (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. GetCurrentScopeDisplayNameAsync is 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 is MMCA.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 ScopeKey travelling with a send.
  • Where it's used: injected into NotificationInboxService (NotificationInboxService.cs:32) and PushNotificationService (PushNotificationService.cs:18); registered with TryAddScoped against NullNotificationScopeProvider by AddNotificationUI() (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 to TimeProvider.System, NotificationState.cs:18,21), System.Threading.Lock, and three EventHandler events. 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. NotificationState is 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) asks IsStale(maxAge) instead of re-reading the API every time the trigger happens to fire (lines 77-85). The subtle rule is stamped in SetUnreadCount: 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 a TimeProvider? parameter defaulting to TimeProvider.System (lines 14-18,21), so a test drives IsStale with a fake clock while an existing host keeps the previous no-argument constructor shape.
  • Walkthrough: members in teaching order.
    • Fields: the Lock _pollerSync (line 20), the resolved _timeProvider (line 21), and the nullable _pollerOwner (line 29).
    • UnreadCount with a private setter (line 32) and LastFetchedUtc with a private setter (line 41).
    • Three events: OnChange when the count changes (line 44), OnRefreshRequested when a real-time notification arrives and the badge should refetch the authoritative count (lines 46-50), and OnPollerSlotFreed when the active-poller slot becomes free so a surviving bell can take polling over (lines 52-57).
    • SetUnreadCount(int) (lines 61-75) stamps LastFetchedUtc first (line 66), returns early when the value is unchanged (lines 68-71), and otherwise assigns and raises OnChange.
    • IsStale(TimeSpan maxAge) (lines 84-85) is true when there is no stamp at all or the stamp is older than maxAge; 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 raises OnChange. RequestRefresh() (line 102) raises OnRefreshRequested.
    • TryRegisterPoller(object owner) (lines 111-125) null-guards, takes _pollerSync, and returns false only when a different owner already holds the slot (lines 117-120); a caller that already holds it gets true again, 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. OnPollerSlotFreed is 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.
  • 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 on OnPollerSlotFreed to take over, and gates its navigation refresh on IsStale (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 by NotificationStateTests (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: IRetryPolicy and RetryContext from Microsoft.AspNetCore.SignalR.Client, HttpRequestException, HttpStatusCode and Random.Shared (BCL). Its primary constructor takes an optional Func<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 within MaxDelay of 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 exceeds MaxDelay, 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 to Random.Shared.NextDouble (line 52); the CA5394 suppression 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 the const 0.3: the largest share of a delay the jitter takes off.
    • MaxDelay (line 38) is internal static at 30 seconds so the hub's restart loop reuses the same cap (NotificationHubService MaxRetryDelay, 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 returns null (stop) when IsAuthenticationRefused(retryContext.RetryReason) (lines 60-63). On the first retry (PreviousRetryCount == 0) it returns FirstRetrySpread * _sample(), somewhere in the first second (lines 65-68). Otherwise it indexes WarmUp by PreviousRetryCount, falls back to MaxDelay once the warm-up is spent, and returns that base through Jitter (lines 70-73).
    • Jitter(delay, sample) (line 84) is internal 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 its InnerException chain looking for an HttpRequestException whose StatusCode is Unauthorized or Forbidden (lines 95-100), and for an AggregateException it 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).
  • 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. Jitter is static for 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 at UnboundedReconnectPolicy.cs:76-80). The sample source is injectable so the jittered schedule stays deterministic under test. It is internal sealed because 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 settable JitterSample (line 139). Its IsAuthenticationRefused is called again from the start loop (NotificationHubService.cs:298), its Jitter from the start-retry backoff (line 318) and the restart backoff (line 744), and MaxDelay is the default of MaxRetryDelay (line 131). Covered by NotificationHubServiceTests (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 for Jitter itself).

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 override GetCurrentScopeDisplayNameAsync, 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 by AddNotificationUI, 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 with TryAddScoped (MMCA.Common/Source/Presentation/MMCA.Common.UI/Notifications/DependencyInjection.cs:24), and the source comment states the reason: TryAdd means an app that registers its own provider wins whichever order the two registration calls run in (lines 22-23). A plain AddScoped would 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 the UserNotificationIdentifierType alias (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 raw HttpClient; 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 is Task<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 a Result<PagedCollectionResult<UserNotificationDTO>> (line 14); GetUnreadCountAsync returns Result<int> (line 23); MarkReadAsync(id, ct) (line 26) and MarkAllReadAsync(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) returns Result<PushNotificationDTO> for the created notification (line 13); GetHistoryAsync(pageNumber = 1, pageSize = 10, ct) returns Result<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/inbox WebAPI 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 answers 401.
  • Depends on: AuthenticatedServiceBase (its base, supplying CreateAuthenticatedClientAsync, CreateClientWithToken, the shared static RetryPolicy, StorageRenewsRejectedTokens and ReadRenewedAccessTokenAsync), 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 own ProblemDetails errors), 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.ExecuteAsync on the outside (exceptions become failed Results; the four public methods are expression-bodied and return that Task directly rather than wrapping it in async/await, lines 42-115), the shared RetryPolicy in the middle, and ProblemDetailsResultReader.ReadAsync at 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.
  • Walkthrough:
    • A primary constructor forwards IHttpClientFactory and ITokenStorageService to AuthenticatedServiceBase and keeps scopeProvider and the optional tokenRefresher (NotificationInboxService.cs:29-34); Endpoint is the constant "notifications/inbox" (line 36); _refreshSync and _refreshInFlight (lines 38-39) hold the single-flight token refresh. The refresher's default of null is 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 through SendReadWithAuthRefreshAsync (lines 54-55), and reads a Result<PagedCollectionResult<UserNotificationDTO>> (lines 57-58).
    • GetUnreadCountAsync (lines 63-78) resolves the scope with "?" (line 67), goes through the same read path, and reads a Result<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-all with 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 cancellationToken into 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 a using for the first client, recording the bearer that client carried as sentToken (lines 135-139, line 137), returns the response untouched when it is not a 401 (lines 141-144), and otherwise asks ReplayTokenAsync for a token (line 146). A null answer returns the original 401 (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. When StorageRenewsRejectedTokens is true (the token storage is an ISessionAwareTokenStorage, MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:106) it returns ReadRenewedAccessTokenAsync(rejectedToken) (lines 171-174), which reads what the storage holds now and yields null when 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 to TryAcquireRefreshedTokenAsync, and only when a refresher is registered; with none it answers null (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 _refreshSync it starts AcquireRefreshedTokenAsync only when no refresh is in flight or the stored one has completed (lines 199-207), under CancellationToken.None so one caller giving up cannot cancel the refresh another is awaiting (comment at lines 194-197). Each caller stops waiting on its own token via WaitAsync (line 211), and the finally clears 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 returns null for 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.
  • 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; implements IDisposable.
  • Concept introduced, subscription-as-token. This is the classic "return an IDisposable to unsubscribe" pattern. Instead of exposing an Unsubscribe(handler) method (which forces callers to hold and match the exact delegate), OnChannelEvent returns a ChannelSubscription; 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, channelKey and handler (NotificationHubService.cs:921), exposing ChannelKey (line 414) and Handler (line 416) as get-only properties. Dispose() (line 418) simply calls owner.RemoveSubscription(this), which takes the shared _channelSync lock, removes the entry, and prunes the channel's list once it empties (lines 373-386). The Handler property is what DispatchChannelEventAsync invokes on each delivery (line 339).
  • Why it's built this way: nesting it privately inside NotificationHubService keeps subscription bookkeeping fully encapsulated, and the IDisposable shape 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; implements IDisposable.
  • Concept reinforced, subscription-as-token. It is the same "return an IDisposable to unsubscribe" shape as ChannelSubscription, applied to a signal that has no channel key. OnConnectionRestored returns 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 as async 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 owner and handler (NotificationHubService.cs:930), exposing Handler as a get-only property (line 911). Dispose() (line 913) calls owner.RemoveConnectionRestoredSubscription(this), which removes the entry under the shared _channelSync lock (lines 814-820). The Handler property is what RaiseConnectionRestoredAsync awaits, 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 IDisposable shape 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/notifications after 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>, reading SameOriginApiEndpoint first and ApiEndpoint second), ITokenStorageService (for the bearer token on a direct connection); AuthDelegatingHandler (its static ReportRejectedAsync, 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, SemaphoreSlim and CancellationTokenSource; implements IAsyncDisposable.
  • 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 = 3 starting at InitialRetryDelay of 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, Reconnected runs RejoinAndRaiseAsync (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), Closed runs RestartAfterCloseAsync (line 247, lines 705-754): a loop that repeats the serialized start, with a doubling backoff capped at MaxRetryDelay (line 131, defaulting to UnboundedReconnectPolicy.MaxDelay; the cap is applied at line 752), until one connects, so live notifications do not stay dead for the rest of the session. A Closed with 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.Jitter with samples from JitterSample (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 really Connected, and only when Interlocked.Exchange on the _restoredConnection latch (line 77) shows no one signalled it yet, so overlapping loops report one restored connection once and a Reconnecting one is left to the Reconnected handler (lines 730-742);
    • a lifetime token ends every start and restart loop on StopAsync or DisposeAsync. _lifetime (line 73) is canceled and replaced by StopCoreAsync (lines 489-535); each loop runs under the token it began in and re-checks IsLifetimeOver (line 756) under _startSync before 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 returns false (lines 298-305), which RestartAfterCloseAsync reads as "stop" (lines 725-728). The next StartAsync tries again. On a direct connection a 401 handshake that carried a bearer is first handed to ReportRefusedHandshakeAsync (lines 684-687, called at line 661), which gives it to AuthDelegatingHandler.ReportRejectedAsync for 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 in StartCoreAsync, or every later StartAsync (including one reached through JoinChannelAsync) would no-op forever (comment at lines 311-313). The guard itself only leaves a connected, connecting or reconnecting connection alone (line 257); a Disconnected one 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.NeedsServerJoin reports the key held but unconfirmed (lines 348-352), with MarkJoined recorded only after the invoke succeeds (line 357);
    • StartAsync is serialized by a SemaphoreSlim (line 61), since two components calling JoinChannelAsync at 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, including LogReconnectExhausted at line 895, LogRestartRetrying at line 898 and LogConnectionRestoredHandlerFailed at line 919), and failures on the channel and restored-handler paths are logged, never thrown.
  • Walkthrough:
    • Constants and fields: the four hub method names (lines 48-51), _sameOriginProxyEndpoint (line 54), _channelSync guarding the subscription dictionary and the restored-handler list (line 56), _lifetimeSync guarding the lifetime swap (line 57), _startSync guarding start (line 61, a SemaphoreSlim rather than a Lock because the guarded body awaits, lines 59-60), the ChannelReferenceCounter (line 63), _channelSubscriptions mapping a channel key to its handler list (line 64), _connectionRestoredSubscriptions holding the ConnectionRestoredSubscription handles (line 65), and the _restoredConnection latch naming the connection a restored signal was last raised for (lines 75-77).
    • NotificationCallback (line 83) is a settable Func<string, string, Task>? the host assigns to surface a snackbar. NotificationFilter (line 91) is an optional Func<IReadOnlyDictionary<string, string>?, Task<bool>> consulted with the notification's live metadata (null for an unscoped send) before the callback runs; false drops 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) and MaxRetryDelay (line 131) are internal and 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 the internal settable Func<double> (default Random.Shared.NextDouble) every reconnect, start-retry and restart delay is jittered with, so a test can pin the schedule; ConnectionFactory (line 146) is an internal test-only hook that replaces the HubConnectionBuilder call 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 _hubUrl from that endpoint, falling back to ApiSettings.ApiEndpoint and 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:HubPathPrefixes and 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 /api proxy, 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 calls StartForLifetimeAsync with the current lifetime token (CurrentLifetime, lines 537-551). StartForLifetimeAsync (lines 178-216) returns true when the lifetime is over, waits on _startSync with the lifetime token (tolerating ObjectDisposedException and OperationCanceledException, both treated as "nothing left to start"), re-checks the lifetime under the gate, runs StartCoreAsync, and releases in a finally that tolerates the disposal race. Its bool result is false only when the server refused authentication.
    • BuildConnection(lifetime) (lines 218-250) builds the HubConnection from ConnectionFactory when set or from a HubConnectionBuilder configured by ConfigureConnection with the unbounded reconnect policy fed by JitterSample (lines 220-223). It registers ReceiveNotification, which applies NotificationFilter and then NotificationCallback (lines 225-236), and ReceiveChannelEvent to DispatchChannelEventAsync (line 238), wires the reconnect re-join and restored signal through RejoinAndRaiseAsync (line 242) and the close-with-error restart bound to this connection's lifetime (line 247).
    • StartCoreAsync(lifetime) (lines 252-327) returns true immediately unless the existing connection is null or Disconnected (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 returns false (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 binds AccessTokenProvider to ITokenStorageService.GetAccessTokenAsync (line 600) and, outside the browser, installs ConnectWebSocketAsync as the socket factory (lines 602-605).
    • ConnectWebSocketAsync (lines 632-672) opens a ClientWebSocket, copies the configured headers and the bearer, and connects. The bearer is held in a local declared before the try (line 635) so the refusal path can still see it. When the server answered the upgrade with a non-101 status it first awaits ReportRefusedHandshakeAsync(statusCode, accessToken) (line 661), then rethrows an HttpRequestException carrying that status (lines 655-666), which is what lets UnboundedReconnectPolicy.IsAuthenticationRefused recognise a 401 or 403; a bare WebSocketException would not carry it.
    • ReportRefusedHandshakeAsync (lines 684-687) is internal: only a 401 with a non-empty bearer calls AuthDelegatingHandler.ReportRejectedAsync(accessToken, _tokenStorageService); anything else returns a completed task.
    • JoinChannelAsync(channelKey) (lines 339-367) counts the join before starting the connection so the replay inside StartAsync sees it (lines 343-346), then invokes the server JoinChannel only when connected and while the key is held but not confirmed joined on this connection (NeedsServerJoin, line 352), and records MarkJoined once 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 invokes LeaveChannel only when Release reports the last outstanding leave (lines 382-398).
    • RejoinChannelsAsync (lines 838-868) first calls ResetJoined (line 842), because a new or restored connection holds no server group membership, then snapshots the distinct held keys (line 845) and, when connected, invokes JoinChannel for 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 call JoinChannelAsync as well (lines 404-405).
    • OnConnectionRestored(handler) (lines 442-453) null-checks the handler, creates a ConnectionRestoredSubscription and adds it to _connectionRestoredSubscriptions under _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 through LogConnectionRestoredHandlerFailed so 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 calls StopCoreAsync (lines 489-535), which swaps in a fresh CancellationTokenSource under _lifetimeSync, cancels and disposes the ended one, then takes _startSync so no start can build anything after the stop returns, disposes and clears the connection, and clears the _restoredConnection latch (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. RestartAfterCloseAsync also checks the lifetime first (lines 707-710), so a close during teardown starts nothing.
  • 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 to OnConnectionRestored for 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 notifications WebAPI 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 supplies Endpoint and the Result-returning SendRequestAsync), 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's SendRequestAsync, 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 keeps scopeProvider (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 a ScopeKey is sent unchanged, and only an unscoped one picks up the ambient key via a record with expression (lines 32-40, rationale at lines 30-31). It then POSTs through SendRequestAsync<PushNotificationDTO> with a fresh idempotencyKey: 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 in N format (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-async method that returns the SendRequestAsync task directly) builds an invariant-culture pageNumber/pageSize query (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.
  • 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-level ScopeKey on 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: SendAsync does not read GetCurrentScopeDisplayNameAsync; 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. A null field 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 at IUserPreferenceWriter.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/preferences endpoint (the Helpdesk seed is the named example at ApiUserPreferenceWriter.cs:11-12) simply not register it: the callers resolve it with GetService<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): null means 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), a byte[]? carrying the EF rowversion in its wire shape, with a CA1819 suppression justified as the same exemption DTOs get (line 10). The replay sends it as If-Match through PendingWrite.IfMatch.
    • CoalesceKey (OfflineWriteOptions.cs:14): pairs writes that cancel each other out, used by IOfflineWriteQueue.CancelPendingAsync.
  • Why it's built this way: an options record with init members keeps EnqueueAsync to 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 IdempotencyKey and CoalesceKey for a create and only CoalesceKey for 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, Rejected or Expired (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.MaxAge and was discarded unsent.
    • There is deliberately no "transient" member: a transient failure keeps the write queued, so it never settles. The queue's private Classify returns OfflineWriteOutcome? and uses null for that case (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteQueue.cs:263).
  • Why it's built this way: an Expired write has no handler result at all (OfflineWriteSettledEventArgs.Result is null for 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 OfflineWriteNotifier component 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: the MaxAge default 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), default TimeSpan.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), default 200: beyond it an enqueue fails with OfflineWrites.QueueFull (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteQueue.cs:163,187).
  • Why it's built this way: mutable set properties so AddOfflineWriteQueue(configure) can apply an Action<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 a null field 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, Culture and Theme, both string? (UserPreferences.cs:9). There is no factory and no validation: the values are whatever the backend returned.
  • Why it's built this way: a positional record is the smallest thing that deserializes cleanly from the auth/preferences payload and compares by value.
  • Where it's used: returned by ApiUserPreferenceReader, including its static Empty instance (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 declared private so 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 the PutAsJsonAsync call (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 empty UserPreferences (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) returning Task<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 in ApplyStoredPreferencesAndNavigateAsync (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) and Kind (line 18), the handler key, for example Engagement.Bookmark.Create.v1.
    • Replay safety: IdempotencyKey (line 21) so a write the server already ran is not run twice, and BasedOnRowVersion (line 25), a byte[]? with a CA1819 suppression justified by the record being persisted locally, not a domain type (line 24).
    • Payload: PayloadJson (line 28), serialized with JsonSerializerOptions.Web, and the generic ReadPayload<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 or null for an anonymous user), EnqueuedOn (line 37) and Attempts (line 40), the count of transient replay failures so far.
    • IfMatch (line 47) is computed, not stored ([JsonIgnore], line 46): the weak ETag of BasedOnRowVersion via ConcurrencyETag.Format, or null when no row version was given.
  • Why it's built this way: required + init members keep an entry immutable; the queue changes Attempts with a with expression (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". Classify returns 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, an OfflineWriteOutcome? whose null means "keep the entry", and StopsPass, which only matters for a kept entry.
    • Three named constructors carry every legal combination: KeepAndStop (line 421, null outcome, stops the pass), KeepAndContinue (line 424, null outcome, the pass goes on) and Settle(outcome) (line 427, an outcome, never stops).
  • 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 struct adds 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: Classify builds it (OfflineWriteQueue.cs:276-301) and ReplayPassAsync acts 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 example Engagement.Bookmark.Create.v1.
    • ReplayAsync(PendingWrite, CancellationToken) returning Task<Result> (line 25). The doc comment (lines 14-21) fixes the contract: send the write with its IdempotencyKey (and IfMatch when set), and report the answer as a Result. 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 Result rather than an outcome lets a handler reuse the normal HTTP-to-Result path, 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 scoped TryAddEnumerable entry (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:111 uses TryAdd).

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) exposing Write (line 12), Outcome (line 15) and Result (line 18), which is null for OfflineWriteOutcome.Expired because an expired write is never sent.
  • Why it's built this way: the standard EventHandler<TEventArgs> shape, raised by OfflineWriteQueue.SettleAsync only 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's SessionBookmarkReplayTests.

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 default NullLocalCacheStore; a host that calls AddBrowserDeviceCapabilities (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, and PendingChanged (line 24), raised after every persisted change.
    • EnqueueAsync<TPayload>(kind, payload, options, cancellationToken) (line 33) returns Result<PendingWrite>: the queued write, or the OfflineWrites.Unavailable / OfflineWrites.QueueFull failure (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 raising WriteSettled.
    • 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 a Result; 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's OfflineWriteNotifier (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: InitialRetryDelay 5 seconds (OfflineWriteQueue.cs:61) and MaxRetryDelay 5 minutes (line 64). Fields include an ordinal handler dictionary (line 68), a SemaphoreSlim(1, 1) _gate (line 73) for store edits, and a Lock _scheduleSync (line 74) for the timer.
    • The constructor (line 90) indexes handlers by Kind with TryAdd, so the first registered wins (line 111), and subscribes to ConnectivityChanged (line 114). IsAvailable is the store's own flag (line 124).
    • EnqueueAsync (line 133) fails with an Error.Unexpected coded OfflineWrites.Unavailable when 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 as UserScope), and adds it through MutateAsync unless MaxPendingWrites is reached (line 163), else an Error.TooManyRequests coded OfflineWrites.QueueFull (lines 186-187). When the kind has a handler it bumps _replayableEnqueues and schedules a retry (lines 173-182).
    • GetPendingAsync (line 191) and CancelPendingAsync (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 the Interlocked.CompareExchange flag (line 224). Its finally always calls CompletePass (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 than MaxAge unsent (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: HttpRequestException or IOException) stops the pass (lines 379-382), and any other throw keeps the entry and goes on (lines 387-388). A Result goes through Classify (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 as Completed (line 280); a CommitOutcomeUnknown result settles as Rejected before 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 that StopsThePass keeps the entry and stops (lines 288-291); an ErrorType.Unexpected keeps it and continues (lines 293-296); anything else settles as Conflict for an ErrorType.Conflict, otherwise Rejected (lines 298-300). StopsThePass (line 307) is the transport or timeout code of HttpResultExecutor, or ErrorType.Unavailable, TooManyRequests or Unauthorized (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 via NextDelay (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 injected TimeProvider, and never while offline or disposed; a per-schedule token object lets OnRetryTimer (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 raises PendingChanged; SettleAsync (line 499) removes the entry and then raises WriteSettled; CountAttemptAsync (line 545) bumps Attempts. Both events go out through RaiseWriteSettled (line 510) and RaisePendingChanged (line 528), which invoke one subscriber at a time, log a throwing one through LogSubscriberFailed (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.
  • 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, and MaxAge bounds 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.System and the options, by AddOfflineWriteQueue (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:420-429); exercised by OfflineWriteQueueTests and OfflineWriteQueueRetryTests (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/preferences with 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); IHttpClientFactory and System.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: GetAsync returns UserPreferences rather 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: Empty is a single shared new UserPreferences(null, null) (line 26), so the failure paths allocate nothing. The expiry skew is not a local copy: the guard passes JwtTokenInfo.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 on JwtTokenInfo.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, and IsFresh also covers the anonymous (null) case. Both return Empty (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 an HttpRequestMessage GET to the relative URI auth/preferences with the token it already read set as the Authorization: Bearer header on that request (lines 44-45). The reader sets it itself because in Blazor Server AuthDelegatingHandler resolves 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 calls AuthDelegatingHandler.TrackTokenOwner(token!, tokenStorageService) (line 49, the helper at MMCA.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 to Empty (lines 51-54), and only then ReadFromJsonAsync<UserPreferences> (line 56).
    • Null-coalescing on the deserialized value (line 57) means a body of literal null is the same as no preference.
    • Two catch blocks, HttpRequestException (line 59) and TaskCanceledException (line 63), both return Empty. Note what is not caught: anything else, including a JsonException from a malformed body, still escapes, so a contract break is loud while a transport failure is quiet.
  • 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 AddUIShared with TryAddScoped (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). Its ApplyStoredPreferencesAndNavigateAsync (Login.razor:387) calls GetAsync, 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) and ServerSignInPreferenceReadTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Services/ServerSignInPreferenceReadTests.cs), alongside its sibling writer's ApiUserPreferenceWriterTests. Because TaskCanceledException is caught unconditionally, a caller that cancels its own token receives Empty rather than an OperationCanceledException, 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/preferences through 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: IHttpClientFactory and System.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 asks JwtTokenInfo whether one is usable, then attaches it as the Authorization: Bearer header of the request message (ApiUserPreferenceWriter.cs:110), the same explicit per-request bearer the reader attaches.
  • Walkthrough
    • The primary constructor takes IHttpClientFactory and ITokenStorageService (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 not async: under a System.Threading.Lock gate (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 with WaitAsync(PreviousSaveWait, cancellationToken) under ConfigureAwaitOptions.SuppressThrowing (ApiUserPreferenceWriter.cs:77-78), so a fault, timeout or cancellation of the earlier save only ends the wait (comment, ApiUserPreferenceWriter.cs:75-76). PreviousSaveWait is an internal init 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 calls PutAsync (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 at MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/JwtTokenInfo.cs:44). The skew is the shared 30-second DefaultExpirySkew (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 that IsFresh also covers null and unreadable tokens, which makes this the anonymous-user guard as well.
    • Guard two compares the current token against _rejectedToken with StringComparison.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 HttpRequestMessage with a JSON body, sent through SendAsync, to the relative auth/preferences (ApiUserPreferenceWriter.cs:105-115), and a 401 Unauthorized latches _rejectedToken (ApiUserPreferenceWriter.cs:117-120). Just before SendAsync it calls AuthDelegatingHandler.TrackTokenOwner(token!, tokenStorageService) (ApiUserPreferenceWriter.cs:114, the helper at MMCA.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 names CreateAuthenticatedClientAsync as the path that already does the same.
    • Both HttpRequestException (ApiUserPreferenceWriter.cs:122) and TaskCanceledException (ApiUserPreferenceWriter.cs:126) are swallowed, each with a comment noting that the cookie already holds the choice for this device.
  • 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 TryAddScoped in 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 by ApiUserPreferenceWriterTests, 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-bg on ChromeBackground (line 36) and --mmca-divider on LightDivider (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 both BrandColors and app.css, and BrandColorTokenTests in 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, one InlineData row each (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Theme/BrandColorTokenTests.cs:35-39); the --mmca-sidebar-bg and --mmca-divider mirrors are named in the doc comments but have no row there.
    • [Rubric §21, Accessibility] lands here rather than only in the theme: the Secondary constant carries its own contrast math in source, Teal 700 #00796B holding about 5.3:1 on light surfaces, replacing the Teal 600 #00897B that 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 for LightWarning and DarkError is deliberately not here: their summaries point at MMCATheme, where the math sits beside the assignment (lines 56, 116, 122).
  • Walkthrough: public const string fields 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), and SecondaryLight = "#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), and ChromeTextMuted = "#FFFFFFB3", white at 70% alpha for sidebar text and icons (line 43).
    • The light palette (lines 45-84): LightTertiary Purple 700, LightInfo Blue 700, LightSuccess Green 800, LightWarning = "#A85D00" with LightWarningContrastText = "#FFFFFF", LightError Red 800, then LightBackground = "#FAFBFC", LightSurface, the two text tones, LightActionDefault, and the two dividers.
    • The dark palette (lines 86-154): DarkPrimaryLighten Blue 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 light Secondary was moved off for contrast, line 99), DarkSecondaryLighten, DarkTertiary, DarkInfo, DarkSuccess, DarkWarning Orange 400, DarkError = "#FF8A80" (line 117), then the four state fills DarkInfoDarken = "#64B5F6" (Blue 300, line 124), DarkSuccessDarken = "#81C784" (line 127), DarkWarningDarken = "#FFB74D" (line 130) and DarkErrorDarken = "#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, then DarkBackground = "#1A2027", DarkSurface = "#27303A", text, action and divider tones. Note DarkInfo and PrimaryLight share #42A5F5, and DarkTextSecondary and DarkActionDefault share #B0BEC5: each keeps its own name so a role can change without dragging the other.
  • Why it's built this way: const rather than static readonly means 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 of BrandColorTokenTestsBase, 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), is true for dark, false for light, and null when 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 and null identically (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 in OnAfterRenderAsync stays 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 by MmcaThemeProviders.razor:47; pinned by MmcaThemeProvidersInitialModeTests.

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 called AddTwoFactorUI(), 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: AddUIShared registers 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 by TwoFactorRoutesTests (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 returns false instead of throwing when it fails.
  • Depends on: JsInteropFailure, whose IsUnavailable predicate 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 covers TaskCanceledException) (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,97 and ThemeToggle.razor:22 (all under MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/); ThemeService names it in the BL0016 justifications 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 by JsInteropFailureTests, which asserts a TaskCanceledException reports 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 to null (line 23); the asset it imports, MMCA.Common/Source/Presentation/MMCA.Common.UI/wwwroot/theme.js, which owns the cookie and localStorage access (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 holds IsDarkMode (line 32); the toggle button, the MudThemeProvider wrapper and, on MAUI, the native chrome all read from it and all subscribe to OnChange (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 or localStorage requires a live browser, so InitializeAsync can 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 from OnAfterRenderAsync(firstRender) (MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/MmcaThemeProviders.razor:59-69).
  • Walkthrough
    • ModulePath is the _content/MMCA.Common.UI/theme.js static-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) and IsInitialized (line 35) are public with a private setter: subscribers read the state, only this class writes it. OnChange (line 38) is a plain EventHandler?. IsDarkMode is seeded from the constructor's initialModeSource?.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 at false.
    • InitializeAsync() (line 44) is idempotent by an early return on IsInitialized (lines 46-49). It imports the module (line 51), asks get for 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 through systemPrefersDark (line 56), which reads prefers-color-scheme (theme.js:33-35). Only then does it set IsInitialized and raise OnChange (lines 59-60), so the first notification carries the resolved answer, not the default.
    • InitializeAtStartupAsync(bool?) (line 72, internal) is the entry point MmcaThemeProviders calls on first render, passing the mode of an optional IInitialThemeModeSource it resolved in OnInitialized (MmcaThemeProviders.razor:50,69). A null falls through to InitializeAsync; a known native value takes InitializeFromNativeAsync (lines 75-92), which is also idempotent on IsInitialized (lines 77-80), adopts the value, sets IsInitialized and raises OnChange (lines 82-84), and only then reseeds the cookie and localStorage through set (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 BL0016 block 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, through set (line 102), then writes the field (line 104) and notifies (line 105): a failed import or JS call leaves IsDarkMode and 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-year max-age and samesite=lax and mirrors it to localStorage, guarding the mirror in a try because 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) is SetDarkModeAsync(!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's IJSObjectReference lives.
  • 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 and localStorage rather than to component state, and why the service holds no MudTheme of its own: it publishes a boolean and lets the theme providers decide what that means visually. Not gating InitializeAsync on RendererInfo is also deliberate and pinned: the prerender test uses the get invocation 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 AddUIShared as scoped (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:229) and consumed by MmcaThemeProviders, which subscribes in OnInitialized, initializes on first render and unsubscribes on dispose (MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/MmcaThemeProviders.razor:56,69,147), by ThemeToggle (MMCA.Common/Source/Presentation/MMCA.Common.UI/Theme/ThemeToggle.razor:2,7), by the MAUI head's NativeThemeSync, 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 by DarkModeE2ETests (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/Services is named for this type; its behavior is covered only through those components, so a change to InitializeAsync surfaces as a component-test failure rather than a direct one. OnChange is 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. SetDarkModeAsync sets IsDarkMode only after the JS write succeeds, so a failed set throws out of the call with the in-memory mode, the persisted mode and the subscribers still in agreement and no OnChange raised. The native-first path orders it the other way on purpose: InitializeFromNativeAsync adopts the native value and raises OnChange before the set reseed, 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 sets Layout: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 StampColorModeOnDocument flag, MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Settings/LayoutSettings.cs:51), and the stampColorMode export of MMCA.Common/Source/Presentation/MMCA.Common.UI/wwwroot/theme.js:103, and JsInteropFailure for its catch filter (ColorModeStamp.cs:38). Externals: Microsoft.JSInterop.IJSRuntime and Microsoft.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: MudThemeProvider only 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 not data-mmca-theme, which belongs to the MAUI head's pre-paint script and its rules in app.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 resolves IOptions<LayoutSettings> with the flag set to true (ColorModeStamp.cs:25-28); a head with no layout settings registered therefore never stamps.
    • Otherwise it imports ./_content/MMCA.Common.UI/theme.js and calls stampColorMode with "dark" or "light", disposing the module reference with await using (ColorModeStamp.cs:32-37). The try is filtered with catch (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 stampColorMode records the last mode, sets the attribute, and attaches one enhancedload listener that re-stamps it, because enhanced navigation resynchronises <html>'s attributes from the new document (theme.js:85-86,103).
  • 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 by MmcaThemeProvidersColorModeTests (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 MudTheme instance, defining the brand palette (light and dark), typography, and layout radius, applied once via MudThemeProvider in 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.Instance is 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.Warning on MudText/MudLink/MudIcon and on outlined chips/buttons), and MudBlazor's default #F57F17 is only about 2.65:1 on Surface, failing the 4.5:1 floor everywhere it is text; #A85D00 is 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 with PrimaryDarken on hover, focus-visible and active while the label keeps PrimaryContrastText, so the darken has to carry the dark label too; the brand #1565C0 left 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, and PrimaryFillContrastTests pins both fills (comment, lines 61-65);
    • dark PrimaryContrastText = "rgba(0,0,0,0.87)" (line 71), because white on the lightened dark-mode primary #42A5F5 is 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 while rgba(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 #FFA726 being 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 #EF5350 was only 3.84:1 as text on Surface, below the 4.5:1 floor wherever Color.Error is a label rather than a fill (inline validation copy, outlined error chips); #FF8A80 reads 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/ErrorDarken from BrandColors.DarkInfoDarken and its three siblings (lines 109-112): a text (default-variant) or outlined alert paints its message in the *Darken colour over the base colour at HoverOpacity (0.06) composited on Surface, and left unset MudBlazor darkens each accent, which on a dark surface moves the text towards the background (Info #2094F3 is 3.82:1 on its tint, Success #4DAC52 4.23:1, Error #FF695C 4.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, and AlertTextContrastTests pins all eight ratios (comment, lines 99-108);
    • dark LinesInputs = "rgba(255,255,255,0.5)" (line 117): the dark default rgba(255,255,255,0.3) is only 2.6:1 on Surface, effectively invisible to a low-vision user, while 0.5 is 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 #27303A into about rgb(82,89,97), where the link colour #42A5F5 is 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, and LinkContrastTests pins 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 for Warning and Error: their constants live in BrandColors, whose summaries point back here for the math.

  • 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 the rgba(...) 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 the Light* constants (Tertiary, Info, Success, Warning, Error, lines 25-37, including the WCAG-driven Warning and LinesInputs values above), and then fixes app chrome: AppbarBackground and DrawerBackground from BrandColors.ChromeBackground, DrawerText/DrawerIcon from ChromeTextMuted, and background, surface, text, action and divider values from the matching Light* 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 600 PrimaryDarken (line 66) and *Darken state colours for Info, Success, Warning and Error (lines 109-112, above), darkens the table row overlays (lines 126-127, above), takes the same Chrome* 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 the Dark* text and divider tones.
    • Typography (lines 141-219). Default sets the font stack Inter, Segoe UI, Helvetica Neue, Arial, sans-serif; the comment above it records that Inter is self-hosted by this RCL (wwwroot/fonts plus an @font-face block in wwwroot/app.css) and that before those faces existed the stack silently fell through to Segoe UI, so the two must stay in step. H1 through H4 use 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; H5 and H6 stay at weight 600 with no negative tracking. Subtitle1/Subtitle2 sit at weight 500, Body1/Body2 set line heights 1.6 and 1.5, and Button sets TextTransform = "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.
    • LayoutProperties sets DefaultBorderRadius = "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 lets BrandColorTokenTests police 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 against SharedResource, placed in NavSection.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 by TwoFactorUIModuleTests (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 one extension(IServiceCollection) block)

  • What it is: the two-factor UI opt-in (ADR-116). One method, AddTwoFactorUI(), registers the account page at TwoFactorUIModule.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 the MMCA.Common.UI.TwoFactor class of that name, not the shared-UI composition root AddUIShared lives in.
  • Depends on: ITwoFactorUIService / TwoFactorUIService, IUIModule / TwoFactorUIModule; externals Microsoft.Extensions.DependencyInjection and its Extensions namespace (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 to AddUIShared in every UI head (web server, WebAssembly client, MAUI) whose API hosts the auth/two-factor endpoints (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 AddUIShared unconditionally (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 by TwoFactorOptInRenderTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/TwoFactor/TwoFactorOptInRenderTests.cs:39,61).
  • Caveats: the group already has a ### DependencyInjection section 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 #dependencyinjection resolves 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 is TwoFactorAccount and 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. Exposing HidesTwoFactorPages separately lets TwoFactorPageAuthorizationHandler reuse the same decision.
  • Where it's used: the shared router's Found branch, beside the notification gate (MMCA.Common/Source/Presentation/MMCA.Common.UI/Routes.razor:15), and TwoFactorPageAuthorizationHandler (TwoFactorPageAuthorizationHandler.cs:23). Pinned by TwoFactorPageGateTests (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's AuthorizationHandler<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 calls context.Succeed(requirement) when TwoFactorPageGate.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 TryAddEnumerable by AddUIShared (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:105-106); pinned by TwoFactorRoutesTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/TwoFactor/TwoFactorRoutesTests.cs:26) and TwoFactorPageAuthorizationTests (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 http or https URL. It is the client-side twin of the server's AbsoluteUrlRules in 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), BCL Uri. 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 image src or a link href, so accepting javascript: or data: 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 exactly http and https (lines 44-46) is the narrow allowlist that keeps a javascript: 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. ErrorMessage is returned unchanged rather than run through string.Format (line 52), which is what lets a model declare ErrorMessage = "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 the ValidationAttribute base, so a model that declares no ErrorMessage still says something useful.
    • IsValid(object?, ValidationContext) (lines 35-53) null-guards the context (line 37), then returns ValidationResult.Success for 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 against Uri.UriSchemeHttp and Uri.UriSchemeHttps. UriKind.Absolute alone 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.MemberName when one is present and returns new 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 with StringComparison.Ordinal against the BCL scheme constants avoids the culture-sensitive comparison trap and matches how Uri normalizes 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 AbsoluteUrlRules it 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 Validation delegate 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 propertyPath is dotted and relative to the model, for example "Title" or "Address.City" (lines 19-23), which is what MudBlazor derives from a field's For expression. 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), returning IEnumerable<string>. object rather than a generic type parameter is deliberate: MudBlazor's Validation parameter 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's Validation parameter 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 in ClientConfigOAuthSection)

  • What it is: the served shape of one generic OIDC provider inside the oAuth section of /client-config: Enabled, DisplayName and UsesDomains, and nothing else (ClientConfigOAuthSection.cs:55).
  • Depends on: nothing first-party; it is a positional record of a bool, a string and a bool. 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). Enabled is always true when the server builds it (:41), because only providers the server lists get an entry; the member exists because the WebAssembly client's ConfigurationOAuthUISettings lists an OAuth:Oidc:<Name> section only when it is flagged Enabled or carries a ClientId (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/ConfigurationOAuthUISettings.cs:60-61), and the served document never carries the client id. UsesDomains is the server's computed answer (a Domains list with entries), which the client reads back through the same UsesDomains key (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 repeating Required / MaxLength per 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 injected IStringLocalizer (line 149) and returned as the raw message when localized.ResourceNotFound (line 150). That single line is what makes the design safe to adopt incrementally: a model can declare ErrorMessage = "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. TryResolveOwner returns 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) catches AmbiguousMatchException and retries with BindingFlags.DeclaredOnly, because a new-shadowed property matches twice under FlattenHierarchy; 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 shared BindingFlags set: Public | Instance | FlattenHierarchy.
    • The constructor (lines 36-41) requires an IStringLocalizer and null-guards it. The parameter doc (lines 31-35) tells callers to pass the page's own IStringLocalizer<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 and PropertyInfo, return an empty array when unresolvable (line 51), then validate the value the model currently holds via property.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) is internal static so ModelValidation.IsRequired can reuse it (ModelValidation.cs:97). It splits the path on . with RemoveEmptyEntries (line 90) and walks segment by segment, returning the last segment's PropertyInfo plus the object that declares it (lines 100-104). [NotNullWhen(true)] on both out parameters (lines 84-85) is what lets callers dereference them without a null check after a true return.
    • ValidateResolved (lines 131-140) builds a ValidationContext(owner) { MemberName = property.Name }, calls Validator.TryValidateProperty (line 135), and projects the results through Localize, 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 Validate from ValidateValue is 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, SignIn and Legal settings from the server head's configuration into the anonymous /client-config document, so a value set where production values are set (an environment variable, Key Vault, appsettings.Production.json on 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 SectionName and type, ClientConfigUiSections.cs:39-42). Externals: Microsoft.Extensions.Configuration (IConfiguration, binder Get(Type)), System.Text.Json (JsonNamingPolicy.CamelCase) and System.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 because Layout (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 to null (: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 as LegalSettings.HasFooterLinks are excluded (doc :81-87). It is internal so 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 ClientConfig callback 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 by ClientConfigEndpointTests (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 in ClientConfigOAuthSection)

  • What it is: the whole served value of the oAuth section 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, GitHubEnabled and AppleEnabled carry the server's resolved IOAuthUISettings flags; Oidc is keyed by provider name with StringComparer.OrdinalIgnoreCase (ClientConfigOAuthSection.cs:39-42). Serialized with camelCase members, the section reads googleEnabled, gitHubEnabled, appleEnabled and oidc, the keys the WebAssembly client's ConfigurationOAuthUISettings reads back case-insensitively as OAuth:GoogleEnabled and OAuth: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 OAuth section of the anonymous /client-config document 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 OidcProviders it projects, line 39), and its two private records OAuthFlags and OidcProviderFlags. Externals: Microsoft.Extensions.DependencyInjection (GetService<T>), BCL LINQ ToDictionary and StringComparer.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 its ClientId is 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, DisplayName and UsesDomains (remarks, ClientConfigOAuthSection.cs:12-16). The client's own reader accepts a pre-computed {Provider}Enabled flag or an Oidc:<Name>:Enabled flag 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 to oAuth on the wire.
    • Build(IServiceProvider) (ClientConfigOAuthSection.cs:31-45) resolves IOAuthUISettings with GetService and returns null when the head registers none (lines 33-37), which the endpoint reads as "write no section". Otherwise it projects OidcProviders into a case-insensitive dictionary keyed by Name, each value a new 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 is object? 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): an OAuth section added through the host's ClientConfig extras replaces this one whole and would drop the OIDC providers, so a host must not add it. Reading IOAuthUISettings rather 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 by ClientConfigEndpointTests: ProjectsTheHeadsSignInProviders_IntoTheShapeTheClientReads binds the served document into a client-side ConfigurationOAuthUISettings, 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_ServesNoOAuthSection pins the null path (:338-347).
  • Caveats / not-in-source: the class summary also names the shape as what ConfigurationOAuthUISettings reads; 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 an EditForm. It runs the same DataAnnotations rules, but through DataAnnotationsModelValidator, so every ErrorMessage is resolved as a resource key and fields bound with For show 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; the EditForm pages used the stock validator, which renders ErrorMessage verbatim, so a model declaring a resource key would show the key. This component closes that gap by feeding the same engine into the EditContext instead of a MudBlazor Validation delegate (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, its ValidationMessageStore, and the validator (lines 23-25). CurrentEditContext is 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) throws InvalidOperationException when no cascading EditContext exists, 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 a new DataAnnotationsModelValidator(Localizer) and subscribes to OnFieldChanged and OnValidationRequested (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 calls NotifyValidationStateChanged (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 own FieldIdentifier (lines 88-91) before notifying once (line 93).
    • Detach (lines 96-109) unsubscribes both handlers, clears the store and nulls all three fields; Dispose is exactly Detach() (line 34), so the component never leaves a handler on a context that outlives it.
  • Why it's built this way: reusing DataAnnotationsModelValidator rather than re-implementing resolution means the EditForm and MudForm paths cannot disagree about which keys resolve. Injecting IStringLocalizer<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 EditForm pages, 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 their ErrorMessage values 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 against SharedResource, so a key that exists only in a page's own resource file passes through untranslated. No file under MMCA.Common/Tests names 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 Validation parameter expects, so a page declares its rules once (on the model) instead of scattering Required and MaxLength across the markup and re-checking them by hand.
  • Depends on: first-party: IModelValidator (the pluggable engine taken by For) and DataAnnotationsModelValidator (taken concretely by ForProperty, and reused via its internal static TryResolveOwner in IsRequired, 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)) in OnInitialized, then Validation="@_validate" on every field.
    • One delegate serves the whole form. For returns 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 fallback instance ?? model on that line is the small robustness detail: MudBlazor normally passes its own MudForm.Model back, 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. ForProperty names 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]: IsRequired exists so a field's Required parameter (the asterisk and the aria-required affordance) 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 a Validation delegate is present, so the localized message from the model is the one shown.
  • 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 via GetPropertyPath (line 79) and returns value => 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.TryResolveOwner and reports property.IsDefined(typeof(RequiredAttribute), inherit: true) (line 98).
    • GetPropertyPath<TModel, TValue> (lines 109-133) renders an expression as the dotted path MudBlazor's For would produce. It first unwraps the Convert node the compiler inserts when TValue is a value type boxed to object (lines 114-116, with the comment saying so), then walks MemberExpression links pushing each name onto a Stack<string> (lines 118-123), which reverses m => m.Address.City into Address.City on string.Join (line 132). Anything that is not a chain of property accesses rooted at the lambda parameter throws ArgumentException with 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 _validate delegate with For (NotificationSend.razor.cs:77) and reads its two Required affordances with IsRequired (NotificationSend.razor:47,58). It is public API of MMCA.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 extras delegate writes into when it wants extra data served on the anonymous /client-config document, one named section per Add call.
  • Depends on: ClientConfigEndpointExtensions (its ApiSectionName and ModulesSectionName constants, checked as the two reserved names, ClientConfigBuilder.cs:51-52); Microsoft.AspNetCore.Http (HttpContext, BCL) and Microsoft.Extensions.DependencyInjection / Microsoft.Extensions.Configuration for 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 is internal (line 23), so the only place a ClientConfigBuilder can come into existence is inside MapClientConfigEndpoint's own request delegate, which is also the one place a host's extras callback 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 a Dictionary<string, object?> keyed with StringComparer.OrdinalIgnoreCase (a collection expression with with(...)), so "Support" and "support" collide as the same section.
    • HttpContext (line 26) and the two accessors built on it, Services (line 29, reads HttpContext.RequestServices) and Configuration (line 32, resolves IConfiguration from those services), let an extras delegate reach DI and configuration without the endpoint having to pass them separately.
    • Add(string name, object? value) (line 47) blank-checks name (ArgumentException.ThrowIfNullOrWhiteSpace, line 49), rejects the reserved framework sections ClientConfigEndpointExtensions.ApiSectionName and ModulesSectionName case-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 returns this for chaining (line 64). The Common.UI settings sections (Layout, Registration, SignIn, Legal) are not reserved: adding one replaces the copy ClientConfigUiSections forwarded. OAuth is not reserved either, but the parameter doc tells a host not to add it, because the framework writes it from IOAuthUISettings (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) is internal, an IReadOnlyDictionary<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 internal Sections getter 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's extras delegate (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:97-98); its Sections are then read back to assemble the response document (ClientConfigEndpointExtensions.cs:123-126). A head reaches it through the ClientConfig option of MmcaBlazorWebPipelineOptions (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/MmcaBlazorWebPipelineOptions.cs:23); the ADC UI head's AddAdcClientConfig adds its Support and Mcp sections that way (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:162-167). Exercised directly by ClientConfigEndpointTests (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 for WasmApiEndpoint, line 87), ApiEndpointUrl (IsAbsoluteHttp, line 88), UIModuleConfiguration (IsModuleEnabled, line 141), ClientConfigUiSections (Build, line 111), ClientConfigOAuthSection (Build and SectionName, lines 118-120), and, only in a host running the same-origin API proxy, SameOriginApiProxyMarker (probed from request services, line 153) and SameOriginApiProxySettings (read for PathPrefix, line 158); externals Microsoft.AspNetCore.Routing (IEndpointRouteBuilder, RouteHandlerBuilder), Microsoft.AspNetCore.Http (HttpContext), IConfiguration, System.Text.Json (JsonNamingPolicy.CamelCase), and the ASP.NET Core minimal-API Results type.
  • 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 serves Api:WasmApiEndpoint, the browser-reachable gateway URL, and never falls back to Api: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 declares AllowAnonymous() itself (line 130) rather than relying on an ambient default, and the remarks warn that only values the public site renders anyway belong in extras (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. The modules section lists every entry of the head's Modules configuration 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). The layout, registration, signIn and legal sections carry the head's Common.UI settings, limited to declared properties and keys the server sets (remarks, lines 58-65), through ClientConfigUiSections. The oAuth section 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 own OAuth extra, 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 Api section, sameOriginApiEndpoint, the proxy's origin-relative base (for example /api/) that the WASM bootstrap resolves against the page's own origin, while apiEndpoint stays 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) and ModulesSectionName = "Modules" (line 31), the two section names ClientConfigBuilder treats as reserved.
    • The extension(IEndpointRouteBuilder endpoints) block (line 33, see primer) holds the single member MapClientConfigEndpoint(Action<ClientConfigBuilder>? extras = null) (line 84).
    • The handler (lines 85-129) takes the request's HttpContext plus IOptions<ApiSettings>, reads apiSettings.Value.WasmApiEndpoint (line 87), throws InvalidOperationException naming the key when ApiEndpointUrl.IsAbsoluteHttp rejects it (lines 88-95), builds a ClientConfigBuilder for the request and invokes extras on it (lines 97-98), and seeds the response with the camelCased Api section from BuildApiSection(context, wasmApiEndpoint) and the camelCased Modules section from BuildModulesSection(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 camelCased SectionName (oAuth), also before the extras (lines 116-121); a head that registers no IOAuthUISettings gets no oAuth section. Finally it overlays every builder section, each name run through the same JsonNamingPolicy.CamelCase policy 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 the Modules section, keyed as spelled there (case-insensitive dictionary), to new { Enabled = UIModuleConfiguration.IsModuleEnabled(configuration, module.Key) }; a head with no Modules section serves an empty object.
    • The private BuildApiSection(HttpContext, string) (lines 151-160) returns new { ApiEndpoint } when GetService<SameOriginApiProxyMarker>() is null (lines 153-156); otherwise it reads IOptions<SameOriginApiProxySettings>.Value.PathPrefix (line 158) and returns new { ApiEndpoint, SameOriginApiEndpoint = prefix + "/" } (line 159).
  • 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 MapClientConfigEndpoint gets the identical fail-closed contract; a host only supplies the pieces specific to it through extras. 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.ClientConfig callback as extras (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:211); its handler constructs ClientConfigBuilder per request. Pinned by ClientConfigEndpointTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/ClientConfig/ClientConfigEndpointTests.cs) and exercised through the pipeline by BlazorWebPipelineTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Hosting/BlazorWebPipelineTests.cs).
  • Caveats / not-in-source: the extras parameter doc still gives "sign-in provider flags" as an example of a host section (line 81), which contradicts the oAuth remarks (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), whose EnsureEmailIsValid and MaxLength it calls; the class doc (:7-11) names it as the check the Email value object runs and the one behind the server's EmailRules. 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 an EditForm by 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 private IsValidEmailFormat (OptionalEmailAttribute.cs:62-67) calls EmailInvariants.EnsureEmailIsValid (MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/EmailInvariants.cs:23) on the trimmed value and accepts on IsSuccess (: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 references MMCA.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 own Email.TooLong failure (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 as AbsoluteUrlAttribute: a mandatory field pairs this with [Required] (class doc, :13-15).
  • 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 set ErrorMessage to 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 calls IsValidEmailFormat (:44). On failure it builds the member-name array from validationContext.MemberName when present and returns new 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 over MaxLength, otherwise returns whether EnsureEmailIsValid(trimmed, nameof(OptionalEmailAttribute)) succeeded (:65-66). The source argument only labels the discarded Error; the Result itself 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 EmailAddressAttribute cannot 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 OptionalEmailAttributeTests in 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 BlazorCircuitLimits configuration 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.RangeAttribute on 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 to 200.
    • DisconnectedCircuitMaxRetained (:45-46), [Range(0, 10_000)], defaults to 25, 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 to 60, 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 on DisconnectedCircuitMaxRetained to 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 by BlazorCircuitLimitExtensions.RetentionFrom for 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 UiRateLimiting configuration section: an on/off switch, a per-client-IP request budget and window, and a replica-wide concurrency ceiling.
  • Depends on: nothing first-party; RangeAttribute on PermitLimit, WindowSeconds, and GlobalConcurrencyLimit (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 from MMCA.Common.Gateway, because a Blazor host is not a reverse proxy and its exemptions differ (it serves /_framework and /_content itself). 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), default true; 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)], default 300, 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 the IsExempt(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)], default 60.
    • GlobalConcurrencyLimit (:75-76), [Range(1, 1_000_000)], default 200: 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 by BlazorCircuitLimits: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 than IOptions<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.OnStarting and the typed Headers.CacheControl / Headers.Pragma properties.
  • 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-store response 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 an extension(IApplicationBuilder app) block (:10): registers an inline app.Use middleware (:26) that does not touch the response itself but registers a Response.OnStarting callback (: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 with text/html, compared ordinally ignoring case. Only then does it set Cache-Control to no-store, no-cache, must-revalidate, max-age=0 (:34) and Pragma: 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 IsAuthenticated keeps public pages bfcache-eligible (the remarks at :19-23); the OnStarting hook 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 before MapRazorComponents so it wraps every page response. It also has to sit after authentication has populated HttpContext.User by the time the response starts, which OnStarting gives for free.
  • Where it's used: BlazorWebHostExtensions calls it in UseMmcaBlazorWebPipeline right after UseAntiforgery() (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.razor calls, 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's RenderMode / IComponentRenderMode, and HttpContext.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 writes E2E__ForceWebAssembly); documented as winning over the server key (:16-19).
    • ForceServerKey (:26): "E2E:ForceServer".
    • Resolve(IConfiguration) (:35): throws on a null configuration, returns RenderMode.InteractiveWebAssembly when the WebAssembly key is true (:39-42), otherwise InteractiveServer when the server key is true, otherwise InteractiveAuto (:44-46). A missing key reads as false.
    • Resolve(IConfiguration, HttpContext) (:60): returns null (static server rendering) when httpContext.AcceptsInteractiveRouting() is false, that is, when the matched page carries ExcludeFromInteractiveRoutingAttribute, otherwise the one-argument result (:65). The doc (:49-56) gives the reason: the framework /Error page 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 E2eRenderModeTests can pin the precedence without a host.
  • Where it's used: MMCA.ADC.UI.Web's App.razor exposes PageRenderMode => 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 MapRazorComponents chain (class doc, RazorComponentsEndpointExtensions.cs:7-9); today one: AllowHead(), which lets every page endpoint answer HEAD as well as the methods it already accepts.
  • Depends on: nothing first-party. Externals: RazorComponentsEndpointConventionBuilder.Finally, IHttpMethodMetadata / HttpMethodMetadata and HttpMethods.Head.
  • Concept introduced, an endpoint Finally convention. Endpoint conventions normally run in registration order; a Finally convention 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 lists GET and POST explicitly without HEAD, so an uptime probe, link checker or crawler sending HEAD / gets a 404 for a page a GET renders; the .NET 11 endpoint already lists HEAD, so there the call changes nothing. [Rubric §9, API & Contract Design] assesses whether HTTP semantics are honored; this restores the rule that a resource answering GET also answers HEAD.
  • Walkthrough
    • AllowHead(this RazorComponentsEndpointConventionBuilder) (:28): a classic this extension (not an extension(T) block). It throws on a null builder and registers a static Finally lambda (:32).
    • Inside, it takes the last IHttpMethodMetadata on the endpoint (:34). An endpoint with none, or with an empty method list, already matches every method including HEAD, so it returns (:35-38). If HEAD is already listed (case-insensitive) it returns (:40-43).
    • Otherwise it appends a new HttpMethodMetadata naming the existing methods plus HEAD, carrying over AcceptCorsPreflight (:45). The remarks (:20-25) note routing honors the last method metadata, so appending is enough and a form page keeps its POST.
    • Returns the builder for chaining (:48). The server answers the HEAD with the GET response's status and headers and no body (:17-18).
  • Why it's built this way: reading the final metadata instead of hard-coding GET, HEAD is 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 the MapRazorComponents chain 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, and System.Reflection for the embedded scripts and the assembly version. The two scripts it serves, Pwa/service-worker.js and Pwa/service-worker-retired.js, are compiled into the assembly as embedded resources under the logical name MMCA.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): setting Pwa:ServiceWorker:Enabled to false serves 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.
  • 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.
    • ActiveScript and RetiredScript (:28, :30): Lazy<string> fields, so each script is read from the manifest and version-stamped once per process.
    • MapCommonServiceWorker() (:60-70), an IEndpointRouteBuilder extension (the extension(IEndpointRouteBuilder) block at :32): maps GET on ServiceWorkerPath, sets Cache-Control: no-cache so the browser revalidates the worker on every update check (:63), reads EnabledKey with a default of true on every request and picks the active or retired script (:64-66), and returns it as text/javascript in 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 the RouteHandlerBuilder for further conventions.
    • ReadScript(string) (:73-84): opens the embedded resource MMCA.Common.UI.Web.Pwa.{fileName} and throws InvalidOperationException naming the file and assembly when it is missing (:76-77); resolves the version from AssemblyInformationalVersionAttribute, then AssemblyName.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 under EnabledKey=false and the route.
  • Caveats / not-in-source: the fetch-handler and cache-deletion behavior lives in the two embedded .js files, 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 CircuitHandler that refuses a new circuit once this replica already holds BlazorCircuitLimitSettings.MaxActiveCircuits active circuits, and counts circuits back down as they close.
  • Depends on: CircuitHandler (base class), IOptions<BlazorCircuitLimitSettings> and ILogger<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 than CircuitOptions: DisconnectedCircuitMaxRetained bounds 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: OnCircuitOpenedAsync returns Task with 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 through OnCircuitClosedAsync, 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 through ActiveCircuits (: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; BoundedCircuitHandlerTests reads it to assert the increment, decrement and floor behavior without inspecting private state.
  • Walkthrough
    • _admitted (:47): a ConcurrentDictionary<Circuit, byte> constructed with ReferenceEqualityComparer.Instance, used as a set of the circuits this handler admitted.
    • _activeCircuits (:49) and ActiveCircuits => Volatile.Read(ref _activeCircuits) (:55): the live count, read with Volatile.Read because it is written from Interlocked calls 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): guards circuit against 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 via LogCircuitRefused, and returns a faulted Task carrying an InvalidOperationException telling the caller to retry (:75-80). Only an admitted circuit is added to _admitted (:83).
    • OnCircuitClosedAsync (:88-109): guards circuit against null (:90), then returns without touching the count unless _admitted.TryRemove finds 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 the partial class declaration.
  • 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 CircuitHandler by BlazorCircuitLimitExtensions's AddBoundedBlazorCircuits(), 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's MudServicesConfiguration.
  • 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 to AddCommonSerilog (for example logs/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 after AddServiceDefaults(), 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 passes rc => rc.AddInteractiveWebAssemblyComponents() (:32-35).
    • ConfigureMudServices (:42): configures MudBlazor; null registers it with defaults.
    • ConfigureFallbackAuthorization (:48): extends the fallback authorization policy (extra exempt path prefixes, for example); null keeps the framework defaults.
  • Why it's built this way: sealed with init properties and only LogFilePath required, 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 sets LogFilePath, ConfigureConfigurationSources (Key Vault), AfterServiceDefaults (Azure Monitor exporter and DataProtection), ConfigureRazorComponents (WebAssembly components) and ConfigureMudServices (snackbar position and cap), and leaves ConfigureFallbackAuthorization unset (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:27-65). Tests: BlazorWebHostExtensionsTests and the BlazorWebHostHarness under MMCA.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 IServiceCollection extension that registers the bounded-circuit handler, and a factory method that builds the CircuitOptions retention callback from configuration.
  • Depends on: BlazorCircuitLimitSettings, BoundedCircuitHandler; ASP.NET Core's IServiceCollection, IConfiguration, and Blazor's CircuitOptions/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 is CircuitOptions on AddInteractiveServerComponents, while the active-circuit ceiling is a CircuitHandler singleton 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 is AddSingleton and 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 to new BlazorCircuitLimitSettings() if the section is absent), and returns an Action<CircuitOptions> that copies DisconnectedCircuitMaxRetained and converts DisconnectedCircuitRetentionSeconds to a TimeSpan for DisconnectedCircuitRetentionPeriod (:37-39).
    • AddBoundedBlazorCircuits() (:51-61), an IServiceCollection extension: binds and validates BlazorCircuitLimitSettings (:55-58), then registers BoundedCircuitHandler as a singleton CircuitHandler (: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() and RetentionFrom are 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 IServiceCollection extension that builds a chained per-IP-and-global limiter from UiRateLimitingSettings, and an IApplicationBuilder extension that adds it to the pipeline. Every rejection is a 429, carrying a Retry-After header whenever the rejecting limiter can say when to come back.
  • Depends on: UiRateLimitingSettings; SameOriginApiProxySettings (its PathPrefix, read through the proxy's own options); RetryAfterRejection from MMCA.Common.RateLimiting (the shared OnRejected wrapper that writes Retry-After, :215); ClientAddressKey from MMCA.Common.RateLimiting (the per-IP partition key, :135); RemainingWindowFixedWindowRateLimiter from MMCA.Common.RateLimiting (the per-IP window, :146-154). Externals: System.Threading.RateLimiting (RateLimitPartition, FixedWindowRateLimiterOptions, ConcurrencyLimiterOptions, PartitionedRateLimiter, MetadataName); ASP.NET Core's AddRateLimiter/RateLimiterOptions/OnRejectedContext and UseRateLimiter; StaticAssetDescriptor from Microsoft.AspNetCore.StaticAssets (:6, read off the matched endpoint). The class carries a [SuppressMessage("Naming", "CA1708", ...)] attribute (:23-26) whose justification records why: with multiple extension(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 /healthz is 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 a StaticAssetDescriptor in its metadata (:105), that is, a real asset mapped by MapStaticAssets. A file extension alone exempts nothing: the doc comment (:66-74) notes that a path such as /missing.png that 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: a WebApplication inserts UseRouting ahead of the whole user pipeline. The ExemptPrefixes doc comment (:46-57) explains the /hubs entry mirrors the Gateway's own GatewayRateLimiting:BypassPathPrefixes bypass 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. /_blazor is 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, but BlazorTransportPrefix (: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 to IsExempt(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. AddUiRateLimiting assigns RateLimiterOptions.OnRejected through the shared RetryAfterRejection.WithRetryAfterHeader (:215; MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:42-52), so a 429 carries Retry-After in whole seconds rounded up (RetryAfterRejection.cs:27-31) whenever the rejecting lease exposes a MetadataName.RetryAfter hint (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.Web and MMCA.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's RateLimitPartition.GetFixedWindowLimiter, because, as the comment at :143-145 records, 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.
  • 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) and IsExempt(HttpContext, PathString) (:100-106): the shared exemption rule, detailed above; internal so it is unit-testable via InternalsVisibleTo (:75-78). The HttpContext overload null-guards the context (:102) and delegates the prefix check to the PathString overload (:104).
    • ClientIpPartition(HttpContext, UiRateLimitingSettings, PathString, TimeProvider?) (:120-155): no limiter for an exempt request (:129-132); otherwise the partition key is ClientAddressKey.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-process TestServer is never collapsed into one shared bucket), otherwise RateLimitPartition.Get keyed on that client key, building a RemainingWindowFixedWindowRateLimiter over FixedWindowRateLimiterOptions with QueueLimit = 0 (rejected immediately, not queued, :146-154). The optional timeProvider (:124) is the clock for the remaining-time hint; null, the production value, is the system clock. The options set no AutoReplenishment: 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-wide ConcurrencyLimiter, one bucket for the whole process with QueueLimit = 0, exempt for every request IsExempt(HttpContext, PathString) matches plus any path under BlazorTransportPrefix (:177).
    • AddUiRateLimiting(IConfiguration) (:196-241), an IServiceCollection extension: binds and validates UiRateLimitingSettings (:201-204), then resolves a plain instance from configuration to close over in the partition callbacks (:206-210) rather than resolving IOptions<T> per request, because the partition callback runs on the hot path of every request and an out-of-range value has already failed ValidateOnStart(). Its own AddRateLimiter call (:212-216) sets RejectionStatusCode to 429 and wraps OnRejected with RetryAfterRejection.WithRetryAfterHeader (:215); both apply even when Enabled is false, in which case the method returns early with no GlobalLimiter configured (:218-221). Otherwise it configures RateLimiterOptions through Configure<IOptions<SameOriginApiProxySettings>> (:226-238), reading the proxy's PathPrefix from the proxy's own options (:229) so the limiter and the proxy cannot disagree, and chains the client-IP and concurrency partitions with PartitionedRateLimiter.CreateChained (:233-237), so a request must satisfy both. The production chain passes no TimeProvider, so the window uses the system clock (:235).
    • UseUiRateLimiting() (:250-254), an IApplicationBuilder extension: calls the framework's UseRateLimiter().
  • 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: AddUiRateLimiting and UseUiRateLimiting are called by BlazorWebHostExtensions (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:96, :187), which MMCA.ADC.UI.Web's Program.cs reaches through AddMmcaBlazorWebHost (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:27); the extension methods live on the IServiceCollection/IApplicationBuilder extension blocks (:187, :244). In MMCA.Common.UI.Web.Tests, UiRateLimitingTests exercises the exemption rule and the partitions, UiRateLimitingRetryAfterTests the Retry-After header, and UiRateLimitingStaticAssetPipelineTests the static-asset exemption (all under MMCA.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 is UseExceptionHandler("/Error")). A net10.0 head with a WebAssembly client passes a => 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 of MapClientConfigEndpoint (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. The DevelopmentPipeline split follows the dual-framework line: .NET 11 debugs WebAssembly without the debug proxy middleware.
  • Where it's used: MMCA.ADC.UI.Web passes only ClientConfig under #if NET11_0_OR_GREATER and adds DevelopmentPipeline = a => a.UseWebAssemblyDebugging() in the #else branch (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: MudBlazor AddMudServices, Microsoft.Extensions.Http.Resilience ResilienceHandler, 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, DevelopmentPipeline and the head's own MapRazorComponents chain), 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), in extension(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, then ConfigureRazorComponents (: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:ApiEndpoint must be an absolute http(s) URL or an Aspire service-discovery name (ApiEndpointUrl.IsAbsoluteHttpOrServiceDiscovery), otherwise InvalidOperationException, 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, then AddHttpContextAccessor and a Replace of IForbiddenReExecutionDetector with the request-reading HttpContextForbiddenReExecutionDetector (only this server host can see a 403 re-executed to /not-found, :136-139), then ITokenRefresher as SameOriginProxyTokenRefresher and the same-origin API proxy. The proxy is registered after token storage because it replaces the circuit's ITokenRefresher and ISessionCookieSync (:132-133); the summary (:63-66) warns a head not to register either afterward, since MapCommonSameOriginApiProxy fails the boot when displaced (ADR-051).
    • Tail (:144-157): JwtAuthenticationStateProvider, cascading auth state, the distributed memory cache, antiforgery with CookieSecurePolicy.SameAsRequest (:153; the comment at :148-152 explains why not Always: 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), in extension(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 or UseExceptionHandler("/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 the Assembly of every registered IUIModule and de-duplicated keeping the first occurrence (:243-244).
    • RemoveApiClientResilienceHandler (:263, private): walks the "APIClient" handler list backward through ConfigureAdditionalHttpMessageHandlers and removes every ResilienceHandler (: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 one HttpClient.Timeout of HttpResilienceDefaults.TotalRequestTimeout (90 s, set by AddUIShared) 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 CA1708 suppression on the class (:40-43) is a documented false positive from having two extension(T) blocks in one static class (ADR-106).
  • Where it's used: MMCA.ADC.UI.Web's Program.cs is 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 own MapRazorComponents<App>() chain (:157), with its app-association endpoints mapped in between as the pipeline summary prescribes (BlazorWebHostExtensions.cs:174-177). Tests: BlazorWebHostExtensionsTests, BlazorWebPipelineTests and BlazorWebHostHarness under MMCA.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 LogFilePath doc example names a Store log file). The AddMmcaBlazorWebHost summary still lists "the web form factor" among the registrations (:60), but the body registers none and no AddCommonWebFormFactor remains 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 nullable Handoff string (SessionHandoffEndpoints.cs:91-92). It is a nested internal sealed record of SessionHandoffEndpoints.
  • 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 unprotects body.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 400 invalid_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) and ViewAsEnd (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: SameOriginApiProxyEndpoint picks the mode in ResolveMode (SameOriginApiProxyEndpoint.cs:315-349): every non-POST is Forward; a POST to the refresh path yields null (the proxy answers it itself); a POST to a token-issuing path is TokenIssuing; a POST to either sign-out path (RevokePath or RevokeCurrentPath) is Revoke (:330-335); a POST to ViewAsEndPath is ViewAsEnd (:337-340); a POST whose last segment is view-as is ViewAsGrant (:342-346); any other POST is Forward.
  • 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: SameOriginApiProxyEndpoint and SameOriginProxyTransformer only; it is internal.

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 class registered as a singleton only by AddCommonSameOriginApiProxy (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: SameOriginApiProxyEndpointExtensions throws when it is absent, naming the missing call (SameOriginApiProxyEndpointExtensions.cs:38-42); ClientConfigEndpointExtensions reads 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 to ApiSettings's ApiEndpoint.
  • Concept: options pattern with fail-fast validation, same shape as the other settings classes in this group (for example BlazorCspSettings with BlazorCspSettingsValidator). [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/5 is forwarded to {gateway}/orders/5.
    • GatewayAddress (:48): null by default; AddCommonSameOriginApiProxy fills it from Api:ApiEndpoint when unset (SameOriginApiProxyServiceExtensions.cs:57-64), so an Aspire discovery name such as https+http://gateway resolves as it does for the host's API clients.
    • AdditionalTokenIssuingPaths (:54): empty; a host adds paths such as auth/2fa/verify.
    • MaxRequestBodySizeByPath (:77): an empty, case-insensitive IDictionary<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 like RefreshPath (for example uploads/file); it covers that path and everything below it on a whole-segment boundary (uploads/file covers uploads/file/5, not uploads/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 by SameOriginApiProxyEndpoint and checked by SameOriginApiProxySettingsValidator.
    • 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 like RevokePath.
    • 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 is view-as is a view-as grant whose token goes into the overlay cookie and never reaches script (:101-107).
    • SessionCookieSameSite = SameSiteMode.Strict (:116); Lax is 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 copying SessionCookieSameSite onto SessionCookieSettings, SameOriginApiProxyServiceExtensions.cs:69-70), SameOriginApiProxySettingsValidator, SameOriginApiProxyEndpoint, SameOriginApiProxyEndpointExtensions and ClientConfigEndpointExtensions.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 IDisposable holder for the one HttpMessageInvoker YARP's forwarder sends every proxied request through (SameOriginProxyInvoker.cs:19,37).
  • Depends on: IServiceDiscoveryHttpMessageHandlerFactory (Microsoft.Extensions.ServiceDiscovery), SocketsHttpHandler, YARP's ReverseProxyPropagator.
  • Concept: YARP's IHttpForwarder expects a long-lived invoker with a transport tuned for proxying, not a pooled HttpClient. [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 with disposeHandler: false and the class keeps _ownedHandler to dispose itself (:22,39-43).
    • An internal ctor takes a test-supplied handler, for example a TestServer's (:34-35); that handler is not owned or disposed.
    • CreateHandler (:45-69) configures SocketsHttpHandler: UseProxy = false, AllowAutoRedirect = false, no automatic decompression, UseCookies = false, multiple HTTP/2 connections, ConnectTimeout 15 s, and a ReverseProxyPropagator over DistributedContextPropagator.Current (:50-59). When discovery is registered it wraps the transport (:61) so https+http://gateway resolves. The null-out-then-finally pattern disposes the transport only if wrapping throws.
  • 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 by SameOriginApiProxyServiceExtensions.cs:74, and built from a handler in the test harness MMCA.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) of SessionHandoffProtector (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 in UnprotectTokenPair, 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 struct describing what one forwarded request does with the view-as overlay cookie (ADR-137): OverlayPresent, ForwardsOverlayBearer, DeleteOverlay and the SameSite mode 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, is ViewAsOverlayCookie.
  • Walkthrough:
    • Built by ResolveOverlay in SameOriginApiProxyEndpoint (SameOriginApiProxyEndpoint.cs:410-422): OverlayPresent when the cookie exists; ForwardsOverlayBearer when the overlay is live (unexpired) and the mode is neither TokenIssuing nor Revoke, in which case the overlay's token replaces the session bearer; DeleteOverlay when the cookie is present but no longer live; SameSite copied from SameOriginApiProxySettings.SessionCookieSameSite.
    • Read by SameOriginProxyTransformer in ShouldDeleteOverlay (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).
    • ForwardsOverlayBearer also turns off the endpoint's 401 capture (SameOriginApiProxyEndpoint.cs:238-239), so a view-as bearer is never refreshed or replayed.
  • 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: SameOriginApiProxyEndpoint and SameOriginProxyTransformer only; it is internal.

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 to BlazorCspSettingsValidator. [Rubric §11, Security] applies to the SameSite check: only Strict or Lax pass, because the cookie now authenticates data calls (:42-45).
  • Walkthrough:
    • ForbiddenPathCharacters = {}*?#\ (:18): route syntax, query, fragment and backslash.
    • PathPrefix must pass IsValidPrefix (: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.
    • GatewayAddress must be an absolute URI with a host (:35-40); the message names the Api:ApiEndpoint fallback.
    • RefreshPath, RevokePath, RevokeCurrentPath, ViewAsEndPath and every AdditionalTokenIssuingPaths entry must pass IsValidRelativePath (:47-51,79-84): not blank after trimming /, no whitespace, no forbidden char, no ://.
    • Every MaxRequestBodySizeByPath entry (:53-66): the key must pass the same IsValidRelativePath, and the limit must be positive (limit <= 0 fails), 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 TryAddEnumerable by SameOriginApiProxyServiceExtensions.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); nested TokenPair.
  • 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 for AccessToken, one for TokenPair (:21-27), so a blob minted for one cannot be opened as the other.
    • ProtectAccessToken / UnprotectAccessToken (:29,31); ProtectTokenPair serializes a TokenPair to JSON (:33-34); UnprotectTokenPair returns a tuple or null on a missing, blank or malformed pair (:36-55).
    • TryUnprotect (:57-73) maps null or whitespace input, and CryptographicException or FormatException (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 at SameOriginApiProxyServiceExtensions.cs:76; tested in MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/SameOriginProxy/SameOriginApiProxyAuthFlowTests.cs and SessionHandoffServicesTests.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 ISessionCookieSync for 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 (compare JsFetchSessionCookieSync).
  • Walkthrough: SyncAsync calls mmcaAuthHandoff.setCookie with ProtectTokenPair(...) (:55-65); the script posts it to /auth/session-cookie/handoff (see SessionHandoffEndpoints). ClearAsync calls mmcaAuthCookie.clear (:67-77). Both return false when interop is unavailable, as decided by the shared JsInteropFailure.IsUnavailable filter (:61,73; the set is InvalidOperationException, JSDisconnectedException, JSException, OperationCanceledException, MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/JsInteropFailure.cs:27-30).
  • Where it's used: registered with Replace as scoped (SameOriginApiProxyServiceExtensions.cs:81) and verified at map time by SameOriginApiProxyEndpointExtensions.
  • Caveats / not-in-source: the mmcaAuthHandoff / mmcaAuthCookie JavaScript 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 (an ITokenRefresher) 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 (compare DirectApiTokenRefresher).
  • Walkthrough: AcquireAccessTokenAsync is a thin wrapper that returns the AccessToken of TryAcquireAccessTokenAsync (:17-18). The latter calls mmcaAuthHandoff.getToken (:25), whose script calls /auth/session/handoff and answers null only for the endpoint's 401. A null handoff yields TokenAcquisition.NoSession (:26-29). Otherwise the blob is unprotected server-side (:33): a non-empty token yields Acquired, while an empty result (expired handoff, or a key this host does not hold) yields Unavailable because it says nothing about the session itself (:33-35). Any failure the shared JsInteropFailure.IsUnavailable filter accepts (SSR prerender, a disconnected circuit, a cancelled call, or a transient endpoint failure surfacing as a JSException) also yields Unavailable (:37-42).
  • Where it's used: registered with Replace as scoped (SameOriginApiProxyServiceExtensions.cs:80); tested in SessionHandoffServicesTests.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 HttpTransformer that rewrites the outbound request (path, bearer, cookies) and treats the response according to its ProxyResponseMode and its ViewAsOverlayTreatment (SameOriginProxyTransformer.cs:51-58).
  • Depends on: ISessionCookieStore, SessionCookieEndpoints (cookie names), ViewAsOverlayCookie, SessionClaimsToken, AuthClaimTypes, SameOriginProxyHeaders; YARP HttpTransformer and RequestUtilities, JwtSecurityTokenHandler, ASP.NET Core Data Protection IDataProtectionProvider (passed to the overlay cookie write, :57,212), and TimeProvider.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), sets Authorization: Bearer from 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 in TokenIssuing or ViewAsGrant mode clears Accept-Encoding so the body arrives as plain JSON (:83-87).
    • TransformResponseAsync (:90-127): when captureUnauthorized is on and upstream answered 401, sets UnauthorizedCaptured and copies nothing so the endpoint can replay (:95-99); deletes the overlay cookie when ShouldDeleteOverlay says so (:103-106); in Revoke clears the session cookies whatever upstream said (:108-113); in TokenIssuing on success hands off to CompleteTokenIssuingAsync (:115-118); in ViewAsGrant on 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 with no-store and 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), on ViewAsEnd or Revoke, 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 from TimeProvider.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 replaces accessToken with 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), replaces accessToken with its claims-only form and empties refreshToken (:259-260), and sets no-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 the Cookie header; 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 from SameOriginApiProxySettings.MaxRequestBodySizeByPath before 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 Protection IDataProtectionProvider (reads the protected overlay cookie and hands the provider to the transformer, :35,413,425,449), SameOriginProxyInvoker, ICookieSessionRefresher with SessionRefreshOutcome / 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 with Retry-After and keeps the session.
  • Walkthrough:
    • Config: RequestConfig uses a 100 s activity timeout and HTTP/1.1 with RequestVersionOrLower (:48-53), which lets YARP turn an HTTP/2 WebSocket into an HTTP/1.1 upgrade; DefaultRetryAfter 5 s (:56); _tokenIssuingPaths merges the defaults and additions case-insensitively (:59-63); _bodySizeLimits holds the configured (PathString, long) caps ordered longest path first, so the most specific entry wins (:65-71); ViewAsGrantSegment = view-as names 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); runs TryAnswerBeforeForwardingAsync; normalizes the gateway-relative path and calls ApplyBodySizeLimit (:89-92), safe because nothing above has read the body and the forward is the first read; resolves the mode, with null meaning RefreshLocallyAsync (:94-99); calls ResolveOverlay (:101), and only when the overlay's bearer is not forwarded, for non-sign-in requests that carry a session cookie, calls ValidateOrRefreshAsync and fails via FailRefreshAsync when no session results (:102-113); forwards with 401 capture decided by CapturesUnauthorized (:115-116); replays on capture (:118-121).
    • ResolveOverlay (:410-422): builds the ViewAsOverlayTreatment. The overlay counts as live only when ViewAsOverlayCookie.TryRead unprotects it with the Data Protection provider and it has not expired (:413). A live overlay's token replaces the session bearer for every mode except TokenIssuing (anonymous) and Revoke (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 or IHttpMaxRequestBodySizeFeature is 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, sets MaxRequestBodySize. This is what stops an upload the API accepts being refused 413 by the UI host first.
    • Gates, in order (TryAnswerBeforeForwardingAsync, :254-283): CrossOriginRejection (403 cross_origin_rejected); OPTIONS answered 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's Origin intact because SameOriginProxyTransformer keeps 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 (403 csrf_header_required). HasCsrfHeader requires exactly one header value equal to SameOriginProxyHeaders's value (:127-130).
    • CrossOriginRejection (:148-154): OriginRejection refuses a foreign Origin and an upgrade with no Origin (:197-205); IsOwnOrigin compares scheme and server against the request as seen after forwarded headers, refusing paths, user info and the null origin (:163-177); FetchSiteRejection allows same-origin, and none only on a non-upgrade GET or HEAD (:207-224). IsWebSocketExtendedConnect detects 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): Rejected ends the session (clear cookies, 401 session_expired, :286-290); anything else answers 503 session_refresh_unavailable with Retry-After from upstream or 5 s.
    • RefreshAndReplayAsync (:356-367): resets status to 200, forces RefreshAsync, 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); ForwardAsync logs a forward error only if the client did not abort (:427-437).
  • 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; its HasCsrfHeader is reused by SessionHandoffEndpoints (SessionHandoffEndpoints.cs:32,62); registered as a singleton at SameOriginApiProxyServiceExtensions.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; YARP AddHttpForwarder, Data Protection.
  • Walkthrough:
    • Binds SameOriginApiProxySettings, post-configures the gateway from Api:ApiEndpoint when unset, ValidateOnStart (:56-66), and adds the validator (:67-68).
    • Configures SessionCookieSettings: only SameSite, 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 and SameOriginApiProxyMarker (:75-78).
    • Replaces the scoped ITokenRefresher and ISessionCookieSync with HandoffTokenRefresher and HandoffSessionCookieSync (:80-81).
  • Why it's built this way: opt-in per host; a host that never calls it is unchanged (ADR-131). Replace means call order matters, which MapCommonSameOriginApiProxy checks.
  • Where it's used: paired with SameOriginApiProxyEndpointExtensions; exercised in MMCA.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/Source other 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/handoff and POST /auth/session-cookie/handoff (SessionHandoffEndpoints.cs:19-20,22).
  • Depends on: ICookieSessionRefresher, ISessionCookieStore, ViewAsOverlayCookie, SessionHandoffProtector, SameOriginApiProxyEndpoint (HasCsrfHeader), HandoffBody, SessionCookieSettings (the SameSite mode the overlay is deleted with); ASP.NET Core Data Protection IDataProtectionProvider, injected into the token handoff handler (:29), and IOptions<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 a HandoffBody with the overlay's protected token so the circuit holds what the page is viewing as, never refreshed (:37-43); otherwise calls GetOrRefreshAsync on the cookie session and answers 401 no_session or a HandoffBody with 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 (400 invalid_handoff on 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/token and 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.
  • Where it's used: called from MapCommonSameOriginApiProxy (SameOriginApiProxyEndpointExtensions.cs:54); reached from the browser by HandoffTokenRefresher and HandoffSessionCookieSync through 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 InvalidOperationException if the marker is absent (:38-42).
    • VerifyCircuitRegistrations (:64-69) resolves ITokenRefresher and ISessionCookieSync in a scope; a resolved type other than the handoff implementation throws, telling the host to call AddCommonSameOriginApiProxy after every such registration (:71-92). A missing dependency such as IJSRuntime (no interactive Server circuit) skips the check (:79-83).
    • Maps the proxy route to proxy.InvokeAsync as ExcludeFromDescription, AllowAnonymous, DisableAntiforgery (:49-52), then SessionHandoffEndpoints.Map (:54).
  • Why it's built this way: a later ITokenRefresher registration would put the access token back in the page on every Server-circuit hydration (:59-63); the doc comment asks hosts to map it after UseAuthorization (: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-config endpoint and the Blazor Web host registration, so a deployment placeholder such as SET-VIA-ENVIRONMENT-VARIABLE is 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:ApiEndpoint and Api: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 when Uri.TryCreate(..., UriKind.Absolute, ...) succeeds AND the scheme is http or https (ApiEndpointUrl.cs:37-39), because on Linux a rooted path such as /relative/path parses as an absolute file:// URI (doc, lines 27-30).
    • [Rubric §26, Front-End Security] assesses browser-side hardening: the CSP's connect-src origin 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 parsed Uri ([NotNullWhen(true)], line 35), otherwise uri is null.
    • IsAbsoluteHttp(string? value) (line 52) is the boolean form of the same test.
    • IsAbsoluteHttpOrServiceDiscovery(string? value) (lines 63-74) accepts everything IsAbsoluteHttp does, plus an Aspire service-discovery URL whose scheme is a +-joined list made only of http and https, such as https+http://gateway (lines 70-73). The doc (lines 54-60) scopes it: that form is valid only for the server head's Api:ApiEndpoint, which IHttpClientFactory clients resolve through the service-discovery handler AddServiceDefaults() adds; a browser cannot, so Api:WasmApiEndpoint uses IsAbsoluteHttp.
    • IsHttpScheme (lines 76-78) compares the scheme to Uri.UriSchemeHttp and Uri.UriSchemeHttps with StringComparison.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 TryParseAbsoluteHttp to pin connect-src (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Security/BlazorCspPolicyProvider.cs:55); ClientConfigEndpointExtensions.MapClientConfigEndpoint throws when Api:WasmApiEndpoint fails IsAbsoluteHttp (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/ClientConfig/ClientConfigEndpointExtensions.cs:88-95); BlazorWebHostExtensions throws at registration when Api:ApiEndpoint fails IsAbsoluteHttpOrServiceDiscovery (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:114-121). Pinned by ApiEndpointUrlTests (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 HttpClient handler 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), BCL Uri.
  • 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), and SendAsync only 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 same HttpClient happens to call. ADR-088 is the policy this enforces on the client side.
  • Walkthrough
    • The constructor (TrustedCallerHandler.cs:39-48) null/blank-guards headerName and secret and null-guards gatewayOrigin, storing all three as readonly fields.
    • SendAsync (TrustedCallerHandler.cs:51-72) null-guards the request, then compares request.RequestUri against _gatewayOrigin with Uri.Compare over UriComponents.Scheme | UriComponents.HostAndPort, case-insensitive (TrustedCallerHandler.cs:57-63). On a match it removes any existing value for the header and adds exactly one via TryAddWithoutValidation (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 calls base.SendAsync unconditionally.
  • Why it's built this way: a DelegatingHandler composes into the existing HttpClient pipeline 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 by TrustedCallerHandlerTests (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-src allowance 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 BuildFrameSrc and validated at startup by BlazorCspSettingsValidator. Externals: Microsoft.Extensions.Options binding conventions (BCL IList<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 no frame-src directive 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 https origin 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.
  • Walkthrough: two members: SectionName (line 28, a public const string) and FrameSources (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 adding frame-src support 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 as IOptions<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 HttpClient handler that stamps the visitor's browser origin (X-Forwarded-For with its address, User-Agent with 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 is RemoteIpAddress, 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-supplied X-Forwarded-For is 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) and UserAgentHeaderName (line 38).
    • SendAsync (lines 41-55) null-guards the request, reads httpContextAccessor.HttpContext (line 47) and, only when a request is in scope, calls Replace for the connection's remote address (line 50) and the request's User-Agent (line 51), then calls base.SendAsync unconditionally (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 via TryAddWithoutValidation (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.
  • Why it's built this way: a DelegatingHandler composes 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 by AddCommonServerTokenStorage() in the MMCA.Common.UI.Web DependencyInjection (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 by BrowserOriginHandlerTests (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 a frame-src origin 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), BCL SearchValues<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 configured FrameSources entry through IsValidOrigin and 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, a SearchValues<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 calls Uri.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-guards options, projects every entry that fails IsValidOrigin into a message naming the section, the entry, and the shape it must satisfy (lines 26-30), and returns ValidateOptionsResult.Success only when that list is empty.
    • IsValidOrigin(string? source) (lines 34-49), internal static: rejects null, whitespace-only, any entry containing whitespace, anything matching ForbiddenCharacters, or anything Uri.TryCreate cannot parse as absolute (lines 36-41). What remains must be https (ordinal case-insensitive), have a non-empty host, and have PathAndQuery equal 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 canonical scheme://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 Uri alone, because Uri will 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); ToOrigin is reused by BlazorCspPolicyProvider's BuildFrameSrc to 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-found from 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-found is 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, TryAddSingleton at MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:262) and this server-side reader replaces it. During static server rendering IHttpContextAccessor returns the request being rendered; with no request in scope the answer is false, 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 as false.
  • 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 touch HttpContext; an interface with a false default there and an HttpContext reader in the server host keeps the page head-agnostic.
  • Where it's used: registered by BlazorWebHostExtensions with services.Replace(ServiceDescriptor.Singleton<IForbiddenReExecutionDetector, HttpContextForbiddenReExecutionDetector>()) right after AddHttpContextAccessor() (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 by HttpContextForbiddenReExecutionDetectorTests (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-src to 'self' plus the configured API or Gateway origin (https and its matching WebSocket origin), optionally adding an opt-in frame-src directive, 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 Enforce flag), SecurityHeadersMiddleware (its only consumer, named in the class doc at line 12), ApiSettings (the endpoint source, injected as IOptions<ApiSettings>, line 34), ApiEndpointUrl (the shared endpoint test, TryParseAbsoluteHttp, line 55), and BlazorCspSettings (the frame-src source, injected as IOptions<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), BCL Uri.
  • 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 computed connect-src (line 65). The load-bearing decision is what happens when the origin cannot be determined. The provider narrows connect-src to '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 deliberately internal (line 28) so the only supported way to get it is the registration call, not a hand-wired new.
    • frame-src is opt-in and null-safe. BlazorCspSettings's default is an empty FrameSources list, and BuildFrameSrc (line 82) returns null when 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 single CspPolicy field computed once. The constructor (lines 33-42) null-guards apiOptions, cspOptions, and environment and calls BuildCsp(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-computed frameSrc as a parameter and resolves the endpoint as api.WasmApiEndpoint ?? api.ApiEndpoint (line 51). The guard on line 55 delegates to ApiEndpointUrl.TryParseAbsoluteHttp, the same test /client-config and AddMmcaBlazorWebHost apply 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/path parses as an absolute file:// URI. A rejected endpoint returns the enforced connect-src 'self' policy, still carrying frameSrc (line 59).
    • With a valid endpoint it derives origin via apiUri.GetLeftPart(UriPartial.Authority) (line 63, scheme://host:port), picks wss or ws to match (line 64), and composes connect-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 opening connect-src to the world.
    • Development only (lines 71-74) appends http://localhost:* and ws://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) returns null on an empty FrameSources (lines 84-87), so the directive is omitted entirely rather than emitted empty; otherwise it maps every entry through BlazorCspSettingsValidator.ToOrigin, de-duplicates with StringComparer.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) takes frameSrc as a parameter and assembles the directive list: default-src 'self', the script-src above 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 computed connect-src, the frame-src directive 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', and frame-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 (not TryAdd) is what makes it replace the default static provider, which is why the ordering rule in the class doc (lines 25-26) matters: call AddCommonBlazorCsp() before AddCommonSecurityHeaders. frame-src is threaded through as a plain string? parameter rather than read a second time inside BuildPolicy, 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-config would refuse.
  • Where it's used: registered by AddCommonBlazorCsp() in the MMCA.Common.UI.Web DependencyInjection with AddSingleton<ICspPolicyProvider, BlazorCspPolicyProvider> (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/DependencyInjection.cs:66-76, whose XML doc, lines 53-58, describes the enforced connect-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 by BlazorCspPolicyProviderTests (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/token endpoint, or the protected /auth/session/handoff when 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 SessionEnded event and the defaulted RenewRejectedAccessTokenAsync, 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-second DefaultExpirySkew, 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), BCL Lock, 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 HttpContext exists and JS interop does not, and then as a stateful circuit whose HttpContext is 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 in TryAnswerFromCookie (lines 306-334, called at line 90), which looks at whether an HttpContext exists and whether memory has yet become authoritative.
    • Cookie-first answer (TryAnswerFromCookie, lines 306-334): when an HttpContext exists and memory is not yet authoritative, the request's HttpOnly cookie is read via cookieTokenReader.ReadAccessToken() (line 315). On a page request being prerendered (not IsHubConnection, 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 SignalR HubMetadata or 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.IsFresh with JwtTokenInfo.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 _accessToken field (line 61). If JwtTokenInfo.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. SetTokensAsync throws InvalidOperationException("The session cookie could not be written.") when SyncAsync returns false (lines 197-200), after the in-memory token is already set, so AuthUIService reports Auth.TokenStorageUnavailable instead 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). ClearTokensAsync discards the boolean (_ = await sessionCookieSync.ClearAsync(), line 214), because logout is best-effort by contract (IAuthUIService.LogoutAsync never fails); a caller that needs proof the session ended uses IAuthUIService.RevokeAllSessionsAsync (comment above it).
    • Anonymous grace, so a signed-out visitor costs one token round trip, not one per API call. AnonymousGrace is a 15-second static readonly TimeSpan (line 56). When a hydrate returns no token and the refresher did not report itself unavailable, HydrateAsync sets _anonymousUntil = now + AnonymousGrace (line 283); GetAccessTokenAsync then answers null from memory while _accessToken is null and the clock is before _anonymousUntil (line 101). SetTokensAsync resets _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 implementing ISessionAwareTokenRefresher reports 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 _sessionHeld flag (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 an ISessionAwareTokenRefresher whose answer is null and not unavailable) while _sessionHeld is true, it clears the flag and raises SessionEnded (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 to RenewRejectedAccessTokenAsync (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).
  • Walkthrough
    • The primary constructor (lines 48-53) takes IHttpContextAccessor, CookieTokenReader, ISessionCookieSync, and ITokenRefresher, and a nullable TimeProvider with no default value (a null falls back to TimeProvider.System, line 59). It is the type's only constructor. The type is sealed and 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, a static readonly TimeSpan of 15 seconds), the Lock _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), the volatile _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 the volatile _sessionHeld (line 83). The class holds no expiry-skew field of its own: both freshness checks (lines 96 and 333) pass the shared JwtTokenInfo.DefaultExpirySkew (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/Tokens/JwtTokenInfo.cs:24). The public SessionEnded event (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 inside lock (_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; HydrateAsync reaches its first await immediately, so nothing slow runs under the lock. The finally (from line 121) clears _hydrateInFlight only 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 an HttpContext exists 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 through AwaitHydrateAsync (line 172).
    • GetRefreshTokenAsync (lines 175-182): returns cookieTokenReader.ReadRefreshToken() (line 180) whenever an HttpContext exists, the live request during SSR and, on the circuit, the hub-connection request whose cookie can be as stale as the class remarks describe; otherwise null. The refresh token is never held in memory. It wraps the value in Task.FromResult rather than being async.
    • 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 awaits sessionCookieSync.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 raises SessionEnded, awaits sessionCookieSync.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 _hydrateInFlight under 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 an ISessionAwareTokenRefresher, calls TryAcquireAccessTokenAsync() (line 262) and keeps the token, the IsUnavailable flag and the derived definitiveNoSession (line 265); otherwise it calls AcquireAccessTokenAsync() (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 _accessToken is returned (lines 272-275). Otherwise the token is cached, memory is marked authoritative (line 279), a null token with unavailable false 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 raises SessionEnded. Every await on the hydrate path uses ConfigureAwait(false) (lines 119, 232, 262, 269), the library posture the cookie-write awaits do not take.
  • 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 on HttpContext presence 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. SessionEnded exists 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 the MMCA.Common.UI.Web DependencyInjection (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 with AddMmcaBlazorWebHost (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 to SessionEnded when the registered storage is session-aware (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/JwtAuthenticationStateProvider.cs:52, handler OnSessionEnded at line 145) to sign the circuit out. Pinned by ServerTokenStorageServiceTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/Services/ServerTokenStorageServiceTests.cs).
  • Caveats / not-in-source: the cookie names, lifetimes, and the /auth/session/token and /auth/session/handoff endpoints themselves are not in this file; they live in the MMCA.Common.API session-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 exports inertOutside and release (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 the inert attribute 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's inert.
  • Walkthrough
    • ApplyAsync(ElementReference lockRoot) (AppLockInertBackground.cs:28-44) imports the module through GetOrImportAsync (:32), calls inertOutside with the overlay wrapper (:33) and only then sets IsApplied (:34). JSDisconnectedException (circuit gone) and JSException (the browser refused) are both swallowed (:36-43): the comment at :42 notes 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), clears IsApplied before the call (:55), invokes release (: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 synchronous Dispose(bool) (BiometricGate.razor.cs:103-108). Keeping IsApplied means a release with nothing applied costs no interop call at all.
  • Where it's used: only BiometricGate, which creates it lazily through its InertBackground property (BiometricGate.razor.cs:48); pinned through BiometricGateTests (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:87 renders 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), the IsViewAs extension on ClaimsPrincipalExtensions (ClaimsPrincipalExtensions.cs:170), and ComponentLifetimeExtensions for LifetimeToken() (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's exp claim, 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, /api when unset (:134).
    • Remaining(ClaimsPrincipal?, DateTimeOffset) (:48-58) is public and static, so it is testable without rendering: it parses exp as invariant Unix seconds (:50-51), returns null when the claim is missing or unreadable (:53), and clamps a past expiry to TimeSpan.Zero (:56-57).
    • OnParametersSetAsync (:70-76) sets _viewAs from IsViewAs() (:73), takes the display name from Identity.Name or the ClaimTypes.Name claim (:74), and turns the remaining time into an absolute _expiresAt (:75).
    • OnAfterRender (:79-87) starts a one-second PeriodicTimer on the first render, only for a view-as principal and only when RendererInfo.IsInteractive (:82); the comment (:81) records that a prerender shows the starting value only. FormatRemaining (:89-98) renders the time left as mm:ss (:97), never negative.
    • TickAsync (:100-122) re-renders every tick (:106) and, once _expiresAt has passed, dispatches EndAsync and stops (:107-111). Cancellation and an ObjectDisposedException between ticks both end the loop quietly (:114-121).
    • EndAsync (:124-141) is guarded by _ending (:126-131) and calls the mmcaViewAs.end script with {prefix}/auth/view-as/end (:134). Any failure that JsInteropFailure.IsUnavailable classifies as interop being unavailable (an InvalidOperationException, JSDisconnectedException, JSException or OperationCanceledException, 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 _ending keeps 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 by ViewAsComponentTests (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 mmcaViewAs script 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.ViewAsUsers and the HasPermissionClaim and IsViewAs extensions 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 without ViewAsUsers and 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: UserId is [EditorRequired] and typed through the UserIdentifierType alias (:32-35); ApiPathPrefix defaults to /api and UsersRoute to Admin/Users when unset (:39, :46, applied at :86-88).
    • OnParametersSetAsync (:56-60) computes _canViewAs from 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-as with an invariant string.Create (:86-88), and awaits mmcaViewAs.start with 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 exception JsInteropFailure.IsUnavailable accepts (an InvalidOperationException, JSDisconnectedException, JSException or OperationCanceledException, which covers a TaskCanceledException; :97-100, JsInteropFailure.cs:27-31), shows the localized Auth.ViewAs.Refused text. _starting clears in finally (:101-104).
  • 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 by ViewAsComponentTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/ViewAsComponentTests.cs) and ADC's ViewAsTests E2E 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 the IStringLocalizer (:32) and ComponentLifetimeExtensions for LifetimeToken() (: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
    • SignIns is 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 calls StateHasChanged when the lookup resolved a zone (:46-49); the comment (:45) records that the zone is only readable once JS is available.
    • Row helpers: DescribeDevice returns the localized Auth.SignIns.ViewedBySupport text for a ViewAs row and otherwise UserAgentSummary.Describe(signIn.Device, signIn.UserAgent, L) (:71-74); DescribeIpAddress falls back to Auth.Sessions.IpUnknown when the address is blank (:76-77).
    • DescribeStatus (:79-89) maps a row with no end reason and no EndedAt to "Active", each SignInEndReasons constant (SignedOut, ReuseDetected, SessionCapExceeded, AccountDeleted, Expired) to its own localized text, and ViewAsEnded and any unknown reason to the generic "Ended" text (:87-88).
    • FormatInstant calls ViewerTime.Format (:91).
    • Disposal: IDisposable with an idempotent protected Dispose(bool) that cancels and disposes the CancellationTokenSource bounding 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 Sessions page (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 by SignInHistoryTableTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/SignInHistoryTableTests.cs) and ADC's UserDetailTests.

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 the IStringLocalizer (UserSessionsTable.razor.cs:31) and ComponentLifetimeExtensions for LifetimeToken() (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
    • Sessions is an [EditorRequired] parameter defaulting to an empty list (UserSessionsTable.razor.cs:27-29).
    • OnAfterRenderAsync runs the zone lookup on first render only, skips it once disposed, and calls StateHasChanged when the lookup resolved a zone (UserSessionsTable.razor.cs:42-49).
    • Row helpers: DescribeDevice passes the session's recorded Device and its UserAgent to UserAgentSummary.Describe (:69), DescribeIpAddress falls back to the localized Auth.Sessions.IpUnknown text when the address is blank (:71-72), and FormatInstant calls ViewerTime.Format (:74).
    • Disposal: the component implements IDisposable with the usual protected Dispose(bool); it cancels and disposes the CancellationTokenSource that 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 by UserSessionsTableTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/UserSessionsTableTests.cs) and ADC's UserDetailTests.

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 through IStringLocalizer (line 34) for every heading, column, operation name and the "System" label. The markup reuses the framework's ListNoRecordsContent (retry on failure) and EmptyState (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 a FetchPage delegate (page number, page size, token in; a Result of 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-fetch CancellationTokenSource means a superseded or disposed fetch can never write rows into the panel.
  • Walkthrough:
    • Parameters: FetchPage is [EditorRequired] (lines 40-42), PageSize defaults to 20 (line 45), Title falls back to the shared AuditHistory.Title text (line 48; markup line 6), and UserLabel, PropertyLabel and DisplayTimeZone (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.
    • OnParametersSet throws InvalidOperationException when no FetchPage was supplied (lines 100-106). OnInitializedAsync loads page 1 only when RendererInfo.IsInteractive (line 110), so nothing is fetched during prerender.
    • LoadPageAsync (line 117) bumps _generation first (line 126), swaps in a fresh token source and cancels the previous one (line 133), then calls FetchPage(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 _hasMore when the page came back full (line 161) and _firstPageEmpty for an empty page 1 (line 162). A cancellation caused by its own token is swallowed (line 164).
    • LoadMoreAsync asks for the next page (line 113), RetryAsync re-fetches the failed page (line 115), and the public ReloadAsync (line 64) clears every row and state flag and fetches page 1 again.
    • Formatting helpers: WhenText converts ChangedOn from UTC into DisplayTimeZone and appends the zone name (line 181), WhoText shows AuditHistory.System for a change with no user (lines 188-192), and FieldText blanks a row with no property name (line 198).
    • Dispose(bool) cancels and disposes the in-flight token source (lines 83-96).
  • 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 own AuthorizeView on 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 its Errors (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: MessageFor compares the field's current value to the stored one and returns null once they differ.
  • Walkthrough
    • The positional record struct carries Value and Message (ChangePasswordCard.razor.cs:198); the default instance 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 equals matchCode, and returns default when 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).
    • TargetsField returns 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 with AsSpan().LastIndexOf('.') (:223). The comment (:214-215) records why only the last segment counts: a validator over the request yields NewPassword, one over the command yields Request.NewPassword, in either casing once it crossed the wire.
  • 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: ShowFieldRefusalsAsync builds 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: ComponentBase and IDisposable (MultiFactorRequiredListener.cs:24), ITokenStorageService (:28), NavigationManager (:30), MultiFactorRequiredSignal for the subscription (:41), ReturnUrlProtector (:93) and TwoFactorUIModule.AccountPath (:51, :95; "/profile/two-factor" at TwoFactorUIModule.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 through ReturnUrlProtector.Sanitize with / as the fallback before putting it in returnUrl (: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 through MultiFactorRequiredSignal.Subscribe(TokenStorage, OnRequired); Dispose (:33-37) disposes and clears the subscription.
    • OnRequired (:62) discards RedirectAsync, which dispatches Redirect through InvokeAsync and swallows ObjectDisposedException and InvalidOperationException, 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 trimmed AccountPath or login. 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. IsExempt is internal rather than private so 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 by MultiFactorRequiredListenerTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/MultiFactorRequiredListenerTests.cs, including ARaise_OnASiblingRouteSharingThePrefix_Redirects at :80 and IsExempt_ComparesWholeSegments at :100), TwoFactorOptInRenderTests and TwoFactorUIModuleTests.

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, implements IDisposable)

  • 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: NavigationManager and LocationChangedEventArgs (Microsoft.AspNetCore.Components), MudBlazor's ISnackbar and Snackbar, the BCL TimeProvider and Lock, 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 than Grace before the navigation is removed. Grace is a public static TimeSpan of 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, or ShowAction with requireInteraction) is never removed, because it is promised to stay until the user dismisses it (lines 21-22). Every timestamp comes from the injected TimeProvider, so a test advances a fake clock instead of waiting.
  • Walkthrough:
    • State (lines 29-31): a Dictionary<Snackbar, DateTimeOffset> _firstSeen that records when each toast was first observed, guarded by a Lock _sync, and _currentPath, the absolute path of the page currently shown.
    • OnInitialized (lines 49-55) records the starting path from Navigation.ToAbsoluteUri(Navigation.Uri).AbsolutePath (line 51), subscribes to Navigation.LocationChanged and Snackbar.OnSnackbarsUpdated, then calls OnSnackbarsUpdated() 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 with TryAdd(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), computes cutoff = 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 calls Snackbar.Remove on 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 injected IToastService is a MudToastService and 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.
  • 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 (MudToastService or a direct ISnackbar call). It is a layout component rather than a behavior of the toast service, and AddCommonUiFacades documents it as the one framework type outside the Mud-backed facades that names MudBlazor's ISnackbar directly, asking MudToastService which 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 by StaleToastSweeperTests.
  • 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 IToastService in place of MudToastService loses 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 for LocalizedErrorMessage (ChangePasswordCard.razor.cs:165), ComponentLifetimeExtensions for LifetimeToken() (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: MudForm and MudTextField from 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 meets MinLength (ChangePasswordCard.razor.cs:113-116), satisfies the shared PasswordComplexity rule 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 fixed ChangePassword.Failed text only when the failure carries none (comment ChangePasswordCard.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: MinLength defaults to 8, the framework's password policy minimum, and also feeds the helper text (ChangePasswordCard.razor.cs:51; ChangePasswordCard.razor:18). MaxLength is an int? that defaults to PasswordComplexity.MaximumLength, the bound the server's password rules enforce; null leaves the field unbounded (ChangePasswordCard.razor.cs:53-59); the razor falls back to the private NoMaxLength constant 524288, 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: OnChanged fires after success, once the toast has been shown (ChangePasswordCard.razor.cs:70); OnFailed carries the failed Result after 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 null for valid or empty input and leave the Required check to report a missing value (comment ChangePasswordCard.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 through L.Plural (:115), then PasswordComplexity.Evaluate: a failing value gets AuthFieldMessages.PasswordComplexity (:122), a passing one gets any held server message (:121). The mismatch uses Validation.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 the try, validates the form and stops on invalid (:143-147) before calling AuthService.ChangePasswordAsync(current, new, _cts.LifetimeToken()) (:149). On success it resets the form, clears the three fields, toasts ChangePassword.Success and raises OnChanged (:151-158). On failure it toasts (:165), calls ShowFieldRefusalsAsync (:166) and raises OnFailed(result) (:167). A cancelled call is swallowed (:170-173), and _isSaving always clears in finally (:176).
    • ShowFieldRefusalsAsync (ChangePasswordCard.razor.cs:183) builds a FieldRefusal for the current-password field (matching the wrong-password code Auth.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 the CancellationTokenSource (ChangePasswordCard.razor.cs:88-98). The MudForm reference is not disposed here because the renderer owns it (comment ChangePasswordCard.razor.cs:36).
  • 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 OperationCanceledException is expected (comment ChangePasswordCard.razor.cs:172). Taking MinLength and MaxLength as 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 by ChangePasswordCardTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/ChangePasswordCardTests.cs) and ChangePasswordCardErrorSummaryTests, and FormsConventionTestsBase (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Ui/FormsConventionTestsBase.cs:33) references it by its <ChangePasswordCard tag.

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 for LocalizedErrorMessage (:145), SharedResource (:44) and ComponentLifetimeExtensions for LifetimeToken() (: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 checks IsAutofillAvailableAsync before 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: OnSignedIn is raised once the passkey signed the user in and the tokens are stored (:33-34); EnableAutofill defaults 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). An OperationCanceledException is 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); a null credential shows the localized Auth.Login.PasskeyCancelled text (:113-117), otherwise it completes the flow (:119). _isBusy clears in finally (:125-128).
    • CompleteAsync (:131-142) posts a PasskeySignInRequest(flowId, assertion) (:133); a failure sets the message and re-renders (:134-139), a success raises OnSignedIn (:141).
    • FailureMessage (:144-145) prefers the result's localized message and falls back to Auth.Login.PasskeyFailed.
    • DisposeAsync (:47-59) is idempotent, cancels and disposes the token source and cancels any running autofill (:57).
  • 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, code Passkeys.StepUpRequired restated as StepUpRequiredCode because UI references Shared only (:23-24), shows the localized Passkeys.SignInAgain text 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) calls LoadAsync (:80-102), which lists the passkeys (:84), toasts a failure (:91) and clears _isLoading in finally (: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 short d pattern (:245) or shows Passkeys.NeverUsed.
    • AddAsync (:104-145) begins registration (:114), asks the platform to create a credential (:121), toasts Passkeys.AddCancelled as info when the user backs out (:122-126), completes the registration with the trimmed name or null (:128-130), and clears the name field on success (:132-135).
    • Rename: StartRename and CancelRename hold 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 through Dialogs.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 raises OnChanged (:232-233).
    • Every mutating method guards on _isBusy and swallows OperationCanceledException only 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 by PasskeysPanelTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/PasskeysPanelTests.cs) and ADC's ProfilePasskeysTests.

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>), BCL TimeProvider, 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), and State.UnregisterPoller(this) releases it only when this instance actually holds it and then raises OnPollerSlotFreed (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 through OnPollerSlotFreed (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 subscription State.OnRefreshRequested += HandleRefreshRequested is made inside BecomeActivePollerAsync (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: OnLocationChanged reads only when State.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 negative PollInterval switches the periodic backstop off entirely (lines 120-123) while push and navigation refresh keep working; the comment (lines 118-119) records that PeriodicTimer rejects 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: an Unauthorized read (line 247) stops the unattended backstop via StopPollTimer (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 through StartPollTimerIfStopped (line 271).
    • [Rubric §14, Testability] assesses whether time-dependent behavior can be driven deterministically. Both the timer and the age comparison run off the injected TimeProvider Clock (line 41), and the PeriodicTimer is constructed with the TimeProvider overload (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 localized aria-label="@L["Notif.Bell.Aria"]" in the markup (NotificationBell.razor:10), which is what the injected IStringLocalizer<SharedResource> L (line 39) is for.
    • Fire-and-forget from a synchronous event handler. HandlePollerSlotFreed (lines 143-144), OnLocationChanged (lines 198-204), and HandleRefreshRequested (lines 216-220) are all EventHandler-shaped, so they cannot be async Task. Rather than async 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.
  • Walkthrough
    • Injected members (lines 36-41): State, InboxService, NavigationManager, L, IOptions<NotificationBellOptions> Options, and TimeProvider Clock. Fields (lines 43-46, 50): a per-component CancellationTokenSource _cts, the PeriodicTimer? _pollTimer, the two flags _isActivePoller and _disposed, and the int _readSequence counter 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, OnChange and OnPollerSlotFreed (lines 59-60), then tries for the slot and, on success, calls BecomeActivePollerAsync() (lines 63-66).
    • BecomeActivePollerAsync (lines 75-99) is the double-start-guarded start: it bails on _disposed || _isActivePoller (lines 77-80), latches _isActivePoller, hooks LocationChanged (line 83) and OnRefreshRequested (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) gates StartPollTimerIfStopped() (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 _isActivePoller guard 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 _pollTimer is already set (line 113). The comment (lines 110-112) explains the _disposed half: Dispose may have run during a read, having already disposed the then-null timer and the token source, so starting the loop now would leak a PeriodicTimer nothing disposes and fault the discarded task on a disposed _cts. It returns without a timer when PollInterval <= TimeSpan.Zero (lines 120-123). Otherwise it creates the timer from Options.Value.PollInterval and the injected clock (line 127) and launches PollLoopAsync(_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 pending WaitForNextTickAsync answer 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 with InvokeAsync(BecomeActivePollerAsync) (line 159), because the event was raised synchronously from the disposing bell's thread (doc, lines 146-149). If that dispatch hits ObjectDisposedException it 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, awaits pollTimer.WaitForNextTickAsync(_cts.LifetimeToken()) in a loop (line 172) and refreshes each tick. Holding its own reference means a StopPollTimer that 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 catches OperationCanceledException (the expected disposal exit) and ObjectDisposedException (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 returns Task<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 with Interlocked.Increment(ref _readSequence) (line 230), and calls InboxService.GetUnreadCountAsync(_cts.LifetimeToken()) (line 233). After the await it drops a superseded read: if sequence != 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 is count.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 with InvokeAsync(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 _disposed and marshals back onto the renderer with InvokeAsync (lines 261-274); inside that callback it re-checks the sequence (line 265), then calls State.SetUnreadCount(unread), StartPollTimerIfStopped() (line 271) and StateHasChanged(). Three catch tiers follow (lines 278-292): cancellation, disposal during the async gap, and a bare catch for 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 into RerenderSafeAsync (lines 299-314), which re-renders through InvokeAsync(StateHasChanged) and tolerates a dispose landing between the event firing and the render dispatch.
    • NavigateToInbox (line 316) sends the click to NotificationRoutePaths.NotificationInbox.
    • Dispose(bool disposing) (lines 318-339) sets _disposed first (line 325), unsubscribes all three state events and LocationChanged (lines 326-329; removing a handler that a non-poller never added is a no-op), then calls State.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 with GC.SuppressFinalize.
  • 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. ResendAsync returns while a send is in flight or after one succeeded (:58), so repeated clicks cannot queue a burst of emails.
  • Walkthrough
    • Parameters: Email is [EditorRequired] (:31-33); OnSent runs after the request was accepted (:36-37).
    • ResendAsync (:56-92) clears the error, trims the address (:64) and shows the localized Auth.Confirm.EmailRequired text for an empty one (:65-69). It then sets _isSending (:71) and calls ResendEmailConfirmationAsync (:74); success sets _sent and raises OnSent (:75-80), a failure shows the localized message or Auth.Confirm.GenericError (:82). A cancellation is swallowed only when disposed (:84), and _isSending clears in finally (:88-91).
    • Dispose (:44-54) is idempotent and cancels and disposes the token source.
  • 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 by EmailConfirmationResendPromptTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Components/Auth/EmailConfirmationResendPromptTests.cs), LoginResendPromptTests and RegisterPendingTests.

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's Resumed event with AppResumedEventArgs, Preferences (IDevicePreferences) read with DevicePreferenceKeys.AppLockEnabled, TokenStorage, SignOutNavigator (SignOutNavigator, used only to sign out), Biometrics, Logger, JS, the page's localizer L; injected in BiometricGate.razor:6-14); AppLockInertBackground for the inert page behind the overlay (BiometricGate.razor.cs:32, :48); MudBlazor's MudButton for 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 to AppLifecycle.Resumed on 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 plain EventHandler<AppResumedEventArgs>, so it cannot be async; it fires ReLockAsync with an explicit discard, and the comment (lines 119-124) states why that discard is safe here: ReLockAsync observes 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. ShouldLockAsync documents both halves (lines 166-171): if the AppLockEnabled preference 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 through EngageLock (lines 206-215), which sets _locked and 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] TimeSpan defaulting 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: _lockRoot is the overlay wrapper the inert boundary is measured from (line 31), _inertBackground the lazily created helper behind the InertBackground property (lines 32, 48), and _focusUnlockPending and _inertPending the two flags acted on after render (lines 40, 46).
    • OnAfterRenderAsync(firstRender) (lines 51-89): first focuses the Unlock button if _focusUnlockPending and 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 _inertPending and 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). On firstRender it subscribes to AppLifecycle.Resumed (lines 78-79), then calls ShouldLockAsync and, if it returns true, calls EngageLock and awaits UnlockAsync (lines 81-88).
    • ReLockAsync (lines 127-164) returns early if already locked or if the background duration was under ReLockAfter (line 131), otherwise dispatches the check, EngageLock and unlock sequence through InvokeAsync (lines 136-146). It catches ObjectDisposedException and InvalidOperationException as expected teardown races (lines 148-155), and a general Exception last under a scoped CA1031 suppression, logged rather than rethrown (lines 156-163).
    • ShouldLockAsync (lines 172-204) wraps the preference read in its own try (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 second try (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 scoped CA1031 suppression naming their disposition.
    • UnlockAsync (lines 217-238) calls Biometrics.AuthenticateAsync with a localized prompt reason; success clears _locked and both pending flags and lifts the inert background through ReleaseBackgroundAsync (lines 219-224); failure re-queues _focusUnlockPending for the next render (line 234). Both paths call StateHasChanged under a BL0012 suppression, because UnlockAsync also runs from OnAfterRenderAsync and ReLockAsync, where nothing re-renders automatically (lines 225-227, 235-237).
    • FocusUnlockAsync (lines 244-258) tolerates JSDisconnectedException (circuit gone) and InvalidOperationException (prerendering, or the element already removed).
    • SignOutAsync (lines 268-275) calls SignOutNavigator.SignOutAsync("/login") (line 270; SignOutNavigator.cs:47), then clears _locked and 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 through RedirectToLogin's returnUrl, 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 from AppLifecycle.Resumed if subscribed, guarded so it is safe to call more than once, then fires and forgets the helper's DisposeAsync so a gate torn down while locked does not leave the page behind it inert (lines 103-109); the public Dispose() (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 ReLockAsync but narrowly inside FocusUnlockAsync reflects 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 inside ShouldLockAsync resolve in opposite directions on purpose: before opt-in the safe default is "no lock", after opt-in it is "lock". Routing every lock through EngageLock keeps 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) and App.xaml.cs (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/App.xaml.cs); referenced by TermsAcceptanceGate (TermsAcceptanceGate.razor.cs); pinned by BiometricGateTests (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 Result really 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.Json and System.Net.Http (BCL) plus Polly (HttpResultExecutor.cs:3) for the fault set it recognizes. It is static and 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 a Result instead of writing a catch, 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) and TimeoutErrorCode = "Http.Timeout" (line 41). They are public because they are the branch a page uses when it needs different wording; the two English messages are internal constants (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 twin ExecuteAsync<T>(Func<Task<Result<T>>>, CancellationToken) (line 91) are the whole public surface. Both are structurally identical, and both start with ArgumentNullException.ThrowIfNull (lines 58,
      1. 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.
    • The try simply 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: HttpClient gave up on its own timeout, which raises the same exception type with the token not cancelled. That one becomes a failure carrying TimeoutError() (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, JsonException and Polly's ExecutionRejectedException (line 128), the base of TimeoutRejectedException and BrokenCircuitException, so a client resilience pipeline that refuses to run or finish the call also becomes a failure (HttpResultExecutor.cs:3 imports Polly). 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's Source rather than its Message (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.
  • 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.LocalizedErrorMessage translates these two by their code, first through the localizer the page passes and then, when that has no such key, through the framework's own SharedResource pair 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 SendRequestAsync overloads, MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:179,209), ChildEntityServiceBase (directly in DeleteByIdAsync, MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/ChildEntityServiceBase.cs:75, and through the same inherited SendRequestAsync overloads for both PostAsync overloads, :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 JsonException is 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's Source but 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 through LocalizedErrorMessage, 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 displays Error.Message directly 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 /paged endpoint 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 through MMCA.Common.Shared.Abstractions, line 3). Externals: BCL CultureInfo, 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 ignores pageSize and always returns that maximum, so rows past it vanish with nothing to say so. Paging until PaginationMetadata.TotalItemCount is 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 public const int of 500, the API's default maximum, so no request is clamped (summary, line 20). TruncatedCode (line 27) is a public const string of "PagedReadAll.Truncated", the Error.Code of the failure the runaway guard produces (summary, lines 23-26). MaxPages (line 33) is a private const of 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=false with string.Create(CultureInfo.InvariantCulture, ...) (lines 49-51). Sorting by Id ascending 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. The CA1055 suppression (lines 44-47) keeps the return a string for that reason, since callers both compose it as text and wrap it as a relative Uri.
    • ReadAllAsync<T>(Func<int, Task<Result<PagedCollectionResult<T>>>> fetchPage, CancellationToken) (line 66) null-guards the delegate (line 70) and loops pageNumber from 1 to MaxPages (line 74). Each iteration checks cancellation first (line 76), fetches the page (line 78), and returns the first failure unchanged as Result.Failure<List<T>>(result.Errors) (lines 79-82). An empty page returns Result.Success(accumulated) (lines 85-88); otherwise the items are accumulated (line 90) and the method returns success once the count reaches TotalItemCount (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 authenticated SendRequestAsync, or an anonymous IdempotentReadRetry GET) and its own filters, while the paging rule lives once. Returning a Result rather than throwing keeps it inside the framework's client contract that a page branches on failures instead of catching them, and the public TruncatedCode lets a caller (or a test) tell the guard apart from a server error.
  • Where it's used: inside the framework, EntityServiceBase<TEntityDTO, TIdentifierType>.GetAllAsync falls 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 reuses PagedReadAll.PageSize (EntityServiceBase.cs:265). ADC UI services SpeakerLookupService (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 Engagement SessionLookupService (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/Lookups/SessionLookupService.cs:26) and QuestionLookupService (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/Lookups/QuestionLookupService.cs:31). The ADC Conference service's SelfHttpOutputCacheWarmupTask replays URLs in the LookupPageUrl shape (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/SelfHttpOutputCacheWarmupTask.cs:42). Pinned by PagedReadAllTests (MMCA.Common/Tests/Presentation/MMCA.Common.UI.Tests/Services/Api/PagedReadAllTests.cs). OrganizerFeedbackService composes its own filtered /paged URLs with PagedReadAll.PageSize rather than LookupPageUrl (OrganizerFeedbackService.cs:31,73), since it needs an EventId or SessionId filter.

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 from MMCA.Common.Shared.Abstractions (line 1), for the fetch's return shape and its IsSuccess test (line 110). Externals: BCL TimeProvider (line 35), Task and DateTimeOffset.
  • 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 successful Result<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 injected TimeProvider (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 at DateTimeOffset.MinValue until a fetch actually succeeds, which is what makes a non-answer expire immediately (lines 40-44); and _generation, bumped by Invalidate (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 in WaitAsync (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 _cachedUntil as 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 by Invalidate completes 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 ADC EventLookupService and SpeakerLookupService copies. 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 example Admin/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 FetchPage delegate once a page binds the first three arguments.
  • Where it's used: implemented by AuditHistoryService and registered by AddAuditHistoryUI with TryAddScoped (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:402-404); resolved by ADC's EventDetail (route prefix Admin/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) and LegalAcceptanceDTO (MMCA.Common.Shared.Legal, ILegalAcceptanceUIService.cs:2); both calls target LegalAcceptanceRoutes.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 a Result carrying 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 via GET Users/me/legal-acceptance (:21). AcceptAsync(version, cancellationToken) records an acceptance via POST Users/me/legal-acceptance and 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 HttpClient with 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 and Auth.Tokens.ITokenRefresher, that is ITokenRefresher, as the source of the replay token. From MMCA.Common.Shared.Resilience (AuthenticatedServiceBase.cs:5) it reads RetryAfterHeader and the MaxRetryAfterWait ceiling 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). From MMCA.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, Polly and Polly.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 the CreateAuthenticatedClientAsync doc comment (AuthenticatedServiceBase.cs:67-72): IHttpClientFactory creates its handlers in a separate DI scope from the Blazor circuit, so a DelegatingHandler cannot reach the circuit's IJSRuntime to 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
    • RetryPolicy is a protected 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. ApiClientName pins 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 an internal static getter that returns that same RetryPolicy instance. 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 compact Guid.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), sets Authorization: Bearer when non-blank (AuthenticatedServiceBase.cs:80-83), and catches InvalidOperationException to proceed without a token during SSR prerender, when JS interop is unavailable (AuthenticatedServiceBase.cs:91-94). When it attaches a bearer it also calls AuthDelegatingHandler.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 a protected flag 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 returns null when 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 answers 401, 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 excludes 501 Not Implemented and 505 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 response CommitOutcomeUnknown.Is recognizes (AuthenticatedServiceBase.cs:285-288): a response carrying the X-Commit-Outcome: unknown header (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/CommitOutcomeUnknown.cs:34-37, checked at CommitOutcomeUnknown.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 which RetryAfterHeader.ExceedsRetryBudget is true (AuthenticatedServiceBase.cs:290-293; MMCA.Common/Source/Core/MMCA.Common.Shared/Resilience/RetryAfterHeader.cs:75): a 429 whose Retry-After asks for longer than HttpResilienceDefaults.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 asks IsReplaySafe whether the request may be sent again and gives up if not (AuthenticatedServiceBase.cs:295-298). Only then does it accept anything >= 500 plus 408 Request Timeout and 429 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-blank Idempotency-Key header, 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 is internal static so a test can pin it directly, and the doc comment on RetryPolicy (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) stores IsReplaySafe(request) in exception.Data under the internal const ReplaySafeDataKey (:336); AuthDelegatingHandler, the outermost handler AddUIShared adds to the API client, calls it (doc comment :338-344, which notes that on a host calling AddServiceDefaults the service-discovery handler wraps it, and so does the standard resilience handler unless the host removes it, as AddMmcaBlazorWebHost does). IsRetryableException (:358) then retries a transport failure unless it was marked not replay-safe (a POST or PATCH without an Idempotency-Key) AND failed after the request may have been sent: only NameResolutionError, ConnectionError and SecureConnectionError (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 is internal so a test can pin the schedule (doc :366-371). The RetryPolicy doc 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 a Retry-After is outside the 4.25-second bound because each such retry can wait up to the cap. The CA5394 suppression 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 a 429 Too Many Requests whose Retry-After parses through RetryAfterHeader.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 over MaxRetryAfterWait, so the delay used here is bounded. The TimeProvider is the clock a date-form Retry-After is measured against.
    • BuildRetryPolicy(Func<int, TimeSpan> backoff, TimeProvider? timeProvider = null) (AuthenticatedServiceBase.cs:414-430) is internal and backoff- and clock-injectable so a test can exercise the disposal and Retry-After contracts without waiting out the real delays; a null clock falls back to TimeProvider.System (AuthenticatedServiceBase.cs:418). It retries 3 times (AuthenticatedServiceBase.cs:422-423), with sleepDurationProvider routed through RetryDelay (AuthenticatedServiceBase.cs:424). Its onRetryAsync disposes 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 handles HttpRequestException through IsRetryableException, :420, and responses through IsRetryableResponse, :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 retried HttpRequestException carries 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 as NewIdempotencyKey() on creates and updates (EntityServiceBase.cs:180 and EntityServiceBase.cs:204), RetryPolicy.ExecuteAsync around each call inside this class's own SendRequestAsync overloads (AuthenticatedServiceBase.cs:185 and AuthenticatedServiceBase.cs:213), which every EntityServiceBase request goes through (EntityServiceBase.cs:177, EntityServiceBase.cs:201, EntityServiceBase.cs:226 and EntityServiceBase.cs:252), and CreateClientWithToken on 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 internal SharedRetryPolicy (line 24, MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:52). Externals: Polly.Retry (AsyncRetryPolicy<HttpResponseMessage>, line 1) and BCL HttpClient.
  • 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 an HttpRequestException, 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 an Idempotency-Key the server deduplicates on.
  • Walkthrough
    • Policy (line 24) is an internal static getter returning AuthenticatedServiceBase.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 returns Policy.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, and HttpRequestException escapes 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 general ExecuteAsync is 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) and NowNextService (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 by IdempotentReadRetryTests (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 shared RetryPolicy.
  • Walkthrough: GetPageAsync (line 27) rejects a null or blank route prefix, alias or key (lines 35-37), builds the relative URL with string.Create under the invariant culture, trimming a trailing slash from the prefix and escaping the alias and key with Uri.EscapeDataString (lines 39-41), then inside HttpResultExecutor.ExecuteAsync creates the authenticated client (line 46), sends the GET through RetryPolicy (lines 47-49) and reads the body as IReadOnlyList<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) and DeleteByIdAsync over 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 inherited SendRequestAsync overloads, which all three methods now call, lines 45, 61 and 83), Result and ErrorType (line 1; ErrorType.NotFound is named in the delete's summary, line 68); IHttpClientFactory and System.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 raw HttpClient calls in components. The interesting design choice here is what is absent: a join row like SessionSpeaker has 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, ITokenStorageService and a string endpoint, forwarding the first two to AuthenticatedServiceBase (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 surfaces protected 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 inherited AuthenticatedServiceBase.SendRequestAsync<TResponse> (lines 45-46) together with a freshly minted idempotencyKey: NewIdempotencyKey() (line 48), so the call takes the same dispatch as an entity create: the executor outside, RetryPolicy in the middle, ProblemDetailsResultReader innermost (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). The request parameter is typed object on purpose, and the doc comment explains why (lines 29-33). The three protected methods return a task directly (protected Task<...>, not async) (lines 44, 60, 80). Join payloads are anonymous objects, System.Text.Json serializes the runtime type for an object declaration, 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-less SendRequestAsync overload (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 inherited SendRequestAsync overload (lines 83-85) with no idempotencyKey, so the removal takes the same dispatch as EntityServiceBase.DeleteAsync: the executor outside, RetryPolicy in 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 no Idempotency-Key. A join row that is not there answers 404, which arrives as an ErrorType.NotFound failure rather than a bare false, 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.
  • 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 each PostAsync mints one Idempotency-Key per call and holds it across every attempt of RetryPolicy (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 on sessioncategoryitems and SpeakerCategoryItemService on speakercategoryitems (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Common/ChildEntityServices.cs:22,35,48). Each adds a typed AddAsync/DeleteAsync pair 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). Neither PostAsync overload exposes the response headers, so an endpoint answering 201 Created with a Location header 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 TEntityDTO constraint, 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, and AuthenticatedServiceBase.cs:253 in 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 inherited RetryPolicy, and System.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 two SendRequestAsync overloads inherited from AuthenticatedServiceBase (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:171,201), reached directly or through SendGetAsync<T> (line 248), contain all of the policy. [Rubric §19, State Management & Data Flow] applies because components never touch HttpClient: they inject the typed interface and receive DTOs wrapped in a Result. [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. AddAsync and UpdateAsync both pass a key (lines 180 and 204), minted by AuthenticatedServiceBase.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 at AuthenticatedServiceBase.cs:238-241 says 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 and DeleteAsync (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. UpdateAsync sends the DTO's concurrency token as an If-Match entity 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 answers 428 Precondition Required rather than accepting a blind write. ConcurrencyTagOf (line
    1. is the whole rule: a DTO that implements IConcurrencyAware with a non-empty RowVersion is formatted by ConcurrencyETag.Format, anything else yields null (lines 216-218). This is ADR-035 (Website/docs-src/adr/035-optimistic-concurrency.md) seen from the client.
  • 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 first ApplicationSettings.MaxPageSize rows (500 by default) and reports the full count in the paging metadata (remarks, lines 52-58). GetAllAsync checks 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, IHttpClientFactory and ITokenStorageService (lines 35-38); note the parameter order differs from ChildEntityServiceBase. Both type parameters are constrained, TEntityDTO : IBaseDTO<TIdentifierType> and TIdentifierType : notnull (lines 39-40). Endpoint is republished as a protected property (line 42) because the read methods append sub-paths to it.
    • PagedIncludeFKs (line 49) is a protected virtual bool that defaults to false, so the paged URL is unchanged by default; a service whose list grid shows a foreign-key name (a product's category) overrides it to true, and GetPagedAsync then appends includeFKs=True (lines 110-113). Only the paged read has this hook: GetAllAsync takes includeFKs as 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 holds TotalItemCount rows it returns them (lines 77-81), so a set within one page costs one request. Otherwise it calls PagedReadAll.ReadAllAsync over the private AllPagesUrl (lines 83-86) and maps the list (line 88). AllPagesUrl (line 262) targets {Endpoint}/paged with PagedReadAll.PageSize, sortColumn=Id&sortDirection=asc and the caller's include flags (lines 263-265).
    • GetPagedAsync(filters, pageNumber, pageSize, sortColumn, sortDirection, includeChildren, ct) (line 92) formats page numbers with string.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 through Uri.EscapeDataString (lines 105-106, 121, 123). Filters serialize as filters[Property].operator= plus an optional filters[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 a CollectionResult<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) returns SendGetAsync's task directly (line 164). A missing entity is a NotFound failure, 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 the If-Match tag (lines 201-206). DeleteAsync(id, ct) (line 221) DELETEs {Endpoint}/{id} (lines 225-229).
    • GetEntityId(entity) (lines 232-233) is protected virtual and returns entity.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 through SendRequestAsync<T> (lines 252-254). The CA1054 suppression (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 deserialized Items collection without assuming the JSON reader produced a list (lines 272-277).
    • The dispatch itself is inherited, not declared here: SendRequestAsync<T> (AuthenticatedServiceBase.cs:171) and SendRequestAsync (AuthenticatedServiceBase.cs:201) are structurally identical and both return the executor's task directly rather than awaiting it (protected Task<...>, no async): 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 through RetryPolicy with 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's EmptyResponseCode, which is why the body-less overload exists at all (documented at AuthenticatedServiceBase.cs:166-170). The client is kept in scope across the read on purpose (comment at AuthenticatedServiceBase.cs:182-183).
    • CreateRequestClientAsync(idempotencyKey, ifMatch) (AuthenticatedServiceBase.cs:232), also inherited, starts from CreateAuthenticatedClientAsync (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 beside If-Match lets the server replay the stored outcome instead of re-checking the precondition against the version that attempt just wrote.
  • 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 are virtual, 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 a GetPagedAsync call 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 a PagedReadAll.Truncated failure 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). GetPagedAsync accepts a filters dictionary 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 and RetryPolicy, ITokenStorageService (constructor, :24-25), HttpResultExecutor and ProblemDetailsResultReader for the error contract, plus LegalAcceptanceRoutes.Path, LegalAcceptanceDTO and AcceptLegalTermsRequest from 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 not async itself: it returns the HttpResultExecutor.ExecuteAsync task directly (:30), creates the authenticated client (:33), sends the GET through RetryPolicy.ExecuteAsync (:34) and reads the response with ProblemDetailsResultReader.ReadAsync<LegalAcceptanceDTO> (:38).
    • AcceptAsync (:44, likewise a plain Task-returning method) rejects a blank version synchronously (:46), then returns the executor task the same way (:48) but posts an AcceptLegalTermsRequest(version) straight through the client (:52-55) without RetryPolicy, 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 sealed and 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 by LegalAcceptanceUIServiceTests (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 Money value object into $12.50 USD and 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: Money and its Currency (both MMCA.Common.Shared.ValueObjects), plus CultureInfo.CurrentCulture and StringComparer.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: Money knows 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 on Money and one on IReadOnlyCollection<Money>, sit in a single static class so both spellings (price.ToDisplayString() and prices.ToDisplayRange()) are available from one using.
  • Walkthrough:
    • The class carries a file-level [SuppressMessage("Naming", "CA1708")] (lines 10-13): with two or more extension(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) exposes ToDisplayString(CultureInfo? culture = null) (lines 29-30), which delegates to FormatGroup(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, culture resolves inside FormatGroup to CultureInfo.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) exposes ToDisplayRange(CultureInfo? culture = null) (lines 47-63): returns string.Empty for an empty collection (lines 49-52), resolves culture ?? CultureInfo.CurrentCulture once into resolved (line 54, ahead of the grouping), then groups by Currency.Code with StringComparer.Ordinal and formats each group from its own min and max under resolved (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 notes GroupBy preserves first-appearance order, so the single-currency case (every collection in practice today) is unchanged. Resolving the culture once outside the Select and passing it into every FormatGroup call 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 the Currency.None sentinel behind Money.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: resolves culture ?? CultureInfo.CurrentCulture (line 90), then renders a single price when min == max and a hyphen-separated range otherwise, each bound through FormatAmount (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.56 and a Spanish reader gets $1.234,56. A negative amount puts the sign before the symbol (-$5.00, not $-5.00) by formatting Math.Abs(amount) behind a leading -, which keeps the culture's digit grouping intact (lines 99-102).
  • Why it's built this way: presentational formatting belongs above the domain, so Money stays display-agnostic and the same value can be rendered differently by a different head. The move from a hardcoded CultureInfo.InvariantCulture to a caller-optional, request-defaulted CultureInfo.CurrentCulture lets 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 a culture argument, so all of them format under the ambient CultureInfo.CurrentCulture. Covered by MoneyExtensionsTests.
  • Caveats / not-in-source: only USD and EUR have symbols; adding a currency means editing Symbol, 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 SkipBearer request-option key (imported at line 1, set at line 34; the key is declared at MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthDelegatingHandler.cs:45). Externals: BCL HttpRequestMessage, HttpMethod and JsonContent (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 with JsonContent.Create(body) and delegates to Post (line 22).
    • Post(string relativeUrl, HttpContent? content) (line 28) creates a POST HttpRequestMessage against a relative Uri (line 30) with the given content, null meaning an empty POST (line 32), sets request.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 class internal (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 (GetAsync and AcceptAsync), 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 at TermsAcceptanceGate.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), BCL CancellationTokenSource, 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 _checkedUserKey it belongs to, and the _visible flag.
    • Not dismissible, on purpose. DialogOptions (lines 37-45) turns off BackdropClick, CloseOnEscapeKey, CloseOnNavigation and CloseButton. The summary (lines 31-36) records the real failure behind CloseOnNavigation = false: the dialog provider dismisses every open dialog on LocationChanged, 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 _checkedUserKey means 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 CurrentVersion is non-null and IsCurrent is 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 the BiometricGate precedent 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).
  • Walkthrough
    • Injected members (lines 57-73): AuthStateProvider, LegalAcceptance, SignOutNavigator, LegalOptions, L, and Logger. Heading (lines 78-80) picks the "first" title when AcceptedVersion is null and the "updated" title when the user accepted an earlier version.
    • OnAfterRenderAsync(bool firstRender) (lines 90-102) returns on later renders, subscribes to AuthenticationStateChanged (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 with LegalAcceptanceErrorCodes.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 localized Legal.Gate.AcceptFailed (lines 218-220, comment lines 215-217). Cancellation is swallowed (lines 222-225) and _busy is cleared in finally (lines 226-229).
    • SignOutAsync (lines 234-238) sets _busy and returns SignOutNavigator.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 by RedirectToLogin's own navigation; the navigator makes RedirectToLogin stand down while its sign-out is in flight (MMCA.Common.UI/Services/Navigation/SignOutNavigator.cs:7-30).
    • OnAuthenticationStateChanged (line 250) discards into ReevaluateAsync (lines 252-275), which awaits the new state, marshals EvaluateAsync through InvokeAsync, and catches ObjectDisposedException, InvalidOperationException, and finally a bare Exception that 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 _disposalCts once, and disposes it; the token source is passed to both service calls (lines 158, 198), so teardown mid-request ends through the cancellation path.
  • 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 /login rather 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 IServiceCollection methods a host calls from Program.cs instead 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 (its IValidateOptions<BlazorCspSettings>), TrustedCallerHandler (the delegating handler AddTrustedCallerHeader composes), 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; every MMCA.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 before AddCommonSecurityHeaders, because the default is registered with TryAdd and 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 bad BlazorCsp:FrameSources entry 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; AddTrustedCallerHeader is that opt-in exemption for this host's own server-to-server calls.
  • Walkthrough
    • AddCommonServerTokenStorage() (lines 40-50): calls services.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 with AddHttpClient("APIClient").AddHttpMessageHandler<BrowserOriginHandler>() (lines 46-47). The doc (lines 30-38) says each server-side request then carries X-Forwarded-For set to the remote IP and User-Agent set 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 second AddHttpClient with the same name appends to the client registered by AddUIShared, 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, AddServerAuthSessionCookie and UseCookieSessionRefresh from MMCA.Common.API, plus a registered ITokenRefresher.
    • AddCommonBlazorCsp() (lines 66-77) does three things. It binds BlazorCspSettings from the "BlazorCsp" configuration section and calls ValidateOnStart() (lines 68-70); it registers BlazorCspSettingsValidator as an IValidateOptions<BlazorCspSettings> through TryAddEnumerable, 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 (not TryAdd) is what makes the replacement deterministic. The doc (lines 59-63) states the configuration contract: BlazorCsp:FrameSources lists the https origins the host's pages may frame, emitted as frame-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, when TrustedCallerSecret is blank (the local/CI default), or TrustedCallerHeaderName is blank, or the server-side ApiSettings.ApiEndpoint is 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 same GatewayRateLimiting section 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 every HttpClient this host builds via services.ConfigureAll<HttpClientFactoryOptions>(...) (lines 143-147) rather than one named client. When it does register, it inserts TrustedCallerHandler at AdditionalHandlers.Insert(0, ...) (lines 145-147), not Add: 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 calls AddServiceDefaults before 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.Web and exposed as one-line registrations. Binding and validating BlazorCspSettings inside AddCommonBlazorCsp() itself, rather than leaving it to the host, means a host that opts into frame-src gets the fail-fast contract for free instead of having to know to add its own ValidateOnStart(). AddTrustedCallerHeader follows 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's Program.cs free 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 posture ValidateOnStart() follows.
  • Where it's used: called from the Program.cs of 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 a BlazorCsp:FrameSources list, if any, is not visible from this file.

⬅ Module System, Composition & Configuration • Index • Aspire Orchestration & Service Defaults ➡