20 Commits
Author SHA1 Message Date
TomandClaude Opus 5.5 1979fd91e9 Prepare changelog for 0.6.0
Build and deploy / build (push) Successful in 1m49s
Release / image (push) Successful in 2m0s
Build and deploy / deploy (push) Successful in 29s
Release / release (push) Successful in 6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:05:05 +01:00
TomandClaude Opus 5.5 119dafa505 Remove the research page, its MCP write tools and token write permission
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:05:05 +01:00
TomandClaude Opus 5.5 7f8a3ae882 Prepare changelog for 0.5.2
Build and deploy / build (push) Successful in 1m41s
Release / image (push) Successful in 2m1s
Build and deploy / deploy (push) Successful in 23s
Release / release (push) Successful in 7s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:29:53 +01:00
TomandClaude Opus 5.5 cbd9830143 Group strategies by base type and rank them by median hold time
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:29:53 +01:00
TomandClaude Opus 5.5 d2cbab5d4b Prepare changelog for 0.5.1
Build and deploy / build (push) Successful in 1m41s
Release / image (push) Successful in 2m7s
Build and deploy / deploy (push) Successful in 22s
Release / release (push) Successful in 6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:52:11 +01:00
TomandClaude Opus 5.5 0655af2699 Show plain German strategy names with explanations in the dashboard
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:52:11 +01:00
TomandClaude Opus 5.5 e250a120ea Prepare changelog for 0.5.0
Release / image (push) Successful in 1m58s
Release / release (push) Successful in 8s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:30:17 +01:00
TomandClaude Opus 5.5 e88dc415f9 Add research page with MCP write tools, longer hold for repeat offenders and svn/hg decoys
Build and deploy / build (push) Successful in 1m50s
Build and deploy / deploy (push) Successful in 21s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:27:35 +01:00
TomandClaude Opus 5.5 a25072e6fb Add link labyrinth, static robots.txt and robots bait paths
Build and deploy / build (push) Successful in 1m28s
Build and deploy / deploy (push) Successful in 20s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:57:52 +01:00
TomandClaude Sonnet 5.5 b7027e2a72 Show the strategy of each catch in the dashboard
Build and deploy / build (push) Successful in 1m31s
Build and deploy / deploy (push) Successful in 30s
Add a Strategie column to the catch list (searchable, filterable) and a
Strategien tab to the Top 10 card. The MCP top tool accepts strategies.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 23:34:10 +01:00
TomandClaude Sonnet 5.5 7d3e6f8842 Add map markers for tiny countries that have a polygon
Build and deploy / build (push) Successful in 1m32s
Build and deploy / deploy (push) Successful in 20s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 23:10:05 +01:00
TomandClaude Sonnet 5.5 aeafaa71a8 Add Hikvision and WordPress login decoy profiles
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 23:06:19 +01:00
TomandClaude Sonnet 5.5 13468bbdf9 Pick tarpit content by request path
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 23:00:26 +01:00
TomandClaude Sonnet 5.5 e48b6bb832 Send a head start of the response immediately before dripping
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 22:54:03 +01:00
TomandClaude Opus 5.5 13a78f4268 Prepare changelog for 0.4.0
Release / image (push) Successful in 1m50s
Release / release (push) Successful in 7s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 23:47:57 +01:00
TomandClaude Opus 5.5 9f07d41cb0 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>
2026-11-15 23:40:52 +01:00
TomandClaude Opus 5.5 8eeb7894a3 Polish dashboard layout and use German number formats
Build and deploy / build (push) Successful in 1m27s
Build and deploy / deploy (push) Successful in 20s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 21:09:52 +01:00
TomandClaude Opus 5.5 e86518cab1 Fix MCP schema mismatches and argument errors, highlight rejected connections and show average hold time
Build and deploy / build (push) Successful in 1m32s
Build and deploy / deploy (push) Successful in 30s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:56:50 +01:00
TomandClaude Opus 5.5 570ac20a5c Prepare changelog for 0.3.1
Build and deploy / build (push) Successful in 1m29s
Release / image (push) Successful in 1m51s
Build and deploy / deploy (push) Successful in 20s
Release / release (push) Successful in 6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:25:03 +01:00
TomandClaude Opus 5.5 393ebcdf0c Combine dashboard top 10 lists into one tabbed card
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:24:02 +01:00
76 changed files with 4032 additions and 233 deletions

No files matched your search

+130 -1
View File
@@ -6,6 +6,129 @@ All notable changes to Flypaper are documented in this file. The format follows
## [Unreleased]
## [0.6.0] - 2026-11-21
### Removed
- Page „Erkenntnisse“ (`/erkenntnisse`) with lab notebook and idea table, including its navigation entry and
all stored entries and ideas (tables `LabEntries` and `Ideas` are dropped by a migration, without backup).
- MCP: tools `list_entries`, `list_ideas`, `create_entry`, `update_entry`, `create_idea`, `update_idea` and
`set_idea_status`. All MCP tools are read-only again.
- MCP tokens: write permission (switch on the settings page, column „Zugriff“, database column `CanWrite`).
- Markdown rendering (Markdig).
## [0.5.2] - 2026-11-17
### Changed
- Dashboard, Top 10 „Strategien“: strategies are grouped by base type, so `html-drip` with any drip speed
is one row „Endlose Webseite“; the old name `drip` counts as the same. Only `head`, `link` and `repeat` stay
separate rows and show small badges („Schnellstart“, „Links“, „Wiederholer“). The drip parameters moved to the
tooltip and the expanded row.
- Columns are now catches, **median hold time per catch** and total. The bar and the default sort use the median
(rows with fewer than 5 catches are greyed out, marked „wenige Daten“ and listed last).
- Clicking a row filters the catch list on all variants of the group. The catch list, filter chip and
expanded row show name plus badges. Old `?strategie=` links still work.
## [0.5.1] - 2026-11-17
### Changed
- Dashboard: strategies are shown with a plain German name (e.g. „Link-Labyrinth“, „Gefälschte Zugangsdaten
(.env)“) instead of the technical abbreviation. Tooltip and expanded row (also on touch devices) explain what
the bot gets, spell out the suffixes (`50-500ms 1-1024B`, `head`, `link`, `repeat`) and show the technical name.
Used in the catch list, the Top 10 „Strategien“ tab, filter chips and the page „Erkenntnisse“. The search also
finds the German names. Unknown names are shown unchanged. Stored values and MCP results stay technical.
## [0.5.0] - 2026-11-17
### Fixed
- Narrow or tiny countries that are drawn as a polygon but barely visible (Israel, Lebanon,
Palestine, Kuwait, Qatar, Netherlands, Belgium, Switzerland and others) now also get a
marker on the world map once they have catches.
### Added
- Version-control file profiles: `git-drip` now answers every `.git` variant (`/.git`, `/.git/…`, `.gitconfig`,
`.git-credentials`, `.gitignore` …), new `svn-drip` (`/.svn/…`: `format`, `entries`, `wc.db`) and `hg-drip`
(`/.hg/…`: `requires`, `store/requires`) serve plausible, endless files that start like the real ones.
- Repeat offenders: an IP that was already held until the limit (outcome `Timeout`) within the last
`Flypaper__RepeatWindowDays` days (default 7, `0` = off) is held for `Flypaper__RepeatHoldDuration`
(default 1 day) instead of the maximum hold duration. The catch's strategy gets the suffix `repeat`, so
it can be compared in the dashboard. Both values are adjustable under „Haltemethode“ on the settings page.
- Page „Erkenntnisse“ (`/erkenntnisse`, in the navigation): a lab notebook (date, title, kind experiment /
observation / hypothesis / measurement method, Markdown text, optional commit and strategy names; newest
first, filterable by kind) and an idea table (effort, efficiency, rationale, status open / in progress /
done / dropped, implementation date and commit; sorted by effort, done and dropped ones can be shown).
Markdown is rendered with Markdig without raw HTML and with only http, https and mailto links.
- MCP: new read tools `list_entries` and `list_ideas` and write tools `create_entry`, `update_entry`,
`create_idea`, `update_idea`, `set_idea_status`. Writing needs a token with write permission, set when
creating the token or later on the settings page (new „Zugriff“ column). Existing tokens and the token from
`Flypaper__Mcp__Token` stay read-only, and read-only tokens do not even see the write tools.
- Link labyrinth: the HTML page (strategy `maze-drip`, with `link <n>B` suffix) carries about ten links
already in the head start and then a new link every `LinkSpacing` bytes (default 160, `0` = old
`html-drip`). Links match the requested path and host (`/wiki/…`, `/docs/v2/…`, `/blog/2025/03/…`,
`/backup/2025/03/`), mix relative and absolute URLs and always lead to another labyrinth page.
Paths ending in `/` get an Apache-style „Index of /…“ listing (`index-drip`). `/robots.txt` is
served at once and complete (`User-agent: *`, `Disallow: /`, strategy `robots-static`), so well-behaved
crawlers stay out and only bots ignoring it get lost. Link spacing is adjustable on the settings page.
- Robots bait: below `Disallow: /` the robots.txt lists a few unlinked, plausible paths (default
`/backup-2024/`, `/admin-old/`, `/internal/db-export/`, `/old-site/`; `Flypaper__Drip__BaitPaths`,
editable on the settings page, empty = off). Requests to them and everything below get the labyrinth
as strategy `robots-bait` and are held for at least 24 hours, so catches show who read the
robots.txt and ignored it. The labyrinth never links to these paths.
- Dashboard: the catch list has a new „Strategie“ column (hidden on narrower screens, shown in
the expanded row) and the search covers it. A new „Strategien“ tab in the Top 10 card shows
catches and hold time per strategy and filters the list on click. The MCP `top` tool accepts
`strategies` as a dimension.
- Content matches the requested path: `.env`, `*.json`, `*.xml` (sitemaps), `*.yml`, `*.sql`,
`/.git/…`, Hikvision `/SDK/…` and `/ISAPI/…` (XML) and `wp-login.php`
(WordPress login page) get an endless, matching file with the right `Content-Type`
instead of an HTML page (strategy names `env-drip`, `json-drip`, …). Switchable on the
settings page (`Flypaper__Drip__MatchPath`).
- Head start: the first bytes of the page (at least `HeadStartSize`, default 1024) are sent
immediately after the `200` headers, with a `Server` header, so scanners see a real response
before the drip begins. Adjustable on the settings page; the stored strategy name gets a
`head <n>B` suffix (none when off).
## [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 +208,13 @@ 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.6.0...main
[0.6.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.6.0
[0.5.2]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.2
[0.5.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.1
[0.5.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.0
[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
+6
View File
@@ -23,6 +23,10 @@ All optional. Read at startup; list entries need an index (`__0`, `__1`, ...).
| `Flypaper__Drip__Content` | Hold method: `Html`, `Text` or `Alternating` | `Html` |
| `Flypaper__Drip__MinDelay` / `MaxDelay` | Pause between chunks | `00:00:00.05` / `00:00:01` |
| `Flypaper__Drip__MinChunkSize` / `MaxChunkSize` | Bytes per chunk | `1` / `64` |
| `Flypaper__Drip__HeadStartSize` | Bytes sent immediately before dripping starts (`0` = off) | `1024` |
| `Flypaper__Drip__LinkSpacing` | Link labyrinth: bytes of text between two links in the HTML page (`0` = off, plain `html-drip`) | `160` |
| `Flypaper__Drip__BaitPaths` | Comma-separated decoy paths listed in `robots.txt` (max. 8, empty = off); requests to them get `robots-bait` and are held for at least 24 h | `/backup-2024/,/admin-old/,/internal/db-export/,/old-site/` |
| `Flypaper__Drip__MatchPath` | Pick content by request path (`/.env`, `*.json`, `*.xml`, `*.yml`, `*.sql`, `/.git/…`, `/SDK/…`, `/ISAPI/…`, `wp-login.php`) | `true` |
| `TZ` | Time zone for the dashboard | UTC |
The defaults of the runtime settings below can also be set this way, e.g.
@@ -38,6 +42,8 @@ general reset button removes all saved values; the hold method section has its o
| Hold method: content (HTML filler text, random plain text, or alternating per catch) | HTML filler text |
| Hold method: pause between chunks, min and max (10 ms to 30 s) | 50 ms / 1000 ms |
| Hold method: chunk size, min and max (1 to 4096 bytes) | 1 / 64 bytes |
| Hold method: head start, sent without delay before the drip (0 to 65536 bytes) | 1024 bytes |
| Hold method: content matching the request path (e.g. `/.env`, `/config.json`) | on |
| Hold method: maximum hold time per catch | `01:00:00` |
| Maximum connections overall | `1000` |
| Maximum connections per IP | `10` |
@@ -0,0 +1,6 @@
namespace Flypaper.Core.Abstractions;
public interface IHoldExtension
{
TimeSpan MinimumHold { get; }
}
@@ -0,0 +1,8 @@
using System.Net;
namespace Flypaper.Core.Abstractions;
public interface IRepeatOffenderLookup
{
ValueTask<bool> HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct);
}
@@ -6,5 +6,9 @@ public interface ITrapChannel
{
TrapSession Session { get; }
string? Path => null;
string? Host => null;
ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct);
}
@@ -5,6 +5,7 @@ using Flypaper.Core.Strategies;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace Flypaper.Core;
@@ -20,9 +21,29 @@ public static class FlypaperCoreExtensions
services.TryAddSingleton<IRandomSource, SystemRandomSource>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, TextDripStrategy>());
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, RobotsStaticStrategy>());
foreach (var kind in Enum.GetValues<MazeKind>())
{
services.AddSingleton<ITarpitStrategy>(provider => new MazeDripStrategy(
kind,
provider.GetRequiredService<IOptionsMonitor<DripOptions>>(),
provider.GetRequiredService<IRandomSource>(),
provider.GetRequiredService<TimeProvider>()));
}
foreach (var profile in FileContent.Profiles)
{
services.AddSingleton<ITarpitStrategy>(provider => new FileDripStrategy(
profile,
provider.GetRequiredService<IOptionsMonitor<DripOptions>>(),
provider.GetRequiredService<IRandomSource>(),
provider.GetRequiredService<TimeProvider>()));
}
services.TryAddSingleton<ITrapStrategySelector, ConfiguredStrategySelector>();
services.TryAddSingleton<TrapRunner>();
services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
services.TryAddSingleton<IRepeatOffenderLookup, NullRepeatOffenderLookup>();
return services;
}
+4
View File
@@ -10,5 +10,9 @@ public sealed class FlypaperOptions
public TimeSpan MaxHoldDuration { get; set; } = TimeSpan.FromHours(1);
public int RepeatWindowDays { get; set; } = 7;
public TimeSpan RepeatHoldDuration { get; set; } = TimeSpan.FromHours(24);
public bool IgnorePrivateNetworks { get; set; } = true;
}
+1 -1
View File
@@ -1,3 +1,3 @@
namespace Flypaper.Core.Models;
public sealed record TrapContext(TrapSession Session, string? Target = null, string? ClientInfo = null);
public sealed record TrapContext(TrapSession Session, string? Target = null, string? ClientInfo = null, string? Path = null);
@@ -0,0 +1,9 @@
using System.Net;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Networking;
internal sealed class NullRepeatOffenderLookup : IRepeatOffenderLookup
{
public ValueTask<bool> HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct) => ValueTask.FromResult(false);
}
@@ -13,16 +13,42 @@ public sealed class ConfiguredStrategySelector(
public ITarpitStrategy? Select(TrapContext context)
{
var candidates = strategies.Where(strategy => strategy.Supports(context.Session.Protocol)).ToList();
if (string.Equals(context.Path, RobotsStaticStrategy.Path, StringComparison.OrdinalIgnoreCase)
&& candidates.FirstOrDefault(strategy => strategy.Name == RobotsStaticStrategy.StrategyName) is { } robots)
{
return robots;
}
if (BaitPaths.Matches(BaitPaths.Parse(options.CurrentValue.BaitPaths), context.Path)
&& candidates.FirstOrDefault(strategy => strategy.Name == MazeDripStrategy.BaitName) is { } bait)
{
return bait;
}
if (options.CurrentValue.MatchPath && FileContent.Match(context.Path) is { } profile
&& candidates.FirstOrDefault(strategy => strategy.Name == profile.Name) is { } fileStrategy)
{
return fileStrategy;
}
var maze = options.CurrentValue.LinkSpacing > 0
&& candidates.Any(strategy => strategy.Name == MazeDripStrategy.PageName);
var page = maze ? MazeDripStrategy.PageName : HtmlDripStrategy.StrategyName;
string[] wanted = options.CurrentValue.Content switch
{
DripContent.Text => [TextDripStrategy.StrategyName],
DripContent.Alternating => [HtmlDripStrategy.StrategyName, TextDripStrategy.StrategyName],
_ => [HtmlDripStrategy.StrategyName]
DripContent.Alternating => [page, TextDripStrategy.StrategyName],
_ => [page]
};
var matching = candidates.Where(strategy => wanted.Contains(strategy.Name)).ToList();
return matching.Count == 0
var chosen = matching.Count == 0
? candidates.FirstOrDefault()
: matching[random.Next(0, matching.Count)];
return chosen?.Name == MazeDripStrategy.PageName && MazeContent.IsDirectory(context.Path)
&& candidates.FirstOrDefault(strategy => strategy.Name == MazeDripStrategy.ListingName) is { } listing
? listing
: chosen;
}
}
@@ -9,6 +9,10 @@ internal sealed class CountingTrapChannel(ITrapChannel inner) : ITrapChannel
public TrapSession Session => inner.Session;
public string? Path => inner.Path;
public string? Host => inner.Host;
public long BytesSent => Interlocked.Read(ref _bytesSent);
public async ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct)
+16 -1
View File
@@ -11,6 +11,7 @@ public sealed partial class TrapRunner(
IConnectionGovernor governor,
ITrapStrategySelector strategies,
ITrapEventSink sink,
IRepeatOffenderLookup repeatOffenders,
IOptionsMonitor<FlypaperOptions> options,
TimeProvider timeProvider,
ILogger<TrapRunner> logger)
@@ -31,7 +32,21 @@ public sealed partial class TrapRunner(
using var _ = lease;
var description = strategy is IStrategyDetails details ? details.Describe() : strategy.Name;
using var hold = new CancellationTokenSource(options.CurrentValue.MaxHoldDuration, timeProvider);
var holdDuration = options.CurrentValue.MaxHoldDuration;
if (strategy is IHoldExtension extension && extension.MinimumHold > holdDuration)
{
holdDuration = extension.MinimumHold;
}
if (options.CurrentValue is { RepeatWindowDays: > 0 } current
&& current.RepeatHoldDuration > holdDuration
&& await repeatOffenders.HasTimedOutSinceAsync(session.RemoteIp, timeProvider.GetUtcNow().UtcDateTime.AddDays(-current.RepeatWindowDays), ct))
{
holdDuration = current.RepeatHoldDuration;
description += " repeat";
}
using var hold = new CancellationTokenSource(holdDuration, timeProvider);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
CountingTrapChannel? channel = null;
@@ -9,7 +9,13 @@ public sealed record HoldMethodSettings(
TimeSpan MaxDelay,
int MinChunkSize,
int MaxChunkSize,
TimeSpan MaxHoldDuration)
int HeadStartSize,
bool MatchPath,
int LinkSpacing,
string BaitPaths,
TimeSpan MaxHoldDuration,
int RepeatWindowDays,
TimeSpan RepeatHoldDuration)
{
public double BytesPerSecond => AverageBytesPerSecond(MinDelay, MaxDelay, MinChunkSize, MaxChunkSize);
@@ -20,7 +26,13 @@ public sealed record HoldMethodSettings(
[SettingKeys.DripMaxDelay] = MaxDelay.ToString("c", CultureInfo.InvariantCulture),
[SettingKeys.DripMinChunkSize] = MinChunkSize.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripMaxChunkSize] = MaxChunkSize.ToString(CultureInfo.InvariantCulture),
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
[SettingKeys.DripHeadStartSize] = HeadStartSize.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripMatchPath] = MatchPath ? "true" : "false",
[SettingKeys.DripLinkSpacing] = LinkSpacing.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripBaitPaths] = BaitPaths,
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
[SettingKeys.RepeatWindowDays] = RepeatWindowDays.ToString(CultureInfo.InvariantCulture),
[SettingKeys.RepeatHoldDuration] = RepeatHoldDuration.ToString("c", CultureInfo.InvariantCulture)
};
public static double AverageBytesPerSecond(TimeSpan minDelay, TimeSpan maxDelay, int minChunkSize, int maxChunkSize)
@@ -36,6 +48,12 @@ public sealed record HoldMethodInput(
string? MaxDelayMs,
string? MinChunkSize,
string? MaxChunkSize,
string? MaxHoldDuration);
string? HeadStartSize,
bool MatchPath,
string? LinkSpacing,
string? BaitPaths,
string? MaxHoldDuration,
string? RepeatWindowDays,
string? RepeatHoldDuration);
public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary<string, string> Errors);
@@ -13,6 +13,9 @@ public static class RuntimeSettingsParser
private const int MinDelayMs = 10;
private const int MaxDelayMs = 30_000;
private const int MaxChunkSize = 4096;
private const int MaxHeadStartSize = 65_536;
private const int MaxLinkSpacing = 4096;
private const int MaxRepeatWindowDays = 365;
public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input)
{
@@ -57,7 +60,12 @@ public static class RuntimeSettingsParser
var maxDelay = ParseInt(input.MaxDelayMs, nameof(input.MaxDelayMs), MinDelayMs, MaxDelayMs, errors);
var minChunk = ParseInt(input.MinChunkSize, nameof(input.MinChunkSize), 1, MaxChunkSize, errors);
var maxChunk = ParseInt(input.MaxChunkSize, nameof(input.MaxChunkSize), 1, MaxChunkSize, errors);
var headStart = ParseInt(input.HeadStartSize, nameof(input.HeadStartSize), 0, MaxHeadStartSize, errors);
var linkSpacing = ParseInt(input.LinkSpacing, nameof(input.LinkSpacing), 0, MaxLinkSpacing, errors);
var baits = ParseBaitPaths(input.BaitPaths, nameof(input.BaitPaths), errors);
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
var repeatWindow = ParseInt(input.RepeatWindowDays, nameof(input.RepeatWindowDays), 0, MaxRepeatWindowDays, errors);
var repeatHold = ParseTimeSpan(input.RepeatHoldDuration, nameof(input.RepeatHoldDuration), MinHold, MaxHold, errors);
if (minDelay > maxDelay)
{
@@ -81,10 +89,36 @@ public static class RuntimeSettingsParser
TimeSpan.FromMilliseconds(maxDelay!.Value),
minChunk!.Value,
maxChunk!.Value,
hold!.Value),
headStart!.Value,
input.MatchPath,
linkSpacing!.Value,
baits!,
hold!.Value,
repeatWindow!.Value,
repeatHold!.Value),
errors);
}
private static string? ParseBaitPaths(string? raw, string field, Dictionary<string, string> errors)
{
var entries = BaitPaths.Split(raw);
var normalized = entries.Select(BaitPaths.Normalize).ToList();
if (normalized.Any(entry => entry is null))
{
errors[field] = "Pfade wie /backup-2024/, ohne Leerzeichen; nicht /robots.txt und nicht unter den Labyrinth-Ordnern (wiki, docs, blog, backup …).";
return null;
}
var distinct = normalized.OfType<string>().Distinct().ToList();
if (distinct.Count > BaitPaths.MaxCount)
{
errors[field] = $"Höchstens {BaitPaths.MaxCount} Pfade.";
return null;
}
return string.Join(',', distinct);
}
private static TimeSpan? ParseTimeSpan(
string? raw,
string field,
@@ -101,7 +135,7 @@ public static class RuntimeSettingsParser
if (!text.Contains(':') || !TimeSpan.TryParse(text, CultureInfo.InvariantCulture, out var value))
{
errors[field] = "Format hh:mm:ss, zum Beispiel 00:00:10.";
errors[field] = "Format hh:mm:ss (ab einem Tag d.hh:mm:ss), zum Beispiel 00:00:10.";
return null;
}
+7 -1
View File
@@ -5,6 +5,8 @@ public static class SettingKeys
public const string MaxConnections = "Flypaper:MaxConnections";
public const string MaxConnectionsPerIp = "Flypaper:MaxConnectionsPerIp";
public const string MaxHoldDuration = "Flypaper:MaxHoldDuration";
public const string RepeatWindowDays = "Flypaper:RepeatWindowDays";
public const string RepeatHoldDuration = "Flypaper:RepeatHoldDuration";
public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks";
public const string RetentionDays = "Flypaper:Retention:Days";
public const string DripContent = "Flypaper:Drip:Content";
@@ -12,12 +14,16 @@ public static class SettingKeys
public const string DripMaxDelay = "Flypaper:Drip:MaxDelay";
public const string DripMinChunkSize = "Flypaper:Drip:MinChunkSize";
public const string DripMaxChunkSize = "Flypaper:Drip:MaxChunkSize";
public const string DripHeadStartSize = "Flypaper:Drip:HeadStartSize";
public const string DripMatchPath = "Flypaper:Drip:MatchPath";
public const string DripBaitPaths = "Flypaper:Drip:BaitPaths";
public const string DripLinkSpacing = "Flypaper:Drip:LinkSpacing";
public static readonly IReadOnlyList<string> General =
[MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays];
public static readonly IReadOnlyList<string> HoldMethod =
[DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, MaxHoldDuration];
[DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, DripHeadStartSize, DripMatchPath, DripLinkSpacing, DripBaitPaths, MaxHoldDuration, RepeatWindowDays, RepeatHoldDuration];
public static readonly IReadOnlySet<string> All =
new HashSet<string>(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase);
+52
View File
@@ -0,0 +1,52 @@
using System.Text.RegularExpressions;
namespace Flypaper.Core.Strategies;
public static partial class BaitPaths
{
public const int MaxCount = 8;
public const string Default = "/backup-2024/,/admin-old/,/internal/db-export/,/old-site/";
[GeneratedRegex("^/[A-Za-z0-9._~-]+(/[A-Za-z0-9._~-]+)*/?$")]
private static partial Regex Valid();
public static IReadOnlyList<string> Split(string? raw) =>
(raw ?? "").Split([',', ';', ' ', '\n', '\r', '\t'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
public static string? Normalize(string entry)
{
if (!Valid().IsMatch(entry) || entry.Length > 100)
{
return null;
}
var normalized = entry.ToLowerInvariant();
if (!normalized.EndsWith('/'))
{
normalized += "/";
}
var first = normalized.Split('/', StringSplitOptions.RemoveEmptyEntries)[0];
return normalized == RobotsStaticStrategy.Path + "/" || Array.IndexOf(MazeContent.Roots, first) >= 0 ? null : normalized;
}
public static IReadOnlyList<string> Parse(string? raw) =>
Split(raw).Select(Normalize).OfType<string>().Distinct().Take(MaxCount).ToList();
public static bool Matches(IReadOnlyList<string> baits, string? path)
{
if (string.IsNullOrEmpty(path) || baits.Count == 0)
{
return false;
}
var normalized = path.ToLowerInvariant();
if (!normalized.EndsWith('/'))
{
normalized += "/";
}
return baits.Any(bait => normalized.StartsWith(bait, StringComparison.Ordinal));
}
}
@@ -13,4 +13,12 @@ public sealed class DripOptions
public int MinChunkSize { get; set; } = 1;
public int MaxChunkSize { get; set; } = 64;
public int HeadStartSize { get; set; } = 1024;
public bool MatchPath { get; set; } = true;
public int LinkSpacing { get; set; } = 160;
public string BaitPaths { get; set; } = Strategies.BaitPaths.Default;
}
@@ -5,6 +5,25 @@ namespace Flypaper.Core.Strategies;
public static class DripSchedule
{
public static ReadOnlyMemory<byte> TakeHead(IEnumerator<string> fragments, int minBytes)
{
var head = new List<byte>();
while (head.Count < minBytes && fragments.MoveNext())
{
head.AddRange(Encoding.UTF8.GetBytes(fragments.Current));
}
return head.ToArray();
}
public static IEnumerable<string> Remaining(IEnumerator<string> fragments)
{
while (fragments.MoveNext())
{
yield return fragments.Current;
}
}
public static IEnumerable<DripStep> Create(IEnumerable<string> content, IRandomSource random, DripOptions options)
{
var minChunk = Math.Max(1, options.MinChunkSize);
+15 -3
View File
@@ -19,14 +19,24 @@ public abstract class DripStrategy(
public string Describe()
{
var current = options.CurrentValue;
var head = current.HeadStartSize > 0 ? $" head {current.HeadStartSize}B" : "";
return string.Create(
CultureInfo.InvariantCulture,
$"{Name} {current.MinDelay.TotalMilliseconds:0}-{current.MaxDelay.TotalMilliseconds:0}ms {current.MinChunkSize}-{current.MaxChunkSize}B");
$"{Name} {current.MinDelay.TotalMilliseconds:0}-{current.MaxDelay.TotalMilliseconds:0}ms {current.MinChunkSize}-{current.MaxChunkSize}B{head}{Extra(current)}");
}
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
{
foreach (var step in DripSchedule.Create(Content(random), random, options.CurrentValue))
var current = options.CurrentValue;
using var fragments = Content(random, channel, current).GetEnumerator();
var head = DripSchedule.TakeHead(fragments, current.HeadStartSize);
if (head.Length > 0)
{
await channel.WriteAsync(head, ct);
}
foreach (var step in DripSchedule.Create(DripSchedule.Remaining(fragments), random, current))
{
ct.ThrowIfCancellationRequested();
await channel.WriteAsync(step.Chunk, ct);
@@ -34,5 +44,7 @@ public abstract class DripStrategy(
}
}
protected abstract IEnumerable<string> Content(IRandomSource random);
protected virtual string Extra(DripOptions options) => "";
protected abstract IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options);
}
+212
View File
@@ -0,0 +1,212 @@
using System.Globalization;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Strategies;
public sealed record FileProfile(
string Name,
string MediaType,
Func<string, bool> Matches,
Func<IRandomSource, IEnumerable<string>> Generate);
public static class FileContent
{
public static readonly IReadOnlyList<FileProfile> Profiles =
[
new("git-drip", "text/plain; charset=utf-8", IsGit, GitConfig),
new("svn-drip", "text/plain; charset=utf-8", path => IsInside(path, "/.svn"), Svn),
new("hg-drip", "text/plain; charset=utf-8", path => IsInside(path, "/.hg"), Mercurial),
new("wordpress-drip", "text/html; charset=UTF-8", path => LastSegment(path) == "wp-login.php", WordPressLogin),
new("hikvision-drip", "application/xml", path => path.StartsWith("/sdk/", StringComparison.Ordinal) || path.StartsWith("/isapi/", StringComparison.Ordinal), Hikvision),
new("env-drip", "text/plain; charset=utf-8", path => IsEnv(LastSegment(path)), Env),
new("json-drip", "application/json", path => path.EndsWith(".json", StringComparison.Ordinal), Json),
new("xml-drip", "application/xml", path => path.EndsWith(".xml", StringComparison.Ordinal), Xml),
new("yaml-drip", "text/plain; charset=utf-8", path => path.EndsWith(".yml", StringComparison.Ordinal) || path.EndsWith(".yaml", StringComparison.Ordinal), Yaml),
new("sql-drip", "text/plain; charset=utf-8", path => path.EndsWith(".sql", StringComparison.Ordinal), Sql)
];
public static FileProfile? Match(string? path)
{
if (string.IsNullOrEmpty(path))
{
return null;
}
var normalized = path.ToLowerInvariant();
return Profiles.FirstOrDefault(profile => profile.Matches(normalized));
}
private static bool IsInside(string path, string directory) =>
path.Contains(directory + "/", StringComparison.Ordinal) || path.EndsWith(directory, StringComparison.Ordinal);
private static bool IsGit(string path) => IsInside(path, "/.git") || LastSegment(path).StartsWith(".git", StringComparison.Ordinal);
private static string LastSegment(string path) => path[(path.LastIndexOf('/') + 1)..];
private static bool IsEnv(string name) =>
name.StartsWith(".env", StringComparison.Ordinal) || name.EndsWith(".env", StringComparison.Ordinal) || name == "env";
private static IEnumerable<string> Env(IRandomSource random)
{
yield return $"APP_NAME=Portal\nAPP_ENV=production\nAPP_DEBUG=false\nAPP_URL=https://example.com\nAPP_KEY=base64:{Hex(random, 32)}\n\n"
+ $"DB_CONNECTION=mysql\nDB_HOST=127.0.0.1\nDB_PORT=3306\nDB_DATABASE=app\nDB_USERNAME=app\nDB_PASSWORD={Hex(random, 16)}\n\n";
while (true)
{
var key = $"{Upper(random)}_{Upper(random)}";
yield return random.Next(0, 4) switch
{
0 => $"{key}=true\n",
1 => $"{key}={random.Next(1, 65536)}\n",
2 => $"{key}=https://{LoremText.Word(random)}.internal/\n",
_ => $"{key}={Hex(random, 24)}\n"
};
}
}
private static IEnumerable<string> WordPressLogin(IRandomSource random)
{
yield return """
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Log In &lsaquo; Portal &#8212; WordPress</title>
<meta name='robots' content='max-image-preview:large, noindex, noarchive' />
<link rel='stylesheet' id='login-css' href='/wp-admin/css/login.min.css?ver=6.4.3' media='all' />
<meta name='viewport' content='width=device-width' />
</head>
<body class="login no-js login-action-login wp-core-ui locale-en-us">
<div id="login">
<h1><a href="https://wordpress.org/">Powered by WordPress</a></h1>
<form name="loginform" id="loginform" action="/wp-login.php" method="post">
<p>
<label for="user_login">Username or Email Address</label>
<input type="text" name="log" id="user_login" class="input" value="" size="20" autocapitalize="off" autocomplete="username" required="required" />
</p>
<div class="user-pass-wrap">
<label for="user_pass">Password</label>
<input type="password" name="pwd" id="user_pass" class="input password-input" value="" size="20" autocomplete="current-password" required="required" />
</div>
<p class="submit">
<input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In" />
<input type="hidden" name="redirect_to" value="/wp-admin/" />
<input type="hidden" name="testcookie" value="1" />
</p>
</form>
<p id="nav"><a href="/wp-login.php?action=lostpassword">Lost your password?</a></p>
<p id="backtoblog"><a href="/">&larr; Go to Portal</a></p>
</div>
""";
while (true)
{
yield return $"<!-- {Hex(random, 32)} -->\n";
}
}
private static IEnumerable<string> Hikvision(IRandomSource random)
{
yield return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<LanguageList version=\"2.0\" xmlns=\"http://www.hikvision.com/ver20/XMLSchema\">\n";
var id = 1;
while (true)
{
yield return $" <Language>\n <id>{id++}</id>\n <name>{LoremText.Word(random)}</name>\n <enabled>{(random.Next(0, 2) == 0 ? "true" : "false")}</enabled>\n </Language>\n";
}
}
private static IEnumerable<string> Json(IRandomSource random)
{
yield return "{\n \"name\": \"portal\",\n \"version\": \"1.4.2\",\n \"private\": true,\n \"entries\": [\n";
var id = 1;
while (true)
{
yield return $" {{\"id\": {id++}, \"name\": \"{LoremText.Word(random)}\", \"token\": \"{Hex(random, 16)}\", \"enabled\": {(random.Next(0, 2) == 0 ? "true" : "false")}}},\n";
}
}
private static IEnumerable<string> Xml(IRandomSource random)
{
yield return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
while (true)
{
var date = string.Create(CultureInfo.InvariantCulture, $"2026-{random.Next(1, 13):00}-{random.Next(1, 29):00}");
yield return $" <url>\n <loc>https://example.com/{Pick(random, MazeContent.Roots)}/{LoremText.Phrase(random, 2).Replace(' ', '-')}</loc>\n <lastmod>{date}</lastmod>\n </url>\n";
}
}
private static IEnumerable<string> Yaml(IRandomSource random)
{
yield return "version: \"3.8\"\nservices:\n";
while (true)
{
yield return $" {LoremText.Word(random)}:\n image: {LoremText.Word(random)}:{random.Next(1, 10)}.{random.Next(0, 20)}\n restart: unless-stopped\n environment:\n - SECRET={Hex(random, 12)}\n";
}
}
private static IEnumerable<string> Sql(IRandomSource random)
{
yield return "-- MySQL dump 10.13 Distrib 8.0.36, for Linux (x86_64)\n--\n-- Host: localhost Database: app\n-- ------------------------------------------------------\n\n"
+ "DROP TABLE IF EXISTS `users`;\nCREATE TABLE `users` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(64) NOT NULL,\n `token` varchar(64) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n\n"
+ "LOCK TABLES `users` WRITE;\n";
var id = 1;
while (true)
{
yield return $"INSERT INTO `users` VALUES ({id++},'{LoremText.Word(random)}','{Hex(random, 32)}');\n";
}
}
private static IEnumerable<string> GitConfig(IRandomSource random)
{
yield return "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n\tlogallrefupdates = true\n"
+ "[remote \"origin\"]\n\turl = https://example.com/portal.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n";
while (true)
{
var branch = $"{LoremText.Word(random)}-{LoremText.Word(random)}";
yield return $"[branch \"{branch}\"]\n\tremote = origin\n\tmerge = refs/heads/{branch}\n";
}
}
private static IEnumerable<string> Svn(IRandomSource random)
{
yield return "12\n\ndir\n4821\nhttps://svn.example.com/repos/portal/trunk\nhttps://svn.example.com/repos/portal\n2026-03-14T09:21:07.512340Z\n4821\ndeploy\n\n\n\n\n\n\n\n";
while (true)
{
var date = string.Create(CultureInfo.InvariantCulture, $"2026-{random.Next(1, 13):00}-{random.Next(1, 29):00}T{random.Next(0, 24):00}:{random.Next(0, 60):00}:{random.Next(0, 60):00}.{random.Next(0, 1_000_000):000000}Z");
yield return $"{LoremText.Word(random)}-{LoremText.Word(random)}.php\nfile\n\n\n{date}\n{Hex(random, 32)}\n{date}\ndeploy\n{random.Next(200, 90_000)}\n\n\n\n\n";
}
}
private static IEnumerable<string> Mercurial(IRandomSource random)
{
yield return "dotencode\nfncache\ngeneraldelta\nrevlogv1\nsparserevlog\nstore\n";
while (true)
{
yield return $"data/{Pick(random, MazeContent.Roots)}/{LoremText.Word(random)}-{LoremText.Word(random)}.php.i\n";
}
}
private static string Hex(IRandomSource random, int length)
{
var chars = new char[length];
for (var i = 0; i < length; i++)
{
chars[i] = "0123456789abcdef"[random.Next(0, 16)];
}
return new string(chars);
}
private static string Upper(IRandomSource random) => LoremText.Word(random).ToUpperInvariant();
private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)];
}
@@ -0,0 +1,17 @@
using Flypaper.Core.Abstractions;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
public sealed class FileDripStrategy(
FileProfile profile,
IOptionsMonitor<DripOptions> options,
IRandomSource random,
TimeProvider timeProvider) : DripStrategy(options, random, timeProvider)
{
public override string Name => profile.Name;
public override string MediaType => profile.MediaType;
protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) => profile.Generate(random);
}
@@ -14,5 +14,5 @@ public sealed class HtmlDripStrategy(
public override string MediaType => "text/html; charset=utf-8";
protected override IEnumerable<string> Content(IRandomSource random) => HtmlContent.Generate(random);
protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) => HtmlContent.Generate(random);
}
+231
View File
@@ -0,0 +1,231 @@
using System.Globalization;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Strategies;
public static partial class MazeContent
{
public static readonly string[] Roots =
["wiki", "docs", "blog", "backup", "archive", "files", "kb", "guides", "releases", "news", "help", "support", "products"];
private const int MaxDepth = 6;
public static bool IsDirectory(string? path) => path is { Length: > 1 } && path[^1] == '/';
public static IEnumerable<string> Page(IRandomSource random, string? path, string? host, int spacing)
{
var site = new Site(path, host);
var siteName = site.Host ?? "Portal";
var title = $"{LoremText.Capitalize(LoremText.Phrase(random, random.Next(2, 4)))} · {siteName}";
yield return $$"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{title}}</title>
<style>body{margin:0 auto;max-width:52rem;padding:1.5rem;font:16px/1.6 system-ui,sans-serif}nav a{margin-right:1rem}</style>
</head>
<body>
<header>
<h1>{{title}}</h1>
""";
yield return Navigation(random, site);
yield return "</header>\n<main>\n<h2>Related pages</h2>\n" + List(random, site, random.Next(7, 11));
yield return "<p>";
var minFiller = Math.Max(1, spacing / 2);
var maxFiller = Math.Max(minFiller, spacing * 3 / 2);
while (true)
{
var words = Math.Max(2, random.Next(minFiller, maxFiller + 1) / 7);
yield return $"{LoremText.Capitalize(LoremText.Phrase(random, words))}. {Anchor(random, site)} ";
switch (random.Next(0, 8))
{
case 0:
yield return $"</p>\n{List(random, site, random.Next(3, 6))}<p>";
break;
case 1:
yield return $"</p>\n<h3>{LoremText.Capitalize(LoremText.Phrase(random, random.Next(2, 6)))}</h3>\n<p>";
break;
}
}
}
public static IEnumerable<string> Listing(IRandomSource random, string? path, string? host)
{
var site = new Site(path, host);
var shown = WebUtility.HtmlEncode(site.DisplayPath);
var wide = site.Section is "backup" or "files" or "archive";
yield return $$"""
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of {{shown}}</title>
</head>
<body>
<h1>Index of {{shown}}</h1>
<pre>Name{{new string(' ', 46)}}Last modified Size
<hr><a href="../">Parent Directory</a> -
""";
while (true)
{
yield return Entry(random, site, wide);
}
}
private static string Entry(IRandomSource random, Site site, bool wide)
{
var slug = Slug(random, site);
var directory = random.Next(0, 3) == 0;
var name = directory
? slug + "/"
: wide
? $"{slug}-{Date(random)[..10]}{Pick(random, [".tar.gz", ".zip", ".bak", ".gz"])}"
: $"{slug}{Pick(random, [".html", ".html", ".htm", ".txt"])}";
var size = directory
? "-"
: random.Next(0, 4) == 0
? string.Create(CultureInfo.InvariantCulture, $"{random.Next(1, 900)}.{random.Next(0, 10)}M")
: string.Create(CultureInfo.InvariantCulture, $"{random.Next(1, 900)}K");
var href = random.Next(0, 5) == 0 ? Absolute(random, site) : name;
var padding = new string(' ', Math.Max(1, 50 - name.Length));
return $"<a href=\"{href}\">{name}</a>{padding}{Date(random)} {size}\n";
}
private static string Date(IRandomSource random) =>
string.Create(CultureInfo.InvariantCulture, $"{random.Next(2022, 2027)}-{random.Next(1, 13):00}-{random.Next(1, 29):00} {random.Next(0, 24):00}:{random.Next(0, 60):00}");
private static string Navigation(IRandomSource random, Site site)
{
var builder = new StringBuilder("<nav>\n");
var count = random.Next(8, 12);
for (var i = 0; i < count; i++)
{
builder.Append($"<a href=\"{Href(random, site, rootOnly: i % 2 == 0)}\">{LoremText.Capitalize(LoremText.Word(random))}</a>\n");
}
return builder.Append("</nav>\n").ToString();
}
private static string List(IRandomSource random, Site site, int items)
{
var builder = new StringBuilder("<ul>\n");
for (var i = 0; i < items; i++)
{
builder.Append($"<li>{Anchor(random, site)}</li>\n");
}
return builder.Append("</ul>\n").ToString();
}
private static string Anchor(IRandomSource random, Site site) =>
$"<a href=\"{Href(random, site)}\">{LoremText.Capitalize(LoremText.Phrase(random, random.Next(2, 5)))}</a>";
private static string Href(IRandomSource random, Site site, bool rootOnly = false)
{
if (rootOnly)
{
return $"/{Pick(random, Roots)}/";
}
var kind = random.Next(0, 10);
if (site.Section is null)
{
kind = 5 + kind % 5;
}
else if (site.Depth >= MaxDepth && kind is 0 or 3)
{
kind = 4;
}
return kind switch
{
0 => $"{Slug(random, site)}/",
1 or 2 => Slug(random, site),
3 => $"{LoremText.Word(random)}/{Slug(random, site)}",
4 => random.Next(0, 2) == 0 ? "../" : $"../{Slug(random, site)}",
< 8 => Absolute(random, site),
_ => site.Host is { } host ? $"http://{host}{Absolute(random, site)}" : Absolute(random, site)
};
}
private static string Absolute(IRandomSource random, Site site)
{
var root = site.Section is { } section && random.Next(0, 10) < 7 ? section : Pick(random, Roots);
var slug = Slug(random, site);
return root switch
{
"docs" => $"/docs/v{random.Next(1, 5)}/{slug}",
"blog" => string.Create(CultureInfo.InvariantCulture, $"/blog/{random.Next(2022, 2027)}/{random.Next(1, 13):00}/{slug}"),
"backup" => string.Create(CultureInfo.InvariantCulture, $"/backup/{random.Next(2022, 2027)}/{random.Next(1, 13):00}/"),
_ => random.Next(0, 3) == 0 ? $"/{root}/{slug}/" : $"/{root}/{slug}"
};
}
private static string Slug(IRandomSource random, Site site)
{
var words = new List<string>();
var count = random.Next(1, 4);
for (var i = 0; i < count; i++)
{
words.Add(LoremText.Word(random));
}
if (site.Topic is { } topic && random.Next(0, 4) == 0)
{
words[0] = topic;
}
return string.Join('-', words);
}
private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)];
[GeneratedRegex("^[A-Za-z0-9.-]{1,253}$")]
private static partial Regex HostPattern();
[GeneratedRegex("^[a-z]{3,}$")]
private static partial Regex TopicPattern();
private sealed class Site
{
public Site(string? path, string? host)
{
var normalized = (path ?? "/").ToLowerInvariant();
var segments = normalized.Split('/', StringSplitOptions.RemoveEmptyEntries);
var endsWithSlash = normalized.EndsWith('/');
Section = segments.Length > 0 && Array.IndexOf(Roots, segments[0]) >= 0 ? segments[0] : null;
Depth = endsWithSlash ? segments.Length : Math.Max(0, segments.Length - 1);
Host = host is not null && HostPattern().IsMatch(host) ? host : null;
DisplayPath = normalized.Length > 200 ? normalized[..200] : normalized;
if (!endsWithSlash && segments.Length > 0)
{
var word = segments[^1].Split('-', '.', '_')[0];
Topic = TopicPattern().IsMatch(word) ? word : null;
}
}
public string? Section { get; }
public int Depth { get; }
public string? Host { get; }
public string? Topic { get; }
public string DisplayPath { get; }
}
}
@@ -0,0 +1,44 @@
using System.Globalization;
using Flypaper.Core.Abstractions;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
public enum MazeKind
{
Page,
Listing,
Bait
}
public sealed class MazeDripStrategy(
MazeKind kind,
IOptionsMonitor<DripOptions> options,
IRandomSource random,
TimeProvider timeProvider) : DripStrategy(options, random, timeProvider), IHoldExtension
{
public const string PageName = "maze-drip";
public const string ListingName = "index-drip";
public const string BaitName = "robots-bait";
public override string Name => kind switch
{
MazeKind.Listing => ListingName,
MazeKind.Bait => BaitName,
_ => PageName
};
public override string MediaType => "text/html; charset=utf-8";
public TimeSpan MinimumHold => kind == MazeKind.Bait ? TimeSpan.FromHours(24) : TimeSpan.Zero;
protected override string Extra(DripOptions options) =>
string.Create(CultureInfo.InvariantCulture, $" link {options.LinkSpacing}B");
protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) =>
kind == MazeKind.Listing || kind == MazeKind.Bait && MazeContent.IsDirectory(channel.Path)
? MazeContent.Listing(random, channel.Path, channel.Host)
: MazeContent.Page(random, channel.Path, channel.Host, options.LinkSpacing);
}
@@ -0,0 +1,27 @@
using System.Text;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
public sealed class RobotsStaticStrategy(IOptionsMonitor<DripOptions> options) : ITarpitStrategy, IStrategyDetails
{
public const string StrategyName = "robots-static";
public const string Path = "/robots.txt";
public string Name => StrategyName;
public string MediaType => "text/plain; charset=utf-8";
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
public string Describe() => Name;
public async Task RunAsync(ITrapChannel channel, CancellationToken ct) =>
await channel.WriteAsync(Encoding.UTF8.GetBytes(Body()), ct);
public string Body() =>
"User-agent: *\nDisallow: /\n" + string.Concat(BaitPaths.Parse(options.CurrentValue.BaitPaths).Select(bait => $"Disallow: {bait}\n"));
}
@@ -14,5 +14,5 @@ public sealed class TextDripStrategy(
public override string MediaType => "text/plain; charset=utf-8";
protected override IEnumerable<string> Content(IRandomSource random) => TextContent.Generate(random);
protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) => TextContent.Generate(random);
}
+4
View File
@@ -8,6 +8,10 @@ internal sealed class HttpTrapChannel(TrapSession session, HttpResponse response
{
public TrapSession Session => session;
public string? Path => response.HttpContext.Request.Path.Value;
public string? Host => response.HttpContext.Request.Host.Host;
public async ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct)
{
await response.Body.WriteAsync(data, ct);
@@ -35,7 +35,8 @@ internal sealed class FlypaperMiddleware(
var trapContext = new TrapContext(
session,
$"{request.Method} {StoredHost(request.Host)}{request.Path}{request.QueryString}",
request.Headers.UserAgent.ToString());
request.Headers.UserAgent.ToString(),
request.Path.Value);
var outcome = await runner.RunAsync(
trapContext,
@@ -73,6 +74,7 @@ internal sealed class FlypaperMiddleware(
var response = context.Response;
response.StatusCode = StatusCodes.Status200OK;
response.ContentType = strategy is IStrategyDetails details ? details.MediaType : "text/html; charset=utf-8";
response.Headers.Server = "nginx";
response.Headers.CacheControl = "no-store";
response.Headers["X-Accel-Buffering"] = "no";
await response.StartAsync(ct);
@@ -1,18 +1,20 @@
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<StrategySample> StrategyCatches,
IReadOnlyList<TopEntry> TopCountries,
IReadOnlyList<TopEntry> TopProviders,
IReadOnlyDictionary<string, int> CatchesByCountry);
public sealed record TopEntry(string Key, int Count, TimeSpan HoldTime, string? Label = null);
public sealed record TopEntry(string Key, int Count, TimeSpan HoldTime, string? Label = null, TimeSpan? MedianHold = null);
public sealed record StrategySample(string Strategy, long DurationMs);
@@ -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,11 +36,13 @@ 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),
await catches.Select(e => new StrategySample(e.Strategy, e.DurationMs)).ToListAsync(ct),
countries
.Take(TopCount)
.Select(x => new TopEntry(x.Key, x.Count, TimeSpan.FromMilliseconds(x.DurationMs), x.Name))
@@ -52,6 +53,91 @@ 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 (filter.Strategy is { } strategy)
{
var bases = strategy.Bases;
events = events.Where(e => bases.Any(name => e.Strategy == name || EF.Functions.Like(e.Strategy, name + " %", "\\")));
foreach (var flag in strategy.With)
{
var pattern = $"% {flag} %";
events = events.Where(e => EF.Functions.Like(" " + e.Strategy + " ", pattern, "\\"));
}
foreach (var flag in strategy.Without)
{
var pattern = $"% {flag} %";
events = events.Where(e => !EF.Functions.Like(" " + e.Strategy + " ", pattern, "\\"));
}
}
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var pattern = $"%{filter.Search.Trim().Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_")}%";
var strategyNames = filter.SearchStrategies ?? [];
events = events.Where(e =>
EF.Functions.Like(e.RemoteIp, pattern, "\\")
|| strategyNames.Any(name => e.Strategy == name || EF.Functions.Like(e.Strategy, name + " %", "\\"))
|| EF.Functions.Like(e.Provider!, pattern, "\\")
|| EF.Functions.Like(e.Target!, pattern, "\\")
|| EF.Functions.Like(e.Strategy, 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,26 @@
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,
StrategyMatch? Strategy = null,
string? Search = null,
int Limit = RecentFilter.DefaultLimit,
IReadOnlyList<string>? SearchStrategies = null)
{
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);
public sealed record StrategyMatch(IReadOnlyList<string> Bases, IReadOnlyList<string> With, IReadOnlyList<string> Without);
@@ -38,6 +38,7 @@ public static class FlypaperStorageExtensions
services.AddHostedService<OriginBackfill>();
services.AddSingleton<DashboardQueries>();
services.AddSingleton<CatchQueries>();
services.AddSingleton<IRepeatOffenderLookup, RepeatOffenderLookup>();
services.AddSingleton<TrapDataMaintenance>();
services.AddHostedService<RetentionCleanup>();
return services;
@@ -0,0 +1,248 @@
// <auto-generated />
using System;
using Flypaper.Storage;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Flypaper.Storage.Migrations
{
[DbContext(typeof(FlypaperDbContext))]
[Migration("20261117165523_AddResearch")]
partial class AddResearch
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
modelBuilder.Entity("Flypaper.Storage.Entities.IdeaEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Commit")
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Efficiency")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Effort")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<DateTime?>("ImplementedOn")
.HasColumnType("TEXT");
b.Property<string>("Rationale")
.IsRequired()
.HasMaxLength(20000)
.HasColumnType("TEXT");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Ideas");
});
modelBuilder.Entity("Flypaper.Storage.Entities.LabEntryEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Commit")
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTime>("Date")
.HasColumnType("TEXT");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Strategies")
.HasMaxLength(512)
.HasColumnType("TEXT");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(20000)
.HasColumnType("TEXT");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("Date");
b.ToTable("LabEntries");
});
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("CanWrite")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastUsedAt")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("McpTokens");
});
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
{
b.Property<string>("Key")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Key");
b.ToTable("Settings");
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("Asn")
.HasColumnType("INTEGER");
b.Property<long>("BytesSent")
.HasColumnType("INTEGER");
b.Property<string>("City")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("ClientInfo")
.HasMaxLength(2048)
.HasColumnType("TEXT");
b.Property<string>("Country")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("CountryCode")
.HasMaxLength(2)
.HasColumnType("TEXT");
b.Property<long>("DurationMs")
.HasColumnType("INTEGER");
b.Property<DateTime>("EndedAt")
.HasColumnType("TEXT");
b.Property<string>("Outcome")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Protocol")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Provider")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("RemoteIp")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<Guid>("SessionId")
.HasColumnType("TEXT");
b.Property<DateTime>("StartedAt")
.HasColumnType("TEXT");
b.Property<string>("Strategy")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<string>("Target")
.HasMaxLength(2048)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("Asn");
b.HasIndex("CountryCode");
b.HasIndex("RemoteIp");
b.HasIndex("StartedAt");
b.ToTable("TrapEvents");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,82 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class AddResearch : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "CanWrite",
table: "McpTokens",
type: "INTEGER",
nullable: false,
defaultValue: false);
migrationBuilder.CreateTable(
name: "Ideas",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
Effort = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Efficiency = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Rationale = table.Column<string>(type: "TEXT", maxLength: 20000, nullable: false),
Status = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
ImplementedOn = table.Column<DateTime>(type: "TEXT", nullable: true),
Commit = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Ideas", x => x.Id);
});
migrationBuilder.CreateTable(
name: "LabEntries",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Date = table.Column<DateTime>(type: "TEXT", nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
Kind = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Text = table.Column<string>(type: "TEXT", maxLength: 20000, nullable: false),
Commit = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
Strategies = table.Column<string>(type: "TEXT", maxLength: 512, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_LabEntries", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_LabEntries_Date",
table: "LabEntries",
column: "Date");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Ideas");
migrationBuilder.DropTable(
name: "LabEntries");
migrationBuilder.DropColumn(
name: "CanWrite",
table: "McpTokens");
}
}
}
@@ -0,0 +1,151 @@
// <auto-generated />
using System;
using Flypaper.Storage;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Flypaper.Storage.Migrations
{
[DbContext(typeof(FlypaperDbContext))]
[Migration("20261121100100_RemoveResearch")]
partial class RemoveResearch
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastUsedAt")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("McpTokens");
});
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
{
b.Property<string>("Key")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Key");
b.ToTable("Settings");
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("Asn")
.HasColumnType("INTEGER");
b.Property<long>("BytesSent")
.HasColumnType("INTEGER");
b.Property<string>("City")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("ClientInfo")
.HasMaxLength(2048)
.HasColumnType("TEXT");
b.Property<string>("Country")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("CountryCode")
.HasMaxLength(2)
.HasColumnType("TEXT");
b.Property<long>("DurationMs")
.HasColumnType("INTEGER");
b.Property<DateTime>("EndedAt")
.HasColumnType("TEXT");
b.Property<string>("Outcome")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Protocol")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Provider")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("RemoteIp")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<Guid>("SessionId")
.HasColumnType("TEXT");
b.Property<DateTime>("StartedAt")
.HasColumnType("TEXT");
b.Property<string>("Strategy")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<string>("Target")
.HasMaxLength(2048)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("Asn");
b.HasIndex("CountryCode");
b.HasIndex("RemoteIp");
b.HasIndex("StartedAt");
b.ToTable("TrapEvents");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,82 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class RemoveResearch : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Ideas");
migrationBuilder.DropTable(
name: "LabEntries");
migrationBuilder.DropColumn(
name: "CanWrite",
table: "McpTokens");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "CanWrite",
table: "McpTokens",
type: "INTEGER",
nullable: false,
defaultValue: false);
migrationBuilder.CreateTable(
name: "Ideas",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Commit = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
Efficiency = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Effort = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
ImplementedOn = table.Column<DateTime>(type: "TEXT", nullable: true),
Rationale = table.Column<string>(type: "TEXT", maxLength: 20000, nullable: false),
Status = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Ideas", x => x.Id);
});
migrationBuilder.CreateTable(
name: "LabEntries",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Commit = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
Date = table.Column<DateTime>(type: "TEXT", nullable: false),
Kind = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Strategies = table.Column<string>(type: "TEXT", maxLength: 512, nullable: true),
Text = table.Column<string>(type: "TEXT", maxLength: 20000, nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_LabEntries", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_LabEntries_Date",
table: "LabEntries",
column: "Date");
}
}
}
@@ -93,6 +93,8 @@ public sealed class CatchQueries(IDbContextFactory<FlypaperDbContext> dbContextF
.Select(g => new TopRow { Key = "AS" + g.Key.ToString(), Label = g.Max(e => e.Provider), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
TopDimension.Targets => catches.Where(e => e.Target != null).GroupBy(e => e.Target!)
.Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
TopDimension.Strategies => catches.GroupBy(e => e.Strategy)
.Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
TopDimension.UserAgents => catches.Where(e => e.ClientInfo != null).GroupBy(e => e.ClientInfo!)
.Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
_ => throw new ArgumentOutOfRangeException(nameof(dimension))
@@ -42,6 +42,7 @@ public enum TopDimension
Countries,
Providers,
Targets,
Strategies,
UserAgents
}
@@ -0,0 +1,16 @@
using System.Net;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Queries;
public sealed class RepeatOffenderLookup(IDbContextFactory<FlypaperDbContext> dbContextFactory) : IRepeatOffenderLookup
{
public async ValueTask<bool> HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct)
{
var ip = address.ToString();
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.TrapEvents.AnyAsync(e => e.RemoteIp == ip && e.Outcome == TrapOutcome.Timeout && e.StartedAt >= since, ct);
}
}
@@ -0,0 +1,126 @@
using System.Globalization;
using System.Net;
using Flypaper.Core.Models;
using Flypaper.Storage.Dashboard;
using Flypaper.Web.Components.Shared;
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? Strategie = 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? strategie,
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(strategie) is { } strategy ? StrategyNames.GroupKey(strategy) : null,
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,
StrategyNames.Group(Strategie),
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, "strategie", Strategie);
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,182 @@
<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" TitleFormatter="tab.TitleFormatter" BadgesFormatter="tab.BadgesFormatter"
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, Strategie, User-Agent" />
</label>
@foreach (var (name, value) in new[] { ("provider", _filter.Provider), ("ip", _filter.Ip), ("ziel", _filter.Ziel), ("strategie", _filter.Strategie) })
{
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-strategy">Strategie</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);
var strategy = StrategyNames.Describe(trapEvent.Strategy);
<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 strategy-info">
<strong>@strategy.DisplayName</strong>
@foreach (var badge in strategy.Badges)
{
<span class="badge">@badge</span>
}
@if (strategy.Explanation is not null)
{
<div>@strategy.Explanation</div>
}
@foreach (var detail in strategy.Details)
{
<div>@detail</div>
}
<div class="mono">@strategy.Raw</div>
</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-strategy" title="@strategy.Tooltip">@strategy.DisplayName@foreach (var badge in strategy.Badges){<span class="badge">@badge</span>}</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 +250,118 @@
@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 = "strategie")] public string? Strategie { 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, Strategie, Q, Limit);
_data = await Queries.GetAsync();
_recent = await Queries.GetRecentAsync(_filter.ToRecentFilter() with { SearchStrategies = StrategyNames.Matching(_filter.Q) });
_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),
new("strategies", "Strategien", "Strategie", StrategyNames.Rank(data.StrategyCatches, 10), f => f.Strategie, (f, key) => f with { Strategie = key }, KeyFormatter: _ => "", LabelFormatter: (key, _) => StrategyNames.Display(key), TitleFormatter: key => StrategyNames.Describe(key).Tooltip, BadgesFormatter: key => StrategyNames.Describe(key).Badges)
];
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.Strategie is { } strategie)
{
var badges = StrategyNames.Describe(strategie).Badges;
yield return ($"Strategie: {StrategyNames.Display(strategie)}{(badges.Count == 0 ? "" : $" ({string.Join(", ", badges)})")}", reset with { Strategie = 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,
Func<string?, string?>? TitleFormatter = null,
Func<string?, IReadOnlyList<string>>? BadgesFormatter = null);
}
@@ -1,44 +1,105 @@
@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" />
@using Flypaper.Web.Components.Shared
@{
var byMedian = Entries.Any(entry => entry.MedianHold is not null);
var barMax = byMedian
? Entries.Where(entry => entry.Count >= StrategyNames.MinCatches).Select(entry => entry.MedianHold!.Value.TotalMilliseconds).DefaultIfEmpty(0).Max()
: Entries.Count == 0 ? 0 : Entries[0].Count;
}
@if (Entries.Count == 0)
{
<p class="empty">Noch keine Einträge.</p>
}
else
{
<table class="top-table @(byMedian ? "by-median" : null)">
<colgroup>
<col />
<col class="share" />
<col class="count" />
@if (byMedian)
{
<col class="hold" />
</colgroup>
<thead>
<tr>
<th>@KeyLabel</th>
<th class="num">Fänge</th>
<th class="num">Haltezeit</th>
</tr>
</thead>
<tbody>
@foreach (var entry in Entries)
}
<col class="hold sum" />
</colgroup>
<thead>
<tr>
<th>@KeyLabel</th>
<th><span class="sr-only">Anteil</span></th>
<th class="num">Fänge</th>
@if (byMedian)
{
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>
<th class="num" title="Mittlere Haltezeit pro Fang (Median): Einzelne Dauerhalter verfälschen sie nicht">Median</th>
}
</tbody>
</table>
<th class="num sum">@(byMedian ? "Summe" : "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 value = byMedian ? entry.MedianHold!.Value.TotalMilliseconds : entry.Count;
var share = (barMax == 0 ? 0 : Math.Min(100, value * 100.0 / barMax)).ToString("0.#", CultureInfo.InvariantCulture);
var sparse = byMedian && entry.Count < StrategyNames.MinCatches;
var badges = BadgesFormatter?.Invoke(entry.Key) ?? [];
var active = IsActive(entry);
var title = TitleFormatter?.Invoke(entry.Key) ?? (label is null ? key : $"{label} · {key}");
if (sparse)
{
title += $"\nNur {entry.Count} {(entry.Count == 1 ? "Fang" : "Fänge")}: wenig aussagekräftig";
}
<tr data-href="@Href(entry)" class="@(active ? "active" : null) @(sparse ? "sparse" : 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>
@foreach (var badge in badges)
{
<span class="badge">@badge</span>
}
@if (sparse)
{
<span class="badge sparse-note">wenige Daten</span>
}
@if (key.Length > 0)
{
<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>
@if (byMedian)
{
<td class="num">@Formatting.Duration(entry.MedianHold!.Value)</td>
}
<td class="num sum">@Formatting.Duration(entry.HoldTime)</td>
</tr>
}
</tbody>
</table>
@if (byMedian)
{
<p class="top-note">Balken = Median Haltezeit pro Fang. Unter @StrategyNames.MinCatches Fängen wenig aussagekräftig, diese Zeilen stehen am Ende.</p>
}
</section>
}
@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 +110,11 @@
[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] public Func<string?, string?>? TitleFormatter { get; set; }
[Parameter] public Func<string?, IReadOnlyList<string>>? BadgesFormatter { get; set; }
[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>
@@ -1 +1 @@
{"width":1000.0,"height":439.1,"countries":[{"code":"AF","name":"Afghanistan","path":"M669.6,108.7L671,108.7L673.1,109.4L674,109.9L675.5,108.8L676.6,109.4L677,107.9L678.5,108L678.7,107.5L678.6,106.1L679.3,104.9L680.9,105.7L681,106.7L681.8,106.9L682.4,109.7L683.8,110.8L684.5,110.1L685.5,109.8L686.6,108.3L688.4,108.5L691.1,108.5L691.8,109.5L690.5,109.9L689.4,110.5L686.6,110.9L684,111.6L683,113.1L684,114.5L684.8,116.2L683.9,117.6L684.4,119L684.1,120.2L681.6,120.1L683.2,122.4L681.8,123.3L681.2,125.4L681.9,127.5L681.1,128.4L680.1,128.1L678.2,128.6L678.1,129.5L676.2,129.5L675.2,131.5L675.8,134.5L672.6,136L670.7,135.7L670.4,136.5L668.7,136L666.1,136.5L661.3,134.7L663,131.5L662.3,129.3L660.2,128.7L659.5,126.5L658,123.7L658.7,121.8L657.4,121.3L657.6,118.8L657.5,114.5L660.5,115.8L662.3,115.4L662.5,113.8L664.4,113.3L665.5,112.3L665.3,109.6L667.2,108.9L667.3,107.7L668.8,108.6L669.6,108.7Z"},{"code":"AL","name":"Albanien","path":"M552.5,97.2L552.5,98L551.7,98.5L551.7,99.6L550.7,101.2L550.2,100.9L550.1,100.2L548.6,99.1L548.2,97.5L548.2,95.3L548.5,94.3L548,93.8L547.8,92.8L548.7,91.2L548.9,91.8L549.5,91.5L550.1,92.4L550.8,92.7L551,93.9L550.8,95L551.3,96.4L552.5,97.2Z"},{"code":"DZ","name":"Algerien","path":"M476.7,143.4L476.8,142.7L476.8,142.5L476.9,138.2L481.3,135.6L483.9,135.1L486.1,134.1L487.2,132.4L490.3,131L490.4,128.4L491.9,128.1L493.1,126.8L496.6,126.2L497.1,124.8L496.4,124.1L495.5,120.4L495.4,118.4L494.4,116.2L496.9,114.3L499.7,113.7L501.3,112.3L503.8,111.3L508.1,110.7L512.3,110.4L513.6,110.9L516,109.6L518.7,109.5L519.8,110.3L521.5,110.1L521.1,111.9L521.6,115.1L521.1,117.9L519.5,119.8L519.8,122.4L522,124.5L522.1,125.3L523.7,126.7L525.1,133L526,136.2L526.2,137.8L525.9,140.7L526.1,142.3L525.8,144.3L526.1,146.6L525.1,148.1L526.8,150.7L526.9,152.2L527.9,154.3L529.2,153.6L531.4,155.3L532.6,157.6L523.5,164.5L515.6,171.8L511.8,173.4L508.7,173.8L508.7,171.4L507.4,170.8L505.7,169.8L505,168L495.8,160L486.7,152.1L476.7,143.4Z"},{"code":"AO","name":"Angola","path":"M536.7,264L535.7,264.8L535.2,265.8L535.1,267.4L534.4,267.8L533.7,265L534.8,263.3L535.7,262.7L536.7,264ZM534.8,269L536,268.5L536.8,268.6L537.8,268.1L546.1,268.1L546.8,271L547.5,273.3L548.2,274.5L549.2,276.5L551.1,276.2L552,275.6L553.6,276.2L554,275.2L554.8,273L556.5,272.9L556.7,272.2L558.1,272.2L557.8,273.6L561.3,273.5L561.3,275.9L561.8,277.4L561.4,279.7L561.5,282L562.4,283.4L562.2,287.9L562.9,287.5L564.1,287.6L565.8,287.1L567.1,287.3L567.4,288.5L567,290.3L567.4,292.1L567,293.5L567.2,294.8L561.3,294.7L560.8,306.7L562.5,309.7L564.3,312L559.1,313.5L552.4,313L550.6,311.2L539.3,311.4L538.9,311.7L537.3,310L535.5,309.9L533.8,310.5L532.5,311.2L532.3,308.9L532.7,305.6L533.8,302.2L533.9,300.6L534.9,297.2L535.6,295.6L537.3,293.2L538.2,291.5L538.5,288.7L538.4,286.6L537.6,285.2L536.9,282.9L536.2,280.6L536.4,279.8L537.3,278.3L536.5,274.7L535.9,272.1L534.5,269.7L534.8,269Z"},{"code":"AR","name":"Argentinien","path":"M343.2,430.7L344.7,432L346.9,434.2L350.6,435.8L354.1,436.5L353.8,437.9L351.7,438.1L350.1,437.1L348.7,437L346.3,437L343.2,430.7ZM347.6,358.1L347.5,361L347.5,364.6L348.3,368L347.9,368.8L348.2,371L348.5,372.8L352.4,375.8L352.6,378.1L354.6,379.6L354.9,381.2L353.5,385.5L350.2,387.3L345.3,388L342.5,387.7L343.6,389.7L343.8,392.1L344.7,393.8L343.6,395L341.2,395.4L338.4,394.2L337.7,395.1L339.1,398.3L341.1,399.3L342.1,398.3L343.4,399.9L341.5,400.9L340.2,402.9L340.9,406.1L341,407.8L338.7,407.8L337.4,409.4L337.6,411.8L340.8,414L343.4,414.6L343.6,417.4L341.5,419.1L341.5,422.6L339.9,423.8L339.5,425.2L341.7,428.2L344,429.9L342.9,429.7L340.6,429.3L334.9,428.9L333.1,427.2L332.1,425L330.6,425.2L329.3,424.1L327.6,421L328.8,419.6L328.7,417.7L327.8,416.2L327.9,413.6L327.1,409.5L326.1,407.6L326.9,407L326.2,405.8L324.8,405.2L325.1,403.9L323.6,402.6L321.6,398.9L322.4,398.3L320.5,394.3L319.9,390.9L319.6,388L320.7,386.8L318.9,383.5L318,380.4L319.2,378.2L318.4,375.4L318.9,372L318,368.8L317.2,368.2L314.4,362.2L315.2,358.6L314.1,355.1L314.3,351.9L315.3,348.6L316.7,346.3L315.7,344.9L316,343.8L314.7,337.7L317.3,336L317.6,332.2L317.1,331.3L318.9,328L322.6,328.8L324.6,331.5L325.2,328.5L328.3,328.7L328.9,329.5L334.8,335.4L337.2,336L340.9,338.7L343.9,340.1L344.6,341.7L342.9,347.1L345.7,348.1L348.8,348.7L350.9,348.1L352.8,345.3L352.8,342.2L354,341.5L355.7,343.6L356.1,346.4L354.1,348.4L352.6,349.9L350.2,353.3L347.6,358.1Z"},{"code":"AM","name":"Armenien","path":"M617.6,104L616.7,104.1L615.2,102.2L615.1,101.7L614,101.7L613.1,100.8L612.6,100.9L611.4,99.9L609.4,99.1L609.3,97.5L608.6,96.3L611.9,95.8L612.6,96.7L613.7,97.3L613.4,98.1L615,99.2L614.5,100.3L615.8,101.2L617,101.7L617.6,104Z"},{"code":"AZ","name":"Aserbaidschan","path":"M615,93.8L615.8,94L617.9,95.9L619.1,96.2L619.3,95.3L620.5,94L622.2,95.7L624,98L625.2,98.2L626.2,99.1L624.2,99.3L624.4,101.9L624.2,103.1L623.5,103.9L623.9,105.5L623.3,105.7L621.4,103.9L621.9,102.3L620.9,101.3L620,101.6L617.6,104L617,101.7L615.8,101.2L614.5,100.3L615,99.2L613.4,98.1L613.7,97.3L612.6,96.7L611.9,95.8L612.4,95.3L614.5,96.2L615.9,96.4L616.1,96.1L614.5,94.3L615,93.8ZM616.7Line truncated
{"width":1000.0,"height":439.1,"countries":[{"code":"AF","name":"Afghanistan","path":"M669.6,108.7L671,108.7L673.1,109.4L674,109.9L675.5,108.8L676.6,109.4L677,107.9L678.5,108L678.7,107.5L678.6,106.1L679.3,104.9L680.9,105.7L681,106.7L681.8,106.9L682.4,109.7L683.8,110.8L684.5,110.1L685.5,109.8L686.6,108.3L688.4,108.5L691.1,108.5L691.8,109.5L690.5,109.9L689.4,110.5L686.6,110.9L684,111.6L683,113.1L684,114.5L684.8,116.2L683.9,117.6L684.4,119L684.1,120.2L681.6,120.1L683.2,122.4L681.8,123.3L681.2,125.4L681.9,127.5L681.1,128.4L680.1,128.1L678.2,128.6L678.1,129.5L676.2,129.5L675.2,131.5L675.8,134.5L672.6,136L670.7,135.7L670.4,136.5L668.7,136L666.1,136.5L661.3,134.7L663,131.5L662.3,129.3L660.2,128.7L659.5,126.5L658,123.7L658.7,121.8L657.4,121.3L657.6,118.8L657.5,114.5L660.5,115.8L662.3,115.4L662.5,113.8L664.4,113.3L665.5,112.3L665.3,109.6L667.2,108.9L667.3,107.7L668.8,108.6L669.6,108.7Z"},{"code":"AL","name":"Albanien","path":"M552.5,97.2L552.5,98L551.7,98.5L551.7,99.6L550.7,101.2L550.2,100.9L550.1,100.2L548.6,99.1L548.2,97.5L548.2,95.3L548.5,94.3L548,93.8L547.8,92.8L548.7,91.2L548.9,91.8L549.5,91.5L550.1,92.4L550.8,92.7L551,93.9L550.8,95L551.3,96.4L552.5,97.2Z"},{"code":"DZ","name":"Algerien","path":"M476.7,143.4L476.8,142.7L476.8,142.5L476.9,138.2L481.3,135.6L483.9,135.1L486.1,134.1L487.2,132.4L490.3,131L490.4,128.4L491.9,128.1L493.1,126.8L496.6,126.2L497.1,124.8L496.4,124.1L495.5,120.4L495.4,118.4L494.4,116.2L496.9,114.3L499.7,113.7L501.3,112.3L503.8,111.3L508.1,110.7L512.3,110.4L513.6,110.9L516,109.6L518.7,109.5L519.8,110.3L521.5,110.1L521.1,111.9L521.6,115.1L521.1,117.9L519.5,119.8L519.8,122.4L522,124.5L522.1,125.3L523.7,126.7L525.1,133L526,136.2L526.2,137.8L525.9,140.7L526.1,142.3L525.8,144.3L526.1,146.6L525.1,148.1L526.8,150.7L526.9,152.2L527.9,154.3L529.2,153.6L531.4,155.3L532.6,157.6L523.5,164.5L515.6,171.8L511.8,173.4L508.7,173.8L508.7,171.4L507.4,170.8L505.7,169.8L505,168L495.8,160L486.7,152.1L476.7,143.4Z"},{"code":"AO","name":"Angola","path":"M536.7,264L535.7,264.8L535.2,265.8L535.1,267.4L534.4,267.8L533.7,265L534.8,263.3L535.7,262.7L536.7,264ZM534.8,269L536,268.5L536.8,268.6L537.8,268.1L546.1,268.1L546.8,271L547.5,273.3L548.2,274.5L549.2,276.5L551.1,276.2L552,275.6L553.6,276.2L554,275.2L554.8,273L556.5,272.9L556.7,272.2L558.1,272.2L557.8,273.6L561.3,273.5L561.3,275.9L561.8,277.4L561.4,279.7L561.5,282L562.4,283.4L562.2,287.9L562.9,287.5L564.1,287.6L565.8,287.1L567.1,287.3L567.4,288.5L567,290.3L567.4,292.1L567,293.5L567.2,294.8L561.3,294.7L560.8,306.7L562.5,309.7L564.3,312L559.1,313.5L552.4,313L550.6,311.2L539.3,311.4L538.9,311.7L537.3,310L535.5,309.9L533.8,310.5L532.5,311.2L532.3,308.9L532.7,305.6L533.8,302.2L533.9,300.6L534.9,297.2L535.6,295.6L537.3,293.2L538.2,291.5L538.5,288.7L538.4,286.6L537.6,285.2L536.9,282.9L536.2,280.6L536.4,279.8L537.3,278.3L536.5,274.7L535.9,272.1L534.5,269.7L534.8,269Z"},{"code":"AR","name":"Argentinien","path":"M343.2,430.7L344.7,432L346.9,434.2L350.6,435.8L354.1,436.5L353.8,437.9L351.7,438.1L350.1,437.1L348.7,437L346.3,437L343.2,430.7ZM347.6,358.1L347.5,361L347.5,364.6L348.3,368L347.9,368.8L348.2,371L348.5,372.8L352.4,375.8L352.6,378.1L354.6,379.6L354.9,381.2L353.5,385.5L350.2,387.3L345.3,388L342.5,387.7L343.6,389.7L343.8,392.1L344.7,393.8L343.6,395L341.2,395.4L338.4,394.2L337.7,395.1L339.1,398.3L341.1,399.3L342.1,398.3L343.4,399.9L341.5,400.9L340.2,402.9L340.9,406.1L341,407.8L338.7,407.8L337.4,409.4L337.6,411.8L340.8,414L343.4,414.6L343.6,417.4L341.5,419.1L341.5,422.6L339.9,423.8L339.5,425.2L341.7,428.2L344,429.9L342.9,429.7L340.6,429.3L334.9,428.9L333.1,427.2L332.1,425L330.6,425.2L329.3,424.1L327.6,421L328.8,419.6L328.7,417.7L327.8,416.2L327.9,413.6L327.1,409.5L326.1,407.6L326.9,407L326.2,405.8L324.8,405.2L325.1,403.9L323.6,402.6L321.6,398.9L322.4,398.3L320.5,394.3L319.9,390.9L319.6,388L320.7,386.8L318.9,383.5L318,380.4L319.2,378.2L318.4,375.4L318.9,372L318,368.8L317.2,368.2L314.4,362.2L315.2,358.6L314.1,355.1L314.3,351.9L315.3,348.6L316.7,346.3L315.7,344.9L316,343.8L314.7,337.7L317.3,336L317.6,332.2L317.1,331.3L318.9,328L322.6,328.8L324.6,331.5L325.2,328.5L328.3,328.7L328.9,329.5L334.8,335.4L337.2,336L340.9,338.7L343.9,340.1L344.6,341.7L342.9,347.1L345.7,348.1L348.8,348.7L350.9,348.1L352.8,345.3L352.8,342.2L354,341.5L355.7,343.6L356.1,346.4L354.1,348.4L352.6,349.9L350.2,353.3L347.6,358.1Z"},{"code":"AM","name":"Armenien","path":"M617.6,104L616.7,104.1L615.2,102.2L615.1,101.7L614,101.7L613.1,100.8L612.6,100.9L611.4,99.9L609.4,99.1L609.3,97.5L608.6,96.3L611.9,95.8L612.6,96.7L613.7,97.3L613.4,98.1L615,99.2L614.5,100.3L615.8,101.2L617,101.7L617.6,104Z"},{"code":"AZ","name":"Aserbaidschan","path":"M615,93.8L615.8,94L617.9,95.9L619.1,96.2L619.3,95.3L620.5,94L622.2,95.7L624,98L625.2,98.2L626.2,99.1L624.2,99.3L624.4,101.9L624.2,103.1L623.5,103.9L623.9,105.5L623.3,105.7L621.4,103.9L621.9,102.3L620.9,101.3L620,101.6L617.6,104L617,101.7L615.8,101.2L614.5,100.3L615,99.2L613.4,98.1L613.7,97.3L612.6,96.7L611.9,95.8L612.4,95.3L614.5,96.2L615.9,96.4L616.1,96.1L614.5,94.3L615,93.8ZM616.7Line truncated
@@ -12,5 +12,17 @@ public sealed class HoldMethodModel
public string? MaxChunkSize { get; set; }
public string? HeadStartSize { get; set; }
public bool MatchPath { get; set; }
public string? LinkSpacing { get; set; }
public string? BaitPaths { get; set; }
public string? MaxHoldDuration { get; set; }
public string? RepeatWindowDays { get; set; }
public string? RepeatHoldDuration { get; set; }
}
@@ -56,11 +56,37 @@
<SettingsField Label="Paket max." For="drip-max-chunk" Unit="Bytes" Hint="Zufällig zwischen min. und max." Errors="_errors" Key="@nameof(HoldMethodModel.MaxChunkSize)">
<InputText id="drip-max-chunk" @bind-Value="Model!.MaxChunkSize" inputmode="numeric" data-bandwidth-input />
</SettingsField>
<SettingsField Label="Schneller Start" For="drip-head-start" Unit="Bytes" Hint="0 bis 65536, sofort ohne Pause gesendet" Errors="_errors" Key="@nameof(HoldMethodModel.HeadStartSize)">
<InputText id="drip-head-start" @bind-Value="Model!.HeadStartSize" inputmode="numeric" />
</SettingsField>
<SettingsField Label="Link-Abstand" For="drip-link-spacing" Unit="Bytes" Hint="0 bis 4096, Text zwischen zwei Links, 0 = Labyrinth aus" Errors="_errors" Key="@nameof(HoldMethodModel.LinkSpacing)">
<InputText id="drip-link-spacing" @bind-Value="Model!.LinkSpacing" inputmode="numeric" />
</SettingsField>
<SettingsField Label="Maximale Haltedauer" For="hold" Hint="hh:mm:ss, höchstens 7 Tage" Errors="_errors" Key="@nameof(HoldMethodModel.MaxHoldDuration)">
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" />
</SettingsField>
<SettingsField Label="Wiederholer erkennen" For="repeat-window" Unit="Tage" Hint="0 bis 365, 0 = aus. IPs mit einem Timeout in diesem Zeitraum gelten als Wiederholer" Errors="_errors" Key="@nameof(HoldMethodModel.RepeatWindowDays)">
<InputText id="repeat-window" @bind-Value="Model!.RepeatWindowDays" inputmode="numeric" />
</SettingsField>
<SettingsField Label="Haltedauer für Wiederholer" For="repeat-hold" Hint="d.hh:mm:ss, höchstens 7 Tage. Strategie bekommt den Zusatz repeat („Wiederholer“)" Errors="_errors" Key="@nameof(HoldMethodModel.RepeatHoldDuration)">
<InputText id="repeat-hold" @bind-Value="Model!.RepeatHoldDuration" />
</SettingsField>
</div>
<div class="fields">
<SettingsField Label="Köder-Pfade in der robots.txt" For="drip-bait-paths" Wide="true" Hint="Kommagetrennt, höchstens 8, leer = keine. Nirgends verlinkt; Anfragen darauf heißen robots-bait und werden 24 Stunden gehalten." Errors="_errors" Key="@nameof(HoldMethodModel.BaitPaths)">
<InputText id="drip-bait-paths" @bind-Value="Model!.BaitPaths" />
</SettingsField>
</div>
<label class="switch-row">
<InputCheckbox class="switch" @bind-Value="Model!.MatchPath" />
<span>
<strong>Inhalt zum Pfad passend wählen</strong>
<span class="muted">Anfragen wie /.env, /config.json, /sitemap.xml oder /backup.sql bekommen passend aussehenden Inhalt statt einer Webseite.</span>
</span>
</label>
<div class="estimate">
<span class="estimate-value">Ø <strong id="drip-bandwidth">@Bandwidth</strong> Bytes/s</span>
<span class="muted">pro gefangener Verbindung, berechnet aus Pausen und Paketgrößen</span>
@@ -81,7 +107,7 @@
@code {
private static readonly (string Value, string Title, string Text)[] Choices =
[
(nameof(DripContent.Html), "HTML-Fülltext", "Eine endlose Webseite mit Überschriften, Absätzen und Links. Wirkt auf Crawler am echtesten."),
(nameof(DripContent.Html), "HTML-Fülltext", "Eine endlose Webseite mit Überschriften, Absätzen und vielen Links, die wieder in die Falle führen (Link-Labyrinth). Wirkt auf Crawler am echtesten."),
(nameof(DripContent.Text), "Zufallstext", "Schlichter Text ohne Markup, ausgeliefert als text/plain."),
(nameof(DripContent.Alternating), "Wechselnd", "Pro Fang zufällig eine der beiden. Gut, um zu vergleichen, was Bots länger hält.")
];
@@ -107,7 +133,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);
}
}
@@ -125,7 +151,13 @@
Model.MaxDelayMs,
Model.MinChunkSize,
Model.MaxChunkSize,
Model.MaxHoldDuration));
Model.HeadStartSize,
Model.MatchPath,
Model.LinkSpacing,
Model.BaitPaths,
Model.MaxHoldDuration,
Model.RepeatWindowDays,
Model.RepeatHoldDuration));
if (result.Settings is null)
{
@@ -153,7 +185,13 @@
MaxDelayMs = ((int)drip.MaxDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
MinChunkSize = drip.MinChunkSize.ToString(CultureInfo.InvariantCulture),
MaxChunkSize = drip.MaxChunkSize.ToString(CultureInfo.InvariantCulture),
MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
HeadStartSize = drip.HeadStartSize.ToString(CultureInfo.InvariantCulture),
MatchPath = drip.MatchPath,
LinkSpacing = drip.LinkSpacing.ToString(CultureInfo.InvariantCulture),
BaitPaths = drip.BaitPaths,
MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
RepeatWindowDays = Core.CurrentValue.RepeatWindowDays.ToString(CultureInfo.InvariantCulture),
RepeatHoldDuration = Core.CurrentValue.RepeatHoldDuration.ToString("c", CultureInfo.InvariantCulture)
};
}
}
@@ -5,7 +5,7 @@
@inject McpTokenStore Store
@inject NavigationManager Navigation
<SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol. Nur lesend und nur im LAN.">
<SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol Nur im LAN.">
@if (Revoked == "revoked")
{
<Notice>Token widerrufen.</Notice>
@@ -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",
@@ -0,0 +1,188 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Flypaper.Storage.Dashboard;
namespace Flypaper.Web.Components.Shared;
public sealed record StrategyInfo(string Raw, string BaseName, string DisplayName, string? Explanation, IReadOnlyList<string> Details, IReadOnlyList<string> Flags)
{
public string GroupKey => string.Join(' ', [BaseName, .. Flags]);
public IReadOnlyList<string> Badges => Flags.Select(StrategyNames.BadgeLabel).ToList();
public string Tooltip
{
get
{
var lines = new List<string> { DisplayName };
if (Explanation is not null)
{
lines.Add(Explanation);
}
lines.AddRange(Details);
lines.Add($"Technisch: {Raw}");
return string.Join("\n", lines);
}
}
}
public static partial class StrategyNames
{
private static readonly Dictionary<string, (string Name, string Explanation)> Known = new(StringComparer.Ordinal)
{
["maze-drip"] = ("Link-Labyrinth", "Eine Webseite voller Links, die immer zu neuen, erfundenen Seiten führen. Der Bot folgt ihnen und verirrt sich, während alles nur tröpfchenweise ankommt."),
["index-drip"] = ("Gefälschtes Ordner-Listing", "Eine Dateiliste im Stil von „Index of /…“ mit erfundenen Ordnern und Dateien. Wer weiterklickt, landet im Link-Labyrinth."),
["html-drip"] = ("Endlose Webseite", "Eine gewöhnlich aussehende Webseite, die nie aufhört und nur Stück für Stück geliefert wird. Der Bot wartet auf das Ende, das nie kommt."),
["text-drip"] = ("Endloser Text", "Unendlicher Fließtext ohne Formatierung, der nur tröpfchenweise ankommt. Der Bot wartet auf das Ende, das nie kommt."),
["env-drip"] = ("Gefälschte Zugangsdaten (.env)", "Eine erfundene .env-Datei mit Passwörtern und Schlüsseln, die nie endet. Bots, die nach geleakten Zugangsdaten suchen, lesen sie bis zum Ende."),
["git-drip"] = ("Gefälschtes Git-Projekt", "Eine erfundene Git-Konfiguration, die wie die echte beginnt und nie endet. Bots, die Quellcode abgreifen wollen, bleiben daran hängen."),
["svn-drip"] = ("Gefälschtes Subversion-Projekt", "Erfundene Dateien aus einem .svn-Ordner, die wie die echten beginnen und nie enden. Bots, die Quellcode abgreifen wollen, bleiben daran hängen."),
["hg-drip"] = ("Gefälschtes Mercurial-Projekt", "Erfundene Dateien aus einem .hg-Ordner, die wie die echten beginnen und nie enden. Bots, die Quellcode abgreifen wollen, bleiben daran hängen."),
["json-drip"] = ("Gefälschte JSON-Datei", "Eine erfundene JSON-Datei, die nie endet. Bots, die Konfigurationen und Daten einsammeln, warten auf das Dateiende."),
["xml-drip"] = ("Gefälschte XML-Datei", "Eine erfundene XML-Datei, die nie endet. Bots, die Konfigurationen und Daten einsammeln, warten auf das Dateiende."),
["yaml-drip"] = ("Gefälschte YAML-Datei", "Eine erfundene YAML-Konfiguration, die nie endet. Bots, die Konfigurationen einsammeln, warten auf das Dateiende."),
["sql-drip"] = ("Gefälschter Datenbank-Export (SQL)", "Ein erfundener SQL-Dump mit endlos vielen Einträgen. Bots, die nach Datenbank-Backups suchen, laden ihn herunter, solange es geht."),
["hikvision-drip"] = ("Gefälschte Überwachungskamera (Hikvision)", "Die Antwort einer erfundenen Hikvision-Kamera, die nie endet. Bots, die nach angreifbaren Kameras suchen, warten auf die komplette Antwort."),
["wordpress-drip"] = ("Gefälschte WordPress-Anmeldung", "Eine erfundene WordPress-Anmeldeseite, die nie fertig geladen wird. Bots, die Passwörter durchprobieren, kommen nie zum Formular."),
["robots-static"] = ("robots.txt (Hinweis an brave Crawler)", "Die robots.txt wird sofort und vollständig geliefert. Sie verbietet alles, brave Crawler bleiben draußen. Es wird bewusst niemand festgehalten."),
["robots-bait"] = ("Köder aus der robots.txt", "Ein Pfad, der in der robots.txt als verboten steht, aber ins Link-Labyrinth führt. Wer dort landet, hat das Verbot gelesen und ignoriert. Er wird mindestens 24 Stunden festgehalten.")
};
private static readonly Dictionary<string, string> Aliases = new(StringComparer.Ordinal)
{
["drip"] = "html-drip"
};
private static readonly string[] VariantFlags = ["head", "link", "repeat"];
private static readonly HashSet<string> LinkedByDesign = new(StringComparer.Ordinal) { "maze-drip", "index-drip", "robots-bait" };
public const int MinCatches = 5;
public static string BadgeLabel(string flag) => flag switch
{
"head" => "Schnellstart",
"link" => "Links",
"repeat" => "Wiederholer",
_ => flag
};
public static StrategyInfo Describe(string? strategy)
{
var raw = strategy?.Trim() ?? "";
var tokens = raw.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length == 0)
{
return new StrategyInfo(raw, raw, raw, null, [], []);
}
var baseName = Aliases.GetValueOrDefault(tokens[0], tokens[0]);
var flags = VariantFlags
.Where(flag => tokens.Skip(1).Contains(flag) && !(flag == "link" && LinkedByDesign.Contains(baseName)))
.ToList();
var details = new List<string>();
if (baseName != tokens[0])
{
details.Add($"früherer Name von {Known[baseName].Name}");
}
for (var i = 1; i < tokens.Length; i++)
{
var token = tokens[i];
if (DelayPattern().Match(token) is { Success: true } delay
&& i + 1 < tokens.Length && SizePattern().Match(tokens[i + 1]) is { Success: true } chunk)
{
details.Add($"tröpfelt {Range(chunk.Groups[1].Value, chunk.Groups[2].Value)} Byte alle {Range(delay.Groups[1].Value, delay.Groups[2].Value)} ms");
i++;
}
else if (token is "head" or "link" && i + 1 < tokens.Length && SingleSizePattern().Match(tokens[i + 1]) is { Success: true } size)
{
var bytes = Number(size.Groups[1].Value);
details.Add(token == "head"
? $"schneller Start: die ersten {bytes} Byte sofort"
: $"alle {bytes} Byte ein Link");
i++;
}
else if (token is "head" or "link")
{
details.Add(token == "head" ? "schneller Start: erste Bytes sofort" : "enthält Links");
}
else if (token == "repeat")
{
details.Add("Wiederholer: darf länger festgehalten werden");
}
else
{
details.Add(token);
}
}
return Known.TryGetValue(baseName, out var known)
? new StrategyInfo(raw, baseName, known.Name, known.Explanation, details, flags)
: new StrategyInfo(raw, baseName, baseName, null, details, flags);
}
public static string Display(string? strategy) => Describe(strategy).DisplayName;
public static string GroupKey(string? strategy) => Describe(strategy).GroupKey;
public static StrategyMatch? Group(string? strategy)
{
var info = Describe(strategy);
if (info.BaseName.Length == 0)
{
return null;
}
var bases = Aliases.Where(pair => pair.Value == info.BaseName).Select(pair => pair.Key).Prepend(info.BaseName).ToList();
var variableFlags = VariantFlags.Where(flag => !(flag == "link" && LinkedByDesign.Contains(info.BaseName)));
return new StrategyMatch(bases, info.Flags, variableFlags.Except(info.Flags).ToList());
}
public static IReadOnlyList<TopEntry> Rank(IEnumerable<StrategySample> samples, int take)
{
var groups = samples
.GroupBy(sample => GroupKey(sample.Strategy))
.Select(group =>
{
var durations = group.Select(sample => sample.DurationMs).Order().ToList();
var middle = durations.Count / 2;
var median = durations.Count % 2 == 1 ? durations[middle] : (durations[middle - 1] + durations[middle]) / 2d;
return new TopEntry(group.Key, durations.Count, TimeSpan.FromMilliseconds(durations.Sum()), MedianHold: TimeSpan.FromMilliseconds(median));
});
return groups
.OrderBy(entry => entry.Count < MinCatches)
.ThenByDescending(entry => entry.MedianHold)
.ThenByDescending(entry => entry.Count)
.Take(take)
.ToList();
}
public static IReadOnlyList<string> Matching(string? search)
{
var term = search?.Trim();
if (string.IsNullOrEmpty(term))
{
return [];
}
var keys = Known.Where(pair => pair.Value.Name.Contains(term, StringComparison.CurrentCultureIgnoreCase)).Select(pair => pair.Key).ToList();
return [.. keys, .. Aliases.Where(pair => keys.Contains(pair.Value)).Select(pair => pair.Key)];
}
private static string Range(string min, string max) => min == max ? Number(min) : $"{Number(min)}–{Number(max)}";
private static string Number(string digits) => long.Parse(digits, CultureInfo.InvariantCulture).ToString("N0", Formatting.German);
[GeneratedRegex(@"^(\d+)-(\d+)ms$")]
private static partial Regex DelayPattern();
[GeneratedRegex(@"^(\d+)-(\d+)B$")]
private static partial Regex SizePattern();
[GeneratedRegex(@"^(\d+)B$")]
private static partial Regex SingleSizePattern();
}
+7 -3
View File
@@ -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, strategies or user_agents.")]
[AllowedValues("ips", "countries", "providers", "targets", "strategies", "user_agents")]
string dimension,
[Description(PeriodDescription)] string period = "24h",
[Description("Number of entries, 1 to 500.")] int limit = 10,
CancellationToken ct = default)
@@ -72,8 +75,9 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove
"countries" => TopDimension.Countries,
"providers" => TopDimension.Providers,
"targets" => TopDimension.Targets,
"strategies" => TopDimension.Strategies,
"user_agents" => TopDimension.UserAgents,
_ => throw new McpException("dimension must be one of ips, countries, providers, targets, user_agents.")
_ => throw new McpException("dimension must be one of ips, countries, providers, targets, strategies, user_agents.")
};
var items = await queries.TopAsync(parsed, Since(period), limit, ct);
+45
View File
@@ -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()))})"
: "";
}
+45 -2
View File
@@ -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;
@@ -14,7 +18,12 @@ public static class McpExtensions
"Flypaper is an HTTP tarpit. Scanning bots that probe a server (e.g. for /.env or /wp-login.php) are " +
"answered with an endless page a few bytes at a time and held as long as possible. Every such catch is " +
"stored with its time, client IP, country, network provider (ASN), requested URL, user agent, duration " +
"and bytes sent. These tools only read that data; times are ISO 8601 UTC, durations in seconds.";
"and bytes sent. All 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)
{
@@ -34,11 +43,45 @@ public static class McpExtensions
options.ServerInstructions = Instructions;
})
.WithHttpTransport(options => options.Stateless = true)
.WithTools<FlypaperTools>();
.WithTools<FlypaperTools>(ToolJsonOptions)
.WithRequestFilters(filters =>
{
filters.AddCallToolFilter(CheckCall);
});
return services;
}
private static McpRequestHandler<CallToolRequestParams, CallToolResult> CheckCall(McpRequestHandler<CallToolRequestParams, CallToolResult> next) =>
async (context, ct) =>
{
var tool = context.Params?.Name;
var logger = context.Services?.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(FlypaperTools));
if (context.MatchedPrimitive is McpServerTool 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);
}
};
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);
@@ -21,7 +21,7 @@ public sealed class McpTokenAuthenticationHandler(
return AuthenticateResult.NoResult();
}
if (!await tokens.ValidateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted))
if (!await tokens.AuthenticateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted))
{
return AuthenticateResult.Fail("Invalid MCP token.");
}
+1 -1
View File
@@ -19,7 +19,7 @@ public sealed class McpTokenService(McpTokenStore store, IOptions<McpOptions> op
return token;
}
public async Task<bool> ValidateAsync(string? token, CancellationToken ct = default)
public async Task<bool> AuthenticateAsync(string? token, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(token))
{
+2
View File
@@ -22,6 +22,8 @@
"MaxConnections": 1000,
"MaxConnectionsPerIp": 10,
"MaxHoldDuration": "01:00:00",
"RepeatWindowDays": 7,
"RepeatHoldDuration": "1.00:00:00",
"Http": {
"TrustedProxies": []
}
+352 -44
View File
@@ -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,260 @@ 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;
}
.badge {
display: inline-block;
margin-left: 6px;
padding: 0 6px;
border-radius: 999px;
background: color-mix(in srgb, var(--text) 8%, transparent);
color: var(--muted);
font-size: 11px;
line-height: 17px;
white-space: nowrap;
vertical-align: 1px;
}
.top-table tr.sparse td {
opacity: 0.55;
}
.top-note {
margin: 8px 0 0;
color: var(--muted);
font-size: 12px;
}
.top-table.by-median .count {
width: 52px;
}
.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 {
@@ -271,6 +491,14 @@ code {
width: 116px;
}
.recent-table .c-strategy {
width: 190px;
}
.recent-table .strategy-info div {
margin-top: 2px;
}
.recent-table .extra {
display: none;
margin-top: 4px;
@@ -281,6 +509,7 @@ code {
@media (max-width: 1199px) {
.recent-table .c-provider,
.recent-table .c-strategy,
.recent-table .c-agent {
display: none;
}
@@ -414,9 +643,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 +871,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 +918,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 +930,9 @@ tbody th {
.map-wrap {
position: relative;
display: flex;
flex: 1;
align-items: center;
}
.map-empty {
@@ -704,17 +950,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 +989,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 +1012,7 @@ button.danger {
}
.metric,
.metric-hero {
.metric:nth-child(n + 4) {
grid-column: span 1;
}
@@ -774,8 +1020,40 @@ 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;
}
.top-table.by-median .sum {
display: none;
}
.top-table.by-median .count {
width: 48px;
}
.top-table.by-median .clip {
white-space: normal;
}
.nav .brand {
@@ -1341,3 +1619,33 @@ button.danger-text {
gap: 2px;
}
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.chips a.chip {
padding: 3px 10px;
border-color: var(--border);
background: transparent;
}
.chips a.chip:hover {
border-color: var(--accent);
}
.chips a.chip.active {
border-color: color-mix(in srgb, var(--accent) 45%, var(--border));
background: color-mix(in srgb, var(--accent) 10%, transparent);
}
.inline-check {
display: inline-flex;
align-items: center;
gap: 6px;
}
+82
View File
@@ -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;
});
}
})();
@@ -0,0 +1,137 @@
using System.Net;
using System.Text;
using Flypaper.Core.Models;
using Flypaper.Core.Runtime;
using Flypaper.Core.Strategies;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Core;
public sealed class FileContentTests
{
[Theory]
[InlineData("/.env", "env-drip")]
[InlineData("/app/.ENV.production", "env-drip")]
[InlineData("/config.json", "json-drip")]
[InlineData("/sitemap.xml", "xml-drip")]
[InlineData("/docker-compose.yml", "yaml-drip")]
[InlineData("/backup/db.sql", "sql-drip")]
[InlineData("/.git/config", "git-drip")]
[InlineData("/.git/HEAD", "git-drip")]
[InlineData("/app/.git/logs/HEAD", "git-drip")]
[InlineData("/.git", "git-drip")]
[InlineData("/.gitconfig", "git-drip")]
[InlineData("/.git-credentials", "git-drip")]
[InlineData("/home/.GITCONFIG", "git-drip")]
[InlineData("/.svn/format", "svn-drip")]
[InlineData("/.svn/wc.db", "svn-drip")]
[InlineData("/.svn/entries", "svn-drip")]
[InlineData("/site/.svn", "svn-drip")]
[InlineData("/.hg/requires", "hg-drip")]
[InlineData("/.hg/store/requires", "hg-drip")]
[InlineData("/.hg", "hg-drip")]
[InlineData("/SDK/webLanguage", "hikvision-drip")]
[InlineData("/ISAPI/System/deviceInfo", "hikvision-drip")]
[InlineData("/wp-login.php", "wordpress-drip")]
[InlineData("/blog/WP-Login.php", "wordpress-drip")]
public void Matches_known_paths(string path, string expected) =>
FileContent.Match(path).ShouldNotBeNull().Name.ShouldBe(expected);
[Theory]
[InlineData("/")]
[InlineData("/index.php")]
[InlineData("/sdkfoo")]
[InlineData("/.svnfoo")]
[InlineData("/.hgrc-not")]
[InlineData("/legit.git/x")]
[InlineData("/environment")]
[InlineData("")]
[InlineData(null)]
public void Ignores_other_paths(string? path) => FileContent.Match(path).ShouldBeNull();
[Theory]
[InlineData("/.env", "APP_NAME=")]
[InlineData("/config.json", "{")]
[InlineData("/sitemap.xml", "<?xml")]
[InlineData("/docker-compose.yml", "version:")]
[InlineData("/dump.sql", "-- MySQL dump")]
[InlineData("/.git/config", "[core]")]
[InlineData("/.git-credentials", "[core]")]
[InlineData("/.svn/entries", "12\n")]
[InlineData("/.svn/wc.db", "12\n")]
[InlineData("/.hg/requires", "dotencode\n")]
[InlineData("/.hg/store/requires", "dotencode\n")]
[InlineData("/SDK/webLanguage", "<?xml")]
[InlineData("/wp-login.php", "<!DOCTYPE html>")]
public void Generates_an_endless_file_that_starts_like_the_real_thing(string path, string start)
{
var profile = FileContent.Match(path).ShouldNotBeNull();
var text = string.Concat(profile.Generate(new SeededRandomSource(5)).Take(200));
text.ShouldStartWith(start);
text.Length.ShouldBeGreaterThan(1000);
}
[Fact]
public void Selector_prefers_the_path_profile_and_can_be_switched_off()
{
var session = new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow);
var context = new TrapContext(session, "GET /.env", Path: "/.env");
Selector(matchPath: true).Select(context).ShouldNotBeNull().Name.ShouldBe("env-drip");
Selector(matchPath: true).Select(context with { Path = "/" }).ShouldNotBeNull().Name.ShouldBe("maze-drip");
Selector(matchPath: false).Select(context).ShouldNotBeNull().Name.ShouldBe("maze-drip");
}
[Fact]
public async Task Robots_txt_is_served_completely_and_at_once_even_without_path_matching()
{
var session = new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow);
var context = new TrapContext(session, "GET /robots.txt", Path: "/Robots.txt");
var strategy = Selector(matchPath: false).Select(context).ShouldNotBeNull();
var channel = new FakeTrapChannel();
await strategy.RunAsync(channel, CancellationToken.None);
strategy.Name.ShouldBe("robots-static");
channel.Writes.Count.ShouldBe(1);
Encoding.UTF8.GetString(channel.Writes.Single())
.ShouldBe("User-agent: *\nDisallow: /\nDisallow: /backup-2024/\nDisallow: /admin-old/\nDisallow: /internal/db-export/\nDisallow: /old-site/\n");
}
[Fact]
public async Task File_strategy_sends_the_head_start_and_names_itself()
{
var options = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromSeconds(30), MaxDelay = TimeSpan.FromSeconds(30), HeadStartSize = 300 });
var strategy = new FileDripStrategy(FileContent.Match("/.env")!, options, new SeededRandomSource(1), TimeProvider.System);
var channel = new FakeTrapChannel();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
Encoding.UTF8.GetString(channel.Writes.First()).ShouldStartWith("APP_NAME=");
channel.Writes.First().Length.ShouldBeGreaterThanOrEqualTo(300);
strategy.Describe().ShouldBe("env-drip 30000-30000ms 1-64B head 300B");
strategy.MediaType.ShouldStartWith("text/plain");
}
private static ConfiguredStrategySelector Selector(bool matchPath)
{
var options = TestOptions.Monitor(new DripOptions { MatchPath = matchPath });
var random = new SeededRandomSource(11);
return new ConfiguredStrategySelector(
[
new HtmlDripStrategy(options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Page, options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Listing, options, random, TimeProvider.System),
new TextDripStrategy(options, random, TimeProvider.System),
new RobotsStaticStrategy(options),
new MazeDripStrategy(MazeKind.Bait, options, random, TimeProvider.System),
.. FileContent.Profiles.Select(profile => new FileDripStrategy(profile, options, random, TimeProvider.System))
],
options,
random);
}
}
@@ -6,7 +6,7 @@ namespace Flypaper.Tests.Core;
public sealed class HoldMethodParserTests
{
private static readonly HoldMethodInput Valid = new("Alternating", "50", "1000", "1", "64", "01:00:00");
private static readonly HoldMethodInput Valid = new("Alternating", "50", "1000", "1", "64", "2048", true, "80", "/Backup-2024, /admin-old/x", "01:00:00", "7", "1.00:00:00");
[Fact]
public void Parses_valid_input()
@@ -18,6 +18,10 @@ public sealed class HoldMethodParserTests
settings.MaxDelay.ShouldBe(TimeSpan.FromSeconds(1));
settings.MinChunkSize.ShouldBe(1);
settings.MaxChunkSize.ShouldBe(64);
settings.HeadStartSize.ShouldBe(2048);
settings.MatchPath.ShouldBeTrue();
settings.LinkSpacing.ShouldBe(80);
settings.BaitPaths.ShouldBe("/backup-2024/,/admin-old/x/");
settings.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1));
settings.ToConfiguration().Keys.ShouldBe(SettingKeys.HoldMethod, ignoreOrder: true);
}
@@ -56,6 +60,47 @@ public sealed class HoldMethodParserTests
errors.Keys.ShouldBe([nameof(HoldMethodInput.MaxDelayMs), nameof(HoldMethodInput.MaxChunkSize)], ignoreOrder: true);
}
[Theory]
[InlineData("0")]
[InlineData("65536")]
public void Accepts_head_start_bounds(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { HeadStartSize = value }).Settings.ShouldNotBeNull();
[Theory]
[InlineData("-1")]
[InlineData("65537")]
[InlineData("")]
public void Rejects_head_start_out_of_range(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { HeadStartSize = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.HeadStartSize)]);
[Theory]
[InlineData("0")]
[InlineData("4096")]
public void Accepts_link_spacing_bounds(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { LinkSpacing = value }).Settings.ShouldNotBeNull();
[Theory]
[InlineData("-1")]
[InlineData("4097")]
[InlineData("")]
public void Rejects_link_spacing_out_of_range(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { LinkSpacing = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.LinkSpacing)]);
[Theory]
[InlineData("")]
[InlineData("/a/,/b/")]
public void Accepts_bait_paths(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { BaitPaths = value }).Settings.ShouldNotBeNull();
[Theory]
[InlineData("backup")]
[InlineData("/robots.txt")]
[InlineData("/wiki/old/")]
[InlineData("/a b<>/")]
[InlineData("/a/,/b/,/c/,/d/,/e/,/f/,/g/,/h/,/i/")]
public void Rejects_invalid_bait_paths(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { BaitPaths = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.BaitPaths)]);
[Theory]
[InlineData("10")]
[InlineData("00:00:00")]
@@ -63,6 +108,37 @@ public sealed class HoldMethodParserTests
public void Rejects_invalid_hold_durations(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { MaxHoldDuration = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.MaxHoldDuration)]);
[Theory]
[InlineData("0")]
[InlineData("365")]
public void Accepts_repeat_window(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { RepeatWindowDays = value }).Settings.ShouldNotBeNull().RepeatWindowDays.ShouldBe(int.Parse(value));
[Theory]
[InlineData("")]
[InlineData("-1")]
[InlineData("366")]
[InlineData("abc")]
public void Rejects_invalid_repeat_window(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { RepeatWindowDays = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.RepeatWindowDays)]);
[Theory]
[InlineData("10")]
[InlineData("00:00:00")]
[InlineData("24:00:00")]
[InlineData("8.00:00:00")]
public void Rejects_invalid_repeat_hold_durations(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { RepeatHoldDuration = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.RepeatHoldDuration)]);
[Fact]
public void Parses_repeat_settings()
{
var settings = RuntimeSettingsParser.ParseHoldMethod(Valid).Settings.ShouldNotBeNull();
settings.RepeatWindowDays.ShouldBe(7);
settings.RepeatHoldDuration.ShouldBe(TimeSpan.FromHours(24));
}
[Fact]
public void Computes_average_bandwidth()
{
@@ -22,6 +22,46 @@ public sealed class HtmlDripStrategyTests
Encoding.UTF8.GetString(channel.Writes.SelectMany(write => write).ToArray()).ShouldStartWith("<!doctype html>");
}
[Fact]
public async Task Sends_head_start_without_delay_before_dripping()
{
var options = new DripOptions { MinDelay = TimeSpan.FromSeconds(30), MaxDelay = TimeSpan.FromSeconds(30), HeadStartSize = 1024 };
var strategy = new HtmlDripStrategy(TestOptions.Monitor(options), new SeededRandomSource(21), TimeProvider.System);
var channel = new FakeTrapChannel();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
channel.Writes.Count.ShouldBe(2);
var head = channel.Writes.First();
head.Length.ShouldBeGreaterThanOrEqualTo(1024);
Encoding.UTF8.GetString(head).ShouldStartWith("<!doctype html>");
}
[Fact]
public async Task Skips_head_start_when_disabled()
{
var options = new DripOptions { MinDelay = TimeSpan.FromSeconds(30), MaxDelay = TimeSpan.FromSeconds(30), HeadStartSize = 0 };
var strategy = new HtmlDripStrategy(TestOptions.Monitor(options), new SeededRandomSource(21), TimeProvider.System);
var channel = new FakeTrapChannel();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
channel.Writes.Count.ShouldBe(1);
channel.Writes.First().Length.ShouldBeLessThanOrEqualTo(64);
}
[Theory]
[InlineData(1024, "html-drip 5-10ms 1-64B head 1024B")]
[InlineData(0, "html-drip 5-10ms 1-64B")]
public void Describe_marks_the_head_start_variant(int headStart, string expected)
{
var options = new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(10), HeadStartSize = headStart };
new HtmlDripStrategy(TestOptions.Monitor(options), new SeededRandomSource(1), TimeProvider.System).Describe().ShouldBe(expected);
}
[Theory]
[InlineData(TrapProtocol.Http, true)]
[InlineData(TrapProtocol.Ssh, false)]
@@ -29,7 +69,7 @@ public sealed class HtmlDripStrategyTests
CreateStrategy().Supports(protocol).ShouldBe(expected);
private static HtmlDripStrategy CreateStrategy() => new(
TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(5) }),
TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(5), HeadStartSize = 0 }),
new SeededRandomSource(21),
TimeProvider.System);
}
@@ -0,0 +1,217 @@
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Flypaper.Core.Models;
using Flypaper.Core.Runtime;
using Flypaper.Core.Strategies;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Core;
public sealed partial class MazeContentTests
{
[GeneratedRegex("href=\"([^\"]*)\"")]
private static partial Regex Href();
private static List<string> Links(string html) => Href().Matches(html).Select(match => match.Groups[1].Value).ToList();
[Fact]
public void Head_start_already_carries_many_links()
{
using var fragments = MazeContent.Page(new SeededRandomSource(1), "/wiki/lorem", "example.com", 160).GetEnumerator();
var head = Encoding.UTF8.GetString(DripSchedule.TakeHead(fragments, 1024).Span);
head.Length.ShouldBeGreaterThanOrEqualTo(1024);
Links(head).Count.ShouldBeGreaterThanOrEqualTo(10);
}
[Fact]
public void Keeps_delivering_links_at_the_configured_spacing()
{
var body = string.Concat(MazeContent.Page(new SeededRandomSource(2), "/wiki/lorem", "example.com", 160).Skip(4).Take(40));
var tight = string.Concat(MazeContent.Page(new SeededRandomSource(2), "/wiki/lorem", "example.com", 40).Skip(4).Take(40));
var bytesPerLink = Encoding.UTF8.GetByteCount(body) / (double)Links(body).Count;
var tightBytesPerLink = Encoding.UTF8.GetByteCount(tight) / (double)Links(tight).Count;
bytesPerLink.ShouldBeInRange(100, 450);
tightBytesPerLink.ShouldBeLessThan(bytesPerLink);
}
[Theory]
[InlineData("/")]
[InlineData("/index.php")]
[InlineData("//images/images/cache.php")]
public void Pages_outside_the_roots_only_link_into_the_disallowed_roots(string path)
{
var page = string.Concat(MazeContent.Page(new SeededRandomSource(3), path, "example.com", 80).Take(300));
var baseUri = new Uri("http://example.com" + path);
foreach (var href in Links(page))
{
var target = new Uri(baseUri, href);
target.Host.ShouldBe("example.com");
MazeContent.Roots.ShouldContain(target.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries).First());
}
}
[Fact]
public void Listings_below_a_root_never_leave_the_root()
{
var listing = string.Concat(MazeContent.Listing(new SeededRandomSource(3), "/files/lorem/", "example.com").Take(200));
var baseUri = new Uri("http://example.com/files/lorem/");
foreach (var href in Links(listing).Where(href => href != "../"))
{
new Uri(baseUri, href).AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries).First().ShouldBeOneOf(MazeContent.Roots);
}
}
[Fact]
public void Relative_links_below_a_root_never_leave_the_root()
{
var page = string.Concat(MazeContent.Page(new SeededRandomSource(4), "/blog/2025/03/lorem", "example.com", 80).Take(300));
var baseUri = new Uri("http://example.com/blog/2025/03/lorem");
foreach (var href in Links(page).Where(href => !href.StartsWith('/') && !href.StartsWith("http", StringComparison.Ordinal)))
{
new Uri(baseUri, href).AbsolutePath.ShouldStartWith("/blog/");
}
}
[Fact]
public void Mixes_relative_and_absolute_links_and_limits_depth()
{
var links = Links(string.Concat(MazeContent.Page(new SeededRandomSource(5), "/docs/lorem", "example.com", 80).Take(300)));
links.ShouldContain(href => href.StartsWith("http://example.com/docs/", StringComparison.Ordinal));
links.ShouldContain(href => href.StartsWith("/docs/", StringComparison.Ordinal));
links.ShouldContain(href => !href.StartsWith('/') && !href.StartsWith("http", StringComparison.Ordinal));
links.ShouldContain(href => href.StartsWith("/blog/20", StringComparison.Ordinal));
var deepPath = "/docs/" + string.Join('/', Enumerable.Repeat("x", 8)) + "/";
var deep = Links(string.Concat(MazeContent.Page(new SeededRandomSource(6), deepPath, null, 80).Take(300)));
deep.ShouldContain("../");
deep.ShouldNotContain(href => href.StartsWith("http", StringComparison.Ordinal));
}
[Fact]
public void Ignores_a_hostile_host_header()
{
var page = string.Concat(MazeContent.Page(new SeededRandomSource(7), "/wiki/a", "evil\"><script>", 80).Take(100));
page.ShouldNotContain("<script>");
Links(page).ShouldNotContain(href => href.StartsWith("http", StringComparison.Ordinal));
}
[Fact]
public void Listing_looks_like_a_directory_index_and_escapes_the_path()
{
var text = string.Concat(MazeContent.Listing(new SeededRandomSource(8), "/backup/<b>/", "example.com").Take(60));
text.ShouldContain("<title>Index of /backup/&lt;b&gt;/</title>");
text.ShouldContain("<a href=\"../\">Parent Directory</a>");
Links(text).Count.ShouldBeGreaterThan(40);
}
[Theory]
[InlineData("/wiki/", "index-drip")]
[InlineData("/", "maze-drip")]
[InlineData("/wiki/lorem", "maze-drip")]
public void Selector_uses_listing_only_for_directories(string path, string expected)
{
var context = new TrapContext(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow), Path: path);
Selector(160).Select(context).ShouldNotBeNull().Name.ShouldBe(expected);
Selector(0).Select(context).ShouldNotBeNull().Name.ShouldBe("html-drip");
}
[Fact]
public async Task Strategy_sends_links_in_the_head_start_and_names_its_spacing()
{
var options = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromSeconds(30), MaxDelay = TimeSpan.FromSeconds(30) });
var strategy = new MazeDripStrategy(MazeKind.Page, options, new SeededRandomSource(9), TimeProvider.System);
var channel = new FakeTrapChannel { Path = "/wiki/lorem", Host = "example.com" };
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
Links(Encoding.UTF8.GetString(channel.Writes.First())).Count.ShouldBeGreaterThanOrEqualTo(10);
strategy.Describe().ShouldBe("maze-drip 30000-30000ms 1-64B head 1024B link 160B");
strategy.MediaType.ShouldStartWith("text/html");
}
[Theory]
[InlineData("/backup-2024/", true)]
[InlineData("/Backup-2024/old/dump.zip", true)]
[InlineData("/backup-2024", true)]
[InlineData("/internal/db-export/x", true)]
[InlineData("/internal/", false)]
[InlineData("/backup-20245/", false)]
[InlineData("/backup/", false)]
public void Bait_paths_and_everything_below_get_robots_bait(string path, bool bait)
{
var context = new TrapContext(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow), Path: path);
Selector(160).Select(context).ShouldNotBeNull().Name.ShouldBe(bait ? "robots-bait" : path.EndsWith('/') ? "index-drip" : "maze-drip");
Selector(0).Select(context).ShouldNotBeNull().Name.ShouldBe(bait ? "robots-bait" : "html-drip");
}
[Fact]
public void Bait_paths_are_never_linked_from_the_maze()
{
var text = string.Concat(MazeContent.Page(new SeededRandomSource(12), "/", "example.com", 40).Take(400))
+ string.Concat(MazeContent.Listing(new SeededRandomSource(12), "/files/", "example.com").Take(400));
foreach (var bait in BaitPaths.Parse(BaitPaths.Default))
{
text.ShouldNotContain(bait.TrimEnd('/'));
}
}
[Fact]
public void Bait_strategy_extends_the_hold_and_keeps_the_maze_content()
{
var options = TestOptions.Monitor(new DripOptions());
var bait = new MazeDripStrategy(MazeKind.Bait, options, new SeededRandomSource(1), TimeProvider.System);
bait.MinimumHold.ShouldBe(TimeSpan.FromHours(24));
bait.Describe().ShouldStartWith("robots-bait ");
new MazeDripStrategy(MazeKind.Page, options, new SeededRandomSource(1), TimeProvider.System).MinimumHold.ShouldBe(TimeSpan.Zero);
}
[Fact]
public void Empty_bait_paths_switch_the_bait_off()
{
var context = new TrapContext(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow), Path: "/backup-2024/");
var options = TestOptions.Monitor(new DripOptions { BaitPaths = "" });
var random = new SeededRandomSource(1);
var selector = new ConfiguredStrategySelector(
[
new MazeDripStrategy(MazeKind.Page, options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Listing, options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Bait, options, random, TimeProvider.System)
],
options,
random);
selector.Select(context).ShouldNotBeNull().Name.ShouldBe("index-drip");
}
private static ConfiguredStrategySelector Selector(int spacing)
{
var options = TestOptions.Monitor(new DripOptions { LinkSpacing = spacing });
var random = new SeededRandomSource(11);
return new ConfiguredStrategySelector(
[
new HtmlDripStrategy(options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Page, options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Listing, options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Bait, options, random, TimeProvider.System)
],
options,
random);
}
}
@@ -44,7 +44,7 @@ public sealed class StrategySelectionTests
var options = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(100), MaxDelay = TimeSpan.FromMilliseconds(250), MinChunkSize = 2, MaxChunkSize = 8 });
var text = new TextDripStrategy(options, new SeededRandomSource(1), TimeProvider.System);
text.Describe().ShouldBe("text-drip 100-250ms 2-8B");
text.Describe().ShouldBe("text-drip 100-250ms 2-8B head 1024B");
text.MediaType.ShouldStartWith("text/plain");
new HtmlDripStrategy(options, new SeededRandomSource(1), TimeProvider.System).MediaType.ShouldStartWith("text/html");
}
+67 -3
View File
@@ -59,7 +59,7 @@ public sealed class TrapRunnerTests
var outcome = await CreateRunner(TimeSpan.FromMinutes(1)).RunAsync(Context(), Open, cts.Token);
outcome.ShouldBe(TrapOutcome.ClientAborted);
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "html-drip 5-20ms 1-64B"));
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "html-drip 5-20ms 1-64B head 1024B"));
}
[Theory]
@@ -99,6 +99,58 @@ public sealed class TrapRunnerTests
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.RemoteIp.Equals(IPAddress.Parse("192.168.1.20"))));
}
[Fact]
public async Task Holds_ips_with_an_earlier_timeout_longer_and_marks_the_strategy()
{
AllowAcquire();
var lookup = Substitute.For<IRepeatOffenderLookup>();
lookup.HasTimedOutSinceAsync(Arg.Any<IPAddress>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>()).Returns(true);
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(500));
var outcome = await CreateRunner(TimeSpan.FromMilliseconds(100), repeatOffenders: lookup, repeatWindowDays: 7, repeatHoldDuration: TimeSpan.FromMinutes(1))
.RunAsync(Context(), Open, cts.Token);
outcome.ShouldBe(TrapOutcome.ClientAborted);
await lookup.Received(1).HasTimedOutSinceAsync(
IPAddress.Parse("203.0.113.9"),
Arg.Is<DateTime>(since => Math.Abs((DateTime.UtcNow.AddDays(-7) - since).TotalSeconds) < 30),
Arg.Any<CancellationToken>());
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Strategy.EndsWith(" repeat")));
}
[Fact]
public async Task Keeps_the_normal_limit_for_new_ips()
{
AllowAcquire();
var lookup = Substitute.For<IRepeatOffenderLookup>();
lookup.HasTimedOutSinceAsync(Arg.Any<IPAddress>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>()).Returns(false);
var outcome = await CreateRunner(TimeSpan.FromMilliseconds(100), repeatOffenders: lookup, repeatWindowDays: 7)
.RunAsync(Context(), Open, CancellationToken.None);
outcome.ShouldBe(TrapOutcome.Timeout);
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => !e.Strategy.EndsWith(" repeat")));
}
[Theory]
[InlineData(0, "00:00:00.100")]
[InlineData(7, "00:00:00.050")]
public async Task Does_not_ask_when_the_feature_is_off_or_would_not_extend_the_hold(int windowDays, string repeatHold)
{
AllowAcquire();
var lookup = Substitute.For<IRepeatOffenderLookup>();
await CreateRunner(TimeSpan.FromMilliseconds(100), repeatOffenders: lookup, repeatWindowDays: windowDays, repeatHoldDuration: TimeSpan.Parse(repeatHold))
.RunAsync(Context(), Open, CancellationToken.None);
await lookup.DidNotReceiveWithAnyArgs().HasTimedOutSinceAsync(default!, default, default);
}
private sealed class NullRepeatLookup : IRepeatOffenderLookup
{
public ValueTask<bool> HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct) => ValueTask.FromResult(false);
}
private IDisposable AllowAcquire()
{
var lease = Substitute.For<IDisposable>();
@@ -113,7 +165,12 @@ public sealed class TrapRunnerTests
private ValueTask<ITrapChannel> Open(ITarpitStrategy strategy, CancellationToken ct) => ValueTask.FromResult<ITrapChannel>(_channel);
private TrapRunner CreateRunner(TimeSpan maxHoldDuration, bool ignorePrivateNetworks = true)
private TrapRunner CreateRunner(
TimeSpan maxHoldDuration,
bool ignorePrivateNetworks = true,
IRepeatOffenderLookup? repeatOffenders = null,
int repeatWindowDays = 0,
TimeSpan? repeatHoldDuration = null)
{
var dripOptions = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(20) });
var random = new SeededRandomSource(7);
@@ -122,7 +179,14 @@ public sealed class TrapRunnerTests
_governor,
new ConfiguredStrategySelector([drip], dripOptions, random),
_sink,
TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration, IgnorePrivateNetworks = ignorePrivateNetworks }),
repeatOffenders ?? new NullRepeatLookup(),
TestOptions.Monitor(new FlypaperOptions
{
MaxHoldDuration = maxHoldDuration,
IgnorePrivateNetworks = ignorePrivateNetworks,
RepeatWindowDays = repeatWindowDays,
RepeatHoldDuration = repeatHoldDuration ?? TimeSpan.FromHours(24)
}),
TimeProvider.System,
NullLogger<TrapRunner>.Instance);
}
@@ -9,6 +9,10 @@ internal sealed class FakeTrapChannel : ITrapChannel
{
public TrapSession Session { get; } = new(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Loopback, DateTimeOffset.UtcNow);
public string? Path { get; init; }
public string? Host { get; init; }
public ConcurrentQueue<byte[]> Writes { get; } = new();
public ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct)
+11 -4
View File
@@ -14,9 +14,14 @@ namespace Flypaper.Tests.Http;
public sealed class ContentTypeTests
{
[Theory]
[InlineData("Html", "text/html; charset=utf-8")]
[InlineData("Text", "text/plain; charset=utf-8")]
public async Task Trap_answers_with_the_media_type_of_the_selected_strategy(string content, string expected)
[InlineData("Html", "/", "text/html; charset=utf-8")]
[InlineData("Text", "/", "text/plain; charset=utf-8")]
[InlineData("Html", "/config.json", "application/json")]
[InlineData("Html", "/.env", "text/plain; charset=utf-8")]
[InlineData("Html", "/sitemap.xml", "application/xml")]
[InlineData("Html", "/SDK/webLanguage", "application/xml")]
[InlineData("Html", "/wp-login.php", "text/html; charset=UTF-8")]
public async Task Trap_answers_with_the_media_type_of_the_selected_strategy(string content, string path, string expected)
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
@@ -39,11 +44,13 @@ public sealed class ContentTypeTests
var context = new DefaultHttpContext { RequestServices = services };
context.Connection.RemoteIpAddress = IPAddress.Parse("203.0.113.9");
context.Connection.LocalPort = 8080;
context.Request.Path = "/";
context.Request.Path = path;
await app.Build()(context);
context.Response.StatusCode.ShouldBe(StatusCodes.Status200OK);
context.Response.ContentType.ShouldBe(expected);
context.Response.Headers.Server.ToString().ShouldBe("nginx");
context.Response.ContentLength.ShouldBeNull();
}
}
@@ -98,6 +98,7 @@ public sealed class FlypaperToolsTests : IDisposable
[InlineData("countries", "CN", 2)]
[InlineData("providers", "AS4134", 2)]
[InlineData("targets", "GET /.env", 1)]
[InlineData("strategies", "html-drip", 4)]
[InlineData("user_agents", "zgrab/0.x", 2)]
public async Task Top_ranks_each_dimension(string dimension, string firstKey, int firstCount)
{
+135 -9
View File
@@ -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|strategies|user_agents)")]
[InlineData("top", """{"period":"all"}""", "missing required parameter 'dimension' (ips|countries|providers|targets|strategies|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();
}
}
+8 -5
View File
@@ -15,21 +15,23 @@ 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();
Add(db, "203.0.113.9", hoursAgo: 1, seconds: 3600, "CN", "Volksrepublik China", "Beijing", 4134, "Chinanet", "GET /.env", "zgrab/0.x");
Add(db, "203.0.113.9", hoursAgo: 1, seconds: 3600, "CN", "Volksrepublik China", "Beijing", 4134, "Chinanet", "GET /.env", "zgrab/0.x", strategy: "env-drip");
Add(db, "203.0.113.9", hoursAgo: 2, seconds: 120, "CN", "Volksrepublik China", "Beijing", 4134, "Chinanet", "GET example.com/wp-login.php", "zgrab/0.x");
Add(db, "198.51.100.7", hoursAgo: 3, seconds: 30, "TW", "Republik China", "Taipeh", 3462, "Data Communication Business Group", "GET /.git/config", "curl/8.5.0");
Add(db, "2001:db8::1", hoursAgo: 30, seconds: 900, "US", "Vereinigte Staaten von Amerika", "Mountain View", 15169, "Google LLC", "POST /xmlrpc.php", "python-requests/2.31");
Add(db, "198.51.100.7", hoursAgo: 4, seconds: 0, "TW", "Republik China", "Taipeh", 3462, "Data Communication Business Group", "GET /.env", "curl/8.5.0", TrapOutcome.Rejected);
Add(db, "198.51.100.7", hoursAgo: 4, seconds: 0, "TW", "Republik China", "Taipeh", 3462, "Data Communication Business Group", "GET /.env", "curl/8.5.0", TrapOutcome.Rejected, "env-drip");
Add(db, "192.0.2.50", hoursAgo: 200, seconds: 5, null, null, null, null, null, "GET /", null);
db.SaveChanges();
}
public IDbContextFactory<FlypaperDbContext> Factory { get; }
public string ConnectionString => $"Data Source={_dbPath}";
private static void Add(
FlypaperDbContext db,
string ip,
@@ -42,14 +44,15 @@ internal sealed class McpTestData : IDisposable
string? provider,
string target,
string? userAgent,
TrapOutcome outcome = TrapOutcome.ClientAborted)
TrapOutcome outcome = TrapOutcome.ClientAborted,
string strategy = "html-drip")
{
var started = Now.AddHours(-hoursAgo);
var entity = TrapEventEntity.From(new TrapEvent(
Guid.NewGuid(),
TrapProtocol.Http,
IPAddress.Parse(ip),
"html-drip",
strategy,
started,
started.AddSeconds(seconds),
seconds * 10,
@@ -21,7 +21,7 @@ public sealed class McpTokenServiceTests : IDisposable
var token = await service.CreateAsync("Claude Desktop");
token.Length.ShouldBeGreaterThan(40);
(await service.ValidateAsync(token)).ShouldBeTrue();
(await service.AuthenticateAsync(token)).ShouldBeTrue();
var stored = (await _store.ListAsync()).ShouldHaveSingleItem();
stored.Name.ShouldBe("Claude Desktop");
stored.TokenHash.ShouldBe(McpTokenService.Hash(token));
@@ -35,12 +35,12 @@ public sealed class McpTokenServiceTests : IDisposable
var service = Create(environmentToken: null);
var token = await service.CreateAsync("test");
(await service.ValidateAsync(null)).ShouldBeFalse();
(await service.ValidateAsync("")).ShouldBeFalse();
(await service.ValidateAsync(token + "x")).ShouldBeFalse();
(await service.AuthenticateAsync(null)).ShouldBeFalse();
(await service.AuthenticateAsync("")).ShouldBeFalse();
(await service.AuthenticateAsync(token + "x")).ShouldBeFalse();
(await _store.RevokeAsync((await _store.ListAsync())[0].Id)).ShouldBeTrue();
(await service.ValidateAsync(token)).ShouldBeFalse();
(await service.AuthenticateAsync(token)).ShouldBeFalse();
}
[Fact]
@@ -50,9 +50,9 @@ public sealed class McpTokenServiceTests : IDisposable
var stored = await service.CreateAsync("test");
service.UsesEnvironmentToken.ShouldBeTrue();
(await service.ValidateAsync("fixed-token-from-environment")).ShouldBeTrue();
(await service.ValidateAsync(stored)).ShouldBeTrue();
(await service.ValidateAsync("fixed-token")).ShouldBeFalse();
(await service.AuthenticateAsync("fixed-token-from-environment")).ShouldBeTrue();
(await service.AuthenticateAsync(stored)).ShouldBeTrue();
(await service.AuthenticateAsync("fixed-token")).ShouldBeFalse();
}
private McpTokenService Create(string? environmentToken) =>
@@ -0,0 +1,133 @@
using System.Net;
using Flypaper.Core.Models;
using Flypaper.Storage.Entities;
using Flypaper.Web.Components.Shared;
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);
}
[Fact]
public async Task Matches_strategy_exactly()
{
var recent = await _queries.GetRecentAsync(new RecentFilter(Strategy: StrategyNames.Group("env-drip")));
recent.Total.ShouldBe(2);
recent.Items.ShouldAllBe(e => e.Strategy == "env-drip");
}
[Fact]
public async Task Dashboard_lists_strategy_durations_among_catches()
{
var data = await _queries.GetAsync();
data.StrategyCatches.Count.ShouldBe(5);
data.StrategyCatches.Count(s => s.Strategy == "env-drip").ShouldBe(1);
data.StrategyCatches.Single(s => s.Strategy == "env-drip").DurationMs.ShouldBe(3_600_000);
}
[Fact]
public async Task Strategy_group_matches_all_variants_of_the_base_type_and_its_old_name()
{
await using (var db = _data.Factory.CreateDbContext())
{
foreach (var strategy in new[] { "drip", "html-drip 50-500ms 1-640B", "html-drip 5-20ms 1-64B head 1024B", "html-drip 50-500ms 1-1024B repeat", "html-drip 50-500ms 1-64B head 1024B repeat" })
{
db.TrapEvents.Add(TrapEventEntity.From(new TrapEvent(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("192.0.2.1"), strategy, McpTestData.Now, McpTestData.Now, 0, TrapOutcome.ClientAborted, null, null)));
}
await db.SaveChangesAsync();
}
async Task<IReadOnlyList<string>> Find(string group) =>
(await _queries.GetRecentAsync(new RecentFilter(Strategy: StrategyNames.Group(group)))).Items.Select(e => e.Strategy).OrderBy(s => s).ToList();
(await Find("html-drip")).Where(s => s != "html-drip").ShouldBe(["drip", "html-drip 50-500ms 1-640B"]);
(await Find("html-drip head")).ShouldBe(["html-drip 5-20ms 1-64B head 1024B"]);
(await Find("html-drip repeat")).ShouldBe(["html-drip 50-500ms 1-1024B repeat"]);
(await Find("html-drip head repeat")).ShouldBe(["html-drip 50-500ms 1-64B head 1024B repeat"]);
}
[Theory]
[InlineData("chinanet", 2)]
[InlineData("env-drip", 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_strategy_and_user_agent(string search, int expected)
{
var recent = await _queries.GetRecentAsync(new RecentFilter(Search: search));
recent.Total.ShouldBe(expected);
}
[Fact]
public async Task Search_also_matches_strategy_base_names_from_display_names()
{
var recent = await _queries.GetRecentAsync(new RecentFilter(Search: "Zugangsdaten", SearchStrategies: ["env-drip"]));
recent.Total.ShouldBe(2);
recent.Items.ShouldAllBe(e => e.Strategy == "env-drip");
}
[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,44 @@
using System.Net;
using Flypaper.Core.Models;
using Flypaper.Storage.Entities;
using Flypaper.Storage.Queries;
using Flypaper.Tests.Mcp;
using Shouldly;
namespace Flypaper.Tests.Storage;
public sealed class RepeatOffenderLookupTests : IDisposable
{
private readonly McpTestData _data = new();
[Fact]
public async Task Finds_only_timeouts_of_the_same_ip_inside_the_window()
{
using (var db = _data.Factory.CreateDbContext())
{
Add(db, "203.0.113.50", hoursAgo: 48, TrapOutcome.Timeout);
Add(db, "203.0.113.51", hoursAgo: 2, TrapOutcome.ClientAborted);
Add(db, "2001:db8::7", hoursAgo: 3, TrapOutcome.Timeout);
Add(db, "203.0.113.52", hoursAgo: 24 * 30, TrapOutcome.Timeout);
db.SaveChanges();
}
var lookup = new RepeatOffenderLookup(_data.Factory);
var since = McpTestData.Now.UtcDateTime.AddDays(-7);
(await lookup.HasTimedOutSinceAsync(IPAddress.Parse("203.0.113.50"), since, default)).ShouldBeTrue();
(await lookup.HasTimedOutSinceAsync(IPAddress.Parse("2001:db8::7"), since, default)).ShouldBeTrue();
(await lookup.HasTimedOutSinceAsync(IPAddress.Parse("203.0.113.51"), since, default)).ShouldBeFalse();
(await lookup.HasTimedOutSinceAsync(IPAddress.Parse("203.0.113.52"), since, default)).ShouldBeFalse();
(await lookup.HasTimedOutSinceAsync(IPAddress.Parse("203.0.113.99"), since, default)).ShouldBeFalse();
}
private static void Add(Flypaper.Storage.FlypaperDbContext db, string ip, int hoursAgo, TrapOutcome outcome)
{
var started = McpTestData.Now.AddHours(-hoursAgo);
db.TrapEvents.Add(TrapEventEntity.From(new TrapEvent(
Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse(ip), "html-drip", started, started.AddSeconds(3600), 100, outcome, "GET /", null)));
}
public void Dispose() => _data.Dispose();
}
@@ -89,17 +89,25 @@ public sealed class SettingsOverrideTests : IDisposable
var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
string[] holdKeys = [.. SettingKeys.HoldMethod];
await store.SaveAsync(new HoldMethodSettings(DripContent.Text, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, TimeSpan.FromMinutes(5)));
await store.SaveAsync(new HoldMethodSettings(DripContent.Text, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, 256, false, 0, "/trap-a/", TimeSpan.FromMinutes(5), 7, TimeSpan.FromHours(24)));
await store.SaveAsync(new RuntimeSettings(50, 4, 90, true));
drip.CurrentValue.Content.ShouldBe(DripContent.Text);
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(200));
drip.CurrentValue.MaxChunkSize.ShouldBe(16);
drip.CurrentValue.HeadStartSize.ShouldBe(256);
drip.CurrentValue.MatchPath.ShouldBeFalse();
drip.CurrentValue.LinkSpacing.ShouldBe(0);
drip.CurrentValue.BaitPaths.ShouldBe("/trap-a/");
core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(5));
core.CurrentValue.MaxConnections.ShouldBe(50);
(await store.HasOverridesAsync(holdKeys)).ShouldBeTrue();
await store.SaveAsync(new HoldMethodSettings(DripContent.Text, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, 256, false, 0, "", TimeSpan.FromMinutes(5), 0, TimeSpan.FromHours(2)));
drip.CurrentValue.BaitPaths.ShouldBe("");
await store.ResetAsync(holdKeys);
drip.CurrentValue.BaitPaths.ShouldBe(BaitPaths.Default);
drip.CurrentValue.Content.ShouldBe(DripContent.Html);
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50));
@@ -0,0 +1,78 @@
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", " env-drip ", " wp ", "100");
filter.ShouldBe(new DashboardFilter("24h", "abgelehnt", "HK", "AS4134", "203.0.113.9", "GET /.env", "env-drip", "wp", 100));
var recent = filter.ToRecentFilter();
recent.ShouldBe(new RecentFilter(TimeSpan.FromHours(24), TrapOutcome.Rejected, "HK", 4134, "203.0.113.9", "GET /.env", recent.Strategy, "wp", 100));
recent.Strategy!.Bases.ShouldBe(["env-drip"]);
recent.Strategy.With.ShouldBeEmpty();
recent.Strategy.Without.ShouldBe(["head", "link", "repeat"]);
}
[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, 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, 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", Strategie: "html-drip head", Limit: 100).Href("f50")
.ShouldBe("/?land=CN&ziel=GET%20example.com%2Fa%26b&strategie=html-drip%20head&limit=100#f50");
}
[Fact]
public void Links_round_trip()
{
var filter = new DashboardFilter("7d", "zeitlimit", "TW", "AS3462", "2001:db8::1", "POST /xmlrpc.php", "hikvision-drip", "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["strategie"], query["q"], query["limit"])
.ShouldBe(filter);
}
[Theory]
[InlineData("html-drip 50-500ms 1-1024B", "html-drip")]
[InlineData("drip", "html-drip")]
[InlineData("html-drip 50-500ms 1-64B head 1024B", "html-drip head")]
public void Normalizes_strategy_links_to_the_group(string strategy, string expected) =>
DashboardFilter.Parse(null, null, null, null, null, null, strategy, null, null).Strategie.ShouldBe(expected);
[Fact]
public void Doubles_the_limit_up_to_the_maximum()
{
new DashboardFilter().NextLimit.ShouldBe(100);
new DashboardFilter(Limit: 400).NextLimit.ShouldBe(RecentFilter.MaxLimit);
}
}
@@ -0,0 +1,107 @@
using Flypaper.Core.Strategies;
using Flypaper.Storage.Dashboard;
using Flypaper.Web.Components.Shared;
using Shouldly;
namespace Flypaper.Tests.Web;
public sealed class StrategyNamesTests
{
[Fact]
public void Describes_the_maze_with_all_suffixes()
{
var info = StrategyNames.Describe("maze-drip 50-500ms 1-1024B head 1024B link 160B repeat");
info.DisplayName.ShouldBe("Link-Labyrinth");
info.Explanation.ShouldNotBeNull();
info.Details.ShouldBe([
"tröpfelt 1–1.024 Byte alle 50–500 ms",
"schneller Start: die ersten 1.024 Byte sofort",
"alle 160 Byte ein Link",
"Wiederholer: darf länger festgehalten werden"
]);
info.Raw.ShouldBe("maze-drip 50-500ms 1-1024B head 1024B link 160B repeat");
info.Tooltip.ShouldContain("Technisch: maze-drip 50-500ms");
}
[Fact]
public void Shows_unknown_names_and_tokens_unchanged()
{
var info = StrategyNames.Describe("ufo-drip 5-9ms 1-2B odd");
info.DisplayName.ShouldBe("ufo-drip");
info.Explanation.ShouldBeNull();
info.Details.ShouldBe(["tröpfelt 1–2 Byte alle 5–9 ms", "odd"]);
}
[Theory]
[InlineData("robots-static")]
[InlineData("robots-bait 10-20ms 1-8B link 160B")]
public void Covers_robots_strategies(string strategy) =>
StrategyNames.Describe(strategy).Explanation.ShouldNotBeNull();
[Fact]
public void Covers_every_strategy_name_of_the_core()
{
string[] names =
[
MazeDripStrategy.PageName, MazeDripStrategy.ListingName, MazeDripStrategy.BaitName,
HtmlDripStrategy.StrategyName, TextDripStrategy.StrategyName, RobotsStaticStrategy.StrategyName,
.. FileContent.Profiles.Select(profile => profile.Name)
];
foreach (var name in names)
{
StrategyNames.Describe(name).Explanation.ShouldNotBeNull(name);
}
}
[Fact]
public void Finds_base_names_by_display_name()
{
StrategyNames.Matching(" gefälschtes git ").ShouldBe(["git-drip"]);
StrategyNames.Matching("zugangsdaten").ShouldBe(["env-drip"]);
StrategyNames.Matching("").ShouldBeEmpty();
StrategyNames.Matching("nichts").ShouldBeEmpty();
}
[Fact]
public void Groups_variants_by_base_type_and_shows_only_content_differences_as_badges()
{
StrategyNames.Describe("html-drip 50-500ms 1-1024B").GroupKey.ShouldBe("html-drip");
StrategyNames.Describe("html-drip 50-500ms 1-640B").GroupKey.ShouldBe("html-drip");
var variant = StrategyNames.Describe("html-drip 5-20ms 1-64B head 1024B repeat");
variant.GroupKey.ShouldBe("html-drip head repeat");
variant.Badges.ShouldBe(["Schnellstart", "Wiederholer"]);
StrategyNames.Describe("maze-drip 50-500ms 1-1024B head 1024B link 160B").Badges.ShouldBe(["Schnellstart"]);
}
[Fact]
public void Treats_drip_as_the_old_name_of_the_endless_page()
{
var info = StrategyNames.Describe("drip");
info.DisplayName.ShouldBe("Endlose Webseite");
info.GroupKey.ShouldBe("html-drip");
StrategyNames.Matching("endlose webseite").ShouldBe(["html-drip", "drip"]);
}
[Fact]
public void Ranks_groups_by_median_and_sinks_groups_with_few_catches()
{
var samples = new List<StrategySample>();
samples.AddRange(Enumerable.Repeat(new StrategySample("html-drip 50-500ms 1-1024B", 10_000), 3));
samples.AddRange(Enumerable.Repeat(new StrategySample("html-drip 50-500ms 1-640B", 20_000), 2));
samples.Add(new StrategySample("drip", 1_000_000));
samples.AddRange(Enumerable.Repeat(new StrategySample("env-drip 50-500ms 1-1024B", 30_000), 5));
samples.Add(new StrategySample("text-drip", 500_000_000));
var ranked = StrategyNames.Rank(samples, 10);
ranked.Select(r => r.Key).ShouldBe(["env-drip", "html-drip", "text-drip"]);
ranked[0].MedianHold.ShouldBe(TimeSpan.FromSeconds(30));
ranked[1].Count.ShouldBe(6);
ranked[1].MedianHold.ShouldBe(TimeSpan.FromSeconds(15));
ranked[1].HoldTime.ShouldBe(TimeSpan.FromMilliseconds(1_070_000));
}
}
+14 -5
View File
@@ -38,14 +38,23 @@ public sealed class WorldMapDataTests
public void Small_bot_heavy_countries_have_markers(string code) =>
_map.Markers.ShouldContain(m => m.Code == code);
[Fact]
public void No_country_has_both_a_polygon_and_a_marker()
[Theory]
[InlineData("IL")]
[InlineData("LB")]
[InlineData("PS")]
[InlineData("KW")]
[InlineData("QA")]
[InlineData("NL")]
public void Tiny_countries_with_a_polygon_also_have_a_marker(string code)
{
var polygons = _map.Countries.Select(c => c.Code).OfType<string>().ToHashSet();
_map.Markers.Where(m => polygons.Contains(m.Code)).ShouldBeEmpty();
_map.Countries.ShouldContain(c => c.Code == code);
_map.Markers.ShouldContain(m => m.Code == code);
}
[Fact]
public void Markers_are_unique_per_country() =>
_map.Markers.Select(m => m.Code).ShouldBeUnique();
[Fact]
public void Markers_lie_inside_the_map() =>
_map.Markers.ShouldAllBe(m => m.X >= 0 && m.X <= _map.Width && m.Y >= 0 && m.Y <= _map.Height);