Files

12 KiB

Application Design - identity-email-notifications

1. Components

flowchart TB
    subgraph Core["SlpModularCms.Core"]
        ES["IEmailSender<br/>SmtpEmailSender (MailKit)"]
        EO["EmailOptions<br/>(section Email) + validator"]
        MR["IMailTemplateRenderer<br/>nl/en resources, shared HTML"]
        LR["ILanguageResolver<br/>user, site default"]
        SS["ISiteSettingsService<br/>SiteSettings table"]
        IM["IIdentityMailService<br/>orchestrates one mail"]
        CD["ResetCooldown<br/>(in-memory)"]
    end
    subgraph Identity["Modules.Identity"]
        UC["UsersController<br/>invite, regenerate, resend,<br/>active, role, me"]
        AC["AuthController<br/>forgot-password, reset-password"]
        SC["SiteSettingsController<br/>mail card API"]
    end
    subgraph FE["frontend"]
        SP["Settings: Mail card"]
        PR["Profile: language"]
        IV["Invite dialog + users list"]
        PW["Forgot / reset pages"]
    end
    UC --> IM
    AC --> IM
    AC --> CD
    IM --> ES
    IM --> MR
    IM --> LR
    IM --> SS
    ES --> EO
    SC --> SS
    SP --> SC
    PR --> UC
    IV --> UC
    PW --> AC
    classDef core fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
    classDef mod fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
    classDef fe fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
    class ES,EO,MR,LR,SS,IM,CD core;
    class UC,AC,SC mod;
    class SP,PR,IV,PW fe;

Text alternative: controllers call one orchestrator (IIdentityMailService) in Core, which uses the sender, the template renderer, the language resolver and the site settings; the frontend talks only to the controllers.

Core

  • IEmailSender (same shape as SimpleDeckApp): Task SendAsync(string toAddress, string subject, string htmlBody, CancellationToken ct). A second overload carrying the plain-text part and the From override is internal to SmtpEmailSender through a MailMessage record, so the public name and first signature stay compatible. SmtpEmailSender: MailKit + MimeKit, StartTls when EnableSsl, authenticate only with a username, connect and operation timeout from options. Registered only when mail is enabled; otherwise NullEmailSender (returns Disabled) is registered so callers never null-check.
  • EmailOptions (section Email): FromAddress, FromName, LogoUrl (optional, absolute or relative to App:PublicBaseUrl), BrandColor (optional #rrggbb), AllowedFromAddresses (array), Smtp{Host, Port=587, EnableSsl=true, Username, Password, TimeoutSeconds=10}. App:PublicBaseUrl, App:DefaultLanguage (nl|en, default nl). Validated at start when Smtp:Host is set: FromAddress valid and in AllowedFromAddresses (or the list is exactly that one address by default), https or localhost base URL without path, logo and colour well-formed, port 1..65535, timeout 1..60.
  • MailSendResult: Sent bool plus ErrorCode (disabled, not_configured, timeout, auth_failed, rejected, unknown). No exception text, no addresses beyond the recipient domain in logs.
  • IMailTemplateRenderer: Render(MailKind kind, string language, MailModel model) returns subject, HTML and text. One shared layout (inline CSS, tables, brand colour and optional logo, button plus raw link, footer). Resource dictionaries in code, one class per language, missing key falls back to nl. All dynamic values HTML-encoded; subject and display names reject CR/LF. Kinds: Invitation, NewInvitationLink, PasswordReset, AccountDeactivated, AccountReactivated, RoleChanged.
  • ILanguageResolver: Resolve(string? userLanguage) returns nl/en using user preference, then App:DefaultLanguage, then nl.
  • ISiteSettingsService: GetMailAsync() returns stored FromAddress/FromName or the configured defaults plus the allowlist; SetMailAsync(address, name, actor) validates (address must be in AllowedFromAddresses, name 1..80, no control characters) and stores. Table SiteSettings (one row, id fixed to 1).
  • IIdentityMailService: SendInvitationAsync(invitation, token, isNewLink), SendPasswordResetAsync(user, token), SendDeactivatedAsync/ReactivatedAsync/RoleChangedAsync(user, ...). Each builds the link from PublicBaseUrl + "/admin" + path, resolves language, renders, sends through IEmailSender, catches everything at the boundary, logs identity_mail_sent/identity_mail_failed (recipient domain, kind, error code) and returns MailSendResult. It never throws into the caller.
  • ResetCooldown: singleton, bool TryEnter(string normalizedAddress); one entry per address per 5 minutes; bounded memory (entries purged on access, hard cap) so it cannot grow without limit.

Identity module

  • UsersController (existing): POST invite accepts optional language, returns { inviteLink, mail }. POST {id}/regenerate-invite returns { inviteLink, mail }. New POST {id}/resend-invite: resends the current link, or regenerates first when expired; same hierarchy as the other invitation actions (UserManagementRules). PUT {id}/active and PUT {id}/role send the notice after success (a failure of the mail never fails the action). PUT me accepts language. UserDto/UserResponse gain language.
  • AuthController (existing): POST auth/forgot-password {email} anonymous, rate limited by the existing login limiter, identical 202 for every outcome, mail only when the account exists, is active and the cooldown allows. POST auth/reset-password {email, token, newPassword} anonymous, login limiter, validates through UserManager.ResetPasswordAsync; success revokes all refresh tokens (completion only); any failure answers one generic 400.
  • SiteSettingsController: GET SiteSettings/mail (Owner, Administrator), PUT SiteSettings/mail (Owner only). Response includes the allowlist so the UI offers only allowed choices.
  • System capabilities (existing SystemController): adds emailEnabled and defaultLanguage.

Frontend

Settings: "Mail" card (Owner edits: allowed address select + display name; Administrator sees it read-only). Profile: language select (nl/en, "default" option), applied immediately and saved. Invite dialog: language select (default = site default), shows the mail result with the copy-link fallback. Users list: resend action for pending invitations. Login: "Wachtwoord vergeten?" when emailEnabled; new pages /forgot-password and /reset-password. Everything hidden or unchanged when emailEnabled is false.

2. Data model (all additive)

Change Detail
SiteSettings (new table) Id int PK (always 1), MailFromAddress varchar(256) null, MailFromName varchar(80) null, UpdatedAt, UpdatedBy varchar(256) null
Users.PreferredLanguage varchar(8) null
Invitations.Language varchar(8) null
Down migrations drop exactly these. No data is rewritten; existing rows read as null (= site default).

3. Key flows

sequenceDiagram
    participant A as Administrator
    participant U as UsersController
    participant M as IdentityMailService
    participant S as SmtpEmailSender
    A->>U: POST Users/invite
    U->>U: create invitation (existing)
    U->>M: SendInvitationAsync
    M->>S: SendAsync
    S-->>M: sent or error code
    M-->>U: MailSendResult
    U-->>A: inviteLink and mail result

Text alternative: the invitation is created first; the mail result (sent or error code) is returned together with the copyable link, so a mail failure never loses the invitation.

sequenceDiagram
    participant V as Visitor
    participant AU as AuthController
    participant C as ResetCooldown
    participant M as IdentityMailService
    V->>AU: POST forgot-password
    AU->>C: TryEnter(address)
    AU->>M: SendPasswordResetAsync (only if user active and allowed)
    AU-->>V: 202 neutral (always the same)
    V->>AU: POST reset-password with token
    AU->>AU: ResetPasswordAsync (stamp changes, token single-use)
    AU->>AU: revoke all refresh tokens (completion only)
    AU-->>V: 200 or generic 400

Text alternative: requesting a reset only sends a mail and changes nothing else; revoking sessions happens only when a new password is actually set.

4. Design decisions and open choices

  • Reset does not touch sessions on request (Bryan's rule). forgot-password writes nothing except the in-memory cooldown. Tests prove: password hash, security stamp, access token and refresh tokens are unchanged after a request; after a completed reset refresh tokens are revoked, the old password fails, the token fails a second time.
  • D1 invitation language (choice, default proposed): the administrator picks nl/en in the invite dialog (default = site default); stored on the invitation, copied to the new account's PreferredLanguage on completion. Alternative: always site default, no field. Default proposal = the picker.
  • D2 access tokens after a completed reset (choice, recommended: yes): a reset or password change updates the security stamp, but today's access tokens stay valid until they expire (up to 60 minutes). Recommended: put the stamp in the access token and compare it in ActiveUserTokenValidation, so a completed reset (or password change) ends all sessions immediately. Cost: tokens issued before the deploy lack the claim and are refused once (refresh silently re-issues them). Alternative: leave access tokens to expire. This also closes the old gap that a password change did not end other sessions.
  • D3 sender envelope. When a site changes its sender in the settings, the mail uses that address in From; the SMTP envelope sender stays the SMTP account's own address (set by the server), which is what SPF checks. The From domain must therefore be aligned (SPF and DKIM) for DMARC, which is why the allowlist is mandatory and the check is in the Operations checklist.
  • D4 logo and colour in mail come from Email:LogoUrl / Email:BrandColor per site configuration (the backend does not know the frontend theme). ASF test sets the logo to /admin/brand-logo-on-light.png.
  • D5 message of the capability flag: a host without mail configuration reports emailEnabled: false; every new UI element is hidden and every endpoint that would send answers as today.
  • D6 timeouts: sending happens inside the request (Q8 A), so TimeoutSeconds bounds it; a timeout is reported as timeout and the fallback link is shown.

5. Property-based test targets (partial PBT)

  • PBT-02 round trip: link builder and parser: token encode then decode returns the token for any token; forgot/reset link query round trip.
  • PBT-03 invariants: rendered HTML never contains an unencoded </" from any display name or link; subject never contains CR/LF whatever the input; allowlist validator never accepts an address outside the list; cooldown never allows two sends within the window for one address.
  • PBT-07/08/09: generators for tokens, display names (including control characters, unicode, very long) and addresses; seeds logged and shrinking kept on; FsCheck.Xunit (already referenced in Core.Tests).

6. Security Baseline check of the design

SECURITY-03 (no PII/tokens/links in logs), 05 (all inputs validated, bounded), 08 (role checks; Owner-only settings write), 09 (no committed credentials, options validated at start), 11 (mail failure isolated, copy-link fallback), 12 (single-use time-limited tokens, uniform responses, revocation only on completion), 13 (pinned MailKit/MimeKit, scan gate), 14 (sent/failed events, alert in Operations), 15 (exceptions handled at the sender boundary): compliant by design. 01, 02, 04, 06, 07, 10: N/A or unchanged.