From 410172f922bdc04e53a80ad8892a469af8343461 Mon Sep 17 00:00:00 2001 From: whoswhip Date: Sat, 19 Oct 2024 15:19:09 -0400 Subject: [PATCH] Update rate limiters, endpoints, and UI styles Added a new "fixed-xl" rate limiter policy with a permit limit of 16 and applied it to several endpoints. Replaced "fixed-bigger" with "fixed-xl" on some endpoints. Introduced a new POST endpoint `/api/pastes/admin/change-id` for changing paste IDs, including authorization checks and error handling. Enhanced logging for paste edits to include paste ID and user info. Adjusted rate limiting policies for various endpoints to use "fixed-bigger" instead of "fixed". Modified UI styles: changed `.nav-div` margin-top in `index.html` from 10px to 1.5px, increased `backdrop-filter` blur in `paste.html` and `privatepaste.html` from 2.5px to 5px, added a border to `.input-wrapper-container` in `paste.html` and `privatepaste.html`, removed the title attribute from `

` in `privatepaste.html`, simplified JSON parsing in `fetchInfo` function, removed redundant localization code, and updated `.user-a` class to use `:any-link` pseudo-class. Various minor adjustments to improve code readability and maintainability. --- PasteBin/Program.cs | 119 +++++++++++++++++++++++++++--- PasteBin/assets/index.html | 2 +- PasteBin/assets/paste.html | 3 +- PasteBin/assets/privatepaste.html | 23 ++---- 4 files changed, 120 insertions(+), 27 deletions(-) diff --git a/PasteBin/Program.cs b/PasteBin/Program.cs index fcbd5ec..adf01b8 100644 --- a/PasteBin/Program.cs +++ b/PasteBin/Program.cs @@ -64,6 +64,14 @@ class Program options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; options.QueueLimit = 4; })); + builder.Services.AddRateLimiter(_ => _ + .AddFixedWindowLimiter(policyName: "fixed-xl", options => + { + options.PermitLimit = 16; + options.Window = TimeSpan.FromSeconds(6); + options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; + options.QueueLimit = 4; + })); builder.Services.AddRateLimiter(options => { options.AddPolicy("OneRequestPerIP", context => @@ -462,7 +470,7 @@ class Program await context.Response.WriteAsync(html); return; } - }).RequireRateLimiting("fixed-bigger"); + }); app.MapGet("/raw/{id}", async (HttpContext context) => { var id = context.Request?.RouteValues?["id"]?.ToString(); @@ -561,7 +569,7 @@ class Program { await stream.CopyToAsync(context.Response.Body); } - }).RequireRateLimiting("fixed-bigger"); + }); app.MapGet("/pastes", async (HttpContext context) => { @@ -802,7 +810,7 @@ class Program return; } } - }); + }).RequireRateLimiting("fixed-xl"); app.MapGet("/uid/{uid}", async (HttpContext context) => { string username = context.Request?.RouteValues?["uid"]?.ToString(); @@ -899,7 +907,7 @@ class Program return; } } - }); + }).RequireRateLimiting("fixed-xl"); #region ADMIN PANEL @@ -1467,7 +1475,92 @@ class Program context.Response.ContentType = "application/json"; await context.Response.WriteAsync(usersJson.ToString()); } - }).RequireRateLimiting("fixed-bigger"); ; + }).RequireRateLimiting("fixed-bigger"); + app.MapPost("/api/pastes/admin/change-id", async (HttpContext context) => + { + var token = context.Request.Cookies["token"] ?? context.Request.Headers["Authorization"]; + var user = await GetLoggedInUserAsync(token); + if (string.IsNullOrEmpty(user.UID) || user.Type != 255) + { + context.Response.StatusCode = 401; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(new JObject { ["error"] = "Unauthorized" }.ToString()); + return; + } + string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync(); + try + { + JObject.Parse(requestBody); + } + catch + { + context.Response.StatusCode = 400; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(new JObject { ["error"] = "Invalid JSON" }.ToString()); + return; + } + var json = JObject.Parse(requestBody); + var pasteId = SanitizeInput(json["pasteId"]?.ToString() ?? ""); + var newPasteId = SanitizeInput(json["newPasteId"]?.ToString() ?? ""); + + if (string.IsNullOrEmpty(pasteId) || string.IsNullOrWhiteSpace(pasteId) || string.IsNullOrEmpty(newPasteId) || string.IsNullOrWhiteSpace(newPasteId)) + { + context.Response.StatusCode = 400; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(new JObject { ["error"] = "Invalid request body" }.ToString()); + return; + } + + if (!File.Exists($"pastes/{pasteId}.txt")) + { + context.Response.StatusCode = 404; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(new JObject { ["error"] = "Paste not found" }.ToString()); + return; + } + using (var connection = new SqliteConnection("Data Source=pastes.sqlite")) + { + await connection.OpenAsync(); + var command = connection.CreateCommand(); + command.CommandText = "SELECT * FROM pastes WHERE Id = @Id"; + command.Parameters.AddWithValue("@Id", pasteId); + var reader = await command.ExecuteReaderAsync(); + await reader.ReadAsync(); + if (!reader.HasRows) + { + context.Response.StatusCode = 404; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(new JObject { ["error"] = "Paste not found" }.ToString()); + return; + } + var paste = new Paste + { + Title = reader.GetString(1), + UnixDate = long.Parse(reader.GetString(2)), + Size = reader.GetString(3), + Visibility = reader.GetString(4), + Id = reader.GetString(5), + Uploader = reader.GetString(6), + }; + var changeIdCommand = connection.CreateCommand(); + changeIdCommand.CommandText = "UPDATE pastes SET Id = @NewId WHERE Id = @Id"; + changeIdCommand.Parameters.AddWithValue("@NewId", newPasteId); + changeIdCommand.Parameters.AddWithValue("@Id", pasteId); + await changeIdCommand.ExecuteNonQueryAsync(); + File.Move($"pastes/{pasteId}.txt", $"pastes/{newPasteId}.txt"); + if (File.Exists($"pastes/{pasteId}.txt")) + { + context.Response.StatusCode = 500; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(new JObject { ["error"] = "Failed to change paste ID" }.ToString()); + return; + } + await Logging.LogInfo($"Paste {pasteId} has been changed to {newPasteId} by {user.Username}({user.UUID})"); + context.Response.StatusCode = 200; + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(new JObject { ["message"] = "Paste ID changed" }.ToString()); + } + }).RequireRateLimiting("fixed"); #endregion @@ -1698,15 +1791,21 @@ class Program return; } + var updateCommand = connection.CreateCommand(); + updateCommand.CommandText = "UPDATE pastes SET Size = @Size WHERE ID = @ID"; + updateCommand.Parameters.AddWithValue("@Size", content.Length.ToString()); + updateCommand.Parameters.AddWithValue("@ID", id); + await updateCommand.ExecuteNonQueryAsync(); + var compressedContent = await Compression.CompressString(content); await File.WriteAllBytesAsync($"pastes/{id}.txt", compressedContent); - await Logging.LogInfo($"{user.Username}({user.UUID}) edited their paste {paste.Id}"); + await Logging.LogInfo($"Paste {paste.Id} edited by {user.Username}({user.UUID})"); } context.Response.StatusCode = 200; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(new JObject { ["message"] = "Paste edited" }.ToString()); - }); + }).RequireRateLimiting("fixed-bigger"); app.MapPost("/api/pastes/delete", async (HttpContext context) => { string token = context.Request.Cookies["token"] ?? context.Request.Headers["Authorization"]; @@ -1947,7 +2046,7 @@ class Program } } - }).RequireRateLimiting("fixed"); + }).RequireRateLimiting("fixed-bigger"); app.MapGet("/api/pastes/info", async (HttpContext context) => { var query = context.Request.Query; @@ -2010,7 +2109,7 @@ class Program context.Response.ContentType = "application/json"; await context.Response.WriteAsync(responseJson.ToString()); } - }).RequireRateLimiting("fixed"); + }); app.MapPost("/api/pastes/password/{pasteid}", async (HttpContext context) => { var body = await new StreamReader(context.Request.Body).ReadToEndAsync(); @@ -2397,7 +2496,7 @@ class Program context.Response.StatusCode = 200; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(responseJson.ToString()); - })).RequireRateLimiting("fixed"); ; + })).RequireRateLimiting("fixed-xl"); ; #endregion diff --git a/PasteBin/assets/index.html b/PasteBin/assets/index.html index ef9e970..8a469e7 100644 --- a/PasteBin/assets/index.html +++ b/PasteBin/assets/index.html @@ -318,7 +318,7 @@ .nav-div { top: 0; - margin-top: 10px; + margin-top: 1.5px; position: absolute; display: flex; flex-direction: row; diff --git a/PasteBin/assets/paste.html b/PasteBin/assets/paste.html index bf4cef7..dac31de 100644 --- a/PasteBin/assets/paste.html +++ b/PasteBin/assets/paste.html @@ -313,7 +313,7 @@ width: 100%; height: 100%; color: white; - backdrop-filter: blur(2.5px); + backdrop-filter: blur(5px); } .input-wrapper-container{ z-index: 101; @@ -325,6 +325,7 @@ border-radius: 5px; padding: 20px; background-color: #181818; + border: #222222 2px solid; } body { diff --git a/PasteBin/assets/privatepaste.html b/PasteBin/assets/privatepaste.html index 051b01b..53e4b43 100644 --- a/PasteBin/assets/privatepaste.html +++ b/PasteBin/assets/privatepaste.html @@ -33,7 +33,7 @@
-

{pastetitle}

+

@@ -97,8 +97,7 @@ function fetchInfo() { fetch('/api/pastes/info?id={pasteid}') .then(response => response.json()) - .then(data => { - const json = JSON.parse(data); + .then(json => { info = json; document.getElementById('uploader-username').innerText = json.uploader; document.getElementById('creationdate').innerText = localizeDateTime(json.date); @@ -144,8 +143,7 @@ }) }) .then(response => response.json()) - .then(obj => { - const result = obj; + .then(result => { if (result.content != null) { const textElement = document.getElementById('text'); textElement.innerText = result.content; @@ -166,10 +164,6 @@ document.addEventListener("DOMContentLoaded", function () { fetchInfo(); authenticated(); - - const creationdateElement = document.getElementById('creationdate'); - const creationdateText = creationdateElement.innerText.trim(); - creationdateElement.innerText = localizeDateTime(parseInt(creationdateText)); var mobile = window.mobileCheck(); if (mobile) { document.querySelector('.nav-div').style.display = 'none'; @@ -218,8 +212,7 @@ }) }) .then(response => response.json()) - .then(obj => { - const result = obj; + .then(result => { if (result.message != null) { createNotification(`Success: ${result.message}`); setTimeout(() => { @@ -244,8 +237,7 @@ }) }) .then(response => response.json()) - .then(obj => { - const result = obj; + .then(result => { if (result.message != null) { createNotification(`Success: ${result.message}`); document.getElementById('text').innerText = text; @@ -313,7 +305,7 @@ width: 100%; height: 100%; color: white; - backdrop-filter: blur(2.5px); + backdrop-filter: blur(5px); } .input-wrapper-container { @@ -326,6 +318,7 @@ border-radius: 5px; padding: 20px; background-color: #181818; + border: #222222 2px solid; } .container-wrapper { @@ -474,7 +467,7 @@ font-weight: 600; } - .user-a { + .user-a:any-link { color: rgb(190, 190, 190); text-decoration: none; text-decoration: underline;