feat: true total paste size; always map the openapi route

style: format via csharpier
This commit is contained in:
2026-02-06 18:28:32 -05:00
parent d04e2962b5
commit 6b32994d16
3 changed files with 211 additions and 150 deletions
@@ -72,7 +72,7 @@
</div>
<div>
<p class="text-sm text-neutral-400">Total Storage Used</p>
<p class="text-2xl font-bold">{formatBytes(stats.pastes.totalSizeInBytes)}</p>
<p class="text-2xl font-bold" use:tooltip={[formatBytes(stats.pastes.trueTotalSizeInBytes), true]}>{formatBytes(stats.pastes.totalSizeInBytes)}</p>
</div>
</div>
<div class="flex items-center space-x-4 rounded-lg bg-neutral-800 p-4">
+115 -62
View File
@@ -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,25 +50,32 @@ namespace SharpbinV3.Server
builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>();
builder.Services.AddScoped<ReportService>();
builder.Services.AddMemoryCache();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddHealthChecks()
.AddDbContextCheck<AppDbContext>("Database");
builder.Services.AddHealthChecks().AddDbContextCheck<AppDbContext>("Database");
builder.Services.AddOptions<PasteSettings>()
builder
.Services.AddOptions<PasteSettings>()
.Bind(builder.Configuration.GetSection("PasteSettings"))
.ValidateDataAnnotations()
.ValidateOnStart();
builder.Services.AddOptions<JWTSettings>()
builder
.Services.AddOptions<JWTSettings>()
.Bind(builder.Configuration.GetSection("JwtSettings"))
.ValidateDataAnnotations()
.ValidateOnStart();
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings"));
builder.Services.Configure<AuthSettings>(
builder.Configuration.GetSection("AuthSettings")
);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
builder
.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer();
builder.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
.Configure<IOptions<JWTSettings>>((options, jwtSettings) =>
builder
.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
.Configure<IOptions<JWTSettings>>(
(options, jwtSettings) =>
{
var settings = jwtSettings.Value;
var key = Encoding.UTF8.GetBytes(settings.Secret);
@@ -88,24 +97,34 @@ namespace SharpbinV3.Server
ClockSkew = TimeSpan.Zero,
RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256]
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.AddAuthorizationBuilder()
.AddPolicy(
"NotBanned",
policy => policy.Requirements.Add(new NotBannedRequirement())
);
builder
.Services.AddAuthorizationBuilder()
.AddPolicy(
"AuthAndNotBanned",
policy => policy.Requirements.Add(new NotBannedRequirement())
);
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(false));
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(true));
builder.Services.AddRateLimiter(options =>
{
options.AddPolicy("Sliding", httpContext =>
RateLimitPartition.GetSlidingWindowLimiter(httpContext.GetRequestIP(), _ => new SlidingWindowRateLimiterOptions
options.AddPolicy(
"Sliding",
httpContext =>
RateLimitPartition.GetSlidingWindowLimiter(
httpContext.GetRequestIP(),
_ => new SlidingWindowRateLimiterOptions
{
Window = TimeSpan.FromSeconds(10),
PermitLimit = 10,
@@ -113,10 +132,15 @@ namespace SharpbinV3.Server
SegmentsPerWindow = 5,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
));
)
);
options.AddPolicy("Strict", httpContext =>
RateLimitPartition.GetTokenBucketLimiter(httpContext.GetRequestIP(), _ => new TokenBucketRateLimiterOptions
options.AddPolicy(
"Strict",
httpContext =>
RateLimitPartition.GetTokenBucketLimiter(
httpContext.GetRequestIP(),
_ => new TokenBucketRateLimiterOptions
{
TokenLimit = 5,
QueueLimit = 0,
@@ -125,10 +149,15 @@ namespace SharpbinV3.Server
AutoReplenishment = true,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
));
)
);
options.AddPolicy("Sensitive", httpContext =>
RateLimitPartition.GetTokenBucketLimiter(httpContext.GetRequestIP(), _ => new TokenBucketRateLimiterOptions
options.AddPolicy(
"Sensitive",
httpContext =>
RateLimitPartition.GetTokenBucketLimiter(
httpContext.GetRequestIP(),
_ => new TokenBucketRateLimiterOptions
{
TokenLimit = 3,
QueueLimit = 0,
@@ -137,61 +166,69 @@ namespace SharpbinV3.Server
AutoReplenishment = true,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
));
)
);
options.AddPolicy("NoLimit", _ => RateLimitPartition.GetNoLimiter(0));
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(
httpContext =>
{
var remoteIp = httpContext.GetRequestIP();
return RateLimitPartition.GetFixedWindowLimiter(remoteIp, _ => new FixedWindowRateLimiterOptions
return RateLimitPartition.GetFixedWindowLimiter(
remoteIp,
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 100,
Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0
});
});
QueueLimit = 0,
}
);
}
);
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, cancellationToken) =>
{
await context.HttpContext.Response.WriteAsJsonAsync(new
await context.HttpContext.Response.WriteAsJsonAsync(
new
{
success = false,
Message = "Too many requests. Please try again later."
}, cancellationToken: cancellationToken);
Message = "Too many requests. Please try again later.",
},
cancellationToken: cancellationToken
);
};
});
builder.Services.AddOutputCache(options =>
{
options.AddPolicy("1Day", builder =>
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.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,23 +257,35 @@ namespace SharpbinV3.Server
)
WHERE rowid = NEW.rowid AND NEW.UID IS NULL;
END;
""");
"""
);
}
app.MapHealthChecks("/health");
app.MapGet("/api/stats", async (AppDbContext db) =>
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 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)
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);
@@ -252,7 +302,8 @@ namespace SharpbinV3.Server
pasteCountWeek += count;
}
return Results.Ok(new
return Results.Ok(
new
{
success = true,
stats = new
@@ -262,18 +313,20 @@ namespace SharpbinV3.Server
total = pasteCount,
past7Days = pasteCountWeek,
totalSizeInBytes = totalPasteSize,
daily = dailyStats
trueTotalSizeInBytes = trueTotalPasteSize,
daily = dailyStats,
},
users = new { total = userCount },
},
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");
+12 -4
View File
@@ -1,5 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
@@ -26,10 +25,19 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="10.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference
Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore"
Version="10.0.1"
/>
<PackageReference
Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets"
Version="1.23.0"
/>
<PackageReference Include="Otp.NET" Version="1.4.1" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.15.0" />
</ItemGroup>
</Project>