Add read-only MCP server with token access
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b8328f6998
commit
49a8fa1154
34 files changed
+1625
No files matched your search
@@ -0,0 +1,14 @@
|
||||
namespace Flypaper.Storage.Entities;
|
||||
|
||||
public sealed class McpTokenEntity
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public required string Name { get; set; }
|
||||
|
||||
public required string TokenHash { get; set; }
|
||||
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
public DateTime? LastUsedAt { get; set; }
|
||||
}
|
||||
@@ -12,6 +12,8 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
||||
|
||||
public DbSet<SettingEntity> Settings => Set<SettingEntity>();
|
||||
|
||||
public DbSet<McpTokenEntity> McpTokens => Set<McpTokenEntity>();
|
||||
|
||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
|
||||
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
|
||||
|
||||
@@ -36,5 +38,10 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
||||
var setting = modelBuilder.Entity<SettingEntity>();
|
||||
setting.HasKey(e => e.Key);
|
||||
setting.Property(e => e.Key).HasMaxLength(128);
|
||||
|
||||
var mcpToken = modelBuilder.Entity<McpTokenEntity>();
|
||||
mcpToken.Property(e => e.Name).HasMaxLength(100);
|
||||
mcpToken.Property(e => e.TokenHash).HasMaxLength(64);
|
||||
mcpToken.HasIndex(e => e.TokenHash).IsUnique();
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Storage.Dashboard;
|
||||
using Flypaper.Storage.Events;
|
||||
using Flypaper.Storage.Maintenance;
|
||||
using Flypaper.Storage.Queries;
|
||||
using Flypaper.Storage.Settings;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@@ -21,6 +22,7 @@ public static class FlypaperStorageExtensions
|
||||
builder.Services.AddSingleton(source);
|
||||
builder.Services.AddSingleton<RuntimeSettingsStore>();
|
||||
builder.Services.AddSingleton<AdminCredentialStore>();
|
||||
builder.Services.AddSingleton<McpTokenStore>();
|
||||
builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName));
|
||||
builder.Services.AddFlypaperStorage(connectionString);
|
||||
|
||||
@@ -35,6 +37,7 @@ public static class FlypaperStorageExtensions
|
||||
services.AddHostedService<TrapEventWriter>();
|
||||
services.AddHostedService<OriginBackfill>();
|
||||
services.AddSingleton<DashboardQueries>();
|
||||
services.AddSingleton<CatchQueries>();
|
||||
services.AddSingleton<TrapDataMaintenance>();
|
||||
services.AddHostedService<RetentionCleanup>();
|
||||
return services;
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Flypaper.Storage;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Flypaper.Storage.Migrations
|
||||
{
|
||||
[DbContext(typeof(FlypaperDbContext))]
|
||||
[Migration("20261115122552_AddMcpTokens")]
|
||||
partial class AddMcpTokens
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime?>("LastUsedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("McpTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("Settings");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("Asn")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("BytesSent")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("City")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("ClientInfo")
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Country")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("CountryCode")
|
||||
.HasMaxLength(2)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("DurationMs")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<DateTime>("EndedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Outcome")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Protocol")
|
||||
.IsRequired()
|
||||
.HasMaxLength(16)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Provider")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("RemoteIp")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("SessionId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime>("StartedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Strategy")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Target")
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Asn");
|
||||
|
||||
b.HasIndex("CountryCode");
|
||||
|
||||
b.HasIndex("RemoteIp");
|
||||
|
||||
b.HasIndex("StartedAt");
|
||||
|
||||
b.ToTable("TrapEvents");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Flypaper.Storage.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddMcpTokens : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "McpTokens",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "INTEGER", nullable: false)
|
||||
.Annotation("Sqlite:Autoincrement", true),
|
||||
Name = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
|
||||
TokenHash = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
LastUsedAt = table.Column<DateTime>(type: "TEXT", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_McpTokens", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_McpTokens_TokenHash",
|
||||
table: "McpTokens",
|
||||
column: "TokenHash",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "McpTokens");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,36 @@ namespace Flypaper.Storage.Migrations
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTime?>("LastUsedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("McpTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
using System.Globalization;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Flypaper.Storage.Queries;
|
||||
|
||||
public sealed class CatchQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory)
|
||||
{
|
||||
public const int MaxLimit = 500;
|
||||
|
||||
public async Task<CatchStats> GetStatsAsync(DateTime? since, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var events = InPeriod(db, since);
|
||||
var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected);
|
||||
|
||||
var count = await catches.CountAsync(ct);
|
||||
var totalMs = count == 0 ? 0 : await catches.SumAsync(e => e.DurationMs, ct);
|
||||
var longest = await catches.OrderByDescending(e => e.DurationMs).ThenByDescending(e => e.Id).FirstOrDefaultAsync(ct);
|
||||
|
||||
return new CatchStats(
|
||||
count,
|
||||
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct),
|
||||
await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct),
|
||||
totalMs / 1000d,
|
||||
count == 0 ? 0 : totalMs / 1000d / count,
|
||||
longest is null ? null : ToRecord(longest));
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<CatchRecord>> ListAsync(CatchFilter filter, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var events = InPeriod(db, filter.Since);
|
||||
|
||||
if (filter.Until is { } until)
|
||||
{
|
||||
events = events.Where(e => e.StartedAt < until);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(filter.Country))
|
||||
{
|
||||
var country = filter.Country.Trim().ToUpperInvariant();
|
||||
events = events.Where(e => e.CountryCode == country);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(filter.Provider))
|
||||
{
|
||||
events = ByProvider(events, filter.Provider.Trim());
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(filter.Ip))
|
||||
{
|
||||
var ip = filter.Ip.Trim();
|
||||
events = events.Where(e => e.RemoteIp == ip);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(filter.TargetContains))
|
||||
{
|
||||
var text = filter.TargetContains.Trim().ToLowerInvariant();
|
||||
events = events.Where(e => e.Target != null && e.Target.ToLower().Contains(text));
|
||||
}
|
||||
|
||||
var rows = await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).Take(Clamp(filter.Limit)).ToListAsync(ct);
|
||||
return rows.Select(ToRecord).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<CatchRecord>> LongestAsync(DateTime? since, int limit, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var rows = await InPeriod(db, since)
|
||||
.Where(e => e.Outcome != TrapOutcome.Rejected)
|
||||
.OrderByDescending(e => e.DurationMs)
|
||||
.ThenByDescending(e => e.Id)
|
||||
.Take(Clamp(limit))
|
||||
.ToListAsync(ct);
|
||||
return rows.Select(ToRecord).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<TopItem>> TopAsync(TopDimension dimension, DateTime? since, int limit, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var catches = InPeriod(db, since).Where(e => e.Outcome != TrapOutcome.Rejected);
|
||||
var take = Clamp(limit);
|
||||
|
||||
IQueryable<TopRow> rows = dimension switch
|
||||
{
|
||||
TopDimension.Ips => catches.GroupBy(e => e.RemoteIp)
|
||||
.Select(g => new TopRow { Key = g.Key, Label = g.Max(e => e.CountryCode), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
|
||||
TopDimension.Countries => catches.Where(e => e.CountryCode != null).GroupBy(e => e.CountryCode!)
|
||||
.Select(g => new TopRow { Key = g.Key, Label = g.Max(e => e.Country), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
|
||||
TopDimension.Providers => catches.Where(e => e.Asn != null).GroupBy(e => e.Asn!.Value)
|
||||
.Select(g => new TopRow { Key = "AS" + g.Key.ToString(), Label = g.Max(e => e.Provider), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
|
||||
TopDimension.Targets => catches.Where(e => e.Target != null).GroupBy(e => e.Target!)
|
||||
.Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
|
||||
TopDimension.UserAgents => catches.Where(e => e.ClientInfo != null).GroupBy(e => e.ClientInfo!)
|
||||
.Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(dimension))
|
||||
};
|
||||
|
||||
var top = await rows
|
||||
.OrderByDescending(x => x.Count)
|
||||
.ThenByDescending(x => x.DurationMs)
|
||||
.Take(take)
|
||||
.ToListAsync(ct);
|
||||
|
||||
return top.Select(x => new TopItem(x.Key, x.Label, x.Count, x.DurationMs / 1000d)).ToList();
|
||||
}
|
||||
|
||||
public async Task<IpProfile?> LookupIpAsync(string ip, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var events = db.TrapEvents.AsNoTracking().Where(e => e.RemoteIp == ip);
|
||||
|
||||
var total = await events.CountAsync(ct);
|
||||
if (total == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected);
|
||||
var origin = await events.Where(e => e.CountryCode != null || e.Asn != null).OrderByDescending(e => e.Id).FirstOrDefaultAsync(ct);
|
||||
var recent = await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).Take(MaxLimit).ToListAsync(ct);
|
||||
|
||||
return new IpProfile(
|
||||
ip,
|
||||
origin?.CountryCode,
|
||||
origin?.Country,
|
||||
origin?.City,
|
||||
origin?.Asn,
|
||||
origin?.Provider,
|
||||
await catches.CountAsync(ct),
|
||||
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct),
|
||||
await catches.SumAsync(e => e.DurationMs, ct) / 1000d,
|
||||
await events.SumAsync(e => e.BytesSent, ct),
|
||||
await events.MinAsync(e => e.StartedAt, ct),
|
||||
await events.MaxAsync(e => e.EndedAt, ct),
|
||||
recent.Select(ToRecord).ToList(),
|
||||
Math.Max(0, total - recent.Count));
|
||||
}
|
||||
|
||||
private static IQueryable<TrapEventEntity> InPeriod(FlypaperDbContext db, DateTime? since)
|
||||
{
|
||||
var events = db.TrapEvents.AsNoTracking();
|
||||
return since is { } start ? events.Where(e => e.StartedAt >= start) : events;
|
||||
}
|
||||
|
||||
private static IQueryable<TrapEventEntity> ByProvider(IQueryable<TrapEventEntity> events, string provider)
|
||||
{
|
||||
var number = provider.StartsWith("AS", StringComparison.OrdinalIgnoreCase) ? provider[2..] : provider;
|
||||
if (long.TryParse(number, NumberStyles.None, CultureInfo.InvariantCulture, out var asn))
|
||||
{
|
||||
return events.Where(e => e.Asn == asn);
|
||||
}
|
||||
|
||||
var text = provider.ToLowerInvariant();
|
||||
return events.Where(e => e.Provider != null && e.Provider.ToLower().Contains(text));
|
||||
}
|
||||
|
||||
private static int Clamp(int limit) => Math.Clamp(limit, 1, MaxLimit);
|
||||
|
||||
private static CatchRecord ToRecord(TrapEventEntity e) => new(
|
||||
e.Id,
|
||||
e.StartedAt,
|
||||
e.EndedAt,
|
||||
e.DurationMs / 1000d,
|
||||
e.BytesSent,
|
||||
e.Outcome,
|
||||
e.RemoteIp,
|
||||
e.CountryCode,
|
||||
e.Country,
|
||||
e.City,
|
||||
e.Asn,
|
||||
e.Provider,
|
||||
e.Target,
|
||||
e.ClientInfo);
|
||||
|
||||
private sealed class TopRow
|
||||
{
|
||||
public required string Key { get; init; }
|
||||
|
||||
public string? Label { get; init; }
|
||||
|
||||
public int Count { get; init; }
|
||||
|
||||
public long DurationMs { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using Flypaper.Core.Models;
|
||||
|
||||
namespace Flypaper.Storage.Queries;
|
||||
|
||||
public sealed record CatchRecord(
|
||||
long Id,
|
||||
DateTime StartedAt,
|
||||
DateTime EndedAt,
|
||||
double DurationSeconds,
|
||||
long BytesSent,
|
||||
TrapOutcome Outcome,
|
||||
string Ip,
|
||||
string? CountryCode,
|
||||
string? Country,
|
||||
string? City,
|
||||
long? Asn,
|
||||
string? Provider,
|
||||
string? Target,
|
||||
string? UserAgent);
|
||||
|
||||
public sealed record CatchFilter(
|
||||
DateTime? Since = null,
|
||||
DateTime? Until = null,
|
||||
string? Country = null,
|
||||
string? Provider = null,
|
||||
string? Ip = null,
|
||||
string? TargetContains = null,
|
||||
int Limit = 50);
|
||||
|
||||
public sealed record CatchStats(
|
||||
int Catches,
|
||||
int Rejected,
|
||||
int UniqueIps,
|
||||
double TotalHoldSeconds,
|
||||
double AverageHoldSeconds,
|
||||
CatchRecord? Longest);
|
||||
|
||||
public enum TopDimension
|
||||
{
|
||||
Ips,
|
||||
Countries,
|
||||
Providers,
|
||||
Targets,
|
||||
UserAgents
|
||||
}
|
||||
|
||||
public sealed record TopItem(string Key, string? Label, int Catches, double TotalHoldSeconds);
|
||||
|
||||
public sealed record IpProfile(
|
||||
string Ip,
|
||||
string? CountryCode,
|
||||
string? Country,
|
||||
string? City,
|
||||
long? Asn,
|
||||
string? Provider,
|
||||
int Catches,
|
||||
int Rejected,
|
||||
double TotalHoldSeconds,
|
||||
long TotalBytesSent,
|
||||
DateTime? FirstSeen,
|
||||
DateTime? LastSeen,
|
||||
IReadOnlyList<CatchRecord> Events,
|
||||
int EventsOmitted);
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Flypaper.Storage.Queries;
|
||||
|
||||
public static partial class QueryPeriod
|
||||
{
|
||||
[GeneratedRegex(@"^(\d{1,5})([mhdw])$", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex Pattern();
|
||||
|
||||
public static bool TryParse(string? value, out TimeSpan? span)
|
||||
{
|
||||
span = null;
|
||||
var text = value?.Trim();
|
||||
if (string.IsNullOrEmpty(text) || text.Equals("all", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var match = Pattern().Match(text);
|
||||
if (!match.Success)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var amount = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
|
||||
span = char.ToLowerInvariant(match.Groups[2].Value[0]) switch
|
||||
{
|
||||
'm' => TimeSpan.FromMinutes(amount),
|
||||
'h' => TimeSpan.FromHours(amount),
|
||||
'd' => TimeSpan.FromDays(amount),
|
||||
_ => TimeSpan.FromDays(amount * 7)
|
||||
};
|
||||
return amount > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using Flypaper.Storage.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Flypaper.Storage.Settings;
|
||||
|
||||
public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
|
||||
{
|
||||
private static readonly TimeSpan LastUsedResolution = TimeSpan.FromMinutes(1);
|
||||
|
||||
public async Task<IReadOnlyList<McpTokenEntity>> ListAsync(CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };
|
||||
db.McpTokens.Add(token);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return token;
|
||||
}
|
||||
|
||||
public async Task<bool> RevokeAsync(int id, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
return await db.McpTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct) > 0;
|
||||
}
|
||||
|
||||
public async Task<McpTokenEntity?> UseAsync(string tokenHash, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var token = await db.McpTokens.SingleOrDefaultAsync(t => t.TokenHash == tokenHash, ct);
|
||||
if (token is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var now = timeProvider.GetUtcNow().UtcDateTime;
|
||||
if (token.LastUsedAt is null || now - token.LastUsedAt >= LastUsedResolution)
|
||||
{
|
||||
token.LastUsedAt = now;
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user