Compare commits
6
Commits
f5bcc55a29
..
v0.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13a78f4268 | ||
|
|
9f07d41cb0 | ||
|
|
8eeb7894a3 | ||
|
|
e86518cab1 | ||
|
|
570ac20a5c | ||
|
|
393ebcdf0c |
No files matched your search
+40
-1
@@ -6,6 +6,43 @@ All notable changes to Flypaper are documented in this file. The format follows
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.4.0] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- MCP results now include fields whose value is `null` (e.g. `since` of `get_stats` with
|
||||
`period=all`, a missing label in `top`) instead of leaving them out, so they match the
|
||||
tools' output schemas.
|
||||
- MCP tools answer unknown or missing parameters with a readable error instead of
|
||||
"An error occurred invoking …" or silently ignoring them, e.g. `unknown parameter 'by';
|
||||
expected 'dimension' (ips|countries|providers|targets|user_agents)`. `top` lists the allowed
|
||||
values of `dimension` in its input schema. Invalid arguments are logged as warnings.
|
||||
|
||||
### Changed
|
||||
|
||||
- Rejected connections stand out on the dashboard: the "Abgelehnt" metric shows the last
|
||||
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.
|
||||
- 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
|
||||
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
|
||||
column, and German number formats throughout (e.g. `1.675` bytes, `15.11. 20:01:50`).
|
||||
|
||||
## [0.3.1] - 2026-11-15
|
||||
|
||||
### Changed
|
||||
|
||||
- The dashboard's top 10 lists share one card with tabs (Länder, Provider, IPs, Ziele); the
|
||||
selected tab survives the auto-refresh.
|
||||
|
||||
## [0.3.0] - 2026-11-15
|
||||
|
||||
### Added
|
||||
@@ -85,7 +122,9 @@ First release.
|
||||
- Unraid Docker template; when started as root, the container hands `/data` to its app user
|
||||
and drops privileges.
|
||||
|
||||
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.3.0...main
|
||||
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.4.0...main
|
||||
[0.4.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.4.0
|
||||
[0.3.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.3.1
|
||||
[0.3.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.3.0
|
||||
[0.2.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.2.0
|
||||
[0.1.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.1.1
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
using Flypaper.Storage.Entities;
|
||||
|
||||
namespace Flypaper.Storage.Dashboard;
|
||||
|
||||
public sealed record DashboardData(
|
||||
int TotalCatches,
|
||||
int CatchesLast24Hours,
|
||||
int Rejected,
|
||||
int RejectedLast24Hours,
|
||||
int UniqueIps,
|
||||
int UniqueIpsLast24Hours,
|
||||
TimeSpan TotalHoldTime,
|
||||
IReadOnlyList<TrapEventEntity> Recent,
|
||||
IReadOnlyList<TopEntry> TopIps,
|
||||
IReadOnlyList<TopEntry> TopTargets,
|
||||
IReadOnlyList<TopEntry> TopCountries,
|
||||
|
||||
@@ -6,7 +6,6 @@ namespace Flypaper.Storage.Dashboard;
|
||||
|
||||
public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
|
||||
{
|
||||
private const int RecentCount = 50;
|
||||
private const int TopCount = 10;
|
||||
|
||||
public async Task<DashboardData> GetAsync(CancellationToken ct = default)
|
||||
@@ -37,9 +36,10 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
|
||||
await catches.CountAsync(ct),
|
||||
await catches.CountAsync(e => e.StartedAt >= since, ct),
|
||||
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct),
|
||||
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected && e.StartedAt >= since, ct),
|
||||
await events.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)),
|
||||
await events.OrderByDescending(e => e.Id).Take(RecentCount).ToListAsync(ct),
|
||||
await TopAsync(catches.GroupBy(e => e.RemoteIp), ct),
|
||||
await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct),
|
||||
countries
|
||||
@@ -52,6 +52,71 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
|
||||
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(
|
||||
IQueryable<IGrouping<string, TrapEventEntity>> groups,
|
||||
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();
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
@page "/"
|
||||
@using Flypaper.Core.Abstractions
|
||||
@using Flypaper.Core.Models
|
||||
@using Flypaper.Http
|
||||
@using Microsoft.Extensions.Options
|
||||
@using Flypaper.Storage.Dashboard
|
||||
@@ -21,29 +22,32 @@
|
||||
@if (_data is { } data)
|
||||
{
|
||||
var active = Governor.ActiveConnections;
|
||||
var tabs = TopTabs(data);
|
||||
<section class="metrics">
|
||||
<div class="metric metric-hero @(active > 0 ? "live" : null)">
|
||||
<div class="metric @(active > 0 ? "live" : null)">
|
||||
<span class="label">Gerade in der Falle</span>
|
||||
<span class="value">@active.ToString("N0")</span>
|
||||
<span class="sub">@(active == 1 ? "Bot wird festgehalten" : "Bots werden festgehalten")</span>
|
||||
<span class="value">@Formatting.Number(active)</span>
|
||||
<span class="sub">@(active == 1 ? "Bot festgehalten" : "Bots festgehalten")</span>
|
||||
</div>
|
||||
<div class="metric metric-hero">
|
||||
<div class="metric">
|
||||
<span class="label">Fänge gesamt</span>
|
||||
<span class="value">@data.TotalCatches.ToString("N0")</span>
|
||||
<span class="sub">+@data.CatchesLast24Hours.ToString("N0") in den letzten 24 h</span>
|
||||
<span class="value">@Formatting.Number(data.TotalCatches)</span>
|
||||
<span class="sub">+@Formatting.Number(data.CatchesLast24Hours) in 24 h</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="label">Eindeutige IPs</span>
|
||||
<span class="value">@data.UniqueIps.ToString("N0")</span>
|
||||
<span class="value">@Formatting.Number(data.UniqueIps)</span>
|
||||
<span class="sub">@Formatting.Number(data.UniqueIpsLast24Hours) in 24 h aktiv</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="label">Haltezeit gesamt</span>
|
||||
<span class="value">@Formatting.Duration(data.TotalHoldTime)</span>
|
||||
<span class="sub">Ø @(data.TotalCatches == 0 ? "–" : Formatting.Duration(data.TotalHoldTime / data.TotalCatches)) pro Fang</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="label">Abgelehnt</span>
|
||||
<span class="value">@data.Rejected.ToString("N0")</span>
|
||||
<span class="sub">wegen Verbindungslimits</span>
|
||||
<span class="value">@Formatting.Number(data.Rejected)</span>
|
||||
<span class="sub">+@Formatting.Number(data.RejectedLast24Hours) in 24 h · Limit erreicht</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -62,76 +66,163 @@
|
||||
|
||||
<section class="origin">
|
||||
<WorldMap CatchesByCountry="data.CatchesByCountry" />
|
||||
<TopTable Title="Top 10 Länder" KeyLabel="Land" Entries="data.TopCountries" ShowFlags="true" LabelFormatter="CountryNames.Display" />
|
||||
<section class="card tops-card">
|
||||
<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">
|
||||
@foreach (var tab in tabs)
|
||||
{
|
||||
var first = tab == tabs[0];
|
||||
<button type="button" role="tab" id="tab-@tab.Id" aria-controls="panel-@tab.Id" aria-selected="@(first ? "true" : "false")" tabindex="@(first ? 0 : -1)">@tab.Label</button>
|
||||
}
|
||||
</div>
|
||||
@foreach (var tab in tabs)
|
||||
{
|
||||
<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"
|
||||
Href="entry => TopFilter(tab, entry).Href()" IsActive="entry => tab.Current(_filter) == entry.Key" />
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
</section>
|
||||
|
||||
@if (data.TotalCatches > 0)
|
||||
@if (data.TotalCatches > 0 || data.Rejected > 0)
|
||||
{
|
||||
<section class="tops">
|
||||
<TopTable Title="Top 10 Provider" KeyLabel="Provider" Entries="data.TopProviders" />
|
||||
<TopTable Title="Top 10 IPs" KeyLabel="IP" Entries="data.TopIps" />
|
||||
<TopTable Title="Top 10 Ziele" KeyLabel="Ziel" Entries="data.TopTargets" KeyFormatter="Formatting.Target" />
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
var recent = _recent!;
|
||||
<section class="card recent-card" id="@DashboardFilter.Anchor">
|
||||
<div class="card-head">
|
||||
<h2>Letzte 50 Fänge</h2>
|
||||
<span class="hint">Zeile anklicken zum Aufklappen</span>
|
||||
<h2>Fänge <span class="count">· @Formatting.Number(recent.Total) Treffer</span></h2>
|
||||
<span class="hint">Filter gelten nur für diese Liste</span>
|
||||
</div>
|
||||
<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 in data.Recent)
|
||||
<form class="filters" method="get" action="/#@DashboardFilter.Anchor">
|
||||
<label>
|
||||
<span>Zeitraum</span>
|
||||
<select name="zeit" data-autosubmit>
|
||||
@foreach (var (value, label) in DashboardFilter.Periods)
|
||||
{
|
||||
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 = trapEvent.BytesSent.ToString("N0");
|
||||
<tr data-expand="event:@trapEvent.Id" tabindex="0" aria-expanded="false">
|
||||
<td class="c-time"><span class="c-date">@started.ToString("dd.MM.") </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: @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()">@trapEvent.Outcome</span></td>
|
||||
</tr>
|
||||
<option value="@value" selected="@(value == (_filter.Zeit ?? ""))">@label</option>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</select>
|
||||
</label>
|
||||
<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.") </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>
|
||||
}
|
||||
}
|
||||
@@ -140,14 +231,107 @@
|
||||
|
||||
@code {
|
||||
private DashboardData? _data;
|
||||
private RecentCatches? _recent;
|
||||
private DashboardFilter _filter = new();
|
||||
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()
|
||||
{
|
||||
_filter = DashboardFilter.Parse(Zeit, Ausgang, Land, Provider, Ip, Ziel, Q, Limit);
|
||||
_data = await Queries.GetAsync();
|
||||
_recent = await Queries.GetRecentAsync(_filter.ToRecentFilter());
|
||||
_loadedAt = DateTime.Now;
|
||||
}
|
||||
|
||||
private static IReadOnlyList<TopTab> TopTabs(DashboardData data) =>
|
||||
[
|
||||
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, f => f.Provider, (f, key) => f with { Provider = key }),
|
||||
new("ips", "IPs", "IP", data.TopIps, f => f.Ip, (f, key) => f with { Ip = key }),
|
||||
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
|
||||
{
|
||||
TrapOutcome.Timeout => "Zeitlimit",
|
||||
TrapOutcome.ClientAborted => "Aufgegeben",
|
||||
TrapOutcome.Rejected => "Abgelehnt",
|
||||
TrapOutcome.Completed => "Beendet",
|
||||
_ => outcome.ToString()
|
||||
};
|
||||
|
||||
private static string Origin(TrapEventEntity trapEvent) =>
|
||||
string.Join(", ", new[] { trapEvent.City, CountryNames.Display(trapEvent.CountryCode, trapEvent.Country) }.Where(part => !string.IsNullOrEmpty(part)));
|
||||
|
||||
private sealed record TopTab(
|
||||
string Id,
|
||||
string Label,
|
||||
string KeyLabel,
|
||||
IReadOnlyList<TopEntry> Entries,
|
||||
Func<DashboardFilter, string?> Current,
|
||||
Func<DashboardFilter, string?, DashboardFilter> Set,
|
||||
bool ShowFlags = false,
|
||||
Func<string?, string?>? KeyFormatter = null,
|
||||
Func<string?, string?, string?>? LabelFormatter = null);
|
||||
}
|
||||
@@ -1,44 +1,63 @@
|
||||
@using System.Globalization
|
||||
@using Flypaper.Storage.Dashboard
|
||||
<section class="card">
|
||||
<h2>@Title</h2>
|
||||
@if (Entries.Count == 0)
|
||||
{
|
||||
<p class="empty">Noch keine Einträge.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<table class="top-table">
|
||||
<colgroup>
|
||||
<col />
|
||||
<col class="count" />
|
||||
<col class="hold" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>@KeyLabel</th>
|
||||
<th class="num">Fänge</th>
|
||||
<th class="num">Haltezeit</th>
|
||||
|
||||
@if (Entries.Count == 0)
|
||||
{
|
||||
<p class="empty">Noch keine Einträge.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<table class="top-table">
|
||||
<colgroup>
|
||||
<col />
|
||||
<col class="share" />
|
||||
<col class="count" />
|
||||
<col class="hold" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>@KeyLabel</th>
|
||||
<th><span class="sr-only">Anteil</span></th>
|
||||
<th class="num">Fänge</th>
|
||||
<th class="num">Haltezeit</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var entry in Entries)
|
||||
{
|
||||
var key = KeyFormatter?.Invoke(entry.Key) ?? entry.Key;
|
||||
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 active = IsActive(entry);
|
||||
var title = label is null ? key : $"{label} · {key}";
|
||||
<tr data-href="@Href(entry)" class="@(active ? "active" : null)">
|
||||
<td class="clip" title="@title">
|
||||
<a href="@Href(entry)" aria-current="@(active ? "true" : null)" title="@(active ? $"Filter {title} entfernen" : $"Fänge filtern: {title}")">
|
||||
@if (ShowFlags)
|
||||
{
|
||||
<span class="flag">@Formatting.Flag(entry.Key)</span>
|
||||
}
|
||||
@if (label is not null)
|
||||
{
|
||||
<span class="top-label">@label</span>
|
||||
<span class="top-key mono">@key</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="mono">@key</span>
|
||||
}
|
||||
</a>
|
||||
</td>
|
||||
<td><span class="share-bar" style="--share: @(share)%"></span></td>
|
||||
<td class="num">@Formatting.Number(entry.Count)</td>
|
||||
<td class="num">@Formatting.Duration(entry.HoldTime)</td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var entry in Entries)
|
||||
{
|
||||
var share = (entry.Count * 100.0 / Entries[0].Count).ToString("0.#", CultureInfo.InvariantCulture);
|
||||
<tr data-expand="@($"{KeyLabel}:{entry.Key}")" tabindex="0" aria-expanded="false" style="--share: @(share)%">
|
||||
<td class="mono clip bar" title="@Display(entry)">@(ShowFlags ? $"{Formatting.Flag(entry.Key)} " : "")@Display(entry)</td>
|
||||
<td class="num">@entry.Count.ToString("N0")</td>
|
||||
<td class="num">@Formatting.Duration(entry.HoldTime)</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
}
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired] public required string Title { get; set; }
|
||||
|
||||
[Parameter, EditorRequired] public required string KeyLabel { get; set; }
|
||||
|
||||
[Parameter, EditorRequired] public required IReadOnlyList<TopEntry> Entries { get; set; }
|
||||
@@ -49,10 +68,7 @@
|
||||
|
||||
[Parameter] public Func<string?, string?, string?>? LabelFormatter { get; set; }
|
||||
|
||||
private string Display(TopEntry entry)
|
||||
{
|
||||
var key = KeyFormatter?.Invoke(entry.Key) ?? entry.Key;
|
||||
var label = LabelFormatter is null ? entry.Label : LabelFormatter(entry.Key, entry.Label);
|
||||
return label is null ? key : $"{key} · {label}";
|
||||
}
|
||||
[Parameter, EditorRequired] public required Func<TopEntry, string> Href { get; set; }
|
||||
|
||||
[Parameter, EditorRequired] public required Func<TopEntry, bool> IsActive { get; set; }
|
||||
}
|
||||
@@ -12,7 +12,7 @@
|
||||
{
|
||||
<span class="swatch @($"level-{level}")"></span>
|
||||
}
|
||||
<span>@_max.ToString("N0")</span>
|
||||
<span>@Formatting.Number(_max)</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -107,7 +107,7 @@
|
||||
|
||||
var bytesPerSecond = HoldMethodSettings.AverageBytesPerSecond(
|
||||
TimeSpan.FromMilliseconds(minDelay), TimeSpan.FromMilliseconds(maxDelay), minChunk, maxChunk);
|
||||
return bytesPerSecond.ToString(bytesPerSecond < 10 ? "0.0" : "N0", CultureInfo.GetCultureInfo("de-DE"));
|
||||
return bytesPerSecond.ToString(bytesPerSecond < 10 ? "0.0" : "N0", Formatting.German);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,12 @@
|
||||
<SettingsSection Id="data" Title="Daten" Description="Gespeicherte Fänge. Einstellungen und GeoIP-Dateien bleiben beim Löschen erhalten.">
|
||||
@if (Deleted is { } deleted)
|
||||
{
|
||||
<Notice>@deleted.ToString("N0") @(deleted == 1 ? "Fang" : "Fänge") gelöscht.</Notice>
|
||||
<Notice>@Formatting.Number(deleted) @(deleted == 1 ? "Fang" : "Fänge") gelöscht.</Notice>
|
||||
}
|
||||
|
||||
<div class="s-body">
|
||||
<div class="stat-row">
|
||||
<div class="stat"><span class="stat-label">Fänge</span><span class="stat-value">@(_stats?.Count.ToString("N0") ?? "–")</span></div>
|
||||
<div class="stat"><span class="stat-label">Fänge</span><span class="stat-value">@((_stats is null ? null : Formatting.Number(_stats.Count)) ?? "–")</span></div>
|
||||
<div class="stat"><span class="stat-label">Ältester Fang</span><span class="stat-value">@(_stats?.Oldest?.ToLocalTime().ToString("dd.MM.yyyy") ?? "–")</span></div>
|
||||
<div class="stat"><span class="stat-label">Datenbank</span><span class="stat-value">@Formatting.Bytes(_stats?.DatabaseBytes)</span></div>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Flypaper.Web.Components.Shared;
|
||||
|
||||
public static class Formatting
|
||||
{
|
||||
public static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
|
||||
|
||||
public static string Number(long value) => value.ToString("N0", German);
|
||||
|
||||
public static string Duration(TimeSpan duration) => duration switch
|
||||
{
|
||||
{ TotalDays: >= 1 } => $"{(int)duration.TotalDays}\u00a0d {duration.Hours}\u00a0h",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using Flypaper.Core.Abstractions;
|
||||
@@ -39,7 +40,7 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove
|
||||
public async Task<CatchListResult> ListCatches(
|
||||
[Description("Only events that started at or after this ISO 8601 time, e.g. 2026-11-15T08:00:00Z.")] string? since = null,
|
||||
[Description("Only events that started before this ISO 8601 time.")] string? until = null,
|
||||
[Description("ISO 3166-1 alpha-2 country code, e.g. CN.")] string? country = null,
|
||||
[Description("Country as ISO 3166-1 alpha-2 code, e.g. CN or GB.")] string? country = null,
|
||||
[Description("Network provider: an AS number such as AS4134, or part of the provider name.")] string? provider = null,
|
||||
[Description("Exact client IP address.")] string? ip = null,
|
||||
[Description("Case-insensitive text the request (method, host and path) must contain, e.g. .env.")] string? target_contains = null,
|
||||
@@ -61,7 +62,9 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove
|
||||
[McpServerTool(Name = "top", Title = "Top values", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Most frequent values among the catches of a time window, by number of catches. Rejected connections are not counted.")]
|
||||
public async Task<TopResult> Top(
|
||||
[Description("What to rank: ips, countries, providers, targets or user_agents.")] string dimension,
|
||||
[Description("What to rank by: ips, countries, providers, targets or user_agents.")]
|
||||
[AllowedValues("ips", "countries", "providers", "targets", "user_agents")]
|
||||
string dimension,
|
||||
[Description(PeriodDescription)] string period = "24h",
|
||||
[Description("Number of entries, 1 to 500.")] int limit = 10,
|
||||
CancellationToken ct = default)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Flypaper.Web.Mcp;
|
||||
|
||||
public static class McpArgumentCheck
|
||||
{
|
||||
public static string? FindProblem(JsonElement inputSchema, IReadOnlyDictionary<string, JsonElement>? arguments)
|
||||
{
|
||||
var properties = inputSchema.TryGetProperty("properties", out var schemaProperties)
|
||||
? schemaProperties.EnumerateObject().ToDictionary(p => p.Name, p => p.Value, StringComparer.Ordinal)
|
||||
: [];
|
||||
var required = inputSchema.TryGetProperty("required", out var schemaRequired)
|
||||
? schemaRequired.EnumerateArray().Select(r => r.GetString()!).ToList()
|
||||
: [];
|
||||
var given = arguments?.Keys.ToList() ?? [];
|
||||
|
||||
var unknown = given.Where(name => !properties.ContainsKey(name)).ToList();
|
||||
var missing = required.Where(name => !given.Contains(name, StringComparer.Ordinal)).ToList();
|
||||
if (unknown.Count == 0 && missing.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var problems = new List<string>();
|
||||
if (unknown.Count == 1 && missing.Count == 1)
|
||||
{
|
||||
problems.Add($"unknown parameter '{unknown[0]}'; expected '{missing[0]}'{Values(properties[missing[0]])}");
|
||||
}
|
||||
else
|
||||
{
|
||||
problems.AddRange(unknown.Select(name => $"unknown parameter '{name}'"));
|
||||
problems.AddRange(missing.Select(name => $"missing required parameter '{name}'{Values(properties[name])}"));
|
||||
}
|
||||
|
||||
var allowed = properties.Count == 0
|
||||
? "none"
|
||||
: string.Join(", ", properties.Select(p => required.Contains(p.Key) ? $"{p.Key} (required)" : p.Key));
|
||||
return $"{string.Join("; ", problems)}. Parameters: {allowed}.";
|
||||
}
|
||||
|
||||
private static string Values(JsonElement property) =>
|
||||
property.TryGetProperty("enum", out var values)
|
||||
? $" ({string.Join("|", values.EnumerateArray().Select(v => v.GetString()))})"
|
||||
: "";
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Flypaper.Storage.Settings;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using ModelContextProtocol;
|
||||
using ModelContextProtocol.Protocol;
|
||||
using ModelContextProtocol.Server;
|
||||
|
||||
namespace Flypaper.Web.Mcp;
|
||||
|
||||
@@ -16,6 +20,11 @@ public static class McpExtensions
|
||||
"stored with its time, client IP, country, network provider (ASN), requested URL, user agent, duration " +
|
||||
"and bytes sent. These tools only read that data; times are ISO 8601 UTC, durations in seconds.";
|
||||
|
||||
private static readonly JsonSerializerOptions ToolJsonOptions = new(McpJsonUtilities.DefaultOptions)
|
||||
{
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.Never
|
||||
};
|
||||
|
||||
public static IServiceCollection AddFlypaperMcp(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.Configure<McpOptions>(configuration.GetSection(McpOptions.SectionName));
|
||||
@@ -34,11 +43,39 @@ public static class McpExtensions
|
||||
options.ServerInstructions = Instructions;
|
||||
})
|
||||
.WithHttpTransport(options => options.Stateless = true)
|
||||
.WithTools<FlypaperTools>();
|
||||
.WithTools<FlypaperTools>(ToolJsonOptions)
|
||||
.WithRequestFilters(filters => filters.AddCallToolFilter(next => async (context, ct) =>
|
||||
{
|
||||
var tool = context.Params?.Name;
|
||||
var logger = context.Services?.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(FlypaperTools));
|
||||
|
||||
if (context.MatchedPrimitive is McpServerTool matched
|
||||
&& McpArgumentCheck.FindProblem(matched.ProtocolTool.InputSchema, context.Params?.Arguments?.AsReadOnly()) is { } problem)
|
||||
{
|
||||
logger?.LogWarning("MCP tool {Tool} was called with invalid arguments: {Problem}", tool, problem);
|
||||
return InvalidArguments(tool, problem);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return await next(context, ct);
|
||||
}
|
||||
catch (ArgumentException exception)
|
||||
{
|
||||
logger?.LogWarning(exception, "MCP tool {Tool} was called with invalid arguments", tool);
|
||||
return InvalidArguments(tool, exception.Message);
|
||||
}
|
||||
}));
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
private static CallToolResult InvalidArguments(string? tool, string message) => new()
|
||||
{
|
||||
IsError = true,
|
||||
Content = [new TextContentBlock { Text = $"Invalid arguments for '{tool}': {message}" }]
|
||||
};
|
||||
|
||||
public static IEndpointRouteBuilder MapFlypaperMcp(this IEndpointRouteBuilder app)
|
||||
{
|
||||
app.MapMcp(Path).RequireAuthorization(PolicyName);
|
||||
|
||||
@@ -42,7 +42,7 @@ h1:focus {
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 1280px;
|
||||
max-width: 1440px;
|
||||
margin: 0 auto;
|
||||
padding: 24px 16px 48px;
|
||||
}
|
||||
@@ -58,7 +58,7 @@ h2 {
|
||||
|
||||
.metrics {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1.4fr)) repeat(3, minmax(0, 1fr));
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
@@ -85,33 +85,32 @@ h2 {
|
||||
}
|
||||
|
||||
.metric .value {
|
||||
margin-top: 4px;
|
||||
font-size: 22px;
|
||||
margin: 6px 0 2px;
|
||||
font-size: 28px;
|
||||
font-weight: 600;
|
||||
line-height: 1.15;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.metric .sub {
|
||||
overflow: hidden;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.metric-hero .value {
|
||||
font-size: 32px;
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.metric-hero.live {
|
||||
.metric.live {
|
||||
border-color: color-mix(in srgb, var(--accent) 55%, var(--border));
|
||||
background: color-mix(in srgb, var(--accent) 8%, var(--surface));
|
||||
}
|
||||
|
||||
.metric-hero.live .value {
|
||||
.metric.live .value {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.metric-hero.live .label::before,
|
||||
.metric.live .label::before,
|
||||
.live-dot {
|
||||
content: "";
|
||||
display: inline-block;
|
||||
@@ -135,7 +134,7 @@ h2 {
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.metric-hero.live .label::before,
|
||||
.metric.live .label::before,
|
||||
.live-dot {
|
||||
animation: none;
|
||||
}
|
||||
@@ -182,39 +181,233 @@ code {
|
||||
|
||||
.origin {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.8fr) minmax(0, 1fr);
|
||||
grid-template-columns: minmax(0, 1.75fr) minmax(0, 1fr);
|
||||
gap: 16px;
|
||||
align-items: start;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.origin > .card {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.map-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.origin > * {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.tops {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 16px;
|
||||
.tops-card h2 {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.tops > :last-child {
|
||||
grid-column: 1 / -1;
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
margin: 0 -4px 8px;
|
||||
padding: 0 4px;
|
||||
overflow-x: auto;
|
||||
border-bottom: 1px solid var(--border);
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.tops > * {
|
||||
min-width: 0;
|
||||
.tabs button[role="tab"] {
|
||||
flex: none;
|
||||
margin-bottom: -1px;
|
||||
padding: 7px 12px;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
border-radius: 6px 6px 0 0;
|
||||
background: none;
|
||||
color: var(--muted);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.tabs button[role="tab"]:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.tabs button[role="tab"][aria-selected="true"] {
|
||||
border-bottom-color: var(--accent);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.tabs button[role="tab"]:focus-visible,
|
||||
[role="tabpanel"]:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.top-table {
|
||||
table-layout: fixed;
|
||||
}
|
||||
|
||||
.top-table .count {
|
||||
.top-table .share {
|
||||
width: 64px;
|
||||
}
|
||||
|
||||
.top-table .count {
|
||||
width: 60px;
|
||||
}
|
||||
|
||||
.top-table .hold {
|
||||
width: 104px;
|
||||
width: 96px;
|
||||
}
|
||||
|
||||
.top-table .flag {
|
||||
margin-right: 6px;
|
||||
}
|
||||
|
||||
.top-key {
|
||||
margin-left: 6px;
|
||||
color: var(--muted);
|
||||
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 {
|
||||
display: block;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
background: linear-gradient(to right, var(--accent) var(--share), color-mix(in srgb, var(--text) 8%, transparent) var(--share));
|
||||
}
|
||||
|
||||
.top-table .clip {
|
||||
@@ -414,9 +607,21 @@ tr.open .clip {
|
||||
}
|
||||
|
||||
.outcome.rejected {
|
||||
padding: 1px 7px;
|
||||
border: 1px solid color-mix(in srgb, var(--bad) 45%, transparent);
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--bad) 12%, transparent);
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
.recent-table tr.rejected td {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.recent-table tr.rejected td:first-child {
|
||||
box-shadow: inset 3px 0 0 var(--bad);
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.clip {
|
||||
max-width: 180px;
|
||||
@@ -630,8 +835,9 @@ tbody th {
|
||||
}
|
||||
|
||||
.world-map .marker .dot {
|
||||
stroke: var(--surface);
|
||||
stroke: var(--text);
|
||||
stroke-width: 1.5;
|
||||
stroke-opacity: 0.85;
|
||||
}
|
||||
|
||||
.world-map .marker:hover .dot {
|
||||
@@ -676,9 +882,10 @@ tbody th {
|
||||
.map-legend {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
gap: 5px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
font-size: 13px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.map-legend .level-0 {
|
||||
@@ -687,6 +894,9 @@ tbody th {
|
||||
|
||||
.map-wrap {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.map-empty {
|
||||
@@ -704,17 +914,10 @@ tbody th {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
td.bar {
|
||||
background-image: linear-gradient(to right, color-mix(in srgb, var(--accent) 70%, transparent) var(--share), transparent var(--share));
|
||||
background-repeat: no-repeat;
|
||||
background-size: 100% 3px;
|
||||
background-position: 0 calc(100% - 3px);
|
||||
}
|
||||
|
||||
.map-legend .swatch {
|
||||
width: 18px;
|
||||
height: 10px;
|
||||
border-radius: 2px;
|
||||
width: 22px;
|
||||
height: 12px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.detail {
|
||||
@@ -750,14 +953,21 @@ button.danger {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
.metric-hero {
|
||||
.metric:nth-child(n + 4) {
|
||||
grid-column: span 3;
|
||||
}
|
||||
|
||||
.origin,
|
||||
.tops {
|
||||
.origin {
|
||||
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) {
|
||||
@@ -766,7 +976,7 @@ button.danger {
|
||||
}
|
||||
|
||||
.metric,
|
||||
.metric-hero {
|
||||
.metric:nth-child(n + 4) {
|
||||
grid-column: span 1;
|
||||
}
|
||||
|
||||
@@ -774,8 +984,28 @@ button.danger {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
.metric-hero .value {
|
||||
font-size: 26px;
|
||||
.metric .value {
|
||||
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 th:nth-child(2),
|
||||
.top-table td:nth-child(2),
|
||||
.top-key {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.top-table .hold {
|
||||
width: 84px;
|
||||
}
|
||||
|
||||
.nav .brand {
|
||||
@@ -1341,3 +1571,12 @@ button.danger-text {
|
||||
gap: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -52,3 +52,85 @@
|
||||
|
||||
save(expanded);
|
||||
})();
|
||||
|
||||
(() => {
|
||||
const storageKey = "flypaper.tab";
|
||||
const tabs = [...document.querySelectorAll('[role="tab"]')];
|
||||
if (tabs.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const select = (tab, focus) => {
|
||||
for (const other of tabs) {
|
||||
const selected = other === tab;
|
||||
other.setAttribute("aria-selected", String(selected));
|
||||
other.tabIndex = selected ? 0 : -1;
|
||||
document.getElementById(other.getAttribute("aria-controls")).hidden = !selected;
|
||||
}
|
||||
|
||||
if (focus) {
|
||||
tab.focus();
|
||||
}
|
||||
|
||||
try {
|
||||
sessionStorage.setItem(storageKey, tab.id);
|
||||
} catch {
|
||||
}
|
||||
};
|
||||
|
||||
let stored = null;
|
||||
try {
|
||||
stored = sessionStorage.getItem(storageKey);
|
||||
} catch {
|
||||
}
|
||||
|
||||
const initial = tabs.find(tab => tab.id === stored);
|
||||
if (initial) {
|
||||
select(initial, false);
|
||||
}
|
||||
|
||||
for (const tab of tabs) {
|
||||
tab.addEventListener("click", () => select(tab, false));
|
||||
|
||||
tab.addEventListener("keydown", event => {
|
||||
const index = tabs.indexOf(tab);
|
||||
const target = {
|
||||
ArrowRight: tabs[(index + 1) % tabs.length],
|
||||
ArrowLeft: tabs[(index - 1 + tabs.length) % tabs.length],
|
||||
Home: tabs[0],
|
||||
End: tabs.at(-1)
|
||||
}[event.key];
|
||||
|
||||
if (target) {
|
||||
event.preventDefault();
|
||||
select(target, true);
|
||||
}
|
||||
});
|
||||
}
|
||||
})();
|
||||
|
||||
(() => {
|
||||
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;
|
||||
});
|
||||
}
|
||||
})();
|
||||
@@ -4,7 +4,6 @@ using System.Text;
|
||||
using System.Text.Json;
|
||||
using Flypaper.Web.Mcp;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
|
||||
@@ -12,14 +11,14 @@ namespace Flypaper.Tests.Mcp;
|
||||
|
||||
public sealed class McpEndpointTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-mcp-http-{Guid.NewGuid():N}.db");
|
||||
private readonly McpTestData _data = new();
|
||||
private readonly WebApplicationFactory<Program> _factory;
|
||||
|
||||
public McpEndpointTests()
|
||||
{
|
||||
_factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}");
|
||||
builder.UseSetting("ConnectionStrings:Flypaper", _data.ConnectionString);
|
||||
builder.UseSetting("Flypaper:Ports:Dashboard", "0");
|
||||
});
|
||||
}
|
||||
@@ -69,10 +68,141 @@ public sealed class McpEndpointTests : IDisposable
|
||||
|
||||
var stats = await ReadAsync(await client.SendAsync(Rpc("tools/call", token, new { name = "get_stats", arguments = new { period = "all" } })));
|
||||
var structured = stats.GetProperty("result").GetProperty("structuredContent");
|
||||
structured.GetProperty("catches").GetInt32().ShouldBe(0);
|
||||
structured.GetProperty("catches").GetInt32().ShouldBe(5);
|
||||
structured.GetProperty("period").GetString().ShouldBe("all");
|
||||
structured.GetProperty("since").ValueKind.ShouldBe(JsonValueKind.Null);
|
||||
}
|
||||
|
||||
public static TheoryData<string, string> ToolCalls => new()
|
||||
{
|
||||
{ "get_stats", """{"period":"all"}""" },
|
||||
{ "get_stats", """{"period":"24h"}""" },
|
||||
{ "list_catches", """{}""" },
|
||||
{ "list_catches", """{"country":"CN","limit":1}""" },
|
||||
{ "top", """{"dimension":"ips","period":"all"}""" },
|
||||
{ "top", """{"dimension":"countries","period":"all"}""" },
|
||||
{ "top", """{"dimension":"countries","period":"24h"}""" },
|
||||
{ "top", """{"dimension":"providers","period":"all"}""" },
|
||||
{ "top", """{"dimension":"targets","period":"all"}""" },
|
||||
{ "top", """{"dimension":"user_agents","period":"all"}""" },
|
||||
{ "longest_catches", """{"period":"all"}""" },
|
||||
{ "lookup_ip", """{"ip":"203.0.113.9"}""" },
|
||||
{ "lookup_ip", """{"ip":"192.0.2.1"}""" }
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(ToolCalls))]
|
||||
public async Task Tool_results_match_their_output_schema(string tool, string arguments)
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
var token = await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("test");
|
||||
var schema = (await OutputSchemasAsync(client, token))[tool];
|
||||
|
||||
var response = await ReadAsync(await client.SendAsync(Rpc("tools/call", token, new { name = tool, arguments = JsonDocument.Parse(arguments).RootElement })));
|
||||
|
||||
var result = response.GetProperty("result");
|
||||
(result.TryGetProperty("isError", out var isError) && isError.GetBoolean()).ShouldBeFalse(result.ToString());
|
||||
var errors = new List<string>();
|
||||
Validate(schema, result.GetProperty("structuredContent"), "$", errors);
|
||||
errors.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Every_listed_tool_is_covered_by_the_schema_test()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
var token = await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("test");
|
||||
|
||||
var listed = (await OutputSchemasAsync(client, token)).Keys;
|
||||
|
||||
listed.ShouldBe(ToolCalls.Select(row => (string)row[0]!).Distinct(), ignoreOrder: true);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("top", """{"by":"countries","period":"all"}""", "unknown parameter 'by'; expected 'dimension' (ips|countries|providers|targets|user_agents)")]
|
||||
[InlineData("top", """{"period":"all"}""", "missing required parameter 'dimension' (ips|countries|providers|targets|user_agents)")]
|
||||
[InlineData("list_catches", """{"countryCode":"GB"}""", "unknown parameter 'countryCode'")]
|
||||
public async Task Invalid_arguments_return_a_readable_tool_error(string tool, string arguments, string expected)
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
var token = await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("test");
|
||||
|
||||
var response = await ReadAsync(await client.SendAsync(Rpc("tools/call", token, new { name = tool, arguments = JsonDocument.Parse(arguments).RootElement })));
|
||||
|
||||
var result = response.GetProperty("result");
|
||||
result.GetProperty("isError").GetBoolean().ShouldBeTrue();
|
||||
result.GetProperty("content")[0].GetProperty("text").GetString().ShouldNotBeNull().ShouldContain(expected, Case.Sensitive);
|
||||
}
|
||||
|
||||
private static async Task<Dictionary<string, JsonElement>> OutputSchemasAsync(HttpClient client, string token)
|
||||
{
|
||||
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
|
||||
return tools.GetProperty("result").GetProperty("tools").EnumerateArray()
|
||||
.ToDictionary(t => t.GetProperty("name").GetString()!, t => t.GetProperty("outputSchema"));
|
||||
}
|
||||
|
||||
private static void Validate(JsonElement schema, JsonElement value, string path, List<string> errors)
|
||||
{
|
||||
if (schema.TryGetProperty("type", out var type))
|
||||
{
|
||||
var allowed = type.ValueKind == JsonValueKind.Array
|
||||
? type.EnumerateArray().Select(t => t.GetString()!).ToList()
|
||||
: [type.GetString()!];
|
||||
if (!allowed.Any(t => HasType(value, t)))
|
||||
{
|
||||
errors.Add($"{path}: {value.ValueKind} is not {string.Join(" or ", allowed)}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (schema.TryGetProperty("enum", out var values) && !values.EnumerateArray().Any(v => v.ToString() == value.ToString()))
|
||||
{
|
||||
errors.Add($"{path}: {value} is not one of {values}");
|
||||
}
|
||||
|
||||
if (value.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
if (schema.TryGetProperty("required", out var required))
|
||||
{
|
||||
errors.AddRange(required.EnumerateArray()
|
||||
.Where(name => !value.TryGetProperty(name.GetString()!, out _))
|
||||
.Select(name => $"{path}: missing required property '{name.GetString()}'"));
|
||||
}
|
||||
|
||||
if (schema.TryGetProperty("properties", out var properties))
|
||||
{
|
||||
foreach (var property in properties.EnumerateObject())
|
||||
{
|
||||
if (value.TryGetProperty(property.Name, out var child))
|
||||
{
|
||||
Validate(property.Value, child, $"{path}.{property.Name}", errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (value.ValueKind == JsonValueKind.Array && schema.TryGetProperty("items", out var items))
|
||||
{
|
||||
var index = 0;
|
||||
foreach (var item in value.EnumerateArray())
|
||||
{
|
||||
Validate(items, item, $"{path}[{index++}]", errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool HasType(JsonElement value, string type) => type switch
|
||||
{
|
||||
"object" => value.ValueKind == JsonValueKind.Object,
|
||||
"array" => value.ValueKind == JsonValueKind.Array,
|
||||
"string" => value.ValueKind == JsonValueKind.String,
|
||||
"integer" => value.ValueKind == JsonValueKind.Number && value.TryGetInt64(out _),
|
||||
"number" => value.ValueKind == JsonValueKind.Number,
|
||||
"boolean" => value.ValueKind is JsonValueKind.True or JsonValueKind.False,
|
||||
"null" => value.ValueKind == JsonValueKind.Null,
|
||||
_ => throw new NotSupportedException($"Schema type '{type}'")
|
||||
};
|
||||
|
||||
private static HttpRequestMessage Rpc(string method, string? token, object? parameters = null)
|
||||
{
|
||||
var body = JsonSerializer.Serialize(new { jsonrpc = "2.0", id = 1, method, @params = parameters ?? new { } });
|
||||
@@ -104,10 +234,6 @@ public sealed class McpEndpointTests : IDisposable
|
||||
public void Dispose()
|
||||
{
|
||||
_factory.Dispose();
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
File.Delete(_dbPath + suffix);
|
||||
}
|
||||
_data.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ internal sealed class McpTestData : IDisposable
|
||||
|
||||
public McpTestData()
|
||||
{
|
||||
Factory = new TestDbContextFactory($"Data Source={_dbPath}");
|
||||
Factory = new TestDbContextFactory(ConnectionString);
|
||||
using var db = Factory.CreateDbContext();
|
||||
db.Database.Migrate();
|
||||
|
||||
@@ -30,6 +30,8 @@ internal sealed class McpTestData : IDisposable
|
||||
|
||||
public IDbContextFactory<FlypaperDbContext> Factory { get; }
|
||||
|
||||
public string ConnectionString => $"Data Source={_dbPath}";
|
||||
|
||||
private static void Add(
|
||||
FlypaperDbContext db,
|
||||
string ip,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user