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>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-17 18:27:35 +01:00
1 parent a25072e6fb
commit e88dc415f9
48 files changed
+1966 -40

No files matched your search

+16
View File
@@ -14,6 +14,22 @@ 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/…`,
+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" />
@@ -0,0 +1,8 @@
using System.Net;
namespace Flypaper.Core.Abstractions;
public interface IRepeatOffenderLookup
{
ValueTask<bool> HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct);
}
@@ -43,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);
}
+9
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)
@@ -37,6 +38,14 @@ public sealed partial class TrapRunner(
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);
@@ -13,7 +13,9 @@ public sealed record HoldMethodSettings(
bool MatchPath,
int LinkSpacing,
string BaitPaths,
TimeSpan MaxHoldDuration)
TimeSpan MaxHoldDuration,
int RepeatWindowDays,
TimeSpan RepeatHoldDuration)
{
public double BytesPerSecond => AverageBytesPerSecond(MinDelay, MaxDelay, MinChunkSize, MaxChunkSize);
@@ -28,7 +30,9 @@ public sealed record HoldMethodSettings(
[SettingKeys.DripMatchPath] = MatchPath ? "true" : "false",
[SettingKeys.DripLinkSpacing] = LinkSpacing.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripBaitPaths] = BaitPaths,
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
[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)
@@ -48,6 +52,8 @@ public sealed record HoldMethodInput(
bool MatchPath,
string? LinkSpacing,
string? BaitPaths,
string? MaxHoldDuration);
string? MaxHoldDuration,
string? RepeatWindowDays,
string? RepeatHoldDuration);
public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary<string, string> Errors);
@@ -15,6 +15,7 @@ public static class RuntimeSettingsParser
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)
{
@@ -63,6 +64,8 @@ public static class RuntimeSettingsParser
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)
{
@@ -90,7 +93,9 @@ public static class RuntimeSettingsParser
input.MatchPath,
linkSpacing!.Value,
baits!,
hold!.Value),
hold!.Value,
repeatWindow!.Value,
repeatHold!.Value),
errors);
}
@@ -130,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;
}
+3 -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";
@@ -21,7 +23,7 @@ public static class SettingKeys
[MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays];
public static readonly IReadOnlyList<string> HoldMethod =
[DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, DripHeadStartSize, DripMatchPath, DripLinkSpacing, DripBaitPaths, 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);
+29 -1
View File
@@ -13,7 +13,9 @@ public static class FileContent
{
public static readonly IReadOnlyList<FileProfile> Profiles =
[
new("git-drip", "text/plain; charset=utf-8", path => path.Contains("/.git/", StringComparison.Ordinal), GitConfig),
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),
@@ -34,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) =>
@@ -167,6 +174,27 @@ public static class FileContent
}
}
private static IEnumerable<string> Svn(IRandomSource random)
{
yield return "12\n\ndir\n4821\nhttps://svn.example.com/repos/portal/trunk\nhttps://svn.example.com/repos/portal\n2026-03-14T09:21:07.512340Z\n4821\ndeploy\n\n\n\n\n\n\n\n";
while (true)
{
var date = string.Create(CultureInfo.InvariantCulture, $"2026-{random.Next(1, 13):00}-{random.Next(1, 29):00}T{random.Next(0, 24):00}:{random.Next(0, 60):00}:{random.Next(0, 60):00}.{random.Next(0, 1_000_000):000000}Z");
yield return $"{LoremText.Word(random)}-{LoremText.Word(random)}.php\nfile\n\n\n{date}\n{Hex(random, 32)}\n{date}\ndeploy\n{random.Next(200, 90_000)}\n\n\n\n\n";
}
}
private static IEnumerable<string> Mercurial(IRandomSource random)
{
yield return "dotencode\nfncache\ngeneraldelta\nrevlogv1\nsparserevlog\nstore\n";
while (true)
{
yield return $"data/{Pick(random, MazeContent.Roots)}/{LoremText.Word(random)}-{LoremText.Word(random)}.php.i\n";
}
}
private static string Hex(IRandomSource random, int length)
{
var chars = new char[length];
@@ -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");
@@ -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 />
@@ -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"
};
}
@@ -21,4 +21,8 @@ public sealed class HoldMethodModel
public string? BaitPaths { get; set; }
public string? MaxHoldDuration { get; set; }
public string? RepeatWindowDays { get; set; }
public string? RepeatHoldDuration { get; set; }
}
@@ -65,6 +65,12 @@
<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">
@@ -149,7 +155,9 @@
Model.MatchPath,
Model.LinkSpacing,
Model.BaitPaths,
Model.MaxHoldDuration));
Model.MaxHoldDuration,
Model.RepeatWindowDays,
Model.RepeatHoldDuration));
if (result.Settings is null)
{
@@ -181,7 +189,9 @@
MatchPath = drip.MatchPath,
LinkSpacing = drip.LinkSpacing.ToString(CultureInfo.InvariantCulture),
BaitPaths = drip.BaitPaths,
MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
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>
+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": []
}
+114
View File
@@ -1585,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;
}
@@ -18,6 +18,19 @@ public sealed class FileContentTests
[InlineData("/docker-compose.yml", "yaml-drip")]
[InlineData("/backup/db.sql", "sql-drip")]
[InlineData("/.git/config", "git-drip")]
[InlineData("/.git/HEAD", "git-drip")]
[InlineData("/app/.git/logs/HEAD", "git-drip")]
[InlineData("/.git", "git-drip")]
[InlineData("/.gitconfig", "git-drip")]
[InlineData("/.git-credentials", "git-drip")]
[InlineData("/home/.GITCONFIG", "git-drip")]
[InlineData("/.svn/format", "svn-drip")]
[InlineData("/.svn/wc.db", "svn-drip")]
[InlineData("/.svn/entries", "svn-drip")]
[InlineData("/site/.svn", "svn-drip")]
[InlineData("/.hg/requires", "hg-drip")]
[InlineData("/.hg/store/requires", "hg-drip")]
[InlineData("/.hg", "hg-drip")]
[InlineData("/SDK/webLanguage", "hikvision-drip")]
[InlineData("/ISAPI/System/deviceInfo", "hikvision-drip")]
[InlineData("/wp-login.php", "wordpress-drip")]
@@ -29,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)]
@@ -41,6 +57,11 @@ public sealed class FileContentTests
[InlineData("/docker-compose.yml", "version:")]
[InlineData("/dump.sql", "-- MySQL dump")]
[InlineData("/.git/config", "[core]")]
[InlineData("/.git-credentials", "[core]")]
[InlineData("/.svn/entries", "12\n")]
[InlineData("/.svn/wc.db", "12\n")]
[InlineData("/.hg/requires", "dotencode\n")]
[InlineData("/.hg/store/requires", "dotencode\n")]
[InlineData("/SDK/webLanguage", "<?xml")]
[InlineData("/wp-login.php", "<!DOCTYPE html>")]
public void Generates_an_endless_file_that_starts_like_the_real_thing(string path, string start)
@@ -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, "80", "/Backup-2024, /admin-old/x", "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()
@@ -108,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()
{
+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);
}
+41 -2
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]
@@ -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)));
@@ -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) =>
@@ -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, 0, "/trap-a/", 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);
@@ -103,7 +103,7 @@ public sealed class SettingsOverrideTests : IDisposable
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)));
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);
@@ -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();
}