From e88dc415f9c8bbf519c34d175cbeb291d777fd56 Mon Sep 17 00:00:00 2001 From: Tom Date: Tue, 17 Nov 2026 18:27:35 +0100 Subject: [PATCH] Add research page with MCP write tools, longer hold for repeat offenders and svn/hg decoys Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 ++ Directory.Packages.props | 1 + .../Abstractions/IRepeatOffenderLookup.cs | 8 + src/Flypaper.Core/FlypaperCoreExtensions.cs | 1 + src/Flypaper.Core/FlypaperOptions.cs | 4 + .../Networking/NullRepeatOffenderLookup.cs | 9 + src/Flypaper.Core/Runtime/TrapRunner.cs | 9 + .../Settings/HoldMethodSettings.cs | 12 +- .../Settings/RuntimeSettingsParser.cs | 9 +- src/Flypaper.Core/Settings/SettingKeys.cs | 4 +- src/Flypaper.Core/Strategies/FileContent.cs | 30 ++- src/Flypaper.Storage/Entities/IdeaEntity.cs | 41 +++ .../Entities/LabEntryEntity.cs | 33 +++ .../Entities/McpTokenEntity.cs | 2 + src/Flypaper.Storage/FlypaperDbContext.cs | 22 ++ .../FlypaperStorageExtensions.cs | 3 + .../20261117165523_AddResearch.Designer.cs | 248 ++++++++++++++++++ .../Migrations/20261117165523_AddResearch.cs | 82 ++++++ .../FlypaperDbContextModelSnapshot.cs | 97 +++++++ .../Queries/RepeatOffenderLookup.cs | 16 ++ src/Flypaper.Storage/Research/LabLimits.cs | 10 + .../Research/ResearchStore.cs | 247 +++++++++++++++++ .../Settings/McpTokenStore.cs | 10 +- .../Components/Layout/MainLayout.razor | 1 + .../Components/Pages/Research/IdeaTable.razor | 58 ++++ .../Pages/Research/ResearchPage.razor | 139 ++++++++++ .../Pages/Settings/HoldMethodModel.cs | 4 + .../Pages/Settings/HoldMethodSection.razor | 14 +- .../Pages/Settings/McpSection.razor | 26 +- .../Pages/Settings/McpTokenModel.cs | 2 + .../Components/Shared/MarkdownRenderer.cs | 57 ++++ src/Flypaper.Web/Flypaper.Web.csproj | 1 + src/Flypaper.Web/Mcp/McpExtensions.cs | 91 +++++-- src/Flypaper.Web/Mcp/McpResults.cs | 27 ++ .../Mcp/McpTokenAuthenticationHandler.cs | 9 +- src/Flypaper.Web/Mcp/McpTokenService.cs | 20 +- src/Flypaper.Web/Mcp/ResearchTools.cs | 188 +++++++++++++ src/Flypaper.Web/appsettings.json | 2 + src/Flypaper.Web/wwwroot/app.css | 114 ++++++++ test/Flypaper.Tests/Core/FileContentTests.cs | 21 ++ .../Core/HoldMethodParserTests.cs | 33 ++- test/Flypaper.Tests/Core/TrapRunnerTests.cs | 68 ++++- test/Flypaper.Tests/Mcp/McpEndpointTests.cs | 43 ++- .../Mcp/McpTokenServiceTests.cs | 31 ++- .../Storage/RepeatOffenderLookupTests.cs | 44 ++++ .../Storage/ResearchStoreTests.cs | 79 ++++++ .../Storage/SettingsOverrideTests.cs | 4 +- .../Web/MarkdownRendererTests.cs | 50 ++++ 48 files changed, 1983 insertions(+), 57 deletions(-) create mode 100644 src/Flypaper.Core/Abstractions/IRepeatOffenderLookup.cs create mode 100644 src/Flypaper.Core/Networking/NullRepeatOffenderLookup.cs create mode 100644 src/Flypaper.Storage/Entities/IdeaEntity.cs create mode 100644 src/Flypaper.Storage/Entities/LabEntryEntity.cs create mode 100644 src/Flypaper.Storage/Migrations/20261117165523_AddResearch.Designer.cs create mode 100644 src/Flypaper.Storage/Migrations/20261117165523_AddResearch.cs create mode 100644 src/Flypaper.Storage/Queries/RepeatOffenderLookup.cs create mode 100644 src/Flypaper.Storage/Research/LabLimits.cs create mode 100644 src/Flypaper.Storage/Research/ResearchStore.cs create mode 100644 src/Flypaper.Web/Components/Pages/Research/IdeaTable.razor create mode 100644 src/Flypaper.Web/Components/Pages/Research/ResearchPage.razor create mode 100644 src/Flypaper.Web/Components/Shared/MarkdownRenderer.cs create mode 100644 src/Flypaper.Web/Mcp/ResearchTools.cs create mode 100644 test/Flypaper.Tests/Storage/RepeatOffenderLookupTests.cs create mode 100644 test/Flypaper.Tests/Storage/ResearchStoreTests.cs create mode 100644 test/Flypaper.Tests/Web/MarkdownRendererTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 73f5f5e..fc89466 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,22 @@ All notable changes to Flypaper are documented in this file. The format follows ### Added +- Version-control file profiles: `git-drip` now answers every `.git` variant (`/.git`, `/.git/…`, `.gitconfig`, + `.git-credentials`, `.gitignore` …), new `svn-drip` (`/.svn/…`: `format`, `entries`, `wc.db`) and `hg-drip` + (`/.hg/…`: `requires`, `store/requires`) serve plausible, endless files that start like the real ones. +- Repeat offenders: an IP that was already held until the limit (outcome `Timeout`) within the last + `Flypaper__RepeatWindowDays` days (default 7, `0` = off) is held for `Flypaper__RepeatHoldDuration` + (default 1 day) instead of the maximum hold duration. The catch's strategy gets the suffix `repeat`, so + it can be compared in the dashboard. Both values are adjustable under „Haltemethode“ on the settings page. +- Page „Erkenntnisse“ (`/erkenntnisse`, in the navigation): a lab notebook (date, title, kind experiment / + observation / hypothesis / measurement method, Markdown text, optional commit and strategy names; newest + first, filterable by kind) and an idea table (effort, efficiency, rationale, status open / in progress / + done / dropped, implementation date and commit; sorted by effort, done and dropped ones can be shown). + Markdown is rendered with Markdig without raw HTML and with only http, https and mailto links. +- MCP: new read tools `list_entries` and `list_ideas` and write tools `create_entry`, `update_entry`, + `create_idea`, `update_idea`, `set_idea_status`. Writing needs a token with write permission, set when + creating the token or later on the settings page (new „Zugriff“ column). Existing tokens and the token from + `Flypaper__Mcp__Token` stay read-only, and read-only tokens do not even see the write tools. - Link labyrinth: the HTML page (strategy `maze-drip`, with `link B` suffix) carries about ten links already in the head start and then a new link every `LinkSpacing` bytes (default 160, `0` = old `html-drip`). Links match the requested path and host (`/wiki/…`, `/docs/v2/…`, `/blog/2025/03/…`, diff --git a/Directory.Packages.props b/Directory.Packages.props index 2c10719..7c5c78a 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -10,6 +10,7 @@ + diff --git a/src/Flypaper.Core/Abstractions/IRepeatOffenderLookup.cs b/src/Flypaper.Core/Abstractions/IRepeatOffenderLookup.cs new file mode 100644 index 0000000..8d4be7e --- /dev/null +++ b/src/Flypaper.Core/Abstractions/IRepeatOffenderLookup.cs @@ -0,0 +1,8 @@ +using System.Net; + +namespace Flypaper.Core.Abstractions; + +public interface IRepeatOffenderLookup +{ + ValueTask HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct); +} diff --git a/src/Flypaper.Core/FlypaperCoreExtensions.cs b/src/Flypaper.Core/FlypaperCoreExtensions.cs index 3cf5939..561cbce 100644 --- a/src/Flypaper.Core/FlypaperCoreExtensions.cs +++ b/src/Flypaper.Core/FlypaperCoreExtensions.cs @@ -43,6 +43,7 @@ public static class FlypaperCoreExtensions services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); + services.TryAddSingleton(); return services; } diff --git a/src/Flypaper.Core/FlypaperOptions.cs b/src/Flypaper.Core/FlypaperOptions.cs index 5e3b0b7..2dea04e 100644 --- a/src/Flypaper.Core/FlypaperOptions.cs +++ b/src/Flypaper.Core/FlypaperOptions.cs @@ -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; } diff --git a/src/Flypaper.Core/Networking/NullRepeatOffenderLookup.cs b/src/Flypaper.Core/Networking/NullRepeatOffenderLookup.cs new file mode 100644 index 0000000..3cfad8b --- /dev/null +++ b/src/Flypaper.Core/Networking/NullRepeatOffenderLookup.cs @@ -0,0 +1,9 @@ +using System.Net; +using Flypaper.Core.Abstractions; + +namespace Flypaper.Core.Networking; + +internal sealed class NullRepeatOffenderLookup : IRepeatOffenderLookup +{ + public ValueTask HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct) => ValueTask.FromResult(false); +} diff --git a/src/Flypaper.Core/Runtime/TrapRunner.cs b/src/Flypaper.Core/Runtime/TrapRunner.cs index cf8f080..870ac0b 100644 --- a/src/Flypaper.Core/Runtime/TrapRunner.cs +++ b/src/Flypaper.Core/Runtime/TrapRunner.cs @@ -11,6 +11,7 @@ public sealed partial class TrapRunner( IConnectionGovernor governor, ITrapStrategySelector strategies, ITrapEventSink sink, + IRepeatOffenderLookup repeatOffenders, IOptionsMonitor options, TimeProvider timeProvider, ILogger 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); diff --git a/src/Flypaper.Core/Settings/HoldMethodSettings.cs b/src/Flypaper.Core/Settings/HoldMethodSettings.cs index 880ae73..822f431 100644 --- a/src/Flypaper.Core/Settings/HoldMethodSettings.cs +++ b/src/Flypaper.Core/Settings/HoldMethodSettings.cs @@ -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 Errors); diff --git a/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs b/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs index 2900a31..40358f6 100644 --- a/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs +++ b/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs @@ -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; } diff --git a/src/Flypaper.Core/Settings/SettingKeys.cs b/src/Flypaper.Core/Settings/SettingKeys.cs index c69f48f..bd67ac0 100644 --- a/src/Flypaper.Core/Settings/SettingKeys.cs +++ b/src/Flypaper.Core/Settings/SettingKeys.cs @@ -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 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 All = new HashSet(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase); diff --git a/src/Flypaper.Core/Strategies/FileContent.cs b/src/Flypaper.Core/Strategies/FileContent.cs index 4b3ee50..69ace17 100644 --- a/src/Flypaper.Core/Strategies/FileContent.cs +++ b/src/Flypaper.Core/Strategies/FileContent.cs @@ -13,7 +13,9 @@ public static class FileContent { public static readonly IReadOnlyList 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 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 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]; diff --git a/src/Flypaper.Storage/Entities/IdeaEntity.cs b/src/Flypaper.Storage/Entities/IdeaEntity.cs new file mode 100644 index 0000000..f6579c0 --- /dev/null +++ b/src/Flypaper.Storage/Entities/IdeaEntity.cs @@ -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; +} diff --git a/src/Flypaper.Storage/Entities/LabEntryEntity.cs b/src/Flypaper.Storage/Entities/LabEntryEntity.cs new file mode 100644 index 0000000..1b5699b --- /dev/null +++ b/src/Flypaper.Storage/Entities/LabEntryEntity.cs @@ -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 StrategyList => + (Strategies ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); +} diff --git a/src/Flypaper.Storage/Entities/McpTokenEntity.cs b/src/Flypaper.Storage/Entities/McpTokenEntity.cs index c2143f4..a066945 100644 --- a/src/Flypaper.Storage/Entities/McpTokenEntity.cs +++ b/src/Flypaper.Storage/Entities/McpTokenEntity.cs @@ -11,4 +11,6 @@ public sealed class McpTokenEntity public DateTime CreatedAt { get; set; } public DateTime? LastUsedAt { get; set; } + + public bool CanWrite { get; set; } } diff --git a/src/Flypaper.Storage/FlypaperDbContext.cs b/src/Flypaper.Storage/FlypaperDbContext.cs index 7a1739b..e008652 100644 --- a/src/Flypaper.Storage/FlypaperDbContext.cs +++ b/src/Flypaper.Storage/FlypaperDbContext.cs @@ -14,6 +14,10 @@ public sealed class FlypaperDbContext(DbContextOptions option public DbSet McpTokens => Set(); + public DbSet LabEntries => Set(); + + public DbSet Ideas => Set(); + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) => configurationBuilder.Properties().HaveConversion(); @@ -43,5 +47,23 @@ public sealed class FlypaperDbContext(DbContextOptions 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(); + labEntry.Property(e => e.Title).HasMaxLength(LabLimits.TitleLength); + labEntry.Property(e => e.Kind).HasConversion().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(); + idea.Property(e => e.Title).HasMaxLength(LabLimits.TitleLength); + idea.Property(e => e.Effort).HasConversion().HasMaxLength(16); + idea.Property(e => e.Efficiency).HasConversion().HasMaxLength(16); + idea.Property(e => e.Rationale).HasMaxLength(LabLimits.TextLength); + idea.Property(e => e.Status).HasConversion().HasMaxLength(16); + idea.Property(e => e.Commit).HasMaxLength(LabLimits.CommitLength); + idea.Ignore(e => e.IsClosed); } } diff --git a/src/Flypaper.Storage/FlypaperStorageExtensions.cs b/src/Flypaper.Storage/FlypaperStorageExtensions.cs index 6b361a4..1a2e6c9 100644 --- a/src/Flypaper.Storage/FlypaperStorageExtensions.cs +++ b/src/Flypaper.Storage/FlypaperStorageExtensions.cs @@ -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(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.Configure(builder.Configuration.GetSection(RetentionOptions.SectionName)); builder.Services.AddFlypaperStorage(connectionString); @@ -38,6 +40,7 @@ public static class FlypaperStorageExtensions services.AddHostedService(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddHostedService(); return services; diff --git a/src/Flypaper.Storage/Migrations/20261117165523_AddResearch.Designer.cs b/src/Flypaper.Storage/Migrations/20261117165523_AddResearch.Designer.cs new file mode 100644 index 0000000..740cdc3 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261117165523_AddResearch.Designer.cs @@ -0,0 +1,248 @@ +// +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 + { + /// + 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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Commit") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Efficiency") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Effort") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ImplementedOn") + .HasColumnType("TEXT"); + + b.Property("Rationale") + .IsRequired() + .HasMaxLength(20000) + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Ideas"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.LabEntryEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Commit") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Date") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Strategies") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(20000) + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Date"); + + b.ToTable("LabEntries"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CanWrite") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("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("Key") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Value") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("Settings"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Asn") + .HasColumnType("INTEGER"); + + b.Property("BytesSent") + .HasColumnType("INTEGER"); + + b.Property("City") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ClientInfo") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("Country") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("CountryCode") + .HasMaxLength(2) + .HasColumnType("TEXT"); + + b.Property("DurationMs") + .HasColumnType("INTEGER"); + + b.Property("EndedAt") + .HasColumnType("TEXT"); + + b.Property("Outcome") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Provider") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SessionId") + .HasColumnType("TEXT"); + + b.Property("StartedAt") + .HasColumnType("TEXT"); + + b.Property("Strategy") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("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 + } + } +} diff --git a/src/Flypaper.Storage/Migrations/20261117165523_AddResearch.cs b/src/Flypaper.Storage/Migrations/20261117165523_AddResearch.cs new file mode 100644 index 0000000..13b4ab9 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261117165523_AddResearch.cs @@ -0,0 +1,82 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Flypaper.Storage.Migrations +{ + /// + public partial class AddResearch : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "CanWrite", + table: "McpTokens", + type: "INTEGER", + nullable: false, + defaultValue: false); + + migrationBuilder.CreateTable( + name: "Ideas", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Title = table.Column(type: "TEXT", maxLength: 200, nullable: false), + Effort = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Efficiency = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Rationale = table.Column(type: "TEXT", maxLength: 20000, nullable: false), + Status = table.Column(type: "TEXT", maxLength: 16, nullable: false), + ImplementedOn = table.Column(type: "TEXT", nullable: true), + Commit = table.Column(type: "TEXT", maxLength: 64, nullable: true), + CreatedAt = table.Column(type: "TEXT", nullable: false), + UpdatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Ideas", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "LabEntries", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Date = table.Column(type: "TEXT", nullable: false), + Title = table.Column(type: "TEXT", maxLength: 200, nullable: false), + Kind = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Text = table.Column(type: "TEXT", maxLength: 20000, nullable: false), + Commit = table.Column(type: "TEXT", maxLength: 64, nullable: true), + Strategies = table.Column(type: "TEXT", maxLength: 512, nullable: true), + CreatedAt = table.Column(type: "TEXT", nullable: false), + UpdatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_LabEntries", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_LabEntries_Date", + table: "LabEntries", + column: "Date"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Ideas"); + + migrationBuilder.DropTable( + name: "LabEntries"); + + migrationBuilder.DropColumn( + name: "CanWrite", + table: "McpTokens"); + } + } +} diff --git a/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs b/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs index e02f387..4ca173a 100644 --- a/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs +++ b/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs @@ -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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Commit") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Efficiency") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Effort") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ImplementedOn") + .HasColumnType("TEXT"); + + b.Property("Rationale") + .IsRequired() + .HasMaxLength(20000) + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Ideas"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.LabEntryEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Commit") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Date") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Strategies") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(20000) + .HasColumnType("TEXT"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Date"); + + b.ToTable("LabEntries"); + }); + modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b => { b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); + b.Property("CanWrite") + .HasColumnType("INTEGER"); + b.Property("CreatedAt") .HasColumnType("TEXT"); diff --git a/src/Flypaper.Storage/Queries/RepeatOffenderLookup.cs b/src/Flypaper.Storage/Queries/RepeatOffenderLookup.cs new file mode 100644 index 0000000..4d15894 --- /dev/null +++ b/src/Flypaper.Storage/Queries/RepeatOffenderLookup.cs @@ -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 dbContextFactory) : IRepeatOffenderLookup +{ + public async ValueTask 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); + } +} diff --git a/src/Flypaper.Storage/Research/LabLimits.cs b/src/Flypaper.Storage/Research/LabLimits.cs new file mode 100644 index 0000000..8c254d6 --- /dev/null +++ b/src/Flypaper.Storage/Research/LabLimits.cs @@ -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; +} diff --git a/src/Flypaper.Storage/Research/ResearchStore.cs b/src/Flypaper.Storage/Research/ResearchStore.cs new file mode 100644 index 0000000..7570ba5 --- /dev/null +++ b/src/Flypaper.Storage/Research/ResearchStore.cs @@ -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? 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 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> 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 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 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> 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 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 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? 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."); + } +} diff --git a/src/Flypaper.Storage/Settings/McpTokenStore.cs b/src/Flypaper.Storage/Settings/McpTokenStore.cs index 83c8894..89396a1 100644 --- a/src/Flypaper.Storage/Settings/McpTokenStore.cs +++ b/src/Flypaper.Storage/Settings/McpTokenStore.cs @@ -13,10 +13,10 @@ public sealed class McpTokenStore(IDbContextFactory dbContext return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct); } - public async Task CreateAsync(string name, string tokenHash, CancellationToken ct = default) + public async Task 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 dbContext return await db.McpTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct) > 0; } + public async Task 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 UseAsync(string tokenHash, CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); diff --git a/src/Flypaper.Web/Components/Layout/MainLayout.razor b/src/Flypaper.Web/Components/Layout/MainLayout.razor index 35adbc5..fa954d2 100644 --- a/src/Flypaper.Web/Components/Layout/MainLayout.razor +++ b/src/Flypaper.Web/Components/Layout/MainLayout.razor @@ -4,6 +4,7 @@