From 14bbd9c762f641ac738714822d19845d86bb6582 Mon Sep 17 00:00:00 2001 From: whoswhip Date: Sat, 10 Jan 2026 00:06:36 -0500 Subject: [PATCH] feat: reporting apis; better rate limiting refactor: change certain apis to be more REST like (e.g. DELETE /api/paste/{pasteId}/delete -> DELETE /api/paste/{pasteId} --- .../src/routes/[id]/+page.server.ts | 10 +- .../src/routes/[id]/+page.svelte | 6 +- .../Controllers/AuthController.cs | 5 +- .../Controllers/PasteController.cs | 175 +++++++-- .../Controllers/UserController.cs | 104 +++++- SharpbinV3.Server/DTOs/ReportDto.cs | 15 + SharpbinV3.Server/Data/AppDbContext.cs | 14 +- SharpbinV3.Server/Data/Entities/Paste.cs | 1 + SharpbinV3.Server/Data/Entities/Report.cs | 56 +++ SharpbinV3.Server/Data/Entities/User.cs | 1 + .../20260110050306_Reports.Designer.cs | 331 ++++++++++++++++++ .../Migrations/20260110050306_Reports.cs | 81 +++++ .../Migrations/AppDbContextModelSnapshot.cs | 71 ++++ SharpbinV3.Server/Program.cs | 61 +++- SharpbinV3.Server/Services/ReportService.cs | 71 ++++ 15 files changed, 954 insertions(+), 48 deletions(-) create mode 100644 SharpbinV3.Server/DTOs/ReportDto.cs create mode 100644 SharpbinV3.Server/Data/Entities/Report.cs create mode 100644 SharpbinV3.Server/Migrations/20260110050306_Reports.Designer.cs create mode 100644 SharpbinV3.Server/Migrations/20260110050306_Reports.cs create mode 100644 SharpbinV3.Server/Services/ReportService.cs diff --git a/SharpbinV3.Client/src/routes/[id]/+page.server.ts b/SharpbinV3.Client/src/routes/[id]/+page.server.ts index 8acd3ba..a50d8cd 100644 --- a/SharpbinV3.Client/src/routes/[id]/+page.server.ts +++ b/SharpbinV3.Client/src/routes/[id]/+page.server.ts @@ -8,8 +8,8 @@ const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050'; export const load: PageServerLoad = async ({ params, fetch, url, cookies }) => { const { id } = params; - const paste = await fetch(`${apiUrl}/api/paste/${id}`); - if (paste.status === 404) { + const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`); + if (pasteRes.status === 404) { return { status: 404, error: { message: 'Paste not found' } @@ -27,7 +27,9 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies }) => { } }); - const pasteData = (await paste.json()) as Paste; + const pasteData = await pasteRes.json(); + const paste = pasteData.paste as Paste; + if (viewed.status === 200) { const viewJson = await viewed.json(); if (viewJson.success === true && viewJson.message !== 'View already recorded.') { @@ -49,5 +51,5 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies }) => { const options = await pasteOptions.json(); const content = await pasteContent.text(); - return { paste: pasteData, content, options, url: url.href }; + return { paste, content, options, url: url.href }; }; diff --git a/SharpbinV3.Client/src/routes/[id]/+page.svelte b/SharpbinV3.Client/src/routes/[id]/+page.svelte index b82c05d..4c49c78 100644 --- a/SharpbinV3.Client/src/routes/[id]/+page.svelte +++ b/SharpbinV3.Client/src/routes/[id]/+page.svelte @@ -171,7 +171,7 @@ const encrypted = await encryptAES(content, password); content = encrypted; } - const res = await fetch(`/api/paste/${data.paste.id}/edit`, { + const res = await fetch(`/api/paste/${data.paste.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', @@ -196,7 +196,7 @@ metadata?.title !== data.paste.title) && metadata !== null ) { - const res = await fetch(`/api/paste/${data.paste.id}/modify`, { + const res = await fetch(`/api/paste/${data.paste.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', @@ -582,7 +582,7 @@ if (!token) { return; } - const res = await fetch(`/api/paste/${data.paste?.id}/delete`, { + const res = await fetch(`/api/paste/${data.paste?.id}`, { method: 'DELETE', headers: { Authorization: `Bearer ${token}` diff --git a/SharpbinV3.Server/Controllers/AuthController.cs b/SharpbinV3.Server/Controllers/AuthController.cs index be2b2b0..c32447e 100644 --- a/SharpbinV3.Server/Controllers/AuthController.cs +++ b/SharpbinV3.Server/Controllers/AuthController.cs @@ -29,7 +29,7 @@ namespace SharpbinV3.Server.Controllers private readonly AppDbContext _db = db; [HttpPost] - [EnableRateLimiting("Sliding")] + [EnableRateLimiting("Strict")] [Route("register")] public async Task Register([FromBody] RegisterUserDto request) { @@ -75,7 +75,7 @@ namespace SharpbinV3.Server.Controllers [HttpPost] [Route("login")] - [EnableRateLimiting("Sliding")] + [EnableRateLimiting("Strict")] public async Task Login([FromBody] LoginUserDto request) { if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email)) @@ -169,6 +169,7 @@ namespace SharpbinV3.Server.Controllers [HttpPost] [Authorize] [Route("totp/enable")] + [EnableRateLimiting("Sensitive")] public async Task EnableTotp([FromBody] EnableTotpDto request) { var uuidClaim = User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value; diff --git a/SharpbinV3.Server/Controllers/PasteController.cs b/SharpbinV3.Server/Controllers/PasteController.cs index 3806aa1..9475a9e 100644 --- a/SharpbinV3.Server/Controllers/PasteController.cs +++ b/SharpbinV3.Server/Controllers/PasteController.cs @@ -1,7 +1,9 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; using Microsoft.Extensions.Options; using SharpbinV3.Server.Data.Entities; +using SharpbinV3.Server.DTOs; using SharpbinV3.Server.DTOs.Paste; using SharpbinV3.Server.Extensions; using SharpbinV3.Server.Services; @@ -12,17 +14,20 @@ namespace SharpbinV3.Server.Controllers { [Route("api/[controller]")] [ApiController] - public class PasteController(PasteService pasteService, VerificationService verificationService, AuthService authService, IOptions options, IOptions authSettings) : ControllerBase + public class PasteController(PasteService pasteService, VerificationService verificationService, AuthService authService, + ReportService reportService, IOptions options, IOptions authSettings) : ControllerBase { private readonly PasteService _pasteService = pasteService; private readonly VerificationService _verificationService = verificationService; private readonly AuthService _authService = authService; + private readonly ReportService _reportService = reportService; private readonly PasteSettings _pasteSettings = options.Value; private readonly AuthSettings _authSettings = authSettings.Value; [HttpPost] [Route("create")] [Authorize(Policy = "NotBanned")] + [EnableRateLimiting("Strict")] public async Task CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0, string? token = null) { if (!await _pasteService.ValidateExpiresAt(expiresAt)) @@ -59,33 +64,38 @@ namespace SharpbinV3.Server.Controllers paste.ExpiresAt }); } + [HttpGet] [Route("{id}")] public async Task GetPasteByID(string id) { var paste = await _pasteService.Get(id); - if (paste == null) return NotFound(); + if (paste == null) + return NotFound(new { success = false, message = "Paste not found"}); return Ok(new { - paste.ID, - paste.UUID, - paste.Title, - paste.Size, - paste.TrueSize, - paste.IsCompressed, - paste.Views, - paste.Syntax, - paste.Visibility, - paste.ExpiresAt, - paste.EditedAt, - Author = paste.User != null && paste.User.Visibility == 0 ? new - { - paste.User.UID, - paste.User.UUID, - paste.User.Username, - paste.User.DisplayName, - paste.User.Visibility - } : null + success = true, + paste = new { + paste.ID, + paste.UUID, + paste.Title, + paste.Size, + paste.TrueSize, + paste.IsCompressed, + paste.Views, + paste.Syntax, + paste.Visibility, + paste.ExpiresAt, + paste.EditedAt, + Author = paste.User != null && paste.User.Visibility == 0 ? new + { + paste.User.UID, + paste.User.UUID, + paste.User.Username, + paste.User.DisplayName, + paste.User.Visibility + } : null + } }); } [HttpGet] @@ -95,18 +105,13 @@ namespace SharpbinV3.Server.Controllers var paste = await _pasteService.Get(id); if (paste == null) return NotFound(); if (paste.IsCompressed) - { Response.Headers.Append("Content-Encoding", "gzip"); - return File(paste.Content, "application/octet-stream"); - } - else - { - return File(paste.Content, "text/plain; charset=utf-8"); - } + + return File(paste.Content, "text/plain; charset=utf-8"); } [HttpPut] - [Route("{id}/edit")] + [Route("{id}")] [Authorize(Policy = "AuthAndNotBanned")] public async Task EditPaste(string id) { @@ -134,7 +139,7 @@ namespace SharpbinV3.Server.Controllers } [HttpPatch] - [Route("{id}/modify")] + [Route("{id}")] [Authorize(Policy = "AuthAndNotBanned")] public async Task ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request) { @@ -190,8 +195,9 @@ namespace SharpbinV3.Server.Controllers } }); } + [HttpDelete] - [Route("{id}/delete")] + [Route("{id}")] [Authorize(Policy = "AuthAndNotBanned")] public async Task DeletePaste(string id) { @@ -221,6 +227,7 @@ namespace SharpbinV3.Server.Controllers 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) @@ -237,6 +244,112 @@ namespace SharpbinV3.Server.Controllers return Ok(new { success = true, message = "Paste view recorded." }); } + [HttpPost] + [Route("{id}/report")] + [Authorize(Policy = "AuthAndNotBanned")] + [EnableRateLimiting("Sensitive")] + public async Task ReportPaste(string id, [FromBody] ReportDto request) + { + var paste = await _pasteService.Get(id); + if (paste == null) + return NotFound(new { success = false, message = "Paste not found." }); + var user = HttpContext.GetJwtUser(); + if (user == null) + return Unauthorized(new { success = false, message = "Invalid token." }); + + Enum.TryParse(request.ReportType, true, out var reportType); + if (!Enum.IsDefined(reportType)) + return BadRequest(new { success = false, message = "Invalid report type." }); + + if (!await _verificationService.VerifyAsync(new VerificationContext + { + Token = request.VerificationToken, + Ip = HttpContext.GetRequestIP() + })) + return BadRequest(new { success = false, message = "Verification failed." }); + + + Report report = await _reportService.CreateReport(user.UUID, ReportTargetType.Paste, paste.PID, reportType, request.Description); + if (report == null) + return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." }); + + return Ok(new { success = true, message = "Paste reported successfully.", report = new + { + id = report.ReportID, + reportType, + description = report.Description + } + }); + } + + [HttpPatch] + [Route("{id}/report/{reportId}")] + [Authorize(Policy = "AuthAndNotBanned")] + [EnableRateLimiting("Sensitive")] + public async Task ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request) + { + var paste = await _pasteService.Get(id); + if (paste == null) + return NotFound(new { success = false, message = "Paste not found." }); + + var report = await _reportService.GetReportByID(reportId); + if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID) + return NotFound(new { success = false, message = "Report not found." }); + + var user = HttpContext.GetJwtUser(); + if (user == null) + return Unauthorized(new { success = false, message = "Invalid token." }); + + var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); + if (report.ReporterUUID != user.UUID && !hasPrivilegedRole) + return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." }); + + Enum.TryParse(request.ReportType, true, out var reportType); + if (!Enum.IsDefined(reportType)) + return BadRequest(new { success = false, message = "Invalid report type." }); + + report.Type = reportType; + report.Description = request.Description; + + var updatedReport = await _reportService.UpdateReport(report); + if (updatedReport == null) + return StatusCode(500, new { success = false, message = "An error occurred while updating the report." }); + + return Ok(new { success = true, message = "Report updated successfully." }); + } + + [HttpDelete] + [Route("{id}/report/{reportId}")] + [Authorize(Policy = "AuthAndNotBanned")] + [EnableRateLimiting("Sensitive")] + public async Task DeletePasteReport(string id, int reportId) + { + var paste = await _pasteService.Get(id); + if (paste == null) + return NotFound(new { success = false, message = "Paste not found." }); + + var report = await _reportService.GetReportByID(reportId); + if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID) + return NotFound(new { success = false, message = "Report not found." }); + + var user = HttpContext.GetJwtUser(); + if (user == null) + return Unauthorized(new { success = false, message = "Invalid token." }); + + var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); + if (report.ReporterUUID != user.UUID && !hasPrivilegedRole) + return StatusCode(403, new { success = false, message = "You do not have permission to delete this report." }); + + if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA) + return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); + + bool result = await _reportService.DeleteReport(report); + if (!result) + return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." }); + + return Ok(new { success = true, message = "Report deleted successfully." }); + } + [HttpGet] [Route("recent")] public async Task GetRecentPastes() diff --git a/SharpbinV3.Server/Controllers/UserController.cs b/SharpbinV3.Server/Controllers/UserController.cs index 0e03fd2..9e99f2d 100644 --- a/SharpbinV3.Server/Controllers/UserController.cs +++ b/SharpbinV3.Server/Controllers/UserController.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using SharpbinV3.Server.Data; @@ -16,12 +17,14 @@ namespace SharpbinV3.Server.Controllers { [ApiController] [Route("api/[controller]")] - public class UserController(UserService userService, AppDbContext db, TotpVerificationProvider totp, VerificationService verificationService, IOptions authSettings) : ControllerBase + public class UserController(UserService userService, AppDbContext db, TotpVerificationProvider totp, + VerificationService verificationService, ReportService reportServer, IOptions authSettings) : ControllerBase { private readonly UserService _userService = userService; private readonly AppDbContext _db = db; private readonly TotpVerificationProvider _totp = totp; private readonly VerificationService _verificationService = verificationService; + private readonly ReportService _reportService = reportServer; private readonly AuthSettings _authSettings = authSettings.Value; [HttpGet("{username}")] @@ -52,6 +55,7 @@ namespace SharpbinV3.Server.Controllers [HttpPatch("uuid/{uuid}")] [Authorize] + [EnableRateLimiting("Strict")] public async Task UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser) { if (!ModelState.IsValid) @@ -99,6 +103,7 @@ namespace SharpbinV3.Server.Controllers [HttpDelete("uuid/{uuid}")] [Authorize(Policy = "AuthAndNotBanned")] + [EnableRateLimiting("Sensitive")] public async Task DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto) { var jwtUser = HttpContext.GetJwtUser(); @@ -142,6 +147,103 @@ namespace SharpbinV3.Server.Controllers return Ok(new { message = "User deleted successfully." }); } + [HttpPost] + [Route("{uuid}/report")] + [EnableRateLimiting("Sensitive")] + [Authorize(Policy = "AuthAndNotBanned")] + public async Task ReportUser(Guid uuid, [FromBody] ReportDto request) + { + var reporter = HttpContext.GetJwtUser(); + if (reporter == null) + return Unauthorized(new { success = false, message = "Invalid token." }); + + var reportedUser = await _userService.GetByUUID(uuid); + if (reportedUser == null) + return NotFound(new { success = false, message = "User not found." }); + if (reportedUser.UUID == reporter.UUID) + return BadRequest(new { success = false, message = "You cannot report yourself." }); + Enum.TryParse(request.ReportType, true, out var reportType); + if (!Enum.IsDefined(reportType)) + return BadRequest(new { success = false, message = "Invalid report type." }); + + if (!await _verificationService.VerifyAsync(new VerificationContext + { + Token = request.VerificationToken, + Ip = HttpContext.GetRequestIP() + })) + return Unauthorized(new { success = false, message = "Invalid verification token." }); + + Report report = await _reportService.CreateReport(reporter.UUID, ReportTargetType.User, uuid, reportType, request.Description); + if (report == null) + return StatusCode(500, new { success = false, message = "An error occurred while creating the report." }); + + return Ok(new + { + success = true, + message = "Paste reported successfully.", + report = new + { + id = report.ReportID, + reportType, + description = report.Description + } + }); + } + + [HttpPatch] + [Route("{uuid}/report/{reportId}")] + [EnableRateLimiting("Sensitive")] + [Authorize(Policy = "AuthAndNotBanned")] + public async Task UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request) + { + var jwtUser = HttpContext.GetJwtUser(); + if (jwtUser == null) + return Unauthorized(new { success = false, message = "Invalid token." }); + + var user = await _userService.GetByUUID(uuid); + if (user == null) + return NotFound(new { success = false, message = "User not found." }); + + var report = await _reportService.GetReportByID(reportId); + if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID) + return NotFound(new { success = false, message = "Report not found." }); + + Enum.TryParse(request.ReportType, true, out var reportType); + if (!Enum.IsDefined(reportType)) + return BadRequest(new { success = false, message = "Invalid report type." }); + + report.Type = reportType; + report.Description = request.Description ?? report.Description; + + await _db.SaveChangesAsync(); + return Ok(new { success = true, message = "Report updated successfully." }); + } + + [HttpDelete] + [Route("{uuid}/report/{reportId}")] + [EnableRateLimiting("Sensitive")] + [Authorize(Policy = "AuthAndNotBanned")] + public async Task DeleteUserReport(Guid uuid, int reportId) + { + var jwtUser = HttpContext.GetJwtUser(); + if (jwtUser == null) + return Unauthorized(new { success = false, message = "Invalid token." }); + + var user = await _userService.GetByUUID(uuid); + if (user == null) + return NotFound(new { success = false, message = "User not found." }); + + var report = await _reportService.GetReportByID(reportId); + if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID) + return NotFound(new { success = false, message = "Report not found." }); + + var result = await _reportService.DeleteReport(report); + if (!result) + return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." }); + + return Ok(new { success = true, message = "Report deleted successfully." }); + } + private async Task BuildUserResponse(User user, int page = 1) { var isAuthenticatedUser = HttpContext.User?.FindFirst("UUID")?.Value == user.UUID.ToString(); diff --git a/SharpbinV3.Server/DTOs/ReportDto.cs b/SharpbinV3.Server/DTOs/ReportDto.cs new file mode 100644 index 0000000..81c6c4d --- /dev/null +++ b/SharpbinV3.Server/DTOs/ReportDto.cs @@ -0,0 +1,15 @@ +using System.ComponentModel.DataAnnotations; + +namespace SharpbinV3.Server.DTOs +{ + public class ReportDto + { + [Required] + [MaxLength(1000)] + public string Description { get; set; } = string.Empty; + [Required] + public string ReportType { get; set; } = string.Empty; // e.g., "Spam", "Abuse", etc. + public string ReportStatus { get; set; } = "Open"; + public string? VerificationToken { get; set; } + } +} diff --git a/SharpbinV3.Server/Data/AppDbContext.cs b/SharpbinV3.Server/Data/AppDbContext.cs index 74641cf..84343b2 100644 --- a/SharpbinV3.Server/Data/AppDbContext.cs +++ b/SharpbinV3.Server/Data/AppDbContext.cs @@ -10,6 +10,7 @@ namespace SharpbinV3.Server.Data public DbSet PasteViews => Set(); public DbSet RefreshTokens => Set(); public DbSet UserTotps => Set(); + public DbSet Reports => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -38,7 +39,18 @@ namespace SharpbinV3.Server.Data .WithOne(u => u.Totp) .HasForeignKey(t => t.UserUUID) .OnDelete(DeleteBehavior.Cascade); - } + modelBuilder.Entity() + .HasOne(r => r.Paste) + .WithMany(p => p.Reports) + .HasForeignKey(r => r.PastePID) + .OnDelete(DeleteBehavior.Cascade); + + modelBuilder.Entity() + .HasOne(r => r.User) + .WithMany(u => u.Reports) + .HasForeignKey(r => r.UserUUID) + .OnDelete(DeleteBehavior.Cascade); + } } } diff --git a/SharpbinV3.Server/Data/Entities/Paste.cs b/SharpbinV3.Server/Data/Entities/Paste.cs index 58510ba..7b79442 100644 --- a/SharpbinV3.Server/Data/Entities/Paste.cs +++ b/SharpbinV3.Server/Data/Entities/Paste.cs @@ -34,5 +34,6 @@ namespace SharpbinV3.Server.Data.Entities public long ExpiresAt { get; set; } // timestamp of when the paste expires, or 0 for never public List PasteViews { get; set; } = []; + public List Reports { get; set; } = []; } } diff --git a/SharpbinV3.Server/Data/Entities/Report.cs b/SharpbinV3.Server/Data/Entities/Report.cs new file mode 100644 index 0000000..10893f3 --- /dev/null +++ b/SharpbinV3.Server/Data/Entities/Report.cs @@ -0,0 +1,56 @@ +using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; + +namespace SharpbinV3.Server.Data.Entities +{ + [Index(nameof(ReportID), IsUnique = true)] + [Index(nameof(ReporterUUID))] + [Index(nameof(TargetType))] + [Index(nameof(PastePID))] + [Index(nameof(UserUUID))] + public class Report + { + public int? ReportID { get; set; } + + public ReportType Type { get; set; } + public ReportStatus Status { get; set; } = ReportStatus.Open; + + [MaxLength(1000)] + public string? Description { get; set; } + + public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + public long? UpdatedAt { get; set; } + + public Guid ReporterUUID { get; set; } + + public ReportTargetType TargetType { get; set; } + public int? PastePID { get; set; } + public Guid? UserUUID { get; set; } + + public Paste? Paste { get; set; } + public User? User { get; set; } + } + + + public enum ReportStatus + { + Open, + InProgress, + Resolved, + Closed + } + public enum ReportType + { + Spam, + Abuse, + InappropriateContent, + CopyrightViolation, + Fraud, + Other + } + public enum ReportTargetType + { + Paste, + User + } +} diff --git a/SharpbinV3.Server/Data/Entities/User.cs b/SharpbinV3.Server/Data/Entities/User.cs index f3441d9..b149572 100644 --- a/SharpbinV3.Server/Data/Entities/User.cs +++ b/SharpbinV3.Server/Data/Entities/User.cs @@ -21,6 +21,7 @@ namespace SharpbinV3.Server.Data.Entities public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private public List Pastes { get; set; } = []; public List RefreshTokens { get; set; } = []; + public List Reports { get; set; } = []; public UserTotp? Totp { get; set; } } } diff --git a/SharpbinV3.Server/Migrations/20260110050306_Reports.Designer.cs b/SharpbinV3.Server/Migrations/20260110050306_Reports.Designer.cs new file mode 100644 index 0000000..68f8503 --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260110050306_Reports.Designer.cs @@ -0,0 +1,331 @@ +// +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("20260110050306_Reports")] + partial class Reports + { + /// + 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.Report", b => + { + b.Property("ReportID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ReporterUUID") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("TargetType") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("ReportID"); + + b.HasIndex("PastePID"); + + b.HasIndex("ReportID") + .IsUnique(); + + b.HasIndex("ReporterUUID"); + + b.HasIndex("TargetType"); + + b.HasIndex("UserUUID"); + + b.ToTable("Reports"); + }); + + 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.Report", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Reports") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Reports") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("Paste"); + + 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"); + + b.Navigation("Reports"); + }); + + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => + { + b.Navigation("Pastes"); + + b.Navigation("RefreshTokens"); + + b.Navigation("Reports"); + + b.Navigation("Totp"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/SharpbinV3.Server/Migrations/20260110050306_Reports.cs b/SharpbinV3.Server/Migrations/20260110050306_Reports.cs new file mode 100644 index 0000000..3ad730f --- /dev/null +++ b/SharpbinV3.Server/Migrations/20260110050306_Reports.cs @@ -0,0 +1,81 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SharpbinV3.Server.Migrations +{ + /// + public partial class Reports : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Reports", + columns: table => new + { + ReportID = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Type = table.Column(type: "INTEGER", nullable: false), + Status = table.Column(type: "INTEGER", nullable: false), + Description = table.Column(type: "TEXT", maxLength: 1000, nullable: true), + CreatedAt = table.Column(type: "INTEGER", nullable: false), + UpdatedAt = table.Column(type: "INTEGER", nullable: true), + ReporterUUID = table.Column(type: "TEXT", nullable: false), + TargetType = table.Column(type: "INTEGER", nullable: false), + PastePID = table.Column(type: "INTEGER", nullable: true), + UserUUID = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Reports", x => x.ReportID); + table.ForeignKey( + name: "FK_Reports_Pastes_PastePID", + column: x => x.PastePID, + principalTable: "Pastes", + principalColumn: "PID", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Reports_Users_UserUUID", + column: x => x.UserUUID, + principalTable: "Users", + principalColumn: "UUID", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Reports_PastePID", + table: "Reports", + column: "PastePID"); + + migrationBuilder.CreateIndex( + name: "IX_Reports_ReporterUUID", + table: "Reports", + column: "ReporterUUID"); + + migrationBuilder.CreateIndex( + name: "IX_Reports_ReportID", + table: "Reports", + column: "ReportID", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Reports_TargetType", + table: "Reports", + column: "TargetType"); + + migrationBuilder.CreateIndex( + name: "IX_Reports_UserUUID", + table: "Reports", + column: "UserUUID"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Reports"); + } + } +} diff --git a/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs b/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs index 5198bac..7968a57 100644 --- a/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs +++ b/SharpbinV3.Server/Migrations/AppDbContextModelSnapshot.cs @@ -135,6 +135,56 @@ namespace SharpbinV3.Server.Migrations b.ToTable("RefreshTokens"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => + { + b.Property("ReportID") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("PastePID") + .HasColumnType("INTEGER"); + + b.Property("ReporterUUID") + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("TargetType") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("INTEGER"); + + b.Property("UserUUID") + .HasColumnType("TEXT"); + + b.HasKey("ReportID"); + + b.HasIndex("PastePID"); + + b.HasIndex("ReportID") + .IsUnique(); + + b.HasIndex("ReporterUUID"); + + b.HasIndex("TargetType"); + + b.HasIndex("UserUUID"); + + b.ToTable("Reports"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => { b.Property("UUID") @@ -227,6 +277,23 @@ namespace SharpbinV3.Server.Migrations b.Navigation("User"); }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b => + { + b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste") + .WithMany("Reports") + .HasForeignKey("PastePID") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") + .WithMany("Reports") + .HasForeignKey("UserUUID") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("Paste"); + + b.Navigation("User"); + }); + modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b => { b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") @@ -241,6 +308,8 @@ namespace SharpbinV3.Server.Migrations modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => { b.Navigation("PasteViews"); + + b.Navigation("Reports"); }); modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => @@ -249,6 +318,8 @@ namespace SharpbinV3.Server.Migrations b.Navigation("RefreshTokens"); + b.Navigation("Reports"); + b.Navigation("Totp"); }); #pragma warning restore 612, 618 diff --git a/SharpbinV3.Server/Program.cs b/SharpbinV3.Server/Program.cs index 4fe466c..3310218 100644 --- a/SharpbinV3.Server/Program.cs +++ b/SharpbinV3.Server/Program.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using SharpbinV3.Server.Authorization; using SharpbinV3.Server.Data; +using SharpbinV3.Server.Extensions; using SharpbinV3.Server.Services; using SharpbinV3.Server.Services.Verification; using SharpbinV3.Server.Services.Verification.Providers; @@ -40,6 +41,7 @@ namespace SharpbinV3.Server builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddHttpClient(); + builder.Services.AddScoped(); builder.Services.AddMemoryCache(); builder.Services.AddHealthChecks() @@ -97,16 +99,63 @@ namespace SharpbinV3.Server builder.Services.AddRateLimiter(options => { - options.AddSlidingWindowLimiter("Sliding", opt => + 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("Sensitive", httpContext => + RateLimitPartition.GetTokenBucketLimiter(httpContext.GetRequestIP(), _ => new TokenBucketRateLimiterOptions + { + TokenLimit = 3, + QueueLimit = 0, + TokensPerPeriod = 1, + ReplenishmentPeriod = TimeSpan.FromMinutes(1), + AutoReplenishment = true, + QueueProcessingOrder = QueueProcessingOrder.OldestFirst, + } + )); + + options.GlobalLimiter = PartitionedRateLimiter.Create(httpContext => { - opt.Window = TimeSpan.FromSeconds(10); - opt.PermitLimit = 10; - opt.QueueLimit = 2; - opt.SegmentsPerWindow = 5; - opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; + 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); + }; }); builder.Services.AddCors(o => { diff --git a/SharpbinV3.Server/Services/ReportService.cs b/SharpbinV3.Server/Services/ReportService.cs new file mode 100644 index 0000000..323b40e --- /dev/null +++ b/SharpbinV3.Server/Services/ReportService.cs @@ -0,0 +1,71 @@ +using Microsoft.EntityFrameworkCore; +using SharpbinV3.Server.Data; +using SharpbinV3.Server.Data.Entities; + +namespace SharpbinV3.Server.Services +{ + public class ReportService(AppDbContext db) + { + private readonly AppDbContext _db = db; + public async Task CreateReport(Guid reporterUUID, ReportTargetType targetType, Guid userUUID, ReportType type, string description) + { + var report = new Report + { + ReporterUUID = reporterUUID, + TargetType = targetType, + UserUUID = userUUID, + Type = type, + Description = description + }; + await _db.Reports.AddAsync(report); + await _db.SaveChangesAsync(); + return report; + } + public async Task CreateReport(Guid reporterUUID, ReportTargetType targetType, int? pastePID, ReportType type, string description) + { + var report = new Report + { + ReporterUUID = reporterUUID, + TargetType = targetType, + PastePID = pastePID, + Type = type, + Description = description, + }; + await _db.Reports.AddAsync(report); + await _db.SaveChangesAsync(); + return report; + } + + public async Task> GetReports(Guid reporterUUID) + { + return await _db.Reports + .Where(r => r.ReporterUUID == reporterUUID) + .ToListAsync(); + } + public async Task> GetReports(ReportTargetType targetType, int? pastePID) + { + return await _db.Reports + .Where(r => r.TargetType == targetType && r.PastePID == pastePID) + .ToListAsync(); + } + + public async Task GetReportByID(int reportID) + { + return await _db.Reports + .FirstOrDefaultAsync(r => r.ReportID == reportID); + } + + public async Task UpdateReport(Report report) + { + _db.Reports.Update(report); + await _db.SaveChangesAsync(); + return report; + } + public async Task DeleteReport(Report report) + { + _db.Reports.Remove(report); + var result = await _db.SaveChangesAsync(); + return result > 0; + } + } +}