diff --git a/SharpbinV3.Server/.csharpierignore b/SharpbinV3.Server/.csharpierignore new file mode 100644 index 0000000..25686b8 --- /dev/null +++ b/SharpbinV3.Server/.csharpierignore @@ -0,0 +1,5 @@ +Migrations/ +obj/ +bin/ +cache/ +SharpbinV3/ \ No newline at end of file diff --git a/SharpbinV3.Server/.csharpierrc b/SharpbinV3.Server/.csharpierrc new file mode 100644 index 0000000..4583cc0 --- /dev/null +++ b/SharpbinV3.Server/.csharpierrc @@ -0,0 +1,6 @@ +{ + "printWidth": 150, + "useTabs": false, + "indentSize": 4, + "endOfLine": "auto" +} diff --git a/SharpbinV3.Server/Authorization/NotBannedHandler.cs b/SharpbinV3.Server/Authorization/NotBannedHandler.cs index 70a05c8..2636626 100644 --- a/SharpbinV3.Server/Authorization/NotBannedHandler.cs +++ b/SharpbinV3.Server/Authorization/NotBannedHandler.cs @@ -1,5 +1,5 @@ -using Microsoft.AspNetCore.Authorization; -using System.Security.Claims; +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; namespace SharpbinV3.Server.Authorization { @@ -7,18 +7,14 @@ namespace SharpbinV3.Server.Authorization { private readonly bool _requireAuth = requireAuth; - protected override Task HandleRequirementAsync( - AuthorizationHandlerContext context, - NotBannedRequirement requirement) + protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement) { var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false; if (_requireAuth && !isAuthenticated) return Task.CompletedTask; - var isBanned = context.User.Claims.Any(c => - (c.Type == ClaimTypes.Role || c.Type == "role") && - c.Value == "403"); + var isBanned = context.User.Claims.Any(c => (c.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403"); if (!isBanned) context.Succeed(requirement); diff --git a/SharpbinV3.Server/Authorization/NotBannedRequirement.cs b/SharpbinV3.Server/Authorization/NotBannedRequirement.cs index cf09026..28bb17f 100644 --- a/SharpbinV3.Server/Authorization/NotBannedRequirement.cs +++ b/SharpbinV3.Server/Authorization/NotBannedRequirement.cs @@ -2,7 +2,5 @@ namespace SharpbinV3.Server.Authorization { - public class NotBannedRequirement : IAuthorizationRequirement - { - } + public class NotBannedRequirement : IAuthorizationRequirement { } } diff --git a/SharpbinV3.Server/Controllers/AuthController.cs b/SharpbinV3.Server/Controllers/AuthController.cs index e4a1077..024f21f 100644 --- a/SharpbinV3.Server/Controllers/AuthController.cs +++ b/SharpbinV3.Server/Controllers/AuthController.cs @@ -19,8 +19,14 @@ namespace SharpbinV3.Server.Controllers { [ApiController] [Route("api/[controller]")] - public class AuthController(UserService userService, AuthService authService, IOptions options, - VerificationService verification, TotpVerificationProvider totp, AppDbContext db) : ControllerBase + public class AuthController( + UserService userService, + AuthService authService, + IOptions options, + VerificationService verification, + TotpVerificationProvider totp, + AppDbContext db + ) : ControllerBase { private readonly AuthService _authService = authService; private readonly UserService _userService = userService; @@ -37,11 +43,7 @@ namespace SharpbinV3.Server.Controllers return BadRequest(new { success = false, message = "Registration is disabled." }); if (!ModelState.IsValid) return BadRequest(ModelState); - if (!await _verification.VerifyAsync(new VerificationContext - { - Token = request.Token, - Ip = HttpContext.GetRequestIP() - })) + if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() })) return BadRequest(new { success = false, message = "Verification failed." }); var existingUser = await _userService.GetByUsername(request.Username); @@ -57,21 +59,22 @@ namespace SharpbinV3.Server.Controllers return BadRequest(new { success = false, message = "Display name should not exceed 26 characters." }); var user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName); - return Ok(new - { - message = "User registered successfully.", - user = new UserResponseDto + return Ok( + new { - UID = user.UID, - UUID = user.UUID, - Username = user.Username, - DisplayName = user.DisplayName, - Email = user.Email, - Roles = user.Roles, - Visibility = user.Visibility, - LastLogin = user.LastLogin + message = "User registered successfully.", + user = new UserResponseDto + { + UID = user.UID, + UUID = user.UUID, + Username = user.Username, + DisplayName = user.DisplayName, + Email = user.Email, + Roles = user.Roles, + Visibility = user.Visibility, + LastLogin = user.LastLogin, + }, } - } ); } @@ -83,11 +86,7 @@ namespace SharpbinV3.Server.Controllers if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email)) return BadRequest(new { success = false, message = "Username or email is required." }); - if (!await _verification.VerifyAsync(new VerificationContext - { - Token = request.Token, - Ip = HttpContext.GetRequestIP() - })) + if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() })) return BadRequest(new { success = false, message = "Verification failed." }); User? user = null; @@ -104,24 +103,25 @@ namespace SharpbinV3.Server.Controllers { if (string.IsNullOrWhiteSpace(request.TotpCode)) return BadRequest(new { success = false, message = "TOTP code is required." }); - var totpValid = await _totp.VerifyAsync(new VerificationContext - { - UserUUID = user.UUID, - Code = request.TotpCode - }); + + var totpValid = await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = request.TotpCode }); + if (!totpValid) return BadRequest(new { success = false, message = "Invalid TOTP code." }); } var token = _authService.GenerateJWTToken(user); await _authService.UpdateLoginTime(user); var result = await token; - return Ok(new LoginResponseDto - { - Success = true, - Token = result.Token ?? string.Empty, - RefreshToken = result.RefreshToken ?? string.Empty - }); + return Ok( + new LoginResponseDto + { + Success = true, + Token = result.Token ?? string.Empty, + RefreshToken = result.RefreshToken ?? string.Empty, + } + ); } + [HttpPost] [Route("refresh")] [EnableRateLimiting("Sliding")] @@ -130,16 +130,17 @@ namespace SharpbinV3.Server.Controllers try { var jwtResult = await _authService.RefreshJWTToken(request.Token, request.RefreshToken); - return Ok(new TokenRefreshResponseDto - { - Success = jwtResult?.Success ?? false, - Message = jwtResult?.Errors != null && jwtResult.Errors.Count > 0 ? string.Join("; ", jwtResult.Errors) : "Token refreshed successfully.", - Token = jwtResult != null ? new TokenData + return Ok( + new TokenRefreshResponseDto { - Token = jwtResult.Token, - RefreshToken = jwtResult.RefreshToken - } : null - }); + Success = jwtResult?.Success ?? false, + Message = + jwtResult?.Errors != null && jwtResult.Errors.Count > 0 + ? string.Join("; ", jwtResult.Errors) + : "Token refreshed successfully.", + Token = jwtResult != null ? new TokenData { Token = jwtResult.Token, RefreshToken = jwtResult.RefreshToken } : null, + } + ); } catch (Exception ex) { @@ -153,11 +154,13 @@ namespace SharpbinV3.Server.Controllers public IActionResult GetSiteInfo() { var authSettings = options.Value; - return Ok(new - { - cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey, - registration_enabled = authSettings.Registration_Enabled - }); + return Ok( + new + { + cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey, + registration_enabled = authSettings.Registration_Enabled, + } + ); } [HttpGet] @@ -166,13 +169,21 @@ namespace SharpbinV3.Server.Controllers public async Task StartTotpEnrollment() { var user = await _authService.GetUserFromHttpContext(HttpContext); - if (user is null) return BadRequest(new { success = false, message = "User not found." }); + if (user is null) + return BadRequest(new { success = false, message = "User not found." }); var secret = _totp.GenerateSecret(); var secretBase32 = _totp.ToBase32(secret); var account = string.IsNullOrWhiteSpace(user.Email) ? user.Username : user.Email!; var uri = _totp.BuildOtpAuthUri("SharpbinV3", account, secretBase32); - return Ok(new { success = true, secret = secretBase32, otpauth = uri }); + return Ok( + new + { + success = true, + secret = secretBase32, + otpauth = uri, + } + ); } [HttpPost] @@ -215,17 +226,14 @@ namespace SharpbinV3.Server.Controllers public async Task DisableTotp([FromBody] DisableTotpDto dto) { var user = await _authService.GetUserFromHttpContext(HttpContext); - if (user == null) return BadRequest(new { success = false, message = "User not found." }); + if (user == null) + return BadRequest(new { success = false, message = "User not found." }); if (string.IsNullOrWhiteSpace(dto.Code)) return BadRequest(new { success = false, message = "TOTP code is required." }); var existing = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == user.UUID); if (existing is null) return BadRequest(new { success = false, message = "TOTP is not enabled." }); - if (!_totp.VerifyAsync(new VerificationContext - { - UserUUID = user.UUID, - Code = dto.Code - }).Result) + if (!_totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = dto.Code }).Result) return BadRequest(new { success = false, message = "Invalid TOTP code." }); _db.UserTotps.Remove(existing); diff --git a/SharpbinV3.Server/Controllers/PasteController.cs b/SharpbinV3.Server/Controllers/PasteController.cs index 6665c9f..74f4ab0 100644 --- a/SharpbinV3.Server/Controllers/PasteController.cs +++ b/SharpbinV3.Server/Controllers/PasteController.cs @@ -15,8 +15,14 @@ namespace SharpbinV3.Server.Controllers { [Route("api/[controller]")] [ApiController] - public class PasteController(PasteService pasteService, VerificationService verificationService, AuthService authService, - ReportService reportService, 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; @@ -29,7 +35,13 @@ namespace SharpbinV3.Server.Controllers [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) + public async Task CreatePaste( + string title = "", + string syntax = "plaintext", + int visibility = 0, + long expiresAt = 0, + string? token = null + ) { if (!_pasteService.ValidateExpiresAt(expiresAt)) return BadRequest(new { success = false, message = "Invalid expiration time." }); @@ -44,27 +56,30 @@ namespace SharpbinV3.Server.Controllers if (content.Length == 0) return BadRequest(new { success = false, message = "Paste content cannot be empty." }); if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes) - return BadRequest(new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }); + return BadRequest( + new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." } + ); - if (_pasteSettings.RequiresVerification && !await _verificationService.VerifyAsync(new VerificationContext - { - Token = token, - Ip = HttpContext.GetRequestIP() - })) + if ( + _pasteSettings.RequiresVerification + && !await _verificationService.VerifyAsync(new VerificationContext { Token = token, Ip = HttpContext.GetRequestIP() }) + ) return BadRequest(new { success = false, message = "Verification failed." }); var user = await _authService.GetUserFromHttpContext(HttpContext); Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression); - return Ok(new PasteCreatedResponseDto - { - ID = paste.ID, - UUID = paste.UUID, - CreatedAt = paste.CreatedAt, - IsCompressed = paste.IsCompressed, - Size = paste.Size, - TrueSize = paste.TrueSize, - ExpiresAt = paste.ExpiresAt - }); + return Ok( + new PasteCreatedResponseDto + { + ID = paste.ID, + UUID = paste.UUID, + CreatedAt = paste.CreatedAt, + IsCompressed = paste.IsCompressed, + Size = paste.Size, + TrueSize = paste.TrueSize, + ExpiresAt = paste.ExpiresAt, + } + ); } [HttpGet] @@ -79,42 +94,44 @@ namespace SharpbinV3.Server.Controllers int? reportCount = null; if (jwtUser != null && jwtUser.Roles.Any(r => r == 1 || r == 255)) { - var query = new ReportQuery - { - PastePID = paste.PID - }; + var query = new ReportQuery { PastePID = paste.PID }; reportCount = await _reportService.GetReportCount(query); } - return Ok(new - { - success = true, - paste = new PasteResponseDto + return Ok( + new { - ID = paste.ID, - UUID = paste.UUID, - CreatedAt = paste.CreatedAt, - Title = paste.Title, - Size = paste.Size, - TrueSize = paste.TrueSize, - IsCompressed = paste.IsCompressed, - Views = paste.Views, - Syntax = paste.Syntax, - Visibility = paste.Visibility, - ExpiresAt = paste.ExpiresAt, - EditedAt = paste.EditedAt, - ReportCount = reportCount, - Author = paste.User != null && paste.User.Visibility == 0 ? new UserSimpleDto + success = true, + paste = new PasteResponseDto { - UID = paste.User.UID, - UUID = paste.User.UUID, - Username = paste.User.Username, - DisplayName = paste.User.DisplayName, - Visibility = paste.User.Visibility, - Roles = paste.User.Roles - } : null + ID = paste.ID, + UUID = paste.UUID, + CreatedAt = paste.CreatedAt, + Title = paste.Title, + Size = paste.Size, + TrueSize = paste.TrueSize, + IsCompressed = paste.IsCompressed, + Views = paste.Views, + Syntax = paste.Syntax, + Visibility = paste.Visibility, + ExpiresAt = paste.ExpiresAt, + EditedAt = paste.EditedAt, + ReportCount = reportCount, + Author = + paste.User != null && paste.User.Visibility == 0 + ? new UserSimpleDto + { + UID = paste.User.UID, + UUID = paste.User.UUID, + Username = paste.User.Username, + DisplayName = paste.User.DisplayName, + Visibility = paste.User.Visibility, + Roles = paste.User.Roles, + } + : null, + }, } - }); + ); } [HttpGet] @@ -122,7 +139,8 @@ namespace SharpbinV3.Server.Controllers public async Task GetRawPasteByID(string id) { var paste = await _pasteService.Get(id); - if (paste == null) return NotFound(); + if (paste == null) + return NotFound(); if (paste.IsCompressed) Response.Headers.Append("Content-Encoding", "gzip"); @@ -153,7 +171,8 @@ namespace SharpbinV3.Server.Controllers return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); bool result = await _pasteService.EditText(paste, content); - if (!result) return StatusCode(500, new { success = false, message = "An error occurred while editing the paste." }); + if (!result) + return StatusCode(500, new { success = false, message = "An error occurred while editing the paste." }); return Ok(new { message = "Paste edited successfully." }); } @@ -195,25 +214,27 @@ namespace SharpbinV3.Server.Controllers return BadRequest(new { success = false, message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." }); var newPaste = await _pasteService.Edit(paste); - return Ok(new - { - success = true, - message = "Paste metadata updated successfully.", - paste = new PasteResponseDto + return Ok( + new { - ID = newPaste.ID, - UUID = newPaste.UUID, - CreatedAt = newPaste.CreatedAt, - Title = newPaste.Title, - Size = newPaste.Size, - TrueSize = newPaste.TrueSize, - IsCompressed = newPaste.IsCompressed, - Views = newPaste.Views, - Syntax = newPaste.Syntax, - Visibility = newPaste.Visibility, - ExpiresAt = newPaste.ExpiresAt + success = true, + message = "Paste metadata updated successfully.", + paste = new PasteResponseDto + { + ID = newPaste.ID, + UUID = newPaste.UUID, + CreatedAt = newPaste.CreatedAt, + Title = newPaste.Title, + Size = newPaste.Size, + TrueSize = newPaste.TrueSize, + IsCompressed = newPaste.IsCompressed, + Views = newPaste.Views, + Syntax = newPaste.Syntax, + Visibility = newPaste.Visibility, + ExpiresAt = newPaste.ExpiresAt, + }, } - }); + ); } [HttpDelete] @@ -222,7 +243,8 @@ namespace SharpbinV3.Server.Controllers public async Task DeletePaste(string id) { var paste = await _pasteService.Get(id); - if (paste == null) return NotFound(new { success = false, message = "Paste not found." }); + if (paste == null) + return NotFound(new { success = false, message = "Paste not found." }); var user = HttpContext.GetJwtUser(); if (user == null) @@ -235,7 +257,8 @@ namespace SharpbinV3.Server.Controllers return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); bool result = await _pasteService.Delete(paste); - if (!result) return StatusCode(500, new { success = false, message = "An error occurred while deleting the paste." }); + if (!result) + return StatusCode(500, new { success = false, message = "An error occurred while deleting the paste." }); return Ok(new { success = true, message = "Paste deleted successfully." }); } @@ -250,8 +273,10 @@ namespace SharpbinV3.Server.Controllers 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"]) + 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); @@ -281,35 +306,36 @@ namespace SharpbinV3.Server.Controllers 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() - })) + 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 ReportResponseDto + return Ok( + new { - ReportID = report.ReportID, - Type = report.Type, - Status = report.Status, - Description = report.Description, - CreatedAt = report.CreatedAt, - UpdatedAt = report.UpdatedAt, - ReporterUUID = report.ReporterUUID, - TargetType = report.TargetType, - UserUUID = report.UserUUID + success = true, + message = "Paste reported successfully.", + report = new ReportResponseDto + { + ReportID = report.ReportID, + Type = report.Type, + Status = report.Status, + Description = report.Description, + CreatedAt = report.CreatedAt, + UpdatedAt = report.UpdatedAt, + ReporterUUID = report.ReporterUUID, + TargetType = report.TargetType, + UserUUID = report.UserUUID, + }, } - }); + ); } [HttpPatch] @@ -385,30 +411,35 @@ namespace SharpbinV3.Server.Controllers public async Task GetRecentPastes() { var results = await _pasteService.GetList(0, 50, true); - return Ok(results.Select(p => new PasteResponseDto - { - ID = p.ID, - UUID = p.UUID, - CreatedAt = p.CreatedAt, - Title = p.Title, - Size = p.Size, - TrueSize = p.TrueSize, - IsCompressed = p.IsCompressed, - Views = p.Views, - Syntax = p.Syntax, - Visibility = p.Visibility, - ExpiresAt = p.ExpiresAt, - EditedAt = p.EditedAt, - Author = p.User != null && p.User.Visibility == 0 ? new UserSimpleDto + return Ok( + results.Select(p => new PasteResponseDto { - UID = p.User.UID, - UUID = p.User.UUID, - Username = p.User.Username, - DisplayName = p.User.DisplayName, - Visibility = p.User.Visibility, - Roles = p.User.Roles - } : null - })); + ID = p.ID, + UUID = p.UUID, + CreatedAt = p.CreatedAt, + Title = p.Title, + Size = p.Size, + TrueSize = p.TrueSize, + IsCompressed = p.IsCompressed, + Views = p.Views, + Syntax = p.Syntax, + Visibility = p.Visibility, + ExpiresAt = p.ExpiresAt, + EditedAt = p.EditedAt, + Author = + p.User != null && p.User.Visibility == 0 + ? new UserSimpleDto + { + UID = p.User.UID, + UUID = p.User.UUID, + Username = p.User.Username, + DisplayName = p.User.DisplayName, + Visibility = p.User.Visibility, + Roles = p.User.Roles, + } + : null, + }) + ); } [HttpGet] @@ -416,19 +447,21 @@ namespace SharpbinV3.Server.Controllers [Route("info")] public IActionResult GetCreatePasteOptions() { - return Ok(new PasteOptionsDto - { - Syntaxes = [.. _pasteSettings.ValidSyntaxLanguages], - Visibilities = - [ - new() { Value = 0, DisplayName = "Public" }, - new() { Value = 1, DisplayName = "Unlisted" }, - new() { Value = 2, DisplayName = "Private" } - ], - MaxTitleLength = _pasteSettings.MaxTitleLength, - MaxPasteSize = _pasteSettings.MaxPasteSizeInBytes, - RequiresVerification = _pasteSettings.RequiresVerification - }); + return Ok( + new PasteOptionsDto + { + Syntaxes = [.. _pasteSettings.ValidSyntaxLanguages], + Visibilities = + [ + new() { Value = 0, DisplayName = "Public" }, + new() { Value = 1, DisplayName = "Unlisted" }, + new() { Value = 2, DisplayName = "Private" }, + ], + MaxTitleLength = _pasteSettings.MaxTitleLength, + MaxPasteSize = _pasteSettings.MaxPasteSizeInBytes, + RequiresVerification = _pasteSettings.RequiresVerification, + } + ); } } } diff --git a/SharpbinV3.Server/Controllers/ReportController.cs b/SharpbinV3.Server/Controllers/ReportController.cs index bde5f5c..69e6a54 100644 --- a/SharpbinV3.Server/Controllers/ReportController.cs +++ b/SharpbinV3.Server/Controllers/ReportController.cs @@ -32,24 +32,26 @@ namespace SharpbinV3.Server.Controllers var (Username, DisplayName) = await reportService.GetReporterInfo(report.ReporterUUID); - return Ok(new ReportResponseDto - { - ReportID = report.ReportID, - Type = report.Type, - Status = report.Status, - Description = report.Description, - CreatedAt = report.CreatedAt, - UpdatedAt = report.UpdatedAt, - ReporterUUID = report.ReporterUUID, - ReporterUsername = Username, - ReporterDisplayName = DisplayName, - TargetType = report.TargetType, - PasteId = report.Paste?.ID, - PasteTitle = report.Paste?.Title, - UserUUID = report.UserUUID, - TargetUsername = report.User?.Username, - TargetDisplayName = report.User?.DisplayName - }); + return Ok( + new ReportResponseDto + { + ReportID = report.ReportID, + Type = report.Type, + Status = report.Status, + Description = report.Description, + CreatedAt = report.CreatedAt, + UpdatedAt = report.UpdatedAt, + ReporterUUID = report.ReporterUUID, + ReporterUsername = Username, + ReporterDisplayName = DisplayName, + TargetType = report.TargetType, + PasteId = report.Paste?.ID, + PasteTitle = report.Paste?.Title, + UserUUID = report.UserUUID, + TargetUsername = report.User?.Username, + TargetDisplayName = report.User?.DisplayName, + } + ); } [Route("{reportId:int}")] @@ -91,24 +93,26 @@ namespace SharpbinV3.Server.Controllers var updated = await reportService.UpdateReport(report); var (Username, DisplayName) = await reportService.GetReporterInfo(updated.ReporterUUID); - return Ok(new ReportResponseDto - { - ReportID = updated.ReportID, - Type = updated.Type, - Status = updated.Status, - Description = updated.Description, - CreatedAt = updated.CreatedAt, - UpdatedAt = updated.UpdatedAt, - ReporterUUID = updated.ReporterUUID, - ReporterUsername = Username, - ReporterDisplayName = DisplayName, - TargetType = updated.TargetType, - PasteId = updated.Paste?.ID, - PasteTitle = updated.Paste?.Title, - UserUUID = updated.UserUUID, - TargetUsername = updated.User?.Username, - TargetDisplayName = updated.User?.DisplayName - }); + return Ok( + new ReportResponseDto + { + ReportID = updated.ReportID, + Type = updated.Type, + Status = updated.Status, + Description = updated.Description, + CreatedAt = updated.CreatedAt, + UpdatedAt = updated.UpdatedAt, + ReporterUUID = updated.ReporterUUID, + ReporterUsername = Username, + ReporterDisplayName = DisplayName, + TargetType = updated.TargetType, + PasteId = updated.Paste?.ID, + PasteTitle = updated.Paste?.Title, + UserUUID = updated.UserUUID, + TargetUsername = updated.User?.Username, + TargetDisplayName = updated.User?.DisplayName, + } + ); } [Route("options")] @@ -132,27 +136,24 @@ namespace SharpbinV3.Server.Controllers if (!user.Roles.Contains(1) && !user.Roles.Contains(255)) return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." }); - var query = request with - { - Page = Math.Max(request.Page, 1), - PageSize = Math.Clamp(request.PageSize, 1, 100), - UserUUID = null - }; + var query = request with { Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100), UserUUID = null }; var reports = await reportService.GetPasteReports(query); var totalCount = await reportService.GetReportCount(query); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); - return Ok(new - { - Reports = reports, - Pagination = new + return Ok( + new { - query.Page, - query.PageSize, - TotalCount = totalCount, - TotalPages = totalPages + Reports = reports, + Pagination = new + { + query.Page, + query.PageSize, + TotalCount = totalCount, + TotalPages = totalPages, + }, } - }); + ); } [Route("users")] @@ -172,23 +173,25 @@ namespace SharpbinV3.Server.Controllers Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100), PastePID = null, - PasteId = null + PasteId = null, }; var reports = await reportService.GetUserReports(query); var totalCount = await reportService.GetReportCount(query); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); - return Ok(new - { - Reports = reports, - Pagination = new + return Ok( + new { - query.Page, - query.PageSize, - TotalCount = totalCount, - TotalPages = totalPages + Reports = reports, + Pagination = new + { + query.Page, + query.PageSize, + TotalCount = totalCount, + TotalPages = totalPages, + }, } - }); + ); } [Route("all")] @@ -201,7 +204,8 @@ namespace SharpbinV3.Server.Controllers [FromQuery] ReportType? type, [FromQuery] ReportStatus? status, [FromQuery] int page = 1, - [FromQuery] int pageSize = 20) + [FromQuery] int pageSize = 20 + ) { var user = HttpContext.GetJwtUser(); if (user is null) @@ -216,23 +220,25 @@ namespace SharpbinV3.Server.Controllers Type = type, Status = status, Page = Math.Max(page, 1), - PageSize = Math.Clamp(pageSize, 1, 100) + PageSize = Math.Clamp(pageSize, 1, 100), }; var reports = await reportService.GetReports(query); var totalCount = await reportService.GetReportCount(query); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); - return Ok(new - { - Reports = reports, - Pagination = new + return Ok( + new { - query.Page, - query.PageSize, - TotalCount = totalCount, - TotalPages = totalPages + Reports = reports, + Pagination = new + { + query.Page, + query.PageSize, + TotalCount = totalCount, + TotalPages = totalPages, + }, } - }); + ); } } } diff --git a/SharpbinV3.Server/Controllers/UserController.cs b/SharpbinV3.Server/Controllers/UserController.cs index edf39e8..2419262 100644 --- a/SharpbinV3.Server/Controllers/UserController.cs +++ b/SharpbinV3.Server/Controllers/UserController.cs @@ -19,8 +19,14 @@ namespace SharpbinV3.Server.Controllers { [ApiController] [Route("api/[controller]")] - public class UserController(UserService userService, AppDbContext db, TotpVerificationProvider totp, - VerificationService verificationService, ReportService reportServer, 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; @@ -72,7 +78,10 @@ namespace SharpbinV3.Server.Controllers if (user == null) return NotFound(new { success = false, message = "User not found." }); - if ((user.Roles.Contains(255) && !jwtUser.Roles.Contains(255)) || (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID)) + if ( + (user.Roles.Contains(255) && !jwtUser.Roles.Contains(255)) + || (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID) + ) return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." }); if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA) @@ -88,11 +97,10 @@ namespace SharpbinV3.Server.Controllers { if (updatedUser.Roles.Contains(255) && jwtUser.TotpEnabled) { - if (string.IsNullOrEmpty(updatedUser.TotpCode) || !await _totp.VerifyAsync(new VerificationContext - { - UserUUID = jwtUser.UUID, - Code = updatedUser.TotpCode - })) + if ( + string.IsNullOrEmpty(updatedUser.TotpCode) + || !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = updatedUser.TotpCode }) + ) { return Unauthorized(new { message = "Invalid TOTP code." }); } @@ -124,22 +132,20 @@ namespace SharpbinV3.Server.Controllers if (jwtUser.TotpEnabled) { - if (string.IsNullOrEmpty(dto.TotpCode) || !await _totp.VerifyAsync(new VerificationContext - { - UserUUID = jwtUser.UUID, - Code = dto.TotpCode - })) + if ( + string.IsNullOrEmpty(dto.TotpCode) + || !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = dto.TotpCode }) + ) { return Unauthorized(new { message = "Invalid TOTP code." }); } } else { - if (string.IsNullOrEmpty(dto.Token) || !await _verificationService.VerifyAsync(new VerificationContext - { - Token = dto.Token, - Ip = HttpContext.GetRequestIP() - })) + if ( + string.IsNullOrEmpty(dto.Token) + || !await _verificationService.VerifyAsync(new VerificationContext { Token = dto.Token, Ip = HttpContext.GetRequestIP() }) + ) { return Unauthorized(new { message = "Invalid verification token." }); } @@ -169,34 +175,36 @@ namespace SharpbinV3.Server.Controllers 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() - })) + 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 = "User reported successfully.", - report = new ReportResponseDto + return Ok( + new { - ReportID = report.ReportID, - Type = report.Type, - Status = report.Status, - Description = report.Description, - CreatedAt = report.CreatedAt, - UpdatedAt = report.UpdatedAt, - ReporterUUID = report.ReporterUUID, - TargetType = report.TargetType, - UserUUID = report.UserUUID + success = true, + message = "User reported successfully.", + report = new ReportResponseDto + { + ReportID = report.ReportID, + Type = report.Type, + Status = report.Status, + Description = report.Description, + CreatedAt = report.CreatedAt, + UpdatedAt = report.UpdatedAt, + ReporterUUID = report.ReporterUUID, + TargetType = report.TargetType, + UserUUID = report.UserUUID, + }, } - }); + ); } [HttpPatch] @@ -269,26 +277,23 @@ namespace SharpbinV3.Server.Controllers if (!jwtUser.Roles.Any(r => r == 1 || r == 255)) return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." }); - var query = request with - { - UserUUID = user.UUID, - Page = Math.Max(request.Page, 1), - PageSize = Math.Clamp(request.PageSize, 1, 100) - }; + var query = request with { UserUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) }; var reports = await _reportService.GetUserReports(query); var totalCount = await _reportService.GetReportCount(query); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); - return Ok(new - { - Reports = reports, - Pagination = new + return Ok( + new { - query.Page, - query.PageSize, - TotalCount = totalCount, - TotalPages = totalPages + Reports = reports, + Pagination = new + { + query.Page, + query.PageSize, + TotalCount = totalCount, + TotalPages = totalPages, + }, } - }); + ); } [HttpGet] @@ -309,28 +314,25 @@ namespace SharpbinV3.Server.Controllers if (!isOwner && !hasPrivilegedRole) return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." }); - var query = request with - { - ReporterUUID = user.UUID, - Page = Math.Max(request.Page, 1), - PageSize = Math.Clamp(request.PageSize, 1, 100) - }; + var query = request with { ReporterUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) }; var reports = await _reportService.GetReports(query); var totalCount = await _reportService.GetReportCount(query); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); - return Ok(new - { - Reports = reports, - Pagination = new + return Ok( + new { - query.Page, - query.PageSize, - TotalCount = totalCount, - TotalPages = totalPages + Reports = reports, + Pagination = new + { + query.Page, + query.PageSize, + TotalCount = totalCount, + TotalPages = totalPages, + }, } - }); + ); } private async Task BuildUserResponse(User user, int page = 1) @@ -369,7 +371,7 @@ namespace SharpbinV3.Server.Controllers Views = p.Views, Visibility = p.Visibility, EditedAt = p.EditedAt, - ExpiresAt = p.ExpiresAt + ExpiresAt = p.ExpiresAt, }) .ToListAsync(); @@ -378,61 +380,67 @@ namespace SharpbinV3.Server.Controllers Page = page, PageSize = pageSize, TotalCount = totalCount, - TotalPages = totalPages + TotalPages = totalPages, }; if (isAuthenticatedUser) { - var reports = await _reportService.GetReports(new ReportQuery - { - ReporterUUID = user.UUID, - Page = page, - PageSize = pageSize - }); + var reports = await _reportService.GetReports( + new ReportQuery + { + ReporterUUID = user.UUID, + Page = page, + PageSize = pageSize, + } + ); var reportsCount = await _reportService.GetReportCountByReporter(user.UUID); - return Ok(new + return Ok( + new + { + User = new UserResponseDto + { + UID = user.UID, + Username = user.Username, + UUID = user.UUID, + CreatedAt = user.CreatedAt, + DisplayName = user.DisplayName, + Email = user.Email, + LastLogin = user.LastLogin, + Roles = user.Roles, + Visibility = user.Visibility, + }, + Pastes = pastes, + Reports = reports, + Pagination = pagination, + ReportsPagination = new + { + Page = page, + PageSize = pageSize, + TotalCount = reportsCount, + TotalPages = (int)Math.Ceiling(reportsCount / (double)pageSize), + }, + } + ); + } + + return Ok( + new { - User = new UserResponseDto + User = new UserSimpleDto { UID = user.UID, Username = user.Username, UUID = user.UUID, CreatedAt = user.CreatedAt, DisplayName = user.DisplayName, - Email = user.Email, - LastLogin = user.LastLogin, Roles = user.Roles, - Visibility = user.Visibility + Visibility = user.Visibility, }, Pastes = pastes, - Reports = reports, Pagination = pagination, - ReportsPagination = new - { - Page = page, - PageSize = pageSize, - TotalCount = reportsCount, - TotalPages = (int)Math.Ceiling(reportsCount / (double)pageSize) - } - }); - } - - return Ok(new - { - User = new UserSimpleDto - { - UID = user.UID, - Username = user.Username, - UUID = user.UUID, - CreatedAt = user.CreatedAt, - DisplayName = user.DisplayName, - Roles = user.Roles, - Visibility = user.Visibility - }, - Pastes = pastes, - Pagination = pagination - }); + } + ); } } } diff --git a/SharpbinV3.Server/DTOs/Auth/RefreshTokenDto.cs b/SharpbinV3.Server/DTOs/Auth/RefreshTokenDto.cs index ee4c915..91c25e7 100644 --- a/SharpbinV3.Server/DTOs/Auth/RefreshTokenDto.cs +++ b/SharpbinV3.Server/DTOs/Auth/RefreshTokenDto.cs @@ -6,6 +6,7 @@ namespace SharpbinV3.Server.DTOs.Auth { [Required] public required string Token { get; set; } + [Required] public required string RefreshToken { get; set; } } diff --git a/SharpbinV3.Server/DTOs/Auth/TurnstileResponseDto.cs b/SharpbinV3.Server/DTOs/Auth/TurnstileResponseDto.cs index 22ab315..5c2629d 100644 --- a/SharpbinV3.Server/DTOs/Auth/TurnstileResponseDto.cs +++ b/SharpbinV3.Server/DTOs/Auth/TurnstileResponseDto.cs @@ -6,6 +6,7 @@ namespace SharpbinV3.Server.DTOs.Auth { [JsonPropertyName("success")] public bool Success { get; set; } + [JsonPropertyName("error-codes")] public string[]? ErrorCodes { get; set; } } diff --git a/SharpbinV3.Server/DTOs/Report/ReportDto.cs b/SharpbinV3.Server/DTOs/Report/ReportDto.cs index f4a56c8..2feefa3 100644 --- a/SharpbinV3.Server/DTOs/Report/ReportDto.cs +++ b/SharpbinV3.Server/DTOs/Report/ReportDto.cs @@ -7,6 +7,7 @@ namespace SharpbinV3.Server.DTOs.Report [Required] [MinLength(12), MaxLength(1000)] public string Description { get; set; } = string.Empty; + [Required] public string ReportType { get; set; } = string.Empty; public string ReportStatus { get; set; } = "Open"; diff --git a/SharpbinV3.Server/DTOs/Report/ReportUpdateDto.cs b/SharpbinV3.Server/DTOs/Report/ReportUpdateDto.cs index 462e043..f0af0d3 100644 --- a/SharpbinV3.Server/DTOs/Report/ReportUpdateDto.cs +++ b/SharpbinV3.Server/DTOs/Report/ReportUpdateDto.cs @@ -6,6 +6,7 @@ namespace SharpbinV3.Server.DTOs.Report { public string? Status { get; set; } public string? Type { get; set; } + [MaxLength(1000)] public string? Description { get; set; } } diff --git a/SharpbinV3.Server/DTOs/User/LoginUserDto.cs b/SharpbinV3.Server/DTOs/User/LoginUserDto.cs index c10f5be..185d121 100644 --- a/SharpbinV3.Server/DTOs/User/LoginUserDto.cs +++ b/SharpbinV3.Server/DTOs/User/LoginUserDto.cs @@ -7,6 +7,7 @@ namespace SharpbinV3.Server.DTOs.User [StringLength(50, MinimumLength = 3)] public string? Username { get; set; } public string? Email { get; set; } + [StringLength(128, MinimumLength = 6)] public string? Password { get; set; } public string? Token { get; set; } diff --git a/SharpbinV3.Server/DTOs/User/RegisterUserDto.cs b/SharpbinV3.Server/DTOs/User/RegisterUserDto.cs index 8590ded..b3933e8 100644 --- a/SharpbinV3.Server/DTOs/User/RegisterUserDto.cs +++ b/SharpbinV3.Server/DTOs/User/RegisterUserDto.cs @@ -24,14 +24,24 @@ namespace SharpbinV3.Server.DTOs if (!ValidateUsername().IsMatch(Username)) results.Add(new ValidationResult("Username can only contain letters, numbers, underscores, and dots.", [nameof(Username)])); if (!ValidatePassword().IsMatch(Password)) - results.Add(new ValidationResult("Password should have at least 8 characters, including uppercase, lowercase, and digits.", [nameof(Password)])); + results.Add( + new ValidationResult( + "Password should have at least 8 characters, including uppercase, lowercase, and digits.", + [nameof(Password)] + ) + ); if (DisplayName != null && DisplayName.Length > 0) { if (DisplayName.Length < 3 || DisplayName.Length > 26) results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)])); if (!ValidateDisplayname().IsMatch(DisplayName)) - results.Add(new ValidationResult("DisplayName can only contain alphanumeric characters, underscores, periods, and spaces (no leading or trailing spaces).", [nameof(DisplayName)])); + results.Add( + new ValidationResult( + "DisplayName can only contain alphanumeric characters, underscores, periods, and spaces (no leading or trailing spaces).", + [nameof(DisplayName)] + ) + ); } if (Email != null && Email.Length > 0) { @@ -44,8 +54,10 @@ namespace SharpbinV3.Server.DTOs [GeneratedRegex("^[A-Za-z0-9_.]+$")] private static partial Regex ValidateUsername(); + [GeneratedRegex("^[A-Za-z0-9_.]+(?: [A-Za-z0-9_.]+)*$")] private static partial Regex ValidateDisplayname(); + [GeneratedRegex("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$")] public static partial Regex ValidatePassword(); } diff --git a/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs b/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs index fad6897..336a51c 100644 --- a/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs +++ b/SharpbinV3.Server/DTOs/User/UpdateUserDto.cs @@ -19,7 +19,12 @@ namespace SharpbinV3.Server.DTOs if (DisplayName.Length < 3 || DisplayName.Length > 26) results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)])); if (!ValidateDisplayname().IsMatch(DisplayName)) - results.Add(new ValidationResult("DisplayName can only contain alphanumeric characters, underscores, periods, and spaces (no leading or trailing spaces).", [nameof(DisplayName)])); + results.Add( + new ValidationResult( + "DisplayName can only contain alphanumeric characters, underscores, periods, and spaces (no leading or trailing spaces).", + [nameof(DisplayName)] + ) + ); } if (Email != null && Email.Length > 0) { @@ -42,7 +47,6 @@ namespace SharpbinV3.Server.DTOs if (!validRoles.Contains(role)) results.Add(new ValidationResult($"Invalid role: {role}.", [nameof(Roles)])); } - } return results; } diff --git a/SharpbinV3.Server/Extensions/HttpContextExtensions.cs b/SharpbinV3.Server/Extensions/HttpContextExtensions.cs index c86e811..80a7a03 100644 --- a/SharpbinV3.Server/Extensions/HttpContextExtensions.cs +++ b/SharpbinV3.Server/Extensions/HttpContextExtensions.cs @@ -1,20 +1,21 @@ -using SharpbinV3.Server.Services; -using System.IdentityModel.Tokens.Jwt; +using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; +using SharpbinV3.Server.Services; namespace SharpbinV3.Server.Extensions { public static class HttpContextExtensions { - public readonly static string[] ipHeaders = + public static readonly string[] ipHeaders = [ "X-Forwarded-For", "X-Real-IP", "CF-Connecting-IP", "True-Client-IP", "X-Cluster-Client-IP", - "X-ProxyUser-IP" + "X-ProxyUser-IP", ]; + public static JwtUser? GetJwtUser(this HttpContext context) { if (context.User == null || !context.User.Identity?.IsAuthenticated == true) @@ -30,15 +31,13 @@ namespace SharpbinV3.Server.Extensions var displayName = claims.FirstOrDefault(c => c.Type == "displayname")?.Value ?? ""; var totpEnabled = claims.FirstOrDefault(c => c.Type == "totp_enabled")?.Value == "True"; - var roles = claims - .Where(c => c.Type == ClaimTypes.Role) - .Select(c => int.TryParse(c.Value, out var r) ? r : 0) - .ToArray(); + var roles = claims.Where(c => c.Type == ClaimTypes.Role).Select(c => int.TryParse(c.Value, out var r) ? r : 0).ToArray(); var expClaim = claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value; - var expires = expClaim != null && long.TryParse(expClaim, out var expUnix) - ? DateTimeOffset.FromUnixTimeSeconds(expUnix).UtcDateTime - : DateTime.UtcNow.AddMinutes(15); + var expires = + expClaim != null && long.TryParse(expClaim, out var expUnix) + ? DateTimeOffset.FromUnixTimeSeconds(expUnix).UtcDateTime + : DateTime.UtcNow.AddMinutes(15); return new JwtUser { @@ -47,7 +46,7 @@ namespace SharpbinV3.Server.Extensions DisplayName = displayName, TotpEnabled = totpEnabled, Roles = roles.Length > 0 ? roles : [0], - Expires = expires + Expires = expires, }; } diff --git a/SharpbinV3.Server/Program.cs b/SharpbinV3.Server/Program.cs index 8e37afc..e44f53e 100644 --- a/SharpbinV3.Server/Program.cs +++ b/SharpbinV3.Server/Program.cs @@ -30,8 +30,7 @@ namespace SharpbinV3.Server .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(options => @@ -74,13 +73,9 @@ namespace SharpbinV3.Server .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) - .AddJwtBearer(); + builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(); builder .Services.AddOptions(JwtBearerDefaults.AuthenticationScheme) @@ -112,18 +107,8 @@ namespace SharpbinV3.Server } ); - 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(new NotBannedHandler(false)); builder.Services.AddSingleton(new NotBannedHandler(true)); @@ -181,33 +166,27 @@ namespace SharpbinV3.Server options.AddPolicy("NoLimit", _ => RateLimitPartition.GetNoLimiter(0)); - options.GlobalLimiter = PartitionedRateLimiter.Create( - httpContext => - { - var remoteIp = httpContext.GetRequestIP(); + options.GlobalLimiter = PartitionedRateLimiter.Create(httpContext => + { + var remoteIp = httpContext.GetRequestIP(); - return RateLimitPartition.GetFixedWindowLimiter( - remoteIp, - _ => new FixedWindowRateLimiterOptions - { - PermitLimit = 100, - Window = TimeSpan.FromMinutes(1), - QueueProcessingOrder = QueueProcessingOrder.OldestFirst, - QueueLimit = 0, - } - ); - } - ); + 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.", - }, + new { success = false, Message = "Too many requests. Please try again later." }, cancellationToken: cancellationToken ); }; @@ -225,9 +204,7 @@ namespace SharpbinV3.Server builder.Services.AddCors(o => { - o.AddDefaultPolicy(p => - p.WithOrigins("http://localhost:5173").AllowAnyHeader().AllowAnyMethod() - ); + o.AddDefaultPolicy(p => p.WithOrigins("http://localhost:5173").AllowAnyHeader().AllowAnyMethod()); }); builder @@ -278,15 +255,7 @@ namespace SharpbinV3.Server 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(); @@ -343,9 +312,7 @@ namespace SharpbinV3.Server if (!string.IsNullOrEmpty(overridepath)) return new DirectoryInfo(overridepath); - var basePath = env.IsDevelopment() - ? Environment.CurrentDirectory - : Environment.SpecialFolder.ApplicationData.ToString(); + var basePath = env.IsDevelopment() ? Environment.CurrentDirectory : Environment.SpecialFolder.ApplicationData.ToString(); var path = Path.Combine(basePath, "SharpbinV3", "DataProtectionKeys"); diff --git a/SharpbinV3.Server/Services/AuthService.cs b/SharpbinV3.Server/Services/AuthService.cs index 7a5b84d..6e65531 100644 --- a/SharpbinV3.Server/Services/AuthService.cs +++ b/SharpbinV3.Server/Services/AuthService.cs @@ -1,13 +1,13 @@ -using Microsoft.EntityFrameworkCore; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using SharpbinV3.Server.Data; using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.DTOs.Auth; using SharpbinV3.Server.Settings; -using System.IdentityModel.Tokens.Jwt; -using System.Security.Claims; -using System.Text; using Bcrypt = BCrypt.Net.BCrypt; namespace SharpbinV3.Server.Services @@ -21,7 +21,13 @@ namespace SharpbinV3.Server.Services public int[] Roles { get; set; } = []; public DateTime Expires { get; set; } } - public sealed class AuthService(AppDbContext db, IOptions jwtOptions, IOptions authOptions, ILogger logger) + + public sealed class AuthService( + AppDbContext db, + IOptions jwtOptions, + IOptions authOptions, + ILogger logger + ) { private readonly AppDbContext _db = db; private readonly JWTSettings _jwtSettings = jwtOptions.Value; @@ -36,7 +42,7 @@ namespace SharpbinV3.Server.Services PasswordHash = Bcrypt.HashPassword(password), Email = email, DisplayName = displayName, - UUID = Guid.CreateVersion7() + UUID = Guid.CreateVersion7(), }; if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync()) @@ -46,6 +52,7 @@ namespace SharpbinV3.Server.Services await _db.SaveChangesAsync(); return user; } + public async Task GenerateJWTToken(User user) { var jwtHandler = new JwtSecurityTokenHandler(); @@ -58,7 +65,7 @@ namespace SharpbinV3.Server.Services new("username", user.Username), new("displayname", user.DisplayName ?? ""), new("totp_enabled", totpEnabled.ToString()), - new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) + new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; if (user.Roles != null) @@ -77,10 +84,7 @@ namespace SharpbinV3.Server.Services Issuer = _jwtSettings.Issuer, Audience = _jwtSettings.Audience, Expires = DateTime.UtcNow.AddMinutes(15), - SigningCredentials = new SigningCredentials( - new SymmetricSecurityKey(key), - SecurityAlgorithms.HmacSha256Signature - ) + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature), }; var token = jwtHandler.CreateToken(descriptor); @@ -97,7 +101,7 @@ namespace SharpbinV3.Server.Services CreatedAt = DateTimeOffset.UtcNow, ExpiresAt = DateTimeOffset.UtcNow.AddMonths(6), Used = false, - Revoked = false + Revoked = false, }; await _db.RefreshTokens.AddAsync(refreshToken); @@ -107,7 +111,7 @@ namespace SharpbinV3.Server.Services { Token = jwtToken, Success = true, - RefreshToken = rawRefreshToken + RefreshToken = rawRefreshToken, }; } @@ -118,38 +122,39 @@ namespace SharpbinV3.Server.Services try { - var principal = jwtHandler.ValidateToken(token, new TokenValidationParameters - { - ValidateIssuerSigningKey = true, - IssuerSigningKey = new SymmetricSecurityKey(key), - ValidateIssuer = true, - ValidIssuer = _jwtSettings.Issuer, - ValidateAudience = true, - ValidAudience = _jwtSettings.Audience, - ClockSkew = TimeSpan.Zero, - ValidateLifetime = false, - RequireSignedTokens = true, - ValidAlgorithms = [SecurityAlgorithms.HmacSha256] - }, out SecurityToken validatedToken); + var principal = jwtHandler.ValidateToken( + token, + new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = true, + ValidIssuer = _jwtSettings.Issuer, + ValidateAudience = true, + ValidAudience = _jwtSettings.Audience, + ClockSkew = TimeSpan.Zero, + ValidateLifetime = false, + RequireSignedTokens = true, + ValidAlgorithms = [SecurityAlgorithms.HmacSha256], + }, + out SecurityToken validatedToken + ); var jti = principal.Claims.First(c => c.Type == JwtRegisteredClaimNames.Jti).Value; var tokenHash = Utilities.ComputeSha256(refreshToken); - var storedToken = await _db.RefreshTokens - .FirstOrDefaultAsync(rt => rt.TokenHash == tokenHash); + var storedToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt => rt.TokenHash == tokenHash); - if (storedToken == null + if ( + storedToken == null || storedToken.Used || storedToken.Revoked || storedToken.ExpiresAt < DateTimeOffset.UtcNow - || storedToken.JwtId != jti) + || storedToken.JwtId != jti + ) { - return new CreateJWT - { - Success = false, - Errors = ["Invalid or expired refresh token."] - }; + return new CreateJWT { Success = false, Errors = ["Invalid or expired refresh token."] }; } storedToken.Used = true; @@ -172,7 +177,6 @@ namespace SharpbinV3.Server.Services } } - public async Task UpdateUser(User user) { var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found"); @@ -186,6 +190,7 @@ namespace SharpbinV3.Server.Services await _db.SaveChangesAsync(); return user; } + public async Task UpdateLoginTime(User user) { var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found"); diff --git a/SharpbinV3.Server/Services/CompressionService.cs b/SharpbinV3.Server/Services/CompressionService.cs index 28796bb..afd418a 100644 --- a/SharpbinV3.Server/Services/CompressionService.cs +++ b/SharpbinV3.Server/Services/CompressionService.cs @@ -1,6 +1,5 @@ using System.IO.Compression; - namespace SharpbinV3.Server.Services { public class CompressionService : ICompressionService @@ -21,11 +20,13 @@ namespace SharpbinV3.Server.Services return data; } + public byte[] Compress(string data) { ArgumentNullException.ThrowIfNull(data); return Compress(System.Text.Encoding.UTF8.GetBytes(data)); } + public byte[] Decompress(byte[] compressedData) { ArgumentNullException.ThrowIfNull(compressedData); diff --git a/SharpbinV3.Server/Services/PasteCleanUpService.cs b/SharpbinV3.Server/Services/PasteCleanUpService.cs index 6ecd62c..f8e4b7c 100644 --- a/SharpbinV3.Server/Services/PasteCleanUpService.cs +++ b/SharpbinV3.Server/Services/PasteCleanUpService.cs @@ -6,6 +6,7 @@ namespace SharpbinV3.Server.Services public class PasteCleanUpService(IServiceProvider serviceProvider, ILogger logger) : BackgroundService { private readonly TimeSpan _period = TimeSpan.FromMinutes(5); + protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using var timer = new PeriodicTimer(_period); diff --git a/SharpbinV3.Server/Services/PasteService.cs b/SharpbinV3.Server/Services/PasteService.cs index d29cf08..064c08b 100644 --- a/SharpbinV3.Server/Services/PasteService.cs +++ b/SharpbinV3.Server/Services/PasteService.cs @@ -9,12 +9,7 @@ using SharpbinV3.Server.Settings; namespace SharpbinV3.Server.Services { - public sealed class PasteService( - AppDbContext db, - ICompressionService cs, - IMemoryCache cache, - IOptions options - ) + public sealed class PasteService(AppDbContext db, ICompressionService cs, IMemoryCache cache, IOptions options) { private readonly AppDbContext _db = db; private readonly ICompressionService _cs = cs; @@ -114,10 +109,7 @@ namespace SharpbinV3.Server.Services return result > 0; } - public async Task<(Paste? paste, bool alreadyExists)> RecordView( - Paste paste, - HttpContext context - ) + public async Task<(Paste? paste, bool alreadyExists)> RecordView(Paste paste, HttpContext context) { if (paste == null) return (null, false); @@ -132,21 +124,11 @@ namespace SharpbinV3.Server.Services string viewerHash; if (viewerUser != null) - viewerHash = Utilities.ComputeHmacSha256( - _pasteSettings.View_HMAC_Secret, - viewerUser.UUID.ToString() - ); + viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerUser.UUID.ToString()); else - viewerHash = Utilities.ComputeHmacSha256( - _pasteSettings.View_HMAC_Secret, - viewerIp + viewerUserAgent - ); + viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerIp + viewerUserAgent); - if ( - await _db.PasteViews.AnyAsync(pv => - pv.PastePID == paste.PID && pv.ViewerHash == viewerHash - ) - ) + if (await _db.PasteViews.AnyAsync(pv => pv.PastePID == paste.PID && pv.ViewerHash == viewerHash)) return (null, true); _db.PasteViews.Add( @@ -176,9 +158,7 @@ namespace SharpbinV3.Server.Services async entry => { entry.SetSlidingExpiration(TimeSpan.FromMinutes(10)); - return await _db - .Pastes.Include(p => p.User) - .FirstOrDefaultAsync(p => p.ID == id); + return await _db.Pastes.Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id); } ); return paste ?? null; @@ -201,12 +181,7 @@ namespace SharpbinV3.Server.Services if (publicOnly) query = query.Where(p => p.Visibility == 0); - return await query - .OrderByDescending(p => p.PID) - .Skip(offset) - .Take(count) - .Include(p => p.User) - .ToListAsync(); + return await query.OrderByDescending(p => p.PID).Skip(offset).Take(count).Include(p => p.User).ToListAsync(); } ); diff --git a/SharpbinV3.Server/Services/PasteViewCleanUpService.cs b/SharpbinV3.Server/Services/PasteViewCleanUpService.cs index aebadaa..cdc73a9 100644 --- a/SharpbinV3.Server/Services/PasteViewCleanUpService.cs +++ b/SharpbinV3.Server/Services/PasteViewCleanUpService.cs @@ -3,21 +3,16 @@ using SharpbinV3.Server.Data; namespace SharpbinV3.Server.Services { - public sealed class PasteViewCleanUpService( - IServiceProvider serviceProvider, - ILogger logger - ) : BackgroundService + 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; + 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)) + while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken)) { try { @@ -35,16 +30,12 @@ namespace SharpbinV3.Server.Services using var scope = serviceProvider.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - var cutoff = - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - RetentionMs; + var cutoff = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - RetentionMs; - var deleted = await db.PasteViews - .Where(v => v.ViewedAt < cutoff) - .ExecuteDeleteAsync(token); + 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/ReportService.cs b/SharpbinV3.Server/Services/ReportService.cs index ab60d8c..cb0e3f9 100644 --- a/SharpbinV3.Server/Services/ReportService.cs +++ b/SharpbinV3.Server/Services/ReportService.cs @@ -8,7 +8,9 @@ namespace SharpbinV3.Server.Services public class ReportService(AppDbContext db) { private readonly AppDbContext _db = db; + private sealed record UserInfo(string Username, string? DisplayName); + public async Task CreateReport(Guid reporterUUID, ReportTargetType targetType, Guid userUUID, ReportType type, string description) { var report = new Report @@ -17,12 +19,13 @@ namespace SharpbinV3.Server.Services TargetType = targetType, UserUUID = userUUID, Type = type, - Description = description + 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 @@ -53,10 +56,7 @@ namespace SharpbinV3.Server.Services if (query.PasteId != null) { - q = q.Where(r => _db.Pastes - .Where(p => p.ID == query.PasteId) - .Select(p => (int?)p.PID) - .Contains(r.PastePID)); + q = q.Where(r => _db.Pastes.Where(p => p.ID == query.PasteId).Select(p => (int?)p.PID).Contains(r.PastePID)); } if (query.TargetType != null) @@ -71,25 +71,16 @@ namespace SharpbinV3.Server.Services return q; } - public async Task> GetPasteReports(ReportQuery query) { - query = query with - { - TargetType = ReportTargetType.Paste, - UserUUID = null - }; + query = query with { TargetType = ReportTargetType.Paste, UserUUID = null }; return await GetReports(query); } public async Task> GetUserReports(ReportQuery query) { - query = query with - { - TargetType = ReportTargetType.User, - PastePID = null - }; + query = query with { TargetType = ReportTargetType.User, PastePID = null }; return await GetReports(query); } @@ -109,27 +100,22 @@ namespace SharpbinV3.Server.Services CreatedAt = r.CreatedAt, UpdatedAt = r.UpdatedAt, ReporterUUID = r.ReporterUUID, - ReporterUsername = _db.Users - .Where(u => u.UUID == r.ReporterUUID) - .Select(u => u.Username) - .FirstOrDefault(), - ReporterDisplayName = _db.Users - .Where(u => u.UUID == r.ReporterUUID) - .Select(u => u.DisplayName) - .FirstOrDefault(), + ReporterUsername = _db.Users.Where(u => u.UUID == r.ReporterUUID).Select(u => u.Username).FirstOrDefault(), + ReporterDisplayName = _db.Users.Where(u => u.UUID == r.ReporterUUID).Select(u => u.DisplayName).FirstOrDefault(), TargetType = r.TargetType, PasteId = r.Paste != null ? r.Paste.ID : null, PasteTitle = r.Paste != null ? r.Paste.Title : null, UserUUID = r.UserUUID, TargetUsername = r.User != null ? r.User.Username : null, - TargetDisplayName = r.User != null ? r.User.DisplayName : null + TargetDisplayName = r.User != null ? r.User.DisplayName : null, }) .ToListAsync(); } public async Task<(string? Username, string? DisplayName)> GetReporterInfo(Guid reporterUUID) { - var info = await _db.Users.AsNoTracking() + var info = await _db + .Users.AsNoTracking() .Where(u => u.UUID == reporterUUID) .Select(u => new UserInfo(u.Username, u.DisplayName)) .FirstOrDefaultAsync(); @@ -137,25 +123,19 @@ namespace SharpbinV3.Server.Services return info is null ? (null, null) : (info.Username, info.DisplayName); } - public async Task GetReportCount(ReportTargetType targetType) { - return await _db.Reports - .Where(r => r.TargetType == targetType) - .CountAsync(); + return await _db.Reports.Where(r => r.TargetType == targetType).CountAsync(); } public async Task GetReportCountByReporter(Guid reporterUUID) { - return await _db.Reports - .Where(r => r.ReporterUUID == reporterUUID) - .CountAsync(); + return await _db.Reports.Where(r => r.ReporterUUID == reporterUUID).CountAsync(); } public async Task GetReportCount() { - return await _db.Reports - .CountAsync(); + return await _db.Reports.CountAsync(); } public async Task GetReportCount(ReportQuery query) @@ -165,10 +145,7 @@ namespace SharpbinV3.Server.Services public async Task GetReportByID(int reportID) { - return await _db.Reports - .Include(r => r.User) - .Include(r => r.Paste) - .FirstOrDefaultAsync(r => r.ReportID == reportID); + return await _db.Reports.Include(r => r.User).Include(r => r.Paste).FirstOrDefaultAsync(r => r.ReportID == reportID); } public async Task UpdateReport(Report report) @@ -177,6 +154,7 @@ namespace SharpbinV3.Server.Services await _db.SaveChangesAsync(); return report; } + public async Task DeleteReport(Report report) { _db.Reports.Remove(report); diff --git a/SharpbinV3.Server/Services/UserService.cs b/SharpbinV3.Server/Services/UserService.cs index f61bd9a..7f781c0 100644 --- a/SharpbinV3.Server/Services/UserService.cs +++ b/SharpbinV3.Server/Services/UserService.cs @@ -2,12 +2,12 @@ using SharpbinV3.Server.Data; using SharpbinV3.Server.Data.Entities; - namespace SharpbinV3.Server.Services { public sealed class UserService(AppDbContext db) { private readonly AppDbContext _db = db; + public Task GetByUID(int uid, bool withPastes = false) { IQueryable query = _db.Users; diff --git a/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs b/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs index bf76530..00bcb7c 100644 --- a/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs +++ b/SharpbinV3.Server/Services/Verification/Providers/TotpVerificationProvider.cs @@ -6,7 +6,8 @@ using SharpbinV3.Server.Data; namespace SharpbinV3.Server.Services.Verification.Providers { - public sealed class TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache) : IVerificationProvider + public sealed class TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache) + : IVerificationProvider { private readonly AppDbContext _db = db; private readonly IDataProtector _protector = dataProtectionProvider.CreateProtector("TotpSecret-v1"); @@ -17,11 +18,14 @@ namespace SharpbinV3.Server.Services.Verification.Providers public async Task VerifyAsync(VerificationContext ctx) { - if (ctx.UserUUID is null) return false; - if (string.IsNullOrWhiteSpace(ctx.Code)) return false; + if (ctx.UserUUID is null) + return false; + if (string.IsNullOrWhiteSpace(ctx.Code)) + return false; var userTotp = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == ctx.UserUUID.Value); - if (userTotp is null) return false; + if (userTotp is null) + return false; var secret = _protector.Unprotect(userTotp.EncryptedSecret); if (!VerifyCode(secret, ctx.Code, out var step)) @@ -39,7 +43,14 @@ namespace SharpbinV3.Server.Services.Verification.Providers public byte[] FromBase32(string base32) => string.IsNullOrWhiteSpace(base32) ? [] : Base32Encoding.ToBytes(base32); - public string BuildOtpAuthUri(string issuer, string accountName, string secretBase32, int digits = 6, int period = 30, string algorithm = "SHA1") + public string BuildOtpAuthUri( + string issuer, + string accountName, + string secretBase32, + int digits = 6, + int period = 30, + string algorithm = "SHA1" + ) { var label = Uri.EscapeDataString($"{issuer}:{accountName}"); var query = $"secret={secretBase32}&issuer={Uri.EscapeDataString(issuer)}&algorithm={algorithm}&digits={digits}&period={period}"; @@ -47,6 +58,7 @@ namespace SharpbinV3.Server.Services.Verification.Providers } public byte[] Protect(byte[] secret) => _protector.Protect(secret); + public byte[] Unprotect(byte[] protectedSecret) => _protector.Unprotect(protectedSecret); public bool VerifyWithSecretBase32(string secretBase32, string code, int digits = 6, int period = 30, int window = 1) diff --git a/SharpbinV3.Server/Services/Verification/Providers/TurnstileVerificationProvider.cs b/SharpbinV3.Server/Services/Verification/Providers/TurnstileVerificationProvider.cs index 75b3c7d..538b527 100644 --- a/SharpbinV3.Server/Services/Verification/Providers/TurnstileVerificationProvider.cs +++ b/SharpbinV3.Server/Services/Verification/Providers/TurnstileVerificationProvider.cs @@ -1,7 +1,7 @@ -using Microsoft.Extensions.Options; +using System.Text.Json; +using Microsoft.Extensions.Options; using SharpbinV3.Server.DTOs.Auth; using SharpbinV3.Server.Settings; -using System.Text.Json; namespace SharpbinV3.Server.Services.Verification.Providers { @@ -11,7 +11,8 @@ namespace SharpbinV3.Server.Services.Verification.Providers private const string SiteverifyUrl = "https://challenges.cloudflare.com/turnstile/v0/siteverify"; public int Priority => 1; - public bool IsConfigured => !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey) && !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey); + public bool IsConfigured => + !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey) && !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey); public async Task VerifyAsync(VerificationContext ctx) { @@ -20,11 +21,7 @@ namespace SharpbinV3.Server.Services.Verification.Providers if (string.IsNullOrEmpty(ctx.Token)) return false; - var parameters = new Dictionary - { - { "secret", _authSettings.CF_Turnstile_SecretKey }, - { "response", ctx.Token } - }; + var parameters = new Dictionary { { "secret", _authSettings.CF_Turnstile_SecretKey }, { "response", ctx.Token } }; if (!string.IsNullOrEmpty(ctx.Ip)) parameters.Add("remoteip", ctx.Ip); diff --git a/SharpbinV3.Server/Services/Verification/VerificationContext.cs b/SharpbinV3.Server/Services/Verification/VerificationContext.cs index e4beed8..a3e224b 100644 --- a/SharpbinV3.Server/Services/Verification/VerificationContext.cs +++ b/SharpbinV3.Server/Services/Verification/VerificationContext.cs @@ -8,5 +8,4 @@ public Guid? UserUUID { get; init; } public string? Code { get; init; } } - } diff --git a/SharpbinV3.Server/Services/Verification/VerificationService.cs b/SharpbinV3.Server/Services/Verification/VerificationService.cs index 8b5670d..2ac7a6c 100644 --- a/SharpbinV3.Server/Services/Verification/VerificationService.cs +++ b/SharpbinV3.Server/Services/Verification/VerificationService.cs @@ -8,10 +8,7 @@ namespace SharpbinV3.Server.Services.Verification private IVerificationProvider? GetActiveProvider() { - return _providers - .Where(p => p.IsConfigured) - .OrderByDescending(p => p.Priority) - .FirstOrDefault(); + return _providers.Where(p => p.IsConfigured).OrderByDescending(p => p.Priority).FirstOrDefault(); } public async Task VerifyAsync(VerificationContext context, IVerificationProvider? provider = null) diff --git a/SharpbinV3.Server/Settings/JWTSettings.cs b/SharpbinV3.Server/Settings/JWTSettings.cs index d120035..0ae8aea 100644 --- a/SharpbinV3.Server/Settings/JWTSettings.cs +++ b/SharpbinV3.Server/Settings/JWTSettings.cs @@ -6,8 +6,10 @@ namespace SharpbinV3.Server.Settings { [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 9304b99..9854ad6 100644 --- a/SharpbinV3.Server/Settings/PasteSettings.cs +++ b/SharpbinV3.Server/Settings/PasteSettings.cs @@ -9,8 +9,10 @@ namespace SharpbinV3.Server.Settings public int MaxPasteSizeInBytes { get; set; } = 1_048_576; // 1 MB public bool EnablePasteCompression { get; set; } = true; public bool RequiresVerification { 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/SharpbinV3.Server.csproj b/SharpbinV3.Server/SharpbinV3.Server.csproj index ace4cd5..2a0eada 100644 --- a/SharpbinV3.Server/SharpbinV3.Server.csproj +++ b/SharpbinV3.Server/SharpbinV3.Server.csproj @@ -1,44 +1,38 @@ - - net10.0 - enable - enable - a95b1aac-5cce-4fa9-8056-51f0d045cf2f - Linux + + net10.0 + enable + enable + a95b1aac-5cce-4fa9-8056-51f0d045cf2f + Linux - false - false - True - false - + false + false + True + false + - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - - - - + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + diff --git a/SharpbinV3.Server/Utilities.cs b/SharpbinV3.Server/Utilities.cs index 3d0f880..3647c13 100644 --- a/SharpbinV3.Server/Utilities.cs +++ b/SharpbinV3.Server/Utilities.cs @@ -10,12 +10,14 @@ namespace SharpbinV3.Server var random = new Random(); return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]); } + public static string ComputeSha256(string input) { var inputBytes = System.Text.Encoding.UTF8.GetBytes(input); var hashBytes = SHA256.HashData(inputBytes); return Convert.ToHexString(hashBytes); } + public static string ComputeHmacSha256(string secret, string input) { var secretBytes = System.Text.Encoding.UTF8.GetBytes(secret); diff --git a/SharpbinV3.Server/dotnet-tools.json b/SharpbinV3.Server/dotnet-tools.json new file mode 100644 index 0000000..97f37dc --- /dev/null +++ b/SharpbinV3.Server/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "csharpier": { + "version": "1.2.6", + "commands": [ + "csharpier" + ], + "rollForward": false + } + } +} \ No newline at end of file