feat: reports; improved+simplifed modals; extractError funcction;

refactor: change jwt claims to lowercase; use response dtos for sensitive data
fix: nullify user on token clears; change appsettings.dev View_Internal_API_Key
This commit is contained in:
2026-01-14 19:41:52 -05:00
parent 1da88dba4e
commit 67447d51ae
39 changed files with 2291 additions and 454 deletions
@@ -1,34 +1,97 @@
import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { getServerToken } from '$lib/utils/auth';
import type { User } from '$lib/types/user';
import type { Paste } from '$lib/types/paste';
import type { Pagination } from '$lib/types/pagination';
import type { Report, ReportListResponse } from '$lib/types/report';
const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050';
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
export const load: PageServerLoad = async ({ params, fetch, cookies, url }) => {
const { username } = params;
const token = getServerToken(cookies);
const res = await fetch(`${apiUrl}/api/user/${username}`, {
headers: {
Authorization: token ? `Bearer ${token}` : ''
function decodeJwtRoles(token?: string | null): number[] {
try {
if (!token) return [];
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
const roles = payload?.role;
if (Array.isArray(roles)) {
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
}
return [];
} catch {
return [];
}
}
function decodeJwtUuid(token?: string | null): string | null {
try {
if (!token) return null;
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
const uuid = payload?.uuid;
return typeof uuid === 'string' ? uuid : null;
} catch {
return null;
}
}
export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent }) => {
const token = getServerToken(cookies);
const { username } = params;
const { options } = await parent();
const jwtUuid = decodeJwtUuid(token);
const res = await fetch(`${API_URL}/api/user/${username}`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined
});
if (res.status === 500) {
return {
status: 500,
error: { message: 'Internal server error' }
if (!res.ok) {
const { message } = await res.json().catch(() => ({}));
throw error(res.status, message ?? 'Request failed');
}
const { user, pastes, pagination, reports, reportsPagination } = (await res.json()) as {
user: User;
pastes: Paste[];
pagination: Pagination;
reports?: Report[];
reportsPagination?: Pagination;
};
const isOwner = jwtUuid ? user.uuid === jwtUuid : false;
let reportsTarget: ReportListResponse | null = null;
let reportsSubmitted: ReportListResponse | null = null;
const roles = token ? decodeJwtRoles(token) : [];
const canModerate = roles.includes(255) || roles.includes(1);
if (isOwner && reports && reportsPagination) {
reportsSubmitted = {
reports,
pagination: reportsPagination
};
}
const json = await res.json();
if (res.status !== 200) {
return {
status: res.status,
error: { message: json.message || 'An error occurred' }
};
if (token && canModerate && (!reportsSubmitted || !isOwner)) {
const submittedRes = await fetch(`${API_URL}/api/user/${user.uuid}/reports/submitted`, {
headers: { Authorization: `Bearer ${token}` }
});
if (submittedRes.ok) reportsSubmitted = await submittedRes.json();
}
const user = json as User;
return { user, url: url.href };
if (token && !isOwner) {
if (canModerate) {
const r = await fetch(`${API_URL}/api/user/${user.uuid}/reports`, {
headers: { Authorization: `Bearer ${token}` }
});
if (r.ok) reportsTarget = await r.json();
}
}
return {
user,
pastes: { pastes, pagination },
reportsTarget,
reportsSubmitted,
url: url.href,
authOptions: options
};
};
@@ -1,5 +1,6 @@
<script lang="ts">
import { resolve } from '$app/paths';
import { goto } from '$app/navigation';
import type { PageData } from './$types';
import type { Pagination } from '$lib/types/pagination';
import {
@@ -12,44 +13,40 @@
Pencil,
Trash2,
Clock,
Hash
Hash,
Flag
} from '@lucide/svelte';
import { extractDateFromUUIDv7, tooltip, dateToRelativeString } from '$lib/utils/misc';
import { roles } from '$lib/consts';
import { getToken } from '$lib/utils/auth';
import { needsAdminTotp } from '$lib/utils/totp';
import Modal from '$lib/components/Modal.svelte';
import { openModal } from '$lib/stores/modal';
import { user } from '$lib/stores/user';
import { onMount } from 'svelte';
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
export let data: PageData;
let currentPage = data.user?.pagination?.page ?? 1;
let pagination: Pagination = data.user?.pagination ?? {
let currentPage = data.pastes?.pagination?.page ?? 1;
let pagination: Pagination = data.pastes?.pagination ?? {
page: 1,
pageSize: 50,
totalCount: 0,
totalPages: 1
};
let pastes = data.user?.pastes ?? [];
let pastes = data.pastes?.pastes ?? [];
let loading = false;
let isOwner = false;
let showEditModal = false;
let showDeleteModal = false;
let showRoleModal = false;
let showTotpModal = false;
let showRoleTotpModal = false;
let showDeleteTotpModal = false;
let modalError = '';
let totpEnabled = false;
let pendingRoles: number[] | null = null;
let roleTotpCode = '';
let deleteTotpCode = '';
let now = new Date();
let interval: ReturnType<typeof setInterval> | null = null;
$: isOwner = data.user && $user ? data.user?.uuid === $user.uuid : false;
$: totpEnabled = Boolean($user?.totpEnabled);
$: reportsSubmitted = data.reportsSubmitted;
$: reportsTarget = data.reportsTarget;
const roleOptions = [
{ label: 'Member', value: 0 },
@@ -82,11 +79,22 @@
const token = getToken();
const currentRoles = data.user?.roles ?? [];
const nextRoles = selectedRoles ?? currentRoles;
if (needsAdminTotp(totpEnabled, currentRoles, nextRoles) && !roleTotpCode) {
pendingRoles = nextRoles;
showRoleTotpModal = true;
loading = false;
return;
let totpcode = '';
if (needsAdminTotp(totpEnabled, currentRoles, nextRoles)) {
totpcode = String(
await openModal<string>({
mode: 'totp',
title: 'Admin role requires TOTP',
placeholder: 'Enter 6-digit code',
inputType: 'text',
confirmButtonText: 'Continue',
cancelValue: ''
})
).trim();
if (!totpcode) {
loading = false;
return;
}
}
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
method: 'PATCH',
@@ -97,61 +105,70 @@
body: JSON.stringify({
...(displayName !== undefined ? { displayName: displayName.trim() } : {}),
...(selectedRoles !== undefined ? { roles: selectedRoles } : {}),
...(roleTotpCode ? { totpcode: roleTotpCode } : {})
...(totpcode ? { totpcode } : {})
})
});
loading = false;
if (!res.ok) {
const err = await res.json();
modalError = err.message || 'Failed to update display name';
await openModal({
mode: 'confirm',
title: 'Error',
message: modalError,
confirmButtonText: 'OK',
cancelValue: true
});
return;
}
showEditModal = false;
showRoleModal = false;
data.user!.displayName = displayName || data.user!.displayName;
if (selectedRoles !== undefined) {
data.user!.roles = selectedRoles;
}
roleTotpCode = '';
showRoleTotpModal = false;
pendingRoles = null;
modalError = '';
}
function handleRoleTotpConfirm(value: unknown) {
if (typeof value === 'string') {
roleTotpCode = value.trim();
}
showRoleTotpModal = false;
if (!roleTotpCode) return;
handleUserUpdate(undefined, pendingRoles ?? data.user?.roles ?? []);
}
async function handleDeleteAccount() {
loading = true;
modalError = '';
const token = getToken();
if (totpEnabled && !deleteTotpCode) {
showDeleteTotpModal = true;
loading = false;
return;
let totpcode = '';
if (totpEnabled) {
totpcode = String(
await openModal<string>({
mode: 'totp',
title: 'Enter TOTP to delete',
placeholder: 'Enter 6-digit code',
inputType: 'text',
confirmButtonText: 'Delete Account',
cancelValue: ''
})
).trim();
if (!totpcode) {
loading = false;
return;
}
}
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${token}`
},
body: totpEnabled && deleteTotpCode ? JSON.stringify({ totpcode: deleteTotpCode }) : undefined
body: totpEnabled && totpcode ? JSON.stringify({ totpcode }) : undefined
});
loading = false;
if (!res.ok) {
const err = await res.json();
modalError = err.message || 'Failed to delete account';
await openModal({
mode: 'confirm',
title: 'Error',
message: modalError,
confirmButtonText: 'OK',
cancelValue: true
});
return;
}
showDeleteModal = false;
showDeleteTotpModal = false;
deleteTotpCode = '';
window.location.href = '/';
}
@@ -160,17 +177,57 @@
totpEnabled = Boolean((value as { enabled?: boolean }).enabled);
}
user.update((u) => (u ? { ...u, totpEnabled } : u));
showTotpModal = false;
modalError = '';
}
function handleDeleteTotpConfirm(value: unknown) {
if (typeof value === 'string') {
deleteTotpCode = value.trim();
async function openEditDisplayName() {
const value = String(
await openModal<string>({
mode: 'prompt',
title: 'Edit Display Name',
placeholder: 'New Display Name',
error: modalError,
cancelValue: ''
})
).trim();
if (!value) return;
await handleUserUpdate(value);
}
async function openEditRoles() {
const value = await openModal({
mode: 'multiselect',
title: 'Edit User Roles',
items: roleOptions,
initialValue: data.user?.roles,
cancelValue: null
});
if (!Array.isArray(value)) return;
await handleUserUpdate(undefined, value as number[]);
}
async function openDeleteAccount() {
const ok = await openModal<boolean>({
mode: 'confirm',
title: 'Delete Account',
message: `This action cannot be undone. ${isOwner ? 'All your' : "This user's"} pastes and account data will be permanently deleted.`,
confirmButtonText: 'Delete Account',
cancelValue: false
});
if (!ok) return;
await handleDeleteAccount();
}
async function openTotpSetup() {
const result = await openModal({
mode: 'totpSetup',
title: 'Two-Factor Authentication',
totpActive: totpEnabled,
cancelValue: null
});
if (result) {
handleTotpConfirm(result);
}
showDeleteTotpModal = false;
if (!deleteTotpCode) return;
handleDeleteAccount();
}
onMount(() => {
@@ -181,6 +238,10 @@
if (interval) clearInterval(interval);
};
});
$: reportSiteKey =
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
?.cf_turnstile_site_key ?? null;
</script>
<svelte:head>
@@ -206,9 +267,9 @@
<main
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">
<div class="relative 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">
{#if data.user?.roles.includes(403)}
{#if data.user?.roles?.includes(403)}
<span
class="relative flex h-7 w-7 items-center justify-center overflow-hidden rounded-full"
use:tooltip={roles[403]}
@@ -216,7 +277,7 @@
<User class="h-8 w-8 text-neutral-500" />
<Ban class="absolute h-7 w-7 text-red-500" />
</span>
{:else if data.user?.roles.includes(1) || data.user?.roles.includes(255)}
{:else if data.user?.roles?.includes(1) || data.user?.roles?.includes(255)}
{#if data.user?.roles?.length}
<span use:tooltip={roles[Math.max(...data.user.roles) as keyof typeof roles]}>
<ShieldUser class="h-8 w-8 text-neutral-400" />
@@ -253,6 +314,27 @@
>{pagination.totalCount} paste{pagination.totalCount !== 1 ? 's' : ''}</span
>
</div>
{#if reportsSubmitted}
<div class="flex shrink-0 items-center">
<Flag class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400"
>{reportsSubmitted.pagination.totalCount} submitted report{reportsSubmitted.pagination
.totalCount !== 1
? 's'
: ''}</span
>
</div>
{/if}
{#if reportsTarget}
<div class="flex shrink-0 items-center">
<Flag class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400"
>{reportsTarget.pagination.totalCount} report{reportsTarget.pagination.totalCount !== 1
? 's'
: ''}</span
>
</div>
{/if}
<div class="flex shrink-0 items-center">
<Hash class="mr-1 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400" use:tooltip={`User #${data.user?.uid}`}>
@@ -271,13 +353,29 @@
</div>
{/if}
</div>
{#if isOwner || $user?.roles.some((r) => r === 255 || r === 1)}
{#if !isOwner || !$user?.roles?.some((r) => r === 403)}
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="absolute top-0 right-0"
on:click={() =>
openModal({
mode: 'report',
title: 'Report User',
reportTarget: 'user',
reportTargetId: data.user?.uuid || '',
reportSiteKey: reportSiteKey,
confirmButtonText: 'Submit Report',
cancelValue: null
})}
>
<Flag class="m-4 h-6 w-6 cursor-pointer text-neutral-400 hover:text-amber-400" />
</div>
{/if}
{#if isOwner || $user?.roles?.some((r) => r === 255 || r === 1)}
<div class="mt-4 flex flex-wrap justify-center gap-2">
<button
on:click={() => {
showEditModal = true;
modalError = '';
}}
on:click={openEditDisplayName}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
>
<Pencil class="h-4 w-4" />
@@ -285,34 +383,25 @@
</button>
{#if isOwner}
<button
on:click={() => {
showTotpModal = true;
modalError = '';
}}
on:click={openTotpSetup}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
>
<ShieldUser class="h-4 w-4" />
{totpEnabled ? 'Manage 2FA' : 'Enable 2FA'}
</button>
{/if}
{#if $user?.roles.some((r) => r === 255)}
{#if $user?.roles?.some((r) => r === 255)}
<button
on:click={() => {
showRoleModal = true;
modalError = '';
}}
on:click={openEditRoles}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
>
<ShieldUser class="h-4 w-4" />
Edit Roles
</button>
{/if}
{#if isOwner || $user?.roles.some((r) => r === 255)}
{#if isOwner || $user?.roles?.some((r) => r === 255)}
<button
on:click={() => {
showDeleteModal = true;
modalError = '';
}}
on:click={openDeleteAccount}
class="flex items-center gap-2 rounded bg-red-900 px-4 py-2 text-sm font-medium transition-colors hover:bg-red-800"
>
<Trash2 class="h-4 w-4" />
@@ -342,6 +431,156 @@
</p>
{/if}
</div>
{#if reportsSubmitted || reportsTarget}
<div class="mt-6 space-y-6">
{#if reportsSubmitted}
<div class="rounded border border-neutral-800 bg-neutral-900/60 p-4">
<h2 class="mb-3 text-xl font-semibold text-neutral-200">Submitted Reports</h2>
{#if reportsSubmitted.reports.length > 0}
<div class="space-y-3">
{#each reportsSubmitted.reports as report (report.reportID)}
<div
class="flex cursor-pointer flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
role="link"
tabindex="0"
on:click={() => goto(resolve(`/report/${report.reportID}`))}
on:keydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
goto(resolve(`/report/${report.reportID}`));
}
}}
>
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="text-lg font-semibold text-neutral-100">
Report #{report.reportID}
</span>
<span class="text-sm text-neutral-300">
{reportTypeLabels[report.type] ?? 'Other'}
· {reportStatusLabels[report.status] ?? 'Open'}
</span>
</div>
<div class="flex flex-wrap items-center gap-3 text-sm text-neutral-400">
<span>{reportTargetLabels[report.targetType] ?? 'Unknown'}</span>
{#if report.pasteId}
<a
href={resolve(`/${report.pasteId}`)}
class="text-neutral-300 hover:text-white"
on:click|stopPropagation
>
{report.pasteTitle !== '' ? report.pasteTitle : report.pasteId}
</a>
{/if}
{#if report.userUUID}
{#if report.targetUsername}
<a
href={resolve(`/user/${report.targetUsername}`)}
class="text-neutral-300 hover:text-white"
use:tooltip={report.userUUID}
on:click|stopPropagation
>
{report.targetDisplayName || report.targetUsername}
</a>
{:else}
<span>{report.userUUID}</span>
{/if}
{/if}
<span>
Created {new Date(report.createdAt * 1000).toLocaleString()}
</span>
</div>
{#if report.description}
<p class="text-sm text-neutral-300">{report.description}</p>
{/if}
</div>
{/each}
</div>
{:else}
<p class="text-center text-neutral-400">No submitted reports to show.</p>
{/if}
</div>
{/if}
{#if reportsTarget}
<div class="rounded border border-neutral-800 bg-neutral-900/60 p-4">
<h2 class="mb-3 text-xl font-semibold text-neutral-200">Reports About This User</h2>
{#if reportsTarget.reports.length > 0}
<div class="space-y-3">
{#each reportsTarget.reports as report (report.reportID)}
<div
class="flex flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
role="link"
tabindex="0"
on:click={() => goto(resolve(`/report/${report.reportID}`))}
on:keydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
goto(resolve(`/report/${report.reportID}`));
}
}}
>
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="text-lg font-semibold text-neutral-100">
Report #{report.reportID}
</span>
<span class="text-sm text-neutral-300">
{reportTypeLabels[report.type] ?? 'Other'}
· {reportStatusLabels[report.status] ?? 'Open'}
</span>
</div>
<div class="flex flex-wrap items-center gap-3 text-sm text-neutral-400">
<span>{reportTargetLabels[report.targetType] ?? 'Unknown'}</span>
{#if report.reporterUsername}
<a
href={resolve(`/user/${report.reporterUsername}`)}
class="text-neutral-300 hover:text-white"
use:tooltip={report.reporterUUID}
on:click|stopPropagation
>
{report.reporterDisplayName || report.reporterUsername}
</a>
{:else}
<span>{report.reporterUUID}</span>
{/if}
{#if report.pastePID}
<a
href={resolve(`/${report.pasteId ?? report.pastePID}`)}
class="text-neutral-300 hover:text-white"
on:click|stopPropagation
>
{report.pasteTitle ? report.pasteTitle : `Paste #${report.pastePID}`}
</a>
{/if}
{#if report.userUUID}
{#if report.targetUsername}
<a
href={resolve(`/user/${report.targetUsername}`)}
class="text-neutral-300 hover:text-white"
use:tooltip={report.userUUID}
on:click|stopPropagation
>
{report.targetDisplayName || report.targetUsername}
</a>
{:else}
<span>{report.userUUID}</span>
{/if}
{/if}
<span>
Created {new Date(report.createdAt * 1000).toLocaleString()}
</span>
</div>
{#if report.description}
<p class="text-sm text-neutral-300">{report.description}</p>
{/if}
</div>
{/each}
</div>
{:else}
<p class="text-center text-neutral-400">No reports to show.</p>
{/if}
</div>
{/if}
</div>
{/if}
{#if pagination.totalPages && pagination.totalPages > 1}
<div class="mt-4 flex items-center justify-center gap-4">
<button
@@ -366,92 +605,6 @@
</div>
</main>
<Modal
show={showEditModal}
mode="prompt"
title="Edit Display Name "
placeholder="New Display Name"
bind:error={modalError}
onConfirm={(value) => handleUserUpdate(value as string)}
onCancel={() => {
showEditModal = false;
modalError = '';
}}
/>
<Modal
show={showDeleteModal}
mode="confirm"
title="Delete Account"
message={`This action cannot be undone. ${isOwner ? 'All your' : "This user's"} pastes and account data will be permanently deleted.`}
confirmButtonText="Delete Account"
error={modalError}
onConfirm={() => handleDeleteAccount()}
onCancel={() => {
showDeleteModal = false;
modalError = '';
}}
/>
<Modal
show={showDeleteTotpModal}
mode="totp"
title="Enter TOTP to delete"
placeholder="Enter 6-digit code"
inputType="text"
error={modalError}
confirmButtonText="Delete Account"
onConfirm={(value) => handleDeleteTotpConfirm(value)}
onCancel={() => {
showDeleteTotpModal = false;
deleteTotpCode = '';
modalError = '';
}}
/>
<Modal
show={showRoleModal}
mode="multiselect"
title="Edit User Roles"
items={roleOptions}
initialValue={data.user?.roles}
error={modalError}
onConfirm={(value) => handleUserUpdate(undefined, value as number[])}
onCancel={() => {
showRoleModal = false;
modalError = '';
}}
/>
<Modal
show={showTotpModal}
mode="totpSetup"
title="Two-Factor Authentication"
error={modalError}
totpActive={totpEnabled}
onConfirm={(value) => handleTotpConfirm(value)}
onCancel={() => {
showTotpModal = false;
modalError = '';
}}
/>
<Modal
show={showRoleTotpModal}
mode="totp"
title="Admin role requires TOTP"
placeholder="Enter 6-digit code"
inputType="text"
error={modalError}
confirmButtonText="Continue"
onConfirm={(value) => handleRoleTotpConfirm(value)}
onCancel={() => {
showRoleTotpModal = false;
roleTotpCode = '';
pendingRoles = null;
modalError = '';
}}
/>
<style>
button {
cursor: pointer;