From 01a637f5dded64112f9f865e661d452d9e891b30 Mon Sep 17 00:00:00 2001 From: whoswhip <124531971+whoswhip@users.noreply.github.com> Date: Fri, 17 Jan 2025 21:17:37 -0500 Subject: [PATCH] Add frontend files, improve backend. --- README.md | 9 ++ SharpbinV2.Server/Program.cs | 125 +++++++++++++++++++- SharpbinV2.Server/SharpbinV2.Server.csproj | 11 +- SharpbinV2.Server/assets/index.html | 0 SharpbinV2.Server/wwwroot/css/paste.css | 75 ++++++++++++ SharpbinV2.Server/wwwroot/css/style.css | 130 +++++++++++++++++++++ SharpbinV2.Server/wwwroot/error.html | 23 ++++ SharpbinV2.Server/wwwroot/index.html | 58 +++++++++ SharpbinV2.Server/wwwroot/js/error.js | 22 ++++ SharpbinV2.Server/wwwroot/js/index.js | 79 +++++++++++++ SharpbinV2.Server/wwwroot/js/navbar.js | 9 ++ SharpbinV2.Server/wwwroot/js/paste.js | 127 ++++++++++++++++++++ SharpbinV2.Server/wwwroot/paste.html | 42 +++++++ 13 files changed, 699 insertions(+), 11 deletions(-) create mode 100644 README.md delete mode 100644 SharpbinV2.Server/assets/index.html create mode 100644 SharpbinV2.Server/wwwroot/css/paste.css create mode 100644 SharpbinV2.Server/wwwroot/css/style.css create mode 100644 SharpbinV2.Server/wwwroot/error.html create mode 100644 SharpbinV2.Server/wwwroot/index.html create mode 100644 SharpbinV2.Server/wwwroot/js/error.js create mode 100644 SharpbinV2.Server/wwwroot/js/index.js create mode 100644 SharpbinV2.Server/wwwroot/js/navbar.js create mode 100644 SharpbinV2.Server/wwwroot/js/paste.js create mode 100644 SharpbinV2.Server/wwwroot/paste.html diff --git a/README.md b/README.md new file mode 100644 index 0000000..b4fff61 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# SharpbinV2 +SharpbinV2 is a re-write to the original messy code base. Instead of using html files and replacing variables it now is done with just apis and static html pages served from `wwwroot`. +## Current Features +- Account Systrem +- Syntax Highlighting +- Private Pastes with Client Side Encryption +- Raw Text Serving +- Paste Compression at Rest and on Response Transit (Files are only compressed when there is a considerable file size decrease) +- Cleaner Code Base \ No newline at end of file diff --git a/SharpbinV2.Server/Program.cs b/SharpbinV2.Server/Program.cs index 8018371..2256ec5 100644 --- a/SharpbinV2.Server/Program.cs +++ b/SharpbinV2.Server/Program.cs @@ -48,6 +48,7 @@ namespace SharpbinV2.Server //app.UseHttpsRedirection(); app.UseRouting(); + app.UseStaticFiles(); //app.UseRateLimiter(); @@ -63,9 +64,107 @@ namespace SharpbinV2.Server #region Static Endpoints app.MapGet("/", async (HttpContext context) => { + context.Response.Redirect("/index.html"); + }); + app.MapGet("/{pasteid}", async (HttpContext context, IWebHostEnvironment env) => + { + var pasteid = context.Request.RouteValues["pasteid"].ToString() ?? null; + if (string.IsNullOrEmpty(pasteid)) + { + context.Response.StatusCode = 400; + context.Response.Redirect("/error?error=400&message=Invalid paste id."); + return; + } + + var filePath = Path.Combine(env.WebRootPath, pasteid); + if (File.Exists(filePath)) + { + context.Response.StatusCode = 200; + switch (Path.GetExtension(filePath)) + { + case "html": + context.Response.Headers.Add("Content-Type", "text/html"); + break; + case "css": + context.Response.Headers.Add("Content-Type", "text/css"); + break; + case "js": + context.Response.Headers.Add("Content-Type", "text/javascript"); + break; + case "json": + context.Response.Headers.Add("Content-Type", "application/json"); + break; + case "png": + context.Response.Headers.Add("Content-Type", "image/png"); + break; + case "jpg": + case "jpeg": + context.Response.Headers.Add("Content-Type", "image/jpeg"); + break; + case "ico": + context.Response.Headers.Add("Content-Type", "image/x-icon"); + break; + } + await context.Response.SendFileAsync(filePath); + return; + } + var paste = await Database.GetPasteFromID(pasteid); + if (paste == null) + { + context.Response.StatusCode = 400; + context.Response.Redirect("/error?error=400&message=Paste not found."); + return; + } + paste.Views++; + using (var connection = new SqliteConnection(MainDatabaseConnection)) + { + await connection.OpenAsync(); + using (var command = connection.CreateCommand()) + { + command.CommandText = "UPDATE pastes SET Views = @Views WHERE UUID = @UUID;"; + command.Parameters.AddWithValue("@Views", paste.Views); + command.Parameters.AddWithValue("@UUID", paste.UUID); + await command.ExecuteNonQueryAsync(); + } + await connection.CloseAsync(); + } context.Response.StatusCode = 200; context.Response.Headers.Add("Content-Type", "text/html"); - await context.Response.SendFileAsync("assets/index.html"); + await context.Response.SendFileAsync("wwwroot/paste.html"); + }); + app.MapGet("/error", async (HttpContext context) => + { + context.Response.StatusCode = 400; + context.Response.Headers.Add("Content-Type", "text/html"); + await context.Response.SendFileAsync("wwwroot/error.html"); + }); + app.MapGet("/raw/{pasteid}", async (HttpContext context) => + { + var pasteid = context.Request.RouteValues["pasteid"].ToString() ?? null; + if (string.IsNullOrEmpty(pasteid)) + { + context.Response.StatusCode = 400; + context.Response.Redirect("/error?error=400&message=Invalid paste id."); + return; + } + var paste = await Database.GetPasteFromID(pasteid); + if (paste == null) + { + context.Response.StatusCode = 400; + context.Response.Redirect("/error?error=400&message=Paste not found."); + return; + } + context.Response.StatusCode = 200; + context.Response.Headers.Add("Content-Type", "text/plain"); + if (paste.FilePath.EndsWith(".gz")) + { + context.Response.Headers.Add("Content-Encoding", "gzip"); + await context.Response.SendFileAsync(paste.FilePath); + } + else + { + await context.Response.SendFileAsync(paste.FilePath); + } }); #endregion @@ -290,6 +389,10 @@ namespace SharpbinV2.Server paste.Visibility = queries.ContainsKey("visibility") ? Convert.ToInt32(queries["visibility"]) : 0; paste.Title = queries.ContainsKey("title") ? queries["title"].ToString() : $"Untitled-{await Database.EnumeratePastes()}"; paste.Edited = 0; + paste.Views = 0; + paste.Syntax = queries.ContainsKey("syntax") ? queries["syntax"].ToString() : null; + + Console.WriteLine(paste.Syntax); bool shouldCompress = await Compression.ShouldCompress(body); if (shouldCompress) @@ -310,7 +413,7 @@ namespace SharpbinV2.Server await connection.OpenAsync(); using (var command = connection.CreateCommand()) { - command.CommandText = "INSERT INTO pastes (UUID, ID, Visibility, Title, AuthorUUID, FilePath, Created, Edited, Size, TrueSize, Views) VALUES (@UUID, @ID, @Visibility, @Title, @AuthorUUID, @FilePath, @Created, @Edited, @Size, @TrueSize, @Views);"; + command.CommandText = "INSERT INTO pastes (UUID, ID, Visibility, Title, AuthorUUID, FilePath, Created, Edited, Size, TrueSize, Views, Syntax) VALUES (@UUID, @ID, @Visibility, @Title, @AuthorUUID, @FilePath, @Created, @Edited, @Size, @TrueSize, @Views, @Syntax);"; command.Parameters.AddWithValue("@UUID", paste.UUID); command.Parameters.AddWithValue("@ID", paste.ID); command.Parameters.AddWithValue("@Visibility", paste.Visibility); @@ -322,11 +425,12 @@ namespace SharpbinV2.Server command.Parameters.AddWithValue("@Size", paste.Size); command.Parameters.AddWithValue("@TrueSize", paste.TrueSize); command.Parameters.AddWithValue("@Views", paste.Views); + command.Parameters.AddWithValue("@Syntax", paste.Syntax); await command.ExecuteNonQueryAsync(); } await connection.CloseAsync(); } - + paste.FilePath = null; context.Response.StatusCode = 200; await context.Response.WriteAsJsonAsync(new { success = true, message = "Paste created.", paste = paste }); logger.LogInfo($"A Paste of {FormatBytes(paste.Size)} was created by {paste.UUID}"); @@ -348,6 +452,16 @@ namespace SharpbinV2.Server await context.Response.WriteAsJsonAsync(new { success = false, message = "Paste not found." }); return; } + if (paste.AuthorUUID != "0") + { + var user = await Database.UserFromUUID(paste.AuthorUUID); + paste.AuthorUUID = user.Username; + } + else + { + paste.AuthorUUID = "Anonymous"; + } + paste.FilePath = null; context.Response.StatusCode = 200; await context.Response.WriteAsJsonAsync(new { success = true, paste = paste }); }); @@ -493,6 +607,7 @@ namespace SharpbinV2.Server Size INTEGER NOT NULL, TrueSize INTEGER NOT NULL, Views INTEGER NOT NULL DEFAULT 0, + Syntax TEXT, PRIMARY KEY(UID AUTOINCREMENT) );"; await command.ExecuteNonQueryAsync(); @@ -686,7 +801,8 @@ namespace SharpbinV2.Server Edited = reader.GetInt64(8), Size = reader.GetInt32(9), TrueSize = reader.GetInt32(10), - Views = reader.GetInt32(11) + Views = reader.GetInt32(11), + Syntax = reader.IsDBNull(12) ? null : reader.GetString(12) }; } } @@ -839,6 +955,7 @@ namespace SharpbinV2.Server public int Size { get; set; } public int TrueSize { get; set; } public int Views { get; set; } + public string Syntax { get; set; } } class Session { diff --git a/SharpbinV2.Server/SharpbinV2.Server.csproj b/SharpbinV2.Server/SharpbinV2.Server.csproj index 4c7990e..c430c3e 100644 --- a/SharpbinV2.Server/SharpbinV2.Server.csproj +++ b/SharpbinV2.Server/SharpbinV2.Server.csproj @@ -9,13 +9,6 @@ False - - - - - - - @@ -24,4 +17,8 @@ + + + + diff --git a/SharpbinV2.Server/assets/index.html b/SharpbinV2.Server/assets/index.html deleted file mode 100644 index e69de29..0000000 diff --git a/SharpbinV2.Server/wwwroot/css/paste.css b/SharpbinV2.Server/wwwroot/css/paste.css new file mode 100644 index 0000000..300321f --- /dev/null +++ b/SharpbinV2.Server/wwwroot/css/paste.css @@ -0,0 +1,75 @@ +#blur[data-decrypted="false"] { + -webkit-backdrop-filter: blur(10px); + backdrop-filter: blur(10px); +} + +#blur[data-decrypted="true"] { + z-index: -1; +} + +#blur { + z-index: 999; + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; +} + +.paste-information { + display: flex; + justify-content: space-between; + align-items: center; + padding: 10px; + border-bottom: 1px solid var(--neutral-700); +} + +.paste-information p { + margin-left: 2.5px; + margin-right: 2.5px; +} + +.paste-header { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; +} + +.paste-content { + display: flex; + flex-direction: column; + width: 100%; + max-height: 80%; + margin-top: 15px; + background-color: var(--neutral-800); + border-radius: 5px; + border: 1px solid var(--neutral-700); +} +#paste-content { + padding: 10px; + max-width: 100%; + overflow-wrap: break-word; + word-wrap: break-word; + white-space: pre-wrap; +} +.paste-actions{ + padding: 10px; + width: 100%; + border-bottom: 1px solid var(--neutral-700); +} + +button { + padding: 5px; + margin: 5px 0; + border-radius: 5px; + border: 1px solid var(--neutral-700); + background-color: var(--neutral-800); + color: var(--neutral-50); + cursor: pointer; + transition: background-color 0.3s; + font-size: 1rem; +} + + diff --git a/SharpbinV2.Server/wwwroot/css/style.css b/SharpbinV2.Server/wwwroot/css/style.css new file mode 100644 index 0000000..8a1f228 --- /dev/null +++ b/SharpbinV2.Server/wwwroot/css/style.css @@ -0,0 +1,130 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; + font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace; + color: white; +} + +:root { + /* TailwindCSS Neutral Colors */ + --neutral-50: #fafafa; + --neutral-100: #f5f5f5; + --neutral-200: #e5e5e5; + --neutral-300: #d4d4d4; + --neutral-400: #a3a3a3; + --neutral-500: #737373; + --neutral-600: #525252; + --neutral-700: #404040; + --neutral-800: #262626; + --neutral-900: #171717; + --neutral-950: #0a0a0a; +} + +body { + font-family: 'Roboto', sans-serif; + background-color: var(--neutral-950); + height: 100vh; + width: 100%; + display: flex; + justify-content: center; + align-items: center; +} + +.main-container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: var(--neutral-900); + padding: 20px; + border-radius: 5px; + border: 1px solid var(--neutral-800); + width: 80%; +} + +.create-form { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; +} + +.create-form input { + width: 100%; + padding: 10px; + margin: 5px 0; + border-radius: 5px; + border: 1px solid var(--neutral-800); + background-color: var(--neutral-800); + color: var(--neutral-50); + transition: border 0.3s; + font-size: 1rem; +} + +.create-form input:focus { + outline: none; +} + +.create-form input:hover { + border: 1px solid var(--neutral-600); +} + +.create-form textarea { + width: 100%; + min-width: 100%; + max-width: 100%; + height: 2.5rem; + min-height: 2.5rem; + font-size: 1rem; + max-height: 40%; + padding: 10px; + margin: 5px 0; + border-radius: 5px; + border: 1px solid var(--neutral-800); + background-color: var(--neutral-800); + color: var(--neutral-50); + transition: border 0.3s; +} + +.create-form textarea:focus { + outline: none; +} + +.create-form textarea:hover { + border: 1px solid var(--neutral-600); +} + +.create-form button { + width: 100%; + padding: 10px; + margin: 5px 0; + border-radius: 5px; + border: 1px solid var(--neutral-800); + background-color: var(--neutral-800); + color: var(--neutral-50); + cursor: pointer; + transition: background-color 0.3s; + font-size: 1rem; +} + +.create-form button:hover { + background-color: var(--neutral-700); +} + +select { + width: 100%; + padding: 10px; + margin: 5px 0; + border-radius: 5px; + border: 1px solid var(--neutral-800); + background-color: var(--neutral-800); + color: var(--neutral-50); + transition: border 0.3s; + font-size: 1rem; +} + +#syntax { + padding-left: 14rem; +} diff --git a/SharpbinV2.Server/wwwroot/error.html b/SharpbinV2.Server/wwwroot/error.html new file mode 100644 index 0000000..9c72989 --- /dev/null +++ b/SharpbinV2.Server/wwwroot/error.html @@ -0,0 +1,23 @@ + + + + + + Error! - Sharpbin + + + + + + + + +
+

Oops! We've ran into an error.

+

+

+ + + \ No newline at end of file diff --git a/SharpbinV2.Server/wwwroot/index.html b/SharpbinV2.Server/wwwroot/index.html new file mode 100644 index 0000000..f4ac163 --- /dev/null +++ b/SharpbinV2.Server/wwwroot/index.html @@ -0,0 +1,58 @@ + + + + + + + Sharpbin + + + + + + + + + +
+
+ + + + + + + +
+
+ + + + \ No newline at end of file diff --git a/SharpbinV2.Server/wwwroot/js/error.js b/SharpbinV2.Server/wwwroot/js/error.js new file mode 100644 index 0000000..07392fd --- /dev/null +++ b/SharpbinV2.Server/wwwroot/js/error.js @@ -0,0 +1,22 @@ +const errors = { + "400": "You've made a bad request.", + "401": "You are unauthorized to access this page.", + "403": "Forbidden! You don't have permission.", + "404": "Page not found.", + "500": "Internal server error.", +}; + +document.addEventListener("DOMContentLoaded", function () { + var queries = new URLSearchParams(window.location.search); + var error = queries.get("error"); + var message = queries.get("message"); + var errorElement = document.getElementById("error-header"); + var messageElement = document.getElementById("error-message"); + + if (error != null) { + errorElement.innerText = errors[error]; + } + if (message != null) { + messageElement.innerText = message; + } +}); \ No newline at end of file diff --git a/SharpbinV2.Server/wwwroot/js/index.js b/SharpbinV2.Server/wwwroot/js/index.js new file mode 100644 index 0000000..c21cd2f --- /dev/null +++ b/SharpbinV2.Server/wwwroot/js/index.js @@ -0,0 +1,79 @@ +document.addEventListener("DOMContentLoaded", async function () { + var visibility = document.getElementById("visibility"); + visibility.value = "0"; +}); + + +document.getElementById("create-form").addEventListener("submit", async function (event) { + event.preventDefault(); + var title = document.getElementById("title").value; + var content = document.getElementById("content").value; + + var visibility = document.getElementById("visibility").value; + var password = document.getElementById("password").value; + var syntax = document.getElementById("syntax").value; + + if (visibility === "2" && password !== "" && password.length >= 6) { + content = await encryptAES(content, password); + console.log(content); + } + else if (visibility === "2") { + alert("Password must be at least 6 characters long"); + return; + } + + fetch(`/api/pastes/create?title=${title}&visibility=${visibility}&syntax=${syntax}`, { + method: "POST", + body: content + }) + .then(response => response.json()) + .then(data => { + const paste = data.paste; + window.location.href = `/${paste.id}`; + }); +}); + +function changeVisibility() { + var visibility = document.getElementById("visibility").value; + var password = document.getElementById("password"); + if (visibility === "2") { + password.style.display = "block"; + } else { + password.style.display = "none"; + } +} + +async function encryptAES(content, password) { + const enc = new TextEncoder(); + const keyMaterial = await window.crypto.subtle.importKey( + "raw", + enc.encode(password), + { name: "PBKDF2" }, + false, + ["deriveKey"] + ); + const key = await window.crypto.subtle.deriveKey( + { + name: "PBKDF2", + salt: enc.encode("salt"), + iterations: 100000, + hash: "SHA-256" + }, + keyMaterial, + { name: "AES-GCM", length: 256 }, + false, + ["encrypt"] + ); + const iv = window.crypto.getRandomValues(new Uint8Array(12)); + const encryptedContent = await window.crypto.subtle.encrypt( + { + name: "AES-GCM", + iv: iv + }, + key, + enc.encode(content) + ); + const encryptedArray = new Uint8Array(encryptedContent); + const encryptedString = btoa(String.fromCharCode(...iv) + String.fromCharCode(...encryptedArray)); + return encryptedString; +} diff --git a/SharpbinV2.Server/wwwroot/js/navbar.js b/SharpbinV2.Server/wwwroot/js/navbar.js new file mode 100644 index 0000000..020d691 --- /dev/null +++ b/SharpbinV2.Server/wwwroot/js/navbar.js @@ -0,0 +1,9 @@ +function AddToDom() { + var nav = document.createElement("nav"); + nav.innerHTML = "Home | About | Contact"; + document.body.appendChild(nav); + console.log("Added nav to dom"); +} +document.addEventListener("DOMContentLoaded", function () { + AddToDom(); +}); \ No newline at end of file diff --git a/SharpbinV2.Server/wwwroot/js/paste.js b/SharpbinV2.Server/wwwroot/js/paste.js new file mode 100644 index 0000000..24d87b1 --- /dev/null +++ b/SharpbinV2.Server/wwwroot/js/paste.js @@ -0,0 +1,127 @@ +const visibility = [{ id: 0, name: "Public" }, { id: 1, name: "Unlisted" }, { id: 2, name: "Private" }]; + +document.addEventListener("DOMContentLoaded", async function () { + const id = window.location.pathname.split("/")[1]; + const content = await (await fetch(`/api/pastes/${id}`)).text(); + const info = await (await fetch(`/api/pastes/${id}/info`)).json(); + const paste = info.paste; + const blur = document.createElement("div"); + blur.id = "blur"; + blur.dataset.decrypted = "false"; + document.body.appendChild(blur); + const blur2 = document.getElementById("blur"); + + if (paste.visibility === 2) { + + const password = prompt("Enter the password"); + try { + const decrypted = await decryptAES(content, password); + blur2.dataset.decrypted = "true"; + addContent(decrypted, paste.syntax); + } catch (error) { + alert("Failed to decrypt, invalid password, or invalid data."); + } + + + } else { + blur2.dataset.decrypted = "true"; + addContent(content, paste.syntax); + } + document.title = `${paste.title} - Sharpbin`; + addInfo(paste); + +}); + +function addInfo(paste) { + document.getElementById("paste-title").innerText = paste.title; + document.getElementById("paste-date").innerText = convertUnixToLocal(paste.created); + document.getElementById("paste-syntax").innerText = paste.syntax === "none" ? "" : paste.syntax || ""; + document.getElementById("copy-button").addEventListener("click", function () { + navigator.clipboard.writeText(window.location.href); + }); + document.getElementById("download-button").addEventListener("click", function () { + if (paste.visibility === 2) { + const content = document.getElementById("paste-content").innerText; + const blob = new Blob([content], { type: "text/plain" }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = `${paste.title}.txt`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + } + else { + const blob = new Blob([document.getElementById("paste-content").innerText], { type: "text/plain" }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = `${paste.title}.txt`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + } + }); + document.getElementById("raw-button").addEventListener("click", function () { + window.location.href = `/raw/${paste.id}`; + }); + +} + +function addContent(content, syntax) { + if (syntax === "none" || syntax === "" || syntax === null) { + document.getElementById("paste-content").innerText = content; + } else { + var code = document.createElement("code"); + code.innerText = content; + var pre = document.getElementById("paste-content"); + pre.innerText = ""; + pre.appendChild(code); + pre.removeAttribute("id"); + code.id = "paste-content"; + code.classList.add("language-" + syntax); + hljs.highlightElement(code); + } +} + +async function decryptAES(content, password) { + const enc = new TextEncoder(); + const keyMaterial = await window.crypto.subtle.importKey( + "raw", + enc.encode(password), + { name: "PBKDF2" }, + false, + ["deriveKey"] + ); + const key = await window.crypto.subtle.deriveKey( + { + name: "PBKDF2", + salt: enc.encode("salt"), + iterations: 100000, + hash: "SHA-256" + }, + keyMaterial, + { name: "AES-GCM", length: 256 }, + false, + ["decrypt"] + ); + const rawData = atob(content); + const rawDataArray = Uint8Array.from(rawData, c => c.charCodeAt(0)); + const iv = rawDataArray.slice(0, 12); + const ciphertext = rawDataArray.slice(12); + const decrypted = await window.crypto.subtle.decrypt( + { + name: "AES-GCM", + iv: iv + }, + key, + ciphertext + ); + return new TextDecoder().decode(decrypted); +} + +function convertUnixToLocal(unix) { + return new Date(unix * 1000).toLocaleString(); +} \ No newline at end of file diff --git a/SharpbinV2.Server/wwwroot/paste.html b/SharpbinV2.Server/wwwroot/paste.html new file mode 100644 index 0000000..23a6829 --- /dev/null +++ b/SharpbinV2.Server/wwwroot/paste.html @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + +
+
+

Title

+
+

Syntax

+

Date

+
+
+
+
+ + + +
+
Content
+
+
+ + + + \ No newline at end of file