Add filters to the dashboard catch list and filter by clicking top 10 rows
Build and deploy / build (push) Successful in 1m30s
Build and deploy / deploy (push) Successful in 30s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-15 23:40:52 +01:00
1 parent 8eeb7894a3
commit 9f07d41cb0
11 files changed
+771 -83

No files matched your search

+7
View File
@@ -22,6 +22,13 @@ All notable changes to Flypaper are documented in this file. The format follows
24 hours, and the catch list marks them with an "Abgelehnt" badge. Outcomes are shown in 24 hours, and the catch list marks them with an "Abgelehnt" badge. Outcomes are shown in
German. Top lists and hold times still count only real catches. German. Top lists and hold times still count only real catches.
- The "Haltezeit gesamt" metric shows the average hold time per catch below it. - The "Haltezeit gesamt" metric shows the average hold time per catch below it.
- The catch list on the dashboard has filters for period, outcome, country and a free-text
search over IP, provider, target and user agent. A click on a top 10 row filters the list by
that country, provider, IP or target (a second click removes it). Active filters show as
chips with the number of matches, live in the URL (`?land=HK&ausgang=abgelehnt&q=…`) and
survive the auto-refresh; "Weitere laden" shows up to 500 entries. Metrics and top 10 stay
unfiltered.
- The outcome "Abgebrochen" is now called "Aufgegeben".
- Dashboard polish: equal metric tiles with a one-line note each (unique IPs show the last - Dashboard polish: equal metric tiles with a one-line note each (unique IPs show the last
24 hours), map and top 10 card of equal height with a larger legend and visible 24 hours), map and top 10 card of equal height with a larger legend and visible
small-country markers, country and provider names in the regular font with a separate share small-country markers, country and provider names in the regular font with a separate share
@@ -1,5 +1,3 @@
using Flypaper.Storage.Entities;
namespace Flypaper.Storage.Dashboard; namespace Flypaper.Storage.Dashboard;
public sealed record DashboardData( public sealed record DashboardData(
@@ -10,7 +8,6 @@ public sealed record DashboardData(
int UniqueIps, int UniqueIps,
int UniqueIpsLast24Hours, int UniqueIpsLast24Hours,
TimeSpan TotalHoldTime, TimeSpan TotalHoldTime,
IReadOnlyList<TrapEventEntity> Recent,
IReadOnlyList<TopEntry> TopIps, IReadOnlyList<TopEntry> TopIps,
IReadOnlyList<TopEntry> TopTargets, IReadOnlyList<TopEntry> TopTargets,
IReadOnlyList<TopEntry> TopCountries, IReadOnlyList<TopEntry> TopCountries,
@@ -6,7 +6,6 @@ namespace Flypaper.Storage.Dashboard;
public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider) public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
{ {
private const int RecentCount = 50;
private const int TopCount = 10; private const int TopCount = 10;
public async Task<DashboardData> GetAsync(CancellationToken ct = default) public async Task<DashboardData> GetAsync(CancellationToken ct = default)
@@ -41,7 +40,6 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct), await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct),
await events.Where(e => e.StartedAt >= since).Select(e => e.RemoteIp).Distinct().CountAsync(ct), await events.Where(e => e.StartedAt >= since).Select(e => e.RemoteIp).Distinct().CountAsync(ct),
TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)), TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)),
await events.OrderByDescending(e => e.Id).Take(RecentCount).ToListAsync(ct),
await TopAsync(catches.GroupBy(e => e.RemoteIp), ct), await TopAsync(catches.GroupBy(e => e.RemoteIp), ct),
await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct), await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct),
countries countries
@@ -54,6 +52,71 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
countries.ToDictionary(x => x.Key, x => x.Count, StringComparer.OrdinalIgnoreCase)); countries.ToDictionary(x => x.Key, x => x.Count, StringComparer.OrdinalIgnoreCase));
} }
public async Task<RecentCatches> GetRecentAsync(RecentFilter filter, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var events = Apply(db.TrapEvents.AsNoTracking(), filter);
var countries = await db.TrapEvents
.Where(e => e.CountryCode != null)
.GroupBy(e => e.CountryCode!)
.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);
}
private IQueryable<TrapEventEntity> Apply(IQueryable<TrapEventEntity> events, RecentFilter filter)
{
if (filter.Window is { } window)
{
var since = timeProvider.GetUtcNow().UtcDateTime - window;
events = events.Where(e => e.StartedAt >= since);
}
if (filter.Outcome is { } outcome)
{
events = events.Where(e => e.Outcome == outcome);
}
if (filter.CountryCode is { } country)
{
events = events.Where(e => e.CountryCode == country);
}
if (filter.Asn is { } asn)
{
events = events.Where(e => e.Asn == asn);
}
if (filter.Ip is { } ip)
{
events = events.Where(e => e.RemoteIp == ip);
}
if (filter.Target is { } target)
{
events = events.Where(e => e.Target == target);
}
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var pattern = $"%{filter.Search.Trim().Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_")}%";
events = events.Where(e =>
EF.Functions.Like(e.RemoteIp, pattern, "\\")
|| EF.Functions.Like(e.Provider!, pattern, "\\")
|| EF.Functions.Like(e.Target!, pattern, "\\")
|| EF.Functions.Like(e.ClientInfo!, pattern, "\\"));
}
return events;
}
private static async Task<IReadOnlyList<TopEntry>> TopAsync( private static async Task<IReadOnlyList<TopEntry>> TopAsync(
IQueryable<IGrouping<string, TrapEventEntity>> groups, IQueryable<IGrouping<string, TrapEventEntity>> groups,
CancellationToken ct) CancellationToken ct)
@@ -0,0 +1,22 @@
using Flypaper.Core.Models;
using Flypaper.Storage.Entities;
namespace Flypaper.Storage.Dashboard;
public sealed record RecentFilter(
TimeSpan? Window = null,
TrapOutcome? Outcome = null,
string? CountryCode = null,
long? Asn = null,
string? Ip = null,
string? Target = null,
string? Search = null,
int Limit = RecentFilter.DefaultLimit)
{
public const int DefaultLimit = 50;
public const int MaxLimit = 500;
}
public sealed record RecentCatches(IReadOnlyList<TrapEventEntity> Items, int Total, IReadOnlyList<CountryOption> Countries);
public sealed record CountryOption(string Code, string? Name);
@@ -0,0 +1,120 @@
using System.Globalization;
using System.Net;
using Flypaper.Core.Models;
using Flypaper.Storage.Dashboard;
namespace Flypaper.Web.Components.Pages.Dashboard;
public sealed record DashboardFilter(
string? Zeit = null,
string? Ausgang = null,
string? Land = null,
string? Provider = null,
string? Ip = null,
string? Ziel = null,
string? Q = null,
int Limit = RecentFilter.DefaultLimit)
{
public const string Anchor = "faenge";
public static readonly IReadOnlyList<(string Value, string Label)> Periods = [("", "Alles"), ("24h", "24 h"), ("7d", "7 Tage")];
public static readonly IReadOnlyList<(string Value, string Label)> Outcomes =
[("", "Alle"), ("aufgegeben", "Aufgegeben"), ("zeitlimit", "Zeitlimit"), ("abgelehnt", "Abgelehnt")];
public bool IsEmpty => this with { Limit = RecentFilter.DefaultLimit } == new DashboardFilter();
public static DashboardFilter Parse(
string? zeit,
string? ausgang,
string? land,
string? provider,
string? ip,
string? ziel,
string? q,
string? limit)
{
var parsedLimit = int.TryParse(limit, NumberStyles.None, CultureInfo.InvariantCulture, out var value)
? Math.Clamp(value, 1, RecentFilter.MaxLimit)
: RecentFilter.DefaultLimit;
return new DashboardFilter(
Known(Periods, zeit),
Known(Outcomes, ausgang),
Clean(land) is { Length: 2 } country && country.All(char.IsAsciiLetter) ? country.ToUpperInvariant() : null,
Asn(provider) is { } asn ? $"AS{asn.ToString(CultureInfo.InvariantCulture)}" : null,
IPAddress.TryParse(Clean(ip), out var address) ? address.ToString() : null,
Clean(ziel),
Clean(q),
parsedLimit);
}
public RecentFilter ToRecentFilter() => new(
Zeit switch
{
"24h" => TimeSpan.FromHours(24),
"7d" => TimeSpan.FromDays(7),
_ => null
},
Ausgang switch
{
"aufgegeben" => TrapOutcome.ClientAborted,
"zeitlimit" => TrapOutcome.Timeout,
"abgelehnt" => TrapOutcome.Rejected,
_ => null
},
Land,
Asn(Provider),
Ip,
Ziel,
Q,
Limit);
public int NextLimit => Math.Min(Limit * 2, RecentFilter.MaxLimit);
public string Href(string anchor = Anchor)
{
var parts = new List<string>();
Add(parts, "zeit", Zeit);
Add(parts, "ausgang", Ausgang);
Add(parts, "land", Land);
Add(parts, "provider", Provider);
Add(parts, "ip", Ip);
Add(parts, "ziel", Ziel);
Add(parts, "q", Q);
if (Limit != RecentFilter.DefaultLimit)
{
Add(parts, "limit", Limit.ToString(CultureInfo.InvariantCulture));
}
return parts.Count == 0 ? $"/#{anchor}" : $"/?{string.Join("&", parts)}#{anchor}";
}
private static void Add(List<string> parts, string name, string? value)
{
if (!string.IsNullOrEmpty(value))
{
parts.Add($"{name}={Uri.EscapeDataString(value)}");
}
}
private static string? Known(IReadOnlyList<(string Value, string Label)> options, string? value)
{
var clean = Clean(value)?.ToLowerInvariant();
return clean is not null && options.Any(o => o.Value == clean) ? clean : null;
}
private static long? Asn(string? value)
{
var clean = Clean(value);
if (clean is null)
{
return null;
}
var digits = clean.StartsWith("AS", StringComparison.OrdinalIgnoreCase) ? clean[2..] : clean;
return long.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out var asn) ? asn : null;
}
private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
@@ -67,7 +67,10 @@
<section class="origin"> <section class="origin">
<WorldMap CatchesByCountry="data.CatchesByCountry" /> <WorldMap CatchesByCountry="data.CatchesByCountry" />
<section class="card tops-card"> <section class="card tops-card">
<h2 id="tops-title">Top 10</h2> <div class="card-head">
<h2 id="tops-title">Top 10</h2>
<span class="hint">Klick filtert die Fänge</span>
</div>
<div class="tabs" role="tablist" aria-labelledby="tops-title"> <div class="tabs" role="tablist" aria-labelledby="tops-title">
@foreach (var tab in tabs) @foreach (var tab in tabs)
{ {
@@ -78,73 +81,148 @@
@foreach (var tab in tabs) @foreach (var tab in tabs)
{ {
<div role="tabpanel" id="panel-@tab.Id" aria-labelledby="tab-@tab.Id" tabindex="0" hidden="@(tab != tabs[0])"> <div role="tabpanel" id="panel-@tab.Id" aria-labelledby="tab-@tab.Id" tabindex="0" hidden="@(tab != tabs[0])">
<TopTable KeyLabel="@tab.KeyLabel" Entries="tab.Entries" ShowFlags="tab.ShowFlags" KeyFormatter="tab.KeyFormatter" LabelFormatter="tab.LabelFormatter" /> <TopTable KeyLabel="@tab.KeyLabel" Entries="tab.Entries" ShowFlags="tab.ShowFlags" KeyFormatter="tab.KeyFormatter" LabelFormatter="tab.LabelFormatter"
Href="entry => TopFilter(tab, entry).Href()" IsActive="entry => tab.Current(_filter) == entry.Key" />
</div> </div>
} }
</section> </section>
</section> </section>
@if (data.TotalCatches > 0) @if (data.TotalCatches > 0 || data.Rejected > 0)
{ {
<section class="card"> var recent = _recent!;
<section class="card recent-card" id="@DashboardFilter.Anchor">
<div class="card-head"> <div class="card-head">
<h2>Letzte 50 Fänge</h2> <h2>Fänge <span class="count">· @Formatting.Number(recent.Total) Treffer</span></h2>
<span class="hint">Zeile anklicken zum Aufklappen</span> <span class="hint">Filter gelten nur für diese Liste</span>
</div> </div>
<div class="scroll"> <form class="filters" method="get" action="/#@DashboardFilter.Anchor">
<table class="recent-table"> <label>
<thead> <span>Zeitraum</span>
<tr> <select name="zeit" data-autosubmit>
<th class="c-time">Zeit</th> @foreach (var (value, label) in DashboardFilter.Periods)
<th class="c-ip">IP</th>
<th class="c-origin">Herkunft</th>
<th class="c-provider">Provider</th>
<th class="c-target">Ziel</th>
<th class="c-agent">User-Agent</th>
<th class="c-duration num">Dauer</th>
<th class="c-bytes num">Bytes</th>
<th class="c-outcome">Ausgang</th>
</tr>
</thead>
<tbody>
@foreach (var trapEvent in data.Recent)
{ {
var started = trapEvent.StartedAt.ToLocalTime(); <option value="@value" selected="@(value == (_filter.Zeit ?? ""))">@label</option>
var provider = Formatting.Provider(trapEvent.Asn, trapEvent.Provider);
var target = Formatting.Target(trapEvent.Target);
var duration = Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs));
var bytes = Formatting.Number(trapEvent.BytesSent);
<tr 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>
<td class="c-origin" title="@Origin(trapEvent)">
@if (trapEvent.CountryCode is { } countryCode)
{
@($"{Formatting.Flag(countryCode)} {countryCode}")
}
else
{
<span class="muted">–</span>
}
</td>
<td class="c-provider" title="@provider">@provider</td>
<td class="c-target mono" title="@target">
@target
<div class="extra extra-md">Provider: @(provider ?? "–")</div>
<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-xs">Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @OutcomeLabel(trapEvent.Outcome)</div>
</td>
<td class="c-agent" title="@trapEvent.ClientInfo">@trapEvent.ClientInfo</td>
<td class="c-duration num">@duration</td>
<td class="c-bytes num">@bytes</td>
<td class="c-outcome"><span class="outcome @trapEvent.Outcome.ToString().ToLowerInvariant()">@OutcomeLabel(trapEvent.Outcome)</span></td>
</tr>
} }
</tbody> </select>
</table> </label>
</div> <label>
<span>Ausgang</span>
<select name="ausgang" data-autosubmit>
@foreach (var (value, label) in DashboardFilter.Outcomes)
{
<option value="@value" selected="@(value == (_filter.Ausgang ?? ""))">@label</option>
}
</select>
</label>
<label>
<span>Land</span>
<select name="land" data-autosubmit>
<option value="" selected="@(_filter.Land is null)">Alle</option>
@foreach (var country in recent.Countries.OrderBy(c => CountryNames.Display(c.Code, c.Name), StringComparer.CurrentCulture))
{
<option value="@country.Code" selected="@(country.Code == _filter.Land)">@Formatting.Flag(country.Code) @CountryNames.Display(country.Code, country.Name)</option>
}
</select>
</label>
<label class="filter-search">
<span>Suche</span>
<input type="search" name="q" value="@_filter.Q" placeholder="IP, Provider, Ziel, User-Agent" />
</label>
@foreach (var (name, value) in new[] { ("provider", _filter.Provider), ("ip", _filter.Ip), ("ziel", _filter.Ziel) })
{
if (value is not null)
{
<input type="hidden" name="@name" value="@value" />
}
}
<button type="submit">Filtern</button>
</form>
@if (!_filter.IsEmpty)
{
<div class="chips">
@foreach (var (label, without) in Chips())
{
<a class="chip" href="@without.Href()" title="Filter entfernen">@label <span aria-hidden="true">✕</span></a>
}
<a class="chip-reset" href="@(new DashboardFilter().Href())">Alle Filter zurücksetzen</a>
</div>
}
@if (recent.Items.Count == 0)
{
<p class="empty">Keine Fänge für diese Filter. <a href="@(new DashboardFilter().Href())">Filter zurücksetzen</a></p>
}
else
{
<div class="scroll">
<table class="recent-table">
<thead>
<tr>
<th class="c-time">Zeit</th>
<th class="c-ip">IP</th>
<th class="c-origin">Herkunft</th>
<th class="c-provider">Provider</th>
<th class="c-target">Ziel</th>
<th class="c-agent">User-Agent</th>
<th class="c-duration num">Dauer</th>
<th class="c-bytes num">Bytes</th>
<th class="c-outcome">Ausgang</th>
</tr>
</thead>
<tbody>
@foreach (var (trapEvent, index) in recent.Items.Select((trapEvent, index) => (trapEvent, index)))
{
var started = trapEvent.StartedAt.ToLocalTime();
var provider = Formatting.Provider(trapEvent.Asn, trapEvent.Provider);
var target = Formatting.Target(trapEvent.Target);
var duration = Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs));
var bytes = Formatting.Number(trapEvent.BytesSent);
<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>
<td class="c-origin" title="@Origin(trapEvent)">
@if (trapEvent.CountryCode is { } countryCode)
{
@($"{Formatting.Flag(countryCode)} {countryCode}")
}
else
{
<span class="muted">–</span>
}
</td>
<td class="c-provider" title="@provider">@provider</td>
<td class="c-target mono" title="@target">
@target
<div class="extra extra-md">Provider: @(provider ?? "–")</div>
<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-xs">Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @OutcomeLabel(trapEvent.Outcome)</div>
</td>
<td class="c-agent" title="@trapEvent.ClientInfo">@trapEvent.ClientInfo</td>
<td class="c-duration num">@duration</td>
<td class="c-bytes num">@bytes</td>
<td class="c-outcome"><span class="outcome @trapEvent.Outcome.ToString().ToLowerInvariant()">@OutcomeLabel(trapEvent.Outcome)</span></td>
</tr>
}
</tbody>
</table>
</div>
@if (recent.Total > recent.Items.Count)
{
<div class="more">
<span class="muted">@Formatting.Number(recent.Items.Count) von @Formatting.Number(recent.Total)</span>
@if (_filter.Limit < RecentFilter.MaxLimit)
{
<a class="button ghost" href="@((_filter with { Limit = _filter.NextLimit }).Href($"f{recent.Items.Count}"))">Weitere laden</a>
}
else
{
<span class="muted">· Für ältere Fänge die Filter eingrenzen</span>
}
</div>
}
}
</section> </section>
} }
} }
@@ -153,26 +231,91 @@
@code { @code {
private DashboardData? _data; private DashboardData? _data;
private RecentCatches? _recent;
private DashboardFilter _filter = new();
private DateTime _loadedAt; private DateTime _loadedAt;
[SupplyParameterFromQuery(Name = "zeit")] public string? Zeit { get; set; }
[SupplyParameterFromQuery(Name = "ausgang")] public string? Ausgang { get; set; }
[SupplyParameterFromQuery(Name = "land")] public string? Land { get; set; }
[SupplyParameterFromQuery(Name = "provider")] public string? Provider { get; set; }
[SupplyParameterFromQuery(Name = "ip")] public string? Ip { get; set; }
[SupplyParameterFromQuery(Name = "ziel")] public string? Ziel { get; set; }
[SupplyParameterFromQuery(Name = "q")] public string? Q { get; set; }
[SupplyParameterFromQuery(Name = "limit")] public string? Limit { get; set; }
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
_filter = DashboardFilter.Parse(Zeit, Ausgang, Land, Provider, Ip, Ziel, Q, Limit);
_data = await Queries.GetAsync(); _data = await Queries.GetAsync();
_recent = await Queries.GetRecentAsync(_filter.ToRecentFilter());
_loadedAt = DateTime.Now; _loadedAt = DateTime.Now;
} }
private static IReadOnlyList<TopTab> TopTabs(DashboardData data) => private static IReadOnlyList<TopTab> TopTabs(DashboardData data) =>
[ [
new("countries", "Länder", "Land", data.TopCountries, ShowFlags: true, LabelFormatter: CountryNames.Display), new("countries", "Länder", "Land", data.TopCountries, f => f.Land, (f, key) => f with { Land = key }, ShowFlags: true, LabelFormatter: CountryNames.Display),
new("providers", "Provider", "Provider", data.TopProviders), new("providers", "Provider", "Provider", data.TopProviders, f => f.Provider, (f, key) => f with { Provider = key }),
new("ips", "IPs", "IP", data.TopIps), new("ips", "IPs", "IP", data.TopIps, f => f.Ip, (f, key) => f with { Ip = key }),
new("targets", "Ziele", "Ziel", data.TopTargets, KeyFormatter: Formatting.Target) new("targets", "Ziele", "Ziel", data.TopTargets, f => f.Ziel, (f, key) => f with { Ziel = key }, KeyFormatter: Formatting.Target)
]; ];
private DashboardFilter TopFilter(TopTab tab, TopEntry entry) =>
tab.Set(_filter with { Limit = RecentFilter.DefaultLimit }, tab.Current(_filter) == entry.Key ? null : entry.Key);
private IEnumerable<(string Label, DashboardFilter Without)> Chips()
{
var reset = _filter with { Limit = RecentFilter.DefaultLimit };
if (_filter.Zeit is { } zeit)
{
yield return ($"Zeitraum: {DashboardFilter.Periods.First(p => p.Value == zeit).Label}", reset with { Zeit = null });
}
if (_filter.Ausgang is { } ausgang)
{
yield return ($"Ausgang: {DashboardFilter.Outcomes.First(o => o.Value == ausgang).Label}", reset with { Ausgang = null });
}
if (_filter.Land is { } land)
{
var name = _recent?.Countries.FirstOrDefault(c => c.Code == land)?.Name;
yield return ($"Land: {CountryNames.Display(land, name)}", reset with { Land = null });
}
if (_filter.Provider is { } provider)
{
var name = _data?.TopProviders.FirstOrDefault(p => p.Key == provider)?.Label
?? _recent?.Items.FirstOrDefault()?.Provider;
yield return ($"Provider: {(name is null ? provider : $"{name} ({provider})")}", reset with { Provider = null });
}
if (_filter.Ip is { } ip)
{
yield return ($"IP: {ip}", reset with { Ip = null });
}
if (_filter.Ziel is { } ziel)
{
yield return ($"Ziel: {Formatting.Target(ziel)}", reset with { Ziel = null });
}
if (_filter.Q is { } q)
{
yield return ($"Suche: „{q}“", reset with { Q = null });
}
}
private static string OutcomeLabel(TrapOutcome outcome) => outcome switch private static string OutcomeLabel(TrapOutcome outcome) => outcome switch
{ {
TrapOutcome.Timeout => "Zeitlimit", TrapOutcome.Timeout => "Zeitlimit",
TrapOutcome.ClientAborted => "Abgebrochen", TrapOutcome.ClientAborted => "Aufgegeben",
TrapOutcome.Rejected => "Abgelehnt", TrapOutcome.Rejected => "Abgelehnt",
TrapOutcome.Completed => "Beendet", TrapOutcome.Completed => "Beendet",
_ => outcome.ToString() _ => outcome.ToString()
@@ -186,6 +329,8 @@
string Label, string Label,
string KeyLabel, string KeyLabel,
IReadOnlyList<TopEntry> Entries, IReadOnlyList<TopEntry> Entries,
Func<DashboardFilter, string?> Current,
Func<DashboardFilter, string?, DashboardFilter> Set,
bool ShowFlags = false, bool ShowFlags = false,
Func<string?, string?>? KeyFormatter = null, Func<string?, string?>? KeyFormatter = null,
Func<string?, string?, string?>? LabelFormatter = null); Func<string?, string?, string?>? LabelFormatter = null);
@@ -28,21 +28,25 @@ else
var key = KeyFormatter?.Invoke(entry.Key) ?? entry.Key; var key = KeyFormatter?.Invoke(entry.Key) ?? entry.Key;
var label = LabelFormatter is null ? entry.Label : LabelFormatter(entry.Key, entry.Label); var label = LabelFormatter is null ? entry.Label : LabelFormatter(entry.Key, entry.Label);
var share = (entry.Count * 100.0 / Entries[0].Count).ToString("0.#", CultureInfo.InvariantCulture); var share = (entry.Count * 100.0 / Entries[0].Count).ToString("0.#", CultureInfo.InvariantCulture);
<tr data-expand="@($"{KeyLabel}:{entry.Key}")" tabindex="0" aria-expanded="false"> var active = IsActive(entry);
<td class="clip" title="@(label is null ? key : $"{label} · {key}")"> var title = label is null ? key : $"{label} · {key}";
@if (ShowFlags) <tr data-href="@Href(entry)" class="@(active ? "active" : null)">
{ <td class="clip" title="@title">
<span class="flag">@Formatting.Flag(entry.Key)</span> <a href="@Href(entry)" aria-current="@(active ? "true" : null)" title="@(active ? $"Filter {title} entfernen" : $"Fänge filtern: {title}")">
} @if (ShowFlags)
@if (label is not null) {
{ <span class="flag">@Formatting.Flag(entry.Key)</span>
<span class="top-label">@label</span> }
<span class="top-key mono">@key</span> @if (label is not null)
} {
else <span class="top-label">@label</span>
{ <span class="top-key mono">@key</span>
<span class="mono">@key</span> }
} else
{
<span class="mono">@key</span>
}
</a>
</td> </td>
<td><span class="share-bar" style="--share: @(share)%"></span></td> <td><span class="share-bar" style="--share: @(share)%"></span></td>
<td class="num">@Formatting.Number(entry.Count)</td> <td class="num">@Formatting.Number(entry.Count)</td>
@@ -63,4 +67,8 @@ else
[Parameter] public Func<string?, string?>? KeyFormatter { get; set; } [Parameter] public Func<string?, string?>? KeyFormatter { get; set; }
[Parameter] public Func<string?, string?, string?>? LabelFormatter { get; set; } [Parameter] public Func<string?, string?, string?>? LabelFormatter { get; set; }
[Parameter, EditorRequired] public required Func<TopEntry, string> Href { get; set; }
[Parameter, EditorRequired] public required Func<TopEntry, bool> IsActive { get; set; }
} }
+154
View File
@@ -266,6 +266,143 @@ code {
font-size: 12px; font-size: 12px;
} }
.top-table tr[data-href] {
cursor: pointer;
}
.top-table tr[data-href]:hover td {
background-color: color-mix(in srgb, var(--text) 4%, transparent);
}
.top-table tr.active td {
background-color: color-mix(in srgb, var(--accent) 12%, transparent);
}
.top-table tr.active td:first-child {
box-shadow: inset 3px 0 0 var(--accent);
}
.top-table td a {
color: inherit;
text-decoration: none;
}
.top-table td a:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: 3px;
}
.recent-card {
scroll-margin-top: 16px;
}
.recent-card h2 .count {
color: var(--muted);
font-weight: 500;
}
.recent-table tr[id] {
scroll-margin-top: 80px;
}
.filters {
display: grid;
grid-template-columns: minmax(110px, 140px) minmax(120px, 150px) minmax(160px, 230px) minmax(180px, 1fr) auto;
gap: 10px;
align-items: end;
margin-bottom: 12px;
}
.filters label {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
color: var(--muted);
font-size: 12px;
font-weight: 500;
}
.filters button {
border: 1px solid var(--border);
background: var(--surface);
color: var(--text);
font-weight: 500;
}
.filters button:hover {
border-color: var(--accent);
}
.filters select,
.filters input {
padding: 7px 10px;
font-size: 13px;
}
.chips {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 8px;
margin-bottom: 12px;
}
.chip {
display: inline-flex;
align-items: center;
gap: 6px;
max-width: 100%;
padding: 3px 6px 3px 10px;
overflow: hidden;
border: 1px solid color-mix(in srgb, var(--accent) 45%, var(--border));
border-radius: 999px;
background: color-mix(in srgb, var(--accent) 10%, transparent);
color: var(--text);
font-size: 12.5px;
text-decoration: none;
white-space: nowrap;
text-overflow: ellipsis;
}
.chip span {
color: var(--muted);
font-size: 11px;
}
.chip:hover span {
color: var(--text);
}
.chip-reset {
color: var(--muted);
font-size: 12.5px;
}
.more {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 12px;
padding-top: 14px;
}
a.button {
display: inline-block;
padding: 7px 14px;
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text);
font-weight: 500;
text-decoration: none;
}
a.button:hover {
border-color: var(--accent);
}
.share-bar { .share-bar {
display: block; display: block;
height: 6px; height: 6px;
@@ -823,6 +960,14 @@ button.danger {
.origin { .origin {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
} }
.filters {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.filter-search {
grid-column: 1 / 3;
}
} }
@media (max-width: 599px) { @media (max-width: 599px) {
@@ -843,6 +988,15 @@ button.danger {
font-size: 24px; font-size: 24px;
} }
.filters {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.filter-search,
.filters button {
grid-column: 1 / -1;
}
.top-table .share, .top-table .share,
.top-table th:nth-child(2), .top-table th:nth-child(2),
.top-table td:nth-child(2), .top-table td:nth-child(2),
+26
View File
@@ -108,3 +108,29 @@
}); });
} }
})(); })();
(() => {
const form = document.querySelector("form.filters");
if (form) {
form.addEventListener("submit", () => {
for (const field of form.elements) {
if (field.name && field.value === "") {
field.disabled = true;
}
}
});
for (const select of form.querySelectorAll("select[data-autosubmit]")) {
select.addEventListener("change", () => form.requestSubmit());
}
}
for (const row of document.querySelectorAll("tr[data-href]")) {
row.addEventListener("click", event => {
if (event.target.closest("a") || !window.getSelection()?.isCollapsed) {
return;
}
window.location.href = row.dataset.href;
});
}
})();
@@ -0,0 +1,79 @@
using Flypaper.Core.Models;
using Flypaper.Storage.Dashboard;
using Flypaper.Tests.Fakes;
using Flypaper.Tests.Mcp;
using Shouldly;
namespace Flypaper.Tests.Storage;
public sealed class RecentCatchesTests : IDisposable
{
private readonly McpTestData _data = new();
private readonly DashboardQueries _queries;
public RecentCatchesTests() => _queries = new DashboardQueries(_data.Factory, new FixedTimeProvider(McpTestData.Now));
[Fact]
public async Task Without_filters_returns_all_events_newest_first()
{
var recent = await _queries.GetRecentAsync(new RecentFilter());
recent.Total.ShouldBe(6);
recent.Items.Select(e => e.StartedAt).ShouldBeInOrder(SortDirection.Descending);
recent.Countries.Select(c => c.Code).ShouldBe(["CN", "TW", "US"], ignoreOrder: true);
}
[Fact]
public async Task Combines_filters()
{
var recent = await _queries.GetRecentAsync(new RecentFilter(Window: TimeSpan.FromHours(24), CountryCode: "TW", Outcome: TrapOutcome.Rejected));
recent.Total.ShouldBe(1);
recent.Items.ShouldHaveSingleItem().RemoteIp.ShouldBe("198.51.100.7");
}
[Theory]
[InlineData(4134L, null, null, 2)]
[InlineData(null, "203.0.113.9", null, 2)]
[InlineData(null, null, "GET /.env", 2)]
[InlineData(4134L, null, "GET /.env", 1)]
public async Task Matches_provider_ip_and_target_exactly(long? asn, string? ip, string? target, int expected)
{
var recent = await _queries.GetRecentAsync(new RecentFilter(Asn: asn, Ip: ip, Target: target));
recent.Total.ShouldBe(expected);
}
[Theory]
[InlineData("chinanet", 2)]
[InlineData("CURL", 2)]
[InlineData("198.51", 2)]
[InlineData("wp-login", 1)]
[InlineData("100%", 0)]
public async Task Search_is_case_insensitive_over_ip_provider_target_and_user_agent(string search, int expected)
{
var recent = await _queries.GetRecentAsync(new RecentFilter(Search: search));
recent.Total.ShouldBe(expected);
}
[Fact]
public async Task Returns_an_empty_result_when_nothing_matches()
{
var recent = await _queries.GetRecentAsync(new RecentFilter(CountryCode: "US", Outcome: TrapOutcome.Rejected));
recent.Total.ShouldBe(0);
recent.Items.ShouldBeEmpty();
}
[Fact]
public async Task Limits_the_items_but_counts_all_matches()
{
var recent = await _queries.GetRecentAsync(new RecentFilter(Limit: 2));
recent.Items.Count.ShouldBe(2);
recent.Total.ShouldBe(6);
}
public void Dispose() => _data.Dispose();
}
@@ -0,0 +1,67 @@
using Flypaper.Core.Models;
using Flypaper.Storage.Dashboard;
using Flypaper.Web.Components.Pages.Dashboard;
using Shouldly;
namespace Flypaper.Tests.Web;
public sealed class DashboardFilterTests
{
[Fact]
public void Parses_all_parameters()
{
var filter = DashboardFilter.Parse("24h", "Abgelehnt", "hk", "as4134", " 203.0.113.9 ", "GET /.env", " wp ", "100");
filter.ShouldBe(new DashboardFilter("24h", "abgelehnt", "HK", "AS4134", "203.0.113.9", "GET /.env", "wp", 100));
filter.ToRecentFilter().ShouldBe(new RecentFilter(TimeSpan.FromHours(24), TrapOutcome.Rejected, "HK", 4134, "203.0.113.9", "GET /.env", "wp", 100));
}
[Theory]
[InlineData("aufgegeben", TrapOutcome.ClientAborted)]
[InlineData("zeitlimit", TrapOutcome.Timeout)]
[InlineData("abgelehnt", TrapOutcome.Rejected)]
public void Maps_outcomes(string value, TrapOutcome expected) =>
DashboardFilter.Parse(null, value, null, null, null, null, null, null).ToRecentFilter().Outcome.ShouldBe(expected);
[Fact]
public void Ignores_invalid_values()
{
var filter = DashboardFilter.Parse("gestern", "kaputt", "Hongkong", "Chinanet", "not-an-ip", " ", "", "viele");
filter.ShouldBe(new DashboardFilter());
filter.IsEmpty.ShouldBeTrue();
filter.ToRecentFilter().ShouldBe(new RecentFilter());
}
[Theory]
[InlineData("0", 1)]
[InlineData("100000", RecentFilter.MaxLimit)]
[InlineData(null, RecentFilter.DefaultLimit)]
public void Clamps_the_limit(string? limit, int expected) =>
DashboardFilter.Parse(null, null, null, null, null, null, null, limit).Limit.ShouldBe(expected);
[Fact]
public void Builds_links_without_defaults_and_with_escaping()
{
new DashboardFilter().Href().ShouldBe("/#faenge");
new DashboardFilter(Land: "CN", Ziel: "GET example.com/a&b", Limit: 100).Href("f50")
.ShouldBe("/?land=CN&ziel=GET%20example.com%2Fa%26b&limit=100#f50");
}
[Fact]
public void Links_round_trip()
{
var filter = new DashboardFilter("7d", "zeitlimit", "TW", "AS3462", "2001:db8::1", "POST /xmlrpc.php", "curl", 200);
var query = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(new Uri("http://x" + filter.Href()).Query);
DashboardFilter.Parse(query["zeit"], query["ausgang"], query["land"], query["provider"], query["ip"], query["ziel"], query["q"], query["limit"])
.ShouldBe(filter);
}
[Fact]
public void Doubles_the_limit_up_to_the_maximum()
{
new DashboardFilter().NextLimit.ShouldBe(100);
new DashboardFilter(Limit: 400).NextLimit.ShouldBe(RecentFilter.MaxLimit);
}
}