From 6b32994d16b201a5a99037fcb23af30bd35876bc Mon Sep 17 00:00:00 2001 From: whoswhip Date: Fri, 6 Feb 2026 18:28:32 -0500 Subject: [PATCH] feat: true total paste size; always map the openapi route style: format via csharpier --- .../src/routes/stats/+page.svelte | 2 +- SharpbinV3.Server/Program.cs | 343 ++++++++++-------- SharpbinV3.Server/SharpbinV3.Server.csproj | 16 +- 3 files changed, 211 insertions(+), 150 deletions(-) diff --git a/SharpbinV3.Client/src/routes/stats/+page.svelte b/SharpbinV3.Client/src/routes/stats/+page.svelte index 1b759a2..cc93a4a 100644 --- a/SharpbinV3.Client/src/routes/stats/+page.svelte +++ b/SharpbinV3.Client/src/routes/stats/+page.svelte @@ -72,7 +72,7 @@

Total Storage Used

-

{formatBytes(stats.pastes.totalSizeInBytes)}

+

{formatBytes(stats.pastes.totalSizeInBytes)}

diff --git a/SharpbinV3.Server/Program.cs b/SharpbinV3.Server/Program.cs index 4a76802..0fb66de 100644 --- a/SharpbinV3.Server/Program.cs +++ b/SharpbinV3.Server/Program.cs @@ -1,3 +1,6 @@ +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.RateLimiting; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; @@ -11,9 +14,6 @@ using SharpbinV3.Server.Services; using SharpbinV3.Server.Services.Verification; using SharpbinV3.Server.Services.Verification.Providers; using SharpbinV3.Server.Settings; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.RateLimiting; namespace SharpbinV3.Server { @@ -25,11 +25,13 @@ namespace SharpbinV3.Server // Add services to the container. - builder.Services.AddControllers() + builder + .Services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; - options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; + options.JsonSerializerOptions.DefaultIgnoreCondition = + JsonIgnoreCondition.WhenWritingNull; }); // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi builder.Services.AddOpenApi(); @@ -48,150 +50,185 @@ namespace SharpbinV3.Server builder.Services.AddHttpClient(); builder.Services.AddScoped(); builder.Services.AddMemoryCache(); + builder.Services.AddEndpointsApiExplorer(); - builder.Services.AddHealthChecks() - .AddDbContextCheck("Database"); + builder.Services.AddHealthChecks().AddDbContextCheck("Database"); - builder.Services.AddOptions() + builder + .Services.AddOptions() .Bind(builder.Configuration.GetSection("PasteSettings")) .ValidateDataAnnotations() .ValidateOnStart(); - builder.Services.AddOptions() + builder + .Services.AddOptions() .Bind(builder.Configuration.GetSection("JwtSettings")) .ValidateDataAnnotations() .ValidateOnStart(); - builder.Services.Configure(builder.Configuration.GetSection("AuthSettings")); + builder.Services.Configure( + builder.Configuration.GetSection("AuthSettings") + ); - builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + builder + .Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(); - builder.Services.AddOptions(JwtBearerDefaults.AuthenticationScheme) - .Configure>((options, jwtSettings) => - { - var settings = jwtSettings.Value; - var key = Encoding.UTF8.GetBytes(settings.Secret); - - options.SaveToken = true; - options.TokenValidationParameters = new TokenValidationParameters + builder + .Services.AddOptions(JwtBearerDefaults.AuthenticationScheme) + .Configure>( + (options, jwtSettings) => { - ValidateIssuerSigningKey = true, - IssuerSigningKey = new SymmetricSecurityKey(key), + var settings = jwtSettings.Value; + var key = Encoding.UTF8.GetBytes(settings.Secret); - ValidateIssuer = true, - ValidIssuer = settings.Issuer, + options.SaveToken = true; + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), - ValidateAudience = true, - ValidAudience = settings.Audience, + ValidateIssuer = true, + ValidIssuer = settings.Issuer, - RequireExpirationTime = true, - ValidateLifetime = true, - ClockSkew = TimeSpan.Zero, + ValidateAudience = true, + ValidAudience = settings.Audience, - RequireSignedTokens = true, - ValidAlgorithms = [SecurityAlgorithms.HmacSha256] - }; - }); + RequireExpirationTime = true, + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero, - builder.Services.AddAuthorizationBuilder() - .AddPolicy("NotBanned", policy => - policy.Requirements.Add(new NotBannedRequirement())); - builder.Services.AddAuthorizationBuilder() - .AddPolicy("AuthAndNotBanned", policy => - policy.Requirements.Add(new NotBannedRequirement())); + RequireSignedTokens = true, + ValidAlgorithms = [SecurityAlgorithms.HmacSha256], + }; + } + ); + + builder + .Services.AddAuthorizationBuilder() + .AddPolicy( + "NotBanned", + policy => policy.Requirements.Add(new NotBannedRequirement()) + ); + builder + .Services.AddAuthorizationBuilder() + .AddPolicy( + "AuthAndNotBanned", + policy => policy.Requirements.Add(new NotBannedRequirement()) + ); builder.Services.AddSingleton(new NotBannedHandler(false)); builder.Services.AddSingleton(new NotBannedHandler(true)); - builder.Services.AddRateLimiter(options => { - options.AddPolicy("Sliding", httpContext => - RateLimitPartition.GetSlidingWindowLimiter(httpContext.GetRequestIP(), _ => new SlidingWindowRateLimiterOptions - { - Window = TimeSpan.FromSeconds(10), - PermitLimit = 10, - QueueLimit = 2, - SegmentsPerWindow = 5, - QueueProcessingOrder = QueueProcessingOrder.OldestFirst, - } - )); + options.AddPolicy( + "Sliding", + httpContext => + RateLimitPartition.GetSlidingWindowLimiter( + httpContext.GetRequestIP(), + _ => new SlidingWindowRateLimiterOptions + { + Window = TimeSpan.FromSeconds(10), + PermitLimit = 10, + QueueLimit = 2, + SegmentsPerWindow = 5, + QueueProcessingOrder = QueueProcessingOrder.OldestFirst, + } + ) + ); - options.AddPolicy("Strict", httpContext => - RateLimitPartition.GetTokenBucketLimiter(httpContext.GetRequestIP(), _ => new TokenBucketRateLimiterOptions - { - TokenLimit = 5, - QueueLimit = 0, - TokensPerPeriod = 1, - ReplenishmentPeriod = TimeSpan.FromSeconds(30), - AutoReplenishment = true, - QueueProcessingOrder = QueueProcessingOrder.OldestFirst, - } - )); + options.AddPolicy( + "Strict", + httpContext => + RateLimitPartition.GetTokenBucketLimiter( + httpContext.GetRequestIP(), + _ => new TokenBucketRateLimiterOptions + { + TokenLimit = 5, + QueueLimit = 0, + TokensPerPeriod = 1, + ReplenishmentPeriod = TimeSpan.FromSeconds(30), + AutoReplenishment = true, + QueueProcessingOrder = QueueProcessingOrder.OldestFirst, + } + ) + ); - options.AddPolicy("Sensitive", httpContext => - RateLimitPartition.GetTokenBucketLimiter(httpContext.GetRequestIP(), _ => new TokenBucketRateLimiterOptions - { - TokenLimit = 3, - QueueLimit = 0, - TokensPerPeriod = 1, - ReplenishmentPeriod = TimeSpan.FromMinutes(1), - AutoReplenishment = true, - QueueProcessingOrder = QueueProcessingOrder.OldestFirst, - } - )); + options.AddPolicy( + "Sensitive", + httpContext => + RateLimitPartition.GetTokenBucketLimiter( + httpContext.GetRequestIP(), + _ => new TokenBucketRateLimiterOptions + { + TokenLimit = 3, + QueueLimit = 0, + TokensPerPeriod = 1, + ReplenishmentPeriod = TimeSpan.FromMinutes(1), + AutoReplenishment = true, + QueueProcessingOrder = QueueProcessingOrder.OldestFirst, + } + ) + ); options.AddPolicy("NoLimit", _ => RateLimitPartition.GetNoLimiter(0)); - options.GlobalLimiter = PartitionedRateLimiter.Create(httpContext => - { - var remoteIp = httpContext.GetRequestIP(); - - return RateLimitPartition.GetFixedWindowLimiter(remoteIp, _ => new FixedWindowRateLimiterOptions + options.GlobalLimiter = PartitionedRateLimiter.Create( + httpContext => { - PermitLimit = 100, - Window = TimeSpan.FromMinutes(1), - QueueProcessingOrder = QueueProcessingOrder.OldestFirst, - QueueLimit = 0 - }); - }); + var remoteIp = httpContext.GetRequestIP(); + + return RateLimitPartition.GetFixedWindowLimiter( + remoteIp, + _ => new FixedWindowRateLimiterOptions + { + PermitLimit = 100, + Window = TimeSpan.FromMinutes(1), + QueueProcessingOrder = QueueProcessingOrder.OldestFirst, + QueueLimit = 0, + } + ); + } + ); options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; options.OnRejected = async (context, cancellationToken) => { - await context.HttpContext.Response.WriteAsJsonAsync(new - { - success = false, - Message = "Too many requests. Please try again later." - }, cancellationToken: cancellationToken); + await context.HttpContext.Response.WriteAsJsonAsync( + new + { + success = false, + Message = "Too many requests. Please try again later.", + }, + cancellationToken: cancellationToken + ); }; }); builder.Services.AddOutputCache(options => { - options.AddPolicy("1Day", builder => - { - builder.Expire(TimeSpan.FromDays(1)); - }); + options.AddPolicy( + "1Day", + builder => + { + builder.Expire(TimeSpan.FromDays(1)); + } + ); }); builder.Services.AddCors(o => { o.AddDefaultPolicy(p => - p.WithOrigins("http://localhost:5173") - .AllowAnyHeader() - .AllowAnyMethod()); + p.WithOrigins("http://localhost:5173").AllowAnyHeader().AllowAnyMethod() + ); }); - builder.Services.AddDataProtection() + builder + .Services.AddDataProtection() .PersistKeysToFileSystem(GetDataProtectionKeyDirectory(builder.Environment)) .SetApplicationName("SharpbinV3"); var app = builder.Build(); app.UseRateLimiter(); - // Configure the HTTP request pipeline. - if (app.Environment.IsDevelopment()) - { - app.MapOpenApi(); - } + app.MapOpenApi(); app.UseHttpsRedirection(); app.UseCors(); @@ -209,7 +246,8 @@ namespace SharpbinV3.Server db.Database.Migrate(); // this is temporary since the migration doesnt seem to work properly - db.Database.ExecuteSql($""" + db.Database.ExecuteSql( + $""" CREATE TRIGGER IF NOT EXISTS Users_UID_AutoIncrement AFTER INSERT ON Users BEGIN @@ -219,61 +257,76 @@ namespace SharpbinV3.Server ) WHERE rowid = NEW.rowid AND NEW.UID IS NULL; END; - """); + """ + ); } app.MapHealthChecks("/health"); - app.MapGet("/api/stats", async (AppDbContext db) => - { - var now = DateTimeOffset.UtcNow; - var todayStart = new DateTimeOffset(now.Year, now.Month, now.Day, 0, 0, 0, TimeSpan.Zero); - var sevenDaysAgo = todayStart.AddDays(-6).ToUnixTimeMilliseconds(); - - var pasteCount = await db.Pastes.CountAsync(); - var userCount = await db.Users.CountAsync(); - var totalPasteSize = await db.Pastes.SumAsync(p => p.Size); - - var dailyCounts = await db.Pastes - .Where(p => p.CreatedAt >= sevenDaysAgo) - .GroupBy(p => p.CreatedAt / 86400000) - .Select(g => new { Day = g.Key, Count = g.Count() }) - .ToDictionaryAsync(x => x.Day, x => x.Count); - - var dailyStats = new List(); - var pasteCountWeek = 0; - - for (int i = 6; i >= 0; i--) - { - var dayTs = todayStart.AddDays(-i).ToUnixTimeMilliseconds(); - dailyCounts.TryGetValue(dayTs / 86400000, out var count); - - dailyStats.Add(new { date = dayTs, count }); - pasteCountWeek += count; - } - - return Results.Ok(new - { - success = true, - stats = new + app.MapGet( + "/api/stats", + async (AppDbContext db) => { - pastes = new + var now = DateTimeOffset.UtcNow; + var todayStart = new DateTimeOffset( + now.Year, + now.Month, + now.Day, + 0, + 0, + 0, + TimeSpan.Zero + ); + var sevenDaysAgo = todayStart.AddDays(-6).ToUnixTimeMilliseconds(); + + var pasteCount = await db.Pastes.CountAsync(); + var userCount = await db.Users.CountAsync(); + var totalPasteSize = await db.Pastes.SumAsync(p => p.Size); + var trueTotalPasteSize = await db.Pastes.SumAsync(p => p.TrueSize); + + var dailyCounts = await db + .Pastes.Where(p => p.CreatedAt >= sevenDaysAgo) + .GroupBy(p => p.CreatedAt / 86400000) + .Select(g => new { Day = g.Key, Count = g.Count() }) + .ToDictionaryAsync(x => x.Day, x => x.Count); + + var dailyStats = new List(); + var pasteCountWeek = 0; + + for (int i = 6; i >= 0; i--) { - total = pasteCount, - past7Days = pasteCountWeek, - totalSizeInBytes = totalPasteSize, - daily = dailyStats - }, - users = new - { - total = userCount + var dayTs = todayStart.AddDays(-i).ToUnixTimeMilliseconds(); + dailyCounts.TryGetValue(dayTs / 86400000, out var count); + + dailyStats.Add(new { date = dayTs, count }); + pasteCountWeek += count; } + + return Results.Ok( + new + { + success = true, + stats = new + { + pastes = new + { + total = pasteCount, + past7Days = pasteCountWeek, + totalSizeInBytes = totalPasteSize, + trueTotalSizeInBytes = trueTotalPasteSize, + daily = dailyStats, + }, + users = new { total = userCount }, + }, + } + ); } - }); - }).CacheOutput(policy => policy.Expire(TimeSpan.FromHours(6)).Tag("stats")); + ) + .CacheOutput(policy => policy.Expire(TimeSpan.FromHours(6)).Tag("stats")); app.Run(); } + static DirectoryInfo GetDataProtectionKeyDirectory(IHostEnvironment env) { var overridepath = Environment.GetEnvironmentVariable("DATA_PROTECTION_KEY_PATH"); diff --git a/SharpbinV3.Server/SharpbinV3.Server.csproj b/SharpbinV3.Server/SharpbinV3.Server.csproj index 80aed85..5d1542e 100644 --- a/SharpbinV3.Server/SharpbinV3.Server.csproj +++ b/SharpbinV3.Server/SharpbinV3.Server.csproj @@ -1,5 +1,4 @@ - net10.0 enable @@ -26,10 +25,19 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + -