4 Commits
Author SHA1 Message Date
TomandClaude Opus 5.5 1979fd91e9 Prepare changelog for 0.6.0
Build and deploy / build (push) Successful in 1m49s
Release / image (push) Successful in 2m0s
Build and deploy / deploy (push) Successful in 29s
Release / release (push) Successful in 6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:05:05 +01:00
TomandClaude Opus 5.5 119dafa505 Remove the research page, its MCP write tools and token write permission
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:05:05 +01:00
TomandClaude Opus 5.5 7f8a3ae882 Prepare changelog for 0.5.2
Build and deploy / build (push) Successful in 1m41s
Release / image (push) Successful in 2m1s
Build and deploy / deploy (push) Successful in 23s
Release / release (push) Successful in 7s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:29:53 +01:00
TomandClaude Opus 5.5 cbd9830143 Group strategies by base type and rank them by median hold time
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:29:53 +01:00
40 changed files with 572 additions and 1346 deletions

No files matched your search

+27 -1
View File
@@ -6,6 +6,30 @@ All notable changes to Flypaper are documented in this file. The format follows
## [Unreleased] ## [Unreleased]
## [0.6.0] - 2026-11-21
### Removed
- Page „Erkenntnisse“ (`/erkenntnisse`) with lab notebook and idea table, including its navigation entry and
all stored entries and ideas (tables `LabEntries` and `Ideas` are dropped by a migration, without backup).
- MCP: tools `list_entries`, `list_ideas`, `create_entry`, `update_entry`, `create_idea`, `update_idea` and
`set_idea_status`. All MCP tools are read-only again.
- MCP tokens: write permission (switch on the settings page, column „Zugriff“, database column `CanWrite`).
- Markdown rendering (Markdig).
## [0.5.2] - 2026-11-17
### Changed
- Dashboard, Top 10 „Strategien“: strategies are grouped by base type, so `html-drip` with any drip speed
is one row „Endlose Webseite“; the old name `drip` counts as the same. Only `head`, `link` and `repeat` stay
separate rows and show small badges („Schnellstart“, „Links“, „Wiederholer“). The drip parameters moved to the
tooltip and the expanded row.
- Columns are now catches, **median hold time per catch** and total. The bar and the default sort use the median
(rows with fewer than 5 catches are greyed out, marked „wenige Daten“ and listed last).
- Clicking a row filters the catch list on all variants of the group. The catch list, filter chip and
expanded row show name plus badges. Old `?strategie=` links still work.
## [0.5.1] - 2026-11-17 ## [0.5.1] - 2026-11-17
### Changed ### Changed
@@ -184,7 +208,9 @@ First release.
- Unraid Docker template; when started as root, the container hands `/data` to its app user - Unraid Docker template; when started as root, the container hands `/data` to its app user
and drops privileges. and drops privileges.
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.5.1...main [Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.6.0...main
[0.6.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.6.0
[0.5.2]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.2
[0.5.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.1 [0.5.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.1
[0.5.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.0 [0.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.4.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.4.0
-1
View File
@@ -10,7 +10,6 @@
<PackageVersion Include="Microsoft.Extensions.Http" Version="10.0.15" /> <PackageVersion Include="Microsoft.Extensions.Http" Version="10.0.15" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" 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="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="MaxMind.GeoIP2" Version="6.1.0" />
<PackageVersion Include="ModelContextProtocol.AspNetCore" Version="2.4.0" /> <PackageVersion Include="ModelContextProtocol.AspNetCore" Version="2.4.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15" /> <PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15" />
@@ -10,9 +10,11 @@ public sealed record DashboardData(
TimeSpan TotalHoldTime, TimeSpan TotalHoldTime,
IReadOnlyList<TopEntry> TopIps, IReadOnlyList<TopEntry> TopIps,
IReadOnlyList<TopEntry> TopTargets, IReadOnlyList<TopEntry> TopTargets,
IReadOnlyList<TopEntry> TopStrategies, IReadOnlyList<StrategySample> StrategyCatches,
IReadOnlyList<TopEntry> TopCountries, IReadOnlyList<TopEntry> TopCountries,
IReadOnlyList<TopEntry> TopProviders, IReadOnlyList<TopEntry> TopProviders,
IReadOnlyDictionary<string, int> CatchesByCountry); IReadOnlyDictionary<string, int> CatchesByCountry);
public sealed record TopEntry(string Key, int Count, TimeSpan HoldTime, string? Label = null); public sealed record TopEntry(string Key, int Count, TimeSpan HoldTime, string? Label = null, TimeSpan? MedianHold = null);
public sealed record StrategySample(string Strategy, long DurationMs);
@@ -42,7 +42,7 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)), TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)),
await TopAsync(catches.GroupBy(e => e.RemoteIp), ct), await TopAsync(catches.GroupBy(e => e.RemoteIp), ct),
await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct), await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct),
await TopAsync(catches.GroupBy(e => e.Strategy), ct), await catches.Select(e => new StrategySample(e.Strategy, e.DurationMs)).ToListAsync(ct),
countries countries
.Take(TopCount) .Take(TopCount)
.Select(x => new TopEntry(x.Key, x.Count, TimeSpan.FromMilliseconds(x.DurationMs), x.Name)) .Select(x => new TopEntry(x.Key, x.Count, TimeSpan.FromMilliseconds(x.DurationMs), x.Name))
@@ -107,7 +107,19 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
if (filter.Strategy is { } strategy) if (filter.Strategy is { } strategy)
{ {
events = events.Where(e => e.Strategy == strategy); var bases = strategy.Bases;
events = events.Where(e => bases.Any(name => e.Strategy == name || EF.Functions.Like(e.Strategy, name + " %", "\\")));
foreach (var flag in strategy.With)
{
var pattern = $"% {flag} %";
events = events.Where(e => EF.Functions.Like(" " + e.Strategy + " ", pattern, "\\"));
}
foreach (var flag in strategy.Without)
{
var pattern = $"% {flag} %";
events = events.Where(e => !EF.Functions.Like(" " + e.Strategy + " ", pattern, "\\"));
}
} }
if (!string.IsNullOrWhiteSpace(filter.Search)) if (!string.IsNullOrWhiteSpace(filter.Search))
@@ -10,7 +10,7 @@ public sealed record RecentFilter(
long? Asn = null, long? Asn = null,
string? Ip = null, string? Ip = null,
string? Target = null, string? Target = null,
string? Strategy = null, StrategyMatch? Strategy = null,
string? Search = null, string? Search = null,
int Limit = RecentFilter.DefaultLimit, int Limit = RecentFilter.DefaultLimit,
IReadOnlyList<string>? SearchStrategies = null) IReadOnlyList<string>? SearchStrategies = null)
@@ -22,3 +22,5 @@ public sealed record RecentFilter(
public sealed record RecentCatches(IReadOnlyList<TrapEventEntity> Items, int Total, IReadOnlyList<CountryOption> Countries); public sealed record RecentCatches(IReadOnlyList<TrapEventEntity> Items, int Total, IReadOnlyList<CountryOption> Countries);
public sealed record CountryOption(string Code, string? Name); public sealed record CountryOption(string Code, string? Name);
public sealed record StrategyMatch(IReadOnlyList<string> Bases, IReadOnlyList<string> With, IReadOnlyList<string> Without);
@@ -1,41 +0,0 @@
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;
}
@@ -1,33 +0,0 @@
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,6 +11,4 @@ public sealed class McpTokenEntity
public DateTime CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
public DateTime? LastUsedAt { get; set; } public DateTime? LastUsedAt { get; set; }
public bool CanWrite { get; set; }
} }
-22
View File
@@ -14,10 +14,6 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
public DbSet<McpTokenEntity> McpTokens => Set<McpTokenEntity>(); public DbSet<McpTokenEntity> McpTokens => Set<McpTokenEntity>();
public DbSet<LabEntryEntity> LabEntries => Set<LabEntryEntity>();
public DbSet<IdeaEntity> Ideas => Set<IdeaEntity>();
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) => protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>(); configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
@@ -47,23 +43,5 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
mcpToken.Property(e => e.Name).HasMaxLength(100); mcpToken.Property(e => e.Name).HasMaxLength(100);
mcpToken.Property(e => e.TokenHash).HasMaxLength(64); mcpToken.Property(e => e.TokenHash).HasMaxLength(64);
mcpToken.HasIndex(e => e.TokenHash).IsUnique(); 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,7 +3,6 @@ using Flypaper.Storage.Dashboard;
using Flypaper.Storage.Events; using Flypaper.Storage.Events;
using Flypaper.Storage.Maintenance; using Flypaper.Storage.Maintenance;
using Flypaper.Storage.Queries; using Flypaper.Storage.Queries;
using Flypaper.Storage.Research;
using Flypaper.Storage.Settings; using Flypaper.Storage.Settings;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@@ -24,7 +23,6 @@ public static class FlypaperStorageExtensions
builder.Services.AddSingleton<RuntimeSettingsStore>(); builder.Services.AddSingleton<RuntimeSettingsStore>();
builder.Services.AddSingleton<AdminCredentialStore>(); builder.Services.AddSingleton<AdminCredentialStore>();
builder.Services.AddSingleton<McpTokenStore>(); builder.Services.AddSingleton<McpTokenStore>();
builder.Services.AddSingleton<ResearchStore>();
builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName)); builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName));
builder.Services.AddFlypaperStorage(connectionString); builder.Services.AddFlypaperStorage(connectionString);
@@ -0,0 +1,151 @@
// <auto-generated />
using System;
using Flypaper.Storage;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Flypaper.Storage.Migrations
{
[DbContext(typeof(FlypaperDbContext))]
[Migration("20261121100100_RemoveResearch")]
partial class RemoveResearch
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastUsedAt")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("McpTokens");
});
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
{
b.Property<string>("Key")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Key");
b.ToTable("Settings");
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("Asn")
.HasColumnType("INTEGER");
b.Property<long>("BytesSent")
.HasColumnType("INTEGER");
b.Property<string>("City")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("ClientInfo")
.HasMaxLength(2048)
.HasColumnType("TEXT");
b.Property<string>("Country")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("CountryCode")
.HasMaxLength(2)
.HasColumnType("TEXT");
b.Property<long>("DurationMs")
.HasColumnType("INTEGER");
b.Property<DateTime>("EndedAt")
.HasColumnType("TEXT");
b.Property<string>("Outcome")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Protocol")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Provider")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("RemoteIp")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<Guid>("SessionId")
.HasColumnType("TEXT");
b.Property<DateTime>("StartedAt")
.HasColumnType("TEXT");
b.Property<string>("Strategy")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<string>("Target")
.HasMaxLength(2048)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("Asn");
b.HasIndex("CountryCode");
b.HasIndex("RemoteIp");
b.HasIndex("StartedAt");
b.ToTable("TrapEvents");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,82 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class RemoveResearch : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Ideas");
migrationBuilder.DropTable(
name: "LabEntries");
migrationBuilder.DropColumn(
name: "CanWrite",
table: "McpTokens");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "CanWrite",
table: "McpTokens",
type: "INTEGER",
nullable: false,
defaultValue: false);
migrationBuilder.CreateTable(
name: "Ideas",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Commit = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
Efficiency = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Effort = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
ImplementedOn = table.Column<DateTime>(type: "TEXT", nullable: true),
Rationale = table.Column<string>(type: "TEXT", maxLength: 20000, nullable: false),
Status = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Ideas", x => x.Id);
});
migrationBuilder.CreateTable(
name: "LabEntries",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Commit = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
Date = table.Column<DateTime>(type: "TEXT", nullable: false),
Kind = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Strategies = table.Column<string>(type: "TEXT", maxLength: 512, nullable: true),
Text = table.Column<string>(type: "TEXT", maxLength: 20000, nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_LabEntries", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_LabEntries_Date",
table: "LabEntries",
column: "Date");
}
}
}
@@ -17,109 +17,12 @@ namespace Flypaper.Storage.Migrations
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.15"); 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 => modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<bool>("CanWrite")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt") b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
@@ -1,10 +0,0 @@
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;
}
@@ -1,247 +0,0 @@
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); return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct);
} }
public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, bool canWrite = false, CancellationToken ct = default) public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, CancellationToken ct = default)
{ {
await using var db = await dbContextFactory.CreateDbContextAsync(ct); await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CanWrite = canWrite, CreatedAt = timeProvider.GetUtcNow().UtcDateTime }; var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };
db.McpTokens.Add(token); db.McpTokens.Add(token);
await db.SaveChangesAsync(ct); await db.SaveChangesAsync(ct);
return token; return token;
@@ -28,12 +28,6 @@ public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContext
return await db.McpTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct) > 0; 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) public async Task<McpTokenEntity?> UseAsync(string tokenHash, CancellationToken ct = default)
{ {
await using var db = await dbContextFactory.CreateDbContextAsync(ct); await using var db = await dbContextFactory.CreateDbContextAsync(ct);
@@ -4,7 +4,6 @@
<nav class="nav"> <nav class="nav">
<a href="/" class="brand"><span class="brand-mark" aria-hidden="true"></span>Flypaper</a> <a href="/" class="brand"><span class="brand-mark" aria-hidden="true"></span>Flypaper</a>
<NavLink href="/" Match="NavLinkMatch.All">Dashboard</NavLink> <NavLink href="/" Match="NavLinkMatch.All">Dashboard</NavLink>
<NavLink href="/erkenntnisse">Erkenntnisse</NavLink>
<NavLink href="/settings">Einstellungen</NavLink> <NavLink href="/settings">Einstellungen</NavLink>
<form method="post" action="/auth/logout" class="logout"> <form method="post" action="/auth/logout" class="logout">
<AntiforgeryToken /> <AntiforgeryToken />
@@ -2,6 +2,7 @@ using System.Globalization;
using System.Net; using System.Net;
using Flypaper.Core.Models; using Flypaper.Core.Models;
using Flypaper.Storage.Dashboard; using Flypaper.Storage.Dashboard;
using Flypaper.Web.Components.Shared;
namespace Flypaper.Web.Components.Pages.Dashboard; namespace Flypaper.Web.Components.Pages.Dashboard;
@@ -47,7 +48,7 @@ public sealed record DashboardFilter(
Asn(provider) is { } asn ? $"AS{asn.ToString(CultureInfo.InvariantCulture)}" : null, Asn(provider) is { } asn ? $"AS{asn.ToString(CultureInfo.InvariantCulture)}" : null,
IPAddress.TryParse(Clean(ip), out var address) ? address.ToString() : null, IPAddress.TryParse(Clean(ip), out var address) ? address.ToString() : null,
Clean(ziel), Clean(ziel),
Clean(strategie), Clean(strategie) is { } strategy ? StrategyNames.GroupKey(strategy) : null,
Clean(q), Clean(q),
parsedLimit); parsedLimit);
} }
@@ -70,7 +71,7 @@ public sealed record DashboardFilter(
Asn(Provider), Asn(Provider),
Ip, Ip,
Ziel, Ziel,
Strategie, StrategyNames.Group(Strategie),
Q, Q,
Limit); Limit);
@@ -81,7 +81,7 @@
@foreach (var tab in tabs) @foreach (var tab in tabs)
{ {
<div role="tabpanel" id="panel-@tab.Id" aria-labelledby="tab-@tab.Id" tabindex="0" hidden="@(tab != tabs[0])"> <div role="tabpanel" id="panel-@tab.Id" aria-labelledby="tab-@tab.Id" tabindex="0" hidden="@(tab != tabs[0])">
<TopTable KeyLabel="@tab.KeyLabel" Entries="tab.Entries" ShowFlags="tab.ShowFlags" KeyFormatter="tab.KeyFormatter" LabelFormatter="tab.LabelFormatter" TitleFormatter="tab.TitleFormatter" <TopTable KeyLabel="@tab.KeyLabel" Entries="tab.Entries" ShowFlags="tab.ShowFlags" KeyFormatter="tab.KeyFormatter" LabelFormatter="tab.LabelFormatter" TitleFormatter="tab.TitleFormatter" BadgesFormatter="tab.BadgesFormatter"
Href="entry => TopFilter(tab, entry).Href()" IsActive="entry => tab.Current(_filter) == entry.Key" /> Href="entry => TopFilter(tab, entry).Href()" IsActive="entry => tab.Current(_filter) == entry.Key" />
</div> </div>
} }
@@ -199,6 +199,10 @@
<div class="extra extra-md">User-Agent: @(trapEvent.ClientInfo ?? "–")</div> <div class="extra extra-md">User-Agent: @(trapEvent.ClientInfo ?? "–")</div>
<div class="extra extra-all strategy-info"> <div class="extra extra-all strategy-info">
<strong>@strategy.DisplayName</strong> <strong>@strategy.DisplayName</strong>
@foreach (var badge in strategy.Badges)
{
<span class="badge">@badge</span>
}
@if (strategy.Explanation is not null) @if (strategy.Explanation is not null)
{ {
<div>@strategy.Explanation</div> <div>@strategy.Explanation</div>
@@ -213,7 +217,7 @@
<div class="extra extra-sm">Dauer: @duration · Bytes: @bytes</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> <div class="extra extra-xs">Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @OutcomeLabel(trapEvent.Outcome)</div>
</td> </td>
<td class="c-strategy" title="@strategy.Tooltip">@strategy.DisplayName</td> <td class="c-strategy" title="@strategy.Tooltip">@strategy.DisplayName@foreach (var badge in strategy.Badges){<span class="badge">@badge</span>}</td>
<td class="c-agent" title="@trapEvent.ClientInfo">@trapEvent.ClientInfo</td> <td class="c-agent" title="@trapEvent.ClientInfo">@trapEvent.ClientInfo</td>
<td class="c-duration num">@duration</td> <td class="c-duration num">@duration</td>
<td class="c-bytes num">@bytes</td> <td class="c-bytes num">@bytes</td>
@@ -282,7 +286,7 @@
new("providers", "Provider", "Provider", data.TopProviders, f => f.Provider, (f, key) => f with { Provider = key }), 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("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 }, KeyFormatter: StrategyNames.Summary, LabelFormatter: (key, _) => StrategyNames.Display(key), TitleFormatter: key => StrategyNames.Describe(key).Tooltip) new("strategies", "Strategien", "Strategie", StrategyNames.Rank(data.StrategyCatches, 10), f => f.Strategie, (f, key) => f with { Strategie = key }, KeyFormatter: _ => "", LabelFormatter: (key, _) => StrategyNames.Display(key), TitleFormatter: key => StrategyNames.Describe(key).Tooltip, BadgesFormatter: key => StrategyNames.Describe(key).Badges)
]; ];
private DashboardFilter TopFilter(TopTab tab, TopEntry entry) => private DashboardFilter TopFilter(TopTab tab, TopEntry entry) =>
@@ -326,7 +330,8 @@
if (_filter.Strategie is { } strategie) if (_filter.Strategie is { } strategie)
{ {
yield return ($"Strategie: {StrategyNames.Display(strategie)}", reset with { Strategie = null }); var badges = StrategyNames.Describe(strategie).Badges;
yield return ($"Strategie: {StrategyNames.Display(strategie)}{(badges.Count == 0 ? "" : $" ({string.Join(", ", badges)})")}", reset with { Strategie = null });
} }
if (_filter.Q is { } q) if (_filter.Q is { } q)
@@ -357,5 +362,6 @@
bool ShowFlags = false, bool ShowFlags = false,
Func<string?, string?>? KeyFormatter = null, Func<string?, string?>? KeyFormatter = null,
Func<string?, string?, string?>? LabelFormatter = null, Func<string?, string?, string?>? LabelFormatter = null,
Func<string?, string?>? TitleFormatter = null); Func<string?, string?>? TitleFormatter = null,
Func<string?, IReadOnlyList<string>>? BadgesFormatter = null);
} }
@@ -1,25 +1,40 @@
@using System.Globalization @using System.Globalization
@using Flypaper.Storage.Dashboard @using Flypaper.Storage.Dashboard
@using Flypaper.Web.Components.Shared
@{
var byMedian = Entries.Any(entry => entry.MedianHold is not null);
var barMax = byMedian
? Entries.Where(entry => entry.Count >= StrategyNames.MinCatches).Select(entry => entry.MedianHold!.Value.TotalMilliseconds).DefaultIfEmpty(0).Max()
: Entries.Count == 0 ? 0 : Entries[0].Count;
}
@if (Entries.Count == 0) @if (Entries.Count == 0)
{ {
<p class="empty">Noch keine Einträge.</p> <p class="empty">Noch keine Einträge.</p>
} }
else else
{ {
<table class="top-table"> <table class="top-table @(byMedian ? "by-median" : null)">
<colgroup> <colgroup>
<col /> <col />
<col class="share" /> <col class="share" />
<col class="count" /> <col class="count" />
<col class="hold" /> @if (byMedian)
{
<col class="hold" />
}
<col class="hold sum" />
</colgroup> </colgroup>
<thead> <thead>
<tr> <tr>
<th>@KeyLabel</th> <th>@KeyLabel</th>
<th><span class="sr-only">Anteil</span></th> <th><span class="sr-only">Anteil</span></th>
<th class="num">Fänge</th> <th class="num">Fänge</th>
<th class="num">Haltezeit</th> @if (byMedian)
{
<th class="num" title="Mittlere Haltezeit pro Fang (Median): Einzelne Dauerhalter verfälschen sie nicht">Median</th>
}
<th class="num sum">@(byMedian ? "Summe" : "Haltezeit")</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -27,10 +42,18 @@ else
{ {
var key = KeyFormatter?.Invoke(entry.Key) ?? entry.Key; var key = KeyFormatter?.Invoke(entry.Key) ?? entry.Key;
var label = LabelFormatter is null ? entry.Label : LabelFormatter(entry.Key, entry.Label); var label = LabelFormatter is null ? entry.Label : LabelFormatter(entry.Key, entry.Label);
var share = (entry.Count * 100.0 / Entries[0].Count).ToString("0.#", CultureInfo.InvariantCulture); var value = byMedian ? entry.MedianHold!.Value.TotalMilliseconds : entry.Count;
var share = (barMax == 0 ? 0 : Math.Min(100, value * 100.0 / barMax)).ToString("0.#", CultureInfo.InvariantCulture);
var sparse = byMedian && entry.Count < StrategyNames.MinCatches;
var badges = BadgesFormatter?.Invoke(entry.Key) ?? [];
var active = IsActive(entry); var active = IsActive(entry);
var title = TitleFormatter?.Invoke(entry.Key) ?? (label is null ? key : $"{label} · {key}"); var title = TitleFormatter?.Invoke(entry.Key) ?? (label is null ? key : $"{label} · {key}");
<tr data-href="@Href(entry)" class="@(active ? "active" : null)"> if (sparse)
{
title += $"\nNur {entry.Count} {(entry.Count == 1 ? "Fang" : "Fänge")}: wenig aussagekräftig";
}
<tr data-href="@Href(entry)" class="@(active ? "active" : null) @(sparse ? "sparse" : null)">
<td class="clip" title="@title"> <td class="clip" title="@title">
<a href="@Href(entry)" aria-current="@(active ? "true" : null)" title="@(active ? $"Filter {title} entfernen" : $"Fänge filtern: {title}")"> <a href="@Href(entry)" aria-current="@(active ? "true" : null)" title="@(active ? $"Filter {title} entfernen" : $"Fänge filtern: {title}")">
@if (ShowFlags) @if (ShowFlags)
@@ -40,6 +63,14 @@ else
@if (label is not null) @if (label is not null)
{ {
<span class="top-label">@label</span> <span class="top-label">@label</span>
@foreach (var badge in badges)
{
<span class="badge">@badge</span>
}
@if (sparse)
{
<span class="badge sparse-note">wenige Daten</span>
}
@if (key.Length > 0) @if (key.Length > 0)
{ {
<span class="top-key mono">@key</span> <span class="top-key mono">@key</span>
@@ -53,11 +84,19 @@ else
</td> </td>
<td><span class="share-bar" style="--share: @(share)%"></span></td> <td><span class="share-bar" style="--share: @(share)%"></span></td>
<td class="num">@Formatting.Number(entry.Count)</td> <td class="num">@Formatting.Number(entry.Count)</td>
<td class="num">@Formatting.Duration(entry.HoldTime)</td> @if (byMedian)
{
<td class="num">@Formatting.Duration(entry.MedianHold!.Value)</td>
}
<td class="num sum">@Formatting.Duration(entry.HoldTime)</td>
</tr> </tr>
} }
</tbody> </tbody>
</table> </table>
@if (byMedian)
{
<p class="top-note">Balken = Median Haltezeit pro Fang. Unter @StrategyNames.MinCatches Fängen wenig aussagekräftig, diese Zeilen stehen am Ende.</p>
}
} }
@code { @code {
@@ -73,6 +112,8 @@ else
[Parameter] public Func<string?, string?>? TitleFormatter { get; set; } [Parameter] public Func<string?, string?>? TitleFormatter { get; set; }
[Parameter] public Func<string?, IReadOnlyList<string>>? BadgesFormatter { get; set; }
[Parameter, EditorRequired] public required Func<TopEntry, string> Href { get; set; } [Parameter, EditorRequired] public required Func<TopEntry, string> Href { get; set; }
[Parameter, EditorRequired] public required Func<TopEntry, bool> IsActive { get; set; } [Parameter, EditorRequired] public required Func<TopEntry, bool> IsActive { get; set; }
@@ -1,58 +0,0 @@
@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"
};
}
@@ -1,139 +0,0 @@
@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 title="@StrategyNames.Describe(strategy).Tooltip">@StrategyNames.Display(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"
};
}
@@ -5,19 +5,11 @@
@inject McpTokenStore Store @inject McpTokenStore Store
@inject NavigationManager Navigation @inject NavigationManager Navigation
<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."> <SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol Nur im LAN.">
@if (Revoked == "revoked") @if (Revoked == "revoked")
{ {
<Notice>Token widerrufen.</Notice> <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) @if (_newToken is not null)
{ {
@@ -45,7 +37,6 @@
<th>Name</th> <th>Name</th>
<th>Erstellt</th> <th>Erstellt</th>
<th>Zuletzt genutzt</th> <th>Zuletzt genutzt</th>
<th>Zugriff</th>
<th></th> <th></th>
</tr> </tr>
</thead> </thead>
@@ -56,14 +47,6 @@
<td>@token.Name</td> <td>@token.Name</td>
<td class="nowrap">@token.CreatedAt.ToLocalTime().ToString("dd.MM.yyyy HH:mm")</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">@(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"> <td class="num">
<form method="post" action="/mcp-tokens/@token.Id/revoke" onsubmit="return confirm('Token „@token.Name“ widerrufen?')"> <form method="post" action="/mcp-tokens/@token.Id/revoke" onsubmit="return confirm('Token „@token.Name“ widerrufen?')">
<AntiforgeryToken /> <AntiforgeryToken />
@@ -89,10 +72,6 @@
<span class="field-error">@nameError</span> <span class="field-error">@nameError</span>
} }
</div> </div>
<label class="inline-check">
<InputCheckbox @bind-Value="Model!.CanWrite" />
<span>Mit Schreibrecht</span>
</label>
<button type="submit">Token erzeugen</button> <button type="submit">Token erzeugen</button>
</EditForm> </EditForm>
</SettingsSection> </SettingsSection>
@@ -124,10 +103,9 @@
return; return;
} }
_newToken = await Tokens.CreateAsync(name, Model.CanWrite); _newToken = await Tokens.CreateAsync(name);
_newTokenName = name; _newTokenName = name;
Model.Name = null; Model.Name = null;
Model.CanWrite = false;
_tokens = await Store.ListAsync(); _tokens = await Store.ListAsync();
} }
} }
@@ -3,6 +3,4 @@ namespace Flypaper.Web.Components.Pages.Settings;
public sealed class McpTokenModel public sealed class McpTokenModel
{ {
public string? Name { get; set; } public string? Name { get; set; }
public bool CanWrite { get; set; }
} }
@@ -1,57 +0,0 @@
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,10 +1,15 @@
using System.Globalization; using System.Globalization;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Flypaper.Storage.Dashboard;
namespace Flypaper.Web.Components.Shared; namespace Flypaper.Web.Components.Shared;
public sealed record StrategyInfo(string Raw, string BaseName, string DisplayName, string? Explanation, IReadOnlyList<string> Details) public sealed record StrategyInfo(string Raw, string BaseName, string DisplayName, string? Explanation, IReadOnlyList<string> Details, IReadOnlyList<string> Flags)
{ {
public string GroupKey => string.Join(' ', [BaseName, .. Flags]);
public IReadOnlyList<string> Badges => Flags.Select(StrategyNames.BadgeLabel).ToList();
public string Tooltip public string Tooltip
{ {
get get
@@ -44,16 +49,45 @@ public static partial class StrategyNames
["robots-bait"] = ("Köder aus der robots.txt", "Ein Pfad, der in der robots.txt als verboten steht, aber ins Link-Labyrinth führt. Wer dort landet, hat das Verbot gelesen und ignoriert. Er wird mindestens 24 Stunden festgehalten.") ["robots-bait"] = ("Köder aus der robots.txt", "Ein Pfad, der in der robots.txt als verboten steht, aber ins Link-Labyrinth führt. Wer dort landet, hat das Verbot gelesen und ignoriert. Er wird mindestens 24 Stunden festgehalten.")
}; };
private static readonly Dictionary<string, string> Aliases = new(StringComparer.Ordinal)
{
["drip"] = "html-drip"
};
private static readonly string[] VariantFlags = ["head", "link", "repeat"];
private static readonly HashSet<string> LinkedByDesign = new(StringComparer.Ordinal) { "maze-drip", "index-drip", "robots-bait" };
public const int MinCatches = 5;
public static string BadgeLabel(string flag) => flag switch
{
"head" => "Schnellstart",
"link" => "Links",
"repeat" => "Wiederholer",
_ => flag
};
public static StrategyInfo Describe(string? strategy) public static StrategyInfo Describe(string? strategy)
{ {
var raw = strategy?.Trim() ?? ""; var raw = strategy?.Trim() ?? "";
var tokens = raw.Split(' ', StringSplitOptions.RemoveEmptyEntries); var tokens = raw.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length == 0) if (tokens.Length == 0)
{ {
return new StrategyInfo(raw, raw, raw, null, []); return new StrategyInfo(raw, raw, raw, null, [], []);
} }
var baseName = Aliases.GetValueOrDefault(tokens[0], tokens[0]);
var flags = VariantFlags
.Where(flag => tokens.Skip(1).Contains(flag) && !(flag == "link" && LinkedByDesign.Contains(baseName)))
.ToList();
var details = new List<string>(); var details = new List<string>();
if (baseName != tokens[0])
{
details.Add($"früherer Name von {Known[baseName].Name}");
}
for (var i = 1; i < tokens.Length; i++) for (var i = 1; i < tokens.Length; i++)
{ {
var token = tokens[i]; var token = tokens[i];
@@ -71,6 +105,10 @@ public static partial class StrategyNames
: $"alle {bytes} Byte ein Link"); : $"alle {bytes} Byte ein Link");
i++; i++;
} }
else if (token is "head" or "link")
{
details.Add(token == "head" ? "schneller Start: erste Bytes sofort" : "enthält Links");
}
else if (token == "repeat") else if (token == "repeat")
{ {
details.Add("Wiederholer: darf länger festgehalten werden"); details.Add("Wiederholer: darf länger festgehalten werden");
@@ -81,22 +119,58 @@ public static partial class StrategyNames
} }
} }
return Known.TryGetValue(tokens[0], out var known) return Known.TryGetValue(baseName, out var known)
? new StrategyInfo(raw, tokens[0], known.Name, known.Explanation, details) ? new StrategyInfo(raw, baseName, known.Name, known.Explanation, details, flags)
: new StrategyInfo(raw, tokens[0], tokens[0], null, details); : new StrategyInfo(raw, baseName, baseName, null, details, flags);
} }
public static string Display(string? strategy) => Describe(strategy).DisplayName; public static string Display(string? strategy) => Describe(strategy).DisplayName;
public static string Summary(string? strategy) => public static string GroupKey(string? strategy) => Describe(strategy).GroupKey;
string.Join(" · ", Describe(strategy).Details.Where(detail => detail.StartsWith("tröpfelt", StringComparison.Ordinal) || detail.StartsWith("Wiederholer", StringComparison.Ordinal)).Select(detail => detail.Split(':')[0]));
public static StrategyMatch? Group(string? strategy)
{
var info = Describe(strategy);
if (info.BaseName.Length == 0)
{
return null;
}
var bases = Aliases.Where(pair => pair.Value == info.BaseName).Select(pair => pair.Key).Prepend(info.BaseName).ToList();
var variableFlags = VariantFlags.Where(flag => !(flag == "link" && LinkedByDesign.Contains(info.BaseName)));
return new StrategyMatch(bases, info.Flags, variableFlags.Except(info.Flags).ToList());
}
public static IReadOnlyList<TopEntry> Rank(IEnumerable<StrategySample> samples, int take)
{
var groups = samples
.GroupBy(sample => GroupKey(sample.Strategy))
.Select(group =>
{
var durations = group.Select(sample => sample.DurationMs).Order().ToList();
var middle = durations.Count / 2;
var median = durations.Count % 2 == 1 ? durations[middle] : (durations[middle - 1] + durations[middle]) / 2d;
return new TopEntry(group.Key, durations.Count, TimeSpan.FromMilliseconds(durations.Sum()), MedianHold: TimeSpan.FromMilliseconds(median));
});
return groups
.OrderBy(entry => entry.Count < MinCatches)
.ThenByDescending(entry => entry.MedianHold)
.ThenByDescending(entry => entry.Count)
.Take(take)
.ToList();
}
public static IReadOnlyList<string> Matching(string? search) public static IReadOnlyList<string> Matching(string? search)
{ {
var term = search?.Trim(); var term = search?.Trim();
return string.IsNullOrEmpty(term) if (string.IsNullOrEmpty(term))
? [] {
: Known.Where(pair => pair.Value.Name.Contains(term, StringComparison.CurrentCultureIgnoreCase)).Select(pair => pair.Key).ToList(); return [];
}
var keys = Known.Where(pair => pair.Value.Name.Contains(term, StringComparison.CurrentCultureIgnoreCase)).Select(pair => pair.Key).ToList();
return [.. keys, .. Aliases.Where(pair => keys.Contains(pair.Value)).Select(pair => pair.Key)];
} }
private static string Range(string min, string max) => min == max ? Number(min) : $"{Number(min)}–{Number(max)}"; private static string Range(string min, string max) => min == max ? Number(min) : $"{Number(min)}–{Number(max)}";
-1
View File
@@ -10,7 +10,6 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Markdig" />
<PackageReference Include="ModelContextProtocol.AspNetCore" /> <PackageReference Include="ModelContextProtocol.AspNetCore" />
</ItemGroup> </ItemGroup>
+1 -42
View File
@@ -1,4 +1,3 @@
using System.Security.Claims;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using Flypaper.Storage.Settings; using Flypaper.Storage.Settings;
@@ -19,9 +18,7 @@ public static class McpExtensions
"Flypaper is an HTTP tarpit. Scanning bots that probe a server (e.g. for /.env or /wp-login.php) are " + "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 " + "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 " + "stored with its time, client IP, country, network provider (ASN), requested URL, user agent, duration " +
"and bytes sent. Most tools only read that data; times are ISO 8601 UTC, durations in seconds. The tools " + "and bytes sent. All tools only read that data; times are ISO 8601 UTC, durations in seconds.";
"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) private static readonly JsonSerializerOptions ToolJsonOptions = new(McpJsonUtilities.DefaultOptions)
{ {
@@ -47,44 +44,20 @@ public static class McpExtensions
}) })
.WithHttpTransport(options => options.Stateless = true) .WithHttpTransport(options => options.Stateless = true)
.WithTools<FlypaperTools>(ToolJsonOptions) .WithTools<FlypaperTools>(ToolJsonOptions)
.WithTools<ResearchTools>(ToolJsonOptions)
.WithRequestFilters(filters => .WithRequestFilters(filters =>
{ {
filters.AddListToolsFilter(HideWriteTools);
filters.AddCallToolFilter(CheckCall); filters.AddCallToolFilter(CheckCall);
}); });
return services; 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) => private static McpRequestHandler<CallToolRequestParams, CallToolResult> CheckCall(McpRequestHandler<CallToolRequestParams, CallToolResult> next) =>
async (context, ct) => async (context, ct) =>
{ {
var tool = context.Params?.Name; var tool = context.Params?.Name;
var logger = context.Services?.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(FlypaperTools)); 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 if (context.MatchedPrimitive is McpServerTool matched
&& McpArgumentCheck.FindProblem(matched.ProtocolTool.InputSchema, context.Params?.Arguments?.AsReadOnly()) is { } problem) && McpArgumentCheck.FindProblem(matched.ProtocolTool.InputSchema, context.Params?.Arguments?.AsReadOnly()) is { } problem)
{ {
@@ -103,8 +76,6 @@ public static class McpExtensions
} }
}; };
private static bool CanWrite(ClaimsPrincipal? user) => user?.HasClaim(McpTokenAuthenticationHandler.WriteClaim, "true") == true;
private static CallToolResult InvalidArguments(string? tool, string message) => new() private static CallToolResult InvalidArguments(string? tool, string message) => new()
{ {
IsError = true, IsError = true,
@@ -126,18 +97,6 @@ public static class McpExtensions
return Results.LocalRedirect("/settings?mcp=revoked#mcp"); 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; return app;
} }
} }
-27
View File
@@ -50,30 +50,3 @@ public sealed record IpLookupResult(
DateTime? LastSeen, DateTime? LastSeen,
IReadOnlyList<CatchItem> Events, IReadOnlyList<CatchItem> Events,
int EventsOmitted); 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,8 +13,6 @@ public sealed class McpTokenAuthenticationHandler(
{ {
public const string SchemeName = "McpToken"; public const string SchemeName = "McpToken";
public const string WriteClaim = "mcp:write";
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{ {
var header = Request.Headers.Authorization.ToString(); var header = Request.Headers.Authorization.ToString();
@@ -23,17 +21,12 @@ public sealed class McpTokenAuthenticationHandler(
return AuthenticateResult.NoResult(); return AuthenticateResult.NoResult();
} }
if (await tokens.AuthenticateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted) is not { } access) if (!await tokens.AuthenticateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted))
{ {
return AuthenticateResult.Fail("Invalid MCP token."); return AuthenticateResult.Fail("Invalid MCP token.");
} }
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "mcp")], SchemeName); 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)); return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName));
} }
+6 -14
View File
@@ -6,41 +6,33 @@ using Microsoft.Extensions.Options;
namespace Flypaper.Web.Mcp; namespace Flypaper.Web.Mcp;
public enum McpAccess
{
Read,
Write
}
public sealed class McpTokenService(McpTokenStore store, IOptions<McpOptions> options) public sealed class McpTokenService(McpTokenStore store, IOptions<McpOptions> options)
{ {
private const string Prefix = "fpm_"; private const string Prefix = "fpm_";
public bool UsesEnvironmentToken => !string.IsNullOrEmpty(options.Value.Token); public bool UsesEnvironmentToken => !string.IsNullOrEmpty(options.Value.Token);
public async Task<string> CreateAsync(string name, bool canWrite = false, CancellationToken ct = default) public async Task<string> CreateAsync(string name, CancellationToken ct = default)
{ {
var token = Prefix + WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32)); var token = Prefix + WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
await store.CreateAsync(name, Hash(token), canWrite, ct); await store.CreateAsync(name, Hash(token), ct);
return token; return token;
} }
public async Task<McpAccess?> AuthenticateAsync(string? token, CancellationToken ct = default) public async Task<bool> AuthenticateAsync(string? token, CancellationToken ct = default)
{ {
if (string.IsNullOrEmpty(token)) if (string.IsNullOrEmpty(token))
{ {
return null; return false;
} }
if (UsesEnvironmentToken if (UsesEnvironmentToken
&& CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(token)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Value.Token!)))) && CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(token)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Value.Token!))))
{ {
return McpAccess.Read; return true;
} }
return await store.UseAsync(Hash(token), ct) is { } stored return await store.UseAsync(Hash(token), ct) is not null;
? stored.CanWrite ? McpAccess.Write : McpAccess.Read
: null;
} }
public static string Hash(string token) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token))); public static string Hash(string token) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
-188
View File
@@ -1,188 +0,0 @@
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);
}
+39 -93
View File
@@ -266,6 +266,33 @@ code {
font-size: 12px; font-size: 12px;
} }
.badge {
display: inline-block;
margin-left: 6px;
padding: 0 6px;
border-radius: 999px;
background: color-mix(in srgb, var(--text) 8%, transparent);
color: var(--muted);
font-size: 11px;
line-height: 17px;
white-space: nowrap;
vertical-align: 1px;
}
.top-table tr.sparse td {
opacity: 0.55;
}
.top-note {
margin: 8px 0 0;
color: var(--muted);
font-size: 12px;
}
.top-table.by-median .count {
width: 52px;
}
.top-table tr[data-href] { .top-table tr[data-href] {
cursor: pointer; cursor: pointer;
} }
@@ -1017,6 +1044,18 @@ button.danger {
width: 84px; width: 84px;
} }
.top-table.by-median .sum {
display: none;
}
.top-table.by-median .count {
width: 48px;
}
.top-table.by-median .clip {
white-space: normal;
}
.nav .brand { .nav .brand {
margin-right: 4px; margin-right: 4px;
font-size: 0; font-size: 0;
@@ -1590,10 +1629,6 @@ button.danger-text {
white-space: nowrap; white-space: nowrap;
} }
.table-scroll {
overflow-x: auto;
}
.chips a.chip { .chips a.chip {
padding: 3px 10px; padding: 3px 10px;
border-color: var(--border); border-color: var(--border);
@@ -1609,95 +1644,6 @@ button.danger-text {
background: color-mix(in srgb, var(--accent) 10%, transparent); 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 { .inline-check {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
+2 -41
View File
@@ -62,7 +62,7 @@ public sealed class McpEndpointTests : IDisposable
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token))); var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
var listed = tools.GetProperty("result").GetProperty("tools").EnumerateArray().ToList(); var listed = tools.GetProperty("result").GetProperty("tools").EnumerateArray().ToList();
listed.Select(t => t.GetProperty("name").GetString()) listed.Select(t => t.GetProperty("name").GetString())
.ShouldBe(["get_stats", "list_catches", "list_entries", "list_ideas", "longest_catches", "lookup_ip", "top"], ignoreOrder: true); .ShouldBe(["get_stats", "list_catches", "longest_catches", "lookup_ip", "top"], ignoreOrder: true);
listed.ShouldAllBe(t => t.GetProperty("annotations").GetProperty("readOnlyHint").GetBoolean()); listed.ShouldAllBe(t => t.GetProperty("annotations").GetProperty("readOnlyHint").GetBoolean());
listed.Where(t => !t.TryGetProperty("outputSchema", out var schema) || schema.ValueKind != JsonValueKind.Object).ShouldBeEmpty(); listed.Where(t => !t.TryGetProperty("outputSchema", out var schema) || schema.ValueKind != JsonValueKind.Object).ShouldBeEmpty();
@@ -87,11 +87,7 @@ public sealed class McpEndpointTests : IDisposable
{ "top", """{"dimension":"user_agents","period":"all"}""" }, { "top", """{"dimension":"user_agents","period":"all"}""" },
{ "longest_catches", """{"period":"all"}""" }, { "longest_catches", """{"period":"all"}""" },
{ "lookup_ip", """{"ip":"203.0.113.9"}""" }, { "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] [Theory]
@@ -138,41 +134,6 @@ public sealed class McpEndpointTests : IDisposable
result.GetProperty("content")[0].GetProperty("text").GetString().ShouldNotBeNull().ShouldContain(expected, Case.Sensitive); 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) private static async Task<Dictionary<string, JsonElement>> OutputSchemasAsync(HttpClient client, string token)
{ {
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", 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"); var token = await service.CreateAsync("Claude Desktop");
token.Length.ShouldBeGreaterThan(40); token.Length.ShouldBeGreaterThan(40);
(await service.AuthenticateAsync(token)).ShouldBe(McpAccess.Read); (await service.AuthenticateAsync(token)).ShouldBeTrue();
var stored = (await _store.ListAsync()).ShouldHaveSingleItem(); var stored = (await _store.ListAsync()).ShouldHaveSingleItem();
stored.Name.ShouldBe("Claude Desktop"); stored.Name.ShouldBe("Claude Desktop");
stored.TokenHash.ShouldBe(McpTokenService.Hash(token)); stored.TokenHash.ShouldBe(McpTokenService.Hash(token));
@@ -35,12 +35,12 @@ public sealed class McpTokenServiceTests : IDisposable
var service = Create(environmentToken: null); var service = Create(environmentToken: null);
var token = await service.CreateAsync("test"); var token = await service.CreateAsync("test");
(await service.AuthenticateAsync(null)).ShouldBeNull(); (await service.AuthenticateAsync(null)).ShouldBeFalse();
(await service.AuthenticateAsync("")).ShouldBeNull(); (await service.AuthenticateAsync("")).ShouldBeFalse();
(await service.AuthenticateAsync(token + "x")).ShouldBeNull(); (await service.AuthenticateAsync(token + "x")).ShouldBeFalse();
(await _store.RevokeAsync((await _store.ListAsync())[0].Id)).ShouldBeTrue(); (await _store.RevokeAsync((await _store.ListAsync())[0].Id)).ShouldBeTrue();
(await service.AuthenticateAsync(token)).ShouldBeNull(); (await service.AuthenticateAsync(token)).ShouldBeFalse();
} }
[Fact] [Fact]
@@ -50,24 +50,9 @@ public sealed class McpTokenServiceTests : IDisposable
var stored = await service.CreateAsync("test"); var stored = await service.CreateAsync("test");
service.UsesEnvironmentToken.ShouldBeTrue(); service.UsesEnvironmentToken.ShouldBeTrue();
(await service.AuthenticateAsync("fixed-token-from-environment")).ShouldBe(McpAccess.Read); (await service.AuthenticateAsync("fixed-token-from-environment")).ShouldBeTrue();
(await service.AuthenticateAsync(stored)).ShouldBe(McpAccess.Read); (await service.AuthenticateAsync(stored)).ShouldBeTrue();
(await service.AuthenticateAsync("fixed-token")).ShouldBeNull(); (await service.AuthenticateAsync("fixed-token")).ShouldBeFalse();
}
[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) => private McpTokenService Create(string? environmentToken) =>
@@ -1,4 +1,7 @@
using System.Net;
using Flypaper.Core.Models; using Flypaper.Core.Models;
using Flypaper.Storage.Entities;
using Flypaper.Web.Components.Shared;
using Flypaper.Storage.Dashboard; using Flypaper.Storage.Dashboard;
using Flypaper.Tests.Fakes; using Flypaper.Tests.Fakes;
using Flypaper.Tests.Mcp; using Flypaper.Tests.Mcp;
@@ -47,19 +50,42 @@ public sealed class RecentCatchesTests : IDisposable
[Fact] [Fact]
public async Task Matches_strategy_exactly() public async Task Matches_strategy_exactly()
{ {
var recent = await _queries.GetRecentAsync(new RecentFilter(Strategy: "env-drip")); var recent = await _queries.GetRecentAsync(new RecentFilter(Strategy: StrategyNames.Group("env-drip")));
recent.Total.ShouldBe(2); recent.Total.ShouldBe(2);
recent.Items.ShouldAllBe(e => e.Strategy == "env-drip"); recent.Items.ShouldAllBe(e => e.Strategy == "env-drip");
} }
[Fact] [Fact]
public async Task Dashboard_ranks_strategies_among_catches() public async Task Dashboard_lists_strategy_durations_among_catches()
{ {
var data = await _queries.GetAsync(); var data = await _queries.GetAsync();
data.TopStrategies.Select(s => (s.Key, s.Count)).ShouldBe([("html-drip", 4), ("env-drip", 1)]); data.StrategyCatches.Count.ShouldBe(5);
data.TopStrategies[1].HoldTime.ShouldBe(TimeSpan.FromHours(1)); data.StrategyCatches.Count(s => s.Strategy == "env-drip").ShouldBe(1);
data.StrategyCatches.Single(s => s.Strategy == "env-drip").DurationMs.ShouldBe(3_600_000);
}
[Fact]
public async Task Strategy_group_matches_all_variants_of_the_base_type_and_its_old_name()
{
await using (var db = _data.Factory.CreateDbContext())
{
foreach (var strategy in new[] { "drip", "html-drip 50-500ms 1-640B", "html-drip 5-20ms 1-64B head 1024B", "html-drip 50-500ms 1-1024B repeat", "html-drip 50-500ms 1-64B head 1024B repeat" })
{
db.TrapEvents.Add(TrapEventEntity.From(new TrapEvent(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("192.0.2.1"), strategy, McpTestData.Now, McpTestData.Now, 0, TrapOutcome.ClientAborted, null, null)));
}
await db.SaveChangesAsync();
}
async Task<IReadOnlyList<string>> Find(string group) =>
(await _queries.GetRecentAsync(new RecentFilter(Strategy: StrategyNames.Group(group)))).Items.Select(e => e.Strategy).OrderBy(s => s).ToList();
(await Find("html-drip")).Where(s => s != "html-drip").ShouldBe(["drip", "html-drip 50-500ms 1-640B"]);
(await Find("html-drip head")).ShouldBe(["html-drip 5-20ms 1-64B head 1024B"]);
(await Find("html-drip repeat")).ShouldBe(["html-drip 50-500ms 1-1024B repeat"]);
(await Find("html-drip head repeat")).ShouldBe(["html-drip 50-500ms 1-64B head 1024B repeat"]);
} }
[Theory] [Theory]
@@ -1,79 +0,0 @@
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();
}
@@ -13,7 +13,11 @@ public sealed class DashboardFilterTests
var filter = DashboardFilter.Parse("24h", "Abgelehnt", "hk", "as4134", " 203.0.113.9 ", "GET /.env", " env-drip ", " 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", "env-drip", "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)); var recent = filter.ToRecentFilter();
recent.ShouldBe(new RecentFilter(TimeSpan.FromHours(24), TrapOutcome.Rejected, "HK", 4134, "203.0.113.9", "GET /.env", recent.Strategy, "wp", 100));
recent.Strategy!.Bases.ShouldBe(["env-drip"]);
recent.Strategy.With.ShouldBeEmpty();
recent.Strategy.Without.ShouldBe(["head", "link", "repeat"]);
} }
[Theory] [Theory]
@@ -44,8 +48,8 @@ public sealed class DashboardFilterTests
public void Builds_links_without_defaults_and_with_escaping() public void Builds_links_without_defaults_and_with_escaping()
{ {
new DashboardFilter().Href().ShouldBe("/#faenge"); new DashboardFilter().Href().ShouldBe("/#faenge");
new DashboardFilter(Land: "CN", Ziel: "GET example.com/a&b", Strategie: "html-drip 50-500ms 1-1024B", Limit: 100).Href("f50") new DashboardFilter(Land: "CN", Ziel: "GET example.com/a&b", Strategie: "html-drip head", Limit: 100).Href("f50")
.ShouldBe("/?land=CN&ziel=GET%20example.com%2Fa%26b&strategie=html-drip%2050-500ms%201-1024B&limit=100#f50"); .ShouldBe("/?land=CN&ziel=GET%20example.com%2Fa%26b&strategie=html-drip%20head&limit=100#f50");
} }
[Fact] [Fact]
@@ -58,6 +62,13 @@ public sealed class DashboardFilterTests
.ShouldBe(filter); .ShouldBe(filter);
} }
[Theory]
[InlineData("html-drip 50-500ms 1-1024B", "html-drip")]
[InlineData("drip", "html-drip")]
[InlineData("html-drip 50-500ms 1-64B head 1024B", "html-drip head")]
public void Normalizes_strategy_links_to_the_group(string strategy, string expected) =>
DashboardFilter.Parse(null, null, null, null, null, null, strategy, null, null).Strategie.ShouldBe(expected);
[Fact] [Fact]
public void Doubles_the_limit_up_to_the_maximum() public void Doubles_the_limit_up_to_the_maximum()
{ {
@@ -1,50 +0,0 @@
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();
}
@@ -1,4 +1,5 @@
using Flypaper.Core.Strategies; using Flypaper.Core.Strategies;
using Flypaper.Storage.Dashboard;
using Flypaper.Web.Components.Shared; using Flypaper.Web.Components.Shared;
using Shouldly; using Shouldly;
@@ -63,4 +64,44 @@ public sealed class StrategyNamesTests
StrategyNames.Matching("").ShouldBeEmpty(); StrategyNames.Matching("").ShouldBeEmpty();
StrategyNames.Matching("nichts").ShouldBeEmpty(); StrategyNames.Matching("nichts").ShouldBeEmpty();
} }
[Fact]
public void Groups_variants_by_base_type_and_shows_only_content_differences_as_badges()
{
StrategyNames.Describe("html-drip 50-500ms 1-1024B").GroupKey.ShouldBe("html-drip");
StrategyNames.Describe("html-drip 50-500ms 1-640B").GroupKey.ShouldBe("html-drip");
var variant = StrategyNames.Describe("html-drip 5-20ms 1-64B head 1024B repeat");
variant.GroupKey.ShouldBe("html-drip head repeat");
variant.Badges.ShouldBe(["Schnellstart", "Wiederholer"]);
StrategyNames.Describe("maze-drip 50-500ms 1-1024B head 1024B link 160B").Badges.ShouldBe(["Schnellstart"]);
}
[Fact]
public void Treats_drip_as_the_old_name_of_the_endless_page()
{
var info = StrategyNames.Describe("drip");
info.DisplayName.ShouldBe("Endlose Webseite");
info.GroupKey.ShouldBe("html-drip");
StrategyNames.Matching("endlose webseite").ShouldBe(["html-drip", "drip"]);
}
[Fact]
public void Ranks_groups_by_median_and_sinks_groups_with_few_catches()
{
var samples = new List<StrategySample>();
samples.AddRange(Enumerable.Repeat(new StrategySample("html-drip 50-500ms 1-1024B", 10_000), 3));
samples.AddRange(Enumerable.Repeat(new StrategySample("html-drip 50-500ms 1-640B", 20_000), 2));
samples.Add(new StrategySample("drip", 1_000_000));
samples.AddRange(Enumerable.Repeat(new StrategySample("env-drip 50-500ms 1-1024B", 30_000), 5));
samples.Add(new StrategySample("text-drip", 500_000_000));
var ranked = StrategyNames.Rank(samples, 10);
ranked.Select(r => r.Key).ShouldBe(["env-drip", "html-drip", "text-drip"]);
ranked[0].MedianHold.ShouldBe(TimeSpan.FromSeconds(30));
ranked[1].Count.ShouldBe(6);
ranked[1].MedianHold.ShouldBe(TimeSpan.FromSeconds(15));
ranked[1].HoldTime.ShouldBe(TimeSpan.FromMilliseconds(1_070_000));
}
} }