From 2437880013a80d0573ef60105c22a8e6bec67823 Mon Sep 17 00:00:00 2001 From: Tom Date: Sat, 21 Nov 2026 11:46:22 +0100 Subject: [PATCH] Add explanation rules for catches, editable over MCP Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 ++ .../Dashboard/DashboardQueries.cs | 27 ++- .../Dashboard/RecentFilter.cs | 3 +- .../Entities/ExplanationRuleEntity.cs | 31 +++ .../Entities/McpTokenEntity.cs | 2 + .../Explanations/ExplanationLimits.cs | 11 + .../Explanations/ExplanationQueries.cs | 186 +++++++++++++++ .../Explanations/ExplanationRuleStore.cs | 156 ++++++++++++ .../Explanations/ExplanationText.cs | 54 +++++ .../Explanations/ExplanationValidator.cs | 82 +++++++ src/Flypaper.Storage/Explanations/RuleSet.cs | 77 ++++++ src/Flypaper.Storage/FlypaperDbContext.cs | 10 + .../FlypaperStorageExtensions.cs | 3 + ...dExplanationRulesAndTokenWrite.Designer.cs | 201 ++++++++++++++++ ...103849_AddExplanationRulesAndTokenWrite.cs | 54 +++++ .../FlypaperDbContextModelSnapshot.cs | 50 ++++ .../Settings/McpTokenStore.cs | 10 +- .../Components/Layout/MainLayout.razor | 1 + .../Pages/Dashboard/DashboardFilter.cs | 15 +- .../Pages/Dashboard/DashboardPage.razor | 42 +++- .../Pages/Explanations/ExplanationsPage.razor | 89 +++++++ .../Pages/Settings/McpSection.razor | 26 +- .../Pages/Settings/McpTokenModel.cs | 2 + .../Explanations/ExplanationEndpoints.cs | 35 +++ src/Flypaper.Web/Mcp/ExplanationTools.cs | 187 +++++++++++++++ src/Flypaper.Web/Mcp/McpExtensions.cs | 49 +++- src/Flypaper.Web/Mcp/McpResults.cs | 37 +++ .../Mcp/McpTokenAuthenticationHandler.cs | 11 +- src/Flypaper.Web/Mcp/McpTokenService.cs | 15 +- src/Flypaper.Web/Program.cs | 2 + src/Flypaper.Web/wwwroot/app.css | 33 +++ test/Flypaper.Tests/Mcp/McpEndpointTests.cs | 60 ++++- .../Mcp/McpTokenServiceTests.cs | 39 ++- .../Storage/ExplanationRuleTests.cs | 222 ++++++++++++++++++ .../Storage/ExplanationTextTests.cs | 36 +++ .../Storage/RecentCatchesTests.cs | 17 +- .../Web/DashboardFilterTests.cs | 13 + 37 files changed, 1867 insertions(+), 37 deletions(-) create mode 100644 src/Flypaper.Storage/Entities/ExplanationRuleEntity.cs create mode 100644 src/Flypaper.Storage/Explanations/ExplanationLimits.cs create mode 100644 src/Flypaper.Storage/Explanations/ExplanationQueries.cs create mode 100644 src/Flypaper.Storage/Explanations/ExplanationRuleStore.cs create mode 100644 src/Flypaper.Storage/Explanations/ExplanationText.cs create mode 100644 src/Flypaper.Storage/Explanations/ExplanationValidator.cs create mode 100644 src/Flypaper.Storage/Explanations/RuleSet.cs create mode 100644 src/Flypaper.Storage/Migrations/20261121103849_AddExplanationRulesAndTokenWrite.Designer.cs create mode 100644 src/Flypaper.Storage/Migrations/20261121103849_AddExplanationRulesAndTokenWrite.cs create mode 100644 src/Flypaper.Web/Components/Pages/Explanations/ExplanationsPage.razor create mode 100644 src/Flypaper.Web/Explanations/ExplanationEndpoints.cs create mode 100644 src/Flypaper.Web/Mcp/ExplanationTools.cs create mode 100644 test/Flypaper.Tests/Storage/ExplanationRuleTests.cs create mode 100644 test/Flypaper.Tests/Storage/ExplanationTextTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index aeba227..a88e111 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ All notable changes to Flypaper are documented in this file. The format follows ## [Unreleased] +### Added + +- Explanations for catches: rules in the database (kind `Target`, `ClientInfo` or `Outcome`, regular expression, + German plain text, priority, on/off, note, creator) explain what a bot wanted, with which tool and how it ended. + Rules are matched when a catch is displayed, so new rules also apply to old catches; per kind the rule with + the highest priority wins. Patterns run with `NonBacktracking` and a timeout, are validated and length-limited + when saved, and compiled rules are cached until a rule changes. No rules are shipped. +- Dashboard: expanded rows of the catch list show „Was ist passiert?“ (or a muted „Unbekanntes Ziel“), the catch + filter has „Erklärung: Ohne Erklärung“, and the new page „Erklärungen“ lists the rules with pattern, text, + number of matches, on/off switch and delete. +- MCP: read-only tools `list_explanation_rules`, `list_unexplained` and `test_explanation_rule`; tools + `create_explanation_rule`, `update_explanation_rule`, `set_explanation_rule_enabled` and + `delete_explanation_rule` for tokens with write permission. +- MCP tokens: write permission is back (switch on the settings page, database column `CanWrite`, new migration). + Tokens without it neither see nor can call the write tools. The server description mentions the new tools. + ### Changed - Dashboard: the expanded row of the catch list no longer repeats the strategy name, explanation and diff --git a/src/Flypaper.Storage/Dashboard/DashboardQueries.cs b/src/Flypaper.Storage/Dashboard/DashboardQueries.cs index 3567f01..655d95c 100644 --- a/src/Flypaper.Storage/Dashboard/DashboardQueries.cs +++ b/src/Flypaper.Storage/Dashboard/DashboardQueries.cs @@ -1,10 +1,11 @@ using Flypaper.Core.Models; using Flypaper.Storage.Entities; +using Flypaper.Storage.Explanations; using Microsoft.EntityFrameworkCore; namespace Flypaper.Storage.Dashboard; -public sealed class DashboardQueries(IDbContextFactory dbContextFactory, TimeProvider timeProvider) +public sealed class DashboardQueries(IDbContextFactory dbContextFactory, TimeProvider timeProvider, ExplanationRuleStore explanations) { private const int TopCount = 10; @@ -64,12 +65,24 @@ public sealed class DashboardQueries(IDbContextFactory dbCont .Select(g => new CountryOption(g.Key, g.Max(e => e.Country))) .ToListAsync(ct); - return new RecentCatches( - await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id) - .Take(Math.Clamp(filter.Limit, 1, RecentFilter.MaxLimit)) - .ToListAsync(ct), - await events.CountAsync(ct), - countries); + var ordered = events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id); + var take = Math.Clamp(filter.Limit, 1, RecentFilter.MaxLimit); + + if (filter.Unexplained) + { + var rules = await explanations.GetRuleSetAsync(ct); + var candidates = await ordered.Where(e => e.Target != null).Select(e => new { e.Id, e.Target }).ToListAsync(ct); + var ids = candidates + .Where(c => rules.Winner(ExplanationKind.Target, ExplanationText.Path(c.Target)!) is null) + .Select(c => c.Id) + .ToList(); + var page = ids.Take(take).ToList(); + var items = (await db.TrapEvents.AsNoTracking().Where(e => page.Contains(e.Id)).ToListAsync(ct)) + .OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).ToList(); + return new RecentCatches(items, ids.Count, countries); + } + + return new RecentCatches(await ordered.Take(take).ToListAsync(ct), await events.CountAsync(ct), countries); } private IQueryable Apply(IQueryable events, RecentFilter filter) diff --git a/src/Flypaper.Storage/Dashboard/RecentFilter.cs b/src/Flypaper.Storage/Dashboard/RecentFilter.cs index 1489da6..61c7dfa 100644 --- a/src/Flypaper.Storage/Dashboard/RecentFilter.cs +++ b/src/Flypaper.Storage/Dashboard/RecentFilter.cs @@ -13,7 +13,8 @@ public sealed record RecentFilter( StrategyMatch? Strategy = null, string? Search = null, int Limit = RecentFilter.DefaultLimit, - IReadOnlyList? SearchStrategies = null) + IReadOnlyList? SearchStrategies = null, + bool Unexplained = false) { public const int DefaultLimit = 50; public const int MaxLimit = 500; diff --git a/src/Flypaper.Storage/Entities/ExplanationRuleEntity.cs b/src/Flypaper.Storage/Entities/ExplanationRuleEntity.cs new file mode 100644 index 0000000..18b5389 --- /dev/null +++ b/src/Flypaper.Storage/Entities/ExplanationRuleEntity.cs @@ -0,0 +1,31 @@ +namespace Flypaper.Storage.Entities; + +public enum ExplanationKind +{ + Target, + ClientInfo, + Outcome +} + +public sealed class ExplanationRuleEntity +{ + public int Id { get; set; } + + public ExplanationKind Kind { get; set; } + + public required string Pattern { get; set; } + + public required string Text { get; set; } + + public int Priority { get; set; } + + public bool Enabled { get; set; } = true; + + public string? Note { get; set; } + + public DateTime CreatedAt { get; set; } + + public DateTime UpdatedAt { get; set; } + + public required string CreatedBy { get; set; } +} diff --git a/src/Flypaper.Storage/Entities/McpTokenEntity.cs b/src/Flypaper.Storage/Entities/McpTokenEntity.cs index c2143f4..a066945 100644 --- a/src/Flypaper.Storage/Entities/McpTokenEntity.cs +++ b/src/Flypaper.Storage/Entities/McpTokenEntity.cs @@ -11,4 +11,6 @@ public sealed class McpTokenEntity public DateTime CreatedAt { get; set; } public DateTime? LastUsedAt { get; set; } + + public bool CanWrite { get; set; } } diff --git a/src/Flypaper.Storage/Explanations/ExplanationLimits.cs b/src/Flypaper.Storage/Explanations/ExplanationLimits.cs new file mode 100644 index 0000000..14c5101 --- /dev/null +++ b/src/Flypaper.Storage/Explanations/ExplanationLimits.cs @@ -0,0 +1,11 @@ +namespace Flypaper.Storage.Explanations; + +public static class ExplanationLimits +{ + public const int MaxPatternLength = 500; + public const int MaxTextLength = 600; + public const int MaxNoteLength = 500; + public const int MaxCreatedByLength = 100; + public const int MaxPriority = 1000; + public const int MaxRules = 2000; +} diff --git a/src/Flypaper.Storage/Explanations/ExplanationQueries.cs b/src/Flypaper.Storage/Explanations/ExplanationQueries.cs new file mode 100644 index 0000000..b4578b8 --- /dev/null +++ b/src/Flypaper.Storage/Explanations/ExplanationQueries.cs @@ -0,0 +1,186 @@ +using Flypaper.Storage.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Flypaper.Storage.Explanations; + +public enum UnexplainedGrouping +{ + Path, + Pattern +} + +public sealed record ObservedValue(string Value, int Catches, DateTime FirstSeen, DateTime LastSeen, string? ExampleTarget, string? ExampleUserAgent); + +public sealed record UnexplainedGroup(string Key, int Catches, IReadOnlyList ExamplePaths, string? ExampleUserAgent, DateTime FirstSeen, DateTime LastSeen); + +public sealed record UnexplainedResult(int Catches, int DistinctPaths, IReadOnlyList Groups, int GroupsOmitted); + +public sealed record RuleTakeover(ExplanationRuleEntity Rule, int Catches, IReadOnlyList Examples); + +public sealed record RuleTestResult( + int Catches, + int DistinctValues, + IReadOnlyList<(string Value, int Catches)> Examples, + int NewlyExplained, + IReadOnlyList TakesOver, + int Lost, + IReadOnlyList LostExamples); + +public sealed class ExplanationQueries(IDbContextFactory dbContextFactory, ExplanationRuleStore store) +{ + public const int ExampleCount = 10; + public const int MaxGroups = 500; + + public async Task> GetValuesAsync(ExplanationKind kind, DateTime? since, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var events = db.TrapEvents.AsNoTracking(); + if (since is { } start) + { + events = events.Where(e => e.StartedAt >= start); + } + + IEnumerable values; + switch (kind) + { + case ExplanationKind.Target: + var targets = await events.Where(e => e.Target != null).GroupBy(e => e.Target!) + .Select(g => new { g.Key, Count = g.Count(), First = g.Min(e => e.StartedAt), Last = g.Max(e => e.StartedAt), Agent = g.Max(e => e.ClientInfo) }) + .ToListAsync(ct); + values = targets.Select(t => new ObservedValue(ExplanationText.Path(t.Key)!, t.Count, t.First, t.Last, t.Key, t.Agent)); + break; + case ExplanationKind.ClientInfo: + var agents = await events.GroupBy(e => e.ClientInfo ?? "") + .Select(g => new { g.Key, Count = g.Count(), First = g.Min(e => e.StartedAt), Last = g.Max(e => e.StartedAt), Target = g.Max(e => e.Target) }) + .ToListAsync(ct); + values = agents.Select(a => new ObservedValue(a.Key, a.Count, a.First, a.Last, a.Target, a.Key.Length == 0 ? null : a.Key)); + break; + default: + var outcomes = await events.GroupBy(e => new { e.Outcome, Seconds = e.DurationMs / 1000 }) + .Select(g => new { g.Key.Outcome, g.Key.Seconds, Count = g.Count(), First = g.Min(e => e.StartedAt), Last = g.Max(e => e.StartedAt), Target = g.Max(e => e.Target), Agent = g.Max(e => e.ClientInfo) }) + .ToListAsync(ct); + values = outcomes.Select(o => new ObservedValue(ExplanationText.Outcome(o.Outcome, o.Seconds * 1000), o.Count, o.First, o.Last, o.Target, o.Agent)); + break; + } + + return values + .GroupBy(v => v.Value) + .Select(g => new ObservedValue( + g.Key, + g.Sum(v => v.Catches), + g.Min(v => v.FirstSeen), + g.Max(v => v.LastSeen), + g.OrderByDescending(v => v.Catches).First().ExampleTarget, + g.Select(v => v.ExampleUserAgent).FirstOrDefault(a => a is not null))) + .ToList(); + } + + public async Task FindUnexplainedAsync(DateTime? since, UnexplainedGrouping grouping, int limit, CancellationToken ct = default) + { + var rules = await store.GetRuleSetAsync(ct); + var unexplained = (await GetValuesAsync(ExplanationKind.Target, since, ct)) + .Where(v => rules.Winner(ExplanationKind.Target, v.Value) is null) + .ToList(); + + var groups = unexplained + .GroupBy(v => grouping == UnexplainedGrouping.Path ? v.Value : ExplanationText.PathShape(v.Value)) + .Select(g => new UnexplainedGroup( + g.Key, + g.Sum(v => v.Catches), + g.OrderByDescending(v => v.Catches).Take(3).Select(v => v.Value).ToList(), + g.OrderByDescending(v => v.Catches).Select(v => v.ExampleUserAgent).FirstOrDefault(a => a is not null), + g.Min(v => v.FirstSeen), + g.Max(v => v.LastSeen))) + .OrderByDescending(g => g.Catches) + .ThenBy(g => g.Key, StringComparer.Ordinal) + .ToList(); + + var take = Math.Clamp(limit, 1, MaxGroups); + return new UnexplainedResult(unexplained.Sum(v => v.Catches), unexplained.Count, groups.Take(take).ToList(), Math.Max(0, groups.Count - take)); + } + + public async Task TestAsync(ExplanationKind kind, string pattern, int priority, int? replacesRuleId, DateTime? since, CancellationToken ct = default) + { + var validPattern = ExplanationValidator.Pattern(pattern); + ExplanationValidator.Priority(priority); + + var existing = (await store.ListAsync(ct)).Where(r => r.Enabled).ToList(); + var candidateId = replacesRuleId ?? int.MaxValue; + var candidate = new ExplanationRuleEntity { Id = candidateId, Kind = kind, Pattern = validPattern, Text = "-", Priority = priority, CreatedBy = "test" }; + var before = new RuleSet(existing); + var after = new RuleSet(existing.Where(r => r.Id != replacesRuleId).Append(candidate)); + var candidateOnly = new RuleSet([candidate]); + + var byId = existing.ToDictionary(r => r.Id); + var matched = new List(); + var newly = 0; + var lost = 0; + var lostExamples = new List(); + var takeovers = new Dictionary Examples)>(); + + foreach (var value in (await GetValuesAsync(kind, since, ct)).OrderByDescending(v => v.Catches)) + { + var wasWinner = before.Winner(kind, value.Value); + var nowWinner = after.Winner(kind, value.Value); + var hit = candidateOnly.Winner(kind, value.Value) is not null; + if (hit) + { + matched.Add(value); + } + + if (nowWinner?.Id == candidateId) + { + if (wasWinner is null) + { + newly += value.Catches; + } + else if (wasWinner.Id != candidateId) + { + var (catches, examples) = takeovers.GetValueOrDefault(wasWinner.Id, (0, [])); + if (examples.Count < ExampleCount) + { + examples.Add(value.Value); + } + + takeovers[wasWinner.Id] = (catches + value.Catches, examples); + } + } + else if (wasWinner?.Id == candidateId && nowWinner is null) + { + lost += value.Catches; + if (lostExamples.Count < ExampleCount) + { + lostExamples.Add(value.Value); + } + } + } + + return new RuleTestResult( + matched.Sum(v => v.Catches), + matched.Count, + matched.Take(ExampleCount).Select(v => (v.Value, v.Catches)).ToList(), + newly, + takeovers.OrderByDescending(t => t.Value.Catches).Select(t => new RuleTakeover(byId[t.Key], t.Value.Catches, t.Value.Examples)).ToList(), + lost, + lostExamples); + } + + public async Task> CountHitsAsync(CancellationToken ct = default) + { + var rules = await store.ListAsync(ct); + var hits = rules.ToDictionary(r => r.Id, _ => 0); + foreach (var group in rules.GroupBy(r => r.Kind)) + { + var set = new RuleSet(group); + foreach (var value in await GetValuesAsync(group.Key, null, ct)) + { + foreach (var rule in set.Matching(group.Key, value.Value)) + { + hits[rule.Id] += value.Catches; + } + } + } + + return hits; + } +} diff --git a/src/Flypaper.Storage/Explanations/ExplanationRuleStore.cs b/src/Flypaper.Storage/Explanations/ExplanationRuleStore.cs new file mode 100644 index 0000000..bf70774 --- /dev/null +++ b/src/Flypaper.Storage/Explanations/ExplanationRuleStore.cs @@ -0,0 +1,156 @@ +using Flypaper.Storage.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Flypaper.Storage.Explanations; + +public sealed record ExplanationRuleInput( + ExplanationKind? Kind = null, + string? Pattern = null, + string? Text = null, + int? Priority = null, + string? Note = null); + +public sealed class ExplanationRuleStore(IDbContextFactory dbContextFactory, TimeProvider timeProvider) +{ + public const string DashboardActor = "Dashboard"; + + private readonly object _gate = new(); + private RuleSet? _cached; + private int _version; + + public async Task GetRuleSetAsync(CancellationToken ct = default) + { + int version; + lock (_gate) + { + if (_cached is { } cached) + { + return cached; + } + + version = _version; + } + + var rules = new RuleSet((await ListAsync(ct)).Where(r => r.Enabled)); + lock (_gate) + { + if (version == _version) + { + _cached = rules; + } + } + + return rules; + } + + public async Task> ListAsync(CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + return await db.ExplanationRules.AsNoTracking().OrderBy(r => r.Kind).ThenByDescending(r => r.Priority).ThenBy(r => r.Id).ToListAsync(ct); + } + + public async Task GetAsync(int id, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + return await db.ExplanationRules.AsNoTracking().FirstOrDefaultAsync(r => r.Id == id, ct); + } + + public async Task CreateAsync(ExplanationRuleInput input, string createdBy, CancellationToken ct = default) + { + var rule = new ExplanationRuleEntity + { + Kind = input.Kind ?? throw new ArgumentException("The kind is required."), + Pattern = ExplanationValidator.Pattern(input.Pattern), + Text = ExplanationValidator.Text(input.Text), + Priority = ExplanationValidator.Priority(input.Priority ?? 0), + Note = ExplanationValidator.Note(input.Note), + CreatedBy = createdBy.Length > ExplanationLimits.MaxCreatedByLength ? createdBy[..ExplanationLimits.MaxCreatedByLength] : createdBy, + CreatedAt = timeProvider.GetUtcNow().UtcDateTime + }; + rule.UpdatedAt = rule.CreatedAt; + + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + if (await db.ExplanationRules.CountAsync(ct) >= ExplanationLimits.MaxRules) + { + throw new ArgumentException($"There are already {ExplanationLimits.MaxRules} rules; delete unused ones first."); + } + + db.ExplanationRules.Add(rule); + await db.SaveChangesAsync(ct); + Invalidate(); + return rule; + } + + public async Task UpdateAsync(int id, ExplanationRuleInput input, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var rule = await db.ExplanationRules.FirstOrDefaultAsync(r => r.Id == id, ct); + if (rule is null) + { + return null; + } + + if (input.Kind is { } kind) + { + rule.Kind = kind; + } + + if (input.Pattern is not null) + { + rule.Pattern = ExplanationValidator.Pattern(input.Pattern); + } + + if (input.Text is not null) + { + rule.Text = ExplanationValidator.Text(input.Text); + } + + if (input.Priority is { } priority) + { + rule.Priority = ExplanationValidator.Priority(priority); + } + + if (input.Note is not null) + { + rule.Note = ExplanationValidator.Note(input.Note); + } + + rule.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime; + await db.SaveChangesAsync(ct); + Invalidate(); + return rule; + } + + public async Task SetEnabledAsync(int id, bool enabled, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var rule = await db.ExplanationRules.FirstOrDefaultAsync(r => r.Id == id, ct); + if (rule is null) + { + return null; + } + + rule.Enabled = enabled; + rule.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime; + await db.SaveChangesAsync(ct); + Invalidate(); + return rule; + } + + public async Task DeleteAsync(int id, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var deleted = await db.ExplanationRules.Where(r => r.Id == id).ExecuteDeleteAsync(ct) > 0; + Invalidate(); + return deleted; + } + + private void Invalidate() + { + lock (_gate) + { + _version++; + _cached = null; + } + } +} diff --git a/src/Flypaper.Storage/Explanations/ExplanationText.cs b/src/Flypaper.Storage/Explanations/ExplanationText.cs new file mode 100644 index 0000000..227b88e --- /dev/null +++ b/src/Flypaper.Storage/Explanations/ExplanationText.cs @@ -0,0 +1,54 @@ +using System.Text.RegularExpressions; +using Flypaper.Core.Models; +using Flypaper.Storage.Entities; + +namespace Flypaper.Storage.Explanations; + +public static partial class ExplanationText +{ + [GeneratedRegex("[0-9a-fA-F]{8,}")] + private static partial Regex LongHex(); + + [GeneratedRegex("[0-9]+")] + private static partial Regex Digits(); + + public static string? Path(string? target) + { + if (target is null) + { + return null; + } + + var space = target.IndexOf(' '); + if (space < 0) + { + return target; + } + + var hostAndPath = target[(space + 1)..]; + if (hostAndPath.StartsWith('/')) + { + return hostAndPath; + } + + var slash = hostAndPath.IndexOf('/'); + return slash < 0 ? "/" : hostAndPath[slash..]; + } + + public static string Outcome(TrapOutcome outcome, long durationMs) => + outcome == TrapOutcome.Rejected ? outcome.ToString() : $"{outcome} {durationMs / 1000}s"; + + public static string Value(ExplanationKind kind, TrapEventEntity trapEvent) => kind switch + { + ExplanationKind.Target => Path(trapEvent.Target) ?? "", + ExplanationKind.ClientInfo => trapEvent.ClientInfo ?? "", + _ => Outcome(trapEvent.Outcome, trapEvent.DurationMs) + }; + + public static string PathShape(string path) + { + var query = path.IndexOf('?'); + var bare = query < 0 ? path : path[..query]; + return Digits().Replace(LongHex().Replace(bare, "{hex}"), "{n}"); + } +} diff --git a/src/Flypaper.Storage/Explanations/ExplanationValidator.cs b/src/Flypaper.Storage/Explanations/ExplanationValidator.cs new file mode 100644 index 0000000..57cb71b --- /dev/null +++ b/src/Flypaper.Storage/Explanations/ExplanationValidator.cs @@ -0,0 +1,82 @@ +using System.Text.RegularExpressions; + +namespace Flypaper.Storage.Explanations; + +public static class ExplanationValidator +{ + public static readonly TimeSpan MatchTimeout = TimeSpan.FromMilliseconds(250); + + public static Regex Compile(string pattern) => + new(pattern, RegexOptions.NonBacktracking | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, MatchTimeout); + + public static string Pattern(string? pattern) + { + var value = pattern?.Trim(); + if (string.IsNullOrEmpty(value)) + { + throw new ArgumentException("The pattern must not be empty."); + } + + if (value.Length > ExplanationLimits.MaxPatternLength) + { + throw new ArgumentException($"The pattern must have at most {ExplanationLimits.MaxPatternLength} characters."); + } + + try + { + Compile(value); + } + catch (ArgumentException exception) + { + throw new ArgumentException($"The pattern is not a valid regular expression: {exception.Message}"); + } + catch (NotSupportedException exception) + { + throw new ArgumentException($"The pattern uses a feature that is not supported (no lookarounds, backreferences or atomic groups): {exception.Message}"); + } + + return value; + } + + public static string Text(string? text) + { + var value = text?.Trim(); + if (string.IsNullOrEmpty(value)) + { + throw new ArgumentException("The text must not be empty."); + } + + if (value.Length > ExplanationLimits.MaxTextLength) + { + throw new ArgumentException($"The text must have at most {ExplanationLimits.MaxTextLength} characters."); + } + + if (value.Any(char.IsControl)) + { + throw new ArgumentException("The text must be plain text without line breaks or control characters."); + } + + return value; + } + + public static string? Note(string? note) + { + var value = note?.Trim(); + if (string.IsNullOrEmpty(value)) + { + return null; + } + + if (value.Length > ExplanationLimits.MaxNoteLength) + { + throw new ArgumentException($"The note must have at most {ExplanationLimits.MaxNoteLength} characters."); + } + + return value.Any(char.IsControl) ? throw new ArgumentException("The note must be plain text without control characters.") : value; + } + + public static int Priority(int priority) => + Math.Abs(priority) <= ExplanationLimits.MaxPriority + ? priority + : throw new ArgumentException($"The priority must be between -{ExplanationLimits.MaxPriority} and {ExplanationLimits.MaxPriority}."); +} diff --git a/src/Flypaper.Storage/Explanations/RuleSet.cs b/src/Flypaper.Storage/Explanations/RuleSet.cs new file mode 100644 index 0000000..173f619 --- /dev/null +++ b/src/Flypaper.Storage/Explanations/RuleSet.cs @@ -0,0 +1,77 @@ +using System.Text.RegularExpressions; +using Flypaper.Storage.Entities; + +namespace Flypaper.Storage.Explanations; + +public sealed record Explanation(ExplanationRuleEntity? Target, ExplanationRuleEntity? Client, ExplanationRuleEntity? Outcome) +{ + public bool HasTarget => Target is not null; +} + +public sealed class RuleSet +{ + public static readonly RuleSet Empty = new([]); + + private readonly IReadOnlyDictionary> _byKind; + + public RuleSet(IEnumerable rules) + { + var compiled = new Dictionary>(); + foreach (var rule in rules.OrderByDescending(r => r.Priority).ThenBy(r => r.Id)) + { + Regex regex; + try + { + regex = ExplanationValidator.Compile(rule.Pattern); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException) + { + continue; + } + + if (!compiled.TryGetValue(rule.Kind, out var list)) + { + compiled[rule.Kind] = list = []; + } + + list.Add((rule, regex)); + } + + _byKind = compiled.ToDictionary(p => p.Key, p => (IReadOnlyList<(ExplanationRuleEntity, Regex)>)p.Value); + } + + public ExplanationRuleEntity? Winner(ExplanationKind kind, string value) => Matching(kind, value).FirstOrDefault(); + + public IEnumerable Matching(ExplanationKind kind, string value) + { + if (!_byKind.TryGetValue(kind, out var rules)) + { + yield break; + } + + foreach (var (rule, regex) in rules) + { + if (IsMatch(regex, value)) + { + yield return rule; + } + } + } + + public Explanation Explain(TrapEventEntity trapEvent) => new( + trapEvent.Target is null ? null : Winner(ExplanationKind.Target, ExplanationText.Value(ExplanationKind.Target, trapEvent)), + Winner(ExplanationKind.ClientInfo, ExplanationText.Value(ExplanationKind.ClientInfo, trapEvent)), + Winner(ExplanationKind.Outcome, ExplanationText.Value(ExplanationKind.Outcome, trapEvent))); + + private static bool IsMatch(Regex regex, string value) + { + try + { + return regex.IsMatch(value); + } + catch (RegexMatchTimeoutException) + { + return false; + } + } +} diff --git a/src/Flypaper.Storage/FlypaperDbContext.cs b/src/Flypaper.Storage/FlypaperDbContext.cs index 7a1739b..e6892c9 100644 --- a/src/Flypaper.Storage/FlypaperDbContext.cs +++ b/src/Flypaper.Storage/FlypaperDbContext.cs @@ -1,4 +1,5 @@ using Flypaper.Storage.Entities; +using Flypaper.Storage.Explanations; using Microsoft.EntityFrameworkCore; namespace Flypaper.Storage; @@ -14,6 +15,8 @@ public sealed class FlypaperDbContext(DbContextOptions option public DbSet McpTokens => Set(); + public DbSet ExplanationRules => Set(); + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) => configurationBuilder.Properties().HaveConversion(); @@ -43,5 +46,12 @@ public sealed class FlypaperDbContext(DbContextOptions option mcpToken.Property(e => e.Name).HasMaxLength(100); mcpToken.Property(e => e.TokenHash).HasMaxLength(64); mcpToken.HasIndex(e => e.TokenHash).IsUnique(); + + var explanationRule = modelBuilder.Entity(); + explanationRule.Property(e => e.Kind).HasConversion().HasMaxLength(16); + explanationRule.Property(e => e.Pattern).HasMaxLength(ExplanationLimits.MaxPatternLength); + explanationRule.Property(e => e.Text).HasMaxLength(ExplanationLimits.MaxTextLength); + explanationRule.Property(e => e.Note).HasMaxLength(ExplanationLimits.MaxNoteLength); + explanationRule.Property(e => e.CreatedBy).HasMaxLength(ExplanationLimits.MaxCreatedByLength); } } diff --git a/src/Flypaper.Storage/FlypaperStorageExtensions.cs b/src/Flypaper.Storage/FlypaperStorageExtensions.cs index ec66fe4..c36d869 100644 --- a/src/Flypaper.Storage/FlypaperStorageExtensions.cs +++ b/src/Flypaper.Storage/FlypaperStorageExtensions.cs @@ -1,6 +1,7 @@ using Flypaper.Core.Abstractions; using Flypaper.Storage.Dashboard; using Flypaper.Storage.Events; +using Flypaper.Storage.Explanations; using Flypaper.Storage.Maintenance; using Flypaper.Storage.Queries; using Flypaper.Storage.Settings; @@ -36,6 +37,8 @@ public static class FlypaperStorageExtensions services.AddSingleton(sp => sp.GetRequiredService()); services.AddHostedService(); services.AddHostedService(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Flypaper.Storage/Migrations/20261121103849_AddExplanationRulesAndTokenWrite.Designer.cs b/src/Flypaper.Storage/Migrations/20261121103849_AddExplanationRulesAndTokenWrite.Designer.cs new file mode 100644 index 0000000..2d3cfbb --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261121103849_AddExplanationRulesAndTokenWrite.Designer.cs @@ -0,0 +1,201 @@ +// +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("20261121103849_AddExplanationRulesAndTokenWrite")] + partial class AddExplanationRulesAndTokenWrite + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.15"); + + modelBuilder.Entity("Flypaper.Storage.Entities.ExplanationRuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Note") + .HasMaxLength(500) + .HasColumnType("TEXT"); + + b.Property("Pattern") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("TEXT"); + + b.Property("Priority") + .HasColumnType("INTEGER"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(600) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("ExplanationRules"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CanWrite") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("McpTokens"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.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.Entities.TrapEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Asn") + .HasColumnType("INTEGER"); + + b.Property("BytesSent") + .HasColumnType("INTEGER"); + + b.Property("City") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ClientInfo") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("Country") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("CountryCode") + .HasMaxLength(2) + .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("Provider") + .HasMaxLength(256) + .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("Asn"); + + b.HasIndex("CountryCode"); + + b.HasIndex("RemoteIp"); + + b.HasIndex("StartedAt"); + + b.ToTable("TrapEvents"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Flypaper.Storage/Migrations/20261121103849_AddExplanationRulesAndTokenWrite.cs b/src/Flypaper.Storage/Migrations/20261121103849_AddExplanationRulesAndTokenWrite.cs new file mode 100644 index 0000000..afea995 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261121103849_AddExplanationRulesAndTokenWrite.cs @@ -0,0 +1,54 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Flypaper.Storage.Migrations +{ + /// + public partial class AddExplanationRulesAndTokenWrite : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "CanWrite", + table: "McpTokens", + type: "INTEGER", + nullable: false, + defaultValue: false); + + migrationBuilder.CreateTable( + name: "ExplanationRules", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Kind = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Pattern = table.Column(type: "TEXT", maxLength: 500, nullable: false), + Text = table.Column(type: "TEXT", maxLength: 600, nullable: false), + Priority = table.Column(type: "INTEGER", nullable: false), + Enabled = table.Column(type: "INTEGER", nullable: false), + Note = table.Column(type: "TEXT", maxLength: 500, nullable: true), + CreatedAt = table.Column(type: "TEXT", nullable: false), + UpdatedAt = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", maxLength: 100, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ExplanationRules", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ExplanationRules"); + + migrationBuilder.DropColumn( + name: "CanWrite", + table: "McpTokens"); + } + } +} diff --git a/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs b/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs index e02f387..ceec7a2 100644 --- a/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs +++ b/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs @@ -17,12 +17,62 @@ namespace Flypaper.Storage.Migrations #pragma warning disable 612, 618 modelBuilder.HasAnnotation("ProductVersion", "10.0.15"); + modelBuilder.Entity("Flypaper.Storage.Entities.ExplanationRuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Note") + .HasMaxLength(500) + .HasColumnType("TEXT"); + + b.Property("Pattern") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("TEXT"); + + b.Property("Priority") + .HasColumnType("INTEGER"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(600) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("ExplanationRules"); + }); + modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); + b.Property("CanWrite") + .HasColumnType("INTEGER"); + b.Property("CreatedAt") .HasColumnType("TEXT"); diff --git a/src/Flypaper.Storage/Settings/McpTokenStore.cs b/src/Flypaper.Storage/Settings/McpTokenStore.cs index 83c8894..89396a1 100644 --- a/src/Flypaper.Storage/Settings/McpTokenStore.cs +++ b/src/Flypaper.Storage/Settings/McpTokenStore.cs @@ -13,10 +13,10 @@ public sealed class McpTokenStore(IDbContextFactory dbContext return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct); } - public async Task CreateAsync(string name, string tokenHash, CancellationToken ct = default) + public async Task CreateAsync(string name, string tokenHash, bool canWrite = false, CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); - var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CreatedAt = timeProvider.GetUtcNow().UtcDateTime }; + var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CanWrite = canWrite, CreatedAt = timeProvider.GetUtcNow().UtcDateTime }; db.McpTokens.Add(token); await db.SaveChangesAsync(ct); return token; @@ -28,6 +28,12 @@ public sealed class McpTokenStore(IDbContextFactory dbContext return await db.McpTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct) > 0; } + public async Task SetCanWriteAsync(int id, bool canWrite, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + return await db.McpTokens.Where(t => t.Id == id).ExecuteUpdateAsync(set => set.SetProperty(t => t.CanWrite, canWrite), ct) > 0; + } + public async Task UseAsync(string tokenHash, CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); diff --git a/src/Flypaper.Web/Components/Layout/MainLayout.razor b/src/Flypaper.Web/Components/Layout/MainLayout.razor index 35adbc5..665909a 100644 --- a/src/Flypaper.Web/Components/Layout/MainLayout.razor +++ b/src/Flypaper.Web/Components/Layout/MainLayout.razor @@ -4,6 +4,7 @@