U1 mail-foundation (backend): verzender, opties, sjabloon, SiteSettings met toegestane afzenderlijst

IEmailSender met MailKit-implementatie (StartTls, timeout, fouten als waarde), opties met
startvalidatie, nl/en sjabloon, taalkeuze, tabel SiteSettings (additieve migratie),
SiteSettings-API (Beheerder leest, Eigenaar wijzigt) en emailEnabled/defaultLanguage in de
capabilities. Zonder SMTP-host verandert er niets.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 18:22:26 +01:00
co-authored by Claude Sonnet 5.5
parent 1a2fb56e1e
commit 745f0b2203
27 changed files with 2069 additions and 2 deletions
@@ -74,4 +74,16 @@ public class HostConfigurationTests
referenced.Should().NotContain("SlpModularCms.Modules.Offerings")
.And.NotContain("SlpModularCms.Modules.Master");
}
[Fact]
public void Mail_IsOffByDefault_AndNoCredentialIsCommitted()
{
var config = Load();
config["Email:Smtp:Host"].Should().BeNullOrEmpty("mail is switched on per environment");
config["Email:Smtp:Username"].Should().BeNullOrEmpty();
config["Email:Smtp:Password"].Should().BeNullOrEmpty();
config["Email:FromAddress"].Should().NotBeNullOrEmpty();
config["Email:LogoUrl"].Should().Be("/admin/brand-logo-on-light.png");
}
}
@@ -48,6 +48,31 @@
// production instance must set Website__NoIndex=false explicitly.
"NoIndex": true
},
// Mail (invitations, password reset, notices). Mail is OFF while Email:Smtp:Host is empty and every
// flow then works as before (copy the link). Enable per environment with environment variables:
// Email__Smtp__Host, Email__Smtp__Port, Email__Smtp__EnableSsl, Email__Smtp__Username,
// Email__Smtp__Password (secrets only there, never in this file) and App__PublicBaseUrl.
// Extra sender addresses a site may choose in its settings go in Email:AllowedFromAddresses.
"Email": {
"FromAddress": "no-reply@slpsoftware.nl",
"FromName": "Andrea Slop Fotografie",
"AllowedFromAddresses": [],
"LogoUrl": "/admin/brand-logo-on-light.png",
"BrandColor": "#5f6a58",
"Smtp": {
"Host": "",
"Port": 587,
"EnableSsl": true,
"Username": "",
"Password": "",
"TimeoutSeconds": 10
}
},
"App": {
// Public https address of this site, used for links in mails, e.g. https://test.andreaslop.nl
"PublicBaseUrl": "",
"DefaultLanguage": "nl"
},
"Cors": {
"AllowedOrigins": []
},
@@ -33,6 +33,31 @@
"FailOpenAfterMinutes": 5,
"HttpTimeoutSeconds": 5
},
// Mail (invitations, password reset, notices). Mail is OFF while Email:Smtp:Host is empty and every
// flow then works as before (copy the link). Enable per environment with environment variables:
// Email__Smtp__Host, Email__Smtp__Port, Email__Smtp__EnableSsl, Email__Smtp__Username,
// Email__Smtp__Password (secrets only there, never in this file) and App__PublicBaseUrl.
// Extra sender addresses a site may choose in its settings go in Email:AllowedFromAddresses.
"Email": {
"FromAddress": "no-reply@slpsoftware.nl",
"FromName": "SLP Software",
"AllowedFromAddresses": [],
"LogoUrl": "",
"BrandColor": "",
"Smtp": {
"Host": "",
"Port": 587,
"EnableSsl": true,
"Username": "",
"Password": "",
"TimeoutSeconds": 10
}
},
"App": {
// Public https address of this site, used for links in mails, e.g. https://test.andreaslop.nl
"PublicBaseUrl": "",
"DefaultLanguage": "nl"
},
"Cors": {
"AllowedOrigins": []
},
@@ -0,0 +1,264 @@
using FluentAssertions;
using FsCheck;
using FsCheck.Fluent;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Email;
using Xunit.Abstractions;
namespace SlpModularCms.Core.Tests.Email;
public class EmailOptionsValidatorTests
{
private static EmailOptionsValidator Validator(string baseUrl = "https://test.example.nl", string lang = "nl") =>
new(Options.Create(new AppMailOptions { PublicBaseUrl = baseUrl, DefaultLanguage = lang }));
private static EmailOptions Valid() => new()
{
FromAddress = "no-reply@example.nl",
FromName = "Example",
Smtp = { Host = "mail.example.nl", Port = 587, Username = "u", Password = "p" }
};
[Fact]
public void WithoutAHost_MailIsDisabled_AndNothingIsValidated() =>
Validator("", "xx").Validate(null, new EmailOptions()).Succeeded.Should().BeTrue();
[Fact]
public void AValidConfiguration_Passes() =>
Validator().Validate(null, Valid()).Succeeded.Should().BeTrue();
[Theory]
[InlineData("http://example.nl")] // http only allowed for localhost
[InlineData("https://example.nl/admin")] // no path
[InlineData("https://example.nl/?a=1")]
[InlineData("https://user:pw@example.nl")]
[InlineData("example.nl")]
[InlineData("")]
public void ABadPublicBaseUrl_FailsStartup(string url) =>
Validator(url).Validate(null, Valid()).Failed.Should().BeTrue();
[Theory]
[InlineData("http://localhost:5200")]
[InlineData("https://test.andreaslop.nl")]
[InlineData("https://test.andreaslop.nl/")]
public void GoodPublicBaseUrls_Pass(string url) =>
Validator(url).Validate(null, Valid()).Succeeded.Should().BeTrue();
[Fact]
public void EachProblem_IsReported_AndNeverEchoesTheCredentials()
{
var o = Valid();
o.FromAddress = "not-an-address";
o.FromName = "";
o.Smtp.Port = 0;
o.Smtp.TimeoutSeconds = 0;
o.Smtp.Password = ""; // username set, password empty
o.BrandColor = "red";
o.LogoUrl = "javascript:alert(1)";
o.AllowedFromAddresses = ["bad"];
var result = Validator("http://x.nl", "xx").Validate(null, o);
result.Failed.Should().BeTrue();
var text = string.Join(" | ", result.Failures!);
text.Should().Contain("FromAddress").And.Contain("FromName").And.Contain("Port").And.Contain("TimeoutSeconds")
.And.Contain("Password").And.Contain("BrandColor").And.Contain("LogoUrl")
.And.Contain("AllowedFromAddresses").And.Contain("PublicBaseUrl").And.Contain("DefaultLanguage");
text.Should().NotContain("mail.example.nl");
}
[Fact]
public void ToString_NeverContainsTheCredentials()
{
var o = Valid();
o.Smtp.Username = "user-secret-1";
o.Smtp.Password = "pw-secret-2";
o.ToString().Should().NotContain("user-secret-1").And.NotContain("pw-secret-2");
}
}
public class EmailAddressRulesTests
{
[Theory]
[InlineData("no-reply@slpsoftware.nl", true)]
[InlineData("a.b+c@sub.example.org", true)]
[InlineData("", false)]
[InlineData("a@b", false)]
[InlineData("a b@example.nl", false)]
[InlineData("a@example.nl\r\nBcc: x@y.nl", false)]
[InlineData("\"quoted\"@example.nl", false)]
[InlineData("a@exa mple.nl", false)]
[InlineData("<a@example.nl>", false)]
public void Address_IsAnAllowlistMatch(string value, bool expected) =>
EmailAddressRules.IsValidAddress(value).Should().Be(expected);
[Theory]
[InlineData("Andrea Slop Fotografie", true)]
[InlineData("Décor & Co", true)]
[InlineData("", false)]
[InlineData(" ", false)]
[InlineData("two\nlines", false)]
[InlineData("tab\there", false)]
public void DisplayName_RejectsControlCharacters(string value, bool expected) =>
EmailAddressRules.IsValidDisplayName(value).Should().Be(expected);
[Fact]
public void DisplayName_HasALengthLimit()
{
EmailAddressRules.IsValidDisplayName(new string('a', 80)).Should().BeTrue();
EmailAddressRules.IsValidDisplayName(new string('a', 81)).Should().BeFalse();
}
[Fact]
public void Sender_MustBeTheDefaultOrOnTheAllowlist()
{
string[] allowed = ["info@andreaslop.nl"];
EmailAddressRules.IsAllowedSender("no-reply@slpsoftware.nl", "no-reply@slpsoftware.nl", allowed).Should().BeTrue();
EmailAddressRules.IsAllowedSender("INFO@AndreaSlop.nl", "no-reply@slpsoftware.nl", allowed).Should().BeTrue();
EmailAddressRules.IsAllowedSender("evil@other.nl", "no-reply@slpsoftware.nl", allowed).Should().BeFalse();
}
}
public class MailTemplateRendererTests
{
private readonly MailTemplateRenderer _renderer = new();
private static MailModel Model(string site = "Andrea Slop Fotografie", string? action = "https://t.nl/admin/invite/complete?token=abc%2Fd", string? name = null) =>
new(site, name, action, ValidForMinutes: 1440, Detail: "Administrator", LogoUrl: "https://t.nl/admin/brand-logo-on-light.png", BrandColor: "#2b6cb0");
[Fact]
public void Invitation_IsRenderedInDutchWithLinkLogoAndColour()
{
var mail = _renderer.Render(MailKind.Invitation, "nl", Model());
mail.Subject.Should().Be("Uitnodiging voor Andrea Slop Fotografie");
mail.Html.Should().Contain("Account activeren").And.Contain("https://t.nl/admin/invite/complete?token=abc%2Fd")
.And.Contain("brand-logo-on-light.png").And.Contain("#2b6cb0").And.Contain("24 uur");
mail.Text.Should().Contain("https://t.nl/admin/invite/complete?token=abc%2Fd").And.Contain("24 uur");
}
[Fact]
public void English_IsSupported_AndAnUnknownLanguageFallsBackToDutch()
{
_renderer.Render(MailKind.Invitation, "en", Model()).Subject.Should().Be("Invitation to Andrea Slop Fotografie");
_renderer.Render(MailKind.Invitation, "fr", Model()).Subject.Should().StartWith("Uitnodiging");
_renderer.Render(MailKind.Invitation, "EN-gb", Model()).Subject.Should().StartWith("Invitation");
}
[Fact]
public void RoleNotice_UsesTheLocalisedRoleName()
{
_renderer.Render(MailKind.RoleChanged, "nl", Model(action: null)).Text.Should().Contain("Beheerder");
_renderer.Render(MailKind.RoleChanged, "en", Model(action: null)).Text.Should().Contain("Administrator");
}
[Fact]
public void ANoticeWithoutAButton_HasNoLink()
{
var mail = _renderer.Render(MailKind.AccountDeactivated, "nl", Model(action: "https://t.nl/x"));
mail.Html.Should().NotContain("https://t.nl/x");
mail.Text.Should().NotContain("https://t.nl/x");
}
[Fact]
public void ADisplayNameWithMarkup_IsEncoded_NotInterpreted()
{
var mail = _renderer.Render(MailKind.Invitation, "nl", Model(site: "<script>alert(1)</script> & \"Co\"", name: "<b>x</b>"));
mail.Html.Should().NotContain("<script>").And.NotContain("<b>x</b>");
mail.Html.Should().Contain("&lt;script&gt;");
}
[Fact]
public void PasswordReset_States_ThatIgnoringItKeepsThePassword()
{
_renderer.Render(MailKind.PasswordReset, "nl", Model()).Text.Should().Contain("ongewijzigd");
_renderer.Render(MailKind.PasswordReset, "en", Model()).Text.Should().Contain("unchanged");
}
[Fact]
public void AnInvalidBrandColour_FallsBackToTheDefault()
{
var mail = _renderer.Render(MailKind.Invitation, "nl", Model() with { BrandColor = "red;}</style>" });
mail.Html.Should().NotContain("red;}");
}
[Fact]
public void LanguageResolver_UsesUserThenSiteDefaultThenDutch()
{
var resolver = new LanguageResolver(Options.Create(new AppMailOptions { DefaultLanguage = "en" }));
resolver.Resolve("nl").Should().Be("nl");
resolver.Resolve(null).Should().Be("en");
resolver.Resolve("de").Should().Be("en");
new LanguageResolver(Options.Create(new AppMailOptions { DefaultLanguage = "??" })).Resolve(null).Should().Be("nl");
}
}
/// <summary>Property-based tests (PBT-03 invariants, PBT-07 generators with control characters and markup; PBT-08 seed printed by FsCheck).</summary>
public class MailPropertyTests(ITestOutputHelper output)
{
private static readonly string[] Pieces =
[
"a", "Z", "é", "ß", " ", "<", ">", "&", "\"", "'", "/", "\\", "\r", "\n", "\0", "\t", "{", "}", "{0}", "%", "@", ".", "-", "😀", "script", "javascript:"
];
private static Arbitrary<string> Strings() =>
Gen.Elements(Pieces).ArrayOf().Select(p => string.Concat(p)).ToArbitrary();
private void Check(Func<string, bool> property)
{
Prop.ForAll(Strings(), s => property(s)).Check(Config.QuickThrowOnFailure.WithMaxTest(1500));
output.WriteLine("Property held for 1500 generated inputs.");
}
[Fact]
public void Rendering_NeverThrows_NeverLeaksMarkup_AndKeepsTheSubjectOnOneLine() =>
Check(s =>
{
var renderer = new MailTemplateRenderer();
// Markers make the generated value findable inside the output.
var site = "QQ" + s + "ZZ";
var hasMarkup = s.IndexOfAny(['<', '>', '&', '"']) >= 0;
foreach (var kind in Enum.GetValues<MailKind>())
foreach (var lang in new[] { "nl", "en" })
{
var mail = renderer.Render(kind, lang, new MailModel(site, site, "https://t.nl/x?a=" + Uri.EscapeDataString(site), 60, site));
if (mail.Subject.Any(char.IsControl)) return false;
// A value containing markup characters must never appear raw in the HTML body.
if (hasMarkup && mail.Html.Contains(site, StringComparison.Ordinal)) return false;
}
return true;
});
[Fact]
public void ADisplayNameWithAControlCharacter_IsNeverValid() =>
Check(s => !s.Any(char.IsControl) || !EmailAddressRules.IsValidDisplayName(s));
[Fact]
public void AnAddressWithAnythingOutsideTheAllowedAlphabet_IsNeverValid() =>
Check(s => !EmailAddressRules.IsValidAddress(s)
|| s.All(c => char.IsAsciiLetterOrDigit(c) || "._%+-@".Contains(c)));
[Fact]
public void AnAddressNotOnTheAllowlist_IsNeverAllowedAsSender() =>
Check(s =>
{
string[] allowed = ["info@andreaslop.nl"];
var ok = EmailAddressRules.IsAllowedSender(s, "no-reply@slpsoftware.nl", allowed);
return !ok || s.Equals("no-reply@slpsoftware.nl", StringComparison.OrdinalIgnoreCase)
|| s.Equals("info@andreaslop.nl", StringComparison.OrdinalIgnoreCase);
});
[Fact]
public void ATokenSurvivesTheLinkRoundTrip() =>
Check(token =>
{
// The link carries the token as a query value: escape, then parse, must return the token.
var link = "https://t.nl/admin/invite/complete?token=" + Uri.EscapeDataString(token);
var query = new Uri(link).Query.TrimStart('?');
var value = Uri.UnescapeDataString(query["token=".Length..]);
return value == token;
});
}
@@ -0,0 +1,59 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using MySql.Data.MySqlClient;
using SlpModularCms.Core.Data;
namespace SlpModularCms.Core.Tests.Email;
/// <summary>
/// The schema changes for this feature must apply, undo and re-apply on a real MariaDB (additive and
/// reversible, safe for SlpSoftware's database). Uses its own scratch database from
/// <c>ConnectionStrings__DefaultConnection</c> (set in CI); does nothing when that variable is absent.
/// </summary>
public class MigrationRoundTripTests
{
[Fact]
public async Task AllMigrations_ApplyOnMariaDb_AndTheNewestCanBeUndoneAndReapplied()
{
var raw = Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection");
if (string.IsNullOrWhiteSpace(raw)) return; // no MariaDB available here
var cs = new MySqlConnectionStringBuilder(raw) { Database = "migration_roundtrip_probe" }.ConnectionString;
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseMySQL(cs)
.ReplaceService<Microsoft.EntityFrameworkCore.Migrations.IHistoryRepository, SlpModularCms.Core.Hosting.NonLockingMySQLHistoryRepository>() // as in production
.Options;
await using var db = new ApplicationDbContext(options);
try
{
await db.Database.EnsureDeletedAsync();
await db.Database.MigrateAsync();
(await TableExists(db, "SiteSettings")).Should().BeTrue();
var migrations = db.GetService<IMigrationsAssembly>().Migrations.Keys.OrderBy(k => k).ToList();
var previous = migrations[^2];
var migrator = db.GetService<IMigrator>();
await migrator.MigrateAsync(previous); // undo the newest
(await TableExists(db, "SiteSettings")).Should().BeFalse();
await migrator.MigrateAsync(); // and apply it again
(await TableExists(db, "SiteSettings")).Should().BeTrue();
}
finally
{
await db.Database.EnsureDeletedAsync();
}
}
private static async Task<bool> TableExists(ApplicationDbContext db, string table)
{
var rows = await db.Database
.SqlQuery<int>($"select count(*) as Value from information_schema.tables where table_schema = database() and table_name = {table}")
.ToListAsync();
return rows[0] > 0;
}
}
@@ -0,0 +1,154 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Data;
using SlpModularCms.Core.Email;
using SlpModularCms.Core.Hosting;
using SlpModularCms.Core.SiteSettings;
namespace SlpModularCms.Core.Tests.Email;
public class SiteSettingsServiceTests : IDisposable
{
private readonly ApplicationDbContext _db;
public SiteSettingsServiceTests() =>
_db = new ApplicationDbContext(new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
public void Dispose() => _db.Dispose();
private SiteSettingsService Service(string host = "mail.example.nl", string[]? allowed = null) =>
new(_db, Options.Create(new EmailOptions
{
FromAddress = "no-reply@example.nl",
FromName = "Example",
AllowedFromAddresses = allowed ?? ["info@andreaslop.nl"],
Smtp = { Host = host }
}));
[Fact]
public async Task WithNothingStored_TheConfiguredDefaultsApply()
{
var view = await Service().GetMailAsync();
view.EmailEnabled.Should().BeTrue();
view.FromAddress.Should().Be("no-reply@example.nl");
view.FromName.Should().Be("Example");
view.IsCustomized.Should().BeFalse();
view.AllowedFromAddresses.Should().BeEquivalentTo("no-reply@example.nl", "info@andreaslop.nl");
}
[Fact]
public async Task AnAllowedAddressAndName_AreStored_AndUsed()
{
var result = await Service().SetMailAsync("info@andreaslop.nl", "Andrea Slop Fotografie", "owner@example.nl");
result.Ok.Should().BeTrue();
var sender = await Service().GetEffectiveSenderAsync();
sender.Should().Be(("info@andreaslop.nl", "Andrea Slop Fotografie"));
var row = await _db.SiteSettings.SingleAsync();
row.UpdatedBy.Should().Be("owner@example.nl");
}
[Theory]
[InlineData("evil@other.nl", "Name", SetMailResult.AddressNotAllowed)]
[InlineData("not-an-address", "Name", SetMailResult.InvalidAddress)]
[InlineData("info@andreaslop.nl", "two\nlines", SetMailResult.InvalidName)]
[InlineData("info@andreaslop.nl", "x", null)]
public async Task Validation_RejectsWhatIsNotAllowed(string address, string name, string? expectedError)
{
var result = await Service().SetMailAsync(address, name, null);
result.Error.Should().Be(expectedError);
if (expectedError is not null) (await _db.SiteSettings.CountAsync()).Should().Be(0);
}
[Fact]
public async Task BlankValues_ResetToTheDefaults()
{
await Service().SetMailAsync("info@andreaslop.nl", "Andrea", null);
(await Service().SetMailAsync(null, " ", null)).Ok.Should().BeTrue();
var view = await Service().GetMailAsync();
view.FromAddress.Should().Be("no-reply@example.nl");
view.IsCustomized.Should().BeFalse();
}
[Fact]
public async Task AStoredAddress_ThatIsNoLongerAllowed_FallsBackToTheDefault()
{
await Service().SetMailAsync("info@andreaslop.nl", "Andrea", null);
// The host's allowlist is narrowed later: the mail must not go out as the old address.
var sender = await Service(allowed: []).GetEffectiveSenderAsync();
sender.Address.Should().Be("no-reply@example.nl");
sender.Name.Should().Be("Andrea");
}
[Fact]
public async Task WhenMailIsDisabled_SettingsCannotBeChanged()
{
var result = await Service(host: "").SetMailAsync("info@andreaslop.nl", "x", null);
result.Error.Should().Be(SetMailResult.MailDisabled);
(await Service(host: "").GetMailAsync()).EmailEnabled.Should().BeFalse();
}
}
public class EmailRegistrationTests
{
private static IServiceProvider Build(Dictionary<string, string?> values)
{
var config = new ConfigurationBuilder().AddInMemoryCollection(values).Build();
var services = new ServiceCollection();
services.AddLogging();
services.AddCmsEmail(config);
return services.BuildServiceProvider();
}
[Fact]
public void WithoutAHost_TheNullSenderIsRegistered_AndNothingIsValidated()
{
var sp = Build(new() { ["App:PublicBaseUrl"] = "garbage" });
sp.GetRequiredService<IEmailSender>().Should().BeOfType<NullEmailSender>();
sp.GetRequiredService<IOptions<EmailOptions>>().Value.Smtp.Host.Should().BeEmpty();
}
[Fact]
public void WithAHost_TheSmtpSenderIsRegistered()
{
var sp = Build(new()
{
["Email:Smtp:Host"] = "mail.example.nl", ["Email:FromAddress"] = "no-reply@example.nl",
["Email:FromName"] = "Example", ["App:PublicBaseUrl"] = "https://example.nl"
});
sp.GetRequiredService<IEmailSender>().Should().BeOfType<SmtpEmailSender>();
sp.GetRequiredService<IOptions<EmailOptions>>().Value.Smtp.Port.Should().Be(587);
sp.GetRequiredService<IOptions<EmailOptions>>().Value.Smtp.EnableSsl.Should().BeTrue();
}
[Fact]
public void WithAHostButABrokenConfiguration_OptionsFail()
{
var sp = Build(new() { ["Email:Smtp:Host"] = "mail.example.nl", ["App:PublicBaseUrl"] = "http://example.nl" });
var act = () => sp.GetRequiredService<IOptions<EmailOptions>>().Value;
act.Should().Throw<OptionsValidationException>().WithMessage("*FromAddress*");
}
[Fact]
public void IsEmailEnabled_FollowsTheHost()
{
new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?> { ["Email:Smtp:Host"] = "x" }).Build()
.IsEmailEnabled().Should().BeTrue();
new ConfigurationBuilder().Build().IsEmailEnabled().Should().BeFalse();
}
}
@@ -0,0 +1,160 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Email;
namespace SlpModularCms.Core.Tests.Email;
/// <summary>A minimal in-process SMTP server: accepts one message and records it. No TLS, no auth.</summary>
internal sealed class StubSmtpServer : IDisposable
{
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
private readonly bool _silent;
private readonly Task _loop;
public string? ReceivedData { get; private set; }
public string? MailFrom { get; private set; }
public List<string> Recipients { get; } = [];
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
/// <param name="silent">Accept connections but never answer (to provoke the timeout).</param>
public StubSmtpServer(bool silent = false)
{
_silent = silent;
_listener.Start();
_loop = Task.Run(Serve);
}
private async Task Serve()
{
try
{
using var client = await _listener.AcceptTcpClientAsync();
if (_silent) { await Task.Delay(TimeSpan.FromSeconds(30)); return; }
await using var stream = client.GetStream();
using var reader = new StreamReader(stream, Encoding.ASCII);
await using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true, NewLine = "\r\n" };
await writer.WriteLineAsync("220 stub ESMTP");
while (await reader.ReadLineAsync() is { } line)
{
if (line.StartsWith("EHLO", StringComparison.OrdinalIgnoreCase)) await writer.WriteLineAsync("250 stub");
else if (line.StartsWith("MAIL FROM", StringComparison.OrdinalIgnoreCase)) { MailFrom = line; await writer.WriteLineAsync("250 ok"); }
else if (line.StartsWith("RCPT TO", StringComparison.OrdinalIgnoreCase)) { Recipients.Add(line); await writer.WriteLineAsync("250 ok"); }
else if (line.StartsWith("DATA", StringComparison.OrdinalIgnoreCase))
{
await writer.WriteLineAsync("354 go");
var data = new StringBuilder();
while (await reader.ReadLineAsync() is { } d && d != ".") data.AppendLine(d);
ReceivedData = data.ToString();
await writer.WriteLineAsync("250 queued");
}
else if (line.StartsWith("QUIT", StringComparison.OrdinalIgnoreCase)) { await writer.WriteLineAsync("221 bye"); break; }
else await writer.WriteLineAsync("250 ok");
}
}
catch (Exception) { /* the test ended or the client disconnected */ }
}
public void Dispose() => _listener.Stop();
}
public class SmtpEmailSenderTests
{
private static SmtpEmailSender Sender(int port, int timeoutSeconds = 5) => new(
Options.Create(new EmailOptions
{
FromAddress = "no-reply@example.nl",
FromName = "Example Site",
Smtp = { Host = "127.0.0.1", Port = port, EnableSsl = false, TimeoutSeconds = timeoutSeconds }
}),
NullLogger<SmtpEmailSender>.Instance);
[Fact]
public async Task Sends_TheMail_WithTheConfiguredSender()
{
using var server = new StubSmtpServer();
var result = await Sender(server.Port).SendAsync(new OutgoingMail("to@example.org", "Hello", "<p>Body</p>", "Body"));
result.Should().Be(MailSendResult.Ok);
server.MailFrom.Should().Contain("no-reply@example.nl");
server.Recipients.Should().ContainSingle().Which.Should().Contain("to@example.org");
server.ReceivedData.Should().Contain("Subject: Hello").And.Contain("Example Site").And.Contain("Body");
}
[Fact]
public async Task ASenderOverride_IsUsedForTheFromHeader()
{
using var server = new StubSmtpServer();
var result = await Sender(server.Port).SendAsync(
new OutgoingMail("to@example.org", "Hi", "<p>x</p>", FromAddress: "info@example.nl", FromName: "Andrea"));
result.Sent.Should().BeTrue();
server.ReceivedData.Should().Contain("From: Andrea <info@example.nl>");
}
[Fact]
public async Task ASimpleDeckAppShapedCall_Works()
{
using var server = new StubSmtpServer();
var result = await Sender(server.Port).SendAsync("to@example.org", "Subject", "<p>x</p>");
result.Sent.Should().BeTrue();
}
[Theory]
[InlineData("to@example.org\r\nBcc: victim@example.org", "Subject")]
[InlineData("not-an-address", "Subject")]
[InlineData("to@example.org", "Subject\r\nBcc: victim@example.org")]
public async Task HeaderInjectionAndBadAddresses_AreRefused_WithoutConnecting(string to, string subject)
{
using var server = new StubSmtpServer();
var result = await Sender(server.Port).SendAsync(new OutgoingMail(to, subject, "<p>x</p>"));
result.Should().Be(MailSendResult.Fail(MailSendResult.Rejected));
server.ReceivedData.Should().BeNull();
server.Recipients.Should().BeEmpty();
}
[Fact]
public async Task ASlowServer_ProducesATimeout_NotAnException()
{
using var server = new StubSmtpServer(silent: true);
var started = DateTime.UtcNow;
var result = await Sender(server.Port, timeoutSeconds: 1).SendAsync(new OutgoingMail("to@example.org", "S", "<p>x</p>"));
result.Should().Be(MailSendResult.Fail(MailSendResult.Timeout));
(DateTime.UtcNow - started).Should().BeLessThan(TimeSpan.FromSeconds(10));
}
[Fact]
public async Task ANeverListeningServer_IsAFailureValue_NotAnException()
{
int freePort;
using (var probe = new TcpListener(IPAddress.Loopback, 0)) { probe.Start(); freePort = ((IPEndPoint)probe.LocalEndpoint).Port; }
var result = await Sender(freePort, timeoutSeconds: 2).SendAsync(new OutgoingMail("to@example.org", "S", "<p>x</p>"));
result.Sent.Should().BeFalse();
result.ErrorCode.Should().NotBeNullOrEmpty();
}
[Fact]
public async Task WithoutAHost_ItReportsNotConfigured()
{
var sender = new SmtpEmailSender(Options.Create(new EmailOptions()), NullLogger<SmtpEmailSender>.Instance);
(await sender.SendAsync(new OutgoingMail("to@example.org", "S", "x"))).Should().Be(MailSendResult.Fail(MailSendResult.NotConfigured));
}
[Fact]
public async Task TheNullSender_ReportsDisabled() =>
(await new NullEmailSender().SendAsync(new OutgoingMail("to@example.org", "S", "x"))).Should().Be(MailSendResult.Fail(MailSendResult.Disabled));
}
@@ -23,6 +23,7 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Applicati
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
public DbSet<Invitation> Invitations => Set<Invitation>();
public DbSet<SlpModularCms.Core.SiteSettings.SiteSettingsEntity> SiteSettings => Set<SlpModularCms.Core.SiteSettings.SiteSettingsEntity>();
public DbSet<ModulePermission> ModulePermissions => Set<ModulePermission>();
public DbSet<GlobalAvailabilityState> AvailabilityStates => Set<GlobalAvailabilityState>();
@@ -75,6 +76,17 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Applicati
entity.Property(e => e.Email).IsRequired().HasMaxLength(256);
});
// Configuratie voor SiteSettings (een rij, Id = 1)
builder.Entity<SlpModularCms.Core.SiteSettings.SiteSettingsEntity>(entity =>
{
entity.ToTable("SiteSettings");
entity.HasKey(e => e.Id);
entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.MailFromAddress).HasMaxLength(256);
entity.Property(e => e.MailFromName).HasMaxLength(80);
entity.Property(e => e.UpdatedBy).HasMaxLength(256);
});
// Configuratie voor ModulePermissions
builder.Entity<ModulePermission>(entity =>
{
@@ -0,0 +1,38 @@
using System.Text.RegularExpressions;
namespace SlpModularCms.Core.Email;
/// <summary>
/// Validation of the values that end up in mail headers. Strict on purpose (allowlist, no control
/// characters): a sender address or display name is a header, and a header is an injection target.
/// </summary>
public static partial class EmailAddressRules
{
public const int MaxAddressLength = 254;
public const int MaxDisplayNameLength = 80;
// Plain ASCII local@domain.tld: deliberately narrower than RFC 5322 (no quoted strings, no comments).
[GeneratedRegex(@"^[A-Za-z0-9._%+\-]{1,64}@(?:[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}$")]
private static partial Regex AddressRegex();
[GeneratedRegex(@"^#[0-9A-Fa-f]{6}$")]
private static partial Regex ColourRegex();
public static bool IsValidAddress(string? value) =>
!string.IsNullOrEmpty(value) && value.Length <= MaxAddressLength && AddressRegex().IsMatch(value);
public static bool IsValidDisplayName(string? value) =>
!string.IsNullOrWhiteSpace(value) && value.Trim().Length <= MaxDisplayNameLength && !ContainsControlCharacters(value);
public static bool IsValidColour(string? value) => !string.IsNullOrEmpty(value) && ColourRegex().IsMatch(value);
/// <summary>True for CR, LF, NUL and any other control character (header injection and friends).</summary>
public static bool ContainsControlCharacters(string value) => value.Any(char.IsControl);
public static bool IsAllowedSender(string? address, string defaultAddress, IEnumerable<string> allowed)
{
if (!IsValidAddress(address)) return false;
if (string.Equals(address, defaultAddress, StringComparison.OrdinalIgnoreCase)) return true;
return allowed.Any(a => string.Equals(a, address, StringComparison.OrdinalIgnoreCase));
}
}
@@ -0,0 +1,65 @@
using System.Diagnostics.CodeAnalysis;
namespace SlpModularCms.Core.Email;
/// <summary>
/// Mail configuration (section <c>Email</c>). Mail is enabled when <see cref="SmtpOptions.Host"/> is set;
/// without a host every flow behaves as it did before mail existed.
/// </summary>
/// <remarks>
/// Same shape and names as SimpleDeckApp's options on purpose, extended with the settings this CMS
/// needs (allowlist of sender addresses, brand, timeout). Credentials come from the environment
/// (<c>Email__Smtp__Username</c>, <c>Email__Smtp__Password</c>), never from a committed file.
/// </remarks>
public sealed class EmailOptions
{
public const string SectionName = "Email";
/// <summary>Default sender address when the site settings hold none.</summary>
public string FromAddress { get; set; } = "";
/// <summary>Default sender display name; also used as the site name inside the mail.</summary>
public string FromName { get; set; } = "";
/// <summary>
/// Sender addresses a site may choose in its settings. Mandatory: a free address could send as a
/// domain the SMTP account is not authorised for (SPF/DKIM mismatch, spoofing). Empty means only
/// <see cref="FromAddress"/> is allowed.
/// </summary>
public string[] AllowedFromAddresses { get; set; } = [];
/// <summary>Optional logo for the mail header, absolute or relative to <c>App:PublicBaseUrl</c>.</summary>
public string LogoUrl { get; set; } = "";
/// <summary>Optional brand colour, <c>#rrggbb</c>.</summary>
public string BrandColor { get; set; } = "";
public SmtpOptions Smtp { get; set; } = new();
[ExcludeFromCodeCoverage]
public override string ToString() => $"Email(From={FromAddress}, Host={Smtp.Host})"; // never the credentials
}
public sealed class SmtpOptions
{
public string Host { get; set; } = "";
public int Port { get; set; } = 587;
public bool EnableSsl { get; set; } = true;
public string Username { get; set; } = "";
public string Password { get; set; } = "";
/// <summary>Connect and send are bounded by this, because mail is sent inside the request.</summary>
public int TimeoutSeconds { get; set; } = 10;
}
/// <summary>Site-level settings around mail (section <c>App</c>).</summary>
public sealed class AppMailOptions
{
public const string SectionName = "App";
/// <summary>Public https address of the site, used to build links in mails (for example https://test.andreaslop.nl).</summary>
public string PublicBaseUrl { get; set; } = "";
/// <summary>Default language of the site for mails: nl or en.</summary>
public string DefaultLanguage { get; set; } = "nl";
}
@@ -0,0 +1,63 @@
using Microsoft.Extensions.Options;
namespace SlpModularCms.Core.Email;
/// <summary>
/// Start-up validation of the mail configuration. Only runs checks when mail is enabled (an SMTP host
/// is set); a host without mail configuration starts exactly as before. Messages never contain the
/// credentials.
/// </summary>
public sealed class EmailOptionsValidator(IOptions<AppMailOptions> app) : IValidateOptions<EmailOptions>
{
public ValidateOptionsResult Validate(string? name, EmailOptions options)
{
if (string.IsNullOrWhiteSpace(options.Smtp.Host))
return ValidateOptionsResult.Success; // mail disabled
var failures = new List<string>();
if (!EmailAddressRules.IsValidAddress(options.FromAddress))
failures.Add("Email:FromAddress must be a valid e-mail address.");
if (!EmailAddressRules.IsValidDisplayName(options.FromName))
failures.Add($"Email:FromName is required (1..{EmailAddressRules.MaxDisplayNameLength} characters, no control characters).");
if (options.Smtp.Port is < 1 or > 65535)
failures.Add("Email:Smtp:Port must be between 1 and 65535.");
if (options.Smtp.TimeoutSeconds is < 1 or > 60)
failures.Add("Email:Smtp:TimeoutSeconds must be between 1 and 60.");
if (!string.IsNullOrEmpty(options.Smtp.Username) && string.IsNullOrEmpty(options.Smtp.Password))
failures.Add("Email:Smtp:Password is required when Email:Smtp:Username is set.");
if (!string.IsNullOrEmpty(options.BrandColor) && !EmailAddressRules.IsValidColour(options.BrandColor))
failures.Add("Email:BrandColor must look like #rrggbb.");
foreach (var allowed in options.AllowedFromAddresses)
{
if (!EmailAddressRules.IsValidAddress(allowed))
failures.Add("Email:AllowedFromAddresses contains an invalid e-mail address.");
}
var baseUrl = app.Value.PublicBaseUrl;
if (!IsValidPublicBaseUrl(baseUrl))
failures.Add("App:PublicBaseUrl must be an absolute https URL (http only for localhost) without a path.");
if (!MailLanguages.IsSupported(app.Value.DefaultLanguage))
failures.Add("App:DefaultLanguage must be 'nl' or 'en'.");
if (!string.IsNullOrEmpty(options.LogoUrl) && !IsValidLogoUrl(options.LogoUrl))
failures.Add("Email:LogoUrl must be an https URL or a path starting with '/'.");
return failures.Count == 0 ? ValidateOptionsResult.Success : ValidateOptionsResult.Fail(failures);
}
public static bool IsValidPublicBaseUrl(string? value)
{
if (string.IsNullOrWhiteSpace(value) || !Uri.TryCreate(value, UriKind.Absolute, out var uri)) return false;
var local = uri.IsLoopback;
if (uri.Scheme != Uri.UriSchemeHttps && !(local && uri.Scheme == Uri.UriSchemeHttp)) return false;
return (uri.AbsolutePath == "/" || uri.AbsolutePath == "") && string.IsNullOrEmpty(uri.Query) && string.IsNullOrEmpty(uri.Fragment)
&& string.IsNullOrEmpty(uri.UserInfo);
}
private static bool IsValidLogoUrl(string value)
{
if (value.StartsWith('/') && !value.StartsWith("//") && !value.Any(char.IsControl)) return true;
return Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps;
}
}
@@ -0,0 +1,37 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.SiteSettings;
namespace SlpModularCms.Core.Email;
public static class EmailServiceCollectionExtensions
{
/// <summary>
/// Registers the mail building blocks. Mail is on when <c>Email:Smtp:Host</c> is set; otherwise a
/// <see cref="NullEmailSender"/> is registered and every flow behaves as before mail existed.
/// The options are validated at start-up (only when mail is on).
/// </summary>
public static IServiceCollection AddCmsEmail(this IServiceCollection services, IConfiguration configuration)
{
services.AddOptions<AppMailOptions>().Bind(configuration.GetSection(AppMailOptions.SectionName));
services.AddOptions<EmailOptions>().Bind(configuration.GetSection(EmailOptions.SectionName)).ValidateOnStart();
services.AddSingleton<IValidateOptions<EmailOptions>, EmailOptionsValidator>();
var enabled = !string.IsNullOrWhiteSpace(configuration[$"{EmailOptions.SectionName}:Smtp:Host"]);
if (enabled)
services.TryAddSingleton<IEmailSender, SmtpEmailSender>();
else
services.TryAddSingleton<IEmailSender, NullEmailSender>();
services.TryAddSingleton<IMailTemplateRenderer, MailTemplateRenderer>();
services.TryAddSingleton<ILanguageResolver, LanguageResolver>();
services.TryAddScoped<ISiteSettingsService, SiteSettingsService>();
return services;
}
/// <summary>True when an SMTP host is configured.</summary>
public static bool IsEmailEnabled(this IConfiguration configuration) =>
!string.IsNullOrWhiteSpace(configuration[$"{EmailOptions.SectionName}:Smtp:Host"]);
}
@@ -0,0 +1,26 @@
namespace SlpModularCms.Core.Email;
/// <summary>
/// Sends one mail. Same name and first four parameters as SimpleDeckApp's <c>IEmailSender.SendAsync</c>
/// (see the extension below); differs on purpose in that it returns a <see cref="MailSendResult"/>
/// instead of throwing, because in this CMS a mail failure must never fail the action that triggered it.
/// </summary>
public interface IEmailSender
{
Task<MailSendResult> SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default);
}
public static class EmailSenderExtensions
{
/// <summary>SimpleDeckApp-shaped call: to, subject, html body.</summary>
public static Task<MailSendResult> SendAsync(
this IEmailSender sender, string toAddress, string subject, string htmlBody, CancellationToken cancellationToken = default) =>
sender.SendAsync(new OutgoingMail(toAddress, subject, htmlBody), cancellationToken);
}
/// <summary>Registered when no SMTP host is configured: reports "disabled" so callers never null-check.</summary>
public sealed class NullEmailSender : IEmailSender
{
public Task<MailSendResult> SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default) =>
Task.FromResult(MailSendResult.Fail(MailSendResult.Disabled));
}
@@ -0,0 +1,201 @@
using System.Net;
using System.Text;
using Microsoft.Extensions.Options;
namespace SlpModularCms.Core.Email;
public interface IMailTemplateRenderer
{
RenderedMail Render(MailKind kind, string language, MailModel model);
}
public interface ILanguageResolver
{
/// <summary>The user's language if supported, else the site default, else Dutch.</summary>
string Resolve(string? preferredLanguage);
}
public sealed class LanguageResolver(IOptions<AppMailOptions> options) : ILanguageResolver
{
public string Resolve(string? preferredLanguage) =>
MailLanguages.Normalize(preferredLanguage)
?? MailLanguages.Normalize(options.Value.DefaultLanguage)
?? MailLanguages.Dutch;
}
/// <summary>
/// One shared layout, texts per language kept in code. Every dynamic value is HTML-encoded for the
/// HTML part; the subject and plain-text part carry the raw values (no markup there). A missing
/// language or key falls back to Dutch. Table layout and inline CSS only, so it renders in mail clients.
/// </summary>
public sealed class MailTemplateRenderer : IMailTemplateRenderer
{
private const string DefaultColour = "#1f2937";
private sealed record Texts(
string Subject, string Heading, string Intro, string? Button, string? Note, string Footer);
// {0} = site name, {1} = role, {2} = minutes/hours text. Keys: kind, then language.
private static readonly Dictionary<MailKind, Dictionary<string, Texts>> Catalog = new()
{
[MailKind.Invitation] = new()
{
["nl"] = new("Uitnodiging voor {0}", "Je bent uitgenodigd",
"Je bent uitgenodigd om een account aan te maken voor {0}. Kies met de knop hieronder je wachtwoord om je account te activeren.",
"Account activeren", "Deze link is {2} geldig. Is hij verlopen, vraag dan de beheerder om een nieuwe uitnodiging.",
"Deze mail is automatisch verstuurd door {0}."),
["en"] = new("Invitation to {0}", "You have been invited",
"You have been invited to create an account for {0}. Use the button below to choose your password and activate your account.",
"Activate account", "This link is valid for {2}. If it has expired, ask the administrator for a new invitation.",
"This message was sent automatically by {0}.")
},
[MailKind.NewInvitationLink] = new()
{
["nl"] = new("Nieuwe uitnodigingslink voor {0}", "Je hebt een nieuwe uitnodigingslink",
"Er is een nieuwe uitnodigingslink voor je aangemaakt voor {0}. De vorige link werkt niet meer.",
"Account activeren", "Deze link is {2} geldig.",
"Deze mail is automatisch verstuurd door {0}."),
["en"] = new("New invitation link for {0}", "You have a new invitation link",
"A new invitation link has been created for you for {0}. The previous link no longer works.",
"Activate account", "This link is valid for {2}.",
"This message was sent automatically by {0}.")
},
[MailKind.PasswordReset] = new()
{
["nl"] = new("Wachtwoord opnieuw instellen voor {0}", "Wachtwoord opnieuw instellen",
"Er is gevraagd om het wachtwoord van je account bij {0} opnieuw in te stellen. Gebruik de knop hieronder om een nieuw wachtwoord te kiezen.",
"Nieuw wachtwoord kiezen", "Deze link is {2} geldig en werkt één keer. Heb jij dit niet gevraagd? Negeer deze mail dan: je wachtwoord blijft ongewijzigd.",
"Deze mail is automatisch verstuurd door {0}."),
["en"] = new("Reset your password for {0}", "Reset your password",
"A request was made to reset the password of your account at {0}. Use the button below to choose a new password.",
"Choose a new password", "This link is valid for {2} and works once. Did you not ask for this? Ignore this message: your password stays unchanged.",
"This message was sent automatically by {0}.")
},
[MailKind.AccountDeactivated] = new()
{
["nl"] = new("Je account bij {0} is gedeactiveerd", "Account gedeactiveerd",
"Een beheerder heeft je account bij {0} gedeactiveerd. Je kunt niet meer inloggen.",
null, "Denk je dat dit niet klopt? Neem dan contact op met de beheerder.",
"Deze mail is automatisch verstuurd door {0}."),
["en"] = new("Your account at {0} has been deactivated", "Account deactivated",
"An administrator has deactivated your account at {0}. You can no longer sign in.",
null, "Think this is a mistake? Please contact the administrator.",
"This message was sent automatically by {0}.")
},
[MailKind.AccountReactivated] = new()
{
["nl"] = new("Je account bij {0} is weer actief", "Account weer actief",
"Een beheerder heeft je account bij {0} weer geactiveerd. Je kunt weer inloggen.",
"Inloggen", null, "Deze mail is automatisch verstuurd door {0}."),
["en"] = new("Your account at {0} is active again", "Account active again",
"An administrator has reactivated your account at {0}. You can sign in again.",
"Sign in", null, "This message was sent automatically by {0}.")
},
[MailKind.RoleChanged] = new()
{
["nl"] = new("Je rol bij {0} is gewijzigd", "Rol gewijzigd",
"Een beheerder heeft je rol bij {0} gewijzigd naar: {1}.",
null, "Denk je dat dit niet klopt? Neem dan contact op met de beheerder.",
"Deze mail is automatisch verstuurd door {0}."),
["en"] = new("Your role at {0} has changed", "Role changed",
"An administrator has changed your role at {0} to: {1}.",
null, "Think this is a mistake? Please contact the administrator.",
"This message was sent automatically by {0}.")
}
};
private static readonly Dictionary<string, Dictionary<string, string>> Roles = new()
{
["nl"] = new() { ["Owner"] = "Eigenaar", ["Administrator"] = "Beheerder", ["User"] = "Gebruiker" },
["en"] = new() { ["Owner"] = "Owner", ["Administrator"] = "Administrator", ["User"] = "User" }
};
public RenderedMail Render(MailKind kind, string language, MailModel model)
{
var lang = MailLanguages.Normalize(language) ?? MailLanguages.Dutch;
var perKind = Catalog[kind];
var t = perKind.TryGetValue(lang, out var found) ? found : perKind[MailLanguages.Dutch];
var site = Plain(model.SiteName);
var role = RoleName(lang, model.Detail);
var validity = Validity(lang, model.ValidForMinutes);
string F(string template) => string.Format(template, site, role, validity);
var subject = Plain(F(t.Subject));
var heading = F(t.Heading);
var intro = F(t.Intro);
var note = t.Note is null ? null : F(t.Note);
var footer = F(t.Footer);
var greeting = string.IsNullOrWhiteSpace(model.RecipientName)
? null
: (lang == "en" ? $"Hello {model.RecipientName.Trim()}," : $"Hallo {model.RecipientName.Trim()},");
var colour = EmailAddressRules.IsValidColour(model.BrandColor) ? model.BrandColor! : DefaultColour;
var hasAction = t.Button is not null && !string.IsNullOrEmpty(model.ActionUrl);
return new RenderedMail(subject, BuildHtml(model, site, colour, greeting, heading, intro, hasAction ? t.Button : null, note, footer),
BuildText(greeting, heading, intro, hasAction ? model.ActionUrl : null, note, footer));
}
private static string RoleName(string lang, string? key) =>
key is not null && Roles[lang].TryGetValue(key, out var name) ? name : (key ?? "");
private static string Validity(string lang, int? minutes)
{
if (minutes is null) return "";
var m = minutes.Value;
if (m % 60 == 0)
{
var h = m / 60;
return lang == "en" ? $"{h} hour{(h == 1 ? "" : "s")}" : $"{h} uur";
}
return lang == "en" ? $"{m} minutes" : $"{m} minuten";
}
/// <summary>For the subject and text: no markup, and no line breaks (a subject is a header).</summary>
private static string Plain(string value) => new(value.Where(c => !char.IsControl(c)).ToArray());
private static string E(string value) => WebUtility.HtmlEncode(value);
private static string BuildHtml(
MailModel model, string site, string colour, string? greeting, string heading, string intro,
string? button, string? note, string footer)
{
var sb = new StringBuilder();
sb.Append("<!DOCTYPE html><html><body style=\"margin:0;padding:0;background:#f3f4f6;\">");
sb.Append("<table role=\"presentation\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#f3f4f6;padding:24px 0;\"><tr><td align=\"center\">");
sb.Append("<table role=\"presentation\" width=\"560\" cellpadding=\"0\" cellspacing=\"0\" style=\"max-width:560px;width:100%;background:#ffffff;border-radius:8px;font-family:Arial,Helvetica,sans-serif;color:#111827;\">");
sb.Append($"<tr><td style=\"padding:24px 32px;border-bottom:3px solid {colour};\">");
if (!string.IsNullOrEmpty(model.LogoUrl))
sb.Append($"<img src=\"{E(model.LogoUrl)}\" alt=\"{E(site)}\" height=\"48\" style=\"display:block;height:48px;width:auto;border:0;\">");
else
sb.Append($"<span style=\"font-size:20px;font-weight:bold;color:{colour};\">{E(site)}</span>");
sb.Append("</td></tr><tr><td style=\"padding:32px;font-size:15px;line-height:1.5;\">");
sb.Append($"<h1 style=\"margin:0 0 16px 0;font-size:22px;color:{colour};\">{E(heading)}</h1>");
if (greeting is not null) sb.Append($"<p style=\"margin:0 0 12px 0;\">{E(greeting)}</p>");
sb.Append($"<p style=\"margin:0 0 24px 0;\">{E(intro)}</p>");
if (button is not null && !string.IsNullOrEmpty(model.ActionUrl))
{
sb.Append($"<p style=\"margin:0 0 24px 0;\"><a href=\"{E(model.ActionUrl)}\" style=\"display:inline-block;background:{colour};color:#ffffff;text-decoration:none;padding:12px 24px;border-radius:6px;font-weight:bold;\">{E(button)}</a></p>");
sb.Append($"<p style=\"margin:0 0 24px 0;font-size:13px;color:#4b5563;word-break:break-all;\">{E(model.ActionUrl)}</p>");
}
if (note is not null) sb.Append($"<p style=\"margin:0 0 24px 0;font-size:13px;color:#4b5563;\">{E(note)}</p>");
sb.Append("</td></tr>");
sb.Append($"<tr><td style=\"padding:16px 32px;font-size:12px;color:#6b7280;border-top:1px solid #e5e7eb;\">{E(footer)}</td></tr>");
sb.Append("</table></td></tr></table></body></html>");
return sb.ToString();
}
private static string BuildText(string? greeting, string heading, string intro, string? url, string? note, string footer)
{
var sb = new StringBuilder();
sb.AppendLine(heading).AppendLine();
if (greeting is not null) sb.AppendLine(greeting).AppendLine();
sb.AppendLine(intro).AppendLine();
if (url is not null) sb.AppendLine(url).AppendLine();
if (note is not null) sb.AppendLine(note).AppendLine();
sb.AppendLine("--").AppendLine(footer);
return sb.ToString();
}
}
+63
View File
@@ -0,0 +1,63 @@
namespace SlpModularCms.Core.Email;
/// <summary>Outcome of one send. Sending never throws into the caller: a failure is a value.</summary>
public readonly record struct MailSendResult(bool Sent, string? ErrorCode)
{
public const string Disabled = "disabled";
public const string NotConfigured = "not_configured";
public const string Timeout = "timeout";
public const string AuthFailed = "auth_failed";
public const string Rejected = "rejected";
public const string Unknown = "unknown";
public static MailSendResult Ok { get; } = new(true, null);
public static MailSendResult Fail(string code) => new(false, code);
}
/// <summary>One message to send. <see cref="FromAddress"/>/<see cref="FromName"/> null means the configured defaults.</summary>
public sealed record OutgoingMail(
string ToAddress,
string Subject,
string HtmlBody,
string? TextBody = null,
string? FromAddress = null,
string? FromName = null);
public enum MailKind
{
Invitation,
NewInvitationLink,
PasswordReset,
AccountDeactivated,
AccountReactivated,
RoleChanged
}
/// <summary>Values the template needs. <see cref="Detail"/> carries the role key for <see cref="MailKind.RoleChanged"/>.</summary>
public sealed record MailModel(
string SiteName,
string? RecipientName = null,
string? ActionUrl = null,
int? ValidForMinutes = null,
string? Detail = null,
string? LogoUrl = null,
string? BrandColor = null);
public sealed record RenderedMail(string Subject, string Html, string Text);
public static class MailLanguages
{
public const string Dutch = "nl";
public const string English = "en";
public static bool IsSupported(string? value) => Normalize(value) is not null;
/// <summary>Returns "nl" or "en" for a supported value (case-insensitive, region tags allowed), otherwise null.</summary>
public static string? Normalize(string? value)
{
var v = value?.Trim().ToLowerInvariant();
if (string.IsNullOrEmpty(v)) return null;
var primary = v.Split('-', '_')[0];
return primary is Dutch or English ? primary : null;
}
}
@@ -0,0 +1,82 @@
using MailKit;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MimeKit;
namespace SlpModularCms.Core.Email;
/// <summary>
/// MailKit/MimeKit sender, following SimpleDeckApp: StartTls when <c>EnableSsl</c>, authenticate only
/// when a username is configured. Every failure is caught here and mapped to a short error code; the
/// exception text is never logged or returned because it can quote addresses.
/// </summary>
public sealed class SmtpEmailSender(IOptions<EmailOptions> options, ILogger<SmtpEmailSender> logger) : IEmailSender
{
private readonly EmailOptions _options = options.Value;
public async Task<MailSendResult> SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(_options.Smtp.Host))
return MailSendResult.Fail(MailSendResult.NotConfigured);
var fromAddress = mail.FromAddress ?? _options.FromAddress;
var fromName = mail.FromName ?? _options.FromName;
// Everything that becomes a header is checked first: a bad value is refused, never sent.
if (!EmailAddressRules.IsValidAddress(mail.ToAddress)
|| !EmailAddressRules.IsValidAddress(fromAddress)
|| EmailAddressRules.ContainsControlCharacters(mail.Subject)
|| EmailAddressRules.ContainsControlCharacters(fromName))
{
logger.LogWarning("identity_mail_failed code={Code} reason=invalid_header", MailSendResult.Rejected);
return MailSendResult.Fail(MailSendResult.Rejected);
}
var message = new MimeMessage();
message.From.Add(new MailboxAddress(fromName, fromAddress));
message.To.Add(MailboxAddress.Parse(mail.ToAddress));
message.Subject = mail.Subject;
message.Body = new BodyBuilder { HtmlBody = mail.HtmlBody, TextBody = mail.TextBody }.ToMessageBody();
var timeout = TimeSpan.FromSeconds(_options.Smtp.TimeoutSeconds);
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutSource.CancelAfter(timeout);
try
{
using var client = new SmtpClient { Timeout = (int)timeout.TotalMilliseconds };
await client.ConnectAsync(
_options.Smtp.Host,
_options.Smtp.Port,
_options.Smtp.EnableSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.None,
timeoutSource.Token);
if (!string.IsNullOrEmpty(_options.Smtp.Username))
await client.AuthenticateAsync(_options.Smtp.Username, _options.Smtp.Password, timeoutSource.Token);
await client.SendAsync(message, timeoutSource.Token);
await client.DisconnectAsync(true, timeoutSource.Token);
return MailSendResult.Ok;
}
catch (Exception ex)
{
var code = Map(ex, cancellationToken);
// The exception TYPE only: its message may contain the recipient or server replies.
logger.LogWarning("identity_mail_failed code={Code} exception={ExceptionType}", code, ex.GetType().Name);
return MailSendResult.Fail(code);
}
}
private static string Map(Exception ex, CancellationToken callerToken) => ex switch
{
OperationCanceledException when !callerToken.IsCancellationRequested => MailSendResult.Timeout,
TimeoutException => MailSendResult.Timeout,
OperationCanceledException => MailSendResult.Unknown,
AuthenticationException => MailSendResult.AuthFailed,
SmtpCommandException or SmtpProtocolException or SslHandshakeException => MailSendResult.Rejected,
ServiceNotConnectedException or ServiceNotAuthenticatedException => MailSendResult.Rejected,
_ => MailSendResult.Unknown
};
}
@@ -13,6 +13,7 @@ using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using SlpModularCms.Core.Availability;
using SlpModularCms.Core.Data;
using SlpModularCms.Core.Email;
using SlpModularCms.Core.Exceptions;
using SlpModularCms.Core.Hosting.Proxy;
using SlpModularCms.Core.Hosting.Security;
@@ -66,6 +67,8 @@ public static class ServiceCollectionExtensions
$"{InvitationSettings.SectionName}:ExpiryHours must be between 1 and {InvitationSettings.MaxExpiryHours}.")
.ValidateOnStart();
services.AddCmsEmail(configuration);
services.AddScoped<IAuthService, AuthService>();
services.AddScoped<IInvitationService, InvitationService>();
services.AddScoped<ISetupService, SetupService>();
@@ -1,4 +1,6 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Email;
namespace SlpModularCms.Core.Hosting;
@@ -12,15 +14,26 @@ namespace SlpModularCms.Core.Hosting;
public class SystemController : ControllerBase
{
private readonly ModuleOrchestrator _orchestrator;
private readonly IOptions<EmailOptions> _email;
private readonly IOptions<AppMailOptions> _app;
public SystemController(ModuleOrchestrator orchestrator)
public SystemController(ModuleOrchestrator orchestrator, IOptions<EmailOptions> email, IOptions<AppMailOptions> app)
{
_orchestrator = orchestrator;
_email = email;
_app = app;
}
[HttpGet("capabilities")]
public IActionResult GetCapabilities()
{
return Ok(new { Modules = _orchestrator.ModuleNames });
// EmailEnabled tells the UI whether mail actions exist on this site; DefaultLanguage is the
// site's mail language fallback. Neither exposes configuration values beyond that.
return Ok(new
{
Modules = _orchestrator.ModuleNames,
EmailEnabled = !string.IsNullOrWhiteSpace(_email.Value.Smtp.Host),
DefaultLanguage = MailLanguages.Normalize(_app.Value.DefaultLanguage) ?? MailLanguages.Dutch
});
}
}
@@ -0,0 +1,466 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SlpModularCms.Core.Data;
#nullable disable
namespace SlpModularCms.Core.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20261108170420_AddSiteSettings")]
partial class AddSiteSettings
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("FriendlyName")
.HasColumnType("longtext");
b.Property<string>("Xml")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("DataProtectionKeys");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<Guid>("RoleId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("RoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext");
b.Property<string>("ClaimValue")
.HasColumnType("longtext");
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("UserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderKey")
.HasColumnType("varchar(255)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("longtext");
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("UserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.Property<Guid>("RoleId")
.HasColumnType("char(36)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("UserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255)");
b.Property<string>("Name")
.HasColumnType("varchar(255)");
b.Property<string>("Value")
.HasColumnType("longtext");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("UserTokens", (string)null);
});
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ApplicationRole", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ApplicationUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<string>("DisplayName")
.HasColumnType("longtext");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("tinyint(1)");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetime");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("PasswordHash")
.HasColumnType("longtext");
b.Property<string>("PhoneNumber")
.HasColumnType("longtext");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("tinyint(1)");
b.Property<string>("SecurityStamp")
.HasColumnType("longtext");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.GlobalAvailabilityState", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("LastUpdatedAt")
.HasColumnType("datetime");
b.Property<string>("Message")
.HasColumnType("longtext");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<string>("UpdatedBy")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("AvailabilityState", (string)null);
});
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.Invitation", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<DateTimeOffset>("ExpiryDate")
.HasColumnType("datetime");
b.Property<bool>("IsAccepted")
.HasColumnType("tinyint(1)");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Token")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("Token")
.IsUnique();
b.ToTable("Invitations");
});
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ModulePermission", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.Property<string>("ModuleName")
.HasMaxLength(128)
.HasColumnType("varchar(128)");
b.Property<string>("Permission")
.HasMaxLength(128)
.HasColumnType("varchar(128)");
b.HasKey("UserId", "ModuleName", "Permission");
b.ToTable("ModulePermissions");
});
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<string>("CreatedByIp")
.HasColumnType("longtext");
b.Property<DateTimeOffset>("ExpiryDate")
.HasColumnType("datetime");
b.Property<bool>("IsRevoked")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsUsed")
.HasColumnType("tinyint(1)");
b.Property<string>("Token")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<Guid>("UserId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.HasIndex("Token")
.IsUnique();
b.HasIndex("UserId");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SlpModularCms.Core.SiteSettings.SiteSettingsEntity", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<string>("MailFromAddress")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("MailFromName")
.HasMaxLength(80)
.HasColumnType("varchar(80)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.Property<string>("UpdatedBy")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.ToTable("SiteSettings", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ModulePermission", b =>
{
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", "User")
.WithMany("ModulePermissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.RefreshToken", b =>
{
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationUser", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SlpModularCms.Core.Identity.Entities.ApplicationUser", b =>
{
b.Navigation("ModulePermissions");
b.Navigation("RefreshTokens");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,38 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Core.Migrations
{
/// <inheritdoc />
public partial class AddSiteSettings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "SiteSettings",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false),
MailFromAddress = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true),
MailFromName = table.Column<string>(type: "varchar(80)", maxLength: 80, nullable: true),
UpdatedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
UpdatedBy = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_SiteSettings", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "SiteSettings");
}
}
}
@@ -353,6 +353,31 @@ namespace SlpModularCms.Core.Migrations
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SlpModularCms.Core.SiteSettings.SiteSettingsEntity", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<string>("MailFromAddress")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<string>("MailFromName")
.HasMaxLength(80)
.HasColumnType("varchar(80)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("datetime");
b.Property<string>("UpdatedBy")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.ToTable("SiteSettings", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.HasOne("SlpModularCms.Core.Identity.Entities.ApplicationRole", null)
@@ -0,0 +1,19 @@
using System.Diagnostics.CodeAnalysis;
namespace SlpModularCms.Core.SiteSettings;
/// <summary>
/// Per-site settings, one row (Id is always 1). Only mail settings for now; the planned brand/site-name
/// settings would live here too. A null column means "use the configured default".
/// </summary>
[ExcludeFromCodeCoverage]
public class SiteSettingsEntity
{
public const int SingletonId = 1;
public int Id { get; set; } = SingletonId;
public string? MailFromAddress { get; set; }
public string? MailFromName { get; set; }
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
public string? UpdatedBy { get; set; }
}
@@ -0,0 +1,107 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Data;
using SlpModularCms.Core.Email;
namespace SlpModularCms.Core.SiteSettings;
public sealed record MailSettingsView(
bool EmailEnabled,
string FromAddress,
string FromName,
string DefaultFromAddress,
string DefaultFromName,
IReadOnlyList<string> AllowedFromAddresses,
bool IsCustomized);
public readonly record struct SetMailResult(bool Ok, string? Error)
{
public const string MailDisabled = "mail_disabled";
public const string InvalidAddress = "invalid_address";
public const string AddressNotAllowed = "address_not_allowed";
public const string InvalidName = "invalid_name";
public static SetMailResult Success { get; } = new(true, null);
public static SetMailResult Fail(string error) => new(false, error);
}
public interface ISiteSettingsService
{
Task<MailSettingsView> GetMailAsync(CancellationToken ct = default);
/// <summary>Sets the sender; both values null (or blank) resets to the configured defaults.</summary>
Task<SetMailResult> SetMailAsync(string? fromAddress, string? fromName, string? actor, CancellationToken ct = default);
/// <summary>The sender a mail is sent with right now: stored values if still allowed, else the defaults.</summary>
Task<(string Address, string Name)> GetEffectiveSenderAsync(CancellationToken ct = default);
}
public sealed class SiteSettingsService(ApplicationDbContext db, IOptions<EmailOptions> options) : ISiteSettingsService
{
private readonly EmailOptions _options = options.Value;
private bool Enabled => !string.IsNullOrWhiteSpace(_options.Smtp.Host);
private IReadOnlyList<string> Allowed() =>
new[] { _options.FromAddress }.Concat(_options.AllowedFromAddresses)
.Where(a => !string.IsNullOrWhiteSpace(a))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
public async Task<MailSettingsView> GetMailAsync(CancellationToken ct = default)
{
var (address, name) = await GetEffectiveSenderAsync(ct);
var row = await db.SiteSettings.AsNoTracking().FirstOrDefaultAsync(s => s.Id == SiteSettingsEntity.SingletonId, ct);
var customized = row is not null && (row.MailFromAddress is not null || row.MailFromName is not null);
return new MailSettingsView(Enabled, address, name, _options.FromAddress, _options.FromName, Allowed(), customized);
}
public async Task<SetMailResult> SetMailAsync(string? fromAddress, string? fromName, string? actor, CancellationToken ct = default)
{
if (!Enabled) return SetMailResult.Fail(SetMailResult.MailDisabled);
var reset = string.IsNullOrWhiteSpace(fromAddress) && string.IsNullOrWhiteSpace(fromName);
string? address = null;
string? name = null;
if (!reset)
{
address = fromAddress?.Trim();
name = fromName?.Trim();
if (!EmailAddressRules.IsValidAddress(address)) return SetMailResult.Fail(SetMailResult.InvalidAddress);
if (!EmailAddressRules.IsAllowedSender(address, _options.FromAddress, _options.AllowedFromAddresses))
return SetMailResult.Fail(SetMailResult.AddressNotAllowed);
if (!EmailAddressRules.IsValidDisplayName(name)) return SetMailResult.Fail(SetMailResult.InvalidName);
}
var row = await db.SiteSettings.FirstOrDefaultAsync(s => s.Id == SiteSettingsEntity.SingletonId, ct);
if (row is null)
{
row = new SiteSettingsEntity();
db.SiteSettings.Add(row);
}
row.MailFromAddress = address;
row.MailFromName = name;
row.UpdatedAt = DateTimeOffset.UtcNow;
row.UpdatedBy = actor;
await db.SaveChangesAsync(ct);
return SetMailResult.Success;
}
public async Task<(string Address, string Name)> GetEffectiveSenderAsync(CancellationToken ct = default)
{
var row = await db.SiteSettings.AsNoTracking().FirstOrDefaultAsync(s => s.Id == SiteSettingsEntity.SingletonId, ct);
// A stored address is re-checked on every use: if the allowlist has since been narrowed, the
// mail falls back to the configured default instead of sending as an address no longer allowed.
var address = row?.MailFromAddress is { } stored
&& EmailAddressRules.IsAllowedSender(stored, _options.FromAddress, _options.AllowedFromAddresses)
? stored
: _options.FromAddress;
var name = row?.MailFromName is { } storedName && EmailAddressRules.IsValidDisplayName(storedName)
? storedName
: _options.FromName;
return (address, name);
}
}
@@ -12,6 +12,7 @@
<ItemGroup>
<PackageReference Include="Asp.Versioning.Mvc" Version="10.0.0" />
<PackageReference Include="MailKit" Version="4.18.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.9" />
<!--
Persists the Data Protection key ring in the database instead of on the filesystem.
@@ -0,0 +1,56 @@
using System.Reflection;
using FluentAssertions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using SlpModularCms.Core.SiteSettings;
using SlpModularCms.Modules.Identity.Controllers;
namespace SlpModularCms.Modules.Identity.Tests.Controllers;
public class SiteSettingsControllerTests
{
private readonly ISiteSettingsService _settings = Substitute.For<ISiteSettingsService>();
private SiteSettingsController Controller() => new(_settings)
{
ControllerContext = new ControllerContext { HttpContext = new Microsoft.AspNetCore.Http.DefaultHttpContext() }
};
private static string PolicyOf(string method) =>
typeof(SiteSettingsController).GetMethod(method)!.GetCustomAttribute<AuthorizeAttribute>()!.Policy!;
[Fact]
public void AnAdministratorReads_OnlyAnOwnerChanges()
{
PolicyOf(nameof(SiteSettingsController.GetMail)).Should().Be("AdminOnly");
PolicyOf(nameof(SiteSettingsController.SetMail)).Should().Be("OwnerOnly");
}
[Fact]
public async Task Set_ReturnsTheNewView_OnSuccess()
{
var view = new MailSettingsView(true, "a@b.nl", "N", "d@b.nl", "D", ["a@b.nl"], true);
_settings.SetMailAsync("a@b.nl", "N", Arg.Any<string?>(), Arg.Any<CancellationToken>()).Returns(SetMailResult.Success);
_settings.GetMailAsync(Arg.Any<CancellationToken>()).Returns(view);
var result = await Controller().SetMail(new UpdateMailSettingsRequest("a@b.nl", "N"), default);
result.Should().BeOfType<OkObjectResult>().Which.Value.Should().Be(view);
}
[Theory]
[InlineData(SetMailResult.InvalidAddress, 400)]
[InlineData(SetMailResult.AddressNotAllowed, 400)]
[InlineData(SetMailResult.InvalidName, 400)]
[InlineData(SetMailResult.MailDisabled, 409)]
public async Task Set_MapsFailuresToStatusCodes(string error, int status)
{
_settings.SetMailAsync(Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(SetMailResult.Fail(error));
var result = await Controller().SetMail(new UpdateMailSettingsRequest("x", "y"), default);
result.Should().BeAssignableTo<ObjectResult>().Which.StatusCode.Should().Be(status);
}
}
@@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SlpModularCms.Core.SiteSettings;
namespace SlpModularCms.Modules.Identity.Controllers;
/// <summary>Per-site settings. Mail: an Administrator reads, only an Owner changes.</summary>
[ApiController]
[Route("[controller]")]
public class SiteSettingsController : ControllerBase
{
private readonly ISiteSettingsService _settings;
public SiteSettingsController(ISiteSettingsService settings)
{
_settings = settings;
}
[HttpGet("mail")]
[Authorize(Policy = "AdminOnly")]
public async Task<IActionResult> GetMail(CancellationToken ct) => Ok(await _settings.GetMailAsync(ct));
[HttpPut("mail")]
[Authorize(Policy = "OwnerOnly")]
public async Task<IActionResult> SetMail([FromBody] UpdateMailSettingsRequest request, CancellationToken ct)
{
var result = await _settings.SetMailAsync(request.FromAddress, request.FromName, User.Identity?.Name, ct);
if (result.Ok) return Ok(await _settings.GetMailAsync(ct));
return result.Error == SetMailResult.MailDisabled
? Conflict(new { code = result.Error, detail = "Mail is not enabled on this site." })
: BadRequest(new { code = result.Error, detail = "The mail settings are not valid." });
}
}
/// <summary>Both values empty (or null) resets the sender to the configured defaults.</summary>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public record UpdateMailSettingsRequest(string? FromAddress, string? FromName);