Eén bron (IMailAvailability) bepaalt of mail aan staat: SMTP-host gezet EN de hele mailconfiguratie geldig. Anders start de host gewoon, gebruikt de Null-verzender, meldt emailEnabled=false en logt eenmalig mail_configuration_invalid met de namen van de ontbrekende of ongeldige instellingen (nooit waarden of geheimen). Getest: halve config, elke soort fout, geen geheim in het log, volledige config werkt als voorheen, geen mailinstelling geeft geen enkele waarschuwing, alle verbruikers zien mail als uit. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
16 KiB
Requirements - identity-email-notifications
1. Intent analysis
- User request: Real e-mail for the CMS identity flows instead of "copy the link and pass it on": invitation mail, new link when an administrator regenerates one, password reset, and a notice on deactivation or role change. Decisions by Bryan, relayed by session "CMS & API" (17 answers in
requirement-verification-questions.md). - Request type: New feature (shared Core capability plus Identity flows plus admin UI).
- Scope: Multiple components: Core (sender abstraction, options, templates), Identity (flows, endpoints), Availability/settings (only if P1 is approved), Frontend (resend action, mail status, password-reset pages), all Clients (switched on per configuration).
- Complexity: Complex. Depth: Comprehensive (credentials, account-granting links, personal data, an anonymous endpoint).
- Extensions: Security Baseline = enforced; Property-Based Testing = partial (PBT-02, 03, 07, 08, 09); Operations phase = yes.
- Reference implementation (read-only): SimpleDeckApp (
SmtpEmailSender,IEmailSender,EmailOptions).
2. Fixed decisions (from the answers)
| # | Decision |
|---|---|
| Q1 | Same SMTP service as SimpleDeckApp. Local manual runs: smtp4dev (already installed). |
| Q3 | SPF/DKIM/DMARC already set up (Bryan); read-only DNS check in section 7. |
| Q4 | Mails: invitation, new invitation link, password reset, notice on deactivation, notice on role change. |
| Q5 | Shared template with the site's logo and brand colour (reuse the getBrand / BrandLogo idea). |
| Q6 | Dutch and English; selection rule is proposal P3. |
| Q7 | If sending fails the action still succeeds and the admin sees a clear message plus the copyable link. The admin can resend the mail (after a failure, and by hand). The copyable link is always available. |
| Q8 | Sent directly during the request (no queue). |
| Q9 | Credentials as Email__Smtp__Username / Email__Smtp__Password in the host's shared/env (mode 600). |
| Q10 | Only role checks, no extra rate limit; the anonymous password-reset request keeps the existing limiters (risk in P4). |
| Q11 | Public base URL per site (App:PublicBaseUrl or similar), validated at start-up. |
| Q12 | IEmailSender and EmailOptions in SlpModularCms.Core, same shape and names as SimpleDeckApp; no code shared across repos. |
| Q13 | Fake sender in tests (always); smtp4dev for manual runs; one real test mail to an address of Bryan on the test host before approval. |
| Q14 | All sites, switched on by configuration. No mail configured means today's copy-link flow, unchanged. |
3. Functional requirements
- FR-01 Sender abstraction.
IEmailSender.SendAsync(toAddress, subject, htmlBody, cancellationToken)in Core;SmtpEmailSender(MailKit/MimeKit; StartTls whenEnableSsl; authenticate only when a username is set).EmailOptions(sectionEmail):FromAddress,FromName,Smtp{Host, Port=587, EnableSsl=true, Username, Password}, plus a connect/send timeout (new, default 10 s). - FR-02 Enabled by configuration. Mail is enabled when
Email:Smtp:Hostis non-empty. When disabled, every flow behaves exactly as today.GETsystem capabilities exposesemailEnabledso the UI knows which actions to offer. - FR-03 Start-up validation (changed by Bryan, 2026-11-08: soft). When an SMTP host is set: valid
FromAddress/FromName, a port in range, credentials as a pair, and an absolute https (or localhost)App:PublicBaseUrlwithout a path. If anything is missing or invalid the host STILL starts, mail stays OFF (emailEnabled=false) and one Error log line names each setting (names only, no values, no secrets). - FR-04 Invitation mail. Creating an invitation sends a mail with the link
PublicBaseUrl + /admin + /invite/complete?token=.... The response still returnsinviteLinkand now alsomail: { sent: true|false, error?: <short code> }. A failure never rolls back the invitation. - FR-05 New link mail. The "create new invite link" action (existing) also sends the mail when enabled, with the same result object.
- FR-06 Resend. Admin action "Mail opnieuw versturen" for a pending invitation: resends the mail with the current valid link; if the invitation is expired it first regenerates it (new token, new lifetime), then sends. Same hierarchy rules as the other invitation actions (Administrator only for role User).
- FR-07 Password reset. Proposal P2 (below).
- FR-08 Notices. After a successful deactivation (and reactivation) and after a role change, the affected user gets a short notice mail (never the actor's data beyond a generic "an administrator"). Failure to send never fails the action. No notice for self-service changes.
- FR-09 Template. One shared HTML template (inline CSS, table layout, no external images except the brand logo URL served by the same site, plain-text alternative part): site name, logo (when the theme has one), brand colour, a primary button plus the raw link as text, footer with the sender. All dynamic values are HTML-encoded. Subject and display names are validated against header injection (no CR/LF).
- FR-10 Languages. Proposal P3.
- FR-11 Sender address per site. Proposal P1 (needs approval; not built until then).
- FR-12 UI. The invite dialog and the users list show the mail result ("Mail verstuurd naar ..." / "Mail kon niet worden verstuurd, kopieer de link"), the resend action, and keep the copy-link action. With mail disabled the UI is unchanged. Dutch and English strings.
- FR-13 Observability. Structured log events for sent / failed (recipient domain only, never the full address, never links, tokens or credentials). A security event for repeated failed reset requests per client is optional (P4).
4. Non-functional requirements
- NFR-01 No secrets in code or messages; credentials only via environment; never logged; options
ToString/validation messages never echo them. - NFR-02 Fail safe: SMTP errors are caught, logged, mapped to a short error code for the UI; they never become a 500 for the admin action; the request is bounded by the timeout (Q8 sends in-request).
- NFR-03 No account enumeration: the anonymous reset request answers identically for known and unknown addresses (status, body, and as far as practical timing).
- NFR-04 Tokens: reset and invitation tokens are single-use, time-limited, cryptographically random; reset tokens are stored hashed or are stateless (P2).
- NFR-05 Testability:
IEmailSenderis faked in unit and integration tests; the SMTP sender is tested against an in-process SMTP stub or smtp4dev where practical. - NFR-06 Compatibility: no behaviour change for any host without mail configuration; SlpSoftware and ASF both get the capability but only act when configured.
- NFR-07 Accessibility/usability of the mail: readable without images, link also as text, sensible subject lines.
5. Security Baseline compliance (applies, enforced)
| Rule | How this feature meets it |
|---|---|
| SECURITY-03 logging | Structured sent/failed events; no PII beyond recipient domain; no tokens, links or credentials in logs |
| SECURITY-05 input validation | Address format and length allowlist validation on every request that contains an address; display name length and control-character rules; link and token handling parameterised |
| SECURITY-08 access control | Mail actions follow UserManagementRules; settings changes follow the role chosen in P1; reset endpoints anonymous by necessity but limited (P4) |
| SECURITY-09 hardening | No default or sample credentials committed; placeholders only; start-up validation of options |
| SECURITY-11 secure design | Mail failure is non-fatal and isolated behind an interface; copy-link fallback keeps the system usable |
| SECURITY-12 credentials | Reset flow: single-use time-limited tokens, uniform responses, existing password rules, existing token revocation on password change; SMTP credentials via env only |
| SECURITY-13 integrity | Packages pinned (MailKit/MimeKit exact versions, vulnerability scan stays a gate) |
| SECURITY-14 alerting | Sent/failed counts as log events; Sentry picks up errors; an alert on repeated send failures is part of Operations |
| SECURITY-15 exceptions | All SMTP exceptions handled at the sender boundary; generic user-facing messages |
| SECURITY-01/02/04/06/07/10 | N/A or unchanged (no new data store beyond P1/P2 options, no new network intermediary; SMTP over StartTls enforced when EnableSsl) |
6. Proposals that need Bryan's approval before they are built
Nothing below is built until approved (relayed through "CMS & API").
P1 - Sender address per site in the site settings (answer to Q2)
Facts: there is no general site-settings store today. The only "settings" screen is availability; the admin-editable brand/site-name capability is a separately planned feature (noted earlier). A per-site sender address therefore needs a new, small settings store.
- Where it lives: a new Core table
SiteSettings(single row per site, versioned columns) with aSiteSettingsService; the existing Settings page gets a "Mail" card. It is the same store the planned brand/site-name capability would use, so this is also its first building block. Needs one EF migration (a new table; every host gets it on start, no data change). - Security: the free field must not let someone send as an arbitrary domain through the shared SMTP account (SPF/DKIM mismatch, spoofing, rejection). Proposed rule: the display name is free text (length 1..80, no control characters); the address is chosen from an allowlist configured per host (
Email:AllowedFromAddresses, exact full addresses, validated at start-up). The UI shows only the allowed choices. Default when nothing is set:Email:FromAddressfrom configuration. - Who may change it: Owner only (it influences deliverability and trust), Administrator may read.
- Alternatives: (a) config only now (smallest, no migration; per-site address set by whoever deploys); (b) the proposal above. Recommendation: (b) but built as a small store that the later brand feature reuses; if Bryan prefers a smaller first step, (a) plus the display name editable in settings.
P2 - Password reset as a new flow (answer to Q4 C)
Today there is no "forgot password". Proposed: POST auth/forgot-password (anonymous, always 202 with a neutral message, mail sent only when the address exists and is active) and POST auth/reset-password (token, new password). Tokens from ASP.NET Identity's data-protection token provider (stateless, single-use through the security stamp, default 1 hour, configurable), mail link to /admin/reset-password?token=...&email=..., new frontend page and a "Wachtwoord vergeten?" link on the login page (only when emailEnabled). A completed reset revokes all refresh tokens of the user. The existing "login" rate limiter applies. This adds default token providers to the Identity registration (a Core change that affects all hosts but is inert without mail).
P3 - Language selection (answer to Q6)
No per-user language exists today. Proposed for v1: the mail language is the site's default language (new App:DefaultLanguage, nl or en, default nl, aligned with the admin's VITE_DEFAULT_LANGUAGE). Per-user preferred language would need a new user column and migration and is left out. Strings live in one resource per language in Core; a missing key falls back to Dutch.
P4 - Anonymous reset and answer 10 B (risk)
B (role checks only) is fine for admin-triggered mails. The anonymous forgot-password endpoint can be used to flood one person's inbox (spread over many client addresses the per-address limiter does not help). Proposed small addition, no migration: a per-recipient cooldown in memory (one reset mail per address per 5 minutes, silently ignored while cooling down, same response). Needs approval because it goes beyond "no extra rate limit".
P5 - Mail status persistence (answer to Q7)
"Mail opnieuw versturen" needs to know which mails failed. Proposed v1: show the result in the response of the action and always offer the resend action for pending invitations (no stored status, no migration). A stored LastMailSentAt/LastMailError on invitations is a later option.
Decisions on P1-P5 (Bryan, relayed 2026-11-08) - these override the proposal text above where they differ
- P1 approved: build the
SiteSettingsstore with the mandatory allowlistEmail:AllowedFromAddresses. Only an Owner changes it; an Administrator reads it. A "Mail" card on the Settings page. Default when nothing is set:Email:FromAddress. - P2 approved, with a rule: sessions and refresh tokens are revoked only AFTER a new password has been chosen (a completed reset). Requesting a reset must not touch the existing password, sessions or refresh tokens. This is a hard requirement (FR-07a) with tests: request -> password unchanged, existing access token and refresh token still work; completed reset -> all refresh tokens revoked, old password rejected, reset token unusable a second time.
- P3 changed to per user, now: a nullable
PreferredLanguagecolumn on the user (additive migration, valuesnl/en), chosen in the profile. Fallback chain: user preference, else the site defaultApp:DefaultLanguage(defaultnl). For an invitee without an account: the administrator may choose a language when inviting (stored on the invitation, copied to the new account); without a choice the site default applies (design decision D1, see application design). The password-reset mail uses the user's preference, then the site default. - P4 approved: in-memory cooldown, one reset mail per address per 5 minutes, silently ignored with the identical response.
- P5 approved: no stored mail status; result in the response plus a resend action.
- Operations checklist item (production): the sender domain must be aligned: SPF of the sender domain must authorise the SMTP service that actually sends, and that service must DKIM-sign for that domain. See section 7; carried into the Operations plan.
7. Read-only check of sender domains (DNS, 2026-11-08)
slpsoftware.nl: SPFv=spf1 a mx include:smtp.spf.ziggo.nl ~all; DMARCv=DMARC1; p=none; DKIM record found at selectordkim._domainkey(public key present).andreaslop.nl: SPFv=spf1 a mx include:smtp.spf.ziggo.nl ~all; DMARCv=DMARC1; p=none; DKIM record found at selectordkim._domainkey.- Observations (for Bryan): SPF authorises the domain's own A/MX hosts and the Ziggo SMTP relay; it does not name any transactional service, so sending through the SimpleDeckApp SMTP service works only when that service is
mail.<domain>or the Ziggo relay (to be confirmed with the real host name; not visible from the repo). DMARC isp=none(monitoring only, not enforced). The DKIM record being present does not prove that the SMTP service signs with it. Per-site domains such asandreaslop.nlhave the same pattern asslpsoftware.nlbut are a different domain: a mail with sender@andreaslop.nlis only aligned if the SMTP service signs for that domain too. This is exactly why P1 proposes an allowlist.
8. Out of scope
HTML template editor, per-user language, queue or retry worker, delivery tracking or bounces, marketing mail, SMS, inbound mail.
9. Acceptance (summary)
- Mail disabled: all existing tests unchanged and green.
- Mail enabled with a fake sender: invitation, new link, resend, reset, deactivation and role-change notices produce the expected message (recipient, language, link, encoded values); failures never fail the action and show the copy-link fallback.
- Property-based tests (partial): link builder round trip (token encode/decode), template HTML-encoding invariant for any display name, header-injection rejection for any subject/name, allowlist validator (PBT-02/03/07/08/09).
- Manual: smtp4dev run, then one real test mail to an address of Bryan from the test host before approval.