feat: paste compression & verification enforcement settings; enforce 2fa on admins setting; increase paste validation; anonymous uploads

fix: minor styling issue on main elements; resolve lint issue
refactor: remove 2FA badge on user pages; enhance paste creation flow; body background color always neutral-950; improve paste creation paste info (lines, cchars etc) for mobile
This commit is contained in:
2026-01-08 15:25:42 -05:00
parent fabef95159
commit 9f55aa1b22
16 changed files with 186 additions and 75 deletions
+8 -8
View File
@@ -1,16 +1,16 @@
export function formatBytes(bytes: number, decimals = 2): string {
if (bytes === 0) return '0 Bytes';
if (bytes === 0) return '0 Bytes';
const unit = 1024;
const units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const unit = 1024;
const units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const exponent = Math.floor(Math.log(bytes) / Math.log(unit));
const value = bytes / Math.pow(unit, exponent);
const exponent = Math.floor(Math.log(bytes) / Math.log(unit));
const value = bytes / Math.pow(unit, exponent);
const unitLabel = value === 1 && exponent === 0 ? 'Byte' : units[exponent];
const formattedValue = Number.isInteger(value) ? value : value.toFixed(decimals);
const unitLabel = value === 1 && exponent === 0 ? 'Byte' : units[exponent];
const formattedValue = Number.isInteger(value) ? value : value.toFixed(decimals);
return `${formattedValue} ${unitLabel}`;
return `${formattedValue} ${unitLabel}`;
}
export function formatNumber(num: number): string {
+1 -1
View File
@@ -38,7 +38,7 @@
<svelte:head>
<link rel="icon" href={favicon} />
{#if data.options?.cf_turnstile_site_key && (page.url.pathname === '/login' || page.url.pathname === '/register')}
{#if data.options?.cf_turnstile_site_key && (page.url.pathname === '/login' || page.url.pathname === '/register' || page.url.pathname === '/')}
<script
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=turnstileLoaded"
async
+5 -3
View File
@@ -2,9 +2,11 @@ import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ fetch, url }) => {
try {
const res = await fetch('/api/paste/create/options');
const options = await res.json();
return { options, url: url.href };
const optionsRes = await fetch('/api/paste/create/options');
const authInfo = await fetch('/api/auth/info');
const options = await optionsRes.json();
const auth = await authInfo.json();
return { options, auth, url: url.href };
} catch {
return { options: null, url: url.href };
}
+112 -34
View File
@@ -3,10 +3,12 @@
import { displayNames } from '$lib/consts';
import { user } from '$lib/stores/user';
import { getToken } from '$lib/utils/auth';
import { onMount } from 'svelte';
import { fly } from 'svelte/transition';
import { encryptAES } from '$lib/utils/encryption';
import { formatBytes } from '$lib/utils/misc';
import { formatBytes, formatNumber } from '$lib/utils/misc';
import Dropdown from '$lib/components/Dropdown.svelte';
import { SvelteURLSearchParams } from 'svelte/reactivity';
export let data: PageData;
@@ -17,6 +19,32 @@
let expiresIn: number = 0;
let selectedVisibility = data.options?.visibilities?.[0]?.value;
let password = '';
let anonymousUpload = false;
onMount(() => {
const render = () => {
if (
window.turnstile &&
data.options?.requiresVerification &&
data.auth?.cf_turnstile_site_key
) {
window.turnstile.render('.cf-turnstile', {
sitekey: data.auth.cf_turnstile_site_key,
theme: 'dark'
});
}
};
if (window.turnstile) {
render();
} else {
window.addEventListener('turnstile:loaded', render, { once: true });
}
return () => {
window.removeEventListener('turnstile:loaded', render);
};
});
const syntaxOptions =
data.options?.syntaxes?.map((lang: string) => ({
@@ -48,12 +76,24 @@
async function handleSubmit(event: Event) {
event.preventDefault();
const params = new URLSearchParams({
const params = new SvelteURLSearchParams({
title: title.trim(),
syntax: selectedSyntax,
visibility: selectedVisibility.toString(),
expiresAt: expiresIn > 0 ? (Date.now() + Number(expiresIn)).toString() : '0'
});
if (
data.options?.requiresVerification &&
data.auth?.cf_turnstile_site_key &&
window.turnstile
) {
const token = window.turnstile.getResponse();
if (token) {
params.append('token', token);
}
}
let body = content;
if (selectedVisibility === 2) {
body = await encryptAES(content, password);
@@ -64,7 +104,7 @@
headers: { 'Content-Type': 'text/plain' },
body
};
if ($user) {
if ($user && !anonymousUpload) {
const token = getToken();
if (token) {
options.headers = {
@@ -83,10 +123,24 @@
}
window.location.href = `/${result.id}`;
} else {
if (window.turnstile) {
window.turnstile.reset();
}
if (response.status === 403) {
error = 'You are banned from creating new pastes.';
} else {
error = 'Failed to create paste. Please try again.';
const resData = await response.json();
if (resData.errors) {
const messages = Object.values(resData.errors).flat();
error = messages.join('\n');
} else {
if (resData.message === 'Verification failed.') {
if (window.turnstile) {
window.turnstile.reset();
}
}
error = resData.message || 'Registration failed. Please try again.';
}
}
setInterval(() => {
error = '';
@@ -105,7 +159,7 @@
</svelte:head>
<main
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center bg-neutral-950 pt-5 text-white"
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div class="w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-4xl font-bold">Create a Paste</h1>
@@ -138,51 +192,75 @@
}}
></textarea>
<div
class="mb-4 flex items-center h-8 justify-between rounded-b border border-neutral-700 bg-neutral-800 p-1 pl-2 pr-2 text-sm text-neutral-400 monospace"
class="monospace mb-4 flex h-12 items-center justify-between rounded-b border border-neutral-700 bg-neutral-800 p-1 pr-2 pl-2 text-sm text-neutral-400 md:h-8"
>
<div>
{content.split('\n').length} line{content.split('\n').length !== 1 ? 's' : ''}, {content.length}
character{content.length !== 1 ? 's' : ''}
<div class="flex flex-col md:flex-row md:gap-2">
<span>
{content.split('\n').length} line{content.split('\n').length !== 1 ? 's' : ''}
</span>
<span class="hidden text-neutral-600 md:block">•</span>
<span>{formatNumber(content.length)} char{content.length !== 1 ? 's' : ''}</span>
</div>
<div class="flex flex-col text-center md:flex-row md:gap-2">
<span class="border-b border-neutral-600 md:border-0">
{formatBytes(new TextEncoder().encode(content).length)}
</span>
<span class="hidden md:block">/</span>
{formatBytes(data.options?.maxPasteSize ?? 0)}
</div>
{#if data.options?.maxPasteSize}
{formatBytes(new TextEncoder().encode(content).length)} / {formatBytes(
data.options.maxPasteSize
)}
{:else}
{formatBytes(new TextEncoder().encode(content).length)}
{/if}
</div>
</div>
<Dropdown
options={syntaxOptions}
bind:value={selectedSyntax}
placeholder="Select syntax..."
searchable={true}
/>
<Dropdown
options={expiresOptions}
bind:value={expiresIn}
placeholder="Select expiration..."
/>
<Dropdown
options={visibilityOptions}
bind:value={selectedVisibility}
placeholder="Select visibility..."
/>
<div class="grid grid-cols-1 md:grid-cols-3 md:gap-2">
<Dropdown
options={syntaxOptions}
bind:value={selectedSyntax}
placeholder="Select syntax..."
searchable={true}
/>
<Dropdown
options={expiresOptions}
bind:value={expiresIn}
placeholder="Select expiration..."
/>
<Dropdown
options={visibilityOptions}
bind:value={selectedVisibility}
placeholder="Select visibility..."
/>
</div>
{#if selectedVisibility === 2}
<input
type="password"
placeholder="Password for private paste"
class="mb-4 w-full rounded border border-neutral-700 bg-neutral-800 p-2"
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2"
spellcheck="false"
autocomplete="off"
bind:value={password}
/>
{/if}
{#if $user}
<label
class="flex w-full items-center gap-2 rounded border border-neutral-700 bg-neutral-800 p-2"
>
<input
type="checkbox"
bind:checked={anonymousUpload}
class="h-4 w-4 rounded border-neutral-600 bg-neutral-700 text-neutral-500"
/>
<span>Upload anonymously</span>
</label>
{/if}
{#if data.options?.requiresVerification && data.auth?.cf_turnstile_site_key}
<div
class="mt-2 flex w-auto items-center justify-center rounded border border-neutral-700 bg-neutral-800 p-2 pb-1"
>
<div class="cf-turnstile" data-sitekey={data.auth.cf_turnstile_site_key}></div>
</div>
{/if}
<button
type="submit"
disabled={$user?.roles && $user.roles.includes(403)}
class="w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-950/50 disabled:text-neutral-400"
class="mt-2 w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-950/50 disabled:text-neutral-400"
>Create Paste</button
>
{#if error}
@@ -318,7 +318,7 @@
</svelte:head>
<main
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center bg-neutral-950 pt-5 pb-5 text-white"
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div
class="max-h-[90vh] w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-4"
+1 -1
View File
@@ -6,7 +6,7 @@
}
body {
background-color: black;
background-color: var(--color-neutral-950);
}
body,
@@ -88,7 +88,7 @@
</script>
<main
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center bg-neutral-950 text-white"
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-3xl font-bold">Login</h1>
@@ -113,7 +113,7 @@
</script>
<main
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center bg-neutral-950 text-white"
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-3xl font-bold">Register</h1>
@@ -204,7 +204,7 @@
</svelte:head>
<main
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center bg-neutral-950 pt-5 text-white"
class="flex min-h-[calc(100vh-60px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div class="w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="flex items-center justify-center gap-4 text-center text-4xl font-bold">
@@ -259,12 +259,6 @@
{data.user?.uid}
</span>
</div>
{#if isOwner}
<div class="flex shrink-0 items-center">
<ShieldUser class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">2FA {totpEnabled ? 'enabled' : 'disabled'}</span>
</div>
{/if}
{#if isOwner && data.user?.lastLogin}
<div class="flex shrink-0 items-center">
<Clock class="mr-2 h-6 w-6 text-neutral-400" />
@@ -433,9 +427,6 @@
show={showTotpModal}
mode="totpSetup"
title="Two-Factor Authentication"
message={totpEnabled
? 'Two-factor authentication is currently enabled.'
: 'Enable two-factor authentication with an authenticator app.'}
error={modalError}
totpActive={totpEnabled}
onConfirm={(value) => handleTotpConfirm(value)}
@@ -5,23 +5,25 @@ using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs.Paste;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services;
using SharpbinV3.Server.Services.Verification;
using SharpbinV3.Server.Settings;
namespace SharpbinV3.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PasteController(PasteService pasteService, UserService userService, AuthService authService, IOptions<PasteSettings> options) : ControllerBase
public class PasteController(PasteService pasteService, VerificationService verificationService, AuthService authService, IOptions<PasteSettings> options, IOptions<AuthSettings> authSettings) : ControllerBase
{
private readonly PasteService _pasteService = pasteService;
private readonly UserService _userService = userService;
private readonly VerificationService _verificationService = verificationService;
private readonly AuthService _authService = authService;
private readonly PasteSettings _pasteSettings = options.Value;
private readonly AuthSettings _authSettings = authSettings.Value;
[HttpPost]
[Route("create")]
[Authorize(Policy = "NotBanned")]
public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0)
public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0, string? token = null)
{
if (!await _pasteService.ValidateExpiresAt(expiresAt))
return BadRequest(new { message = "Invalid expiration time." });
@@ -33,10 +35,20 @@ namespace SharpbinV3.Server.Controllers
return BadRequest(new { message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." });
string content = await new StreamReader(Request.Body).ReadToEndAsync();
if (content.Length == 0)
return BadRequest(new { message = "Paste content cannot be empty." });
if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes)
return BadRequest(new { message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." });
if (_pasteSettings.RequiresVerfication && !await _verificationService.VerifyAsync(new VerificationContext
{
Token = token,
Ip = HttpContext.GetRequestIP()
}))
return BadRequest(new { message = "Verification failed." });
var user = await _authService.GetUserFromHttpContext(HttpContext);
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt);
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
return Ok(new
{
paste.ID,
@@ -102,11 +114,16 @@ namespace SharpbinV3.Server.Controllers
if (content == null || id == null) return NotFound();
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
var user = HttpContext.GetJwtUser();
if (user == null) return Forbid();
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
return Forbid();
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
return Forbid();
bool result = await _pasteService.EditText(paste, content);
if (!result) return NotFound();
return Ok(new { message = "Paste edited successfully." });
@@ -119,11 +136,16 @@ namespace SharpbinV3.Server.Controllers
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
var user = HttpContext.GetJwtUser();
if (user == null) return Forbid();
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
return Forbid();
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
return Forbid();
if (request.Title != null)
paste.Title = request.Title;
if (request.Syntax != null)
@@ -168,11 +190,16 @@ namespace SharpbinV3.Server.Controllers
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
var user = HttpContext.GetJwtUser();
if (user == null) return Forbid();
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
return Forbid();
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
return Forbid();
bool result = await _pasteService.Delete(paste);
if (!result) return NotFound();
return Ok(new { message = "Paste deleted successfully." });
@@ -192,7 +219,8 @@ namespace SharpbinV3.Server.Controllers
new { value = 2, displayName = "Private" }
},
maxTitleLength = _pasteSettings.MaxTitleLength,
maxPasteSize = _pasteSettings.MaxPasteSizeInBytes
maxPasteSize = _pasteSettings.MaxPasteSizeInBytes,
requiresVerification = _pasteSettings.RequiresVerfication
};
return Ok(options);
}
@@ -1,6 +1,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
@@ -9,18 +10,19 @@ using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services;
using SharpbinV3.Server.Services.Verification;
using SharpbinV3.Server.Services.Verification.Providers;
using SharpbinV3.Server.Settings;
namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController(UserService userService, AppDbContext db, AuthService authService, TotpVerificationProvider totp, VerificationService verificationService) : ControllerBase
public class UserController(UserService userService, AppDbContext db, TotpVerificationProvider totp, VerificationService verificationService, IOptions<AuthSettings> authSettings) : ControllerBase
{
private readonly UserService _userService = userService;
private readonly AppDbContext _db = db;
private readonly AuthService _authService = authService;
private readonly TotpVerificationProvider _totp = totp;
private readonly VerificationService _verificationService = verificationService;
private readonly AuthSettings _authSettings = authSettings.Value;
[HttpGet("{username}")]
public async Task<IActionResult> GetByUsername(string username, [FromQuery] int page = 1)
@@ -63,6 +65,8 @@ namespace SharpbinV3.Server.Controllers
return Forbid();
if (user.Roles.Contains(255) && !jwtUser.Roles.Contains(255))
return Forbid();
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
return Forbid();
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
if (jwtUser.Roles.Any(r => r == 255) || user.UUID == jwtUser.UUID) // only admins or self
@@ -100,6 +104,8 @@ namespace SharpbinV3.Server.Controllers
if (user == null) return Forbid();
if (!jwtUser.Roles.Any(r => r == 255) && user.UUID != jwtUser.UUID)
return Forbid();
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
return Forbid();
if (jwtUser.TotpEnabled)
{
+8 -5
View File
@@ -13,9 +13,12 @@ namespace SharpbinV3.Server.Services
private readonly ICompressionService _cs = cs;
private readonly PasteSettings _pasteSettings = options.Value;
public async Task<Paste> Create(User? author, string content, string title, string syntax, int visibility, long expiresAt)
public async Task<Paste> Create(User? author, string content, string title, string syntax, int visibility, long expiresAt, bool shouldCompress)
{
var compressedData = _cs.Compress(content);
var data = Encoding.UTF8.GetBytes(content);
if (shouldCompress)
data = _cs.Compress(content);
var paste = new Paste
{
UUID = Guid.CreateVersion7(),
@@ -23,10 +26,10 @@ namespace SharpbinV3.Server.Services
Title = title,
AuthorUUID = author?.UUID,
User = author,
Content = compressedData,
Size = compressedData.Length,
Content = data,
Size = data.Length,
TrueSize = Encoding.UTF8.GetByteCount(content),
IsCompressed = compressedData.Length < Encoding.UTF8.GetByteCount(content),
IsCompressed = data.Length < Encoding.UTF8.GetByteCount(content),
Syntax = syntax,
Visibility = visibility,
ExpiresAt = expiresAt,
@@ -6,5 +6,6 @@
public string CF_Turnstile_SecretKey { get; set; } = string.Empty;
public bool Registration_Enabled { get; set; } = true;
public bool First_User_Admin { get; set; } = true;
public bool Admins_Require_2FA { get; set; } = true;
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
{
public class JWTSettings
{
public string Secret { get; set; } = Utilities.GenerateRandomString(64);
public string Secret { get; set; } = string.Empty;
public string Issuer { get; set; } = "SharpbinApi";
public string Audience { get; set; } = "SharpbinClient";
}
@@ -5,5 +5,7 @@
public string[] ValidSyntaxLanguages { get; set; } = [];
public int MaxTitleLength { get; set; } = 500;
public int MaxPasteSizeInBytes { get; set; } = 1_048_576; // 1 MB
public bool EnablePasteCompression { get; set; } = true;
public bool RequiresVerfication { get; set; } = true;
}
}