diff --git a/Directory.Packages.props b/Directory.Packages.props
index f396bbd..7b0a3f4 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -4,6 +4,7 @@
true
+
diff --git a/src/Flypaper.Core/ConnectionGovernor.cs b/src/Flypaper.Core/ConnectionGovernor.cs
index 8820ab5..6e15cdc 100644
--- a/src/Flypaper.Core/ConnectionGovernor.cs
+++ b/src/Flypaper.Core/ConnectionGovernor.cs
@@ -4,7 +4,7 @@ using Microsoft.Extensions.Options;
namespace Flypaper.Core;
-public sealed class ConnectionGovernor(IOptions options) : IConnectionGovernor
+public sealed class ConnectionGovernor(IOptionsMonitor options) : IConnectionGovernor
{
private readonly Lock _gate = new();
private readonly Dictionary _perIp = [];
@@ -24,7 +24,7 @@ public sealed class ConnectionGovernor(IOptions options) : ICon
public bool TryAcquire(TrapSession session, [NotNullWhen(true)] out IDisposable? lease)
{
var ip = Normalize(session.RemoteIp);
- var limits = options.Value;
+ var limits = options.CurrentValue;
lock (_gate)
{
diff --git a/src/Flypaper.Core/RuntimeSettings.cs b/src/Flypaper.Core/RuntimeSettings.cs
new file mode 100644
index 0000000..c32aae1
--- /dev/null
+++ b/src/Flypaper.Core/RuntimeSettings.cs
@@ -0,0 +1,22 @@
+using System.Globalization;
+
+namespace Flypaper.Core;
+
+public sealed record RuntimeSettings(
+ IReadOnlyList TrapPaths,
+ TimeSpan DripInterval,
+ int MaxConnections,
+ int MaxConnectionsPerIp,
+ TimeSpan MaxHoldDuration,
+ IReadOnlyList ExtraKnownHosts)
+{
+ public IReadOnlyDictionary ToConfiguration() => new Dictionary
+ {
+ [SettingKeys.TrapPaths] = SettingsList.Join(TrapPaths),
+ [SettingKeys.DripInterval] = DripInterval.ToString("c", CultureInfo.InvariantCulture),
+ [SettingKeys.MaxConnections] = MaxConnections.ToString(CultureInfo.InvariantCulture),
+ [SettingKeys.MaxConnectionsPerIp] = MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
+ [SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
+ [SettingKeys.ExtraKnownHosts] = SettingsList.Join(ExtraKnownHosts)
+ };
+}
diff --git a/src/Flypaper.Core/RuntimeSettingsInput.cs b/src/Flypaper.Core/RuntimeSettingsInput.cs
new file mode 100644
index 0000000..b9b4e60
--- /dev/null
+++ b/src/Flypaper.Core/RuntimeSettingsInput.cs
@@ -0,0 +1,11 @@
+namespace Flypaper.Core;
+
+public sealed record RuntimeSettingsInput(
+ string? TrapPaths,
+ string? DripInterval,
+ string? MaxConnections,
+ string? MaxConnectionsPerIp,
+ string? MaxHoldDuration,
+ string? ExtraKnownHosts);
+
+public sealed record RuntimeSettingsParseResult(RuntimeSettings? Settings, IReadOnlyDictionary Errors);
diff --git a/src/Flypaper.Core/RuntimeSettingsParser.cs b/src/Flypaper.Core/RuntimeSettingsParser.cs
new file mode 100644
index 0000000..b808720
--- /dev/null
+++ b/src/Flypaper.Core/RuntimeSettingsParser.cs
@@ -0,0 +1,157 @@
+using System.Globalization;
+using System.Text.RegularExpressions;
+
+namespace Flypaper.Core;
+
+public static partial class RuntimeSettingsParser
+{
+ private const int MaxListEntries = 500;
+ private const int MaxPathLength = 256;
+ private const int MaxHostLength = 253;
+ private const int MaxLimit = 100_000;
+
+ private static readonly TimeSpan MinInterval = TimeSpan.FromMilliseconds(100);
+ private static readonly TimeSpan MaxInterval = TimeSpan.FromHours(1);
+ private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1);
+ private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7);
+
+ [GeneratedRegex(@"^(\*\.)?[A-Za-z0-9]([A-Za-z0-9.\-]*[A-Za-z0-9])?$")]
+ private static partial Regex HostPattern();
+
+ public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input)
+ {
+ var errors = new Dictionary();
+
+ var paths = ParseList(input.TrapPaths, nameof(input.TrapPaths), ValidatePath, errors);
+ var hosts = ParseList(input.ExtraKnownHosts, nameof(input.ExtraKnownHosts), ValidateHost, errors);
+ var interval = ParseTimeSpan(input.DripInterval, nameof(input.DripInterval), MinInterval, MaxInterval, errors);
+ var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
+ var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), errors);
+ var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), errors);
+
+ if (maxConnections is { } total && perIp is { } single && single > total
+ && !errors.ContainsKey(nameof(input.MaxConnectionsPerIp)))
+ {
+ errors[nameof(input.MaxConnectionsPerIp)] = "Darf nicht größer sein als die Gesamtzahl der Verbindungen.";
+ }
+
+ if (errors.Count > 0)
+ {
+ return new RuntimeSettingsParseResult(null, errors);
+ }
+
+ var settings = new RuntimeSettings(paths!, interval!.Value, maxConnections!.Value, perIp!.Value, hold!.Value, hosts!);
+ return new RuntimeSettingsParseResult(settings, errors);
+ }
+
+ private static string[]? ParseList(
+ string? raw,
+ string field,
+ Func validate,
+ Dictionary errors)
+ {
+ var lines = (raw ?? string.Empty)
+ .Split(['\r', '\n'], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
+
+ if (lines.Length > MaxListEntries)
+ {
+ errors[field] = $"Höchstens {MaxListEntries} Einträge.";
+ return null;
+ }
+
+ var problems = new List();
+ for (var i = 0; i < lines.Length; i++)
+ {
+ if (validate(lines[i]) is { } problem)
+ {
+ problems.Add($"„{lines[i]}“: {problem}");
+ }
+ }
+
+ if (problems.Count > 0)
+ {
+ errors[field] = string.Join(" ", problems.Take(3)) + (problems.Count > 3 ? $" (+{problems.Count - 3} weitere)" : "");
+ return null;
+ }
+
+ return lines.Distinct(StringComparer.Ordinal).ToArray();
+ }
+
+ private static string? ValidatePath(string path)
+ {
+ if (path[0] != '/')
+ {
+ return "muss mit / beginnen.";
+ }
+
+ if (path.Length > MaxPathLength)
+ {
+ return $"höchstens {MaxPathLength} Zeichen.";
+ }
+
+ if (path.Any(char.IsWhiteSpace))
+ {
+ return "darf keine Leerzeichen enthalten.";
+ }
+
+ var star = path.IndexOf('*');
+ return star >= 0 && star != path.Length - 1 ? "* ist nur am Ende erlaubt." : null;
+ }
+
+ private static string? ValidateHost(string host)
+ {
+ if (host.Length > MaxHostLength)
+ {
+ return $"höchstens {MaxHostLength} Zeichen.";
+ }
+
+ return HostPattern().IsMatch(host) ? null : "ungültiger Hostname (nur Name, ohne Schema, Port oder Pfad; Wildcard als *.beispiel.de).";
+ }
+
+ private static TimeSpan? ParseTimeSpan(
+ string? raw,
+ string field,
+ TimeSpan min,
+ TimeSpan max,
+ Dictionary errors)
+ {
+ var text = raw?.Trim();
+ if (string.IsNullOrEmpty(text))
+ {
+ errors[field] = "Pflichtfeld.";
+ return null;
+ }
+
+ if (!text.Contains(':') || !TimeSpan.TryParse(text, CultureInfo.InvariantCulture, out var value))
+ {
+ errors[field] = "Format hh:mm:ss, zum Beispiel 00:00:10.";
+ return null;
+ }
+
+ if (value < min || value > max)
+ {
+ errors[field] = $"Zwischen {min.ToString("c", CultureInfo.InvariantCulture)} und {max.ToString("c", CultureInfo.InvariantCulture)}.";
+ return null;
+ }
+
+ return value;
+ }
+
+ private static int? ParseInt(string? raw, string field, Dictionary errors)
+ {
+ var text = raw?.Trim();
+ if (string.IsNullOrEmpty(text))
+ {
+ errors[field] = "Pflichtfeld.";
+ return null;
+ }
+
+ if (!int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) || value is < 1 or > MaxLimit)
+ {
+ errors[field] = $"Ganze Zahl zwischen 1 und {MaxLimit}.";
+ return null;
+ }
+
+ return value;
+ }
+}
diff --git a/src/Flypaper.Core/SettingKeys.cs b/src/Flypaper.Core/SettingKeys.cs
new file mode 100644
index 0000000..13c1e05
--- /dev/null
+++ b/src/Flypaper.Core/SettingKeys.cs
@@ -0,0 +1,21 @@
+namespace Flypaper.Core;
+
+public static class SettingKeys
+{
+ public const string MaxConnections = "Flypaper:MaxConnections";
+ public const string MaxConnectionsPerIp = "Flypaper:MaxConnectionsPerIp";
+ public const string MaxHoldDuration = "Flypaper:MaxHoldDuration";
+ public const string DripInterval = "Flypaper:Drip:Interval";
+ public const string TrapPaths = "Flypaper:Http:TrapPathsOverride";
+ public const string ExtraKnownHosts = "Flypaper:Http:ExtraKnownHosts";
+
+ public static readonly IReadOnlySet All = new HashSet(StringComparer.OrdinalIgnoreCase)
+ {
+ MaxConnections,
+ MaxConnectionsPerIp,
+ MaxHoldDuration,
+ DripInterval,
+ TrapPaths,
+ ExtraKnownHosts
+ };
+}
diff --git a/src/Flypaper.Core/SettingsList.cs b/src/Flypaper.Core/SettingsList.cs
new file mode 100644
index 0000000..49f9b01
--- /dev/null
+++ b/src/Flypaper.Core/SettingsList.cs
@@ -0,0 +1,15 @@
+namespace Flypaper.Core;
+
+public static class SettingsList
+{
+ private static readonly char[] Separators = ['\r', '\n'];
+
+ public static string[] Split(string? value) =>
+ value is null
+ ? []
+ : value.Split(Separators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
+ .Distinct(StringComparer.Ordinal)
+ .ToArray();
+
+ public static string Join(IEnumerable items) => string.Join('\n', items);
+}
diff --git a/src/Flypaper.Core/Strategies/DripStrategy.cs b/src/Flypaper.Core/Strategies/DripStrategy.cs
index 3dd650d..46ee530 100644
--- a/src/Flypaper.Core/Strategies/DripStrategy.cs
+++ b/src/Flypaper.Core/Strategies/DripStrategy.cs
@@ -2,7 +2,7 @@ using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
-public sealed class DripStrategy(IOptions options, TimeProvider timeProvider) : ITarpitStrategy
+public sealed class DripStrategy(IOptionsMonitor options, TimeProvider timeProvider) : ITarpitStrategy
{
private static readonly byte[] Alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"u8.ToArray();
@@ -18,7 +18,7 @@ public sealed class DripStrategy(IOptions options, TimeProvider tim
ct.ThrowIfCancellationRequested();
buffer[0] = Alphabet[Random.Shared.Next(Alphabet.Length)];
await channel.WriteAsync(buffer, ct);
- await Task.Delay(options.Value.Interval, timeProvider, ct);
+ await Task.Delay(options.CurrentValue.Interval, timeProvider, ct);
}
}
}
diff --git a/src/Flypaper.Core/TrapRunner.cs b/src/Flypaper.Core/TrapRunner.cs
index 527bbad..0999158 100644
--- a/src/Flypaper.Core/TrapRunner.cs
+++ b/src/Flypaper.Core/TrapRunner.cs
@@ -8,7 +8,7 @@ public sealed partial class TrapRunner(
IConnectionGovernor governor,
IEnumerable strategies,
ITrapEventSink sink,
- IOptions options,
+ IOptionsMonitor options,
TimeProvider timeProvider,
ILogger logger)
{
@@ -27,7 +27,7 @@ public sealed partial class TrapRunner(
}
using var _ = lease;
- using var hold = new CancellationTokenSource(options.Value.MaxHoldDuration, timeProvider);
+ using var hold = new CancellationTokenSource(options.CurrentValue.MaxHoldDuration, timeProvider);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
CountingTrapChannel? channel = null;
diff --git a/src/Flypaper.Http/FlypaperHttpExtensions.cs b/src/Flypaper.Http/FlypaperHttpExtensions.cs
index 0cf5184..e2dda3c 100644
--- a/src/Flypaper.Http/FlypaperHttpExtensions.cs
+++ b/src/Flypaper.Http/FlypaperHttpExtensions.cs
@@ -15,6 +15,15 @@ public static class FlypaperHttpExtensions
public static IServiceCollection AddFlypaperHttp(this IServiceCollection services, IConfiguration configuration)
{
services.Configure(configuration.GetSection(HttpTrapOptions.SectionName));
+ services.PostConfigure(options =>
+ {
+ if (options.TrapPathsOverride is not null)
+ {
+ options.TrapPaths = SettingsList.Split(options.TrapPathsOverride);
+ }
+
+ options.KnownHosts = options.KnownHosts.Concat(SettingsList.Split(options.ExtraKnownHosts)).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
+ });
services.TryAddSingleton();
services.AddOptions()
diff --git a/src/Flypaper.Http/HttpTrapOptions.cs b/src/Flypaper.Http/HttpTrapOptions.cs
index 9f7554b..19f07d2 100644
--- a/src/Flypaper.Http/HttpTrapOptions.cs
+++ b/src/Flypaper.Http/HttpTrapOptions.cs
@@ -9,4 +9,8 @@ public sealed class HttpTrapOptions
public string[] TrapPaths { get; set; } = [];
public string[] TrustedProxies { get; set; } = [];
+
+ public string? TrapPathsOverride { get; set; }
+
+ public string? ExtraKnownHosts { get; set; }
}
diff --git a/src/Flypaper.Http/TrapMatcher.cs b/src/Flypaper.Http/TrapMatcher.cs
index dc95e78..55d78c6 100644
--- a/src/Flypaper.Http/TrapMatcher.cs
+++ b/src/Flypaper.Http/TrapMatcher.cs
@@ -2,58 +2,73 @@ using Microsoft.Extensions.Options;
namespace Flypaper.Http;
-public sealed class TrapMatcher
+public sealed class TrapMatcher : IDisposable
{
- private readonly HashSet _hosts = new(StringComparer.OrdinalIgnoreCase);
- private readonly List _hostSuffixes = [];
- private readonly HashSet _paths = new(StringComparer.OrdinalIgnoreCase);
- private readonly List _pathPrefixes = [];
+ private readonly IDisposable? _subscription;
+ private volatile Snapshot _snapshot;
- public TrapMatcher(IOptions options)
+ public TrapMatcher(IOptionsMonitor options)
{
- foreach (var host in options.Value.KnownHosts)
- {
- if (host.StartsWith("*.", StringComparison.Ordinal))
- {
- _hostSuffixes.Add(host[1..]);
- }
- else
- {
- _hosts.Add(host);
- }
- }
-
- foreach (var path in options.Value.TrapPaths)
- {
- if (path.EndsWith('*'))
- {
- _pathPrefixes.Add(path[..^1]);
- }
- else
- {
- _paths.Add(TrimTrailingSlash(path));
- }
- }
+ _snapshot = new Snapshot(options.CurrentValue);
+ _subscription = options.OnChange(updated => _snapshot = new Snapshot(updated));
}
public TrapMatch Match(string? host, string? path)
{
- if (!IsKnownHost(host))
+ var snapshot = _snapshot;
+ if (!snapshot.IsKnownHost(host))
{
return TrapMatch.UnknownHost;
}
- return IsTrapPath(path ?? "/") ? TrapMatch.TrapPath : TrapMatch.None;
+ return snapshot.IsTrapPath(path ?? "/") ? TrapMatch.TrapPath : TrapMatch.None;
}
- private bool IsKnownHost(string? host) =>
- !string.IsNullOrEmpty(host)
- && (_hosts.Contains(host)
- || _hostSuffixes.Any(suffix => host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)));
+ public void Dispose() => _subscription?.Dispose();
- private bool IsTrapPath(string path) =>
- _paths.Contains(TrimTrailingSlash(path))
- || _pathPrefixes.Any(prefix => path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
+ private sealed class Snapshot
+ {
+ private readonly HashSet _hosts = new(StringComparer.OrdinalIgnoreCase);
+ private readonly List _hostSuffixes = [];
+ private readonly HashSet _paths = new(StringComparer.OrdinalIgnoreCase);
+ private readonly List _pathPrefixes = [];
- private static string TrimTrailingSlash(string path) => path.Length > 1 ? path.TrimEnd('/') : path;
+ public Snapshot(HttpTrapOptions options)
+ {
+ foreach (var host in options.KnownHosts.Where(h => !string.IsNullOrWhiteSpace(h)))
+ {
+ if (host.StartsWith("*.", StringComparison.Ordinal))
+ {
+ _hostSuffixes.Add(host[1..]);
+ }
+ else
+ {
+ _hosts.Add(host);
+ }
+ }
+
+ foreach (var path in options.TrapPaths.Where(p => !string.IsNullOrWhiteSpace(p)))
+ {
+ if (path.EndsWith('*'))
+ {
+ _pathPrefixes.Add(path[..^1]);
+ }
+ else
+ {
+ _paths.Add(TrimTrailingSlash(path));
+ }
+ }
+ }
+
+ public bool IsKnownHost(string? host) =>
+ !string.IsNullOrEmpty(host)
+ && (_hosts.Contains(host)
+ || _hostSuffixes.Any(suffix => host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)));
+
+ public bool IsTrapPath(string path) =>
+ _paths.Contains(TrimTrailingSlash(path))
+ || _pathPrefixes.Any(prefix => path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
+
+ private static string TrimTrailingSlash(string path) => path.Length > 1 ? path.TrimEnd('/') : path;
+ }
}
diff --git a/src/Flypaper.Storage/DbConfigurationProvider.cs b/src/Flypaper.Storage/DbConfigurationProvider.cs
new file mode 100644
index 0000000..73e6c66
--- /dev/null
+++ b/src/Flypaper.Storage/DbConfigurationProvider.cs
@@ -0,0 +1,45 @@
+using Flypaper.Core;
+using Microsoft.Data.Sqlite;
+using Microsoft.Extensions.Configuration;
+
+namespace Flypaper.Storage;
+
+internal sealed class DbConfigurationProvider(string connectionString) : ConfigurationProvider
+{
+ public override void Load() => Data = Read();
+
+ public void Reload()
+ {
+ Load();
+ OnReload();
+ }
+
+ private Dictionary Read()
+ {
+ var data = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ var builder = new SqliteConnectionStringBuilder(connectionString) { Mode = SqliteOpenMode.ReadOnly };
+
+ try
+ {
+ using var connection = new SqliteConnection(builder.ConnectionString);
+ connection.Open();
+ using var command = connection.CreateCommand();
+ command.CommandText = "SELECT \"Key\", \"Value\" FROM \"Settings\"";
+ using var reader = command.ExecuteReader();
+ while (reader.Read())
+ {
+ var key = reader.GetString(0);
+ if (SettingKeys.All.Contains(key))
+ {
+ data[key] = reader.GetString(1);
+ }
+ }
+ }
+ catch (SqliteException)
+ {
+ data.Clear();
+ }
+
+ return data;
+ }
+}
diff --git a/src/Flypaper.Storage/DbConfigurationSource.cs b/src/Flypaper.Storage/DbConfigurationSource.cs
new file mode 100644
index 0000000..c32f821
--- /dev/null
+++ b/src/Flypaper.Storage/DbConfigurationSource.cs
@@ -0,0 +1,13 @@
+using Microsoft.Extensions.Configuration;
+
+namespace Flypaper.Storage;
+
+public sealed class DbConfigurationSource(string connectionString) : IConfigurationSource
+{
+ private DbConfigurationProvider? _provider;
+
+ public IConfigurationProvider Build(IConfigurationBuilder builder) =>
+ _provider = new DbConfigurationProvider(connectionString);
+
+ public void Reload() => _provider?.Reload();
+}
diff --git a/src/Flypaper.Storage/Flypaper.Storage.csproj b/src/Flypaper.Storage/Flypaper.Storage.csproj
index db74d4d..f33373c 100644
--- a/src/Flypaper.Storage/Flypaper.Storage.csproj
+++ b/src/Flypaper.Storage/Flypaper.Storage.csproj
@@ -3,6 +3,7 @@
+
diff --git a/src/Flypaper.Storage/FlypaperDbContext.cs b/src/Flypaper.Storage/FlypaperDbContext.cs
index 9c31a60..8ce402b 100644
--- a/src/Flypaper.Storage/FlypaperDbContext.cs
+++ b/src/Flypaper.Storage/FlypaperDbContext.cs
@@ -8,6 +8,8 @@ public sealed class FlypaperDbContext(DbContextOptions option
public DbSet TrapEvents => Set();
+ public DbSet Settings => Set();
+
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var trapEvent = modelBuilder.Entity();
@@ -19,5 +21,9 @@ public sealed class FlypaperDbContext(DbContextOptions option
trapEvent.Property(e => e.ClientInfo).HasMaxLength(MaxTextLength);
trapEvent.HasIndex(e => e.StartedAt);
trapEvent.HasIndex(e => e.RemoteIp);
+
+ var setting = modelBuilder.Entity();
+ setting.HasKey(e => e.Key);
+ setting.Property(e => e.Key).HasMaxLength(128);
}
}
diff --git a/src/Flypaper.Storage/FlypaperStorageExtensions.cs b/src/Flypaper.Storage/FlypaperStorageExtensions.cs
index ae6f166..a07fb52 100644
--- a/src/Flypaper.Storage/FlypaperStorageExtensions.cs
+++ b/src/Flypaper.Storage/FlypaperStorageExtensions.cs
@@ -1,11 +1,26 @@
using Flypaper.Core;
using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
namespace Flypaper.Storage;
public static class FlypaperStorageExtensions
{
+ public static IHostApplicationBuilder AddFlypaperStorage(this IHostApplicationBuilder builder)
+ {
+ var connectionString = builder.Configuration.GetConnectionString("Flypaper") ?? "Data Source=flypaper.db";
+
+ var source = new DbConfigurationSource(connectionString);
+ builder.Configuration.Add(source);
+ builder.Services.AddSingleton(source);
+ builder.Services.AddSingleton();
+ builder.Services.AddFlypaperStorage(connectionString);
+
+ return builder;
+ }
+
public static IServiceCollection AddFlypaperStorage(this IServiceCollection services, string connectionString)
{
services.AddDbContextFactory(options => options.UseSqlite(connectionString));
@@ -19,7 +34,11 @@ public static class FlypaperStorageExtensions
public static async Task MigrateFlypaperDatabaseAsync(this IServiceProvider services, CancellationToken ct = default)
{
var factory = services.GetRequiredService>();
- await using var db = await factory.CreateDbContextAsync(ct);
- await db.Database.MigrateAsync(ct);
+ await using (var db = await factory.CreateDbContextAsync(ct))
+ {
+ await db.Database.MigrateAsync(ct);
+ }
+
+ services.GetService()?.Reload();
}
}
diff --git a/src/Flypaper.Storage/Migrations/20261114123948_AddSettings.Designer.cs b/src/Flypaper.Storage/Migrations/20261114123948_AddSettings.Designer.cs
new file mode 100644
index 0000000..c625835
--- /dev/null
+++ b/src/Flypaper.Storage/Migrations/20261114123948_AddSettings.Designer.cs
@@ -0,0 +1,98 @@
+//
+using System;
+using Flypaper.Storage;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+#nullable disable
+
+namespace Flypaper.Storage.Migrations
+{
+ [DbContext(typeof(FlypaperDbContext))]
+ [Migration("20261114123948_AddSettings")]
+ partial class AddSettings
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
+
+ modelBuilder.Entity("Flypaper.Storage.SettingEntity", b =>
+ {
+ b.Property("Key")
+ .HasMaxLength(128)
+ .HasColumnType("TEXT");
+
+ b.Property("Value")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Key");
+
+ b.ToTable("Settings");
+ });
+
+ modelBuilder.Entity("Flypaper.Storage.TrapEventEntity", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("BytesSent")
+ .HasColumnType("INTEGER");
+
+ b.Property("ClientInfo")
+ .HasMaxLength(2048)
+ .HasColumnType("TEXT");
+
+ b.Property("DurationMs")
+ .HasColumnType("INTEGER");
+
+ b.Property("EndedAt")
+ .HasColumnType("TEXT");
+
+ b.Property("Outcome")
+ .IsRequired()
+ .HasMaxLength(16)
+ .HasColumnType("TEXT");
+
+ b.Property("Protocol")
+ .IsRequired()
+ .HasMaxLength(16)
+ .HasColumnType("TEXT");
+
+ b.Property("RemoteIp")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("TEXT");
+
+ b.Property("SessionId")
+ .HasColumnType("TEXT");
+
+ b.Property("StartedAt")
+ .HasColumnType("TEXT");
+
+ b.Property("Strategy")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("TEXT");
+
+ b.Property("Target")
+ .HasMaxLength(2048)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("RemoteIp");
+
+ b.HasIndex("StartedAt");
+
+ b.ToTable("TrapEvents");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/src/Flypaper.Storage/Migrations/20261114123948_AddSettings.cs b/src/Flypaper.Storage/Migrations/20261114123948_AddSettings.cs
new file mode 100644
index 0000000..ea5decc
--- /dev/null
+++ b/src/Flypaper.Storage/Migrations/20261114123948_AddSettings.cs
@@ -0,0 +1,33 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace Flypaper.Storage.Migrations
+{
+ ///
+ public partial class AddSettings : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "Settings",
+ columns: table => new
+ {
+ Key = table.Column(type: "TEXT", maxLength: 128, nullable: false),
+ Value = table.Column(type: "TEXT", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_Settings", x => x.Key);
+ });
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "Settings");
+ }
+ }
+}
diff --git a/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs b/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs
index b78260b..87f9535 100644
--- a/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs
+++ b/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs
@@ -17,6 +17,21 @@ namespace Flypaper.Storage.Migrations
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
+ modelBuilder.Entity("Flypaper.Storage.SettingEntity", b =>
+ {
+ b.Property("Key")
+ .HasMaxLength(128)
+ .HasColumnType("TEXT");
+
+ b.Property("Value")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Key");
+
+ b.ToTable("Settings");
+ });
+
modelBuilder.Entity("Flypaper.Storage.TrapEventEntity", b =>
{
b.Property("Id")
diff --git a/src/Flypaper.Storage/RuntimeSettingsStore.cs b/src/Flypaper.Storage/RuntimeSettingsStore.cs
new file mode 100644
index 0000000..1ea23f0
--- /dev/null
+++ b/src/Flypaper.Storage/RuntimeSettingsStore.cs
@@ -0,0 +1,31 @@
+using Flypaper.Core;
+using Microsoft.EntityFrameworkCore;
+
+namespace Flypaper.Storage;
+
+public sealed class RuntimeSettingsStore(IDbContextFactory dbContextFactory, DbConfigurationSource source)
+{
+ public async Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default)
+ {
+ await using var db = await dbContextFactory.CreateDbContextAsync(ct);
+ await using var transaction = await db.Database.BeginTransactionAsync(ct);
+ await db.Settings.ExecuteDeleteAsync(ct);
+ db.Settings.AddRange(settings.ToConfiguration().Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value }));
+ await db.SaveChangesAsync(ct);
+ await transaction.CommitAsync(ct);
+ source.Reload();
+ }
+
+ public async Task ResetAsync(CancellationToken ct = default)
+ {
+ await using var db = await dbContextFactory.CreateDbContextAsync(ct);
+ await db.Settings.ExecuteDeleteAsync(ct);
+ source.Reload();
+ }
+
+ public async Task HasOverridesAsync(CancellationToken ct = default)
+ {
+ await using var db = await dbContextFactory.CreateDbContextAsync(ct);
+ return await db.Settings.AnyAsync(ct);
+ }
+}
diff --git a/src/Flypaper.Storage/SettingEntity.cs b/src/Flypaper.Storage/SettingEntity.cs
new file mode 100644
index 0000000..b4f0f91
--- /dev/null
+++ b/src/Flypaper.Storage/SettingEntity.cs
@@ -0,0 +1,8 @@
+namespace Flypaper.Storage;
+
+public sealed class SettingEntity
+{
+ public required string Key { get; set; }
+
+ public required string Value { get; set; }
+}
diff --git a/src/Flypaper.Web/Auth/AdminAuthenticator.cs b/src/Flypaper.Web/Auth/AdminAuthenticator.cs
new file mode 100644
index 0000000..c0edb8d
--- /dev/null
+++ b/src/Flypaper.Web/Auth/AdminAuthenticator.cs
@@ -0,0 +1,22 @@
+using System.Security.Cryptography;
+using System.Text;
+using Microsoft.Extensions.Options;
+
+namespace Flypaper.Web.Auth;
+
+public sealed class AdminAuthenticator(IOptions options)
+{
+ public bool IsConfigured => !string.IsNullOrEmpty(options.Value.Password);
+
+ public bool Verify(string? candidate)
+ {
+ if (!IsConfigured || string.IsNullOrEmpty(candidate))
+ {
+ return false;
+ }
+
+ return CryptographicOperations.FixedTimeEquals(Hash(candidate), Hash(options.Value.Password!));
+ }
+
+ private static byte[] Hash(string value) => SHA256.HashData(Encoding.UTF8.GetBytes(value));
+}
diff --git a/src/Flypaper.Web/Auth/AdminOptions.cs b/src/Flypaper.Web/Auth/AdminOptions.cs
new file mode 100644
index 0000000..ea2dadb
--- /dev/null
+++ b/src/Flypaper.Web/Auth/AdminOptions.cs
@@ -0,0 +1,8 @@
+namespace Flypaper.Web.Auth;
+
+public sealed class AdminOptions
+{
+ public const string SectionName = "Flypaper:Admin";
+
+ public string? Password { get; set; }
+}
diff --git a/src/Flypaper.Web/Auth/AuthEndpoints.cs b/src/Flypaper.Web/Auth/AuthEndpoints.cs
new file mode 100644
index 0000000..c0b092c
--- /dev/null
+++ b/src/Flypaper.Web/Auth/AuthEndpoints.cs
@@ -0,0 +1,48 @@
+using System.Security.Claims;
+using Microsoft.AspNetCore.Antiforgery;
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Authentication.Cookies;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Flypaper.Web.Auth;
+
+public static class AuthEndpoints
+{
+ public static IEndpointRouteBuilder MapAuthEndpoints(this IEndpointRouteBuilder app)
+ {
+ app.MapPost("/auth/login", async (
+ HttpContext context,
+ AdminAuthenticator admin,
+ [FromForm] string? password,
+ [FromForm] string? returnUrl) =>
+ {
+ var target = IsLocalPath(returnUrl) ? returnUrl! : "/";
+
+ if (!admin.Verify(password))
+ {
+ await Task.Delay(750, context.RequestAborted);
+ return Results.LocalRedirect($"/login?error=1&returnUrl={Uri.EscapeDataString(target)}");
+ }
+
+ var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], CookieAuthenticationDefaults.AuthenticationScheme);
+ await context.SignInAsync(new ClaimsPrincipal(identity));
+ return Results.LocalRedirect(target);
+ }).AllowAnonymous();
+
+ app.MapPost("/auth/logout", async (HttpContext context, IAntiforgery antiforgery) =>
+ {
+ if (!await antiforgery.IsRequestValidAsync(context))
+ {
+ return Results.BadRequest();
+ }
+
+ await context.SignOutAsync();
+ return Results.LocalRedirect("/login");
+ });
+
+ return app;
+ }
+
+ private static bool IsLocalPath(string? url) =>
+ !string.IsNullOrEmpty(url) && url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'));
+}
diff --git a/src/Flypaper.Web/Components/App.razor b/src/Flypaper.Web/Components/App.razor
index bedeb46..8716efd 100644
--- a/src/Flypaper.Web/Components/App.razor
+++ b/src/Flypaper.Web/Components/App.razor
@@ -14,7 +14,6 @@
-