Add explanation rules for catches, editable over MCP
Build and deploy / build (push) Successful in 1m29s
Build and deploy / deploy (push) Successful in 21s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-21 11:46:22 +01:00
1 parent 4086fa3da3
commit 2437880013
37 files changed
+1867 -37

No files matched your search

@@ -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<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider, ExplanationRuleStore explanations)
{
private const int TopCount = 10;
@@ -64,12 +65,24 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> 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<TrapEventEntity> Apply(IQueryable<TrapEventEntity> events, RecentFilter filter)
@@ -13,7 +13,8 @@ public sealed record RecentFilter(
StrategyMatch? Strategy = null,
string? Search = null,
int Limit = RecentFilter.DefaultLimit,
IReadOnlyList<string>? SearchStrategies = null)
IReadOnlyList<string>? SearchStrategies = null,
bool Unexplained = false)
{
public const int DefaultLimit = 50;
public const int MaxLimit = 500;
@@ -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; }
}
@@ -11,4 +11,6 @@ public sealed class McpTokenEntity
public DateTime CreatedAt { get; set; }
public DateTime? LastUsedAt { get; set; }
public bool CanWrite { get; set; }
}
@@ -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;
}
@@ -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<string> ExamplePaths, string? ExampleUserAgent, DateTime FirstSeen, DateTime LastSeen);
public sealed record UnexplainedResult(int Catches, int DistinctPaths, IReadOnlyList<UnexplainedGroup> Groups, int GroupsOmitted);
public sealed record RuleTakeover(ExplanationRuleEntity Rule, int Catches, IReadOnlyList<string> Examples);
public sealed record RuleTestResult(
int Catches,
int DistinctValues,
IReadOnlyList<(string Value, int Catches)> Examples,
int NewlyExplained,
IReadOnlyList<RuleTakeover> TakesOver,
int Lost,
IReadOnlyList<string> LostExamples);
public sealed class ExplanationQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, ExplanationRuleStore store)
{
public const int ExampleCount = 10;
public const int MaxGroups = 500;
public async Task<IReadOnlyList<ObservedValue>> 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<ObservedValue> 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<UnexplainedResult> 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<RuleTestResult> 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<ObservedValue>();
var newly = 0;
var lost = 0;
var lostExamples = new List<string>();
var takeovers = new Dictionary<int, (int Catches, List<string> 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<IReadOnlyDictionary<int, int>> 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;
}
}
@@ -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<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
{
public const string DashboardActor = "Dashboard";
private readonly object _gate = new();
private RuleSet? _cached;
private int _version;
public async Task<RuleSet> 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<IReadOnlyList<ExplanationRuleEntity>> 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<ExplanationRuleEntity?> 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<ExplanationRuleEntity> 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<ExplanationRuleEntity?> 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<ExplanationRuleEntity?> 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<bool> 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;
}
}
}
@@ -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}");
}
}
@@ -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}.");
}
@@ -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<ExplanationKind, IReadOnlyList<(ExplanationRuleEntity Rule, Regex Regex)>> _byKind;
public RuleSet(IEnumerable<ExplanationRuleEntity> rules)
{
var compiled = new Dictionary<ExplanationKind, List<(ExplanationRuleEntity, Regex)>>();
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<ExplanationRuleEntity> 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;
}
}
}
+10
View File
@@ -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<FlypaperDbContext> option
public DbSet<McpTokenEntity> McpTokens => Set<McpTokenEntity>();
public DbSet<ExplanationRuleEntity> ExplanationRules => Set<ExplanationRuleEntity>();
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
@@ -43,5 +46,12 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> 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<ExplanationRuleEntity>();
explanationRule.Property(e => e.Kind).HasConversion<string>().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);
}
}
@@ -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<ITrapEventSink>(sp => sp.GetRequiredService<ChannelTrapEventSink>());
services.AddHostedService<TrapEventWriter>();
services.AddHostedService<OriginBackfill>();
services.AddSingleton<ExplanationRuleStore>();
services.AddSingleton<ExplanationQueries>();
services.AddSingleton<DashboardQueries>();
services.AddSingleton<CatchQueries>();
services.AddSingleton<IRepeatOffenderLookup, RepeatOffenderLookup>();
@@ -0,0 +1,201 @@
// <auto-generated />
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
{
/// <inheritdoc />
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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Note")
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<string>("Pattern")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<int>("Priority")
.HasColumnType("INTEGER");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(600)
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("ExplanationRules");
});
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("CanWrite")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastUsedAt")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("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<string>("Key")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Key");
b.ToTable("Settings");
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("Asn")
.HasColumnType("INTEGER");
b.Property<long>("BytesSent")
.HasColumnType("INTEGER");
b.Property<string>("City")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("ClientInfo")
.HasMaxLength(2048)
.HasColumnType("TEXT");
b.Property<string>("Country")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("CountryCode")
.HasMaxLength(2)
.HasColumnType("TEXT");
b.Property<long>("DurationMs")
.HasColumnType("INTEGER");
b.Property<DateTime>("EndedAt")
.HasColumnType("TEXT");
b.Property<string>("Outcome")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Protocol")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Provider")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("RemoteIp")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<Guid>("SessionId")
.HasColumnType("TEXT");
b.Property<DateTime>("StartedAt")
.HasColumnType("TEXT");
b.Property<string>("Strategy")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<string>("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
}
}
}
@@ -0,0 +1,54 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class AddExplanationRulesAndTokenWrite : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "CanWrite",
table: "McpTokens",
type: "INTEGER",
nullable: false,
defaultValue: false);
migrationBuilder.CreateTable(
name: "ExplanationRules",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Kind = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Pattern = table.Column<string>(type: "TEXT", maxLength: 500, nullable: false),
Text = table.Column<string>(type: "TEXT", maxLength: 600, nullable: false),
Priority = table.Column<int>(type: "INTEGER", nullable: false),
Enabled = table.Column<bool>(type: "INTEGER", nullable: false),
Note = table.Column<string>(type: "TEXT", maxLength: 500, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ExplanationRules", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ExplanationRules");
migrationBuilder.DropColumn(
name: "CanWrite",
table: "McpTokens");
}
}
}
@@ -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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Note")
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<string>("Pattern")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<int>("Priority")
.HasColumnType("INTEGER");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(600)
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("ExplanationRules");
});
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("CanWrite")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
@@ -13,10 +13,10 @@ public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContext
return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct);
}
public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, CancellationToken ct = default)
public async Task<McpTokenEntity> 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<FlypaperDbContext> dbContext
return await db.McpTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct) > 0;
}
public async Task<bool> 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<McpTokenEntity?> UseAsync(string tokenHash, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
@@ -4,6 +4,7 @@
<nav class="nav">
<a href="/" class="brand"><span class="brand-mark" aria-hidden="true"></span>Flypaper</a>
<NavLink href="/" Match="NavLinkMatch.All">Dashboard</NavLink>
<NavLink href="/erklaerungen">Erklärungen</NavLink>
<NavLink href="/settings">Einstellungen</NavLink>
<form method="post" action="/auth/logout" class="logout">
<AntiforgeryToken />
@@ -15,7 +15,8 @@ public sealed record DashboardFilter(
string? Ziel = null,
string? Strategie = null,
string? Q = null,
int Limit = RecentFilter.DefaultLimit)
int Limit = RecentFilter.DefaultLimit,
string? Erklaerung = null)
{
public const string Anchor = "faenge";
@@ -24,6 +25,8 @@ public sealed record DashboardFilter(
public static readonly IReadOnlyList<(string Value, string Label)> Outcomes =
[("", "Alle"), ("aufgegeben", "Aufgegeben"), ("zeitlimit", "Zeitlimit"), ("abgelehnt", "Abgelehnt")];
public static readonly IReadOnlyList<(string Value, string Label)> Explanations = [("", "Alle"), ("ohne", "Ohne Erklärung")];
public bool IsEmpty => this with { Limit = RecentFilter.DefaultLimit } == new DashboardFilter();
public static DashboardFilter Parse(
@@ -35,7 +38,8 @@ public sealed record DashboardFilter(
string? ziel,
string? strategie,
string? q,
string? limit)
string? limit,
string? erklaerung = null)
{
var parsedLimit = int.TryParse(limit, NumberStyles.None, CultureInfo.InvariantCulture, out var value)
? Math.Clamp(value, 1, RecentFilter.MaxLimit)
@@ -50,7 +54,8 @@ public sealed record DashboardFilter(
Clean(ziel),
Clean(strategie) is { } strategy ? StrategyNames.GroupKey(strategy) : null,
Clean(q),
parsedLimit);
parsedLimit,
Known(Explanations, erklaerung));
}
public RecentFilter ToRecentFilter() => new(
@@ -73,7 +78,8 @@ public sealed record DashboardFilter(
Ziel,
StrategyNames.Group(Strategie),
Q,
Limit);
Limit,
Unexplained: Erklaerung == "ohne");
public int NextLimit => Math.Min(Limit * 2, RecentFilter.MaxLimit);
@@ -88,6 +94,7 @@ public sealed record DashboardFilter(
Add(parts, "ziel", Ziel);
Add(parts, "strategie", Strategie);
Add(parts, "q", Q);
Add(parts, "erklaerung", Erklaerung);
if (Limit != RecentFilter.DefaultLimit)
{
Add(parts, "limit", Limit.ToString(CultureInfo.InvariantCulture));
@@ -5,7 +5,9 @@
@using Microsoft.Extensions.Options
@using Flypaper.Storage.Dashboard
@using Flypaper.Storage.Entities
@using Flypaper.Storage.Explanations
@inject DashboardQueries Queries
@inject ExplanationRuleStore Explanations
@inject IConnectionGovernor Governor
@inject IOptions<PortOptions> Ports
@@ -125,6 +127,15 @@
}
</select>
</label>
<label>
<span>Erklärung</span>
<select name="erklaerung" data-autosubmit>
@foreach (var (value, label) in DashboardFilter.Explanations)
{
<option value="@value" selected="@(value == (_filter.Erklaerung ?? ""))">@label</option>
}
</select>
</label>
<label class="filter-search">
<span>Suche</span>
<input type="search" name="q" value="@_filter.Q" placeholder="IP, Provider, Ziel, Strategie, User-Agent" />
@@ -179,6 +190,7 @@
var duration = Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs));
var bytes = Formatting.Number(trapEvent.BytesSent);
var strategy = StrategyNames.Describe(trapEvent.Strategy);
var explanation = _rules.Explain(trapEvent);
<tr id="f@(index)" data-expand="event:@trapEvent.Id" tabindex="0" aria-expanded="false" class="@(trapEvent.Outcome == TrapOutcome.Rejected ? "rejected" : null)">
<td class="c-time"><span class="c-date">@started.ToString("dd.MM.")&nbsp;</span>@started.ToString("HH:mm:ss")</td>
<td class="c-ip mono" title="@trapEvent.RemoteIp">@trapEvent.RemoteIp</td>
@@ -199,6 +211,25 @@
<div class="extra extra-md">User-Agent: @(trapEvent.ClientInfo ?? "–")</div>
<div class="extra extra-all">Herkunft: @(trapEvent.CountryCode is { } code ? $"{Formatting.Flag(code)} {code} · {Origin(trapEvent)}" : "–")</div>
<div class="extra extra-sm">Dauer: @duration · Bytes: @bytes</div>
<div class="extra extra-all explain">
<strong>Was ist passiert?</strong>
@if (explanation.Target is { } targetRule)
{
<p>@targetRule.Text</p>
}
else
{
<p class="muted">Unbekanntes Ziel</p>
}
@if (explanation.Client is { } clientRule)
{
<p>@clientRule.Text</p>
}
@if (explanation.Outcome is { } outcomeRule)
{
<p>@outcomeRule.Text</p>
}
</div>
<div class="extra extra-xs">Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @OutcomeLabel(trapEvent.Outcome)</div>
</td>
<td class="c-strategy" title="@strategy.Tooltip">@strategy.DisplayName@foreach (var badge in strategy.Badges){<span class="badge">@badge</span>}</td>
@@ -236,6 +267,7 @@
private DashboardData? _data;
private RecentCatches? _recent;
private DashboardFilter _filter = new();
private RuleSet _rules = RuleSet.Empty;
private DateTime _loadedAt;
[SupplyParameterFromQuery(Name = "zeit")] public string? Zeit { get; set; }
@@ -256,9 +288,12 @@
[SupplyParameterFromQuery(Name = "limit")] public string? Limit { get; set; }
[SupplyParameterFromQuery(Name = "erklaerung")] public string? Erklaerung { get; set; }
protected override async Task OnInitializedAsync()
{
_filter = DashboardFilter.Parse(Zeit, Ausgang, Land, Provider, Ip, Ziel, Strategie, Q, Limit);
_filter = DashboardFilter.Parse(Zeit, Ausgang, Land, Provider, Ip, Ziel, Strategie, Q, Limit, Erklaerung);
_rules = await Explanations.GetRuleSetAsync();
_data = await Queries.GetAsync();
_recent = await Queries.GetRecentAsync(_filter.ToRecentFilter() with { SearchStrategies = StrategyNames.Matching(_filter.Q) });
_loadedAt = DateTime.Now;
@@ -318,6 +353,11 @@
yield return ($"Strategie: {StrategyNames.Display(strategie)}{(badges.Count == 0 ? "" : $" ({string.Join(", ", badges)})")}", reset with { Strategie = null });
}
if (_filter.Erklaerung is { } erklaerung)
{
yield return ($"Erklärung: {DashboardFilter.Explanations.First(e => e.Value == erklaerung).Label}", reset with { Erklaerung = null });
}
if (_filter.Q is { } q)
{
yield return ($"Suche: „{q}“", reset with { Q = null });
@@ -0,0 +1,89 @@
@page "/erklaerungen"
@using Flypaper.Storage.Entities
@using Flypaper.Storage.Explanations
@inject ExplanationRuleStore Store
@inject ExplanationQueries Queries
<PageTitle>Flypaper · Erklärungen</PageTitle>
<header class="page-head">
<h1>Erklärungen</h1>
<p>Regeln, die in der Fang-Liste erklären, was ein Bot wollte. Neue Regeln legt eine KI per MCP an. Änderungen gelten sofort, auch für alte Fänge.</p>
</header>
<section class="card">
<div class="card-head">
<h2>Regeln <span class="count">· @_rules.Count</span></h2>
<span class="hint"><a href="/?erklaerung=ohne#faenge">Fänge ohne Erklärung anzeigen</a></span>
</div>
@if (_rules.Count == 0)
{
<p class="empty">Noch keine Regeln.</p>
}
else
{
<div class="scroll">
<table class="s-table rule-table">
<thead>
<tr>
<th>Art</th>
<th>Muster</th>
<th>Text</th>
<th class="num">Priorität</th>
<th class="num">Treffer</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var rule in _rules)
{
<tr class="@(rule.Enabled ? null : "off")">
<td class="nowrap">@KindLabel(rule.Kind)</td>
<td class="mono">@rule.Pattern</td>
<td>
@rule.Text
<div class="muted rule-meta">
@(rule.Note is { } note ? note + " · " : "")von @rule.CreatedBy, @rule.UpdatedAt.ToLocalTime().ToString("dd.MM.yyyy")
</div>
</td>
<td class="num">@rule.Priority</td>
<td class="num">@Formatting.Number(_hits.GetValueOrDefault(rule.Id))</td>
<td class="nowrap">
<form method="post" action="/explanations/@rule.Id/enabled" class="inline-form">
<AntiforgeryToken />
<input type="hidden" name="enabled" value="@(rule.Enabled ? "false" : "true")" />
<button type="submit" class="ghost">@(rule.Enabled ? "Ausschalten" : "Einschalten")</button>
</form>
</td>
<td class="nowrap">
<form method="post" action="/explanations/@rule.Id/delete" class="inline-form" onsubmit="return confirm('Regel wirklich löschen?')">
<AntiforgeryToken />
<button type="submit" class="ghost danger-text">Löschen</button>
</form>
</td>
</tr>
}
</tbody>
</table>
</div>
}
</section>
@code {
private IReadOnlyList<ExplanationRuleEntity> _rules = [];
private IReadOnlyDictionary<int, int> _hits = new Dictionary<int, int>();
protected override async Task OnInitializedAsync()
{
_rules = await Store.ListAsync();
_hits = await Queries.CountHitsAsync();
}
private static string KindLabel(ExplanationKind kind) => kind switch
{
ExplanationKind.Target => "Ziel",
ExplanationKind.ClientInfo => "User-Agent",
_ => "Ausgang"
};
}
@@ -5,11 +5,19 @@
@inject McpTokenStore Store
@inject NavigationManager Navigation
<SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol Nur im LAN.">
<SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol und pflegen die Erklärungsregeln. Regeln ändern dürfen nur Tokens mit Schreibrecht. Nur im LAN.">
@if (Revoked == "revoked")
{
<Notice>Token widerrufen.</Notice>
}
else if (Revoked == "write-on")
{
<Notice>Schreibrecht erteilt.</Notice>
}
else if (Revoked == "write-off")
{
<Notice>Schreibrecht entzogen.</Notice>
}
@if (_newToken is not null)
{
@@ -37,6 +45,7 @@
<th>Name</th>
<th>Erstellt</th>
<th>Zuletzt genutzt</th>
<th>Zugriff</th>
<th></th>
</tr>
</thead>
@@ -47,6 +56,14 @@
<td>@token.Name</td>
<td class="nowrap">@token.CreatedAt.ToLocalTime().ToString("dd.MM.yyyy HH:mm")</td>
<td class="nowrap">@(token.LastUsedAt?.ToLocalTime().ToString("dd.MM.yyyy HH:mm") ?? "nie")</td>
<td class="nowrap">
<form method="post" action="/mcp-tokens/@token.Id/write" class="inline-form">
<AntiforgeryToken />
<input type="hidden" name="enabled" value="@(token.CanWrite ? "false" : "true")" />
<span>@(token.CanWrite ? "Lesen und schreiben" : "Nur lesen")</span>
<button type="submit" class="ghost">@(token.CanWrite ? "Schreibrecht entziehen" : "Schreibrecht erteilen")</button>
</form>
</td>
<td class="num">
<form method="post" action="/mcp-tokens/@token.Id/revoke" onsubmit="return confirm('Token „@token.Name“ widerrufen?')">
<AntiforgeryToken />
@@ -72,6 +89,10 @@
<span class="field-error">@nameError</span>
}
</div>
<label class="inline-check">
<InputCheckbox @bind-Value="Model!.CanWrite" />
<span>Mit Schreibrecht</span>
</label>
<button type="submit">Token erzeugen</button>
</EditForm>
</SettingsSection>
@@ -103,9 +124,10 @@
return;
}
_newToken = await Tokens.CreateAsync(name);
_newToken = await Tokens.CreateAsync(name, Model.CanWrite);
_newTokenName = name;
Model.Name = null;
Model.CanWrite = false;
_tokens = await Store.ListAsync();
}
}
@@ -3,4 +3,6 @@ namespace Flypaper.Web.Components.Pages.Settings;
public sealed class McpTokenModel
{
public string? Name { get; set; }
public bool CanWrite { get; set; }
}
@@ -0,0 +1,35 @@
using Flypaper.Storage.Explanations;
using Microsoft.AspNetCore.Antiforgery;
namespace Flypaper.Web.Explanations;
public static class ExplanationEndpoints
{
public static IEndpointRouteBuilder MapExplanationEndpoints(this IEndpointRouteBuilder app)
{
app.MapPost("/explanations/{id:int}/enabled", async (int id, HttpContext context, IAntiforgery antiforgery, ExplanationRuleStore store) =>
{
if (!await antiforgery.IsRequestValidAsync(context))
{
return Results.BadRequest();
}
var enabled = (await context.Request.ReadFormAsync(context.RequestAborted))["enabled"] == "true";
await store.SetEnabledAsync(id, enabled, context.RequestAborted);
return Results.LocalRedirect("/erklaerungen");
});
app.MapPost("/explanations/{id:int}/delete", async (int id, HttpContext context, IAntiforgery antiforgery, ExplanationRuleStore store) =>
{
if (!await antiforgery.IsRequestValidAsync(context))
{
return Results.BadRequest();
}
await store.DeleteAsync(id, context.RequestAborted);
return Results.LocalRedirect("/erklaerungen");
});
return app;
}
}
+187
View File
@@ -0,0 +1,187 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Flypaper.Storage.Entities;
using Flypaper.Storage.Explanations;
using Flypaper.Storage.Queries;
using ModelContextProtocol;
using ModelContextProtocol.Server;
namespace Flypaper.Web.Mcp;
[McpServerToolType]
public sealed class ExplanationTools(ExplanationRuleStore store, ExplanationQueries queries, TimeProvider timeProvider, IHttpContextAccessor httpContext)
{
private const string PeriodDescription = "Time window ending now: a number with m (minutes), h (hours), d (days) or w (weeks), e.g. 24h, 7d; or all.";
private const string KindDescription =
"What the pattern is matched against. " +
"target: the requested path including the query string, without method and host, e.g. /.git/HEAD or /index.php?s=/x (the text explains what the bot was looking for). " +
"client_info: the User-Agent header, an empty string if the bot sent none (the text explains which tool or kind of client it is). " +
"outcome: the text '<Outcome> <whole seconds>s', e.g. 'ClientAborted 9s', 'Timeout 60s', 'Completed 3600s', or just 'Rejected' (the text explains how the catch ended; " +
"ClientAborted = the bot gave up, Timeout = Flypaper ended it, Rejected = connection refused because the trap was full, Completed = finished normally).";
private const string PatternDescription =
".NET regular expression, case-insensitive, matches anywhere in the text unless anchored with ^ and $. Lookarounds, backreferences and atomic groups are not supported. " +
"Make it as narrow as possible and anchor it, e.g. ^/\\.env(\\.[a-z0-9_-]+)?$ instead of env. Test it with test_explanation_rule before saving. At most 500 characters.";
private const string TextDescription =
"One or two short sentences in German, simple language for laypeople, plain text only (no Markdown, HTML or line breaks), at most 600 characters. " +
"target: what the bot wanted, e.g. 'Sucht nach einer vergessenen Konfigurationsdatei, in der oft Passwörter stehen.' " +
"client_info: which tool it is, e.g. 'Ein Programm, das das Internet automatisch nach offenen Servern absucht.' " +
"outcome: how it ended, e.g. 'Der Bot hat nach 9 Sekunden aufgegeben.' Do not claim more than the data shows.";
private const string PriorityDescription = "Higher wins when several rules of the same kind match; ties go to the older rule. Use about 10 for narrow rules and 0 for broad fallbacks. Range -1000 to 1000.";
private const string NoteDescription = "Optional source or remark for maintainers, e.g. a CVE number or a link. At most 500 characters. An empty string removes it.";
[McpServerTool(Name = "list_explanation_rules", Title = "List explanation rules", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("All explanation rules with pattern, text, priority, enabled state and how many catches each one matches (counted over all stored catches, even when the rule is disabled). Look here before creating a rule to avoid duplicates.")]
public async Task<RuleListResult> ListRules(
[Description("Only this kind: target, client_info or outcome.")] string? kind = null,
CancellationToken ct = default)
{
var filter = kind is null ? (ExplanationKind?)null : ParseKind(kind);
var hits = await queries.CountHitsAsync(ct);
var rules = (await store.ListAsync(ct)).Where(r => filter is null || r.Kind == filter).Select(r => ToItem(r, hits.GetValueOrDefault(r.Id))).ToList();
return new RuleListResult(rules.Count, rules);
}
[McpServerTool(Name = "list_unexplained", Title = "List unexplained targets", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Catches whose requested path is not explained by any enabled target rule, grouped by path or by path pattern and sorted by number of catches. Start here to find what to write rules for: take the biggest groups first.")]
public async Task<UnexplainedListResult> ListUnexplained(
[Description(PeriodDescription)] string period = "all",
[Description("path: one group per exact path including the query string. pattern: paths that differ only in numbers or long hex strings are merged (digits become {n}, hex strings {hex}) and the query string is dropped.")]
[AllowedValues("path", "pattern")]
string group_by = "pattern",
[Description("Maximum number of groups, 1 to 500.")] int limit = 50,
CancellationToken ct = default)
{
var grouping = group_by.Trim().ToLowerInvariant() switch
{
"path" => UnexplainedGrouping.Path,
"pattern" => UnexplainedGrouping.Pattern,
_ => throw new McpException("group_by must be path or pattern.")
};
var result = await queries.FindUnexplainedAsync(Since(period), grouping, limit, ct);
return new UnexplainedListResult(
Normalize(period),
group_by.Trim().ToLowerInvariant(),
result.Catches,
result.DistinctPaths,
result.Groups.Select(g => new UnexplainedItem(g.Key, g.Catches, g.ExamplePaths, g.ExampleUserAgent, g.FirstSeen, g.LastSeen)).ToList(),
result.GroupsOmitted);
}
[McpServerTool(Name = "test_explanation_rule", Title = "Test an explanation rule", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Tries a pattern against the stored catches without saving anything: how many catches match, example values, how many were unexplained before, and which existing rules would lose catches to it (a higher priority takes over). Check the examples for false positives and tighten the pattern before create_explanation_rule. Pass rule_id to test a change to an existing rule.")]
public async Task<RuleTestItem> TestRule(
[Description(KindDescription)] [AllowedValues("target", "client_info", "outcome")] string kind,
[Description(PatternDescription)] string pattern,
[Description(PriorityDescription)] int priority = 0,
[Description("Id of an existing rule that this pattern would replace; its current pattern is then ignored and catches it would no longer explain are reported.")] int? rule_id = null,
[Description(PeriodDescription)] string period = "all",
CancellationToken ct = default)
{
var parsed = ParseKind(kind);
if (rule_id is { } id && await store.GetAsync(id, ct) is null)
{
throw NotFound(id);
}
var result = await queries.TestAsync(parsed, pattern, priority, rule_id, Since(period), ct);
return new RuleTestItem(
KindName(parsed),
pattern.Trim(),
Normalize(period),
result.Catches,
result.DistinctValues,
result.Examples.Select(e => new ValueCount(e.Value, e.Catches)).ToList(),
result.NewlyExplained,
result.TakesOver.Select(t => new TakeoverItem(t.Rule.Id, t.Rule.Pattern, t.Rule.Text, t.Rule.Priority, t.Catches, t.Examples)).ToList(),
result.Lost,
result.LostExamples);
}
[McpServerTool(Name = "create_explanation_rule", Title = "Create explanation rule", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false, UseStructuredContent = true)]
[Description("Creates an explanation rule. It is active immediately and shows up in the dashboard for all matching catches, old ones included. Test the pattern with test_explanation_rule first. Needs a token with write permission.")]
public async Task<RuleItem> CreateRule(
[Description(KindDescription)] [AllowedValues("target", "client_info", "outcome")] string kind,
[Description(PatternDescription)] string pattern,
[Description(TextDescription)] string text,
[Description(PriorityDescription)] int priority = 0,
[Description(NoteDescription)] string? note = null,
CancellationToken ct = default) =>
ToItem(await store.CreateAsync(new ExplanationRuleInput(ParseKind(kind), pattern, text, priority, note), Actor(), ct), null);
[McpServerTool(Name = "update_explanation_rule", Title = "Update explanation rule", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Changes an explanation rule; only the given fields are changed. Test a new pattern with test_explanation_rule (rule_id) first. Needs a token with write permission.")]
public async Task<RuleItem> UpdateRule(
[Description("Id of the rule.")] int id,
[Description("New kind. " + KindDescription)] string? kind = null,
[Description("New pattern. " + PatternDescription)] string? pattern = null,
[Description("New text. " + TextDescription)] string? text = null,
[Description("New priority. " + PriorityDescription)] int? priority = null,
[Description(NoteDescription)] string? note = null,
CancellationToken ct = default) =>
ToItem(await store.UpdateAsync(id, new ExplanationRuleInput(kind is null ? null : ParseKind(kind), pattern, text, priority, note), ct) ?? throw NotFound(id), null);
[McpServerTool(Name = "set_explanation_rule_enabled", Title = "Enable or disable explanation rule", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Switches a rule on or off without deleting it. Needs a token with write permission.")]
public async Task<RuleItem> SetEnabled(
[Description("Id of the rule.")] int id,
[Description("true to enable, false to disable.")] bool enabled,
CancellationToken ct = default) =>
ToItem(await store.SetEnabledAsync(id, enabled, ct) ?? throw NotFound(id), null);
[McpServerTool(Name = "delete_explanation_rule", Title = "Delete explanation rule", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Permanently deletes a rule. Prefer set_explanation_rule_enabled when unsure. Needs a token with write permission.")]
public async Task<DeleteResult> DeleteRule(
[Description("Id of the rule.")] int id,
CancellationToken ct = default) =>
new(id, await store.DeleteAsync(id, ct));
private string Actor() => httpContext.HttpContext?.User.Identity?.Name is { Length: > 0 } name ? name : "MCP";
private DateTime? Since(string? period)
{
if (!QueryPeriod.TryParse(period, out var span))
{
throw new McpException($"Invalid period '{period}'. {PeriodDescription}");
}
return span is { } window ? timeProvider.GetUtcNow().UtcDateTime - window : null;
}
private static string Normalize(string? period) => string.IsNullOrWhiteSpace(period) ? "all" : period.Trim().ToLowerInvariant();
private static ExplanationKind ParseKind(string kind) => kind.Trim().ToLowerInvariant() switch
{
"target" => ExplanationKind.Target,
"client_info" => ExplanationKind.ClientInfo,
"outcome" => ExplanationKind.Outcome,
_ => throw new McpException("kind must be one of target, client_info, outcome.")
};
private static string KindName(ExplanationKind kind) => kind switch
{
ExplanationKind.Target => "target",
ExplanationKind.ClientInfo => "client_info",
_ => "outcome"
};
private static McpException NotFound(int id) => new($"There is no explanation rule with id {id}.");
private static RuleItem ToItem(ExplanationRuleEntity rule, int? catches) => new(
rule.Id,
KindName(rule.Kind),
rule.Pattern,
rule.Text,
rule.Priority,
rule.Enabled,
rule.Note,
rule.CreatedAt,
rule.UpdatedAt,
rule.CreatedBy,
catches);
}
+48 -1
View File
@@ -1,3 +1,4 @@
using System.Security.Claims;
using System.Text.Json;
using System.Text.Json.Serialization;
using Flypaper.Storage.Settings;
@@ -18,7 +19,14 @@ public static class McpExtensions
"Flypaper is an HTTP tarpit. Scanning bots that probe a server (e.g. for /.env or /wp-login.php) are " +
"answered with an endless page a few bytes at a time and held as long as possible. Every such catch is " +
"stored with its time, client IP, country, network provider (ASN), requested URL, user agent, duration " +
"and bytes sent. All tools only read that data; times are ISO 8601 UTC, durations in seconds.";
"and bytes sent. Times are ISO 8601 UTC, durations in seconds. The tools list_catches, top, longest_catches, " +
"lookup_ip and get_stats only read that data. Explanation rules turn catches into plain German sentences " +
"shown in the dashboard (what a bot wanted, with which tool, how it ended); they are matched when a catch is " +
"displayed, so a new rule also explains old catches. Use list_unexplained to find catches without an " +
"explanation, test_explanation_rule to try a pattern, and list_explanation_rules to see what exists. The tools " +
"create_explanation_rule, update_explanation_rule, set_explanation_rule_enabled and delete_explanation_rule " +
"change rules and need a token with write permission; read-only tokens do not see them. New rules are active " +
"immediately.";
private static readonly JsonSerializerOptions ToolJsonOptions = new(McpJsonUtilities.DefaultOptions)
{
@@ -29,6 +37,7 @@ public static class McpExtensions
{
services.Configure<McpOptions>(configuration.GetSection(McpOptions.SectionName));
services.AddSingleton<McpTokenService>();
services.AddHttpContextAccessor();
services.AddAuthentication()
.AddScheme<AuthenticationSchemeOptions, McpTokenAuthenticationHandler>(McpTokenAuthenticationHandler.SchemeName, null);
@@ -44,20 +53,44 @@ public static class McpExtensions
})
.WithHttpTransport(options => options.Stateless = true)
.WithTools<FlypaperTools>(ToolJsonOptions)
.WithTools<ExplanationTools>(ToolJsonOptions)
.WithRequestFilters(filters =>
{
filters.AddListToolsFilter(HideWriteTools);
filters.AddCallToolFilter(CheckCall);
});
return services;
}
private static McpRequestHandler<ListToolsRequestParams, ListToolsResult> HideWriteTools(McpRequestHandler<ListToolsRequestParams, ListToolsResult> next) =>
async (context, ct) =>
{
var result = await next(context, ct);
if (!CanWrite(context.User))
{
result.Tools = result.Tools.Where(tool => tool.Annotations?.ReadOnlyHint == true).ToList();
}
return result;
};
private static McpRequestHandler<CallToolRequestParams, CallToolResult> CheckCall(McpRequestHandler<CallToolRequestParams, CallToolResult> next) =>
async (context, ct) =>
{
var tool = context.Params?.Name;
var logger = context.Services?.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(FlypaperTools));
if (context.MatchedPrimitive is McpServerTool { ProtocolTool.Annotations.ReadOnlyHint: not true } && !CanWrite(context.User))
{
logger?.LogWarning("MCP tool {Tool} was called with a token without write permission", tool);
return new CallToolResult
{
IsError = true,
Content = [new TextContentBlock { Text = $"'{tool}' needs a token with write permission. Enable it for this token in the dashboard under Einstellungen > MCP-Zugriff." }]
};
}
if (context.MatchedPrimitive is McpServerTool matched
&& McpArgumentCheck.FindProblem(matched.ProtocolTool.InputSchema, context.Params?.Arguments?.AsReadOnly()) is { } problem)
{
@@ -76,6 +109,8 @@ public static class McpExtensions
}
};
private static bool CanWrite(ClaimsPrincipal? user) => user?.HasClaim(McpTokenAuthenticationHandler.WriteClaim, "true") == true;
private static CallToolResult InvalidArguments(string? tool, string message) => new()
{
IsError = true,
@@ -97,6 +132,18 @@ public static class McpExtensions
return Results.LocalRedirect("/settings?mcp=revoked#mcp");
});
app.MapPost("/mcp-tokens/{id:int}/write", async (int id, HttpContext context, IAntiforgery antiforgery, McpTokenStore store) =>
{
if (!await antiforgery.IsRequestValidAsync(context))
{
return Results.BadRequest();
}
var enabled = (await context.Request.ReadFormAsync(context.RequestAborted))["enabled"] == "true";
await store.SetCanWriteAsync(id, enabled, context.RequestAborted);
return Results.LocalRedirect("/settings?mcp=" + (enabled ? "write-on" : "write-off") + "#mcp");
});
return app;
}
}
+37
View File
@@ -50,3 +50,40 @@ public sealed record IpLookupResult(
DateTime? LastSeen,
IReadOnlyList<CatchItem> Events,
int EventsOmitted);
public sealed record RuleItem(
int Id,
string Kind,
string Pattern,
string Text,
int Priority,
bool Enabled,
string? Note,
DateTime CreatedAt,
DateTime UpdatedAt,
string CreatedBy,
int? Catches);
public sealed record RuleListResult(int Count, IReadOnlyList<RuleItem> Rules);
public sealed record DeleteResult(int Id, bool Deleted);
public sealed record UnexplainedItem(string Key, int Catches, IReadOnlyList<string> ExamplePaths, string? ExampleUserAgent, DateTime FirstSeen, DateTime LastSeen);
public sealed record UnexplainedListResult(string Period, string GroupBy, int UnexplainedCatches, int DistinctPaths, IReadOnlyList<UnexplainedItem> Groups, int GroupsOmitted);
public sealed record ValueCount(string Value, int Catches);
public sealed record TakeoverItem(int RuleId, string Pattern, string Text, int Priority, int Catches, IReadOnlyList<string> Examples);
public sealed record RuleTestItem(
string Kind,
string Pattern,
string Period,
int MatchedCatches,
int MatchedDistinctValues,
IReadOnlyList<ValueCount> Examples,
int NewlyExplainedCatches,
IReadOnlyList<TakeoverItem> TakesOverFrom,
int CatchesNoLongerExplained,
IReadOnlyList<string> NoLongerExplainedExamples);
@@ -13,6 +13,8 @@ public sealed class McpTokenAuthenticationHandler(
{
public const string SchemeName = "McpToken";
public const string WriteClaim = "mcp:write";
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var header = Request.Headers.Authorization.ToString();
@@ -21,12 +23,17 @@ public sealed class McpTokenAuthenticationHandler(
return AuthenticateResult.NoResult();
}
if (!await tokens.AuthenticateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted))
if (await tokens.AuthenticateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted) is not { } access)
{
return AuthenticateResult.Fail("Invalid MCP token.");
}
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "mcp")], SchemeName);
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, access.Name)], SchemeName);
if (access.CanWrite)
{
identity.AddClaim(new Claim(WriteClaim, "true"));
}
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName));
}
+9 -6
View File
@@ -6,33 +6,36 @@ using Microsoft.Extensions.Options;
namespace Flypaper.Web.Mcp;
public sealed record McpAccess(string Name, bool CanWrite);
public sealed class McpTokenService(McpTokenStore store, IOptions<McpOptions> options)
{
private const string Prefix = "fpm_";
public const string EnvironmentTokenName = "Umgebungs-Token";
public bool UsesEnvironmentToken => !string.IsNullOrEmpty(options.Value.Token);
public async Task<string> CreateAsync(string name, CancellationToken ct = default)
public async Task<string> CreateAsync(string name, bool canWrite = false, CancellationToken ct = default)
{
var token = Prefix + WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
await store.CreateAsync(name, Hash(token), ct);
await store.CreateAsync(name, Hash(token), canWrite, ct);
return token;
}
public async Task<bool> AuthenticateAsync(string? token, CancellationToken ct = default)
public async Task<McpAccess?> AuthenticateAsync(string? token, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(token))
{
return false;
return null;
}
if (UsesEnvironmentToken
&& CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(token)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Value.Token!))))
{
return true;
return new McpAccess(EnvironmentTokenName, false);
}
return await store.UseAsync(Hash(token), ct) is not null;
return await store.UseAsync(Hash(token), ct) is { } stored ? new McpAccess(stored.Name, stored.CanWrite) : null;
}
public static string Hash(string token) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
+2
View File
@@ -5,6 +5,7 @@ using Flypaper.Storage;
using Flypaper.Web;
using Flypaper.Web.Auth;
using Flypaper.Web.Components;
using Flypaper.Web.Explanations;
using Flypaper.Web.Health;
using Flypaper.Web.Mcp;
using Microsoft.AspNetCore.Authentication.Cookies;
@@ -74,6 +75,7 @@ app.MapStaticAssets().AllowAnonymous();
app.MapAuthEndpoints();
app.MapHealthEndpoint();
app.MapFlypaperMcp();
app.MapExplanationEndpoints();
app.MapRazorComponents<App>();
await app.RunAsync();
+33
View File
@@ -1645,3 +1645,36 @@ button.danger-text {
align-items: center;
gap: 6px;
}
.recent-table .explain {
color: var(--text);
white-space: normal;
}
.recent-table .explain p {
margin: 2px 0 0;
}
.recent-table .explain .muted {
color: var(--muted);
}
.inline-form {
display: inline-flex;
align-items: center;
gap: 8px;
margin: 0;
}
.rule-table td {
vertical-align: top;
}
.rule-table tr.off td {
opacity: 0.55;
}
.rule-meta {
margin-top: 2px;
font-size: 12px;
}