Add frontend files, improve backend.

This commit is contained in:
whoswhip
2025-01-17 21:17:37 -05:00
parent d0cf36108f
commit 01a637f5dd
13 changed files with 699 additions and 11 deletions
+121 -4
View File
@@ -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
{
+4 -7
View File
@@ -9,13 +9,6 @@
<SignAssembly>False</SignAssembly>
</PropertyGroup>
<ItemGroup>
<Compile Remove="wwwroot\**" />
<Content Remove="wwwroot\**" />
<EmbeddedResource Remove="wwwroot\**" />
<None Remove="wwwroot\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.0" />
@@ -24,4 +17,8 @@
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
</Project>
View File
+75
View File
@@ -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;
}
+130
View File
@@ -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;
}
+23
View File
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Error! - Sharpbin</title>
<link rel="preload" href="css/style.css" as="style">
<link rel="stylesheet" href="css/style.css">
<link rel="preload" href="js/error.js" as="script">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Noto+Sans+Mono:wght@100..900&display=swap"
rel="stylesheet">
</head>
<body>
<div class="main-container">
<h1 id="error-header">Oops! We've ran into an error.</h1>
<h3 id="error-message"></p>
</div>
</body>
<script src="js/error.js"></script>
</html>
+58
View File
@@ -0,0 +1,58 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sharpbin</title>
<link rel="preload" href="css/style.css" as="style">
<link rel="stylesheet" href="css/style.css">
<link rel="preload" href="js/index.js" as="script">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Noto+Sans+Mono:wght@100..900&display=swap"
rel="stylesheet">
</head>
<body>
<div class="main-container">
<form class="create-form" id="create-form">
<input type="text" name="title" id="title" placeholder="Title">
<textarea name="content" id="content" placeholder="Content"></textarea>
<label style="margin-bottom: -2.3rem; margin-top: 1.1rem; z-index: 2; align-self: flex-start; margin-left: 1rem; pointer-events: none;">Syntax Highlighting -</label>
<select name="syntax" id="syntax">
<option value="none">None</option>
<option value="bash">Bash</option>
<option value="c">C</option>
<option value="cpp">C++</option>
<option value="csharp">C#</option>
<option value="css">CSS</option>
<option value="html">HTML</option>
<option value="java">Java</option>
<option value="javascript">JavaScript</option>
<option value="json">JSON</option>
<option value="lua">Lua</option>
<option value="markdown">Markdown</option>
<option value="php">PHP</option>
<option value="python">Python</option>
<option value="ruby">Ruby</option>
<option value="rust">Rust</option>
<option value="sql">SQL</option>
<option value="swift">Swift</option>
<option value="typescript">TypeScript</option>
<option value="xml">XML</option>
</select>
<select name="visibility" id="visibility" onchange="changeVisibility()">
<option value="0">Public</option>
<option value="1">Unlisted</option>
<option value="2">Private</option>
</select>
<input type="text" name="password" id="password" placeholder="Password" style="display: none;">
<button type="submit">Create Paste</button>
</form>
</div>
</body>
<script src="js/index.js"></script>
</html>
+22
View File
@@ -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;
}
});
+79
View File
@@ -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;
}
+9
View File
@@ -0,0 +1,9 @@
function AddToDom() {
var nav = document.createElement("nav");
nav.innerHTML = "<a href='index.html'>Home</a> | <a href='about.html'>About</a> | <a href='contact.html'>Contact</a>";
document.body.appendChild(nav);
console.log("Added nav to dom");
}
document.addEventListener("DOMContentLoaded", function () {
AddToDom();
});
+127
View File
@@ -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();
}
+42
View File
@@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preload" href="css/style.css" as="style">
<link rel="preload" href="css/paste.css" as="style">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/paste.css">
<link rel="preload" href="js/paste.js" as="script">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Noto+Sans+Mono:wght@100..900&display=swap"
rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
</head>
<body>
<div class="main-container">
<div class="paste-header">
<h1 id="paste-title">Title</h1>
<div class="paste-information">
<p id="paste-syntax">Syntax</p>
<p id="paste-date">Date</p>
</div>
</div>
<div class="paste-content">
<div class="paste-actions">
<button id="copy-button">Copy</button>
<button id="download-button">Download</button>
<button id="raw-button">Raw</button>
</div>
<pre id="paste-content">Content</pre>
</div>
</div>
</body>
<script src="js/paste.js"></script>
</html>