diff --git a/.vscode/launch.json b/.vscode/launch.json index eabdc4f..0319fd6 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,12 +1,10 @@ { - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", "configurations": [ - - - - + { + "name": "C#: SharpbinV2.Server Debug", + "type": "dotnet", + "request": "launch", + "projectPath": "${workspaceFolder}/SharpbinV2.Server/SharpbinV2.Server.csproj" + } ] } \ No newline at end of file diff --git a/SharpbinV2.Server/Classes.cs b/SharpbinV2.Server/Classes.cs index 5cd34c3..5bb236d 100644 --- a/SharpbinV2.Server/Classes.cs +++ b/SharpbinV2.Server/Classes.cs @@ -52,4 +52,15 @@ public string? UserAgent { get; set; } public long? Created { get; set; } } + public class PasswordReset + { + public string? UID { get; set; } + public string? UUID { get; set; } + public string? USERUUID { get; set; } + public string? URL { get; set; } + public string? Token { get; set; } + public long? Created { get; set; } + public long? Expirary { get; set; } + } + } diff --git a/SharpbinV2.Server/Database.cs b/SharpbinV2.Server/Database.cs index 38225a9..8ec1c4d 100644 --- a/SharpbinV2.Server/Database.cs +++ b/SharpbinV2.Server/Database.cs @@ -279,5 +279,56 @@ namespace SharpbinV2.Server } } } + + public static async Task GetPasswordReset(string url, string uuid, string token) + { + if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(uuid) || string.IsNullOrEmpty(token)) + return null; + using (var connection = new SqliteConnection(Program.MainDatabaseConnection)) + { + await connection.OpenAsync(); + using (var command = new SqliteCommand(Program.MainDatabaseConnection)) + { + command.CommandText = "SELECT * FROM passwordresets WHERE URL = @URL AND UUID = @UUID AND Token = @Token;"; + command.Parameters.AddWithValue("@URL", url); + command.Parameters.AddWithValue("@UUID", uuid); + command.Parameters.AddWithValue("@Token", token); + await command.ExecuteNonQueryAsync(); + using (var reader = await command.ExecuteReaderAsync()) + { + if (!reader.HasRows) + return null; + await reader.ReadAsync(); + return new PasswordReset + { + UID = reader.GetString(0), + UUID = reader.GetString(1), + USERUUID = reader.GetString(2), + URL = reader.GetString(3), + Token = reader.GetString(4), + Created = reader.GetInt64(5), + Expirary = reader.GetInt64(6) + }; + } + } + } + } + public static async Task ResetPassword(string uuid, string password_hash) + { + if (string.IsNullOrEmpty(uuid) || string.IsNullOrEmpty(password_hash)) + return false; + using (var connection = new SqliteConnection(Program.MainDatabaseConnection)) + { + await connection.OpenAsync(); + using (var command = new SqliteCommand(Program.MainDatabaseConnection)) + { + command.CommandText = "UPDATE users SET Password = @Password WHERE UUID = @UUID;"; + command.Parameters.AddWithValue("@Password", password_hash); + command.Parameters.AddWithValue("@UUID", uuid); + await command.ExecuteNonQueryAsync(); + return true; + } + } + } } } diff --git a/SharpbinV2.Server/Program.cs b/SharpbinV2.Server/Program.cs index 2b7e6a6..4295810 100644 --- a/SharpbinV2.Server/Program.cs +++ b/SharpbinV2.Server/Program.cs @@ -4,6 +4,7 @@ using System.Text; using Bcrypt = BCrypt.Net.BCrypt; using System.Security.Cryptography; using UAParser; +using Microsoft.AspNetCore.RateLimiting; namespace SharpbinV2.Server { @@ -49,11 +50,11 @@ namespace SharpbinV2.Server builder.Configuration.AddEnvironmentVariables(); if (Environment.GetEnvironmentVariable("HTTPS") == "true") { - builder.WebHost.UseUrls($"https://*:{Environment.GetEnvironmentVariable("HTTPS_Port") ?? "5820"}"); + builder.WebHost.UseUrls($"https://*:{Environment.GetEnvironmentVariable("ASPNETCORE_HTTPS_PORTS") ?? "5820"}"); } else { - builder.WebHost.UseUrls($"http://*:{Environment.GetEnvironmentVariable("HTTP_Port") ?? "5810"}"); + builder.WebHost.UseUrls($"http://*:{Environment.GetEnvironmentVariable("ASPNETCORE_HTTP_PORTS") ?? "5810"}"); } MaxFileSize = Environment.GetEnvironmentVariable("MAX_FILE_SIZE") != null ? Convert.ToInt64(Environment.GetEnvironmentVariable("MAX_FILE_SIZE")) : MaxFileSize; HMACSecret = Environment.GetEnvironmentVariable("HMAC_SECRET") ?? HMACSecret; @@ -72,6 +73,41 @@ namespace SharpbinV2.Server options.Limits.MaxRequestBodySize = null; }); + builder.Services.AddRateLimiter(options => + { + options.AddTokenBucketLimiter("uploads", opt => + { + opt.TokenLimit = 10; + opt.ReplenishmentPeriod = TimeSpan.FromMinutes(1); + opt.TokensPerPeriod = 2; + opt.AutoReplenishment = true; + }); + + options.AddTokenBucketLimiter("auth", opt => + { + opt.TokenLimit = 15; + opt.ReplenishmentPeriod = TimeSpan.FromMinutes(5); + opt.TokensPerPeriod = 10; + opt.AutoReplenishment = true; + }); + + options.AddFixedWindowLimiter("general", opt => + { + opt.PermitLimit = 200; + opt.Window = TimeSpan.FromMinutes(1); + }); + + options.OnRejected = async (context, token) => + { + context.HttpContext.Response.StatusCode = 429; + await context.HttpContext.Response.WriteAsJsonAsync(new + { + success = false, + message = "Rate limit exceeded. Please try again later." + }); + }; + }); + // Add services to the container. builder.Services.AddCors(); builder.Services.AddResponseCaching(); @@ -92,7 +128,7 @@ namespace SharpbinV2.Server app.UseRouting(); app.UseStaticFiles(); - //app.UseRateLimiter(); + app.UseRateLimiter(); app.UseCors(builder => { @@ -109,7 +145,7 @@ namespace SharpbinV2.Server context.Response.StatusCode = 200; context.Response.Headers.Add("Content-Type", "text/html"); return context.Response.SendFileAsync("wwwroot/index.html"); - }); + }).RequireRateLimiting("general"); app.MapGet("/{pasteid}", async (HttpContext context, IWebHostEnvironment env) => { var pasteid = context.Request.RouteValues["pasteid"].ToString() ?? null; @@ -182,7 +218,7 @@ namespace SharpbinV2.Server context.Response.StatusCode = 200; context.Response.Headers.Add("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/paste.html"); - }); + }).RequireRateLimiting("general"); app.MapGet("/error", async (HttpContext context) => { context.Response.StatusCode = 400; @@ -220,7 +256,7 @@ namespace SharpbinV2.Server { await context.Response.SendFileAsync(paste.FilePath); } - }); + }).RequireRateLimiting("general"); app.MapGet("/paste.html", (HttpContext context) => { context.Response.Redirect("/"); @@ -230,13 +266,13 @@ namespace SharpbinV2.Server context.Response.StatusCode = 200; context.Response.Headers.Add("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/archive.html"); - }); + }).RequireRateLimiting("general"); app.MapGet("/dash", async (HttpContext context) => { context.Response.StatusCode = 200; context.Response.Headers.Add("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/dash.html"); - }); + }).RequireRateLimiting("general"); app.MapGet("/dash.html", (HttpContext context) => { context.Response.Redirect("/dash"); @@ -246,13 +282,13 @@ namespace SharpbinV2.Server context.Response.StatusCode = 200; context.Response.Headers.Add("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/login.html"); - }); + }).RequireRateLimiting("general"); app.MapGet("/register", async (HttpContext context) => { context.Response.StatusCode = 200; context.Response.Headers.Add("Content-Type", "text/html"); await context.Response.SendFileAsync("wwwroot/register.html"); - }); + }).RequireRateLimiting("general"); app.MapGet("/u/{username}", async (HttpContext context) => { var username = context.Request.RouteValues["username"].ToString() ?? null; @@ -270,9 +306,15 @@ namespace SharpbinV2.Server context.Response.Headers.Add("Expires", "0"); - context.Response.WriteAsync(html); + await context.Response.WriteAsync(html); - }); + }).RequireRateLimiting("general"); + app.MapGet("/reset-password", async (HttpContext context) => + { + context.Response.StatusCode = 200; + context.Response.Headers.Add("Content-Type", "text/html"); + await context.Response.SendFileAsync("wwwroot/reset-password.html"); + }).RequireRateLimiting("general"); #endregion @@ -369,7 +411,7 @@ namespace SharpbinV2.Server await context.Response.WriteAsJsonAsync(new { success = true, message = "Account created." }); logger.LogInfo($"Account {username} has been created."); return; - }); + }).RequireRateLimiting("auth"); app.MapPost("/api/accounts/login", async (HttpContext context) => { var requestdetails = GetRequestDetails(context); @@ -466,7 +508,7 @@ namespace SharpbinV2.Server await context.Response.WriteAsJsonAsync(new { success = true, message = "Logged in." }); logger.LogInfo($"User {user.UUID} logged in."); return; - }); + }).RequireRateLimiting("auth"); app.MapGet("/api/accounts/authorized", async (HttpContext context) => { var requestdetails = GetRequestDetails(context); @@ -565,7 +607,7 @@ namespace SharpbinV2.Server context.Response.StatusCode = 200; await context.Response.WriteAsJsonAsync(new { success = true, message = "Account deleted." }); - }); + }).RequireRateLimiting("auth"); app.MapPost("/api/accounts/logout", async (HttpContext context) => { var requestdetails = GetRequestDetails(context); @@ -605,7 +647,103 @@ namespace SharpbinV2.Server context.Response.StatusCode = 200; await context.Response.WriteAsJsonAsync(new { success = true, message = "Logged out." }); }); - + app.MapPost("/api/accounts/reset-password", async (HttpContext context) => + { + var requestdetails = GetRequestDetails(context); + if (string.IsNullOrEmpty(requestdetails.Token)) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "No token provided, not authorized." }); + return; + } + + var body = await new StreamReader(context.Request.Body).ReadToEndAsync(); + if (body == null) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid Body." }); + return; + } + var json = TryParse(body); + if (json == null) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid JSON." }); + return; + } + if (!string.IsNullOrEmpty(json["token"]?.ToString()) && !string.IsNullOrEmpty(json["uuid"]?.ToString()) && !string.IsNullOrEmpty(json["url"]?.ToString())) + { + var password = json["password"]?.ToString(); + var uuid = json["uuid"]?.ToString(); + var token = json["token"]?.ToString(); + var url = json["url"]?.ToString(); + + if (string.IsNullOrEmpty(uuid) || string.IsNullOrEmpty(token) || string.IsNullOrEmpty(url) || string.IsNullOrEmpty(password)) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "Missing required fields." }); + return; + } + + var pwreset = await Database.GetPasswordReset(url, uuid, token); + if (pwreset == null) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token/url/uuid." }); + return; + } + var user = await Database.UserFromUUID(uuid); + if (user == null) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid user." }); + return; + } + var passwordHashed = Bcrypt.HashPassword(password, Bcrypt.GenerateSalt(12)); + if (!Database.ResetPassword(user.UUID ?? "", passwordHashed).Result) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "Failed to reset password." }); + return; + } + else + { + context.Response.StatusCode = 200; + await context.Response.WriteAsJsonAsync(new { success = true, message = "Password reset." }); + } + return; + } + else // normal password resets from the dashboard + { + var user = await Database.UserFromToken(requestdetails.Token); + if (user == null) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token." }); + return; + } + var password = json["password"]?.ToString(); + if (string.IsNullOrEmpty(password)) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "Missing required fields." }); + return; + } + var passwordHashed = Bcrypt.HashPassword(password, Bcrypt.GenerateSalt(12)); + if (!Database.ResetPassword(user.UUID ?? "", passwordHashed).Result) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "Failed to reset password." }); + return; + } + else + { + context.Response.StatusCode = 200; + await context.Response.WriteAsJsonAsync(new { success = true, message = "Password reset." }); + } + } + }).RequireRateLimiting("auth"); + app.MapPost("/api/pastes/create", async (HttpContext context) => { @@ -654,7 +792,7 @@ namespace SharpbinV2.Server context.Response.StatusCode = 400; await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid syntax language." }); return; - } + } bool shouldCompress = await Compression.ShouldCompress(body); if (shouldCompress) @@ -697,7 +835,7 @@ namespace SharpbinV2.Server await context.Response.WriteAsJsonAsync(new { success = true, message = "Paste created.", paste = paste }); logger.LogInfo($"A Paste of {FormatBytes(paste.Size ?? 0)} was created by {paste.UUID}"); return; - }); + }).RequireRateLimiting("uploads"); app.MapGet("/api/pastes/archive", async (HttpContext context) => { var queries = context.Request.Query; @@ -765,7 +903,7 @@ namespace SharpbinV2.Server } } } - }); + }).RequireRateLimiting("general"); app.MapGet("/api/pastes/my", async (HttpContext context) => { var requestdetails = GetRequestDetails(context); @@ -877,9 +1015,9 @@ namespace SharpbinV2.Server authorUsername = "Anonymous"; } context.Response.StatusCode = 200; - await context.Response.WriteAsJsonAsync(new - { - success = true, + await context.Response.WriteAsJsonAsync(new + { + success = true, paste = new { paste.UUID, @@ -894,9 +1032,9 @@ namespace SharpbinV2.Server paste.TrueSize, paste.Views, paste.Syntax - } + } }); - }); + }).RequireRateLimiting("general"); app.MapGet("/api/pastes/{pasteid}", async (HttpContext context) => { var pasteid = context.Request.RouteValues["pasteid"].ToString() ?? null; @@ -919,7 +1057,7 @@ namespace SharpbinV2.Server await context.Response.SendFileAsync(paste.FilePath); } return; - }); + }).RequireRateLimiting("general"); app.MapGet("/api/pastes/{pasteid}/views", async (HttpContext context) => { var requestdetails = GetRequestDetails(context); @@ -993,13 +1131,13 @@ namespace SharpbinV2.Server }); } context.Response.StatusCode = 200; - await context.Response.WriteAsJsonAsync(new { success = true, views, viewcount }); + await context.Response.WriteAsJsonAsync(new { success = true, views, viewcount }); } } } - }); + }).RequireRateLimiting("general"); app.MapGet("/api/users/uuid/{uuid}", async (HttpContext context) => { @@ -1017,7 +1155,7 @@ namespace SharpbinV2.Server await context.Response.WriteAsJsonAsync(new { success = false, message = "User not found." }); return; } - + context.Response.StatusCode = 200; await context.Response.WriteAsJsonAsync(new { @@ -1032,7 +1170,7 @@ namespace SharpbinV2.Server user.LastLogin } }); - }); + }).RequireRateLimiting("general"); app.MapGet("/api/users/{username}", async (HttpContext context) => { var username = context.Request.RouteValues["username"].ToString() ?? null; @@ -1063,7 +1201,7 @@ namespace SharpbinV2.Server user.LastLogin } }); - }); + }).RequireRateLimiting("general"); app.MapGet("/api/users/{uuid}/pastes", async (HttpContext context) => { var uuid = context.Request.RouteValues["uuid"].ToString() ?? null; @@ -1145,7 +1283,7 @@ namespace SharpbinV2.Server } } - }); + }).RequireRateLimiting("general"); app.MapGet("/api/site/info", async (HttpContext context) => { @@ -1155,6 +1293,65 @@ namespace SharpbinV2.Server MaxFileSize }; await context.Response.WriteAsJsonAsync(new { success = true, info }); + }).RequireRateLimiting("general"); + + app.MapGet("/admin/{useruuid}/reset-password", async (HttpContext context) => + { + var requestdetails = GetRequestDetails(context); + var user = await Database.UserFromToken(requestdetails.Token); + if (user == null) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid token." }); + return; + } + if (user.Type != 255) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "Not authorized." }); + return; + } + + var useruuid = context.Request.RouteValues["useruuid"].ToString() ?? null; + if (string.IsNullOrEmpty(useruuid)) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "Invalid UUID." }); + return; + } + var targetuser = await Database.UserFromUUID(useruuid); + if (targetuser == null) + { + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(new { success = false, message = "User not found." }); + return; + } + string uuid = Guid.NewGuid().ToString(); + string url = GenerateRandomString(32); + string token = GenerateToken(); + using (var connection = new SqliteConnection(MainDatabaseConnection)) + { + await connection.OpenAsync(); + var expiry = DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds(); + using (var command = connection.CreateCommand()) + { + command.CommandText = "INSERT INTO passwordresets (UUID, USERUUID, URL, Token,Created, Expirary) VALUES (@UUID, @USERUUID, @URL, @Token,@Created, @Expirary);"; + command.Parameters.AddWithValue("@UUID", uuid); + command.Parameters.AddWithValue("@USERUUID", targetuser.UUID); + command.Parameters.AddWithValue("@URL", url); + command.Parameters.AddWithValue("@Token", token); + command.Parameters.AddWithValue("@Created", DateTimeOffset.UtcNow.ToUnixTimeSeconds()); + command.Parameters.AddWithValue("@Expirary", expiry); + await command.ExecuteNonQueryAsync(); + } + await connection.CloseAsync(); + } + var resetlink = $"{context.Request.Scheme}://{context.Request.Host}/reset-password?uuid={uuid}&url={url}&token={token}"; + + context.Response.StatusCode = 200; + + context.Response.Headers.Add("Content-Type", "application/json"); + await context.Response.WriteAsJsonAsync(new { success = true, resetlink, uuid, url, token }); }); @@ -1347,7 +1544,7 @@ namespace SharpbinV2.Server } } - + /// diff --git a/SharpbinV2.Server/Properties/launchSettings.json b/SharpbinV2.Server/Properties/launchSettings.json index ed6a27c..96392ed 100644 --- a/SharpbinV2.Server/Properties/launchSettings.json +++ b/SharpbinV2.Server/Properties/launchSettings.json @@ -7,7 +7,7 @@ "ASPNETCORE_ENVIRONMENT": "Development" }, "dotnetRunMessages": true, - "applicationUrl": "http://localhost:5028" + "applicationUrl": "http://localhost:5810" }, "https": { "commandName": "Project", @@ -16,7 +16,7 @@ "ASPNETCORE_ENVIRONMENT": "Development" }, "dotnetRunMessages": true, - "applicationUrl": "https://localhost:7260;http://localhost:5028" + "applicationUrl": "https://localhost:5820;http://localhost:5810" }, "IIS Express": { "commandName": "IISExpress", diff --git a/SharpbinV2.Server/wwwroot/css/auth.css b/SharpbinV2.Server/wwwroot/css/auth.css index ea4fde4..4953326 100644 --- a/SharpbinV2.Server/wwwroot/css/auth.css +++ b/SharpbinV2.Server/wwwroot/css/auth.css @@ -26,6 +26,14 @@ color: var(--neutral-100); } +.auth-description { + text-align: center; + color: var(--neutral-400); + font-size: 0.9rem; + margin-bottom: 20px; + line-height: 1.5; +} + .auth-form { display: flex; flex-direction: column; @@ -120,6 +128,17 @@ animation: fadeIn 0.3s ease; } +.success-message { + background-color: rgba(34, 197, 94, 0.1); + color: #22c55e; + padding: 10px 16px; + border-radius: 6px; + margin-bottom: 16px; + font-size: 0.9rem; + border: 1px solid rgba(34, 197, 94, 0.2); + animation: fadeIn 0.3s ease; +} + @keyframes fadeIn { from { opacity: 0; diff --git a/SharpbinV2.Server/wwwroot/login.html b/SharpbinV2.Server/wwwroot/login.html index 40512ec..a9382e0 100644 --- a/SharpbinV2.Server/wwwroot/login.html +++ b/SharpbinV2.Server/wwwroot/login.html @@ -29,9 +29,9 @@ - -