feat: paste creation; paste viewing; more langs supported; jwt settings class; paste settings class; data validation on paste metadata modification

This commit is contained in:
2025-12-28 08:34:53 -05:00
parent adad139081
commit b9b14a3d5a
21 changed files with 1203 additions and 77 deletions
+8
View File
@@ -3,6 +3,14 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap"
rel="stylesheet"
/>
<link
href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500&display=swap"
rel="stylesheet"
/>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
+74
View File
@@ -0,0 +1,74 @@
export const displayNames: Record<string, string> = {
plaintext: 'Plain Text',
abap: 'ABAP',
'actionscript-3': 'ActionScript 3',
apl: 'APL',
applescript: 'AppleScript',
ara: 'ARA',
awk: 'AWK',
bibtex: 'BibTeX',
cmake: 'CMake',
cobol: 'COBOL',
codeql: 'CodeQL',
coffee: 'CoffeeScript',
cpp: 'C++',
csharp: 'C#',
css: 'CSS',
cue: 'CUE',
'dream-maker': 'Dream Maker',
erb: 'ERB',
fsharp: 'F#',
gdresource: 'Godot Resource',
gdscript: 'GDScript',
gdshader: 'Godot Shader',
'git-commit': 'Git Commit',
'git-rebase': 'Git Rebase',
glsl: 'GLSL',
graphql: 'GraphQL',
hcl: 'HCL',
hjson: 'HJSON',
hlsl: 'HLSL',
html: 'HTML',
ini: 'INI',
javascript: 'JavaScript',
json: 'JSON',
json5: 'JSON5',
jsonc: 'JSONC',
jssm: 'JSSM',
jsx: 'JSX',
latex: 'LaTeX',
matlab: 'MATLAB',
mdx: 'MDX',
'objective-c': 'Objective-C',
'objective-cpp': 'Objective-C++',
ocaml: 'OCaml',
php: 'PHP',
plsql: 'PL/SQL',
postcss: 'PostCSS',
powerquery: 'Power Query',
purescript: 'PureScript',
riscv: 'RISC-V',
rst: 'reStructuredText',
sas: 'SAS',
scss: 'SCSS',
shaderlab: 'ShaderLab',
sparql: 'SPARQL',
sql: 'SQL',
'ssh-config': 'SSH Config',
'system-verilog': 'SystemVerilog',
tasl: 'TASL',
tex: 'TeX',
toml: 'TOML',
tsx: 'TSX',
typescript: 'TypeScript',
vb: 'VB',
vhdl: 'VHDL',
viml: 'VimL',
wasm: 'WebAssembly',
xml: 'XML',
xsl: 'XSL',
yaml: 'YAML',
zenscript: 'ZenScript'
};
// only include langs that need special display names
// e.g. cpp -> C++ or toml -> TOML, langs like java are automatically capitalized
+23
View File
@@ -0,0 +1,23 @@
import { createHighlighter } from 'shiki';
import type { Highlighter } from 'shiki';
let highlighterPromise: Promise<Highlighter> | null = null;
async function loadHighlighter() {
const res = await fetch('http://localhost:5050/api/paste/create/options');
if (!res.ok) throw new Error('Failed to fetch paste options');
const data = await res.json();
return createHighlighter({
themes: ['github-dark', 'github-light'],
langs: data.syntaxes
});
}
export function getShiki() {
if (!highlighterPromise) {
highlighterPromise = loadHighlighter();
}
return highlighterPromise;
}
@@ -0,0 +1,7 @@
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ fetch }) => {
const res = await fetch('/api/paste/create/options');
const options = await res.json();
return { options };
};
+142 -2
View File
@@ -1,2 +1,142 @@
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://svelte.dev/docs/kit">svelte.dev/docs/kit</a> to read the documentation</p>
<script lang="ts">
import type { PageData } from './$types';
import { displayNames } from '$lib/consts';
export let data: PageData;
let title = '';
let content = '';
let selectedSyntax = data.options.syntaxes[0];
let selectedVisibility = data.options.visibilities[0].value;
let password = '';
async function handleSubmit(event: Event) {
event.preventDefault();
const params = new URLSearchParams({
title: title.trim(),
syntax: selectedSyntax,
visibility: selectedVisibility.toString()
});
let body = content;
if (selectedVisibility === 2) {
body = await encryptAES(content, password);
}
const url = `/api/paste/create?${params.toString()}`;
const options: RequestInit = {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body
};
const response = await fetch(url, options);
if (response.ok) {
const result = await response.json();
window.location.href = `/${result.id}`;
} else {
alert('Failed to create paste. Please try again.');
}
}
async function encryptAES(content: string, password: string): Promise<string> {
const enc = new TextEncoder();
const keyMaterial = await window.crypto.subtle.importKey(
'raw',
enc.encode(password),
{ name: 'PBKDF2' },
false,
['deriveBits', 'deriveKey']
);
const salt = window.crypto.getRandomValues(new Uint8Array(16));
const key = await window.crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: 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 combined = new Uint8Array(salt.byteLength + iv.byteLength + encryptedContent.byteLength);
combined.set(salt, 0);
combined.set(iv, salt.byteLength);
combined.set(new Uint8Array(encryptedContent), salt.byteLength + iv.byteLength);
const result = {
version: 1,
kdf: 'PBKDF2',
iterations: 100000,
hash: 'SHA-256',
algorithm: 'AES-GCM',
data: btoa(String.fromCharCode(...combined))
};
return JSON.stringify(result);
}
</script>
<main
class="flex min-h-screen w-full flex-col items-center justify-center bg-neutral-950 text-white"
>
<div class="rounded border-2 border-neutral-800 bg-neutral-900 p-6 w-full max-w-5xl">
<h1 class="mb-6 text-center text-4xl font-bold">Create a Paste</h1>
<form class="mt-4" on:submit|preventDefault={handleSubmit}>
<input
type="text"
placeholder="Title (optional)"
class="mb-4 w-full rounded border border-neutral-700 bg-neutral-800 p-2"
spellcheck="false"
autocomplete="off"
bind:value={title}
/>
<textarea
placeholder="Your paste content here..."
class="mb-4 h-64 max-h-[50vh] min-h-10 w-full resize-y rounded border border-neutral-700 bg-neutral-800 p-2"
spellcheck="false"
autocomplete="off"
bind:value={content}
></textarea>
<select
class="mb-4 w-full rounded border border-neutral-700 bg-neutral-800 p-2"
bind:value={selectedSyntax}
>
{#each data.options.syntaxes as lang (lang)}
<option value={lang}
>{displayNames[lang] ?? lang.charAt(0).toUpperCase() + lang.slice(1)}</option
>
{/each}
</select>
<select
class="mb-4 w-full rounded border border-neutral-700 bg-neutral-800 p-2"
bind:value={selectedVisibility}
>
{#each data.options.visibilities as visibility (visibility.value)}
<option value={visibility.value}>{visibility.displayName}</option>
{/each}
</select>
{#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"
spellcheck="false"
autocomplete="off"
bind:value={password}
/>
{/if}
<button
type="submit"
class="w-full rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900"
>Create Paste</button
>
</form>
</div>
</main>
@@ -0,0 +1,30 @@
import type { PageServerLoad } from './$types';
import { getShiki } from '$lib/shiki';
export const load: PageServerLoad = async ({ params, fetch }) => {
const { id } = params;
const paste = await fetch(`/api/paste/${id}`);
if (paste.status === 404) {
return {
status: 404,
error: { message: 'Paste not found' }
};
}
const pasteData = await paste.json();
const pasteContent = await fetch(`/api/paste/raw/${id}`);
const pasteOptions = await fetch('/api/paste/create/options');
const options = await pasteOptions.json();
const content = await pasteContent.text();
let highlighted = '';
if (pasteData && content) {
const shiki = await getShiki();
highlighted = shiki.codeToHtml(content, {
lang: pasteData.syntax || 'plaintext',
theme: 'github-dark'
});
}
return { paste: pasteData, content, options, highlighted };
};
@@ -0,0 +1,83 @@
<script lang="ts">
import type { PageData } from './$types';
export let data: PageData;
function addLineNumbers(html: string): string {
const match = html.match(/<pre.*?>[\s\S]*?<code.*?>([\s\S]*?)<\/code><\/pre>/);
if (!match) return html;
const code = match[1];
const lines = code.split(/\n/);
const digits = String(lines.length).length;
const numbered = lines
.map(
(line, i) =>
`<div class="code-row"><span class="line-number" style="width:${digits}ch">${i + 1}</span><span class="code-line">${line}</span></div>`
)
.join('');
return html.replace(code, numbered);
}
</script>
<main
class="flex min-h-screen w-full flex-col items-center justify-center bg-neutral-950 text-white"
>
{#if data.paste}
<div class="max-h-[80vh] rounded border-2 border-neutral-800 bg-neutral-900 p-4 w-full max-w-5xl">
<h1 class="mb-4 text-center text-4xl font-bold">{data.paste.title || 'Untitled Paste'}</h1>
<div
class="codeblock-with-lines max-w-full overflow-x-auto overflow-y-auto"
style="max-width:100vw; min-width:0;"
>
{@html addLineNumbers(data.highlighted ?? '')}
</div>
</div>
{:else}
<h1 class="text-2xl font-bold">Paste not found</h1>
<h2 class="mt-2 text-lg">The paste you are looking for does not exist.</h2>
{/if}
<style>
.codeblock-with-lines {
max-width: 100vw;
min-width: 0;
overflow-x: auto;
overflow-y: auto;
}
.codeblock-with-lines pre {
display: block;
position: relative;
padding: 1em;
margin: 0;
background: none;
border-radius: 0.25em;
background-color: var(--color-neutral-800) !important;
overflow-x: auto;
min-width: max-content;
max-height: 60vh;
}
.code-row {
display: flex;
align-items: flex-start;
min-width: max-content;
padding: 0.1em 0;
}
.line-number {
flex-shrink: 0;
text-align: right;
color: #888;
user-select: none;
margin-right: 1em;
font-variant-numeric: tabular-nums;
padding-right: 0.5em;
padding-left: 0.25em;
background: none;
}
.code-line {
display: block;
white-space: pre;
word-break: normal;
overflow-wrap: normal;
padding-left: 0.25em;
min-width: 0;
}
</style>
</main>
+28
View File
@@ -1 +1,29 @@
@import 'tailwindcss';
* {
box-sizing: border-box;
}
body,
h1,
h2,
h3,
p {
font-family: 'IBM Plex Sans', sans-serif;
}
pre,
code,
textarea,
option,
select {
font-family: 'Fira Code', monospace;
}
input[type='text'],
input[type='email'],
input[type='password'],
textarea,
select {
outline: none;
}