4 Commits
Author SHA1 Message Date
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
77 changed files with 2816 additions and 88 deletions

No files matched your search

+37 -2
View File
@@ -6,6 +6,8 @@ All notable changes to Flypaper are documented in this file. The format follows
## [Unreleased]
## [0.5.0] - 2026-11-17
### Fixed
- Narrow or tiny countries that are drawn as a polygon but barely visible (Israel, Lebanon,
@@ -14,8 +16,40 @@ All notable changes to Flypaper are documented in this file. The format follows
### 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/…`, `robots.txt`, Hikvision `/SDK/…` and `/ISAPI/…` (XML) and `wp-login.php`
`/.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`).
@@ -140,7 +174,8 @@ 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.4.0...main
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.5.0...main
[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
+1
View File
@@ -10,6 +10,7 @@
<PackageVersion Include="Microsoft.Extensions.Http" Version="10.0.15" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.15" />
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.15" />
<PackageVersion Include="Markdig" Version="0.38.0" />
<PackageVersion Include="MaxMind.GeoIP2" Version="6.1.0" />
<PackageVersion Include="ModelContextProtocol.AspNetCore" Version="2.4.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15" />
+3 -1
View File
@@ -24,7 +24,9 @@ All optional. Read at startup; list entries need an index (`__0`, `__1`, ...).
| `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__MatchPath` | Pick content by request path (`/.env`, `*.json`, `*.xml`, `*.yml`, `*.sql`, `/.git/…`, `robots.txt`, `/SDK/…`, `/ISAPI/…`, `wp-login.php`) | `true` |
| `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.
@@ -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);
}
@@ -21,6 +21,16 @@ 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(
@@ -33,6 +43,7 @@ public static class FlypaperCoreExtensions
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;
}
@@ -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,22 +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;
@@ -11,7 +11,11 @@ public sealed record HoldMethodSettings(
int MaxChunkSize,
int HeadStartSize,
bool MatchPath,
TimeSpan MaxHoldDuration)
int LinkSpacing,
string BaitPaths,
TimeSpan MaxHoldDuration,
int RepeatWindowDays,
TimeSpan RepeatHoldDuration)
{
public double BytesPerSecond => AverageBytesPerSecond(MinDelay, MaxDelay, MinChunkSize, MaxChunkSize);
@@ -24,7 +28,11 @@ public sealed record HoldMethodSettings(
[SettingKeys.DripMaxChunkSize] = MaxChunkSize.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripHeadStartSize] = HeadStartSize.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripMatchPath] = MatchPath ? "true" : "false",
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
[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)
@@ -42,6 +50,10 @@ public sealed record HoldMethodInput(
string? MaxChunkSize,
string? HeadStartSize,
bool MatchPath,
string? MaxHoldDuration);
string? LinkSpacing,
string? BaitPaths,
string? MaxHoldDuration,
string? RepeatWindowDays,
string? RepeatHoldDuration);
public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary<string, string> Errors);
@@ -14,6 +14,8 @@ public static class RuntimeSettingsParser
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)
{
@@ -59,7 +61,11 @@ public static class RuntimeSettingsParser
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)
{
@@ -85,10 +91,34 @@ public static class RuntimeSettingsParser
maxChunk!.Value,
headStart!.Value,
input.MatchPath,
hold!.Value),
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,
@@ -105,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;
}
+5 -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";
@@ -14,12 +16,14 @@ public static class SettingKeys
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, DripHeadStartSize, DripMatchPath, 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));
}
}
@@ -17,4 +17,8 @@ public sealed class DripOptions
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 -3
View File
@@ -22,13 +22,13 @@ public abstract class DripStrategy(
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{head}");
$"{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)
{
var current = options.CurrentValue;
using var fragments = Content(random).GetEnumerator();
using var fragments = Content(random, channel, current).GetEnumerator();
var head = DripSchedule.TakeHead(fragments, current.HeadStartSize);
if (head.Length > 0)
@@ -44,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);
}
+23 -8
View File
@@ -11,12 +11,11 @@ public sealed record FileProfile(
public static class FileContent
{
private static readonly string[] Sections = ["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files"];
public static readonly IReadOnlyList<FileProfile> Profiles =
[
new("git-drip", "text/plain; charset=utf-8", path => path.Contains("/.git/", StringComparison.Ordinal), GitConfig),
new("robots-drip", "text/plain; charset=utf-8", path => LastSegment(path) == "robots.txt", Robots),
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),
@@ -37,6 +36,11 @@ public static class FileContent
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) =>
@@ -131,7 +135,7 @@ public static class FileContent
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, Sections)}/{LoremText.Phrase(random, 2).Replace(' ', '-')}</loc>\n <lastmod>{date}</lastmod>\n </url>\n";
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";
}
}
@@ -170,13 +174,24 @@ public static class FileContent
}
}
private static IEnumerable<string> Robots(IRandomSource random)
private static IEnumerable<string> Svn(IRandomSource random)
{
yield return "User-agent: *\nCrawl-delay: 2\nSitemap: https://example.com/sitemap.xml\n";
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)
{
yield return $"Disallow: /{Pick(random, Sections)}/{LoremText.Word(random)}/\n";
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";
}
}
@@ -13,5 +13,5 @@ public sealed class FileDripStrategy(
public override string MediaType => profile.MediaType;
protected override IEnumerable<string> Content(IRandomSource random) => profile.Generate(random);
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);
@@ -10,6 +10,7 @@ public sealed record DashboardData(
TimeSpan TotalHoldTime,
IReadOnlyList<TopEntry> TopIps,
IReadOnlyList<TopEntry> TopTargets,
IReadOnlyList<TopEntry> TopStrategies,
IReadOnlyList<TopEntry> TopCountries,
IReadOnlyList<TopEntry> TopProviders,
IReadOnlyDictionary<string, int> CatchesByCountry);
@@ -42,6 +42,7 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)),
await TopAsync(catches.GroupBy(e => e.RemoteIp), ct),
await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct),
await TopAsync(catches.GroupBy(e => e.Strategy), ct),
countries
.Take(TopCount)
.Select(x => new TopEntry(x.Key, x.Count, TimeSpan.FromMilliseconds(x.DurationMs), x.Name))
@@ -104,6 +105,11 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
events = events.Where(e => e.Target == target);
}
if (filter.Strategy is { } strategy)
{
events = events.Where(e => e.Strategy == strategy);
}
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var pattern = $"%{filter.Search.Trim().Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_")}%";
@@ -111,6 +117,7 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
EF.Functions.Like(e.RemoteIp, pattern, "\\")
|| EF.Functions.Like(e.Provider!, pattern, "\\")
|| EF.Functions.Like(e.Target!, pattern, "\\")
|| EF.Functions.Like(e.Strategy, pattern, "\\")
|| EF.Functions.Like(e.ClientInfo!, pattern, "\\"));
}
@@ -10,6 +10,7 @@ public sealed record RecentFilter(
long? Asn = null,
string? Ip = null,
string? Target = null,
string? Strategy = null,
string? Search = null,
int Limit = RecentFilter.DefaultLimit)
{
@@ -0,0 +1,41 @@
namespace Flypaper.Storage.Entities;
public enum IdeaLevel
{
Low = 1,
Medium = 2,
High = 3
}
public enum IdeaStatus
{
Open,
InProgress,
Done,
Dropped
}
public sealed class IdeaEntity
{
public int Id { get; set; }
public required string Title { get; set; }
public IdeaLevel Effort { get; set; }
public IdeaLevel Efficiency { get; set; }
public required string Rationale { get; set; }
public IdeaStatus Status { get; set; }
public DateTime? ImplementedOn { get; set; }
public string? Commit { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public bool IsClosed => Status is IdeaStatus.Done or IdeaStatus.Dropped;
}
@@ -0,0 +1,33 @@
namespace Flypaper.Storage.Entities;
public enum LabEntryKind
{
Experiment,
Observation,
Hypothesis,
Method
}
public sealed class LabEntryEntity
{
public int Id { get; set; }
public DateTime Date { get; set; }
public required string Title { get; set; }
public LabEntryKind Kind { get; set; }
public required string Text { get; set; }
public string? Commit { get; set; }
public string? Strategies { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public IReadOnlyList<string> StrategyList =>
(Strategies ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
}
@@ -11,4 +11,6 @@ public sealed class McpTokenEntity
public DateTime CreatedAt { get; set; }
public DateTime? LastUsedAt { get; set; }
public bool CanWrite { get; set; }
}
+22
View File
@@ -14,6 +14,10 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
public DbSet<McpTokenEntity> McpTokens => Set<McpTokenEntity>();
public DbSet<LabEntryEntity> LabEntries => Set<LabEntryEntity>();
public DbSet<IdeaEntity> Ideas => Set<IdeaEntity>();
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
@@ -43,5 +47,23 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
mcpToken.Property(e => e.Name).HasMaxLength(100);
mcpToken.Property(e => e.TokenHash).HasMaxLength(64);
mcpToken.HasIndex(e => e.TokenHash).IsUnique();
var labEntry = modelBuilder.Entity<LabEntryEntity>();
labEntry.Property(e => e.Title).HasMaxLength(LabLimits.TitleLength);
labEntry.Property(e => e.Kind).HasConversion<string>().HasMaxLength(16);
labEntry.Property(e => e.Text).HasMaxLength(LabLimits.TextLength);
labEntry.Property(e => e.Commit).HasMaxLength(LabLimits.CommitLength);
labEntry.Property(e => e.Strategies).HasMaxLength(LabLimits.StrategiesLength);
labEntry.Ignore(e => e.StrategyList);
labEntry.HasIndex(e => e.Date);
var idea = modelBuilder.Entity<IdeaEntity>();
idea.Property(e => e.Title).HasMaxLength(LabLimits.TitleLength);
idea.Property(e => e.Effort).HasConversion<string>().HasMaxLength(16);
idea.Property(e => e.Efficiency).HasConversion<string>().HasMaxLength(16);
idea.Property(e => e.Rationale).HasMaxLength(LabLimits.TextLength);
idea.Property(e => e.Status).HasConversion<string>().HasMaxLength(16);
idea.Property(e => e.Commit).HasMaxLength(LabLimits.CommitLength);
idea.Ignore(e => e.IsClosed);
}
}
@@ -3,6 +3,7 @@ using Flypaper.Storage.Dashboard;
using Flypaper.Storage.Events;
using Flypaper.Storage.Maintenance;
using Flypaper.Storage.Queries;
using Flypaper.Storage.Research;
using Flypaper.Storage.Settings;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
@@ -23,6 +24,7 @@ public static class FlypaperStorageExtensions
builder.Services.AddSingleton<RuntimeSettingsStore>();
builder.Services.AddSingleton<AdminCredentialStore>();
builder.Services.AddSingleton<McpTokenStore>();
builder.Services.AddSingleton<ResearchStore>();
builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName));
builder.Services.AddFlypaperStorage(connectionString);
@@ -38,6 +40,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");
}
}
}
@@ -17,12 +17,109 @@ namespace Flypaper.Storage.Migrations
#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");
@@ -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,10 @@
namespace Flypaper.Storage;
public static class LabLimits
{
public const int TitleLength = 200;
public const int TextLength = 20_000;
public const int CommitLength = 64;
public const int StrategiesLength = 512;
public const int StrategyNameLength = 64;
}
@@ -0,0 +1,247 @@
using System.Text.RegularExpressions;
using Flypaper.Storage.Entities;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Research;
public sealed record LabEntryInput(
string? Title = null,
LabEntryKind? Kind = null,
string? Text = null,
DateTime? Date = null,
string? Commit = null,
IReadOnlyList<string>? Strategies = null);
public sealed record IdeaInput(
string? Title = null,
IdeaLevel? Effort = null,
IdeaLevel? Efficiency = null,
string? Rationale = null,
IdeaStatus? Status = null,
DateTime? ImplementedOn = null,
string? Commit = null);
public sealed partial class ResearchStore(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
{
public const int MaxLimit = 500;
[GeneratedRegex("^[0-9a-f]{4,64}$")]
private static partial Regex CommitPattern();
[GeneratedRegex("^[a-z0-9][a-z0-9._-]*$")]
private static partial Regex StrategyPattern();
public async Task<IReadOnlyList<LabEntryEntity>> ListEntriesAsync(
LabEntryKind? kind = null,
string? strategy = null,
int limit = MaxLimit,
CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var entries = db.LabEntries.AsNoTracking();
if (kind is { } wanted)
{
entries = entries.Where(e => e.Kind == wanted);
}
var rows = await entries.OrderByDescending(e => e.Date).ThenByDescending(e => e.Id).ToListAsync(ct);
if (!string.IsNullOrWhiteSpace(strategy))
{
var name = strategy.Trim().ToLowerInvariant();
rows = rows.Where(e => e.StrategyList.Contains(name, StringComparer.Ordinal)).ToList();
}
return rows.Take(Math.Clamp(limit, 1, MaxLimit)).ToList();
}
public async Task<LabEntryEntity> CreateEntryAsync(LabEntryInput input, CancellationToken ct = default)
{
var now = timeProvider.GetUtcNow().UtcDateTime;
var entry = new LabEntryEntity
{
Title = RequireText(input.Title, "title", LabLimits.TitleLength),
Kind = input.Kind ?? throw new ArgumentException("kind is required."),
Text = RequireText(input.Text, "text", LabLimits.TextLength),
Date = (input.Date ?? now).Date,
Commit = ParseCommit(input.Commit),
Strategies = JoinStrategies(input.Strategies),
CreatedAt = now,
UpdatedAt = now
};
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
db.LabEntries.Add(entry);
await db.SaveChangesAsync(ct);
return entry;
}
public async Task<LabEntryEntity?> UpdateEntryAsync(int id, LabEntryInput input, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var entry = await db.LabEntries.SingleOrDefaultAsync(e => e.Id == id, ct);
if (entry is null)
{
return null;
}
if (input.Title is not null)
{
entry.Title = RequireText(input.Title, "title", LabLimits.TitleLength);
}
if (input.Kind is { } kind)
{
entry.Kind = kind;
}
if (input.Text is not null)
{
entry.Text = RequireText(input.Text, "text", LabLimits.TextLength);
}
if (input.Date is { } date)
{
entry.Date = date.Date;
}
if (input.Commit is not null)
{
entry.Commit = ParseCommit(input.Commit);
}
if (input.Strategies is not null)
{
entry.Strategies = JoinStrategies(input.Strategies);
}
entry.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;
await db.SaveChangesAsync(ct);
return entry;
}
public async Task<IReadOnlyList<IdeaEntity>> ListIdeasAsync(IdeaStatus? status = null, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var ideas = db.Ideas.AsNoTracking();
if (status is { } wanted)
{
ideas = ideas.Where(i => i.Status == wanted);
}
var rows = await ideas.ToListAsync(ct);
return rows
.OrderBy(i => i.Effort)
.ThenByDescending(i => i.Efficiency)
.ThenBy(i => i.Id)
.ToList();
}
public async Task<IdeaEntity> CreateIdeaAsync(IdeaInput input, CancellationToken ct = default)
{
var now = timeProvider.GetUtcNow().UtcDateTime;
var status = input.Status ?? IdeaStatus.Open;
var idea = new IdeaEntity
{
Title = RequireText(input.Title, "title", LabLimits.TitleLength),
Effort = input.Effort ?? throw new ArgumentException("effort is required."),
Efficiency = input.Efficiency ?? throw new ArgumentException("efficiency is required."),
Rationale = RequireText(input.Rationale, "rationale", LabLimits.TextLength),
Status = status,
Commit = ParseCommit(input.Commit),
CreatedAt = now,
UpdatedAt = now
};
idea.ImplementedOn = ImplementedOn(status, input.ImplementedOn, null, now);
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
db.Ideas.Add(idea);
await db.SaveChangesAsync(ct);
return idea;
}
public async Task<IdeaEntity?> UpdateIdeaAsync(int id, IdeaInput input, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var idea = await db.Ideas.SingleOrDefaultAsync(i => i.Id == id, ct);
if (idea is null)
{
return null;
}
var now = timeProvider.GetUtcNow().UtcDateTime;
if (input.Title is not null)
{
idea.Title = RequireText(input.Title, "title", LabLimits.TitleLength);
}
if (input.Effort is { } effort)
{
idea.Effort = effort;
}
if (input.Efficiency is { } efficiency)
{
idea.Efficiency = efficiency;
}
if (input.Rationale is not null)
{
idea.Rationale = RequireText(input.Rationale, "rationale", LabLimits.TextLength);
}
if (input.Commit is not null)
{
idea.Commit = ParseCommit(input.Commit);
}
var status = input.Status ?? idea.Status;
idea.Status = status;
idea.ImplementedOn = ImplementedOn(status, input.ImplementedOn, idea.ImplementedOn, now);
idea.UpdatedAt = now;
await db.SaveChangesAsync(ct);
return idea;
}
private static DateTime? ImplementedOn(IdeaStatus status, DateTime? given, DateTime? current, DateTime now) =>
status == IdeaStatus.Done ? (given ?? current ?? now).Date : null;
private static string RequireText(string? value, string name, int maxLength)
{
var text = value?.Trim();
if (string.IsNullOrEmpty(text))
{
throw new ArgumentException($"{name} must not be empty.");
}
return text.Length <= maxLength ? text : throw new ArgumentException($"{name} is too long (at most {maxLength} characters).");
}
private static string? ParseCommit(string? value)
{
var commit = value?.Trim().ToLowerInvariant();
if (string.IsNullOrEmpty(commit))
{
return null;
}
return CommitPattern().IsMatch(commit) ? commit : throw new ArgumentException("commit must be a hexadecimal hash of 4 to 64 characters.");
}
private static string? JoinStrategies(IReadOnlyList<string>? strategies)
{
var names = (strategies ?? [])
.Select(name => name.Trim().ToLowerInvariant())
.Where(name => name.Length > 0)
.Distinct()
.ToList();
if (names.Any(name => name.Length > LabLimits.StrategyNameLength || !StrategyPattern().IsMatch(name)))
{
throw new ArgumentException("strategies must be strategy names such as maze-drip or git-drip (letters, digits, '.', '_' and '-').");
}
var joined = string.Join(',', names);
return joined.Length == 0 ? null
: joined.Length <= LabLimits.StrategiesLength ? joined
: throw new ArgumentException("strategies list is too long.");
}
}
@@ -13,10 +13,10 @@ public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContext
return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct);
}
public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, CancellationToken ct = default)
public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, bool canWrite = false, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };
var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CanWrite = canWrite, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };
db.McpTokens.Add(token);
await db.SaveChangesAsync(ct);
return token;
@@ -28,6 +28,12 @@ public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContext
return await db.McpTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct) > 0;
}
public async Task<bool> SetCanWriteAsync(int id, bool canWrite, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.McpTokens.Where(t => t.Id == id).ExecuteUpdateAsync(set => set.SetProperty(t => t.CanWrite, canWrite), ct) > 0;
}
public async Task<McpTokenEntity?> UseAsync(string tokenHash, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
@@ -4,6 +4,7 @@
<nav class="nav">
<a href="/" class="brand"><span class="brand-mark" aria-hidden="true"></span>Flypaper</a>
<NavLink href="/" Match="NavLinkMatch.All">Dashboard</NavLink>
<NavLink href="/erkenntnisse">Erkenntnisse</NavLink>
<NavLink href="/settings">Einstellungen</NavLink>
<form method="post" action="/auth/logout" class="logout">
<AntiforgeryToken />
@@ -12,6 +12,7 @@ public sealed record DashboardFilter(
string? Provider = null,
string? Ip = null,
string? Ziel = null,
string? Strategie = null,
string? Q = null,
int Limit = RecentFilter.DefaultLimit)
{
@@ -31,6 +32,7 @@ public sealed record DashboardFilter(
string? provider,
string? ip,
string? ziel,
string? strategie,
string? q,
string? limit)
{
@@ -45,6 +47,7 @@ public sealed record DashboardFilter(
Asn(provider) is { } asn ? $"AS{asn.ToString(CultureInfo.InvariantCulture)}" : null,
IPAddress.TryParse(Clean(ip), out var address) ? address.ToString() : null,
Clean(ziel),
Clean(strategie),
Clean(q),
parsedLimit);
}
@@ -67,6 +70,7 @@ public sealed record DashboardFilter(
Asn(Provider),
Ip,
Ziel,
Strategie,
Q,
Limit);
@@ -81,6 +85,7 @@ public sealed record DashboardFilter(
Add(parts, "provider", Provider);
Add(parts, "ip", Ip);
Add(parts, "ziel", Ziel);
Add(parts, "strategie", Strategie);
Add(parts, "q", Q);
if (Limit != RecentFilter.DefaultLimit)
{
@@ -127,9 +127,9 @@
</label>
<label class="filter-search">
<span>Suche</span>
<input type="search" name="q" value="@_filter.Q" placeholder="IP, Provider, Ziel, User-Agent" />
<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) })
@foreach (var (name, value) in new[] { ("provider", _filter.Provider), ("ip", _filter.Ip), ("ziel", _filter.Ziel), ("strategie", _filter.Strategie) })
{
if (value is not null)
{
@@ -163,6 +163,7 @@
<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>
@@ -194,11 +195,13 @@
<td class="c-target mono" title="@target">
@target
<div class="extra extra-md">Provider: @(provider ?? "–")</div>
<div class="extra extra-md">Strategie: @trapEvent.Strategy</div>
<div class="extra extra-md">User-Agent: @(trapEvent.ClientInfo ?? "–")</div>
<div class="extra extra-all">Herkunft: @(trapEvent.CountryCode is { } code ? $"{Formatting.Flag(code)} {code} · {Origin(trapEvent)}" : "–")</div>
<div class="extra extra-sm">Dauer: @duration · Bytes: @bytes</div>
<div class="extra extra-xs">Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @OutcomeLabel(trapEvent.Outcome)</div>
</td>
<td class="c-strategy mono" title="@trapEvent.Strategy">@trapEvent.Strategy</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>
@@ -247,13 +250,15 @@
[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, Q, Limit);
_filter = DashboardFilter.Parse(Zeit, Ausgang, Land, Provider, Ip, Ziel, Strategie, Q, Limit);
_data = await Queries.GetAsync();
_recent = await Queries.GetRecentAsync(_filter.ToRecentFilter());
_loadedAt = DateTime.Now;
@@ -264,7 +269,8 @@
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("targets", "Ziele", "Ziel", data.TopTargets, f => f.Ziel, (f, key) => f with { Ziel = key }, KeyFormatter: Formatting.Target),
new("strategies", "Strategien", "Strategie", data.TopStrategies, f => f.Strategie, (f, key) => f with { Strategie = key })
];
private DashboardFilter TopFilter(TopTab tab, TopEntry entry) =>
@@ -306,6 +312,11 @@
yield return ($"Ziel: {Formatting.Target(ziel)}", reset with { Ziel = null });
}
if (_filter.Strategie is { } strategie)
{
yield return ($"Strategie: {strategie}", reset with { Strategie = null });
}
if (_filter.Q is { } q)
{
yield return ($"Suche: „{q}“", reset with { Q = null });
@@ -0,0 +1,58 @@
@using Flypaper.Storage.Entities
<div class="table-scroll">
<table class="idea-table">
<thead>
<tr>
<th>Idee</th>
<th>Aufwand</th>
<th>Effizienz</th>
<th>Status</th>
<th>Umgesetzt</th>
</tr>
</thead>
<tbody>
@foreach (var idea in Ideas)
{
<tr>
<td>
<strong>@idea.Title</strong>
<div class="markdown muted">@MarkdownRenderer.Render(idea.Rationale)</div>
</td>
<td class="nowrap">@Level(idea.Effort)</td>
<td class="nowrap">@Level(idea.Efficiency)</td>
<td class="nowrap"><span class="badge status-@idea.Status.ToString().ToLowerInvariant()">@StatusLabel(idea.Status)</span></td>
<td class="nowrap">
@if (idea.ImplementedOn is { } date)
{
@date.ToString("dd.MM.yyyy")
}
@if (idea.Commit is { } commit)
{
<code title="@commit">@(commit.Length > 8 ? commit[..8] : commit)</code>
}
</td>
</tr>
}
</tbody>
</table>
</div>
@code {
[Parameter, EditorRequired] public required IReadOnlyList<IdeaEntity> Ideas { get; set; }
private static string Level(IdeaLevel level) => level switch
{
IdeaLevel.Low => "Gering",
IdeaLevel.Medium => "Mittel",
_ => "Hoch"
};
private static string StatusLabel(IdeaStatus status) => status switch
{
IdeaStatus.Open => "Offen",
IdeaStatus.InProgress => "In Arbeit",
IdeaStatus.Done => "Umgesetzt",
_ => "Verworfen"
};
}
@@ -0,0 +1,139 @@
@page "/erkenntnisse"
@using Flypaper.Storage.Entities
@using Flypaper.Storage.Research
@inject ResearchStore Store
<PageTitle>Flypaper · Erkenntnisse</PageTitle>
<header class="page-head">
<h1>Erkenntnisse</h1>
<p>Laborbuch und Ideen zur Optimierung der Falle. Einträge werden per MCP fortgeschrieben.</p>
</header>
<section class="card" id="laborbuch">
<div class="card-head">
<h2>Laborbuch</h2>
<span class="hint">@_entries.Count @(_entries.Count == 1 ? "Eintrag" : "Einträge")</span>
</div>
<nav class="chips" aria-label="Art filtern">
<a class="chip @(_kind is null ? "active" : null)" href="erkenntnisse@(Query(null, ShowClosed))#laborbuch">Alle</a>
@foreach (var kind in Enum.GetValues<LabEntryKind>())
{
<a class="chip @(_kind == kind ? "active" : null)" href="erkenntnisse@(Query(kind, ShowClosed))#laborbuch">@KindLabel(kind)</a>
}
</nav>
@if (_entries.Count == 0)
{
<p class="empty">Noch keine Einträge.</p>
}
else
{
<div class="lab-entries">
@foreach (var entry in _entries)
{
<article class="lab-entry">
<header>
<time class="mono" datetime="@entry.Date.ToString("yyyy-MM-dd")">@entry.Date.ToString("dd.MM.yyyy")</time>
<span class="badge kind-@entry.Kind.ToString().ToLowerInvariant()">@KindLabel(entry.Kind)</span>
<h3>@entry.Title</h3>
</header>
@if (entry.StrategyList.Count > 0 || entry.Commit is not null)
{
<p class="lab-meta">
@foreach (var strategy in entry.StrategyList)
{
<code>@strategy</code>
}
@if (entry.Commit is { } commit)
{
<span class="muted">Commit</span>
<code title="@commit">@Short(commit)</code>
}
</p>
}
<div class="markdown">@MarkdownRenderer.Render(entry.Text)</div>
</article>
}
</div>
}
</section>
<section class="card" id="ideen">
<div class="card-head">
<h2>Ideen</h2>
<span class="hint">nach Aufwand sortiert</span>
</div>
@if (_open.Count == 0)
{
<p class="empty">Keine offenen Ideen.</p>
}
else
{
<IdeaTable Ideas="_open" />
}
@if (_closed.Count > 0)
{
<p class="more">
<a href="erkenntnisse@(Query(_kind, !ShowClosed))#ideen">
@(ShowClosed ? "Umgesetzte und verworfene ausblenden" : $"{_closed.Count} umgesetzte oder verworfene anzeigen")
</a>
</p>
@if (ShowClosed)
{
<IdeaTable Ideas="_closed" />
}
}
</section>
@code {
private IReadOnlyList<LabEntryEntity> _entries = [];
private IReadOnlyList<IdeaEntity> _open = [];
private IReadOnlyList<IdeaEntity> _closed = [];
private LabEntryKind? _kind;
[SupplyParameterFromQuery(Name = "art")] private string? Art { get; set; }
[SupplyParameterFromQuery(Name = "erledigt")] private string? Closed { get; set; }
private bool ShowClosed => Closed == "1";
protected override async Task OnInitializedAsync()
{
_kind = Enum.TryParse<LabEntryKind>(Art, ignoreCase: true, out var kind) && Enum.IsDefined(kind) ? kind : null;
_entries = await Store.ListEntriesAsync(_kind);
var ideas = await Store.ListIdeasAsync();
_open = ideas.Where(idea => !idea.IsClosed).ToList();
_closed = ideas.Where(idea => idea.IsClosed).ToList();
}
private static string Query(LabEntryKind? kind, bool showClosed)
{
var parts = new List<string>();
if (kind is { } value)
{
parts.Add("art=" + value.ToString().ToLowerInvariant());
}
if (showClosed)
{
parts.Add("erledigt=1");
}
return parts.Count == 0 ? "" : "?" + string.Join('&', parts);
}
private static string Short(string commit) => commit.Length > 8 ? commit[..8] : commit;
internal static string KindLabel(LabEntryKind kind) => kind switch
{
LabEntryKind.Experiment => "Experiment",
LabEntryKind.Observation => "Beobachtung",
LabEntryKind.Hypothesis => "Hypothese",
_ => "Messmethode"
};
}
@@ -16,5 +16,13 @@ public sealed class HoldMethodModel
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; }
}
@@ -59,9 +59,24 @@
<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" 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">
@@ -92,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.")
];
@@ -138,7 +153,11 @@
Model.MaxChunkSize,
Model.HeadStartSize,
Model.MatchPath,
Model.MaxHoldDuration));
Model.LinkSpacing,
Model.BaitPaths,
Model.MaxHoldDuration,
Model.RepeatWindowDays,
Model.RepeatHoldDuration));
if (result.Settings is null)
{
@@ -168,7 +187,11 @@
MaxChunkSize = drip.MaxChunkSize.ToString(CultureInfo.InvariantCulture),
HeadStartSize = drip.HeadStartSize.ToString(CultureInfo.InvariantCulture),
MatchPath = drip.MatchPath,
MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
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,11 +5,19 @@
@inject McpTokenStore Store
@inject NavigationManager Navigation
<SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol. Nur 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 und führen die Erkenntnisse fort. Schreiben dürfen nur Tokens mit Schreibrecht. Nur im LAN.">
@if (Revoked == "revoked")
{
<Notice>Token widerrufen.</Notice>
}
else if (Revoked == "write-on")
{
<Notice>Schreibrecht erteilt.</Notice>
}
else if (Revoked == "write-off")
{
<Notice>Schreibrecht entzogen.</Notice>
}
@if (_newToken is not null)
{
@@ -37,6 +45,7 @@
<th>Name</th>
<th>Erstellt</th>
<th>Zuletzt genutzt</th>
<th>Zugriff</th>
<th></th>
</tr>
</thead>
@@ -47,6 +56,14 @@
<td>@token.Name</td>
<td class="nowrap">@token.CreatedAt.ToLocalTime().ToString("dd.MM.yyyy HH:mm")</td>
<td class="nowrap">@(token.LastUsedAt?.ToLocalTime().ToString("dd.MM.yyyy HH:mm") ?? "nie")</td>
<td class="nowrap">
<form method="post" action="/mcp-tokens/@token.Id/write" class="inline-form">
<AntiforgeryToken />
<input type="hidden" name="enabled" value="@(token.CanWrite ? "false" : "true")" />
<span>@(token.CanWrite ? "Lesen und schreiben" : "Nur lesen")</span>
<button type="submit" class="ghost">@(token.CanWrite ? "Schreibrecht entziehen" : "Schreibrecht erteilen")</button>
</form>
</td>
<td class="num">
<form method="post" action="/mcp-tokens/@token.Id/revoke" onsubmit="return confirm('Token „@token.Name“ widerrufen?')">
<AntiforgeryToken />
@@ -72,6 +89,10 @@
<span class="field-error">@nameError</span>
}
</div>
<label class="inline-check">
<InputCheckbox @bind-Value="Model!.CanWrite" />
<span>Mit Schreibrecht</span>
</label>
<button type="submit">Token erzeugen</button>
</EditForm>
</SettingsSection>
@@ -103,9 +124,10 @@
return;
}
_newToken = await Tokens.CreateAsync(name);
_newToken = await Tokens.CreateAsync(name, Model.CanWrite);
_newTokenName = name;
Model.Name = null;
Model.CanWrite = false;
_tokens = await Store.ListAsync();
}
}
@@ -3,4 +3,6 @@ namespace Flypaper.Web.Components.Pages.Settings;
public sealed class McpTokenModel
{
public string? Name { get; set; }
public bool CanWrite { get; set; }
}
@@ -0,0 +1,57 @@
using Markdig;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
using Microsoft.AspNetCore.Components;
namespace Flypaper.Web.Components.Shared;
public static class MarkdownRenderer
{
private static readonly string[] SafeSchemes = ["http", "https", "mailto"];
private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder()
.DisableHtml()
.UseAutoLinks()
.UsePipeTables()
.UseEmphasisExtras()
.Build();
public static MarkupString Render(string? markdown)
{
if (string.IsNullOrWhiteSpace(markdown))
{
return new MarkupString("");
}
var document = Markdown.Parse(markdown, Pipeline);
foreach (var link in document.Descendants<LinkInline>().Where(link => !IsSafe(link.Url)).ToList())
{
link.Url = "#";
}
foreach (var link in document.Descendants<AutolinkInline>().Where(link => !IsSafe(link.Url)).ToList())
{
link.Url = "#";
}
return new MarkupString(document.ToHtml(Pipeline));
}
private static bool IsSafe(string? url)
{
if (string.IsNullOrWhiteSpace(url))
{
return true;
}
var trimmed = url.Trim();
var colon = trimmed.IndexOf(':');
var firstSeparator = trimmed.IndexOfAny(['/', '?', '#']);
if (colon < 0 || firstSeparator >= 0 && firstSeparator < colon)
{
return true;
}
return SafeSchemes.Contains(trimmed[..colon], StringComparer.OrdinalIgnoreCase);
}
}
+1
View File
@@ -10,6 +10,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Markdig" />
<PackageReference Include="ModelContextProtocol.AspNetCore" />
</ItemGroup>
+4 -3
View File
@@ -62,8 +62,8 @@ 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 by: ips, countries, providers, targets or user_agents.")]
[AllowedValues("ips", "countries", "providers", "targets", "user_agents")]
[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,
@@ -75,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);
+52 -5
View File
@@ -1,3 +1,4 @@
using System.Security.Claims;
using System.Text.Json;
using System.Text.Json.Serialization;
using Flypaper.Storage.Settings;
@@ -18,7 +19,9 @@ 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. Most tools only read that data; times are ISO 8601 UTC, durations in seconds. The tools " +
"for the Erkenntnisse page (lab notebook entries and ideas) can also write, but only with a token that " +
"has write permission; read-only tokens do not see the write tools.";
private static readonly JsonSerializerOptions ToolJsonOptions = new(McpJsonUtilities.DefaultOptions)
{
@@ -44,11 +47,44 @@ public static class McpExtensions
})
.WithHttpTransport(options => options.Stateless = true)
.WithTools<FlypaperTools>(ToolJsonOptions)
.WithRequestFilters(filters => filters.AddCallToolFilter(next => async (context, ct) =>
.WithTools<ResearchTools>(ToolJsonOptions)
.WithRequestFilters(filters =>
{
filters.AddListToolsFilter(HideWriteTools);
filters.AddCallToolFilter(CheckCall);
});
return services;
}
private static McpRequestHandler<ListToolsRequestParams, ListToolsResult> HideWriteTools(McpRequestHandler<ListToolsRequestParams, ListToolsResult> next) =>
async (context, ct) =>
{
var result = await next(context, ct);
if (!CanWrite(context.User))
{
result.Tools = result.Tools.Where(tool => tool.Annotations?.ReadOnlyHint == true).ToList();
}
return result;
};
private static McpRequestHandler<CallToolRequestParams, CallToolResult> CheckCall(McpRequestHandler<CallToolRequestParams, CallToolResult> next) =>
async (context, ct) =>
{
var tool = context.Params?.Name;
var logger = context.Services?.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(FlypaperTools));
if (context.MatchedPrimitive is McpServerTool { ProtocolTool.Annotations.ReadOnlyHint: not true } && !CanWrite(context.User))
{
logger?.LogWarning("MCP tool {Tool} was called with a token without write permission", tool);
return new CallToolResult
{
IsError = true,
Content = [new TextContentBlock { Text = $"'{tool}' needs a token with write permission. Enable it for this token in the dashboard under Einstellungen > MCP-Zugriff." }]
};
}
if (context.MatchedPrimitive is McpServerTool matched
&& McpArgumentCheck.FindProblem(matched.ProtocolTool.InputSchema, context.Params?.Arguments?.AsReadOnly()) is { } problem)
{
@@ -65,10 +101,9 @@ public static class McpExtensions
logger?.LogWarning(exception, "MCP tool {Tool} was called with invalid arguments", tool);
return InvalidArguments(tool, exception.Message);
}
}));
};
return services;
}
private static bool CanWrite(ClaimsPrincipal? user) => user?.HasClaim(McpTokenAuthenticationHandler.WriteClaim, "true") == true;
private static CallToolResult InvalidArguments(string? tool, string message) => new()
{
@@ -91,6 +126,18 @@ public static class McpExtensions
return Results.LocalRedirect("/settings?mcp=revoked#mcp");
});
app.MapPost("/mcp-tokens/{id:int}/write", async (int id, HttpContext context, IAntiforgery antiforgery, McpTokenStore store) =>
{
if (!await antiforgery.IsRequestValidAsync(context))
{
return Results.BadRequest();
}
var enabled = (await context.Request.ReadFormAsync(context.RequestAborted))["enabled"] == "true";
await store.SetCanWriteAsync(id, enabled, context.RequestAborted);
return Results.LocalRedirect("/settings?mcp=" + (enabled ? "write-on" : "write-off") + "#mcp");
});
return app;
}
}
+27
View File
@@ -50,3 +50,30 @@ public sealed record IpLookupResult(
DateTime? LastSeen,
IReadOnlyList<CatchItem> Events,
int EventsOmitted);
public sealed record EntryItem(
int Id,
DateOnly Date,
string Title,
string Kind,
string Text,
string? Commit,
IReadOnlyList<string> Strategies,
DateTime CreatedAt,
DateTime UpdatedAt);
public sealed record EntryListResult(int Count, IReadOnlyList<EntryItem> Entries);
public sealed record IdeaItem(
int Id,
string Title,
string Effort,
string Efficiency,
string Rationale,
string Status,
DateOnly? ImplementedOn,
string? Commit,
DateTime CreatedAt,
DateTime UpdatedAt);
public sealed record IdeaListResult(int Count, IReadOnlyList<IdeaItem> Ideas);
@@ -13,6 +13,8 @@ public sealed class McpTokenAuthenticationHandler(
{
public const string SchemeName = "McpToken";
public const string WriteClaim = "mcp:write";
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var header = Request.Headers.Authorization.ToString();
@@ -21,12 +23,17 @@ public sealed class McpTokenAuthenticationHandler(
return AuthenticateResult.NoResult();
}
if (!await tokens.ValidateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted))
if (await tokens.AuthenticateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted) is not { } access)
{
return AuthenticateResult.Fail("Invalid MCP token.");
}
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "mcp")], SchemeName);
if (access == McpAccess.Write)
{
identity.AddClaim(new Claim(WriteClaim, "true"));
}
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName));
}
+14 -6
View File
@@ -6,33 +6,41 @@ using Microsoft.Extensions.Options;
namespace Flypaper.Web.Mcp;
public enum McpAccess
{
Read,
Write
}
public sealed class McpTokenService(McpTokenStore store, IOptions<McpOptions> options)
{
private const string Prefix = "fpm_";
public bool UsesEnvironmentToken => !string.IsNullOrEmpty(options.Value.Token);
public async Task<string> CreateAsync(string name, CancellationToken ct = default)
public async Task<string> CreateAsync(string name, bool canWrite = false, CancellationToken ct = default)
{
var token = Prefix + WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
await store.CreateAsync(name, Hash(token), ct);
await store.CreateAsync(name, Hash(token), canWrite, ct);
return token;
}
public async Task<bool> ValidateAsync(string? token, CancellationToken ct = default)
public async Task<McpAccess?> AuthenticateAsync(string? token, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(token))
{
return false;
return null;
}
if (UsesEnvironmentToken
&& CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(token)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Value.Token!))))
{
return true;
return McpAccess.Read;
}
return await store.UseAsync(Hash(token), ct) is not null;
return await store.UseAsync(Hash(token), ct) is { } stored
? stored.CanWrite ? McpAccess.Write : McpAccess.Read
: null;
}
public static string Hash(string token) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
+188
View File
@@ -0,0 +1,188 @@
using System.ComponentModel;
using System.Globalization;
using Flypaper.Storage.Entities;
using Flypaper.Storage.Research;
using ModelContextProtocol;
using ModelContextProtocol.Server;
namespace Flypaper.Web.Mcp;
[McpServerToolType]
public sealed class ResearchTools(ResearchStore store)
{
private const string KindDescription = "experiment, observation, hypothesis or method (measurement method).";
private const string LevelDescription = "low, medium or high.";
private const string StatusDescription = "open, in_progress, done or dropped.";
private const string DateDescription = "ISO 8601 date, e.g. 2026-11-17. Defaults to today.";
private const string CommitDescription = "Git commit hash. An empty string removes it.";
private const string StrategiesDescription = "Names of the strategies concerned, e.g. maze-drip, git-drip, robots-bait. An empty list removes them.";
[McpServerTool(Name = "list_entries", Title = "List lab notebook entries", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Entries of the lab notebook on the Erkenntnisse page (experiments, observations, hypotheses, measurement methods), newest first. Text is Markdown.")]
public async Task<EntryListResult> ListEntries(
[Description("Only this kind: " + KindDescription)] string? kind = null,
[Description("Only entries that concern this strategy name.")] string? strategy = null,
[Description("Maximum number of entries, 1 to 500.")] int limit = 100,
CancellationToken ct = default)
{
var entries = (await store.ListEntriesAsync(kind is null ? null : ParseKind(kind), strategy, limit, ct)).Select(ToItem).ToList();
return new EntryListResult(entries.Count, entries);
}
[McpServerTool(Name = "list_ideas", Title = "List ideas", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Ideas for improving the tarpit with effort, efficiency and status, sorted by effort (lowest first).")]
public async Task<IdeaListResult> ListIdeas(
[Description("Only this status: " + StatusDescription)] string? status = null,
CancellationToken ct = default)
{
var ideas = (await store.ListIdeasAsync(status is null ? null : ParseStatus(status), ct)).Select(ToItem).ToList();
return new IdeaListResult(ideas.Count, ideas);
}
[McpServerTool(Name = "create_entry", Title = "Create lab notebook entry", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false, UseStructuredContent = true)]
[Description("Adds an entry to the lab notebook. Needs a token with write permission.")]
public async Task<EntryItem> CreateEntry(
[Description("Short title, at most 200 characters.")] string title,
[Description("Kind: " + KindDescription)] string kind,
[Description("Markdown text; raw HTML is not rendered.")] string text,
[Description(DateDescription)] string? date = null,
[Description("Git commit hash.")] string? commit = null,
[Description(StrategiesDescription)] string[]? strategies = null,
CancellationToken ct = default) =>
ToItem(await store.CreateEntryAsync(new LabEntryInput(title, ParseKind(kind), text, ParseDate(date), commit, strategies), ct));
[McpServerTool(Name = "update_entry", Title = "Update lab notebook entry", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Changes an entry of the lab notebook; only the given fields are changed. Needs a token with write permission.")]
public async Task<EntryItem> UpdateEntry(
[Description("Id of the entry.")] int id,
[Description("New title.")] string? title = null,
[Description("New kind: " + KindDescription)] string? kind = null,
[Description("New Markdown text.")] string? text = null,
[Description("New date: " + DateDescription)] string? date = null,
[Description(CommitDescription)] string? commit = null,
[Description(StrategiesDescription)] string[]? strategies = null,
CancellationToken ct = default) =>
ToItem(await store.UpdateEntryAsync(
id,
new LabEntryInput(title, kind is null ? null : ParseKind(kind), text, ParseDate(date), commit, strategies),
ct) ?? throw NotFound("entry", id));
[McpServerTool(Name = "create_idea", Title = "Create idea", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false, UseStructuredContent = true)]
[Description("Adds an idea for improving the tarpit. Needs a token with write permission.")]
public async Task<IdeaItem> CreateIdea(
[Description("Short title, at most 200 characters.")] string title,
[Description("Effort: " + LevelDescription)] string effort,
[Description("Expected efficiency: " + LevelDescription)] string efficiency,
[Description("Why this might work, in Markdown.")] string rationale,
[Description("Status: " + StatusDescription + " Defaults to open.")] string? status = null,
[Description(CommitDescription)] string? commit = null,
CancellationToken ct = default) =>
ToItem(await store.CreateIdeaAsync(
new IdeaInput(title, ParseLevel(effort, nameof(effort)), ParseLevel(efficiency, nameof(efficiency)), rationale, status is null ? null : ParseStatus(status), null, commit),
ct));
[McpServerTool(Name = "update_idea", Title = "Update idea", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Changes an idea; only the given fields are changed. Needs a token with write permission.")]
public async Task<IdeaItem> UpdateIdea(
[Description("Id of the idea.")] int id,
[Description("New title.")] string? title = null,
[Description("New effort: " + LevelDescription)] string? effort = null,
[Description("New efficiency: " + LevelDescription)] string? efficiency = null,
[Description("New rationale in Markdown.")] string? rationale = null,
[Description("New status: " + StatusDescription)] string? status = null,
[Description("Date of implementation: " + DateDescription)] string? implemented_on = null,
[Description(CommitDescription)] string? commit = null,
CancellationToken ct = default) =>
ToItem(await store.UpdateIdeaAsync(
id,
new IdeaInput(
title,
effort is null ? null : ParseLevel(effort, nameof(effort)),
efficiency is null ? null : ParseLevel(efficiency, nameof(efficiency)),
rationale,
status is null ? null : ParseStatus(status),
ParseDate(implemented_on),
commit),
ct) ?? throw NotFound("idea", id));
[McpServerTool(Name = "set_idea_status", Title = "Set idea status", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
[Description("Sets the status of an idea. Status done records the implementation date (today unless given). Needs a token with write permission.")]
public async Task<IdeaItem> SetIdeaStatus(
[Description("Id of the idea.")] int id,
[Description("Status: " + StatusDescription)] string status,
[Description("Date of implementation, only for done: " + DateDescription)] string? implemented_on = null,
[Description(CommitDescription)] string? commit = null,
CancellationToken ct = default) =>
ToItem(await store.UpdateIdeaAsync(id, new IdeaInput(Status: ParseStatus(status), ImplementedOn: ParseDate(implemented_on), Commit: commit), ct)
?? throw NotFound("idea", id));
private static McpException NotFound(string what, int id) => new($"There is no {what} with id {id}.");
internal static LabEntryKind ParseKind(string value) =>
value.Trim().ToLowerInvariant() switch
{
"experiment" => LabEntryKind.Experiment,
"observation" => LabEntryKind.Observation,
"hypothesis" => LabEntryKind.Hypothesis,
"method" => LabEntryKind.Method,
_ => throw new ArgumentException("kind must be one of experiment, observation, hypothesis, method.")
};
internal static IdeaLevel ParseLevel(string value, string name) =>
value.Trim().ToLowerInvariant() switch
{
"low" => IdeaLevel.Low,
"medium" => IdeaLevel.Medium,
"high" => IdeaLevel.High,
_ => throw new ArgumentException($"{name} must be one of low, medium, high.")
};
internal static IdeaStatus ParseStatus(string value) =>
value.Trim().ToLowerInvariant() switch
{
"open" => IdeaStatus.Open,
"in_progress" => IdeaStatus.InProgress,
"done" => IdeaStatus.Done,
"dropped" => IdeaStatus.Dropped,
_ => throw new ArgumentException("status must be one of open, in_progress, done, dropped.")
};
private static DateTime? ParseDate(string? value) =>
string.IsNullOrWhiteSpace(value) ? null
: DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var date)
? date
: throw new ArgumentException("Dates must be ISO 8601, e.g. 2026-11-17.");
private static string Name(LabEntryKind kind) => kind.ToString().ToLowerInvariant();
private static string Name(IdeaLevel level) => level.ToString().ToLowerInvariant();
private static string Name(IdeaStatus status) => status switch
{
IdeaStatus.InProgress => "in_progress",
_ => status.ToString().ToLowerInvariant()
};
private static EntryItem ToItem(LabEntryEntity entry) => new(
entry.Id,
DateOnly.FromDateTime(entry.Date),
entry.Title,
Name(entry.Kind),
entry.Text,
entry.Commit,
entry.StrategyList,
entry.CreatedAt,
entry.UpdatedAt);
private static IdeaItem ToItem(IdeaEntity idea) => new(
idea.Id,
idea.Title,
Name(idea.Effort),
Name(idea.Efficiency),
idea.Rationale,
Name(idea.Status),
idea.ImplementedOn is { } date ? DateOnly.FromDateTime(date) : null,
idea.Commit,
idea.CreatedAt,
idea.UpdatedAt);
}
+2
View File
@@ -22,6 +22,8 @@
"MaxConnections": 1000,
"MaxConnectionsPerIp": 10,
"MaxHoldDuration": "01:00:00",
"RepeatWindowDays": 7,
"RepeatHoldDuration": "1.00:00:00",
"Http": {
"TrustedProxies": []
}
+119
View File
@@ -464,6 +464,10 @@ a.button:hover {
width: 116px;
}
.recent-table .c-strategy {
width: 190px;
}
.recent-table .extra {
display: none;
margin-top: 4px;
@@ -474,6 +478,7 @@ a.button:hover {
@media (max-width: 1199px) {
.recent-table .c-provider,
.recent-table .c-strategy,
.recent-table .c-agent {
display: none;
}
@@ -1580,3 +1585,117 @@ button.danger-text {
clip-path: inset(50%);
white-space: nowrap;
}
.table-scroll {
overflow-x: auto;
}
.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);
}
.lab-entries {
display: grid;
gap: 12px;
}
.lab-entry {
padding: 12px 14px;
border: 1px solid var(--border);
border-radius: 8px;
}
.lab-entry header {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 10px;
}
.lab-entry h3 {
flex: 1 1 100%;
margin: 2px 0 0;
font-size: 15px;
}
.lab-meta {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
margin: 6px 0 0;
}
.markdown {
overflow-wrap: anywhere;
}
.markdown > :first-child {
margin-top: 6px;
}
.markdown > :last-child {
margin-bottom: 0;
}
.markdown h1,
.markdown h2,
.markdown h3,
.markdown h4 {
margin: 12px 0 4px;
font-size: 14px;
}
.markdown pre {
padding: 8px 10px;
overflow-x: auto;
border-radius: 6px;
background: var(--bg);
}
.markdown table {
width: auto;
}
.idea-table td {
vertical-align: top;
}
.idea-table .markdown {
margin-top: 2px;
font-size: 13px;
}
.badge.status-done {
border-color: var(--ok);
color: var(--ok);
}
.badge.status-dropped {
border-color: var(--muted);
color: var(--muted);
}
.inline-form {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 10px;
}
.inline-check {
display: inline-flex;
align-items: center;
gap: 6px;
}
+43 -4
View File
@@ -18,7 +18,19 @@ public sealed class FileContentTests
[InlineData("/docker-compose.yml", "yaml-drip")]
[InlineData("/backup/db.sql", "sql-drip")]
[InlineData("/.git/config", "git-drip")]
[InlineData("/robots.txt", "robots-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")]
@@ -30,6 +42,9 @@ public sealed class FileContentTests
[InlineData("/")]
[InlineData("/index.php")]
[InlineData("/sdkfoo")]
[InlineData("/.svnfoo")]
[InlineData("/.hgrc-not")]
[InlineData("/legit.git/x")]
[InlineData("/environment")]
[InlineData("")]
[InlineData(null)]
@@ -42,7 +57,11 @@ public sealed class FileContentTests
[InlineData("/docker-compose.yml", "version:")]
[InlineData("/dump.sql", "-- MySQL dump")]
[InlineData("/.git/config", "[core]")]
[InlineData("/robots.txt", "User-agent:")]
[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)
@@ -62,8 +81,24 @@ public sealed class FileContentTests
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("html-drip");
Selector(matchPath: false).Select(context).ShouldNotBeNull().Name.ShouldBe("html-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]
@@ -89,7 +124,11 @@ public sealed class FileContentTests
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,
@@ -6,7 +6,7 @@ namespace Flypaper.Tests.Core;
public sealed class HoldMethodParserTests
{
private static readonly HoldMethodInput Valid = new("Alternating", "50", "1000", "1", "64", "2048", true, "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()
@@ -20,6 +20,8 @@ public sealed class HoldMethodParserTests
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);
}
@@ -71,6 +73,34 @@ public sealed class HoldMethodParserTests
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")]
@@ -78,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()
{
@@ -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);
}
}
+66 -2
View File
@@ -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)
@@ -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)
{
+43 -4
View File
@@ -62,7 +62,7 @@ public sealed class McpEndpointTests : IDisposable
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
var listed = tools.GetProperty("result").GetProperty("tools").EnumerateArray().ToList();
listed.Select(t => t.GetProperty("name").GetString())
.ShouldBe(["get_stats", "list_catches", "longest_catches", "lookup_ip", "top"], ignoreOrder: true);
.ShouldBe(["get_stats", "list_catches", "list_entries", "list_ideas", "longest_catches", "lookup_ip", "top"], ignoreOrder: true);
listed.ShouldAllBe(t => t.GetProperty("annotations").GetProperty("readOnlyHint").GetBoolean());
listed.Where(t => !t.TryGetProperty("outputSchema", out var schema) || schema.ValueKind != JsonValueKind.Object).ShouldBeEmpty();
@@ -87,7 +87,11 @@ public sealed class McpEndpointTests : IDisposable
{ "top", """{"dimension":"user_agents","period":"all"}""" },
{ "longest_catches", """{"period":"all"}""" },
{ "lookup_ip", """{"ip":"203.0.113.9"}""" },
{ "lookup_ip", """{"ip":"192.0.2.1"}""" }
{ "lookup_ip", """{"ip":"192.0.2.1"}""" },
{ "list_entries", """{}""" },
{ "list_entries", """{"kind":"experiment","strategy":"git-drip","limit":5}""" },
{ "list_ideas", """{}""" },
{ "list_ideas", """{"status":"in_progress"}""" }
};
[Theory]
@@ -119,8 +123,8 @@ public sealed class McpEndpointTests : IDisposable
}
[Theory]
[InlineData("top", """{"by":"countries","period":"all"}""", "unknown parameter 'by'; expected 'dimension' (ips|countries|providers|targets|user_agents)")]
[InlineData("top", """{"period":"all"}""", "missing required parameter 'dimension' (ips|countries|providers|targets|user_agents)")]
[InlineData("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)
{
@@ -134,6 +138,41 @@ public sealed class McpEndpointTests : IDisposable
result.GetProperty("content")[0].GetProperty("text").GetString().ShouldNotBeNull().ShouldContain(expected, Case.Sensitive);
}
[Fact]
public async Task Write_tools_are_only_offered_to_and_usable_by_tokens_with_write_permission()
{
using var client = _factory.CreateClient();
var tokens = _factory.Services.GetRequiredService<McpTokenService>();
var readOnly = await tokens.CreateAsync("read");
var writer = await tokens.CreateAsync("write", canWrite: true);
var writerTools = (await ReadAsync(await client.SendAsync(Rpc("tools/list", writer)))).GetProperty("result").GetProperty("tools")
.EnumerateArray().Select(t => t.GetProperty("name").GetString()).ToList();
writerTools.ShouldBe(
["get_stats", "list_catches", "list_entries", "list_ideas", "longest_catches", "lookup_ip", "top", "create_entry", "update_entry", "create_idea", "update_idea", "set_idea_status"],
ignoreOrder: true);
var denied = (await ReadAsync(await client.SendAsync(Rpc("tools/call", readOnly, new
{
name = "create_entry",
arguments = new { title = "Test", kind = "observation", text = "Text" }
})))).GetProperty("result");
denied.GetProperty("isError").GetBoolean().ShouldBeTrue();
denied.GetProperty("content")[0].GetProperty("text").GetString().ShouldNotBeNull().ShouldContain("write permission");
var created = (await ReadAsync(await client.SendAsync(Rpc("tools/call", writer, new
{
name = "create_entry",
arguments = new { title = "Test", kind = "observation", text = "**Text**", strategies = new[] { "git-drip" } }
})))).GetProperty("result");
(created.TryGetProperty("isError", out var isError) && isError.GetBoolean()).ShouldBeFalse(created.ToString());
created.GetProperty("structuredContent").GetProperty("kind").GetString().ShouldBe("observation");
var listed = (await ReadAsync(await client.SendAsync(Rpc("tools/call", readOnly, new { name = "list_entries", arguments = new { } }))))
.GetProperty("result").GetProperty("structuredContent");
listed.GetProperty("count").GetInt32().ShouldBe(1);
}
private static async Task<Dictionary<string, JsonElement>> OutputSchemasAsync(HttpClient client, string token)
{
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
+5 -4
View File
@@ -19,11 +19,11 @@ internal sealed class McpTestData : IDisposable
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();
}
@@ -44,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)).ShouldBe(McpAccess.Read);
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)).ShouldBeNull();
(await service.AuthenticateAsync("")).ShouldBeNull();
(await service.AuthenticateAsync(token + "x")).ShouldBeNull();
(await _store.RevokeAsync((await _store.ListAsync())[0].Id)).ShouldBeTrue();
(await service.ValidateAsync(token)).ShouldBeFalse();
(await service.AuthenticateAsync(token)).ShouldBeNull();
}
[Fact]
@@ -50,9 +50,24 @@ 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")).ShouldBe(McpAccess.Read);
(await service.AuthenticateAsync(stored)).ShouldBe(McpAccess.Read);
(await service.AuthenticateAsync("fixed-token")).ShouldBeNull();
}
[Fact]
public async Task Write_permission_is_granted_per_token_and_can_be_withdrawn()
{
var service = Create(environmentToken: null);
var readOnly = await service.CreateAsync("read");
var writer = await service.CreateAsync("write", canWrite: true);
(await service.AuthenticateAsync(readOnly)).ShouldBe(McpAccess.Read);
(await service.AuthenticateAsync(writer)).ShouldBe(McpAccess.Write);
var id = (await _store.ListAsync()).Single(t => t.Name == "write").Id;
(await _store.SetCanWriteAsync(id, false)).ShouldBeTrue();
(await service.AuthenticateAsync(writer)).ShouldBe(McpAccess.Read);
}
private McpTokenService Create(string? environmentToken) =>
@@ -44,13 +44,32 @@ public sealed class RecentCatchesTests : IDisposable
recent.Total.ShouldBe(expected);
}
[Fact]
public async Task Matches_strategy_exactly()
{
var recent = await _queries.GetRecentAsync(new RecentFilter(Strategy: "env-drip"));
recent.Total.ShouldBe(2);
recent.Items.ShouldAllBe(e => e.Strategy == "env-drip");
}
[Fact]
public async Task Dashboard_ranks_strategies_among_catches()
{
var data = await _queries.GetAsync();
data.TopStrategies.Select(s => (s.Key, s.Count)).ShouldBe([("html-drip", 4), ("env-drip", 1)]);
data.TopStrategies[1].HoldTime.ShouldBe(TimeSpan.FromHours(1));
}
[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_and_user_agent(string search, int expected)
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));
@@ -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();
}
@@ -0,0 +1,79 @@
using Flypaper.Storage.Entities;
using Flypaper.Storage.Research;
using Flypaper.Tests.Fakes;
using Flypaper.Tests.Mcp;
using Shouldly;
namespace Flypaper.Tests.Storage;
public sealed class ResearchStoreTests : IDisposable
{
private readonly McpTestData _data = new();
private readonly ResearchStore _store;
public ResearchStoreTests() => _store = new ResearchStore(_data.Factory, new FixedTimeProvider(McpTestData.Now));
[Fact]
public async Task Entries_are_listed_newest_first_and_filtered_by_kind_and_strategy()
{
await _store.CreateEntryAsync(new LabEntryInput("Alt", LabEntryKind.Experiment, "a", new DateTime(2026, 11, 10), Strategies: ["git-drip"]));
await _store.CreateEntryAsync(new LabEntryInput("Neu", LabEntryKind.Observation, "b", new DateTime(2026, 11, 14), Strategies: ["maze-drip", "git-drip"]));
await _store.CreateEntryAsync(new LabEntryInput("Heute", LabEntryKind.Experiment, "c"));
(await _store.ListEntriesAsync()).Select(e => e.Title).ShouldBe(["Heute", "Neu", "Alt"]);
(await _store.ListEntriesAsync(LabEntryKind.Experiment)).Select(e => e.Title).ShouldBe(["Heute", "Alt"]);
(await _store.ListEntriesAsync(strategy: "GIT-drip")).Select(e => e.Title).ShouldBe(["Neu", "Alt"]);
(await _store.ListEntriesAsync(limit: 1)).ShouldHaveSingleItem().Title.ShouldBe("Heute");
(await _store.ListEntriesAsync()).First().Date.ShouldBe(McpTestData.Now.UtcDateTime.Date);
}
[Fact]
public async Task Update_changes_only_given_fields_and_empty_values_clear_optional_ones()
{
var entry = await _store.CreateEntryAsync(new LabEntryInput("Titel", LabEntryKind.Hypothesis, "Text", Commit: "ABCDEF1", Strategies: ["git-drip"]));
entry.Commit.ShouldBe("abcdef1");
var changed = await _store.UpdateEntryAsync(entry.Id, new LabEntryInput(Text: "Neu"));
changed.ShouldNotBeNull();
(changed.Title, changed.Text, changed.Commit, changed.Strategies).ShouldBe(("Titel", "Neu", "abcdef1", "git-drip"));
var cleared = await _store.UpdateEntryAsync(entry.Id, new LabEntryInput(Commit: "", Strategies: []));
cleared.ShouldNotBeNull();
(cleared.Commit, cleared.Strategies).ShouldBe((null, null));
(await _store.UpdateEntryAsync(999, new LabEntryInput(Title: "x"))).ShouldBeNull();
}
[Theory]
[InlineData("", "Text", "abc1", "git-drip")]
[InlineData("Titel", " ", "abc1", "git-drip")]
[InlineData("Titel", "Text", "not-a-hash", "git-drip")]
[InlineData("Titel", "Text", "abc1", "Git Drip!")]
public async Task Invalid_entries_are_rejected(string title, string text, string commit, string strategy) =>
await Should.ThrowAsync<ArgumentException>(() =>
_store.CreateEntryAsync(new LabEntryInput(title, LabEntryKind.Method, text, Commit: commit, Strategies: [strategy])));
[Fact]
public async Task Ideas_are_sorted_by_effort_then_efficiency_and_status_sets_implementation_date()
{
var hard = await _store.CreateIdeaAsync(new IdeaInput("Schwer", IdeaLevel.High, IdeaLevel.High, "r"));
var cheap = await _store.CreateIdeaAsync(new IdeaInput("Billig", IdeaLevel.Low, IdeaLevel.Medium, "r"));
var cheapBetter = await _store.CreateIdeaAsync(new IdeaInput("Billig und gut", IdeaLevel.Low, IdeaLevel.High, "r"));
(await _store.ListIdeasAsync()).Select(i => i.Title).ShouldBe(["Billig und gut", "Billig", "Schwer"]);
var done = await _store.UpdateIdeaAsync(cheap.Id, new IdeaInput(Status: IdeaStatus.Done, Commit: "abc123"));
done.ShouldNotBeNull();
(done.Status, done.ImplementedOn, done.Commit).ShouldBe((IdeaStatus.Done, McpTestData.Now.UtcDateTime.Date, "abc123"));
var reopened = await _store.UpdateIdeaAsync(cheap.Id, new IdeaInput(Status: IdeaStatus.Open));
reopened.ShouldNotBeNull().ImplementedOn.ShouldBeNull();
(await _store.ListIdeasAsync(IdeaStatus.Open)).Count.ShouldBe(3);
hard.Status.ShouldBe(IdeaStatus.Open);
cheapBetter.Status.ShouldBe(IdeaStatus.Open);
(await _store.UpdateIdeaAsync(999, new IdeaInput(Status: IdeaStatus.Done))).ShouldBeNull();
}
public void Dispose() => _data.Dispose();
}
@@ -89,7 +89,7 @@ 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, 256, false, 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);
@@ -97,11 +97,17 @@ public sealed class SettingsOverrideTests : IDisposable
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));
+10 -10
View File
@@ -10,10 +10,10 @@ public sealed class DashboardFilterTests
[Fact]
public void Parses_all_parameters()
{
var filter = DashboardFilter.Parse("24h", "Abgelehnt", "hk", "as4134", " 203.0.113.9 ", "GET /.env", " wp ", "100");
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", "wp", 100));
filter.ToRecentFilter().ShouldBe(new RecentFilter(TimeSpan.FromHours(24), TrapOutcome.Rejected, "HK", 4134, "203.0.113.9", "GET /.env", "wp", 100));
filter.ShouldBe(new DashboardFilter("24h", "abgelehnt", "HK", "AS4134", "203.0.113.9", "GET /.env", "env-drip", "wp", 100));
filter.ToRecentFilter().ShouldBe(new RecentFilter(TimeSpan.FromHours(24), TrapOutcome.Rejected, "HK", 4134, "203.0.113.9", "GET /.env", "env-drip", "wp", 100));
}
[Theory]
@@ -21,12 +21,12 @@ public sealed class DashboardFilterTests
[InlineData("zeitlimit", TrapOutcome.Timeout)]
[InlineData("abgelehnt", TrapOutcome.Rejected)]
public void Maps_outcomes(string value, TrapOutcome expected) =>
DashboardFilter.Parse(null, value, null, null, null, null, null, null).ToRecentFilter().Outcome.ShouldBe(expected);
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");
var filter = DashboardFilter.Parse("gestern", "kaputt", "Hongkong", "Chinanet", "not-an-ip", " ", " ", "", "viele");
filter.ShouldBe(new DashboardFilter());
filter.IsEmpty.ShouldBeTrue();
@@ -38,23 +38,23 @@ public sealed class DashboardFilterTests
[InlineData("100000", RecentFilter.MaxLimit)]
[InlineData(null, RecentFilter.DefaultLimit)]
public void Clamps_the_limit(string? limit, int expected) =>
DashboardFilter.Parse(null, null, null, null, null, null, null, limit).Limit.ShouldBe(expected);
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", Limit: 100).Href("f50")
.ShouldBe("/?land=CN&ziel=GET%20example.com%2Fa%26b&limit=100#f50");
new DashboardFilter(Land: "CN", Ziel: "GET example.com/a&b", Strategie: "html-drip 50-500ms 1-1024B", Limit: 100).Href("f50")
.ShouldBe("/?land=CN&ziel=GET%20example.com%2Fa%26b&strategie=html-drip%2050-500ms%201-1024B&limit=100#f50");
}
[Fact]
public void Links_round_trip()
{
var filter = new DashboardFilter("7d", "zeitlimit", "TW", "AS3462", "2001:db8::1", "POST /xmlrpc.php", "curl", 200);
var 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["q"], query["limit"])
DashboardFilter.Parse(query["zeit"], query["ausgang"], query["land"], query["provider"], query["ip"], query["ziel"], query["strategie"], query["q"], query["limit"])
.ShouldBe(filter);
}
@@ -0,0 +1,50 @@
using Flypaper.Web.Components.Shared;
using Shouldly;
namespace Flypaper.Tests.Web;
public sealed class MarkdownRendererTests
{
[Fact]
public void Renders_basic_markdown()
{
var html = MarkdownRenderer.Render("# Titel\n\n**fett** und `code`\n\n- eins\n- zwei").Value;
html.ShouldContain("<h1>Titel</h1>");
html.ShouldContain("<strong>fett</strong>");
html.ShouldContain("<code>code</code>");
html.ShouldContain("<li>eins</li>");
}
[Theory]
[InlineData("<script>alert(1)</script>")]
[InlineData("<img src=x onerror=alert(1)>")]
[InlineData("text <b onclick=\"x()\">fett</b>")]
public void Raw_html_is_escaped(string markdown)
{
var html = MarkdownRenderer.Render(markdown).Value;
html.ShouldNotContain("<script");
html.ShouldNotContain("<img");
html.ShouldNotContain("<b ");
}
[Theory]
[InlineData("[x](javascript:alert(1))")]
[InlineData("[x](JaVaScRiPt:alert(1))")]
[InlineData("[x](data:text/html;base64,AAAA)")]
[InlineData("![x](javascript:alert(1))")]
[InlineData("<javascript:alert(1)>")]
public void Unsafe_link_schemes_are_neutralized(string markdown) =>
MarkdownRenderer.Render(markdown).Value.ToLowerInvariant().ShouldNotContain("javascript:");
[Theory]
[InlineData("[x](https://example.com/a)", "https://example.com/a")]
[InlineData("[x](/erkenntnisse?art=experiment)", "/erkenntnisse?art=experiment")]
[InlineData("[x](mailto:a@example.com)", "mailto:a@example.com")]
public void Safe_links_are_kept(string markdown, string url) =>
MarkdownRenderer.Render(markdown).Value.ShouldContain($"href=\"{url}\"");
[Fact]
public void Empty_input_renders_nothing() => MarkdownRenderer.Render(null).Value.ShouldBeEmpty();
}