From 3048af3a6dece0338e278bf6d6b2358c0f4952fc Mon Sep 17 00:00:00 2001 From: whoswhip Date: Fri, 9 Jan 2026 19:12:05 -0500 Subject: [PATCH] feat: paste views; configuration validation; hmacsha256 method; enhance paste clean up serivce; paste view clean up service; --- README.md | 3 + SharpbinV3.Client/README.md | 7 +- .../src/routes/[id]/+page.server.ts | 27 +- .../Controllers/PasteController.cs | 24 ++ SharpbinV3.Server/Data/AppDbContext.cs | 7 + SharpbinV3.Server/Data/Entities/Paste.cs | 3 +- SharpbinV3.Server/Data/Entities/PasteView.cs | 17 ++ .../20260109221625_PasteViews.Designer.cs | 260 ++++++++++++++++++ .../Migrations/20260109221625_PasteViews.cs | 57 ++++ .../Migrations/AppDbContextModelSnapshot.cs | 43 ++- SharpbinV3.Server/Program.cs | 38 ++- SharpbinV3.Server/README.md | 8 + .../Services/PasteCleanUpService.cs | 9 +- SharpbinV3.Server/Services/PasteService.cs | 32 +++ .../Services/PasteViewCleanUpService.cs | 50 ++++ .../Providers/TotpVerificationProvider.cs | 19 +- SharpbinV3.Server/Settings/JWTSettings.cs | 7 +- SharpbinV3.Server/Settings/PasteSettings.cs | 8 +- SharpbinV3.Server/Utilities.cs | 15 +- .../appsettings.Development.json | 4 + 20 files changed, 592 insertions(+), 46 deletions(-) create mode 100644 SharpbinV3.Server/Data/Entities/PasteView.cs create mode 100644 SharpbinV3.Server/Migrations/20260109221625_PasteViews.Designer.cs create mode 100644 SharpbinV3.Server/Migrations/20260109221625_PasteViews.cs create mode 100644 SharpbinV3.Server/Services/PasteViewCleanUpService.cs diff --git a/README.md b/README.md index 6a30113..e659539 100644 --- a/README.md +++ b/README.md @@ -50,11 +50,14 @@ You can configure the application using environment variables. When using Docker - `PasteSettings__MaxPasteSizeInBytes`: Max Paste Size set in bytes, the default is `1_048_576` (1MB) - `PasteSettings__EnablePasteCompression`: Enables/Disables server-side paste compression, `true` by default. - `PasteSettings__RequiresVerification`: Enables/Disables CAPTCHA verification when creating pastes, `true` by default. +- `PasteSettings__View_HMAC_Secret`: Required to securely hash viewer identifiers +- `PasteSettings__View_Internal_API_Key`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend. - `ASPNETCORE_ENVIRONMENT`: Set to `Production` or `Development`. #### Frontend (SharpbinV3.Client) - `VITE_API_URL`: The URL of the backend API (e.g., `http://localhost:8080`). - `VITE_ALLOWED_HOSTS`: A comma separated list of allowed hosts (e.g., `localhost,sharpbin.whoswhip.dev`) +- `VIEW_INTERNAL_API_KEY`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend. The frontend will be accessible at http://localhost:5173. diff --git a/SharpbinV3.Client/README.md b/SharpbinV3.Client/README.md index e5a7d94..d28e620 100644 --- a/SharpbinV3.Client/README.md +++ b/SharpbinV3.Client/README.md @@ -21,10 +21,9 @@ npm install The application requires an environment variable to point to the backend API. Create a `.env` file in this directory or set the variable in your environment: -```env -VITE_API_URL=http://localhost:8080 -VITE_ALLOWED_HOSTS=localhost -``` +- `VITE_API_URL`: The URL of the backend API (e.g., `http://localhost:8080`). +- `VITE_ALLOWED_HOSTS`: A comma separated list of allowed hosts (e.g., `localhost,sharpbin.whoswhip.dev`) +- `VIEW_INTERNAL_API_KEY`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend. ### Running in Development diff --git a/SharpbinV3.Client/src/routes/[id]/+page.server.ts b/SharpbinV3.Client/src/routes/[id]/+page.server.ts index 7e9f702..4966181 100644 --- a/SharpbinV3.Client/src/routes/[id]/+page.server.ts +++ b/SharpbinV3.Client/src/routes/[id]/+page.server.ts @@ -1,7 +1,9 @@ import type { PageServerLoad } from './$types'; import type { Paste } from '$lib/types/paste'; +import { getServerToken } from '$lib/utils/auth'; +import { env } from '$env/dynamic/private'; -export const load: PageServerLoad = async ({ params, fetch, url }) => { +export const load: PageServerLoad = async ({ params, fetch, url, cookies }) => { const { id } = params; const paste = await fetch(`/api/paste/${id}`); @@ -11,9 +13,30 @@ export const load: PageServerLoad = async ({ params, fetch, url }) => { error: { message: 'Paste not found' } }; } + + const token = getServerToken(cookies); + + const viewed = await fetch(`/api/paste/${id}/view`, { + method: 'POST', + headers: { + 'X-Internal-API-Key': env.VIEW_INTERNAL_API_KEY ?? env.View_HMAC_Internal_API_Key ?? '', + Authorization: token ? `Bearer ${token}` : '' + } + }); + const pasteData = (await paste.json()) as Paste; + if (viewed.status === 200) { + const viewJson = await viewed.json(); + if (viewJson.success === true && viewJson.message !== 'View already recorded.') { + pasteData.views += 1; + } + } + else { + console.error(`Failed to increment view count for paste ${id}: ${await viewed.text()}`); + } + const pasteContent = await fetch(`/api/paste/${id}/raw`); - const pasteOptions = await fetch('/api/paste/info'); + const pasteOptions = await fetch('/api/paste/info'); const options = await pasteOptions.json(); const content = await pasteContent.text(); diff --git a/SharpbinV3.Server/Controllers/PasteController.cs b/SharpbinV3.Server/Controllers/PasteController.cs index 8e31190..3806aa1 100644 --- a/SharpbinV3.Server/Controllers/PasteController.cs +++ b/SharpbinV3.Server/Controllers/PasteController.cs @@ -213,6 +213,30 @@ namespace SharpbinV3.Server.Controllers return Ok(new { success = true, message = "Paste deleted successfully." }); } + [HttpPost] + [Route("{id}/view")] + [Authorize(Policy = "NotBanned")] + public async Task RecordPasteView(string id) + { + var paste = await _pasteService.Get(id); + if (paste == null) + return NotFound(new { success = false, message = "Paste not found." }); + if (_pasteSettings.View_HMAC_Secret == null) + return StatusCode(500, new { success = false, message = "View recording is not configured properly." }); + if (!string.IsNullOrWhiteSpace(_pasteSettings.View_Internal_API_Key) + && _pasteSettings.View_Internal_API_Key != Request.Headers["X-Internal-API-Key"]) + return Unauthorized(new { success = false, message = "Invalid API key." }); + + var result = await _pasteService.RecordView(paste, HttpContext); + + if (result.paste is null && !result.alreadyExists) + return StatusCode(500, new { success = false, message = "An error occurred while recording the paste view." }); + else if (result.alreadyExists) + return Ok(new { success = true, message = "View already recorded." }); + + return Ok(new { success = true, message = "Paste view recorded." }); + } + [HttpGet] [Route("recent")] public async Task GetRecentPastes() diff --git a/SharpbinV3.Server/Data/AppDbContext.cs b/SharpbinV3.Server/Data/AppDbContext.cs index 759da98..74641cf 100644 --- a/SharpbinV3.Server/Data/AppDbContext.cs +++ b/SharpbinV3.Server/Data/AppDbContext.cs @@ -7,6 +7,7 @@ namespace SharpbinV3.Server.Data { public DbSet Users => Set(); public DbSet Pastes => Set(); + public DbSet PasteViews => Set(); public DbSet RefreshTokens => Set(); public DbSet UserTotps => Set(); @@ -20,6 +21,12 @@ namespace SharpbinV3.Server.Data .HasForeignKey(p => p.AuthorUUID) .OnDelete(DeleteBehavior.Cascade); + modelBuilder.Entity() + .HasOne(pv => pv.Paste) + .WithMany(p => p.PasteViews) + .HasForeignKey(pv => pv.PastePID) + .OnDelete(DeleteBehavior.Cascade); + modelBuilder.Entity() .HasOne(r => r.User) .WithMany(u => u.RefreshTokens) diff --git a/SharpbinV3.Server/Data/Entities/Paste.cs b/SharpbinV3.Server/Data/Entities/Paste.cs index 1232d2f..58510ba 100644 --- a/SharpbinV3.Server/Data/Entities/Paste.cs +++ b/SharpbinV3.Server/Data/Entities/Paste.cs @@ -8,7 +8,6 @@ namespace SharpbinV3.Server.Data.Entities [Index(nameof(ID), IsUnique = true)] [Index(nameof(AuthorUUID))] [Index(nameof(ExpiresAt))] - [Index(nameof(Views))] [Index(nameof(Visibility))] public sealed class Paste { @@ -33,5 +32,7 @@ namespace SharpbinV3.Server.Data.Entities public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private (encrypted pastes handled on frontend) public long ExpiresAt { get; set; } // timestamp of when the paste expires, or 0 for never + + public List PasteViews { get; set; } = []; } } diff --git a/SharpbinV3.Server/Data/Entities/PasteView.cs b/SharpbinV3.Server/Data/Entities/PasteView.cs new file mode 100644 index 0000000..577f4d8 --- /dev/null +++ b/SharpbinV3.Server/Data/Entities/PasteView.cs @@ -0,0 +1,17 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; + +namespace SharpbinV3.Server.Data.Entities +{ + [Index(nameof(PastePID), nameof(ViewerHash), IsUnique = true)] + public class PasteView + { + [Key] + public int Id { get; set; } + public int PastePID { get; set; } + [MaxLength(64)] + public string ViewerHash { get; set; } = null!; + public long ViewedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + public Paste Paste { get; set; } = null!; + } +} diff --git a/SharpbinV3.Server/Migrations/20260109221625_PasteViews.Designer.cs b/SharpbinV3.Server/Migrations/20260109221625_PasteViews.Designer.cs new file mode 100644 index 0000000..52bbc31 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260109221625_PasteViews.Designer.cs @@ -0,0 +1,260 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SharpbinV3.Server.Data; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260109221625_PasteViews")] + partial class PasteViews + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.1"); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Property("PID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AuthorUUID") + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("BLOB"); + + b.Property("EditedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("ID") + .HasColumnType("TEXT"); + + b.Property("IsCompressed") + .HasColumnType("INTEGER"); + + b.Property("Size") + .HasColumnType("INTEGER"); + + b.Property("Syntax") + .HasColumnType("TEXT"); + + b.Property("Title") + .HasColumnType("TEXT"); + + b.Property("TrueSize") + .HasColumnType("INTEGER"); + + b.Property("UUID") + .HasColumnType("TEXT"); + + b.Property("Views") + .HasColumnType("INTEGER"); + + b.Property("Visibility") + .HasColumnType("INTEGER"); + + b.HasKey("PID"); + + b.HasIndex("AuthorUUID"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("ID") + .IsUnique(); + + b.HasIndex("PID") + .IsUnique(); + + b.HasIndex("UUID") + .IsUnique(); + + b.HasIndex("Visibility"); + + b.ToTable("Pastes"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ViewedAt") + .HasColumnType("INTEGER"); + + b.Property("ViewerHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("PastePID", "ViewerHash") + .IsUnique(); + + b.ToTable("PasteViews"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => + { + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("ExpiresAt") + .HasColumnType("INTEGER"); + + b.Property("JwtId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Token") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Used") + .HasColumnType("INTEGER"); + + b.HasKey("UserUUID"); + + b.ToTable("RefreshTokens"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Property("UUID") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasColumnType("TEXT"); + + b.Property("LastLogin") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.PrimitiveCollection("Roles") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UID") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Visibility") + .HasColumnType("INTEGER"); + + b.HasKey("UUID"); + + b.HasIndex("UID"); + + b.HasIndex("UUID") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => + { + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("EncryptedSecret") + .IsRequired() + .HasColumnType("BLOB"); + + b.HasKey("UserUUID"); + + b.ToTable("UserTotps"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Pastes") + .HasForeignKey("AuthorUUID") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("PasteViews") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Paste"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("RefreshTokens") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithOne("Totp") + .HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Navigation("PasteViews"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Navigation("Pastes"); + + b.Navigation("RefreshTokens"); + + b.Navigation("Totp"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260109221625_PasteViews.cs b/SharpbinV3.Server/Migrations/20260109221625_PasteViews.cs new file mode 100644 index 0000000..62ee571 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260109221625_PasteViews.cs @@ -0,0 +1,57 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + /// + public partial class PasteViews : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Pastes_Views", + table: "Pastes"); + + migrationBuilder.CreateTable( + name: "PasteViews", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + PastePID = table.Column(type: "INTEGER", nullable: false), + ViewerHash = table.Column(type: "TEXT", maxLength: 64, nullable: false), + ViewedAt = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PasteViews", x => x.Id); + table.ForeignKey( + name: "FK_PasteViews_Pastes_PastePID", + column: x => x.PastePID, + principalTable: "Pastes", + principalColumn: "PID", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_PasteViews_PastePID_ViewerHash", + table: "PasteViews", + columns: new[] { "PastePID", "ViewerHash" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PasteViews"); + + migrationBuilder.CreateIndex( + name: "IX_Pastes_Views", + table: "Pastes", + column: "Views"); + } + } +} diff --git a/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs b/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs index d87f0db..5198bac 100644 --- a/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs +++ b/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs @@ -78,13 +78,36 @@ namespace SharpbinV3.Server.Migrations b.HasIndex("UUID") .IsUnique(); - b.HasIndex("Views"); - b.HasIndex("Visibility"); b.ToTable("Pastes"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ViewedAt") + .HasColumnType("INTEGER"); + + b.Property("ViewerHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("PastePID", "ViewerHash") + .IsUnique(); + + b.ToTable("PasteViews"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => { b.Property("UserUUID") @@ -182,6 +205,17 @@ namespace SharpbinV3.Server.Migrations b.Navigation("User"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("PasteViews") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Paste"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b => { b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") @@ -204,6 +238,11 @@ namespace SharpbinV3.Server.Migrations b.Navigation("User"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => + { + b.Navigation("PasteViews"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => { b.Navigation("Pastes"); diff --git a/SharpbinV3.Server/Program.cs b/SharpbinV3.Server/Program.cs index a754d9d..4fe466c 100644 --- a/SharpbinV3.Server/Program.cs +++ b/SharpbinV3.Server/Program.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using SharpbinV3.Server.Authorization; using SharpbinV3.Server.Data; @@ -32,6 +33,7 @@ namespace SharpbinV3.Server }); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -43,24 +45,36 @@ namespace SharpbinV3.Server builder.Services.AddHealthChecks() .AddDbContextCheck("Database"); - builder.Services - .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) - .AddJwtBearer(jwt => - { - var jwtSettings = builder.Configuration.GetSection("JwtSettings"); - var key = Encoding.UTF8.GetBytes(jwtSettings["Secret"]!); + builder.Services.AddOptions() + .Bind(builder.Configuration.GetSection("PasteSettings")) + .ValidateDataAnnotations() + .ValidateOnStart(); + builder.Services.AddOptions() + .Bind(builder.Configuration.GetSection("JwtSettings")) + .ValidateDataAnnotations() + .ValidateOnStart(); + builder.Services.Configure(builder.Configuration.GetSection("AuthSettings")); - jwt.SaveToken = true; - jwt.TokenValidationParameters = new TokenValidationParameters + 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 { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = true, - ValidIssuer = jwtSettings["Issuer"], + ValidIssuer = settings.Issuer, ValidateAudience = true, - ValidAudience = jwtSettings["Audience"], + ValidAudience = settings.Audience, RequireExpirationTime = true, ValidateLifetime = true, @@ -70,6 +84,7 @@ namespace SharpbinV3.Server ValidAlgorithms = [SecurityAlgorithms.HmacSha256] }; }); + builder.Services.AddAuthorizationBuilder() .AddPolicy("NotBanned", policy => policy.Requirements.Add(new NotBannedRequirement())); @@ -100,9 +115,6 @@ namespace SharpbinV3.Server .AllowAnyHeader() .AllowAnyMethod()); }); - builder.Services.Configure(builder.Configuration.GetSection("PasteSettings")); - builder.Services.Configure(builder.Configuration.GetSection("JWTSettings")); - builder.Services.Configure(builder.Configuration.GetSection("AuthSettings")); builder.Services.AddDataProtection() .PersistKeysToFileSystem(GetDataProtectionKeyDirectory(builder.Environment)) diff --git a/SharpbinV3.Server/README.md b/SharpbinV3.Server/README.md index 8b8be7c..a7f5740 100644 --- a/SharpbinV3.Server/README.md +++ b/SharpbinV3.Server/README.md @@ -17,7 +17,15 @@ The server configuration is managed in `appsettings.json`. For development, ensu - `JwtSettings__Secret`: A secure string used for signing JWT tokens. - `AuthSettings__CF_Turnstile_SecretKey`: Your Cloudflare Turnstile secret key. - `AuthSettings__CF_Turnstile_SiteKey`: Your Cloudflare Turnstile site key. +- `AuthSettings__Registration_Enabled`: Set to `true` by default, enables/disables registration. - `AuthSettings__First_User_Admin`: Gives the first user the admin role, it is recommended to disable this after use. +- `AuthSettings__Admins_Require_2FA`: Enforces Admins to have 2FA when trying to do certain actions. +- `PasteSettings__MaxTitleLength`: Max title length in characters. +- `PasteSettings__MaxPasteSizeInBytes`: Max Paste Size set in bytes, the default is `1_048_576` (1MB) +- `PasteSettings__EnablePasteCompression`: Enables/Disables server-side paste compression, `true` by default. +- `PasteSettings__RequiresVerification`: Enables/Disables CAPTCHA verification when creating pastes, `true` by default. +- `PasteSettings__View_HMAC_Secret`: Required to securely hash viewer identifiers +- `PasteSettings__View_Internal_API_Key`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend. ### Database Migrations diff --git a/SharpbinV3.Server/Services/PasteCleanUpService.cs b/SharpbinV3.Server/Services/PasteCleanUpService.cs index 6c5adc5..6ecd62c 100644 --- a/SharpbinV3.Server/Services/PasteCleanUpService.cs +++ b/SharpbinV3.Server/Services/PasteCleanUpService.cs @@ -29,14 +29,9 @@ namespace SharpbinV3.Server.Services var db = scope.ServiceProvider.GetRequiredService(); long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var expiredPastes = db.Pastes.Where(p => p.ExpiresAt != 0 && p.ExpiresAt <= now); - if (await expiredPastes.AnyAsync(stoppingToken)) - { - var deletedCount = await expiredPastes.CountAsync(stoppingToken); - db.Pastes.RemoveRange(expiredPastes); - await db.SaveChangesAsync(stoppingToken); + var deletedCount = await expiredPastes.ExecuteDeleteAsync(stoppingToken); + if (deletedCount > 0) logger.LogInformation("Deleted {Count} expired pastes", deletedCount); - } - } } } diff --git a/SharpbinV3.Server/Services/PasteService.cs b/SharpbinV3.Server/Services/PasteService.cs index c352b64..4b98e8b 100644 --- a/SharpbinV3.Server/Services/PasteService.cs +++ b/SharpbinV3.Server/Services/PasteService.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.Options; using SharpbinV3.Server.Data; using SharpbinV3.Server.Data.Entities; +using SharpbinV3.Server.Extensions; using SharpbinV3.Server.Settings; using System.Text; @@ -79,6 +80,37 @@ namespace SharpbinV3.Server.Services var result = await _db.SaveChangesAsync(); return result > 0; } + public async Task<(Paste? paste, bool alreadyExists)> RecordView(Paste paste, HttpContext context) + { + if (paste == null) return (null, false); + if (context == null) return (null, false); + if (_pasteSettings.View_HMAC_Secret == null) return (null, false); + + var viewerIp = context.GetRequestIP(); + var viewerUserAgent = context.Request.Headers.UserAgent.ToString(); + JwtUser? viewerUser = context.GetJwtUser(); + + string viewerHash; + if (viewerUser != null) + viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerUser.UUID.ToString()); + else + viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerIp + viewerUserAgent); + + if (await _db.PasteViews.AnyAsync(pv => pv.PastePID == paste.PID && pv.ViewerHash == viewerHash)) + return (null, true); + + _db.PasteViews.Add(new PasteView + { + PastePID = paste.PID, + ViewerHash = viewerHash, + ViewedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + }); + + paste.Views += 1; + _db.Pastes.Update(paste); + var result = await _db.SaveChangesAsync(); + return (result > 0 ? paste : null, result > 0); + } public async Task Get(string id) { var paste = await _db.Pastes.Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id); diff --git a/SharpbinV3.Server/Services/PasteViewCleanUpService.cs b/SharpbinV3.Server/Services/PasteViewCleanUpService.cs new file mode 100644 index 0000000..aebadaa --- /dev/null +++ b/SharpbinV3.Server/Services/PasteViewCleanUpService.cs @@ -0,0 +1,50 @@ +using Microsoft.EntityFrameworkCore; +using SharpbinV3.Server.Data; + +namespace SharpbinV3.Server.Services +{ + public sealed class PasteViewCleanUpService( + IServiceProvider serviceProvider, + ILogger logger + ) : BackgroundService + { + private static readonly TimeSpan Period = TimeSpan.FromHours(1); + private static readonly long RetentionMs = + (long)TimeSpan.FromDays(7).TotalMilliseconds; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(Period); + + while (!stoppingToken.IsCancellationRequested && + await timer.WaitForNextTickAsync(stoppingToken)) + { + try + { + await Cleanup(stoppingToken); + } + catch (Exception ex) + { + logger.LogWarning(ex, "PasteView cleanup failed"); + } + } + } + + private async Task Cleanup(CancellationToken token) + { + using var scope = serviceProvider.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var cutoff = + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - RetentionMs; + + var deleted = await db.PasteViews + .Where(v => v.ViewedAt < cutoff) + .ExecuteDeleteAsync(token); + + if (deleted > 0) + logger.LogInformation("Deleted {Count} stale paste views", deleted); + } + } + +} \ No newline at end of file diff --git a/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs b/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs index 10622fe..bf76530 100644 --- a/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs +++ b/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs @@ -6,18 +6,11 @@ using SharpbinV3.Server.Data; namespace SharpbinV3.Server.Services.Verification.Providers { - public sealed class TotpVerificationProvider : IVerificationProvider + public sealed class TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache) : IVerificationProvider { - private readonly AppDbContext _db; - private readonly IDataProtector _protector; - private readonly IMemoryCache _cache; - - public TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache) - { - _db = db; - _protector = dataProtectionProvider.CreateProtector("TotpSecret-v1"); - _cache = cache; - } + private readonly AppDbContext _db = db; + private readonly IDataProtector _protector = dataProtectionProvider.CreateProtector("TotpSecret-v1"); + private readonly IMemoryCache _cache = cache; public int Priority => 0; public bool IsConfigured => false; @@ -62,12 +55,10 @@ namespace SharpbinV3.Server.Services.Verification.Providers return VerifyCode(secret, code, out _, digits, period, window); } - private bool VerifyCode(byte[] secret, string code, out long matchedStep, int digits = 6, int period = 30, int window = 1) + private static bool VerifyCode(byte[] secret, string code, out long matchedStep, int digits = 6, int period = 30, int window = 1) { var totp = new Totp(secret, step: period, mode: OtpHashMode.Sha1, totpSize: digits); return totp.VerifyTotp(code, out matchedStep, new VerificationWindow(previous: window, future: window)); } - - private string ComputeCode(byte[] key, long timestep, int digits) => new Totp(key, totpSize: digits).ComputeTotp(DateTime.UtcNow); } } diff --git a/SharpbinV3.Server/Settings/JWTSettings.cs b/SharpbinV3.Server/Settings/JWTSettings.cs index 965d6bf..d120035 100644 --- a/SharpbinV3.Server/Settings/JWTSettings.cs +++ b/SharpbinV3.Server/Settings/JWTSettings.cs @@ -1,9 +1,14 @@ -namespace SharpbinV3.Server.Settings +using System.ComponentModel.DataAnnotations; + +namespace SharpbinV3.Server.Settings { public class JWTSettings { + [Required, MinLength(32), MaxLength(128)] public string Secret { get; set; } = string.Empty; + [Required, MaxLength(128)] public string Issuer { get; set; } = "SharpbinApi"; + [Required, MaxLength(128)] public string Audience { get; set; } = "SharpbinClient"; } } diff --git a/SharpbinV3.Server/Settings/PasteSettings.cs b/SharpbinV3.Server/Settings/PasteSettings.cs index e36780d..20d87aa 100644 --- a/SharpbinV3.Server/Settings/PasteSettings.cs +++ b/SharpbinV3.Server/Settings/PasteSettings.cs @@ -1,4 +1,6 @@ -namespace SharpbinV3.Server.Settings +using System.ComponentModel.DataAnnotations; + +namespace SharpbinV3.Server.Settings { public class PasteSettings { @@ -7,5 +9,9 @@ public int MaxPasteSizeInBytes { get; set; } = 1_048_576; // 1 MB public bool EnablePasteCompression { get; set; } = true; public bool RequiresVerfication { get; set; } = true; + [Required, MinLength(32), MaxLength(128)] + public string View_HMAC_Secret { get; set; } = string.Empty; + [MinLength(32), MaxLength(128)] + public string View_Internal_API_Key { get; set; } = string.Empty; } } diff --git a/SharpbinV3.Server/Utilities.cs b/SharpbinV3.Server/Utilities.cs index c4ddbf6..1401ca2 100644 --- a/SharpbinV3.Server/Utilities.cs +++ b/SharpbinV3.Server/Utilities.cs @@ -1,4 +1,6 @@ -namespace SharpbinV3.Server +using System.Security.Cryptography; + +namespace SharpbinV3.Server { public class Utilities { @@ -8,5 +10,16 @@ var random = new Random(); return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]); } + + public static string ComputeHmacSha256(string secret, string input) + { + var secretBytes = System.Text.Encoding.UTF8.GetBytes(secret); + var inputBytes = System.Text.Encoding.UTF8.GetBytes(input); + + using var hmac = new HMACSHA256(secretBytes); + var hashBytes = hmac.ComputeHash(inputBytes); + + return Convert.ToHexString(hashBytes); + } } } diff --git a/SharpbinV3.Server/appsettings.Development.json b/SharpbinV3.Server/appsettings.Development.json index 0ae2711..087b9f7 100644 --- a/SharpbinV3.Server/appsettings.Development.json +++ b/SharpbinV3.Server/appsettings.Development.json @@ -13,5 +13,9 @@ "Secret": "ad277c181e51d2131017abc53a5805ccb85410ab902d2e1e09266304e4e86d6c38f2b2543b708d678dfdbfb76016dcf568925ddb25dc91638a69e479e31a23c9", "Issuer": "SharpbinApi", "Audience": "SharpbinClient" + }, + "PasteSettings": { + "View_HMAC_Secret": "1341551a3f1ae93b98dc690b50dd514ed99da49459fda56d7b8c739d754b6e05cbd05ad820cbd2b77c246289d022e311a2e07df9bacb5a17caea38e125b97667", + "View_HMAC_Internal_API_Key": "1fabd25116c87818550b11448ef609c572dd60b2aac2af9d893eb16b754f6dac" } }