Add research page with MCP write tools, longer hold for repeat offenders and svn/hg decoys
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a25072e6fb
commit
e88dc415f9
48 files changed
+1983
-57
No files matched your search
@@ -0,0 +1,8 @@
|
||||
using System.Net;
|
||||
|
||||
namespace Flypaper.Core.Abstractions;
|
||||
|
||||
public interface IRepeatOffenderLookup
|
||||
{
|
||||
ValueTask<bool> HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct);
|
||||
}
|
||||
@@ -43,6 +43,7 @@ public static class FlypaperCoreExtensions
|
||||
services.TryAddSingleton<ITrapStrategySelector, ConfiguredStrategySelector>();
|
||||
services.TryAddSingleton<TrapRunner>();
|
||||
services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
|
||||
services.TryAddSingleton<IRepeatOffenderLookup, NullRepeatOffenderLookup>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -10,5 +10,9 @@ public sealed class FlypaperOptions
|
||||
|
||||
public TimeSpan MaxHoldDuration { get; set; } = TimeSpan.FromHours(1);
|
||||
|
||||
public int RepeatWindowDays { get; set; } = 7;
|
||||
|
||||
public TimeSpan RepeatHoldDuration { get; set; } = TimeSpan.FromHours(24);
|
||||
|
||||
public bool IgnorePrivateNetworks { get; set; } = true;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Abstractions;
|
||||
|
||||
namespace Flypaper.Core.Networking;
|
||||
|
||||
internal sealed class NullRepeatOffenderLookup : IRepeatOffenderLookup
|
||||
{
|
||||
public ValueTask<bool> HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct) => ValueTask.FromResult(false);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ public sealed partial class TrapRunner(
|
||||
IConnectionGovernor governor,
|
||||
ITrapStrategySelector strategies,
|
||||
ITrapEventSink sink,
|
||||
IRepeatOffenderLookup repeatOffenders,
|
||||
IOptionsMonitor<FlypaperOptions> options,
|
||||
TimeProvider timeProvider,
|
||||
ILogger<TrapRunner> logger)
|
||||
@@ -37,6 +38,14 @@ public sealed partial class TrapRunner(
|
||||
holdDuration = extension.MinimumHold;
|
||||
}
|
||||
|
||||
if (options.CurrentValue is { RepeatWindowDays: > 0 } current
|
||||
&& current.RepeatHoldDuration > holdDuration
|
||||
&& await repeatOffenders.HasTimedOutSinceAsync(session.RemoteIp, timeProvider.GetUtcNow().UtcDateTime.AddDays(-current.RepeatWindowDays), ct))
|
||||
{
|
||||
holdDuration = current.RepeatHoldDuration;
|
||||
description += " repeat";
|
||||
}
|
||||
|
||||
using var hold = new CancellationTokenSource(holdDuration, timeProvider);
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
|
||||
|
||||
|
||||
@@ -13,7 +13,9 @@ public sealed record HoldMethodSettings(
|
||||
bool MatchPath,
|
||||
int LinkSpacing,
|
||||
string BaitPaths,
|
||||
TimeSpan MaxHoldDuration)
|
||||
TimeSpan MaxHoldDuration,
|
||||
int RepeatWindowDays,
|
||||
TimeSpan RepeatHoldDuration)
|
||||
{
|
||||
public double BytesPerSecond => AverageBytesPerSecond(MinDelay, MaxDelay, MinChunkSize, MaxChunkSize);
|
||||
|
||||
@@ -28,7 +30,9 @@ public sealed record HoldMethodSettings(
|
||||
[SettingKeys.DripMatchPath] = MatchPath ? "true" : "false",
|
||||
[SettingKeys.DripLinkSpacing] = LinkSpacing.ToString(CultureInfo.InvariantCulture),
|
||||
[SettingKeys.DripBaitPaths] = BaitPaths,
|
||||
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
|
||||
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
|
||||
[SettingKeys.RepeatWindowDays] = RepeatWindowDays.ToString(CultureInfo.InvariantCulture),
|
||||
[SettingKeys.RepeatHoldDuration] = RepeatHoldDuration.ToString("c", CultureInfo.InvariantCulture)
|
||||
};
|
||||
|
||||
public static double AverageBytesPerSecond(TimeSpan minDelay, TimeSpan maxDelay, int minChunkSize, int maxChunkSize)
|
||||
@@ -48,6 +52,8 @@ public sealed record HoldMethodInput(
|
||||
bool MatchPath,
|
||||
string? LinkSpacing,
|
||||
string? BaitPaths,
|
||||
string? MaxHoldDuration);
|
||||
string? MaxHoldDuration,
|
||||
string? RepeatWindowDays,
|
||||
string? RepeatHoldDuration);
|
||||
|
||||
public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary<string, string> Errors);
|
||||
@@ -15,6 +15,7 @@ public static class RuntimeSettingsParser
|
||||
private const int MaxChunkSize = 4096;
|
||||
private const int MaxHeadStartSize = 65_536;
|
||||
private const int MaxLinkSpacing = 4096;
|
||||
private const int MaxRepeatWindowDays = 365;
|
||||
|
||||
public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input)
|
||||
{
|
||||
@@ -63,6 +64,8 @@ public static class RuntimeSettingsParser
|
||||
var linkSpacing = ParseInt(input.LinkSpacing, nameof(input.LinkSpacing), 0, MaxLinkSpacing, errors);
|
||||
var baits = ParseBaitPaths(input.BaitPaths, nameof(input.BaitPaths), errors);
|
||||
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
|
||||
var repeatWindow = ParseInt(input.RepeatWindowDays, nameof(input.RepeatWindowDays), 0, MaxRepeatWindowDays, errors);
|
||||
var repeatHold = ParseTimeSpan(input.RepeatHoldDuration, nameof(input.RepeatHoldDuration), MinHold, MaxHold, errors);
|
||||
|
||||
if (minDelay > maxDelay)
|
||||
{
|
||||
@@ -90,7 +93,9 @@ public static class RuntimeSettingsParser
|
||||
input.MatchPath,
|
||||
linkSpacing!.Value,
|
||||
baits!,
|
||||
hold!.Value),
|
||||
hold!.Value,
|
||||
repeatWindow!.Value,
|
||||
repeatHold!.Value),
|
||||
errors);
|
||||
}
|
||||
|
||||
@@ -130,7 +135,7 @@ public static class RuntimeSettingsParser
|
||||
|
||||
if (!text.Contains(':') || !TimeSpan.TryParse(text, CultureInfo.InvariantCulture, out var value))
|
||||
{
|
||||
errors[field] = "Format hh:mm:ss, zum Beispiel 00:00:10.";
|
||||
errors[field] = "Format hh:mm:ss (ab einem Tag d.hh:mm:ss), zum Beispiel 00:00:10.";
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ public static class SettingKeys
|
||||
public const string MaxConnections = "Flypaper:MaxConnections";
|
||||
public const string MaxConnectionsPerIp = "Flypaper:MaxConnectionsPerIp";
|
||||
public const string MaxHoldDuration = "Flypaper:MaxHoldDuration";
|
||||
public const string RepeatWindowDays = "Flypaper:RepeatWindowDays";
|
||||
public const string RepeatHoldDuration = "Flypaper:RepeatHoldDuration";
|
||||
public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks";
|
||||
public const string RetentionDays = "Flypaper:Retention:Days";
|
||||
public const string DripContent = "Flypaper:Drip:Content";
|
||||
@@ -21,7 +23,7 @@ public static class SettingKeys
|
||||
[MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays];
|
||||
|
||||
public static readonly IReadOnlyList<string> HoldMethod =
|
||||
[DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, DripHeadStartSize, DripMatchPath, DripLinkSpacing, DripBaitPaths, MaxHoldDuration];
|
||||
[DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, DripHeadStartSize, DripMatchPath, DripLinkSpacing, DripBaitPaths, MaxHoldDuration, RepeatWindowDays, RepeatHoldDuration];
|
||||
|
||||
public static readonly IReadOnlySet<string> All =
|
||||
new HashSet<string>(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
@@ -13,7 +13,9 @@ public static class FileContent
|
||||
{
|
||||
public static readonly IReadOnlyList<FileProfile> Profiles =
|
||||
[
|
||||
new("git-drip", "text/plain; charset=utf-8", path => path.Contains("/.git/", StringComparison.Ordinal), GitConfig),
|
||||
new("git-drip", "text/plain; charset=utf-8", IsGit, GitConfig),
|
||||
new("svn-drip", "text/plain; charset=utf-8", path => IsInside(path, "/.svn"), Svn),
|
||||
new("hg-drip", "text/plain; charset=utf-8", path => IsInside(path, "/.hg"), Mercurial),
|
||||
new("wordpress-drip", "text/html; charset=UTF-8", path => LastSegment(path) == "wp-login.php", WordPressLogin),
|
||||
new("hikvision-drip", "application/xml", path => path.StartsWith("/sdk/", StringComparison.Ordinal) || path.StartsWith("/isapi/", StringComparison.Ordinal), Hikvision),
|
||||
new("env-drip", "text/plain; charset=utf-8", path => IsEnv(LastSegment(path)), Env),
|
||||
@@ -34,6 +36,11 @@ public static class FileContent
|
||||
return Profiles.FirstOrDefault(profile => profile.Matches(normalized));
|
||||
}
|
||||
|
||||
private static bool IsInside(string path, string directory) =>
|
||||
path.Contains(directory + "/", StringComparison.Ordinal) || path.EndsWith(directory, StringComparison.Ordinal);
|
||||
|
||||
private static bool IsGit(string path) => IsInside(path, "/.git") || LastSegment(path).StartsWith(".git", StringComparison.Ordinal);
|
||||
|
||||
private static string LastSegment(string path) => path[(path.LastIndexOf('/') + 1)..];
|
||||
|
||||
private static bool IsEnv(string name) =>
|
||||
@@ -167,6 +174,27 @@ public static class FileContent
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<string> Svn(IRandomSource random)
|
||||
{
|
||||
yield return "12\n\ndir\n4821\nhttps://svn.example.com/repos/portal/trunk\nhttps://svn.example.com/repos/portal\n2026-03-14T09:21:07.512340Z\n4821\ndeploy\n\n\n\n\n\n\n\n";
|
||||
|
||||
while (true)
|
||||
{
|
||||
var date = string.Create(CultureInfo.InvariantCulture, $"2026-{random.Next(1, 13):00}-{random.Next(1, 29):00}T{random.Next(0, 24):00}:{random.Next(0, 60):00}:{random.Next(0, 60):00}.{random.Next(0, 1_000_000):000000}Z");
|
||||
yield return $"{LoremText.Word(random)}-{LoremText.Word(random)}.php\nfile\n\n\n{date}\n{Hex(random, 32)}\n{date}\ndeploy\n{random.Next(200, 90_000)}\n\n\n\n\n";
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<string> Mercurial(IRandomSource random)
|
||||
{
|
||||
yield return "dotencode\nfncache\ngeneraldelta\nrevlogv1\nsparserevlog\nstore\n";
|
||||
|
||||
while (true)
|
||||
{
|
||||
yield return $"data/{Pick(random, MazeContent.Roots)}/{LoremText.Word(random)}-{LoremText.Word(random)}.php.i\n";
|
||||
}
|
||||
}
|
||||
|
||||
private static string Hex(IRandomSource random, int length)
|
||||
{
|
||||
var chars = new char[length];
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
namespace Flypaper.Storage.Entities;
|
||||
|
||||
public enum IdeaLevel
|
||||
{
|
||||
Low = 1,
|
||||
Medium = 2,
|
||||
High = 3
|
||||
}
|
||||
|
||||
public enum IdeaStatus
|
||||
{
|
||||
Open,
|
||||
InProgress,
|
||||
Done,
|
||||
Dropped
|
||||
}
|
||||
|
||||
public sealed class IdeaEntity
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public required string Title { get; set; }
|
||||
|
||||
public IdeaLevel Effort { get; set; }
|
||||
|
||||
public IdeaLevel Efficiency { get; set; }
|
||||
|
||||
public required string Rationale { get; set; }
|
||||
|
||||
public IdeaStatus Status { get; set; }
|
||||
|
||||
public DateTime? ImplementedOn { get; set; }
|
||||
|
||||
public string? Commit { get; set; }
|
||||
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
|
||||
public bool IsClosed => Status is IdeaStatus.Done or IdeaStatus.Dropped;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace Flypaper.Storage.Entities;
|
||||
|
||||
public enum LabEntryKind
|
||||
{
|
||||
Experiment,
|
||||
Observation,
|
||||
Hypothesis,
|
||||
Method
|
||||
}
|
||||
|
||||
public sealed class LabEntryEntity
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public DateTime Date { get; set; }
|
||||
|
||||
public required string Title { get; set; }
|
||||
|
||||
public LabEntryKind Kind { get; set; }
|
||||
|
||||
public required string Text { get; set; }
|
||||
|
||||
public string? Commit { get; set; }
|
||||
|
||||
public string? Strategies { get; set; }
|
||||
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
|
||||
public IReadOnlyList<string> StrategyList =>
|
||||
(Strategies ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
}
|
||||
@@ -11,4 +11,6 @@ public sealed class McpTokenEntity
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
public DateTime? LastUsedAt { get; set; }
|
||||
|
||||
public bool CanWrite { get; set; }
|
||||
}
|
||||
@@ -14,6 +14,10 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
||||
|
||||
public DbSet<McpTokenEntity> McpTokens => Set<McpTokenEntity>();
|
||||
|
||||
public DbSet<LabEntryEntity> LabEntries => Set<LabEntryEntity>();
|
||||
|
||||
public DbSet<IdeaEntity> Ideas => Set<IdeaEntity>();
|
||||
|
||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
|
||||
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
|
||||
|
||||
@@ -43,5 +47,23 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
||||
mcpToken.Property(e => e.Name).HasMaxLength(100);
|
||||
mcpToken.Property(e => e.TokenHash).HasMaxLength(64);
|
||||
mcpToken.HasIndex(e => e.TokenHash).IsUnique();
|
||||
|
||||
var labEntry = modelBuilder.Entity<LabEntryEntity>();
|
||||
labEntry.Property(e => e.Title).HasMaxLength(LabLimits.TitleLength);
|
||||
labEntry.Property(e => e.Kind).HasConversion<string>().HasMaxLength(16);
|
||||
labEntry.Property(e => e.Text).HasMaxLength(LabLimits.TextLength);
|
||||
labEntry.Property(e => e.Commit).HasMaxLength(LabLimits.CommitLength);
|
||||
labEntry.Property(e => e.Strategies).HasMaxLength(LabLimits.StrategiesLength);
|
||||
labEntry.Ignore(e => e.StrategyList);
|
||||
labEntry.HasIndex(e => e.Date);
|
||||
|
||||
var idea = modelBuilder.Entity<IdeaEntity>();
|
||||
idea.Property(e => e.Title).HasMaxLength(LabLimits.TitleLength);
|
||||
idea.Property(e => e.Effort).HasConversion<string>().HasMaxLength(16);
|
||||
idea.Property(e => e.Efficiency).HasConversion<string>().HasMaxLength(16);
|
||||
idea.Property(e => e.Rationale).HasMaxLength(LabLimits.TextLength);
|
||||
idea.Property(e => e.Status).HasConversion<string>().HasMaxLength(16);
|
||||
idea.Property(e => e.Commit).HasMaxLength(LabLimits.CommitLength);
|
||||
idea.Ignore(e => e.IsClosed);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using Flypaper.Storage.Dashboard;
|
||||
using Flypaper.Storage.Events;
|
||||
using Flypaper.Storage.Maintenance;
|
||||
using Flypaper.Storage.Queries;
|
||||
using Flypaper.Storage.Research;
|
||||
using Flypaper.Storage.Settings;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@@ -23,6 +24,7 @@ public static class FlypaperStorageExtensions
|
||||
builder.Services.AddSingleton<RuntimeSettingsStore>();
|
||||
builder.Services.AddSingleton<AdminCredentialStore>();
|
||||
builder.Services.AddSingleton<McpTokenStore>();
|
||||
builder.Services.AddSingleton<ResearchStore>();
|
||||
builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName));
|
||||
builder.Services.AddFlypaperStorage(connectionString);
|
||||
|
||||
@@ -38,6 +40,7 @@ public static class FlypaperStorageExtensions
|
||||
services.AddHostedService<OriginBackfill>();
|
||||
services.AddSingleton<DashboardQueries>();
|
||||
services.AddSingleton<CatchQueries>();
|
||||
services.AddSingleton<IRepeatOffenderLookup, RepeatOffenderLookup>();
|
||||
services.AddSingleton<TrapDataMaintenance>();
|
||||
services.AddHostedService<RetentionCleanup>();
|
||||
return services;
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Flypaper.Storage;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Flypaper.Storage.Migrations
|
||||
{
|
||||
[DbContext(typeof(FlypaperDbContext))]
|
||||
[Migration("20261117165523_AddResearch")]
|
||||
partial class AddResearch
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.IdeaEntity", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Commit")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Efficiency")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Effort")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime?>("ImplementedOn")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Rationale")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20000)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Ideas");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.LabEntryEntity", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Commit")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("Date")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Kind")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Strategies")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Text")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20000)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Date");
|
||||
|
||||
b.ToTable("LabEntries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("CanWrite")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime?>("LastUsedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("McpTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("Settings");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("Asn")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("BytesSent")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("City")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("ClientInfo")
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Country")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("CountryCode")
|
||||
.HasMaxLength(2)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("DurationMs")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<DateTime>("EndedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Outcome")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Protocol")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Provider")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("RemoteIp")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("SessionId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("StartedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Strategy")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Target")
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Asn");
|
||||
|
||||
b.HasIndex("CountryCode");
|
||||
|
||||
b.HasIndex("RemoteIp");
|
||||
|
||||
b.HasIndex("StartedAt");
|
||||
|
||||
b.ToTable("TrapEvents");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Flypaper.Storage.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddResearch : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "CanWrite",
|
||||
table: "McpTokens",
|
||||
type: "INTEGER",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Ideas",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "INTEGER", nullable: false)
|
||||
.Annotation("Sqlite:Autoincrement", true),
|
||||
Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
|
||||
Effort = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
|
||||
Efficiency = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
|
||||
Rationale = table.Column<string>(type: "TEXT", maxLength: 20000, nullable: false),
|
||||
Status = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
|
||||
ImplementedOn = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
Commit = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
|
||||
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Ideas", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "LabEntries",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "INTEGER", nullable: false)
|
||||
.Annotation("Sqlite:Autoincrement", true),
|
||||
Date = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
|
||||
Kind = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
|
||||
Text = table.Column<string>(type: "TEXT", maxLength: 20000, nullable: false),
|
||||
Commit = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
|
||||
Strategies = table.Column<string>(type: "TEXT", maxLength: 512, nullable: true),
|
||||
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_LabEntries", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_LabEntries_Date",
|
||||
table: "LabEntries",
|
||||
column: "Date");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Ideas");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "LabEntries");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CanWrite",
|
||||
table: "McpTokens");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,12 +17,109 @@ namespace Flypaper.Storage.Migrations
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.IdeaEntity", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Commit")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Efficiency")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Effort")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime?>("ImplementedOn")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Rationale")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20000)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Ideas");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.LabEntryEntity", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Commit")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("Date")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Kind")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Strategies")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Text")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20000)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Date");
|
||||
|
||||
b.ToTable("LabEntries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("CanWrite")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Flypaper.Storage.Queries;
|
||||
|
||||
public sealed class RepeatOffenderLookup(IDbContextFactory<FlypaperDbContext> dbContextFactory) : IRepeatOffenderLookup
|
||||
{
|
||||
public async ValueTask<bool> HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct)
|
||||
{
|
||||
var ip = address.ToString();
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
return await db.TrapEvents.AnyAsync(e => e.RemoteIp == ip && e.Outcome == TrapOutcome.Timeout && e.StartedAt >= since, ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Flypaper.Storage;
|
||||
|
||||
public static class LabLimits
|
||||
{
|
||||
public const int TitleLength = 200;
|
||||
public const int TextLength = 20_000;
|
||||
public const int CommitLength = 64;
|
||||
public const int StrategiesLength = 512;
|
||||
public const int StrategyNameLength = 64;
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Flypaper.Storage.Research;
|
||||
|
||||
public sealed record LabEntryInput(
|
||||
string? Title = null,
|
||||
LabEntryKind? Kind = null,
|
||||
string? Text = null,
|
||||
DateTime? Date = null,
|
||||
string? Commit = null,
|
||||
IReadOnlyList<string>? Strategies = null);
|
||||
|
||||
public sealed record IdeaInput(
|
||||
string? Title = null,
|
||||
IdeaLevel? Effort = null,
|
||||
IdeaLevel? Efficiency = null,
|
||||
string? Rationale = null,
|
||||
IdeaStatus? Status = null,
|
||||
DateTime? ImplementedOn = null,
|
||||
string? Commit = null);
|
||||
|
||||
public sealed partial class ResearchStore(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
|
||||
{
|
||||
public const int MaxLimit = 500;
|
||||
|
||||
[GeneratedRegex("^[0-9a-f]{4,64}$")]
|
||||
private static partial Regex CommitPattern();
|
||||
|
||||
[GeneratedRegex("^[a-z0-9][a-z0-9._-]*$")]
|
||||
private static partial Regex StrategyPattern();
|
||||
|
||||
public async Task<IReadOnlyList<LabEntryEntity>> ListEntriesAsync(
|
||||
LabEntryKind? kind = null,
|
||||
string? strategy = null,
|
||||
int limit = MaxLimit,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var entries = db.LabEntries.AsNoTracking();
|
||||
if (kind is { } wanted)
|
||||
{
|
||||
entries = entries.Where(e => e.Kind == wanted);
|
||||
}
|
||||
|
||||
var rows = await entries.OrderByDescending(e => e.Date).ThenByDescending(e => e.Id).ToListAsync(ct);
|
||||
if (!string.IsNullOrWhiteSpace(strategy))
|
||||
{
|
||||
var name = strategy.Trim().ToLowerInvariant();
|
||||
rows = rows.Where(e => e.StrategyList.Contains(name, StringComparer.Ordinal)).ToList();
|
||||
}
|
||||
|
||||
return rows.Take(Math.Clamp(limit, 1, MaxLimit)).ToList();
|
||||
}
|
||||
|
||||
public async Task<LabEntryEntity> CreateEntryAsync(LabEntryInput input, CancellationToken ct = default)
|
||||
{
|
||||
var now = timeProvider.GetUtcNow().UtcDateTime;
|
||||
var entry = new LabEntryEntity
|
||||
{
|
||||
Title = RequireText(input.Title, "title", LabLimits.TitleLength),
|
||||
Kind = input.Kind ?? throw new ArgumentException("kind is required."),
|
||||
Text = RequireText(input.Text, "text", LabLimits.TextLength),
|
||||
Date = (input.Date ?? now).Date,
|
||||
Commit = ParseCommit(input.Commit),
|
||||
Strategies = JoinStrategies(input.Strategies),
|
||||
CreatedAt = now,
|
||||
UpdatedAt = now
|
||||
};
|
||||
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
db.LabEntries.Add(entry);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return entry;
|
||||
}
|
||||
|
||||
public async Task<LabEntryEntity?> UpdateEntryAsync(int id, LabEntryInput input, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var entry = await db.LabEntries.SingleOrDefaultAsync(e => e.Id == id, ct);
|
||||
if (entry is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (input.Title is not null)
|
||||
{
|
||||
entry.Title = RequireText(input.Title, "title", LabLimits.TitleLength);
|
||||
}
|
||||
|
||||
if (input.Kind is { } kind)
|
||||
{
|
||||
entry.Kind = kind;
|
||||
}
|
||||
|
||||
if (input.Text is not null)
|
||||
{
|
||||
entry.Text = RequireText(input.Text, "text", LabLimits.TextLength);
|
||||
}
|
||||
|
||||
if (input.Date is { } date)
|
||||
{
|
||||
entry.Date = date.Date;
|
||||
}
|
||||
|
||||
if (input.Commit is not null)
|
||||
{
|
||||
entry.Commit = ParseCommit(input.Commit);
|
||||
}
|
||||
|
||||
if (input.Strategies is not null)
|
||||
{
|
||||
entry.Strategies = JoinStrategies(input.Strategies);
|
||||
}
|
||||
|
||||
entry.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;
|
||||
await db.SaveChangesAsync(ct);
|
||||
return entry;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<IdeaEntity>> ListIdeasAsync(IdeaStatus? status = null, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var ideas = db.Ideas.AsNoTracking();
|
||||
if (status is { } wanted)
|
||||
{
|
||||
ideas = ideas.Where(i => i.Status == wanted);
|
||||
}
|
||||
|
||||
var rows = await ideas.ToListAsync(ct);
|
||||
return rows
|
||||
.OrderBy(i => i.Effort)
|
||||
.ThenByDescending(i => i.Efficiency)
|
||||
.ThenBy(i => i.Id)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public async Task<IdeaEntity> CreateIdeaAsync(IdeaInput input, CancellationToken ct = default)
|
||||
{
|
||||
var now = timeProvider.GetUtcNow().UtcDateTime;
|
||||
var status = input.Status ?? IdeaStatus.Open;
|
||||
var idea = new IdeaEntity
|
||||
{
|
||||
Title = RequireText(input.Title, "title", LabLimits.TitleLength),
|
||||
Effort = input.Effort ?? throw new ArgumentException("effort is required."),
|
||||
Efficiency = input.Efficiency ?? throw new ArgumentException("efficiency is required."),
|
||||
Rationale = RequireText(input.Rationale, "rationale", LabLimits.TextLength),
|
||||
Status = status,
|
||||
Commit = ParseCommit(input.Commit),
|
||||
CreatedAt = now,
|
||||
UpdatedAt = now
|
||||
};
|
||||
idea.ImplementedOn = ImplementedOn(status, input.ImplementedOn, null, now);
|
||||
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
db.Ideas.Add(idea);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return idea;
|
||||
}
|
||||
|
||||
public async Task<IdeaEntity?> UpdateIdeaAsync(int id, IdeaInput input, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var idea = await db.Ideas.SingleOrDefaultAsync(i => i.Id == id, ct);
|
||||
if (idea is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var now = timeProvider.GetUtcNow().UtcDateTime;
|
||||
if (input.Title is not null)
|
||||
{
|
||||
idea.Title = RequireText(input.Title, "title", LabLimits.TitleLength);
|
||||
}
|
||||
|
||||
if (input.Effort is { } effort)
|
||||
{
|
||||
idea.Effort = effort;
|
||||
}
|
||||
|
||||
if (input.Efficiency is { } efficiency)
|
||||
{
|
||||
idea.Efficiency = efficiency;
|
||||
}
|
||||
|
||||
if (input.Rationale is not null)
|
||||
{
|
||||
idea.Rationale = RequireText(input.Rationale, "rationale", LabLimits.TextLength);
|
||||
}
|
||||
|
||||
if (input.Commit is not null)
|
||||
{
|
||||
idea.Commit = ParseCommit(input.Commit);
|
||||
}
|
||||
|
||||
var status = input.Status ?? idea.Status;
|
||||
idea.Status = status;
|
||||
idea.ImplementedOn = ImplementedOn(status, input.ImplementedOn, idea.ImplementedOn, now);
|
||||
idea.UpdatedAt = now;
|
||||
await db.SaveChangesAsync(ct);
|
||||
return idea;
|
||||
}
|
||||
|
||||
private static DateTime? ImplementedOn(IdeaStatus status, DateTime? given, DateTime? current, DateTime now) =>
|
||||
status == IdeaStatus.Done ? (given ?? current ?? now).Date : null;
|
||||
|
||||
private static string RequireText(string? value, string name, int maxLength)
|
||||
{
|
||||
var text = value?.Trim();
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
throw new ArgumentException($"{name} must not be empty.");
|
||||
}
|
||||
|
||||
return text.Length <= maxLength ? text : throw new ArgumentException($"{name} is too long (at most {maxLength} characters).");
|
||||
}
|
||||
|
||||
private static string? ParseCommit(string? value)
|
||||
{
|
||||
var commit = value?.Trim().ToLowerInvariant();
|
||||
if (string.IsNullOrEmpty(commit))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return CommitPattern().IsMatch(commit) ? commit : throw new ArgumentException("commit must be a hexadecimal hash of 4 to 64 characters.");
|
||||
}
|
||||
|
||||
private static string? JoinStrategies(IReadOnlyList<string>? strategies)
|
||||
{
|
||||
var names = (strategies ?? [])
|
||||
.Select(name => name.Trim().ToLowerInvariant())
|
||||
.Where(name => name.Length > 0)
|
||||
.Distinct()
|
||||
.ToList();
|
||||
if (names.Any(name => name.Length > LabLimits.StrategyNameLength || !StrategyPattern().IsMatch(name)))
|
||||
{
|
||||
throw new ArgumentException("strategies must be strategy names such as maze-drip or git-drip (letters, digits, '.', '_' and '-').");
|
||||
}
|
||||
|
||||
var joined = string.Join(',', names);
|
||||
return joined.Length == 0 ? null
|
||||
: joined.Length <= LabLimits.StrategiesLength ? joined
|
||||
: throw new ArgumentException("strategies list is too long.");
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,10 @@ public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContext
|
||||
return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, CancellationToken ct = default)
|
||||
public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, bool canWrite = false, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };
|
||||
var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CanWrite = canWrite, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };
|
||||
db.McpTokens.Add(token);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return token;
|
||||
@@ -28,6 +28,12 @@ public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContext
|
||||
return await db.McpTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct) > 0;
|
||||
}
|
||||
|
||||
public async Task<bool> SetCanWriteAsync(int id, bool canWrite, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
return await db.McpTokens.Where(t => t.Id == id).ExecuteUpdateAsync(set => set.SetProperty(t => t.CanWrite, canWrite), ct) > 0;
|
||||
}
|
||||
|
||||
public async Task<McpTokenEntity?> UseAsync(string tokenHash, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<nav class="nav">
|
||||
<a href="/" class="brand"><span class="brand-mark" aria-hidden="true"></span>Flypaper</a>
|
||||
<NavLink href="/" Match="NavLinkMatch.All">Dashboard</NavLink>
|
||||
<NavLink href="/erkenntnisse">Erkenntnisse</NavLink>
|
||||
<NavLink href="/settings">Einstellungen</NavLink>
|
||||
<form method="post" action="/auth/logout" class="logout">
|
||||
<AntiforgeryToken />
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
@using Flypaper.Storage.Entities
|
||||
|
||||
<div class="table-scroll">
|
||||
<table class="idea-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Idee</th>
|
||||
<th>Aufwand</th>
|
||||
<th>Effizienz</th>
|
||||
<th>Status</th>
|
||||
<th>Umgesetzt</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var idea in Ideas)
|
||||
{
|
||||
<tr>
|
||||
<td>
|
||||
<strong>@idea.Title</strong>
|
||||
<div class="markdown muted">@MarkdownRenderer.Render(idea.Rationale)</div>
|
||||
</td>
|
||||
<td class="nowrap">@Level(idea.Effort)</td>
|
||||
<td class="nowrap">@Level(idea.Efficiency)</td>
|
||||
<td class="nowrap"><span class="badge status-@idea.Status.ToString().ToLowerInvariant()">@StatusLabel(idea.Status)</span></td>
|
||||
<td class="nowrap">
|
||||
@if (idea.ImplementedOn is { } date)
|
||||
{
|
||||
@date.ToString("dd.MM.yyyy")
|
||||
}
|
||||
@if (idea.Commit is { } commit)
|
||||
{
|
||||
<code title="@commit">@(commit.Length > 8 ? commit[..8] : commit)</code>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired] public required IReadOnlyList<IdeaEntity> Ideas { get; set; }
|
||||
|
||||
private static string Level(IdeaLevel level) => level switch
|
||||
{
|
||||
IdeaLevel.Low => "Gering",
|
||||
IdeaLevel.Medium => "Mittel",
|
||||
_ => "Hoch"
|
||||
};
|
||||
|
||||
private static string StatusLabel(IdeaStatus status) => status switch
|
||||
{
|
||||
IdeaStatus.Open => "Offen",
|
||||
IdeaStatus.InProgress => "In Arbeit",
|
||||
IdeaStatus.Done => "Umgesetzt",
|
||||
_ => "Verworfen"
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
@page "/erkenntnisse"
|
||||
@using Flypaper.Storage.Entities
|
||||
@using Flypaper.Storage.Research
|
||||
@inject ResearchStore Store
|
||||
|
||||
<PageTitle>Flypaper · Erkenntnisse</PageTitle>
|
||||
|
||||
<header class="page-head">
|
||||
<h1>Erkenntnisse</h1>
|
||||
<p>Laborbuch und Ideen zur Optimierung der Falle. Einträge werden per MCP fortgeschrieben.</p>
|
||||
</header>
|
||||
|
||||
<section class="card" id="laborbuch">
|
||||
<div class="card-head">
|
||||
<h2>Laborbuch</h2>
|
||||
<span class="hint">@_entries.Count @(_entries.Count == 1 ? "Eintrag" : "Einträge")</span>
|
||||
</div>
|
||||
|
||||
<nav class="chips" aria-label="Art filtern">
|
||||
<a class="chip @(_kind is null ? "active" : null)" href="erkenntnisse@(Query(null, ShowClosed))#laborbuch">Alle</a>
|
||||
@foreach (var kind in Enum.GetValues<LabEntryKind>())
|
||||
{
|
||||
<a class="chip @(_kind == kind ? "active" : null)" href="erkenntnisse@(Query(kind, ShowClosed))#laborbuch">@KindLabel(kind)</a>
|
||||
}
|
||||
</nav>
|
||||
|
||||
@if (_entries.Count == 0)
|
||||
{
|
||||
<p class="empty">Noch keine Einträge.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="lab-entries">
|
||||
@foreach (var entry in _entries)
|
||||
{
|
||||
<article class="lab-entry">
|
||||
<header>
|
||||
<time class="mono" datetime="@entry.Date.ToString("yyyy-MM-dd")">@entry.Date.ToString("dd.MM.yyyy")</time>
|
||||
<span class="badge kind-@entry.Kind.ToString().ToLowerInvariant()">@KindLabel(entry.Kind)</span>
|
||||
<h3>@entry.Title</h3>
|
||||
</header>
|
||||
@if (entry.StrategyList.Count > 0 || entry.Commit is not null)
|
||||
{
|
||||
<p class="lab-meta">
|
||||
@foreach (var strategy in entry.StrategyList)
|
||||
{
|
||||
<code>@strategy</code>
|
||||
}
|
||||
@if (entry.Commit is { } commit)
|
||||
{
|
||||
<span class="muted">Commit</span>
|
||||
<code title="@commit">@Short(commit)</code>
|
||||
}
|
||||
</p>
|
||||
}
|
||||
<div class="markdown">@MarkdownRenderer.Render(entry.Text)</div>
|
||||
</article>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="card" id="ideen">
|
||||
<div class="card-head">
|
||||
<h2>Ideen</h2>
|
||||
<span class="hint">nach Aufwand sortiert</span>
|
||||
</div>
|
||||
|
||||
@if (_open.Count == 0)
|
||||
{
|
||||
<p class="empty">Keine offenen Ideen.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<IdeaTable Ideas="_open" />
|
||||
}
|
||||
|
||||
@if (_closed.Count > 0)
|
||||
{
|
||||
<p class="more">
|
||||
<a href="erkenntnisse@(Query(_kind, !ShowClosed))#ideen">
|
||||
@(ShowClosed ? "Umgesetzte und verworfene ausblenden" : $"{_closed.Count} umgesetzte oder verworfene anzeigen")
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@if (ShowClosed)
|
||||
{
|
||||
<IdeaTable Ideas="_closed" />
|
||||
}
|
||||
}
|
||||
</section>
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<LabEntryEntity> _entries = [];
|
||||
private IReadOnlyList<IdeaEntity> _open = [];
|
||||
private IReadOnlyList<IdeaEntity> _closed = [];
|
||||
private LabEntryKind? _kind;
|
||||
|
||||
[SupplyParameterFromQuery(Name = "art")] private string? Art { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "erledigt")] private string? Closed { get; set; }
|
||||
|
||||
private bool ShowClosed => Closed == "1";
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
_kind = Enum.TryParse<LabEntryKind>(Art, ignoreCase: true, out var kind) && Enum.IsDefined(kind) ? kind : null;
|
||||
_entries = await Store.ListEntriesAsync(_kind);
|
||||
var ideas = await Store.ListIdeasAsync();
|
||||
_open = ideas.Where(idea => !idea.IsClosed).ToList();
|
||||
_closed = ideas.Where(idea => idea.IsClosed).ToList();
|
||||
}
|
||||
|
||||
private static string Query(LabEntryKind? kind, bool showClosed)
|
||||
{
|
||||
var parts = new List<string>();
|
||||
if (kind is { } value)
|
||||
{
|
||||
parts.Add("art=" + value.ToString().ToLowerInvariant());
|
||||
}
|
||||
|
||||
if (showClosed)
|
||||
{
|
||||
parts.Add("erledigt=1");
|
||||
}
|
||||
|
||||
return parts.Count == 0 ? "" : "?" + string.Join('&', parts);
|
||||
}
|
||||
|
||||
private static string Short(string commit) => commit.Length > 8 ? commit[..8] : commit;
|
||||
|
||||
internal static string KindLabel(LabEntryKind kind) => kind switch
|
||||
{
|
||||
LabEntryKind.Experiment => "Experiment",
|
||||
LabEntryKind.Observation => "Beobachtung",
|
||||
LabEntryKind.Hypothesis => "Hypothese",
|
||||
_ => "Messmethode"
|
||||
};
|
||||
}
|
||||
@@ -21,4 +21,8 @@ public sealed class HoldMethodModel
|
||||
public string? BaitPaths { get; set; }
|
||||
|
||||
public string? MaxHoldDuration { get; set; }
|
||||
|
||||
public string? RepeatWindowDays { get; set; }
|
||||
|
||||
public string? RepeatHoldDuration { get; set; }
|
||||
}
|
||||
@@ -65,6 +65,12 @@
|
||||
<SettingsField Label="Maximale Haltedauer" For="hold" Hint="hh:mm:ss, höchstens 7 Tage" Errors="_errors" Key="@nameof(HoldMethodModel.MaxHoldDuration)">
|
||||
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" />
|
||||
</SettingsField>
|
||||
<SettingsField Label="Wiederholer erkennen" For="repeat-window" Unit="Tage" Hint="0 bis 365, 0 = aus. IPs mit einem Timeout in diesem Zeitraum gelten als Wiederholer" Errors="_errors" Key="@nameof(HoldMethodModel.RepeatWindowDays)">
|
||||
<InputText id="repeat-window" @bind-Value="Model!.RepeatWindowDays" inputmode="numeric" />
|
||||
</SettingsField>
|
||||
<SettingsField Label="Haltedauer für Wiederholer" For="repeat-hold" Hint="d.hh:mm:ss, höchstens 7 Tage. Strategie bekommt den Zusatz repeat" Errors="_errors" Key="@nameof(HoldMethodModel.RepeatHoldDuration)">
|
||||
<InputText id="repeat-hold" @bind-Value="Model!.RepeatHoldDuration" />
|
||||
</SettingsField>
|
||||
</div>
|
||||
|
||||
<div class="fields">
|
||||
@@ -149,7 +155,9 @@
|
||||
Model.MatchPath,
|
||||
Model.LinkSpacing,
|
||||
Model.BaitPaths,
|
||||
Model.MaxHoldDuration));
|
||||
Model.MaxHoldDuration,
|
||||
Model.RepeatWindowDays,
|
||||
Model.RepeatHoldDuration));
|
||||
|
||||
if (result.Settings is null)
|
||||
{
|
||||
@@ -181,7 +189,9 @@
|
||||
MatchPath = drip.MatchPath,
|
||||
LinkSpacing = drip.LinkSpacing.ToString(CultureInfo.InvariantCulture),
|
||||
BaitPaths = drip.BaitPaths,
|
||||
MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
|
||||
MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
|
||||
RepeatWindowDays = Core.CurrentValue.RepeatWindowDays.ToString(CultureInfo.InvariantCulture),
|
||||
RepeatHoldDuration = Core.CurrentValue.RepeatHoldDuration.ToString("c", CultureInfo.InvariantCulture)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,19 @@
|
||||
@inject McpTokenStore Store
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol. Nur lesend und nur im LAN.">
|
||||
<SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol und führen die Erkenntnisse fort. Schreiben dürfen nur Tokens mit Schreibrecht. Nur im LAN.">
|
||||
@if (Revoked == "revoked")
|
||||
{
|
||||
<Notice>Token widerrufen.</Notice>
|
||||
}
|
||||
else if (Revoked == "write-on")
|
||||
{
|
||||
<Notice>Schreibrecht erteilt.</Notice>
|
||||
}
|
||||
else if (Revoked == "write-off")
|
||||
{
|
||||
<Notice>Schreibrecht entzogen.</Notice>
|
||||
}
|
||||
|
||||
@if (_newToken is not null)
|
||||
{
|
||||
@@ -37,6 +45,7 @@
|
||||
<th>Name</th>
|
||||
<th>Erstellt</th>
|
||||
<th>Zuletzt genutzt</th>
|
||||
<th>Zugriff</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -47,6 +56,14 @@
|
||||
<td>@token.Name</td>
|
||||
<td class="nowrap">@token.CreatedAt.ToLocalTime().ToString("dd.MM.yyyy HH:mm")</td>
|
||||
<td class="nowrap">@(token.LastUsedAt?.ToLocalTime().ToString("dd.MM.yyyy HH:mm") ?? "nie")</td>
|
||||
<td class="nowrap">
|
||||
<form method="post" action="/mcp-tokens/@token.Id/write" class="inline-form">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="enabled" value="@(token.CanWrite ? "false" : "true")" />
|
||||
<span>@(token.CanWrite ? "Lesen und schreiben" : "Nur lesen")</span>
|
||||
<button type="submit" class="ghost">@(token.CanWrite ? "Schreibrecht entziehen" : "Schreibrecht erteilen")</button>
|
||||
</form>
|
||||
</td>
|
||||
<td class="num">
|
||||
<form method="post" action="/mcp-tokens/@token.Id/revoke" onsubmit="return confirm('Token „@token.Name“ widerrufen?')">
|
||||
<AntiforgeryToken />
|
||||
@@ -72,6 +89,10 @@
|
||||
<span class="field-error">@nameError</span>
|
||||
}
|
||||
</div>
|
||||
<label class="inline-check">
|
||||
<InputCheckbox @bind-Value="Model!.CanWrite" />
|
||||
<span>Mit Schreibrecht</span>
|
||||
</label>
|
||||
<button type="submit">Token erzeugen</button>
|
||||
</EditForm>
|
||||
</SettingsSection>
|
||||
@@ -103,9 +124,10 @@
|
||||
return;
|
||||
}
|
||||
|
||||
_newToken = await Tokens.CreateAsync(name);
|
||||
_newToken = await Tokens.CreateAsync(name, Model.CanWrite);
|
||||
_newTokenName = name;
|
||||
Model.Name = null;
|
||||
Model.CanWrite = false;
|
||||
_tokens = await Store.ListAsync();
|
||||
}
|
||||
}
|
||||
@@ -3,4 +3,6 @@ namespace Flypaper.Web.Components.Pages.Settings;
|
||||
public sealed class McpTokenModel
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
|
||||
public bool CanWrite { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Markdig;
|
||||
using Markdig.Syntax;
|
||||
using Markdig.Syntax.Inlines;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
|
||||
namespace Flypaper.Web.Components.Shared;
|
||||
|
||||
public static class MarkdownRenderer
|
||||
{
|
||||
private static readonly string[] SafeSchemes = ["http", "https", "mailto"];
|
||||
|
||||
private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder()
|
||||
.DisableHtml()
|
||||
.UseAutoLinks()
|
||||
.UsePipeTables()
|
||||
.UseEmphasisExtras()
|
||||
.Build();
|
||||
|
||||
public static MarkupString Render(string? markdown)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(markdown))
|
||||
{
|
||||
return new MarkupString("");
|
||||
}
|
||||
|
||||
var document = Markdown.Parse(markdown, Pipeline);
|
||||
foreach (var link in document.Descendants<LinkInline>().Where(link => !IsSafe(link.Url)).ToList())
|
||||
{
|
||||
link.Url = "#";
|
||||
}
|
||||
|
||||
foreach (var link in document.Descendants<AutolinkInline>().Where(link => !IsSafe(link.Url)).ToList())
|
||||
{
|
||||
link.Url = "#";
|
||||
}
|
||||
|
||||
return new MarkupString(document.ToHtml(Pipeline));
|
||||
}
|
||||
|
||||
private static bool IsSafe(string? url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var trimmed = url.Trim();
|
||||
var colon = trimmed.IndexOf(':');
|
||||
var firstSeparator = trimmed.IndexOfAny(['/', '?', '#']);
|
||||
if (colon < 0 || firstSeparator >= 0 && firstSeparator < colon)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return SafeSchemes.Contains(trimmed[..colon], StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Markdig" />
|
||||
<PackageReference Include="ModelContextProtocol.AspNetCore" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Flypaper.Storage.Settings;
|
||||
@@ -18,7 +19,9 @@ public static class McpExtensions
|
||||
"Flypaper is an HTTP tarpit. Scanning bots that probe a server (e.g. for /.env or /wp-login.php) are " +
|
||||
"answered with an endless page a few bytes at a time and held as long as possible. Every such catch is " +
|
||||
"stored with its time, client IP, country, network provider (ASN), requested URL, user agent, duration " +
|
||||
"and bytes sent. These tools only read that data; times are ISO 8601 UTC, durations in seconds.";
|
||||
"and bytes sent. Most tools only read that data; times are ISO 8601 UTC, durations in seconds. The tools " +
|
||||
"for the Erkenntnisse page (lab notebook entries and ideas) can also write, but only with a token that " +
|
||||
"has write permission; read-only tokens do not see the write tools.";
|
||||
|
||||
private static readonly JsonSerializerOptions ToolJsonOptions = new(McpJsonUtilities.DefaultOptions)
|
||||
{
|
||||
@@ -44,32 +47,64 @@ public static class McpExtensions
|
||||
})
|
||||
.WithHttpTransport(options => options.Stateless = true)
|
||||
.WithTools<FlypaperTools>(ToolJsonOptions)
|
||||
.WithRequestFilters(filters => filters.AddCallToolFilter(next => async (context, ct) =>
|
||||
.WithTools<ResearchTools>(ToolJsonOptions)
|
||||
.WithRequestFilters(filters =>
|
||||
{
|
||||
var tool = context.Params?.Name;
|
||||
var logger = context.Services?.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(FlypaperTools));
|
||||
|
||||
if (context.MatchedPrimitive is McpServerTool matched
|
||||
&& McpArgumentCheck.FindProblem(matched.ProtocolTool.InputSchema, context.Params?.Arguments?.AsReadOnly()) is { } problem)
|
||||
{
|
||||
logger?.LogWarning("MCP tool {Tool} was called with invalid arguments: {Problem}", tool, problem);
|
||||
return InvalidArguments(tool, problem);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return await next(context, ct);
|
||||
}
|
||||
catch (ArgumentException exception)
|
||||
{
|
||||
logger?.LogWarning(exception, "MCP tool {Tool} was called with invalid arguments", tool);
|
||||
return InvalidArguments(tool, exception.Message);
|
||||
}
|
||||
}));
|
||||
filters.AddListToolsFilter(HideWriteTools);
|
||||
filters.AddCallToolFilter(CheckCall);
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
private static McpRequestHandler<ListToolsRequestParams, ListToolsResult> HideWriteTools(McpRequestHandler<ListToolsRequestParams, ListToolsResult> next) =>
|
||||
async (context, ct) =>
|
||||
{
|
||||
var result = await next(context, ct);
|
||||
if (!CanWrite(context.User))
|
||||
{
|
||||
result.Tools = result.Tools.Where(tool => tool.Annotations?.ReadOnlyHint == true).ToList();
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
private static McpRequestHandler<CallToolRequestParams, CallToolResult> CheckCall(McpRequestHandler<CallToolRequestParams, CallToolResult> next) =>
|
||||
async (context, ct) =>
|
||||
{
|
||||
var tool = context.Params?.Name;
|
||||
var logger = context.Services?.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(FlypaperTools));
|
||||
|
||||
if (context.MatchedPrimitive is McpServerTool { ProtocolTool.Annotations.ReadOnlyHint: not true } && !CanWrite(context.User))
|
||||
{
|
||||
logger?.LogWarning("MCP tool {Tool} was called with a token without write permission", tool);
|
||||
return new CallToolResult
|
||||
{
|
||||
IsError = true,
|
||||
Content = [new TextContentBlock { Text = $"'{tool}' needs a token with write permission. Enable it for this token in the dashboard under Einstellungen > MCP-Zugriff." }]
|
||||
};
|
||||
}
|
||||
|
||||
if (context.MatchedPrimitive is McpServerTool matched
|
||||
&& McpArgumentCheck.FindProblem(matched.ProtocolTool.InputSchema, context.Params?.Arguments?.AsReadOnly()) is { } problem)
|
||||
{
|
||||
logger?.LogWarning("MCP tool {Tool} was called with invalid arguments: {Problem}", tool, problem);
|
||||
return InvalidArguments(tool, problem);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return await next(context, ct);
|
||||
}
|
||||
catch (ArgumentException exception)
|
||||
{
|
||||
logger?.LogWarning(exception, "MCP tool {Tool} was called with invalid arguments", tool);
|
||||
return InvalidArguments(tool, exception.Message);
|
||||
}
|
||||
};
|
||||
|
||||
private static bool CanWrite(ClaimsPrincipal? user) => user?.HasClaim(McpTokenAuthenticationHandler.WriteClaim, "true") == true;
|
||||
|
||||
private static CallToolResult InvalidArguments(string? tool, string message) => new()
|
||||
{
|
||||
IsError = true,
|
||||
@@ -91,6 +126,18 @@ public static class McpExtensions
|
||||
return Results.LocalRedirect("/settings?mcp=revoked#mcp");
|
||||
});
|
||||
|
||||
app.MapPost("/mcp-tokens/{id:int}/write", async (int id, HttpContext context, IAntiforgery antiforgery, McpTokenStore store) =>
|
||||
{
|
||||
if (!await antiforgery.IsRequestValidAsync(context))
|
||||
{
|
||||
return Results.BadRequest();
|
||||
}
|
||||
|
||||
var enabled = (await context.Request.ReadFormAsync(context.RequestAborted))["enabled"] == "true";
|
||||
await store.SetCanWriteAsync(id, enabled, context.RequestAborted);
|
||||
return Results.LocalRedirect("/settings?mcp=" + (enabled ? "write-on" : "write-off") + "#mcp");
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -50,3 +50,30 @@ public sealed record IpLookupResult(
|
||||
DateTime? LastSeen,
|
||||
IReadOnlyList<CatchItem> Events,
|
||||
int EventsOmitted);
|
||||
|
||||
public sealed record EntryItem(
|
||||
int Id,
|
||||
DateOnly Date,
|
||||
string Title,
|
||||
string Kind,
|
||||
string Text,
|
||||
string? Commit,
|
||||
IReadOnlyList<string> Strategies,
|
||||
DateTime CreatedAt,
|
||||
DateTime UpdatedAt);
|
||||
|
||||
public sealed record EntryListResult(int Count, IReadOnlyList<EntryItem> Entries);
|
||||
|
||||
public sealed record IdeaItem(
|
||||
int Id,
|
||||
string Title,
|
||||
string Effort,
|
||||
string Efficiency,
|
||||
string Rationale,
|
||||
string Status,
|
||||
DateOnly? ImplementedOn,
|
||||
string? Commit,
|
||||
DateTime CreatedAt,
|
||||
DateTime UpdatedAt);
|
||||
|
||||
public sealed record IdeaListResult(int Count, IReadOnlyList<IdeaItem> Ideas);
|
||||
@@ -13,6 +13,8 @@ public sealed class McpTokenAuthenticationHandler(
|
||||
{
|
||||
public const string SchemeName = "McpToken";
|
||||
|
||||
public const string WriteClaim = "mcp:write";
|
||||
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var header = Request.Headers.Authorization.ToString();
|
||||
@@ -21,12 +23,17 @@ public sealed class McpTokenAuthenticationHandler(
|
||||
return AuthenticateResult.NoResult();
|
||||
}
|
||||
|
||||
if (!await tokens.ValidateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted))
|
||||
if (await tokens.AuthenticateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted) is not { } access)
|
||||
{
|
||||
return AuthenticateResult.Fail("Invalid MCP token.");
|
||||
}
|
||||
|
||||
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "mcp")], SchemeName);
|
||||
if (access == McpAccess.Write)
|
||||
{
|
||||
identity.AddClaim(new Claim(WriteClaim, "true"));
|
||||
}
|
||||
|
||||
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName));
|
||||
}
|
||||
|
||||
|
||||
@@ -6,33 +6,41 @@ using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Web.Mcp;
|
||||
|
||||
public enum McpAccess
|
||||
{
|
||||
Read,
|
||||
Write
|
||||
}
|
||||
|
||||
public sealed class McpTokenService(McpTokenStore store, IOptions<McpOptions> options)
|
||||
{
|
||||
private const string Prefix = "fpm_";
|
||||
|
||||
public bool UsesEnvironmentToken => !string.IsNullOrEmpty(options.Value.Token);
|
||||
|
||||
public async Task<string> CreateAsync(string name, CancellationToken ct = default)
|
||||
public async Task<string> CreateAsync(string name, bool canWrite = false, CancellationToken ct = default)
|
||||
{
|
||||
var token = Prefix + WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
|
||||
await store.CreateAsync(name, Hash(token), ct);
|
||||
await store.CreateAsync(name, Hash(token), canWrite, ct);
|
||||
return token;
|
||||
}
|
||||
|
||||
public async Task<bool> ValidateAsync(string? token, CancellationToken ct = default)
|
||||
public async Task<McpAccess?> AuthenticateAsync(string? token, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (UsesEnvironmentToken
|
||||
&& CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(token)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Value.Token!))))
|
||||
{
|
||||
return true;
|
||||
return McpAccess.Read;
|
||||
}
|
||||
|
||||
return await store.UseAsync(Hash(token), ct) is not null;
|
||||
return await store.UseAsync(Hash(token), ct) is { } stored
|
||||
? stored.CanWrite ? McpAccess.Write : McpAccess.Read
|
||||
: null;
|
||||
}
|
||||
|
||||
public static string Hash(string token) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Flypaper.Storage.Research;
|
||||
using ModelContextProtocol;
|
||||
using ModelContextProtocol.Server;
|
||||
|
||||
namespace Flypaper.Web.Mcp;
|
||||
|
||||
[McpServerToolType]
|
||||
public sealed class ResearchTools(ResearchStore store)
|
||||
{
|
||||
private const string KindDescription = "experiment, observation, hypothesis or method (measurement method).";
|
||||
private const string LevelDescription = "low, medium or high.";
|
||||
private const string StatusDescription = "open, in_progress, done or dropped.";
|
||||
private const string DateDescription = "ISO 8601 date, e.g. 2026-11-17. Defaults to today.";
|
||||
private const string CommitDescription = "Git commit hash. An empty string removes it.";
|
||||
private const string StrategiesDescription = "Names of the strategies concerned, e.g. maze-drip, git-drip, robots-bait. An empty list removes them.";
|
||||
|
||||
[McpServerTool(Name = "list_entries", Title = "List lab notebook entries", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Entries of the lab notebook on the Erkenntnisse page (experiments, observations, hypotheses, measurement methods), newest first. Text is Markdown.")]
|
||||
public async Task<EntryListResult> ListEntries(
|
||||
[Description("Only this kind: " + KindDescription)] string? kind = null,
|
||||
[Description("Only entries that concern this strategy name.")] string? strategy = null,
|
||||
[Description("Maximum number of entries, 1 to 500.")] int limit = 100,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var entries = (await store.ListEntriesAsync(kind is null ? null : ParseKind(kind), strategy, limit, ct)).Select(ToItem).ToList();
|
||||
return new EntryListResult(entries.Count, entries);
|
||||
}
|
||||
|
||||
[McpServerTool(Name = "list_ideas", Title = "List ideas", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Ideas for improving the tarpit with effort, efficiency and status, sorted by effort (lowest first).")]
|
||||
public async Task<IdeaListResult> ListIdeas(
|
||||
[Description("Only this status: " + StatusDescription)] string? status = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var ideas = (await store.ListIdeasAsync(status is null ? null : ParseStatus(status), ct)).Select(ToItem).ToList();
|
||||
return new IdeaListResult(ideas.Count, ideas);
|
||||
}
|
||||
|
||||
[McpServerTool(Name = "create_entry", Title = "Create lab notebook entry", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Adds an entry to the lab notebook. Needs a token with write permission.")]
|
||||
public async Task<EntryItem> CreateEntry(
|
||||
[Description("Short title, at most 200 characters.")] string title,
|
||||
[Description("Kind: " + KindDescription)] string kind,
|
||||
[Description("Markdown text; raw HTML is not rendered.")] string text,
|
||||
[Description(DateDescription)] string? date = null,
|
||||
[Description("Git commit hash.")] string? commit = null,
|
||||
[Description(StrategiesDescription)] string[]? strategies = null,
|
||||
CancellationToken ct = default) =>
|
||||
ToItem(await store.CreateEntryAsync(new LabEntryInput(title, ParseKind(kind), text, ParseDate(date), commit, strategies), ct));
|
||||
|
||||
[McpServerTool(Name = "update_entry", Title = "Update lab notebook entry", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Changes an entry of the lab notebook; only the given fields are changed. Needs a token with write permission.")]
|
||||
public async Task<EntryItem> UpdateEntry(
|
||||
[Description("Id of the entry.")] int id,
|
||||
[Description("New title.")] string? title = null,
|
||||
[Description("New kind: " + KindDescription)] string? kind = null,
|
||||
[Description("New Markdown text.")] string? text = null,
|
||||
[Description("New date: " + DateDescription)] string? date = null,
|
||||
[Description(CommitDescription)] string? commit = null,
|
||||
[Description(StrategiesDescription)] string[]? strategies = null,
|
||||
CancellationToken ct = default) =>
|
||||
ToItem(await store.UpdateEntryAsync(
|
||||
id,
|
||||
new LabEntryInput(title, kind is null ? null : ParseKind(kind), text, ParseDate(date), commit, strategies),
|
||||
ct) ?? throw NotFound("entry", id));
|
||||
|
||||
[McpServerTool(Name = "create_idea", Title = "Create idea", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Adds an idea for improving the tarpit. Needs a token with write permission.")]
|
||||
public async Task<IdeaItem> CreateIdea(
|
||||
[Description("Short title, at most 200 characters.")] string title,
|
||||
[Description("Effort: " + LevelDescription)] string effort,
|
||||
[Description("Expected efficiency: " + LevelDescription)] string efficiency,
|
||||
[Description("Why this might work, in Markdown.")] string rationale,
|
||||
[Description("Status: " + StatusDescription + " Defaults to open.")] string? status = null,
|
||||
[Description(CommitDescription)] string? commit = null,
|
||||
CancellationToken ct = default) =>
|
||||
ToItem(await store.CreateIdeaAsync(
|
||||
new IdeaInput(title, ParseLevel(effort, nameof(effort)), ParseLevel(efficiency, nameof(efficiency)), rationale, status is null ? null : ParseStatus(status), null, commit),
|
||||
ct));
|
||||
|
||||
[McpServerTool(Name = "update_idea", Title = "Update idea", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Changes an idea; only the given fields are changed. Needs a token with write permission.")]
|
||||
public async Task<IdeaItem> UpdateIdea(
|
||||
[Description("Id of the idea.")] int id,
|
||||
[Description("New title.")] string? title = null,
|
||||
[Description("New effort: " + LevelDescription)] string? effort = null,
|
||||
[Description("New efficiency: " + LevelDescription)] string? efficiency = null,
|
||||
[Description("New rationale in Markdown.")] string? rationale = null,
|
||||
[Description("New status: " + StatusDescription)] string? status = null,
|
||||
[Description("Date of implementation: " + DateDescription)] string? implemented_on = null,
|
||||
[Description(CommitDescription)] string? commit = null,
|
||||
CancellationToken ct = default) =>
|
||||
ToItem(await store.UpdateIdeaAsync(
|
||||
id,
|
||||
new IdeaInput(
|
||||
title,
|
||||
effort is null ? null : ParseLevel(effort, nameof(effort)),
|
||||
efficiency is null ? null : ParseLevel(efficiency, nameof(efficiency)),
|
||||
rationale,
|
||||
status is null ? null : ParseStatus(status),
|
||||
ParseDate(implemented_on),
|
||||
commit),
|
||||
ct) ?? throw NotFound("idea", id));
|
||||
|
||||
[McpServerTool(Name = "set_idea_status", Title = "Set idea status", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Sets the status of an idea. Status done records the implementation date (today unless given). Needs a token with write permission.")]
|
||||
public async Task<IdeaItem> SetIdeaStatus(
|
||||
[Description("Id of the idea.")] int id,
|
||||
[Description("Status: " + StatusDescription)] string status,
|
||||
[Description("Date of implementation, only for done: " + DateDescription)] string? implemented_on = null,
|
||||
[Description(CommitDescription)] string? commit = null,
|
||||
CancellationToken ct = default) =>
|
||||
ToItem(await store.UpdateIdeaAsync(id, new IdeaInput(Status: ParseStatus(status), ImplementedOn: ParseDate(implemented_on), Commit: commit), ct)
|
||||
?? throw NotFound("idea", id));
|
||||
|
||||
private static McpException NotFound(string what, int id) => new($"There is no {what} with id {id}.");
|
||||
|
||||
internal static LabEntryKind ParseKind(string value) =>
|
||||
value.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"experiment" => LabEntryKind.Experiment,
|
||||
"observation" => LabEntryKind.Observation,
|
||||
"hypothesis" => LabEntryKind.Hypothesis,
|
||||
"method" => LabEntryKind.Method,
|
||||
_ => throw new ArgumentException("kind must be one of experiment, observation, hypothesis, method.")
|
||||
};
|
||||
|
||||
internal static IdeaLevel ParseLevel(string value, string name) =>
|
||||
value.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"low" => IdeaLevel.Low,
|
||||
"medium" => IdeaLevel.Medium,
|
||||
"high" => IdeaLevel.High,
|
||||
_ => throw new ArgumentException($"{name} must be one of low, medium, high.")
|
||||
};
|
||||
|
||||
internal static IdeaStatus ParseStatus(string value) =>
|
||||
value.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"open" => IdeaStatus.Open,
|
||||
"in_progress" => IdeaStatus.InProgress,
|
||||
"done" => IdeaStatus.Done,
|
||||
"dropped" => IdeaStatus.Dropped,
|
||||
_ => throw new ArgumentException("status must be one of open, in_progress, done, dropped.")
|
||||
};
|
||||
|
||||
private static DateTime? ParseDate(string? value) =>
|
||||
string.IsNullOrWhiteSpace(value) ? null
|
||||
: DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var date)
|
||||
? date
|
||||
: throw new ArgumentException("Dates must be ISO 8601, e.g. 2026-11-17.");
|
||||
|
||||
private static string Name(LabEntryKind kind) => kind.ToString().ToLowerInvariant();
|
||||
|
||||
private static string Name(IdeaLevel level) => level.ToString().ToLowerInvariant();
|
||||
|
||||
private static string Name(IdeaStatus status) => status switch
|
||||
{
|
||||
IdeaStatus.InProgress => "in_progress",
|
||||
_ => status.ToString().ToLowerInvariant()
|
||||
};
|
||||
|
||||
private static EntryItem ToItem(LabEntryEntity entry) => new(
|
||||
entry.Id,
|
||||
DateOnly.FromDateTime(entry.Date),
|
||||
entry.Title,
|
||||
Name(entry.Kind),
|
||||
entry.Text,
|
||||
entry.Commit,
|
||||
entry.StrategyList,
|
||||
entry.CreatedAt,
|
||||
entry.UpdatedAt);
|
||||
|
||||
private static IdeaItem ToItem(IdeaEntity idea) => new(
|
||||
idea.Id,
|
||||
idea.Title,
|
||||
Name(idea.Effort),
|
||||
Name(idea.Efficiency),
|
||||
idea.Rationale,
|
||||
Name(idea.Status),
|
||||
idea.ImplementedOn is { } date ? DateOnly.FromDateTime(date) : null,
|
||||
idea.Commit,
|
||||
idea.CreatedAt,
|
||||
idea.UpdatedAt);
|
||||
}
|
||||
@@ -22,6 +22,8 @@
|
||||
"MaxConnections": 1000,
|
||||
"MaxConnectionsPerIp": 10,
|
||||
"MaxHoldDuration": "01:00:00",
|
||||
"RepeatWindowDays": 7,
|
||||
"RepeatHoldDuration": "1.00:00:00",
|
||||
"Http": {
|
||||
"TrustedProxies": []
|
||||
}
|
||||
|
||||
@@ -1585,3 +1585,117 @@ button.danger-text {
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.table-scroll {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.chips a.chip {
|
||||
padding: 3px 10px;
|
||||
border-color: var(--border);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.chips a.chip:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.chips a.chip.active {
|
||||
border-color: color-mix(in srgb, var(--accent) 45%, var(--border));
|
||||
background: color-mix(in srgb, var(--accent) 10%, transparent);
|
||||
}
|
||||
|
||||
.lab-entries {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.lab-entry {
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.lab-entry header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 10px;
|
||||
}
|
||||
|
||||
.lab-entry h3 {
|
||||
flex: 1 1 100%;
|
||||
margin: 2px 0 0;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.lab-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 6px 0 0;
|
||||
}
|
||||
|
||||
.markdown {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.markdown > :first-child {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.markdown > :last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.markdown h1,
|
||||
.markdown h2,
|
||||
.markdown h3,
|
||||
.markdown h4 {
|
||||
margin: 12px 0 4px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.markdown pre {
|
||||
padding: 8px 10px;
|
||||
overflow-x: auto;
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.markdown table {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.idea-table td {
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.idea-table .markdown {
|
||||
margin-top: 2px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.badge.status-done {
|
||||
border-color: var(--ok);
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
.badge.status-dropped {
|
||||
border-color: var(--muted);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.inline-form {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 10px;
|
||||
}
|
||||
|
||||
.inline-check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
Reference in new issue
Block a user