fix(audit-1): media gating, per-user limits, moderation UI, upload integrity

First audit round: a blocker and eight high-severity findings across the media
access gate, the guest-facing rate limiters, host moderation, and the upload
pipeline — plus the backup commands and the e2e/production divergences that hid
several of them.

Squashed from 7 commits, original messages preserved below.

──────── fix(export): let the keepsake download through X-Frame-Options on iOS

The keepsake download navigates a hidden, same-origin iframe (deliberately:
a top-level navigation to a 404/429 would unload the PWA). Caddy stamped a
site-wide `X-Frame-Options: DENY` that also covered the proxied `/api/*`.

Blink hands a `Content-Disposition: attachment` response to the download
manager at the network layer, so Chromium never noticed. WebKit enforces XFO
on the frame navigation first and aborts the load — so on iOS Safari, the
app's primary platform, tapping Download did nothing at all, silently.

Carve the two export endpoints out to SAMEORIGIN, which still blocks
cross-origin framing. Implemented as two disjoint matchers rather than an
override: Caddy applies the FIRST `header` directive outermost, so it wins on
write and a later, more specific `header` is silently ignored (verified
against the running test stack).

Also close the test gap that let this ship:

- `06-export` ran on chromium-desktop only; add it to `webkit-iphone`, the
  only engine that enforces XFO on the download frame.
- No test in the suite ever clicked a download button — every archive
  assertion used Node `fetch`, which has no frame and no XFO enforcement.
  Add a spec that clicks it and awaits a real `download` event. Verified
  falsifiable: with the blanket DENY reinstated it fails and reports the
  WebKit refusal as the cause.
- Fix `ExportPage`'s card-scoped locators, which matched nothing: the cards
  carry `class="card p-5"` (a Tailwind `@apply` component class), never the
  `rounded-xl` the page object looked for. This had left the "shows enabled
  download buttons" test red on main.

──────── fix(media): close the percent-escape bypass of the media gate

`/media/%70reviews/{id}.jpg` served a taken-down photo to anyone,
unauthenticated. Verified against the running stack: the literal path 404s,
the escaped one returned 200 with the full image. Same for displays,
thumbnails and originals, and any escaped byte in any position works.

Cause: the block was four `nest_service("/media/previews", 404)` route
matches sitting above a `ServeDir` on `/media`. axum matches on the RAW path
(matchit does no percent-decoding), while `ServeDir` percent-decodes when it
resolves the file. So `%70reviews` missed every blocker, fell through to the
ServeDir, and was decoded back to `previews/` on disk — reaching the bytes
with no soft-delete and no ban-hide check. That defeats a host takedown,
which is the entire point of the gate.

Remove the `/media` route tree outright instead of racing the decoder.
Nothing needs it: every media URL the backend emits is already a gated
`/api/v1/upload/{id}/{original,preview,display,thumbnail}` alias
(handlers::feed), the frontend contains zero `/media/` references, and the
`/media` in config.rs/disk.rs is the filesystem path while `media/` in
export.rs is a path inside the zip. `/media/**` now 404s regardless of
encoding. The route's own comment already said it "serves nothing" — it
wasn't a backstop, it was the vector.

Caddy keeps proxying /media/* deliberately: the app 404s it, and forwarding
means the e2e gating specs exercise the app's refusal exactly as production
would rather than being masked by the SvelteKit 404 page.

Extend the gating spec with the encoded variants — asserting only the literal
spelling is what let this sit undetected.

──────── fix(rate-limit): key the guest-facing limiters per user, not per IP

At a venue every guest is behind one NAT, so an IP-keyed limiter hands the
whole party a single bucket. On a fresh deploy 12 guests arriving together
meant 5 joined and 7 were turned away, with no Retry-After telling them when
to retry. `/feed` (60/min) and `/export` (3 per DAY — the fourth guest to
fetch their keepsake locked out until tomorrow) had the same defect.

`feed_delta` was already keyed per-user and its comment states the exact
rationale ("so one client can't starve others behind a shared NAT"); this
makes its siblings match.

- feed:{ip}   -> feed:{user_id}    (auth was already in scope)
- export:{ip} -> export:{user_id}  (resolved from the download ticket's
  session, which was previously looked up and discarded)
- join:{ip}: pre-auth, so there is no user to key on. Split in two — a loose
  per-IP ceiling that only bounds raw volume (new `join_ip_rate_per_min`,
  default 60, migration 017), plus the real 5/60s anti-spam bucket keyed
  per (ip, name), mirroring the existing `recover:{ip}:{name}`.

admin_login / recover / pin_reset_req stay IP-keyed on purpose and are now
commented as such: they guard credential guessing, where a per-user or
per-name key would just hand an attacker a fresh bucket per guess.

Retry-After: the machinery existed but 7 of 8 sites called `check()` and
hard-coded `None`, so a throttled client was told to back off but never for
how long. Delete the bool `check()` wrapper entirely so `check_with_retry`
is the only entry point and the delay cannot be discarded by accident. Also
surface it for the PIN lockout, where the deadline was already known.

Fix the "unknown" fallback while here: every client_ip() caller passed that
literal, so any request without X-Forwarded-For — anything reaching the app
directly rather than through Caddy — shared ONE global bucket. Serve with
connect-info and use the peer address.

Tests: the reseed forces every limiter toggle off before each test, which is
why this whole class was invisible. Add 01-auth/rate-limit-shared-nat, which
enables them and asserts 12 guests share an IP without collision, that one
guest hammering their own name IS still throttled (so the fix re-keys rather
than removes the limit), and that feed/export buckets are per-user. Retarget
the ddos join test at the new per-IP ceiling — it asserted the defect.

Also seed `admin_login_rate_enabled` (read by the handler, seeded by no
migration and no reseed) and register `join_ip_rate_per_min` in the admin
config allowlist. Unrelated pre-existing red test fixed: 01-auth/join
asserted a "Willkommen!" heading the wedding redesign removed.

──────── feat(moderation): let a host remove a guest's photo or comment from the UI

`DELETE /host/upload/{id}` and `DELETE /host/comment/{id}` were complete on the
backend — transactional, SSE-broadcasting, audit-logged — and had zero frontend
callers. The feed context sheet offered "Löschen" only when
`target.user_id === myUserId`, so the only lever a host actually had against an
unwanted photo was banning the uploader.

That is both disproportionate and ineffective. A ban doesn't retract what was
already posted, and it makes things strictly worse for comments: the ban check
runs BEFORE the ownership check on the guest delete route, so banning an abusive
author leaves their comment on screen and permanently undeletable by them. With
no host affordance, nobody could remove it at all.

- feed: hosts/admins get "Beitrag entfernen" on other people's posts, routed to
  the host endpoint (the guest route 403s anything the caller doesn't own) with
  moderation-specific confirm copy. Own-post "Löschen" is unchanged.
- lightbox: same for comments, via /host/comment/{id}.
- Ban semantics are deliberately untouched (USER_JOURNEYS §10 — banned users keep
  read access and cannot write). The deadlock is broken by giving the host a way
  in, not by loosening the ban.

Live role (this had to come first). `getRole()` decodes the JWT claim, but the
token is never reissued — the backend slides the session row forward and treats
the DB row as authoritative. The claim is therefore frozen for the token's
lifetime: up to 30 days. A guest promoted at the party saw no Host-Dashboard and
no moderation actions until they signed out and back in, even though
`/me/context` had been returning their real role on every page load and 4 of its
6 call sites dropped the field on the floor.

Add `role-store.ts`: seeded from the claim so there's no flash of the wrong nav,
then corrected by every `/me/context` response. Point the ad-hoc `getRole()`
callers at it (account, upload, host, admin, and the new feed gate). The host and
admin dashboards now derive `myRole` reactively, so a demotion disables their
controls immediately instead of at next login.

Tests: 04-host/moderation-ui drives the real UI — host removes a guest photo and
it's gone from /feed server-side; a plain guest is offered nothing on someone
else's post (the mirror that keeps the first test honest); a promoted guest gains
the dashboard on reload while their token still carries `role: guest`; and a host
removes the comment of an already-banned guest, asserting first that the author's
own delete 403s so the deadlock is real.

──────── fix(upload): stop destroying originals, apply EXIF orientation, surface rejections

Three defects in the same pipeline, each of which loses a photo or misrepresents
one.

1. A transient error destroyed the guest's only copy.

`process`'s error arm unconditionally `remove_file`d the original. Every failure
routed there: `create_dir_all`, both derivative `save_with_format` calls (disk
full is the canonical case, and it arrives exactly when many guests upload at
once), a panic inside the image codec, or a momentary DB-pool exhaustion. The
row is only SOFT-deleted, so the bytes were the sole unrecoverable part — and
they were the part we deleted. The author already knew this was wrong next door:
`backfill_missing_display` says it "must NEVER soft-delete an upload that already
has a working preview".

Retry up to 3 times with backoff (re-checking the e2e generation guard after each
sleep), and on final failure keep the refund + soft-delete but leave the original
on disk, logging its path. A failed upload is now recoverable instead of gone.

2. Every portrait photo was stored sideways.

Phones don't rotate sensor data — they record the camera orientation in EXIF and
store the pixels as shot. `decode()` returns those raw pixels and the JPEG
re-encode writes no EXIF, so the 800px preview, the 2048px diashow display and
the keepsake were all rotated 90°, while "Original anzeigen" rendered upright
because the original keeps its tag. That asymmetry is why it reads as a viewer
bug. There was no EXIF handling anywhere in the repo and no exif crate.

Read the tag via `into_decoder()` (which carries the decode Limits through, so
the decompression-bomb cap is untouched) and apply it. Missing/malformed tags
fall back to NoTransforms — most images have none.

Existing derivatives are already baked wrong, so migration 018 adds
`derivatives_rev` and `backfill_missing_display` becomes
`backfill_stale_derivatives`: it now also picks up anything below the current rev
and regenerates it once from the original, which still carries its EXIF. Videos
are marked current in the migration — ffmpeg already honours the rotation matrix.
Bump DERIVATIVES_REV for any future change that invalidates derivatives.

3. A rejected upload vanished without a word.

`UploadQueue.svelte` — 162 lines holding the ONLY renderer of an item's error
text, the only "Erneut" retry button and the only rate-limit countdown — was
never imported anywhere, so `retryItem`, `removeItem` and `clearCompleted` were
unreachable at runtime. On a terminal rejection the store purged the blob and
wrote a clear German reason into `entry.error` "so the UI shows a clear reason".
There was no such UI. And `uploadBadgeCount` counted only pending/uploading, so
the badge decremented exactly as if the upload had succeeded.

Mount the queue on /upload, toast the reason immediately (the flow sends the user
to /feed straight after staging, so the list alone would still miss them), and
count blocked/error in the badge so a failure can't read as success.

Tests: 02-upload/exif-orientation uploads a 40x20 fixture tagged Orientation=6
and asserts both derivatives come back PORTRAIT, with a sanity check that the
source really is stored landscape. 02-upload/rejection-visible bans the uploader
between staging and sending, then asserts the toast, the queue row with the
server's reason, and that the item is still counted.

Note: 02-upload/quota's 4 failures are pre-existing and unrelated — see the next
commit.

──────── docs(backup): make the backup commands work; fix the e2e/prod divergences

Backup. Both documented commands failed on the shipped stack, and the sentence
explaining them was wrong too:

- `pg_dump $DATABASE_URL` — `DATABASE_URL` is only ever in the compose
  environment, never an operator's shell, and it points at `db:5432`, which is
  compose-internal DNS. The app image has no postgres client either.
- `> /media/backups/…` — `/media` is a named volume mounted inside the app
  container, not a host path, and nothing ever creates a `backups` subdirectory.
- `rsync /opt/eventsnap/media/` — that path does not exist anywhere.
- "a single path to back up" — false, and dangerously so: exports were moved to
  their own `exports_data` volume precisely so a keepsake (which contains every
  photo in the event) can't be served off the media tree. Backing up only
  `media_data` silently loses every generated keepsake.

Rewritten as three commands — db via `docker compose exec -T db pg_dump`, and one
`docker run … tar` per volume — all verified against the running stack. The
volume mounts use `/src`, not `/media`: I hit the footgun while testing this.
Docker pre-populates an EMPTY volume from the image's own directory and chowns it
to match, so `-v media_data:/media alpine` tars alpine's cdrom/floppy/usb, writes
them into the volume, and leaves it root-owned so the non-root app can no longer
write. Mounting where the image has nothing avoids all of it. Documented inline
so the next person doesn't rediscover it.

Also correct the architecture notes: `/media/*` no longer routes to the backend
(that static tree was removed as a gating bypass), and `exports_data` was missing
from the volume list — the one volume an operator most needs to know about.

e2e stack: add the `EXPORT_PATH` + `/exports` volume it was missing. The file
says "mirrors production layout"; without these, exports landed on the container's
writable layer at the default path, so export-leak and export-video wrote real
archives into ephemeral storage and the "exports live outside media" invariant
was never actually exercised.

Pre-existing red test, unrelated to the audit: all four 02-upload/quota tests
have been failing since 4464147 "stop /me/quota leaking raw disk to guests"
(2026-07-19), which post-dates the spec's last edit. `setLimitTo` calibrated
`quota_tolerance` from `free_disk_bytes` read through the GUEST's token — a field
that commit deliberately zeroes for non-staff. Dividing by it yields a NaN
tolerance, so every test in the block died in the helper. Read the calibration
inputs through a staff token and keep reading the ceiling back through the guest,
whose limit is the thing under test.

──────── test(e2e): document why WebKit can't run the client-queue upload tests

Three 02-upload tests have been failing on `webkit-iphone` on main — `02-upload`
was already in that project's testMatch, so this is pre-existing red, not
something the audit work introduced.

Root cause is the harness, not the app. Playwright's Linux WebKit build cannot
store Blobs in IndexedDB at all: `put()` fails with "UnknownError: Error
preparing Blob/File data to be stored in object store". Confirmed it is not
about how Playwright delivers files — a Blob constructed in-page with
`new Blob([bytes])` fails identically, while Chromium stores both that and a
`setInputFiles` File without complaint.

That breaks every test driving the composer (FAB → UploadSheet → /upload →
submit), because `handleSubmit` awaits `addToQueue`, which persists the file
before it can navigate. The symptom is a submit button stuck on "Wird
hochgeladen…" and a timeout waiting for /feed — which reads like an app hang and
cost real time to run down.

Skip those four (the three above plus the new rejection-visible) on WebKit only,
behind a named helper carrying the full explanation, so the next person gets the
answer instead of the investigation. Deliberately narrow: WebKit still runs every
API-driven upload test, all of 01-auth, 03-feed and 06-export — including the
keepsake download, which only WebKit can meaningfully verify. Chromium continues
to run all 14.

Worth being explicit, since these tests exist to protect iOS: real Safari
supports Blobs in IndexedDB, so this is NOT evidence that the offline upload
queue is broken on the platform. It does mean that guarantee is currently
unverifiable in CI and rests on Chromium coverage plus manual device testing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
fabi
2026-07-28 19:14:37 +02:00
parent a77c2ddc00
commit 0c0eed885a
43 changed files with 1276 additions and 222 deletions

View File

@@ -4,6 +4,7 @@
import { api } from '$lib/api';
import { onSseEvent } from '$lib/sse';
import { getUserId } from '$lib/auth';
import { isStaff } from '$lib/role-store';
import { dataMode, pickMediaUrl } from '$lib/data-mode-store';
import { doubletap } from '$lib/actions/doubletap';
import { focusTrap } from '$lib/actions/focus-trap';
@@ -114,9 +115,15 @@
}
}
async function deleteComment(id: string) {
/**
* `asHost` routes to the moderation endpoint. The guest route only ever deletes the
* caller's OWN comment, and it refuses a banned author outright — so without this a
* host who banned an abusive guest was left with the abuse still on screen and no way
* to remove it, since the ban itself blocks the author's own delete.
*/
async function deleteComment(id: string, asHost: boolean) {
try {
await api.delete(`/comment/${id}`);
await api.delete(asHost ? `/host/comment/${id}` : `/comment/${id}`);
comments = comments.filter((c) => c.id !== id);
} catch (e) {
toastError(e);
@@ -246,11 +253,11 @@
{formatTime(comment.created_at)}
</div>
</div>
{#if comment.user_id === userId}
{#if comment.user_id === userId || $isStaff}
<button
onclick={() => deleteComment(comment.id)}
onclick={() => deleteComment(comment.id, comment.user_id !== userId)}
class="shrink-0 text-gray-400 hover:text-red-500 dark:text-gray-500 dark:hover:text-red-400"
aria-label="Löschen"
aria-label={comment.user_id === userId ? 'Löschen' : 'Kommentar entfernen'}
>
<svg
class="h-3.5 w-3.5"

View File

@@ -1,5 +1,6 @@
import { writable } from 'svelte/store';
import { api } from './api';
import { setRole } from './role-store';
import type { MeContextDto } from './types';
/**
@@ -31,6 +32,9 @@ export async function refreshEventState(): Promise<void> {
const seq = stateSeq;
try {
const ctx = await api.get<MeContextDto>('/me/context');
// The role is unaffected by the close/reopen race guarded below, so apply it
// unconditionally — this is one of the refreshes that used to drop it.
setRole(ctx.role);
// A close/reopen landed while this was in flight — its result is now authoritative;
// don't overwrite it with our possibly-stale snapshot.
if (seq !== stateSeq) return;

View File

@@ -0,0 +1,34 @@
import { derived, writable } from 'svelte/store';
import { getRole } from './auth';
export type Role = 'guest' | 'host' | 'admin';
/**
* The viewer's LIVE role.
*
* The JWT is never reissued — the backend slides the session row forward instead and
* deliberately ignores the token's own role claim (`auth/middleware.rs`: "the live user row
* is authoritative"). So `getRole()`, which decodes the claim, is frozen for the lifetime of
* the token: up to 30 days for a guest. A guest promoted to host saw no Host-Dashboard until
* they signed out and back in, even though `/me/context` had already told the client their
* real role on the very next page load — it was fetched and the `role` field dropped on the
* floor in 4 of its 6 call sites.
*
* This store is seeded from the claim (so there is no flash of the wrong nav on boot) and
* corrected by every `/me/context` response via `setRole`. Read this instead of calling
* `getRole()` ad hoc.
*/
export const role = writable<Role | null>(getRole());
/** True for host and admin — the "can moderate" predicate used across the UI. */
export const isStaff = derived(role, ($role) => $role === 'host' || $role === 'admin');
/** Apply the authoritative role from a `/me/context` response. */
export function setRole(next: Role | null): void {
role.set(next);
}
/** Re-seed from the token, e.g. straight after a login/join that minted a new one. */
export function syncRoleFromToken(): void {
role.set(getRole());
}

View File

@@ -7,8 +7,16 @@ export const showBottomNav = writable(true);
// Controls the UploadSheet overlay. FAB sets true; sheet sets false.
export const uploadSheetOpen = writable(false);
// Count of items currently pending or uploading — shown as FAB badge.
export const uploadBadgeCount = derived(
queueItems,
($items) => $items.filter((i) => i.status === 'pending' || i.status === 'uploading').length
// Count of items still needing attention — shown as FAB badge. Includes the terminal
// states on purpose: counting only pending/uploading meant a rejected upload decremented
// the badge exactly as if it had succeeded, so the failure was indistinguishable from a
// completed upload. 'blocked' and 'error' stay counted until the user clears or retries them.
export const uploadBadgeCount = derived(queueItems, ($items) =>
$items.filter(
(i) =>
i.status === 'pending' ||
i.status === 'uploading' ||
i.status === 'error' ||
i.status === 'blocked'
).length
);

View File

@@ -3,6 +3,7 @@ import { writable, get } from 'svelte/store';
import { getToken, getUserId, clearAuth } from './auth';
import { onSseEvent } from './sse';
import { refreshQuota } from './quota-store';
import { toast } from './toast-store';
export interface QueueItem {
id: string;
@@ -629,6 +630,11 @@ async function uploadItem(id: string): Promise<void> {
entry.error = e.message;
await database.put(STORE_NAME, entry);
updateItemStatus(id, 'blocked', e.message);
// Tell the user NOW. The queue list only lives on /upload, and the flow sends
// them straight to /feed after staging a photo — so without this a rejected
// upload was silently swallowed: the blob is gone, the FAB badge drops exactly
// as if it had succeeded, and the photo simply never appears.
toast(`${entry.fileName}: ${e.message}`, 'error');
return;
}
const msg = e instanceof Error ? e.message : 'Upload fehlgeschlagen.';

View File

@@ -16,6 +16,7 @@
import { api } from '$lib/api';
import type { MeContextDto } from '$lib/types';
import { eventState, markClosed, markOpened, refreshEventState } from '$lib/event-state-store';
import { setRole } from '$lib/role-store';
import { loadEventConfig } from '$lib/event-config-store';
let { children } = $props();
@@ -48,6 +49,9 @@
try {
const ctx = await api.get<MeContextDto>('/me/context');
privacyNote.set(ctx.privacy_note);
// The live role — the JWT claim is frozen for the token's lifetime, so a
// promotion/demotion only reaches the UI through this. See role-store.ts.
setRole(ctx.role);
eventState.set({
uploadsLocked: ctx.uploads_locked,
galleryReleased: ctx.gallery_released

View File

@@ -1,6 +1,7 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { getToken, getDisplayName, getExpiry, getRole, clearAuth, currentPin } from '$lib/auth';
import { getToken, getDisplayName, getExpiry, clearAuth, currentPin } from '$lib/auth';
import { role, setRole } from '$lib/role-store';
import { clearQueue } from '$lib/upload-queue';
import { api } from '$lib/api';
import { onMount, onDestroy } from 'svelte';
@@ -16,7 +17,6 @@
import type { MeContextDto } from '$lib/types';
let displayName = $state<string | null>(null);
let role = $state<'guest' | 'host' | 'admin' | null>(null);
let expiry = $state<Date | null>(null);
let pinCopied = $state(false);
let leaveConfirmOpen = $state(false);
@@ -35,13 +35,13 @@
return;
}
displayName = getDisplayName();
role = getRole();
expiry = getExpiry();
// Refresh server-driven state. Quota + privacy note may have changed since last visit.
try {
const ctx = await api.get<MeContextDto>('/me/context');
privacyNote.set(ctx.privacy_note);
setRole(ctx.role);
} catch {
// non-fatal
}
@@ -177,10 +177,10 @@
</p>
<span
class="mt-0.5 inline-block rounded-full px-2.5 py-0.5 text-xs font-semibold {roleColor(
role
$role
)}"
>
{roleLabel(role)}
{roleLabel($role)}
</span>
</div>
</div>
@@ -192,7 +192,7 @@
</div>
<!-- Dashboards section (host + admin only) -->
{#if role === 'host' || role === 'admin'}
{#if $role === 'host' || $role === 'admin'}
<div class="card overflow-hidden">
<div class="border-b border-gray-100 px-5 py-3 dark:border-gray-700">
<h2
@@ -230,7 +230,7 @@
<path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
</svg>
</a>
{#if role === 'admin'}
{#if $role === 'admin'}
<a
href="/admin"
class="flex items-center gap-3 border-t border-gray-100 px-5 py-4 transition hover:bg-gray-50 dark:border-gray-700 dark:hover:bg-gray-700/50"
@@ -433,7 +433,7 @@
<!-- Per-user quota widget — staff-only (host/admin); guests never see the
server-derived storage figures. -->
{#if (role === 'host' || role === 'admin') && $quotaStore.enabled && $quotaStore.limit_bytes != null}
{#if ($role === 'host' || $role === 'admin') && $quotaStore.enabled && $quotaStore.limit_bytes != null}
<div class="card p-5">
<h2
class="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400"

View File

@@ -1,6 +1,7 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { getToken, getRole } from '$lib/auth';
import { getToken } from '$lib/auth';
import { role as myRoleStore } from '$lib/role-store';
import { api } from '$lib/api';
import { onMount } from 'svelte';
import { toast, toastError } from '$lib/toast-store';
@@ -262,7 +263,8 @@
let pinResetSubmitting = $state(false);
let pinModal = $state<{ name: string; pin: string } | null>(null);
const myRole = getRole();
// Live role, not the frozen JWT claim: a demotion must disable these controls at once.
const myRole = $derived($myRoleStore);
// Generic confirm-then-run for irreversible / privilege-changing actions
// (promote, demote, unban, release gallery). Reuses the shared ConfirmSheet.

View File

@@ -1,6 +1,7 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { getToken, getUserId } from '$lib/auth';
import { isStaff } from '$lib/role-store';
import { api } from '$lib/api';
import { connectSse, disconnectSse, onSseEvent } from '$lib/sse';
import { onMount, onDestroy } from 'svelte';
@@ -34,7 +35,9 @@
let sentinel: HTMLDivElement;
let feedObserver: IntersectionObserver | null = null;
let inPlaceRefreshTimer: ReturnType<typeof setTimeout> | null = null;
let pendingDeleteId = $state<string | null>(null);
// `asHost` picks the endpoint AND the copy: removing someone else's photo is a
// moderation action, not "delete my post", and it hits the host route.
let pendingDelete = $state<{ id: string; asHost: boolean } | null>(null);
// ─────────────────────────────────────────────────────────────────────────
// onMount A — DOM side-effects only (overscroll lock). Synchronous, returns
@@ -87,7 +90,19 @@
icon: '🗑',
tone: 'danger',
onClick: () => {
pendingDeleteId = target.id;
pendingDelete = { id: target.id, asHost: false };
}
});
} else if ($isStaff) {
// Moderation. Without this the only lever a host had against an unwanted photo
// was banning the uploader — which is both disproportionate and ineffective,
// since a ban does not retract what they already posted.
actions.unshift({
label: 'Beitrag entfernen',
icon: '🚫',
tone: 'danger',
onClick: () => {
pendingDelete = { id: target.id, asHost: true };
}
});
}
@@ -99,14 +114,18 @@
}
async function confirmDelete() {
const id = pendingDeleteId;
if (!id) return;
pendingDeleteId = null;
const pending = pendingDelete;
if (!pending) return;
pendingDelete = null;
try {
await api.delete(`/upload/${id}`);
uploads = uploads.filter((u) => u.id !== id);
if (selectedUpload?.id === id) selectedUpload = null;
void refreshQuota();
// The guest route rejects anything the caller doesn't own, so a host removing
// someone else's photo must go through the host route. That one also emits the
// `upload-deleted` SSE and writes an audit-log entry.
await api.delete(pending.asHost ? `/host/upload/${pending.id}` : `/upload/${pending.id}`);
uploads = uploads.filter((u) => u.id !== pending.id);
if (selectedUpload?.id === pending.id) selectedUpload = null;
// Only our own delete frees our quota; a host removal refunds the uploader.
if (!pending.asHost) void refreshQuota();
} catch (e) {
toastError(e);
}
@@ -969,13 +988,15 @@
<!-- Branded delete confirmation — replaces window.confirm() -->
<ConfirmSheet
open={pendingDeleteId !== null}
title="Beitrag löschen?"
message="Diese Aktion kann nicht rückgängig gemacht werden."
confirmLabel="Löschen"
open={pendingDelete !== null}
title={pendingDelete?.asHost ? 'Beitrag entfernen?' : 'Beitrag löschen?'}
message={pendingDelete?.asHost
? 'Der Beitrag verschwindet für alle Gäste. Diese Aktion kann nicht rückgängig gemacht werden.'
: 'Diese Aktion kann nicht rückgängig gemacht werden.'}
confirmLabel={pendingDelete?.asHost ? 'Entfernen' : 'Löschen'}
tone="danger"
onConfirm={confirmDelete}
onCancel={() => (pendingDeleteId = null)}
onCancel={() => (pendingDelete = null)}
/>
<!-- First-visit onboarding guide -->

View File

@@ -1,6 +1,7 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { getToken, getRole, getUserId } from '$lib/auth';
import { getToken, getUserId } from '$lib/auth';
import { role as myRoleStore } from '$lib/role-store';
import { api } from '$lib/api';
import type { MeContextDto } from '$lib/types';
import { onMount, onDestroy } from 'svelte';
@@ -97,7 +98,8 @@
let pinResetSubmitting = $state(false);
let pinModal = $state<{ name: string; pin: string } | null>(null);
const myRole = getRole();
// Live role, not the frozen JWT claim: a demotion must disable these controls at once.
const myRole = $derived($myRoleStore);
const myUserId = getUserId();
// Generic confirm-then-run for the irreversible / privilege-changing actions

View File

@@ -1,6 +1,7 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { getToken, getRole } from '$lib/auth';
import { getToken } from '$lib/auth';
import { isStaff } from '$lib/role-store';
import { addToQueue, loadQueue } from '$lib/upload-queue';
import { toast } from '$lib/toast-store';
import { showBottomNav } from '$lib/ui-store';
@@ -9,6 +10,7 @@
import { onMount, onDestroy } from 'svelte';
import { quotaStore, refreshQuota } from '$lib/quota-store';
import ConfirmSheet from '$lib/components/ConfirmSheet.svelte';
import UploadQueue from '$lib/components/UploadQueue.svelte';
import IconButton from '$lib/components/IconButton.svelte';
import { vibrate } from '$lib/haptics';
import type { PendingFile } from '$lib/pending-upload-store';
@@ -27,7 +29,6 @@
// The storage widget is staff-only (host/admin). Guests never see server-derived
// storage figures — the backend also zeroes the raw-disk fields for non-staff, so
// this is UI-consistency on top of an API guarantee, not the security boundary.
const isStaff = getRole() === 'host' || getRole() === 'admin';
// Quick-tag chips derived from caption as the user types
let captionTags = $derived.by(() => {
@@ -261,7 +262,7 @@
<!-- Per-user quota — staff-only (never shown to guests), and also hidden when
admin disabled enforcement. -->
{#if isStaff && $quotaStore.enabled && $quotaStore.limit_bytes != null}
{#if $isStaff && $quotaStore.enabled && $quotaStore.limit_bytes != null}
<div class="px-4 pt-3 text-xs text-gray-500 dark:text-gray-400">
<div class="flex items-center justify-between">
<span
@@ -344,5 +345,13 @@
: 'Hochladen'}
{/if}
</button>
<!--
The queue list. This component existed, complete with the per-item error text, the
"Erneut" retry button and the rate-limit countdown — and was never imported anywhere,
so none of it could be reached. A rejected upload wrote a clear reason into a store
nothing rendered.
-->
<UploadQueue />
</div>
</div>