diff --git a/src/Helldivers-2-API/Configuration/ApiConfiguration.cs b/src/Helldivers-2-API/Configuration/ApiConfiguration.cs index 7dfa758..1dadb48 100644 --- a/src/Helldivers-2-API/Configuration/ApiConfiguration.cs +++ b/src/Helldivers-2-API/Configuration/ApiConfiguration.cs @@ -15,6 +15,11 @@ public sealed class ApiConfiguration /// public int RateLimitWindow { get; set; } + /// + /// A comma separated list of clients that are (temporarily) blacklisted from making requests. + /// + public string Blacklist { get; set; } = string.Empty; + /// /// Contains the for the API. /// diff --git a/src/Helldivers-2-API/Middlewares/BlacklistMiddleware.cs b/src/Helldivers-2-API/Middlewares/BlacklistMiddleware.cs new file mode 100644 index 0000000..0a8bdb7 --- /dev/null +++ b/src/Helldivers-2-API/Middlewares/BlacklistMiddleware.cs @@ -0,0 +1,25 @@ +using Helldivers.API.Configuration; +using Helldivers.API.Metrics; +using Microsoft.Extensions.Options; + +namespace Helldivers.API.Middlewares; + +/// +/// Handles closing connections from blacklisted clients that violate ToS. +/// +public sealed class BlacklistMiddleware(IOptions options) : IMiddleware +{ + /// + public async Task InvokeAsync(HttpContext context, RequestDelegate next) + { + var client = ClientMetric.GetClientName(context); + if (options.Value.Blacklist.Contains(client, StringComparison.InvariantCultureIgnoreCase)) + { + // don't send response, only wastes more bytes. + context.Abort(); + return; + } + + await next(context); + } +} diff --git a/src/Helldivers-2-API/Program.cs b/src/Helldivers-2-API/Program.cs index b42ed4d..66970ce 100644 --- a/src/Helldivers-2-API/Program.cs +++ b/src/Helldivers-2-API/Program.cs @@ -45,6 +45,7 @@ // Register the rate limiting middleware. builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); // Register the memory cache, used in the rate limiting middleware. builder.Services.AddMemoryCache(); @@ -186,6 +187,7 @@ var app = builder.Build(); app.UseMiddleware(); +app.UseMiddleware(); // Track telemetry for Prometheus (Fly.io metrics) app.UseHttpMetrics(options => diff --git a/src/Helldivers-2-API/appsettings.json b/src/Helldivers-2-API/appsettings.json index 2e2214c..42494c4 100644 --- a/src/Helldivers-2-API/appsettings.json +++ b/src/Helldivers-2-API/appsettings.json @@ -12,6 +12,7 @@ "API": { "RateLimit": 5, "RateLimitWindow": 10, + "Blacklist": "", "Authentication": { "Enabled": true, "ValidIssuers": ["dealloc"],