fix(frontend): park uploads that cannot succeed, and stop two false signals

The upload queue gains `parkedFor`, so a photo rejected for a reason that cannot change on
its own stops re-pushing itself. A ban used to come back as a generic `forbidden`, which
purged the blob and moved the row to `blocked` — a terminal state with no retry button — so
lifting a ban restored everything except the photo actually in flight. Ban and release are
now distinct codes that keep the blob, charge no attempt, and tell the guest what has to
happen. `releaseResolvedParks` drains them at boot from /me/context, because the live
`user-shown` / `event-opened` events only reach a tab that was open when the host acted,
and the usual sequence is the other way round.

Two signals were firing on nothing. A filtered feed set `feedStale` on EVERY delta without
deduping — and the delta cursor boundary is inclusive while sse.ts deliberately rewinds
`lastEventTime`, so deltas routinely re-return rows already delivered. With the backstop
polling every 60-120s, a guest who tapped a hashtag got a "Neue Beiträge" pill they could
never clear, each tap costing a full filtered refetch. It now dedupes in both branches.

The SSE liveness backstop had the mirror problem: `noteDelivered` harvested id, upload_id
AND user_id from every payload, so by the time anything was deleted or anyone banned, their
ids were already marked delivered from ordinary traffic about live content. The
`deleted_ids` and `hidden_user_ids` clauses were false essentially always, leaving a
half-open socket undetected while a host moderated into a feed nobody was listening to.
Each event now records only the id its own clause tests.

Also: /admin no longer bounces to /join on a cleared session — AUTH_ROUTES had the `/admin`
prefix, which suppressed clearAuth() on the dashboard and let the login guard bounce back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
fabi
2026-08-11 22:44:26 +02:00
parent f5c55d6f92
commit a53729a704
13 changed files with 621 additions and 50 deletions

View File

@@ -9,7 +9,13 @@
import Toaster from '$lib/components/Toaster.svelte';
import { showBottomNav } from '$lib/ui-store';
import { isAuthenticated } from '$lib/auth';
import { queueItems, isProcessing, loadQueue, rateLimitRetryAt } from '$lib/upload-queue';
import {
queueItems,
isProcessing,
loadQueue,
rateLimitRetryAt,
releaseResolvedParks
} from '$lib/upload-queue';
import { privacyNote } from '$lib/privacy-note-store';
import { refreshQuota } from '$lib/quota-store';
import { onSseEvent } from '$lib/sse';
@@ -88,6 +94,16 @@
galleryReleased: ctx.gallery_released
});
isBanned.set(ctx.is_banned);
// Now that we know the AUTHORITATIVE state, release anything the queue parked
// waiting on a host action that has already happened. The live `user-shown` /
// `event-opened` events only reach a tab that was open when the host acted, and
// the usual sequence is the other way round: the guest closes the app, the host
// lifts the ban or reopens uploads later. Without this the photo stays parked
// forever, which is exactly the "my pictures never sent" the host gets asked about.
void releaseResolvedParks({
banned: ctx.is_banned,
uploadsOpen: !ctx.uploads_locked && !ctx.gallery_released
});
} catch {
// Cross-cutting hydration on boot — failure is non-fatal; users without
// a session land on /join anyway, and the per-page mount will retry.
@@ -115,8 +131,7 @@
// `{ user_id: UUID }`, broadcast to everyone (it also evicts the banned user's cards
// from every feed), so only OUR id means us. Without this, `isBanned` was seeded once
// on boot and never moved — a guest banned mid-party kept the full UI and learned
// about it one 403 toast at a time, which reads as the app being broken. The ban is
// one-way here on purpose: an unban has no SSE, and the next `/me/context` clears it.
// about it one 403 toast at a time, which reads as the app being broken.
onSseEvent('user-hidden', (data) => {
try {
const payload = JSON.parse(data) as { user_id: string };
@@ -125,6 +140,18 @@
// Malformed payload — discard; nothing actionable for the user.
}
}),
// And the mirror. This used to be one-way ("an unban has no SSE, and the next
// `/me/context` clears it") because `unban_user` broadcast nothing at all — so a
// guest whose ban was lifted kept the banned UI until they happened to reload,
// which for a PWA with no URL bar is not a thing they can easily do.
onSseEvent('user-shown', (data) => {
try {
const payload = JSON.parse(data) as { user_id: string };
if (payload.user_id === getUserId()) isBanned.set(false);
} catch {
// Malformed payload — discard; nothing actionable for the user.
}
}),
// Reflect a host closing/reopening uploads live, so the composer switches to a
// locked state immediately instead of a guest finding out via a rejected upload.
// `event-closed` fires for BOTH a plain lock and a gallery release (release ⇒ lock),

View File

@@ -3,7 +3,7 @@
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 { api, ApiError } from '$lib/api';
import { onMount, onDestroy } from 'svelte';
import { dataMode } from '$lib/data-mode-store';
import { themePreference, type ThemePreference } from '$lib/theme-store';
@@ -14,6 +14,7 @@
import { avatarPalette, initials } from '$lib/avatar';
import ConfirmSheet from '$lib/components/ConfirmSheet.svelte';
import { vibrate } from '$lib/haptics';
import { toast } from '$lib/toast-store';
import type { MeContextDto } from '$lib/types';
let displayName = $state<string | null>(null);
@@ -124,6 +125,40 @@
goto('/join');
}
let deleteConfirmOpen = $state(false);
let deleting = $state(false);
/**
* Erase this account. Unlike `handleLogout`, the server call is NOT best-effort — if it fails
* we must keep the guest signed in and say so, because clearing local auth on a failed delete
* would leave them believing their photos were gone while every one of them is still live.
*/
async function handleDeleteAccount() {
if (deleting) return;
deleting = true;
try {
await api.delete('/me');
} catch (e) {
deleteConfirmOpen = false;
deleting = false;
toast(
e instanceof ApiError ? e.message : 'Löschen fehlgeschlagen. Bitte versuch es erneut.',
'error',
6000
);
return;
}
// Only now is it safe to tear down locally. The queue must go too: its blobs are this
// guest's photos, and leaving them would re-upload everything on the next session.
try {
await clearQueue();
} catch {
/* best-effort cleanup */
}
clearAuth();
goto('/join');
}
function formatDate(d: Date): string {
return d.toLocaleDateString('de-DE', { day: '2-digit', month: 'long', year: 'numeric' });
}
@@ -517,7 +552,13 @@
</a>
<!-- Leave / logout (this device) -->
<!-- `data-testid` rather than an accessible-name locator: this trigger and the
confirm sheet's button are BOTH labelled "Abmelden", so `getByRole('button',
{ name: /abmelden/i })` is ambiguous the moment the sheet opens. The rename
away from "Event verlassen" silently broke three e2e locators — including the
one behind the smoke spec — precisely because they keyed on visible copy. -->
<button
data-testid="account-logout"
onclick={() => {
leaveEverywhere = false;
leaveConfirmOpen = true;
@@ -570,6 +611,32 @@
>Auf allen Geräten abmelden</span
>
</button>
<!-- Erasure. The join page's data notice promises this exists, and until now nothing
did: there was no user-deletion route at any role, so honouring "please remove my
photos" meant hand-written SQL against production. -->
<button
data-testid="account-delete"
onclick={() => (deleteConfirmOpen = true)}
class="flex w-full items-center gap-3 border-t border-gray-100 px-5 py-4 text-left transition hover:bg-red-50 dark:border-gray-700 dark:hover:bg-red-950/30"
>
<svg
class="h-5 w-5 text-red-500 dark:text-red-400"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="1.5"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"
/>
</svg>
<span class="flex-1 text-sm font-medium text-red-600 dark:text-red-400"
>Konto und alle Fotos löschen</span
>
</button>
</div>
</div>
</div>
@@ -624,3 +691,15 @@
onConfirm={() => handleLogout(leaveEverywhere)}
onCancel={() => (leaveConfirmOpen = false)}
/>
<!-- Erasure confirm. Separate sheet from the logout one because the copy has to be unambiguous
about the difference: logging out keeps everything, this destroys it. -->
<ConfirmSheet
open={deleteConfirmOpen}
title="Konto und alle Fotos löschen?"
message="Alle deine Fotos, Bildtexte, Kommentare und Likes werden endgültig gelöscht — auch aus der Diashow und aus dem Erinnerungs-Archiv. Das lässt sich nicht rückgängig machen."
confirmLabel="Endgültig löschen"
tone="danger"
onConfirm={handleDeleteAccount}
onCancel={() => (deleteConfirmOpen = false)}
/>

View File

@@ -195,12 +195,12 @@
clearTimeout(timer);
action();
};
// Always strictly less than the dwell — see PRELOAD_HEADROOM_MS.
const preloadBudget = Math.max(
250,
Math.min(PRELOAD_TIMEOUT_MS, dwellMs - PRELOAD_HEADROOM_MS)
);
timer = setTimeout(() => done(() => commit(candidates[i])), preloadBudget);
// Always strictly less than the dwell — see PRELOAD_HEADROOM_MS.
const preloadBudget = Math.max(
250,
Math.min(PRELOAD_TIMEOUT_MS, dwellMs - PRELOAD_HEADROOM_MS)
);
timer = setTimeout(() => done(() => commit(candidates[i])), preloadBudget);
const pre = new Image();
pre.src = candidates[i];
pre.decode().then(
@@ -445,6 +445,12 @@
unsubs.push(onSseEvent('upload-processed', handleUploadProcessed));
unsubs.push(onSseEvent('upload-deleted', handleUploadDeleted));
unsubs.push(onSseEvent('user-hidden', handleUserHidden));
// An unban restores that guest's photos to the eligible set. The periodic `reconcile`
// below would pick this up on its own, but this is the projector nobody is standing at —
// waiting a whole interval to un-hide photos the host has just decided are fine again is
// needlessly visible. A full reconcile is the only correct response anyway: the hidden
// cards were dropped from local state, so there is nothing to restore in place.
unsubs.push(onSseEvent('user-shown', () => void reconcile()));
unsubs.push(onSseEvent('feed-delta', handleFeedDelta));
// Open the stream ourselves — a kiosk/projector loads /diashow directly (never
// via /feed), so we can't rely on another page having opened the singleton
@@ -515,8 +521,8 @@
<div
class="pointer-events-none absolute bottom-4 left-4 max-w-xs rounded-md bg-black/60 px-3 py-2 text-left text-xs text-white/70 backdrop-blur"
>
Dieser Browser kann den Bildschirm nicht wachhalten. Bitte die automatische
Bildschirmsperre am Gerät deaktivieren.
Dieser Browser kann den Bildschirm nicht wachhalten. Bitte die automatische Bildschirmsperre
am Gerät deaktivieren.
</div>
{/if}

View File

@@ -126,9 +126,7 @@
// they did, the guest got a green success toast, a consumed single-use ticket, one
// of three daily slots gone, and nothing in their Downloads. Now the mint fails
// honestly and lands in the `catch` below.
const { ticket } = await api.post<{ ticket: string }>(
`/export/ticket?kind=${kind}`
);
const { ticket } = await api.post<{ ticket: string }>(`/export/ticket?kind=${kind}`);
downloadFrame.src = `${endpoint}?ticket=${encodeURIComponent(ticket)}`;
// An iframe download produces NO visible change: no spinner, no navigation, and
// on mobile often no browser chrome either. Without a word here the guest cannot

View File

@@ -308,7 +308,11 @@
unsubscribers.push(
onSseEvent('new-upload', (data) => {
try {
const upload: FeedUpload = JSON.parse(data);
// The `new-upload` payload is the backend's `UploadDto`, which carries `hashtags`
// on top of what `FeedUpload` declares — needed for the filter check below.
// Typed explicitly rather than widening `FeedUpload`, because the feed's own
// rows (from `/feed`) genuinely do not include them.
const upload: FeedUpload & { hashtags?: string[] } = JSON.parse(data);
// GRID view must NOT prepend live. Its rows are POSITIONAL windows
// (`uploads.slice(i * COLS, …)` in VirtualFeed), so inserting at the head shifts
// every tile by one slot: each row's keyed `{#each}` then sees a different set of
@@ -329,6 +333,12 @@
// row, and a duplicate id in a keyed `{#each}` is a thrown error, not a
// cosmetic glitch.
if (uploads.some((u) => u.id === upload.id)) return;
// Respect the active filter (H13). `uploads` IS the filtered set — the server
// applied `filterParams()` — but this handler prepended unconditionally, so a
// guest who filtered to #tanzflaeche had that filter quietly destroyed within
// minutes by everyone else's uploads, with no indication and no way back short
// of toggling the chip. The payload carries `hashtags`, so we can just check.
if (selectedHashtag && !upload.hashtags?.includes(selectedHashtag)) return;
uploads = [upload, ...uploads];
} catch {
/* ignore */
@@ -372,6 +382,17 @@
/* ignore */
}
}),
// The ban was lifted — their cards must come back. Unlike a hide we cannot do this in
// place: the cards were filtered out of `uploads`, so there is nothing left to restore
// from. Flag the feed stale and let the existing tap-to-refresh pill resync, which is
// the same treatment a truncated delta gets and keeps the guest's scroll position.
//
// Without this the unban was invisible to every open feed and to the unattended
// projector until somebody reloaded by hand — while the host's confirm copy promised
// the photos were back.
onSseEvent('user-shown', () => {
feedStale = true;
}),
// Patch the single affected card in place from the SSE payload instead of
// refetching page 1 — a busy event fires these constantly and a full reload
// would yank every scrolled-down user back to the top on each reaction.
@@ -406,9 +427,39 @@
return;
}
if (delta.uploads.length) {
// `/feed/delta` takes NO filter parameters, so its rows are the unfiltered
// event. Merging them into a filtered view is the same defect as the
// `new-upload` prepend above (H13) — and here we cannot check hashtags,
// because the delta rows do not carry them.
//
// So when a filter is active, don't merge: flag the feed stale and let the
// existing tap-to-refresh pill re-run page 1 under `filterParams()`. Same
// treatment a truncated delta gets, and it keeps the guest's scroll.
// Dedupe FIRST, in both branches. `delta.uploads.length > 0` is not
// evidence that anything NEW arrived: the delta cursor boundary is
// inclusive and `sse.ts` deliberately rewinds `lastEventTime` to an
// upload's `created_at`, so a delta routinely re-returns rows the
// stream already delivered. The filtered branch skipped this check
// entirely and set `feedStale` on EVERY delta — and the backstop
// polls every 60-120s, so a guest who tapped a hashtag got a "Neue
// Beiträge" pill they could never clear, each tap costing a full
// filtered refetch. That trains guests to ignore the one control
// that means something. It also fired for any other guest's
// non-matching upload, which by construction is never in the
// filtered `uploads`.
const seen = new Set(uploads.map((u) => u.id));
const fresh = delta.uploads.filter((u) => !seen.has(u.id));
if (fresh.length) uploads = [...fresh, ...uploads];
if (fresh.length) {
if (selectedHashtag || activeFilters.length) {
// Still cannot MERGE under a filter — `/feed/delta` takes no
// filter params and its rows carry no hashtags, so we cannot
// tell which belong in this view. Flagging stale is right;
// doing it for rows already on screen was not.
feedStale = true;
} else {
uploads = [...fresh, ...uploads];
}
}
}
// A delta reconciles new uploads and deletions, but not like/comment
// counts that changed on already-visible cards while we were

View File

@@ -8,10 +8,14 @@
// Show which event the guest is joining (USER_JOURNEYS §1). Public, pre-auth.
let eventName = $state('');
// The operator's own data notice, if they set one. Usually empty — see the notice block below.
let privacyNote = $state('');
let noticeOpen = $state(false);
onMount(async () => {
try {
const ev = await api.get<{ name: string; slug: string }>('/event');
const ev = await api.get<{ name: string; slug: string; privacy_note?: string }>('/event');
eventName = ev.name;
privacyNote = ev.privacy_note?.trim() ?? '';
} catch {
// Non-fatal — fall back to the generic heading if the lookup fails.
}
@@ -34,6 +38,39 @@
let pinRequestSent = $state(false);
let pinRequestLoading = $state(false);
/**
* Stable idempotency key for THIS join attempt, surviving a reload or a PWA relaunch.
*
* The failure it closes: `/join` commits the account and the PIN hash, but the plaintext PIN
* only ever exists in the response body. Lose that response — the 5G-to-nothing handoff every
* venue car park has — and the retry used to 409 on the guest's own name, leaving them staring
* at a PIN prompt for a PIN nobody had ever seen. With a key the server recognises the retry
* and answers with a working PIN (it rotates it; see migration 027).
*
* Kept in localStorage rather than component state because the guest's instinctive response to
* a hung request is to reload the page, which would otherwise mint a fresh key and re-create
* the exact bug. Cleared once the join has demonstrably landed.
*/
const JOIN_KEY_STORAGE = 'eventsnap:join-attempt-id';
function joinAttemptId(): string {
let id: string | null = null;
try {
id = localStorage.getItem(JOIN_KEY_STORAGE);
} catch {
// Private mode / storage disabled. A per-call UUID is still better than none: it makes
// a retry within this page view idempotent, which is the common case.
}
if (!id) {
id = crypto.randomUUID();
try {
localStorage.setItem(JOIN_KEY_STORAGE, id);
} catch {
/* best effort */
}
}
return id;
}
async function handleJoin() {
if (!displayName.trim()) return;
loading = true;
@@ -44,9 +81,19 @@
pin: string;
user_id: string;
is_new: boolean;
}>('/join', { display_name: displayName.trim() });
}>('/join', {
display_name: displayName.trim(),
client_join_id: joinAttemptId()
});
setAuth(res.jwt, res.pin, res.user_id, displayName.trim());
// The join landed and we hold the PIN — retire the key so a later deliberate join (a
// second guest on a shared device) is a new attempt rather than a retry of this one.
try {
localStorage.removeItem(JOIN_KEY_STORAGE);
} catch {
/* best effort */
}
pin = res.pin;
showPinModal = true;
} catch (e) {
@@ -311,6 +358,70 @@
</button>
</form>
<!--
Data notice AT THE POINT OF COLLECTION.
There was none at all — not on this page, not anywhere pre-auth — while
PROJECT.md:407 claimed there was. For ~100 EU guests uploading photos of
identifiable people, including children, that was the most consequential gap in
the whole audit, and the least work to close.
The baseline text below is hardcoded rather than read from `privacy_note`,
because `privacy_note` defaults to '' (migration 009) — a notice an operator can
leave blank is not a notice. The operator's own text is shown IN ADDITION when
they have set one.
Summary visible without a tap (that is the part that has to be unmissable);
detail behind a disclosure so it does not bury the one field on the page.
-->
<div class="mt-5 border-t border-gray-200 pt-4 dark:border-gray-700">
<p class="text-xs leading-relaxed text-gray-600 dark:text-gray-400">
Mit dem Beitreten legst du ein Konto mit deinem Namen an. Deine Fotos, Kommentare und
dein Name sind für alle Gäste dieses Events sichtbar.
</p>
<button
type="button"
onclick={() => (noticeOpen = !noticeOpen)}
data-testid="join-privacy-toggle"
aria-expanded={noticeOpen}
class="mt-1 text-xs font-medium text-blue-600 hover:underline dark:text-blue-400"
>
{noticeOpen ? 'Weniger anzeigen' : 'Was passiert mit meinen Daten?'}
</button>
{#if noticeOpen}
<div
class="mt-2 space-y-2 text-xs leading-relaxed text-gray-600 dark:text-gray-400"
data-testid="join-privacy-note"
>
<p>
<strong class="text-gray-800 dark:text-gray-200">Was gespeichert wird:</strong> dein angezeigter
Name, deine hochgeladenen Fotos und Videos samt Aufnahmezeitpunkt, deine Bildtexte, Kommentare
und Likes. Dazu ein verschlüsselter Prüfwert deines PINs — der PIN selbst wird nicht gespeichert.
</p>
<p>
<strong class="text-gray-800 dark:text-gray-200">Wer es sehen kann:</strong> alle Gäste
dieses Events. Die Gastgeber können außerdem Beiträge und Kommentare entfernen. Am Ende
erhalten die Gastgeber ein Archiv mit allen Fotos.
</p>
<p>
<strong class="text-gray-800 dark:text-gray-200">Wie lange:</strong> bis die Gastgeber
das Event abschließen und die Installation abbauen. Du kannst eigene Fotos jederzeit selbst
löschen, und über „Mein Konto“ dein Konto samt aller Inhalte entfernen lassen.
</p>
<p>
Lade bitte keine Fotos von Personen hoch, die damit nicht einverstanden sind — bei
Kindern brauchst du das Einverständnis der Eltern.
</p>
{#if privacyNote}
<p class="border-t border-gray-200 pt-2 dark:border-gray-700">
<strong class="text-gray-800 dark:text-gray-200">Hinweis der Gastgeber:</strong>
{privacyNote}
</p>
{/if}
</div>
{/if}
</div>
<p class="mt-4 text-center text-sm">
<a
href="/recover"

View File

@@ -1,7 +1,7 @@
<script lang="ts">
import { goto, afterNavigate } from '$app/navigation';
import { api, ApiError } from '$lib/api';
import { setAuth, getPin, getToken, clearPin } from '$lib/auth';
import { setAuth, getPin, getToken, clearPin, getDisplayName } from '$lib/auth';
import { markGuideSeen } from '$lib/onboarding';
import { browser } from '$app/environment';
import IconButton from '$lib/components/IconButton.svelte';
@@ -80,10 +80,25 @@
} catch (e) {
if (e instanceof ApiError) {
error = e.message;
// A wrong PIN here often means the locally-cached PIN is stale (a host reset it
// while this device was offline and missed the `pin-reset` SSE). Drop the cached
// value so it doesn't keep pre-filling the field with the dead PIN.
if (e.status === 401) clearPin();
// A wrong PIN CAN mean the locally-cached PIN is stale (a host reset it while this
// device was offline and missed the `pin-reset` SSE), and then dropping it stops the
// field pre-filling with a dead value. `+layout.svelte` already handles the online
// case; this is the offline backstop.
//
// But it must be narrow, because the backend returns the SAME 401 for a wrong PIN
// and an UNKNOWN NAME (deliberately — it closes an enumeration and timing oracle).
// Clearing on any 401 meant a guest who mistyped their own name lost the only copy
// of their PIN: localStorage is where it lives, the server keeps only the bcrypt,
// and rejoining under the same name 409s. One typo, permanently locked out of their
// own account, needing a host with a dashboard open.
//
// So clear only when the evidence actually points at a stale cache: the name they
// submitted is the one this device belongs to, AND the PIN that was rejected is the
// cached one. Any other 401 leaves stored state untouched.
const submittedOwnName =
getDisplayName()?.trim().toLowerCase() === displayName.trim().toLowerCase();
const submittedCachedPin = getPin() !== null && pin.trim() === getPin();
if (e.status === 401 && submittedOwnName && submittedCachedPin) clearPin();
} else {
error = 'Ein Fehler ist aufgetreten.';
}