Add data management, randomized HTML drip and public README
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3671019e60
commit
f5d8ca7484
46 files changed
+1601
-172
No files matched your search
@@ -0,0 +1,6 @@
|
||||
namespace Flypaper.Core.Abstractions;
|
||||
|
||||
public interface IRandomSource
|
||||
{
|
||||
int Next(int minValue, int maxValue);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using Flypaper.Core.Models;
|
||||
|
||||
namespace Flypaper.Core.Abstractions;
|
||||
|
||||
public interface ITrapStrategySelector
|
||||
{
|
||||
ITarpitStrategy? Select(TrapContext context);
|
||||
}
|
||||
@@ -17,7 +17,9 @@ public static class FlypaperCoreExtensions
|
||||
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
|
||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, DripStrategy>());
|
||||
services.TryAddSingleton<IRandomSource, SystemRandomSource>();
|
||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
|
||||
services.TryAddSingleton<ITrapStrategySelector, ProtocolStrategySelector>();
|
||||
services.TryAddSingleton<TrapRunner>();
|
||||
services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
|
||||
|
||||
|
||||
@@ -9,4 +9,6 @@ public sealed class FlypaperOptions
|
||||
public int MaxConnectionsPerIp { get; set; } = 10;
|
||||
|
||||
public TimeSpan MaxHoldDuration { get; set; } = TimeSpan.FromHours(1);
|
||||
|
||||
public bool IgnorePrivateNetworks { get; set; } = true;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
|
||||
namespace Flypaper.Core.Runtime;
|
||||
|
||||
public sealed class ProtocolStrategySelector(IEnumerable<ITarpitStrategy> strategies) : ITrapStrategySelector
|
||||
{
|
||||
public ITarpitStrategy? Select(TrapContext context) =>
|
||||
strategies.FirstOrDefault(strategy => strategy.Supports(context.Session.Protocol));
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
|
||||
namespace Flypaper.Core.Runtime;
|
||||
|
||||
internal sealed class SystemRandomSource : IRandomSource
|
||||
{
|
||||
public int Next(int minValue, int maxValue) => Random.Shared.Next(minValue, maxValue);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Core.Networking;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
@@ -8,7 +9,7 @@ namespace Flypaper.Core.Runtime;
|
||||
|
||||
public sealed partial class TrapRunner(
|
||||
IConnectionGovernor governor,
|
||||
IEnumerable<ITarpitStrategy> strategies,
|
||||
ITrapStrategySelector strategies,
|
||||
ITrapEventSink sink,
|
||||
IOptionsMonitor<FlypaperOptions> options,
|
||||
TimeProvider timeProvider,
|
||||
@@ -20,7 +21,7 @@ public sealed partial class TrapRunner(
|
||||
CancellationToken ct)
|
||||
{
|
||||
var session = context.Session;
|
||||
var strategy = strategies.FirstOrDefault(s => s.Supports(session.Protocol));
|
||||
var strategy = strategies.Select(context);
|
||||
|
||||
if (strategy is null || !governor.TryAcquire(session, out var lease))
|
||||
{
|
||||
@@ -69,9 +70,12 @@ public sealed partial class TrapRunner(
|
||||
context.Target,
|
||||
context.ClientInfo);
|
||||
|
||||
var store = !(options.CurrentValue.IgnorePrivateNetworks && PrivateNetworks.Contains(trapEvent.RemoteIp));
|
||||
var storageNote = store ? "" : " (not stored)";
|
||||
|
||||
if (outcome == TrapOutcome.Rejected)
|
||||
{
|
||||
LogRejected(trapEvent.RemoteIp, trapEvent.Target, trapEvent.ClientInfo);
|
||||
LogRejected(trapEvent.RemoteIp, trapEvent.Target, trapEvent.ClientInfo, storageNote);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -81,22 +85,27 @@ public sealed partial class TrapRunner(
|
||||
trapEvent.Duration.TotalSeconds,
|
||||
trapEvent.BytesSent,
|
||||
trapEvent.Outcome,
|
||||
trapEvent.ClientInfo);
|
||||
trapEvent.ClientInfo,
|
||||
storageNote);
|
||||
}
|
||||
|
||||
sink.Publish(trapEvent);
|
||||
if (store)
|
||||
{
|
||||
sink.Publish(trapEvent);
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information,
|
||||
Message = "Trapped {RemoteIp} {Target} {DurationSeconds:F1}s {BytesSent}B {Outcome} \"{UserAgent}\"")]
|
||||
Message = "Trapped {RemoteIp} {Target} {DurationSeconds:F1}s {BytesSent}B {Outcome} \"{UserAgent}\"{StorageNote}")]
|
||||
private partial void LogTrapped(
|
||||
IPAddress remoteIp,
|
||||
string? target,
|
||||
double durationSeconds,
|
||||
long bytesSent,
|
||||
TrapOutcome outcome,
|
||||
string? userAgent);
|
||||
string? userAgent,
|
||||
string storageNote);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Rejected {RemoteIp} {Target} \"{UserAgent}\"")]
|
||||
private partial void LogRejected(IPAddress remoteIp, string? target, string? userAgent);
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Rejected {RemoteIp} {Target} \"{UserAgent}\"{StorageNote}")]
|
||||
private partial void LogRejected(IPAddress remoteIp, string? target, string? userAgent, string storageNote);
|
||||
}
|
||||
@@ -4,19 +4,21 @@ namespace Flypaper.Core.Settings;
|
||||
|
||||
public sealed record RuntimeSettings(
|
||||
IReadOnlyList<string> TrapPaths,
|
||||
TimeSpan DripInterval,
|
||||
int MaxConnections,
|
||||
int MaxConnectionsPerIp,
|
||||
TimeSpan MaxHoldDuration,
|
||||
IReadOnlyList<string> ExtraKnownHosts)
|
||||
IReadOnlyList<string> ExtraKnownHosts,
|
||||
int RetentionDays,
|
||||
bool IgnorePrivateNetworks)
|
||||
{
|
||||
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
|
||||
{
|
||||
[SettingKeys.TrapPaths] = SettingsList.Join(TrapPaths),
|
||||
[SettingKeys.DripInterval] = DripInterval.ToString("c", CultureInfo.InvariantCulture),
|
||||
[SettingKeys.MaxConnections] = MaxConnections.ToString(CultureInfo.InvariantCulture),
|
||||
[SettingKeys.MaxConnectionsPerIp] = MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
|
||||
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
|
||||
[SettingKeys.ExtraKnownHosts] = SettingsList.Join(ExtraKnownHosts)
|
||||
[SettingKeys.ExtraKnownHosts] = SettingsList.Join(ExtraKnownHosts),
|
||||
[SettingKeys.RetentionDays] = RetentionDays.ToString(CultureInfo.InvariantCulture),
|
||||
[SettingKeys.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false"
|
||||
};
|
||||
}
|
||||
@@ -2,8 +2,9 @@ namespace Flypaper.Core.Settings;
|
||||
|
||||
public sealed record RuntimeSettingsInput(
|
||||
string? TrapPaths,
|
||||
string? DripInterval,
|
||||
string? MaxConnections,
|
||||
string? MaxConnectionsPerIp,
|
||||
string? MaxHoldDuration,
|
||||
string? ExtraKnownHosts);
|
||||
string? ExtraKnownHosts,
|
||||
string? RetentionDays,
|
||||
bool IgnorePrivateNetworks);
|
||||
@@ -9,9 +9,8 @@ public static partial class RuntimeSettingsParser
|
||||
private const int MaxPathLength = 256;
|
||||
private const int MaxHostLength = 253;
|
||||
private const int MaxLimit = 100_000;
|
||||
private const int MaxRetentionDays = 3650;
|
||||
|
||||
private static readonly TimeSpan MinInterval = TimeSpan.FromMilliseconds(100);
|
||||
private static readonly TimeSpan MaxInterval = TimeSpan.FromHours(1);
|
||||
private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1);
|
||||
private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7);
|
||||
|
||||
@@ -24,10 +23,10 @@ public static partial class RuntimeSettingsParser
|
||||
|
||||
var paths = ParseList(input.TrapPaths, nameof(input.TrapPaths), ValidatePath, errors);
|
||||
var hosts = ParseList(input.ExtraKnownHosts, nameof(input.ExtraKnownHosts), ValidateHost, errors);
|
||||
var interval = ParseTimeSpan(input.DripInterval, nameof(input.DripInterval), MinInterval, MaxInterval, errors);
|
||||
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
|
||||
var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), errors);
|
||||
var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), errors);
|
||||
var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), 1, MaxLimit, errors);
|
||||
var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 1, MaxLimit, errors);
|
||||
var retention = ParseInt(input.RetentionDays, nameof(input.RetentionDays), 0, MaxRetentionDays, errors);
|
||||
|
||||
if (maxConnections is { } total && perIp is { } single && single > total
|
||||
&& !errors.ContainsKey(nameof(input.MaxConnectionsPerIp)))
|
||||
@@ -40,7 +39,14 @@ public static partial class RuntimeSettingsParser
|
||||
return new RuntimeSettingsParseResult(null, errors);
|
||||
}
|
||||
|
||||
var settings = new RuntimeSettings(paths!, interval!.Value, maxConnections!.Value, perIp!.Value, hold!.Value, hosts!);
|
||||
var settings = new RuntimeSettings(
|
||||
paths!,
|
||||
maxConnections!.Value,
|
||||
perIp!.Value,
|
||||
hold!.Value,
|
||||
hosts!,
|
||||
retention!.Value,
|
||||
input.IgnorePrivateNetworks);
|
||||
return new RuntimeSettingsParseResult(settings, errors);
|
||||
}
|
||||
|
||||
@@ -137,7 +143,7 @@ public static partial class RuntimeSettingsParser
|
||||
return value;
|
||||
}
|
||||
|
||||
private static int? ParseInt(string? raw, string field, Dictionary<string, string> errors)
|
||||
private static int? ParseInt(string? raw, string field, int min, int max, Dictionary<string, string> errors)
|
||||
{
|
||||
var text = raw?.Trim();
|
||||
if (string.IsNullOrEmpty(text))
|
||||
@@ -146,9 +152,9 @@ public static partial class RuntimeSettingsParser
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) || value is < 1 or > MaxLimit)
|
||||
if (!int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) || value < min || value > max)
|
||||
{
|
||||
errors[field] = $"Ganze Zahl zwischen 1 und {MaxLimit}.";
|
||||
errors[field] = $"Ganze Zahl zwischen {min} und {max}.";
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,17 +5,19 @@ 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 DripInterval = "Flypaper:Drip:Interval";
|
||||
public const string TrapPaths = "Flypaper:Http:TrapPathsOverride";
|
||||
public const string ExtraKnownHosts = "Flypaper:Http:ExtraKnownHosts";
|
||||
public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks";
|
||||
public const string RetentionDays = "Flypaper:Retention:Days";
|
||||
|
||||
public static readonly IReadOnlySet<string> All = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
MaxConnections,
|
||||
MaxConnectionsPerIp,
|
||||
MaxHoldDuration,
|
||||
DripInterval,
|
||||
TrapPaths,
|
||||
ExtraKnownHosts
|
||||
ExtraKnownHosts,
|
||||
IgnorePrivateNetworks,
|
||||
RetentionDays
|
||||
};
|
||||
}
|
||||
@@ -4,5 +4,11 @@ public sealed class DripOptions
|
||||
{
|
||||
public const string SectionName = "Flypaper:Drip";
|
||||
|
||||
public TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(10);
|
||||
public TimeSpan MinDelay { get; set; } = TimeSpan.FromMilliseconds(50);
|
||||
|
||||
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(1);
|
||||
|
||||
public int MinChunkSize { get; set; } = 1;
|
||||
|
||||
public int MaxChunkSize { get; set; } = 64;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Text;
|
||||
using Flypaper.Core.Abstractions;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public static class DripSchedule
|
||||
{
|
||||
public static IEnumerable<DripStep> Create(IEnumerable<string> content, IRandomSource random, DripOptions options)
|
||||
{
|
||||
var minChunk = Math.Max(1, options.MinChunkSize);
|
||||
var maxChunk = Math.Max(minChunk, options.MaxChunkSize);
|
||||
var minDelay = (int)Math.Max(0, options.MinDelay.TotalMilliseconds);
|
||||
var maxDelay = Math.Max(minDelay, (int)options.MaxDelay.TotalMilliseconds);
|
||||
|
||||
using var fragments = content.GetEnumerator();
|
||||
var pending = Array.Empty<byte>();
|
||||
var offset = 0;
|
||||
|
||||
while (true)
|
||||
{
|
||||
var chunk = new byte[random.Next(minChunk, maxChunk + 1)];
|
||||
var filled = 0;
|
||||
|
||||
while (filled < chunk.Length)
|
||||
{
|
||||
if (offset == pending.Length)
|
||||
{
|
||||
if (!fragments.MoveNext())
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
pending = Encoding.UTF8.GetBytes(fragments.Current);
|
||||
offset = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
var count = Math.Min(chunk.Length - filled, pending.Length - offset);
|
||||
pending.AsSpan(offset, count).CopyTo(chunk.AsSpan(filled));
|
||||
offset += count;
|
||||
filled += count;
|
||||
}
|
||||
|
||||
if (filled == 0)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
yield return new DripStep(chunk.AsMemory(0, filled), TimeSpan.FromMilliseconds(random.Next(minDelay, maxDelay + 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public readonly record struct DripStep(ReadOnlyMemory<byte> Chunk, TimeSpan Delay);
|
||||
@@ -1,26 +0,0 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public sealed class DripStrategy(IOptionsMonitor<DripOptions> options, TimeProvider timeProvider) : ITarpitStrategy
|
||||
{
|
||||
private static readonly byte[] Alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"u8.ToArray();
|
||||
|
||||
public string Name => "drip";
|
||||
|
||||
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
|
||||
|
||||
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
|
||||
{
|
||||
var buffer = new byte[1];
|
||||
while (true)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
buffer[0] = Alphabet[Random.Shared.Next(Alphabet.Length)];
|
||||
await channel.WriteAsync(buffer, ct);
|
||||
await Task.Delay(options.CurrentValue.Interval, timeProvider, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
using System.Text;
|
||||
using Flypaper.Core.Abstractions;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public static class HtmlContent
|
||||
{
|
||||
private const string Css = """
|
||||
body { margin: 0 auto; max-width: 52rem; padding: 1.5rem; font: 16px/1.6 system-ui, sans-serif; color: #222; }
|
||||
header { border-bottom: 1px solid #ddd; margin-bottom: 1.5rem; }
|
||||
nav a { margin-right: 1rem; color: #0b5cad; text-decoration: none; }
|
||||
h1, h2, h3 { line-height: 1.25; }
|
||||
article { margin-bottom: 2rem; }
|
||||
a { color: #0b5cad; }
|
||||
""";
|
||||
|
||||
private static readonly string[] Vocabulary =
|
||||
[
|
||||
"lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod",
|
||||
"tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim",
|
||||
"veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea",
|
||||
"commodo", "consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate", "velit", "esse",
|
||||
"cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident",
|
||||
"sunt", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum", "praesent",
|
||||
"luctus", "vitae", "semper", "facilisis", "integer", "nec", "odio", "mauris", "massa", "vestibulum",
|
||||
"lacinia", "arcu", "eget", "nunc", "tristique", "fermentum", "pellentesque", "habitant", "morbi",
|
||||
"senectus", "netus", "malesuada", "fames", "turpis", "egestas", "porttitor", "rhoncus", "dapibus",
|
||||
"ornare", "sapien", "volutpat", "blandit", "aliquam", "etiam", "erat", "velit", "scelerisque",
|
||||
"viverra", "orci", "sagittis", "eu", "tellus", "cras", "pulvinar", "mattis", "pharetra", "convallis",
|
||||
"posuere", "morbi", "leo", "urna", "molestie", "at", "elementum", "sodales", "neque", "gravida",
|
||||
"dictum", "fusce", "ultrices", "placerat", "euismod", "quam", "suspendisse", "potenti", "nullam",
|
||||
"accumsan", "tincidunt", "varius", "sollicitudin", "imperdiet", "hendrerit", "bibendum", "cursus"
|
||||
];
|
||||
|
||||
private static readonly string[] Sections =
|
||||
["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files", "guides", "kb", "releases"];
|
||||
|
||||
private static readonly string[] Titles =
|
||||
["Welcome", "Documentation", "Knowledge Base", "Support Center", "Release Notes", "Resources", "Archive", "Developer Portal"];
|
||||
|
||||
public static IEnumerable<string> Generate(IRandomSource random)
|
||||
{
|
||||
var title = $"{Pick(random, Titles)} · {Title(random, 2, 3)}";
|
||||
yield return $"""
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{title}</title>
|
||||
<style>
|
||||
{Css}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>{title}</h1>
|
||||
|
||||
""";
|
||||
yield return Navigation(random);
|
||||
yield return "</header>\n<main>\n";
|
||||
|
||||
while (true)
|
||||
{
|
||||
yield return random.Next(0, 10) switch
|
||||
{
|
||||
< 5 => Article(random),
|
||||
< 7 => LinkList(random),
|
||||
< 9 => Paragraph(random),
|
||||
_ => $"<h3>{Title(random, 2, 6)}</h3>\n{Paragraph(random)}"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private static string Navigation(IRandomSource random)
|
||||
{
|
||||
var builder = new StringBuilder("<nav>\n");
|
||||
var count = random.Next(3, 7);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
builder.Append($"<a href=\"/{Pick(random, Sections)}/\">{Capitalize(Pick(random, Vocabulary))}</a>\n");
|
||||
}
|
||||
|
||||
return builder.Append("</nav>\n").ToString();
|
||||
}
|
||||
|
||||
private static string Article(IRandomSource random)
|
||||
{
|
||||
var builder = new StringBuilder($"<article>\n<h2>{Title(random, 3, 9)}</h2>\n");
|
||||
var paragraphs = random.Next(1, 6);
|
||||
for (var i = 0; i < paragraphs; i++)
|
||||
{
|
||||
builder.Append(Paragraph(random));
|
||||
}
|
||||
|
||||
return builder.Append("</article>\n").ToString();
|
||||
}
|
||||
|
||||
private static string LinkList(IRandomSource random)
|
||||
{
|
||||
var ordered = random.Next(0, 2) == 0;
|
||||
var builder = new StringBuilder(ordered ? "<ol>\n" : "<ul>\n");
|
||||
var items = random.Next(3, 10);
|
||||
for (var i = 0; i < items; i++)
|
||||
{
|
||||
builder.Append($"<li>{Link(random, random.Next(2, 6))}</li>\n");
|
||||
}
|
||||
|
||||
return builder.Append(ordered ? "</ol>\n" : "</ul>\n").ToString();
|
||||
}
|
||||
|
||||
private static string Paragraph(IRandomSource random)
|
||||
{
|
||||
var builder = new StringBuilder("<p>");
|
||||
var sentences = random.Next(2, 9);
|
||||
for (var i = 0; i < sentences; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
builder.Append(' ');
|
||||
}
|
||||
|
||||
builder.Append(Sentence(random));
|
||||
}
|
||||
|
||||
return builder.Append("</p>\n").ToString();
|
||||
}
|
||||
|
||||
private static string Sentence(IRandomSource random)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
var words = random.Next(4, 21);
|
||||
var linkAt = random.Next(0, 8) == 0 ? random.Next(1, words) : -1;
|
||||
|
||||
for (var i = 0; i < words; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
builder.Append(i > 2 && random.Next(0, 9) == 0 ? ", " : " ");
|
||||
}
|
||||
|
||||
if (i == linkAt)
|
||||
{
|
||||
builder.Append(Link(random, random.Next(1, 4)));
|
||||
continue;
|
||||
}
|
||||
|
||||
var word = Pick(random, Vocabulary);
|
||||
builder.Append(i == 0 ? Capitalize(word) : word);
|
||||
}
|
||||
|
||||
return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString();
|
||||
}
|
||||
|
||||
private static string Link(IRandomSource random, int words)
|
||||
{
|
||||
var text = Phrase(random, words);
|
||||
var slug = text.Replace(' ', '-');
|
||||
return $"<a href=\"/{Pick(random, Sections)}/{slug}\">{text}</a>";
|
||||
}
|
||||
|
||||
private static string Title(IRandomSource random, int min, int max) => Capitalize(Phrase(random, random.Next(min, max + 1)));
|
||||
|
||||
private static string Phrase(IRandomSource random, int count) =>
|
||||
string.Join(' ', Enumerable.Range(0, count).Select(_ => Pick(random, Vocabulary)));
|
||||
|
||||
private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)];
|
||||
|
||||
private static string Capitalize(string value) => value.Length == 0 ? value : char.ToUpperInvariant(value[0]) + value[1..];
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public sealed class HtmlDripStrategy(
|
||||
IOptionsMonitor<DripOptions> options,
|
||||
IRandomSource random,
|
||||
TimeProvider timeProvider) : ITarpitStrategy
|
||||
{
|
||||
public string Name => "html-drip";
|
||||
|
||||
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
|
||||
|
||||
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
|
||||
{
|
||||
foreach (var step in DripSchedule.Create(HtmlContent.Generate(random), random, options.CurrentValue))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await channel.WriteAsync(step.Chunk, ct);
|
||||
await Task.Delay(step.Delay, timeProvider, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Storage.Dashboard;
|
||||
using Flypaper.Storage.Events;
|
||||
using Flypaper.Storage.Maintenance;
|
||||
using Flypaper.Storage.Settings;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@@ -19,6 +20,7 @@ public static class FlypaperStorageExtensions
|
||||
builder.Configuration.Add(source);
|
||||
builder.Services.AddSingleton(source);
|
||||
builder.Services.AddSingleton<RuntimeSettingsStore>();
|
||||
builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName));
|
||||
builder.Services.AddFlypaperStorage(connectionString);
|
||||
|
||||
return builder;
|
||||
@@ -32,6 +34,8 @@ public static class FlypaperStorageExtensions
|
||||
services.AddHostedService<TrapEventWriter>();
|
||||
services.AddHostedService<OriginBackfill>();
|
||||
services.AddSingleton<DashboardQueries>();
|
||||
services.AddSingleton<TrapDataMaintenance>();
|
||||
services.AddHostedService<RetentionCleanup>();
|
||||
return services;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Storage.Maintenance;
|
||||
|
||||
internal sealed partial class RetentionCleanup(
|
||||
TrapDataMaintenance maintenance,
|
||||
IOptionsMonitor<RetentionOptions> options,
|
||||
TimeProvider timeProvider,
|
||||
ILogger<RetentionCleanup> logger) : BackgroundService
|
||||
{
|
||||
private const int VacuumThreshold = 5_000;
|
||||
private static readonly TimeSpan Interval = TimeSpan.FromDays(1);
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
await CleanupAsync(stoppingToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
LogCleanupFailed(ex);
|
||||
}
|
||||
|
||||
await Task.Delay(Interval, timeProvider, stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task<int> CleanupAsync(CancellationToken ct)
|
||||
{
|
||||
var days = options.CurrentValue.Days;
|
||||
if (days <= 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var cutoff = timeProvider.GetUtcNow().UtcDateTime.AddDays(-days);
|
||||
var deleted = await maintenance.DeleteOlderThanAsync(cutoff, ct);
|
||||
if (deleted == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
LogDeleted(deleted, days);
|
||||
if (deleted >= VacuumThreshold)
|
||||
{
|
||||
await maintenance.VacuumAsync(ct);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "Deleted {Count} trap events older than {Days} days")]
|
||||
private partial void LogDeleted(int count, int days);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Retention cleanup failed")]
|
||||
private partial void LogCleanupFailed(Exception exception);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Flypaper.Storage.Maintenance;
|
||||
|
||||
public sealed class RetentionOptions
|
||||
{
|
||||
public const string SectionName = "Flypaper:Retention";
|
||||
|
||||
public int Days { get; set; } = 90;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Networking;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Flypaper.Storage.Maintenance;
|
||||
|
||||
public sealed class TrapDataMaintenance(IDbContextFactory<FlypaperDbContext> dbContextFactory)
|
||||
{
|
||||
private const int DeleteChunkSize = 500;
|
||||
|
||||
public async Task<TrapDataStats> GetStatsAsync(CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var count = await db.TrapEvents.CountAsync(ct);
|
||||
var oldest = count == 0 ? (DateTime?)null : await db.TrapEvents.MinAsync(e => e.StartedAt, ct);
|
||||
return new TrapDataStats(count, oldest, DatabaseSize(db));
|
||||
}
|
||||
|
||||
public async Task<int> DeleteOlderThanAsync(DateTime cutoffUtc, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
return await db.TrapEvents.Where(e => e.StartedAt < cutoffUtc).ExecuteDeleteAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<int> DeletePrivateAsync(CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
var privateIps = (await db.TrapEvents.Select(e => e.RemoteIp).Distinct().ToListAsync(ct))
|
||||
.Where(ip => IPAddress.TryParse(ip, out var address) && PrivateNetworks.Contains(address))
|
||||
.ToList();
|
||||
|
||||
var deleted = 0;
|
||||
foreach (var chunk in privateIps.Chunk(DeleteChunkSize))
|
||||
{
|
||||
deleted += await db.TrapEvents.Where(e => chunk.Contains(e.RemoteIp)).ExecuteDeleteAsync(ct);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
}
|
||||
|
||||
public async Task<int> DeleteAllAsync(CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
return await db.TrapEvents.ExecuteDeleteAsync(ct);
|
||||
}
|
||||
|
||||
public async Task VacuumAsync(CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
await db.Database.ExecuteSqlRawAsync("VACUUM", ct);
|
||||
}
|
||||
|
||||
private static long? DatabaseSize(FlypaperDbContext db)
|
||||
{
|
||||
var path = db.Database.GetDbConnection().DataSource;
|
||||
if (string.IsNullOrEmpty(path) || !File.Exists(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var wal = new FileInfo(path + "-wal");
|
||||
return new FileInfo(path).Length + (wal.Exists ? wal.Length : 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace Flypaper.Storage.Maintenance;
|
||||
|
||||
public sealed record TrapDataStats(int Count, DateTime? Oldest, long? DatabaseBytes);
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
// <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("20261114150222_RemoveDripIntervalSetting")]
|
||||
partial class RemoveDripIntervalSetting
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||
|
||||
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,22 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Flypaper.Storage.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class RemoveDripIntervalSetting : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.Sql("DELETE FROM \"Settings\" WHERE \"Key\" = 'Flypaper:Drip:Interval';");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Flypaper.Web.Components.Pages.Settings;
|
||||
|
||||
public sealed class DeletePrivateModel
|
||||
{
|
||||
public bool Confirmed { get; set; }
|
||||
}
|
||||
|
||||
public sealed class DeleteAllModel
|
||||
{
|
||||
public string? Confirmation { get; set; }
|
||||
}
|
||||
@@ -4,8 +4,6 @@ public sealed class SettingsModel
|
||||
{
|
||||
public string? TrapPaths { get; set; }
|
||||
|
||||
public string? DripInterval { get; set; }
|
||||
|
||||
public string? MaxConnections { get; set; }
|
||||
|
||||
public string? MaxConnectionsPerIp { get; set; }
|
||||
@@ -13,4 +11,8 @@ public sealed class SettingsModel
|
||||
public string? MaxHoldDuration { get; set; }
|
||||
|
||||
public string? ExtraKnownHosts { get; set; }
|
||||
|
||||
public string? RetentionDays { get; set; }
|
||||
|
||||
public bool IgnorePrivateNetworks { get; set; }
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
@page "/settings"
|
||||
@using Flypaper.Core
|
||||
@using Flypaper.Core.Settings
|
||||
@using Flypaper.Core.Strategies
|
||||
@using Flypaper.Http
|
||||
@using Flypaper.Storage.Maintenance
|
||||
@using Flypaper.Storage.Settings
|
||||
@using Flypaper.Web.Auth
|
||||
@using System.Globalization
|
||||
@using Microsoft.Data.Sqlite
|
||||
@using Microsoft.Extensions.Options
|
||||
@inject IOptionsMonitor<FlypaperOptions> Core
|
||||
@inject IOptionsMonitor<DripOptions> Drip
|
||||
@inject IOptionsMonitor<HttpTrapOptions> Http
|
||||
@inject IOptionsMonitor<RetentionOptions> Retention
|
||||
@inject IConfiguration Configuration
|
||||
@inject RuntimeSettingsStore Store
|
||||
@inject AdminAuthenticator Admin
|
||||
@@ -35,7 +35,7 @@ else if (Saved == "reset")
|
||||
<div class="banner ok">Auf Standard zurückgesetzt.</div>
|
||||
}
|
||||
|
||||
<EditForm Model="Model" FormName="settings" OnSubmit="Save" class="card form">
|
||||
<EditForm Model="Model" FormName="settings" OnSubmit="Save" action="/settings" class="card form">
|
||||
<h2>Anpassbar</h2>
|
||||
|
||||
<label for="trap-paths">Fallenpfade <span class="muted">(einer pro Zeile, mit / am Anfang, * am Ende als Präfix)</span></label>
|
||||
@@ -47,11 +47,6 @@ else if (Saved == "reset")
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.ExtraKnownHosts)" />
|
||||
|
||||
<div class="grid">
|
||||
<div>
|
||||
<label for="drip">Tröpfel-Intervall <span class="muted">(hh:mm:ss)</span></label>
|
||||
<InputText id="drip" @bind-Value="Model!.DripInterval" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.DripInterval)" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="hold">Maximale Haltedauer <span class="muted">(hh:mm:ss)</span></label>
|
||||
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" class="mono" />
|
||||
@@ -67,14 +62,24 @@ else if (Saved == "reset")
|
||||
<InputText id="per-ip" @bind-Value="Model!.MaxConnectionsPerIp" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxConnectionsPerIp)" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="retention">Fänge aufbewahren <span class="muted">(Tage, 0 = unbegrenzt)</span></label>
|
||||
<InputText id="retention" @bind-Value="Model!.RetentionDays" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.RetentionDays)" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label class="check">
|
||||
<InputCheckbox @bind-Value="Model!.IgnorePrivateNetworks" />
|
||||
Fänge aus privaten Netzen nicht speichern <span class="muted">(die Falle greift trotzdem)</span>
|
||||
</label>
|
||||
|
||||
<div class="actions">
|
||||
<button type="submit">Speichern</button>
|
||||
</div>
|
||||
</EditForm>
|
||||
|
||||
<EditForm Model="_resetModel" FormName="reset" OnSubmit="Reset" class="card form">
|
||||
<EditForm Model="_resetModel" FormName="reset" OnSubmit="Reset" action="/settings" class="card form">
|
||||
<h2>Standard</h2>
|
||||
<p class="muted">Löscht alle gespeicherten Änderungen. Danach gelten wieder die Werte aus Umgebungsvariablen und appsettings.</p>
|
||||
<div class="actions">
|
||||
@@ -82,6 +87,8 @@ else if (Saved == "reset")
|
||||
</div>
|
||||
</EditForm>
|
||||
|
||||
<TrapDataSection />
|
||||
|
||||
<section class="card">
|
||||
<h2>Nur per Umgebungsvariable</h2>
|
||||
<p class="muted">Gelten ab Containerstart und lassen sich hier nicht ändern.</p>
|
||||
@@ -117,11 +124,12 @@ else if (Saved == "reset")
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput(
|
||||
Model!.TrapPaths,
|
||||
Model.DripInterval,
|
||||
Model.MaxConnections,
|
||||
Model.MaxConnectionsPerIp,
|
||||
Model.MaxHoldDuration,
|
||||
Model.ExtraKnownHosts));
|
||||
Model.ExtraKnownHosts,
|
||||
Model.RetentionDays,
|
||||
Model.IgnorePrivateNetworks));
|
||||
|
||||
if (result.Settings is null)
|
||||
{
|
||||
@@ -147,10 +155,11 @@ else if (Saved == "reset")
|
||||
{
|
||||
TrapPaths = SettingsList.Join(http.TrapPaths),
|
||||
ExtraKnownHosts = SettingsList.Join(SettingsList.Split(http.ExtraKnownHosts)),
|
||||
DripInterval = Drip.CurrentValue.Interval.ToString("c", CultureInfo.InvariantCulture),
|
||||
MaxHoldDuration = core.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
|
||||
MaxConnections = core.MaxConnections.ToString(CultureInfo.InvariantCulture),
|
||||
MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture)
|
||||
MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
|
||||
RetentionDays = Retention.CurrentValue.Days.ToString(CultureInfo.InvariantCulture),
|
||||
IgnorePrivateNetworks = core.IgnorePrivateNetworks
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
@using Flypaper.Storage.Maintenance
|
||||
@inject TrapDataMaintenance Maintenance
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<section class="card form">
|
||||
<h2>Daten</h2>
|
||||
|
||||
@if (Deleted is { } deleted)
|
||||
{
|
||||
<div class="banner ok">@deleted.ToString("N0") @(deleted == 1 ? "Fang" : "Fänge") gelöscht.</div>
|
||||
}
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr><th>Fänge</th><td>@_stats?.Count.ToString("N0")</td></tr>
|
||||
<tr><th>Ältester Fang</th><td>@(_stats?.Oldest?.ToLocalTime().ToString("dd.MM.yyyy HH:mm") ?? "–")</td></tr>
|
||||
<tr><th>Größe der Datenbank</th><td>@Formatting.Bytes(_stats?.DatabaseBytes)</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="muted">Einstellungen und GeoIP-Dateien bleiben beim Löschen erhalten.</p>
|
||||
|
||||
<EditForm Model="DeletePrivate" FormName="delete-private" OnSubmit="DeletePrivateAsync" action="/settings" class="danger-zone">
|
||||
<h3>Fänge aus privaten Netzen löschen</h3>
|
||||
<p class="muted">Loopback, 10/8, 172.16/12, 192.168/16, Link-Local und ULA, zum Beispiel lokale Testaufrufe.</p>
|
||||
<label class="check">
|
||||
<InputCheckbox @bind-Value="DeletePrivate!.Confirmed" />
|
||||
Ich bin sicher
|
||||
</label>
|
||||
<FieldError Errors="_errors" Field="@nameof(DeletePrivateModel.Confirmed)" />
|
||||
<div class="actions">
|
||||
<button type="submit" class="secondary">Private Fänge löschen</button>
|
||||
</div>
|
||||
</EditForm>
|
||||
|
||||
<EditForm Model="DeleteAll" FormName="delete-all" OnSubmit="DeleteAllAsync" action="/settings" class="danger-zone">
|
||||
<h3>Alle Fänge löschen</h3>
|
||||
<label for="delete-all-confirmation">Zum Bestätigen <strong>LÖSCHEN</strong> eingeben</label>
|
||||
<InputText id="delete-all-confirmation" @bind-Value="DeleteAll!.Confirmation" autocomplete="off" />
|
||||
<FieldError Errors="_errors" Field="@nameof(DeleteAllModel.Confirmation)" />
|
||||
<div class="actions">
|
||||
<button type="submit" class="danger">Alle Fänge löschen</button>
|
||||
</div>
|
||||
</EditForm>
|
||||
</section>
|
||||
|
||||
@code {
|
||||
private const string ConfirmationWord = "LÖSCHEN";
|
||||
|
||||
private TrapDataStats? _stats;
|
||||
private Dictionary<string, string> _errors = [];
|
||||
|
||||
[SupplyParameterFromForm(FormName = "delete-private")] private DeletePrivateModel? DeletePrivate { get; set; }
|
||||
|
||||
[SupplyParameterFromForm(FormName = "delete-all")] private DeleteAllModel? DeleteAll { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "deleted")] private int? Deleted { get; set; }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
DeletePrivate ??= new DeletePrivateModel();
|
||||
DeleteAll ??= new DeleteAllModel();
|
||||
_stats = await Maintenance.GetStatsAsync();
|
||||
}
|
||||
|
||||
private async Task DeletePrivateAsync()
|
||||
{
|
||||
if (!DeletePrivate!.Confirmed)
|
||||
{
|
||||
_errors[nameof(DeletePrivateModel.Confirmed)] = "Bitte bestätigen.";
|
||||
return;
|
||||
}
|
||||
|
||||
await FinishAsync(await Maintenance.DeletePrivateAsync());
|
||||
}
|
||||
|
||||
private async Task DeleteAllAsync()
|
||||
{
|
||||
if (DeleteAll!.Confirmation?.Trim() != ConfirmationWord)
|
||||
{
|
||||
_errors[nameof(DeleteAllModel.Confirmation)] = $"Bitte genau {ConfirmationWord} eingeben.";
|
||||
return;
|
||||
}
|
||||
|
||||
await FinishAsync(await Maintenance.DeleteAllAsync());
|
||||
}
|
||||
|
||||
private async Task FinishAsync(int deleted)
|
||||
{
|
||||
if (deleted > 0)
|
||||
{
|
||||
await Maintenance.VacuumAsync();
|
||||
}
|
||||
|
||||
Navigation.NavigateTo($"/settings?deleted={deleted}");
|
||||
}
|
||||
}
|
||||
@@ -15,5 +15,14 @@ public static class Formatting
|
||||
? string.Concat(countryCode.ToUpperInvariant().Select(c => char.ConvertFromUtf32(0x1F1E6 + c - 'A')))
|
||||
: "";
|
||||
|
||||
public static string Bytes(long? bytes) => bytes switch
|
||||
{
|
||||
null => "–",
|
||||
>= 1024 * 1024 * 1024 => $"{bytes / (1024d * 1024 * 1024):0.0} GB",
|
||||
>= 1024 * 1024 => $"{bytes / (1024d * 1024):0.0} MB",
|
||||
>= 1024 => $"{bytes / 1024d:0} KB",
|
||||
_ => $"{bytes} B"
|
||||
};
|
||||
|
||||
public static string? Provider(long? asn, string? provider) => asn is null ? provider : $"AS{asn} {provider}".TrimEnd();
|
||||
}
|
||||
@@ -6,9 +6,6 @@
|
||||
}
|
||||
},
|
||||
"Flypaper": {
|
||||
"Drip": {
|
||||
"Interval": "00:00:01"
|
||||
},
|
||||
"Http": {
|
||||
"KnownHosts": [
|
||||
"localhost"
|
||||
|
||||
@@ -22,9 +22,6 @@
|
||||
"MaxConnections": 1000,
|
||||
"MaxConnectionsPerIp": 10,
|
||||
"MaxHoldDuration": "01:00:00",
|
||||
"Drip": {
|
||||
"Interval": "00:00:10"
|
||||
},
|
||||
"Http": {
|
||||
"KnownHosts": [],
|
||||
"TrustedProxies": [],
|
||||
|
||||
@@ -451,3 +451,37 @@ tr.open .detail {
|
||||
.footer a {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.check input {
|
||||
width: auto;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
.danger-zone {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin-top: 16px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.danger-zone h3 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.danger-zone p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
button.danger {
|
||||
background: var(--bad);
|
||||
}
|
||||
Reference in new issue
Block a user