Adversarial re-review of df275bb found the two-guard ready-flip fix still left a
narrow double-race open, plus test-hygiene drift from the banUser param removal.
MED — residual stale-keepsake race the `export_released_at` guard alone missed
The flip relied on two guards defeating two clearers: the `release_seq` EXISTS
check (vs a re-release bump) and `export_released_at IS NOT NULL` (vs open_event's
clear). But release_gallery re-arms `export_released_at = NOW()` and bumps
`release_seq` as SEPARATE statements, so a stale worker's flip landing in the gap
between them satisfies BOTH guards (released re-armed, seq not yet bumped) and
resurrects a pre-reopen keepsake — the next re-release then skips regeneration and
serves an archive missing the reopen-window uploads.
Root-cause fix: `open_event` now bumps every `export_job.release_seq`, making a
reopen a supersession point symmetric with a re-release. A worker that captured the
pre-reopen seq can never match its `release_seq`-guarded finalize/flip again,
regardless of when the re-release re-arms `export_released_at`. The released-anchor
guard stays as defense-in-depth. Added a deterministic e2e asserting the reopen
bumps the seq (the invariant that closes the race without depending on
sub-millisecond worker timing).
LOW
- Gate the `export-progress: 100` SSE + `prune_stale_export_files` on the ready-flip
actually flipping (rows_affected > 0). A superseded worker no longer advertises a
misleading 100% or prunes on a fresh generation's behalf.
- moderation.spec.ts: the two ban tests had become byte-identical after the
hide_uploads param removal; drop the one whose "hide_uploads=true" title no longer
matched what it exercised, keep the accurate "always hides" test.
- host-dashboard page-object: drop the dead `banUser(hideUploads)` param + its
checkbox branch (the UI no longer renders that checkbox — a latent hang trap).
- sse-eviction.spec.ts: rename the test whose title referenced the removed flag.
Verified: backend 40 tests, e2e 156 passed / 1 skipped on chromium-desktop
(incl. the new reopen-supersession regression).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adversarial re-review of the persona-audit + audit-followup rounds (6411747..)
found one HIGH and one MED regression plus LOW gaps. All fixed with coverage.
HIGH — export stale-keepsake resurrected by an open_event race
A reopen landing in the window between a *current* export worker's finalize_job
and its ready-flag flip cleared export_released_at + the ready flags but left the
export_job row `done` at the same release_seq. The seq-guarded flip then still
matched and re-set export_{zip,html}_ready=TRUE on a pre-reopen snapshot; the next
re-release read that stale TRUE and skipped regeneration (`if ready { continue }`),
serving a keepsake missing every upload from the reopen window — the exact data
loss migration 012 exists to prevent. Both ready-flip UPDATEs are now additionally
anchored on `export_released_at IS NOT NULL`, so a landed reopen makes the flip a
no-op and the re-release regenerates cleanly.
MED — queue dedup broke for reloaded items
loadQueue rebuilt QueueItems from IndexedDB without copying lastModified, which the
new addToQueue dedup keys on. A file re-selected after a page reload / PWA relaunch
missed the duplicate check and uploaded twice. Rehydration now carries lastModified
(extracted to a pure, tested entryToQueueItem helper).
LOW
- diashow: clear the upload-processed debounce timer in onDestroy (no stray
post-unmount /feed fetch).
- USER_JOURNEYS §9.5: document the reconnect-delta ban replay (hidden_user_ids /
uploads_hidden_at, migration 013), not just the live user-hidden SSE.
- e2e api-client: drop the misleading hide_uploads param from banUser — the backend
takes no body and always hides; strip the dead boolean at all call sites.
Tests
- Extract isReversibleLock (the terminal-403 KEEP-vs-PURGE-blob discriminator) into a
pure exported helper + unit tests, so the data-loss-critical branch is covered
without an XHR harness.
- entryToQueueItem unit tests lock the lastModified-carry regression.
- Document the export flip-race guard in the reopen/re-release spec (the sub-ms
finalize↔flip interleave isn't deterministically forceable with fast fixtures;
covered by the SQL guard + the end-to-end completeness test).
Verified: backend 40 tests, frontend 44 unit tests, svelte-check 0 errors,
e2e 156 passed / 1 skipped on chromium-desktop.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adversarial re-review of the persona-audit commit surfaced two HIGH regressions I'd
introduced plus MED/LOW gaps. All fixed:
HIGH
- Auth privilege escalation: reads are sessionStorage-first, but guest `setAuth` wrote only
localStorage — a resident admin token shadowed a new guest login (guest ran as admin on a
shared device). setAuth/setAdminAuth now DISPLACE the other store so exactly one identity
is resident. Adds unit + e2e regression guards.
- Host dashboard: `exportGenerating` used `||`, so a one-half export failure stuck on
"wird erstellt…" forever and never showed the re-release hint. Changed to `&&`.
MEDIUM
- Locked-upload auto-resume was unreliable (`event-opened` has no reconnect replay and SSE
is down on non-feed pages) — now also resumes on `feed-delta`, which fires on every SSE
reconnect.
- Queue-cap eviction could drop a recoverable locked item (parked as `error` with a live
blob) — now evicts only `done`/`blocked`.
- Host page async-`onMount` leaked SSE handlers if unmounted mid-load — added a `destroyed`
guard before registration.
LOW
- An unparseable 403 body now keeps the blob (reversible) instead of purging it.
- `refreshEventState` is sequence-guarded so a late close-refresh can't clobber a reopen.
- `/export/status` moved out of the all-or-nothing `reload()` so its failure can't blank the
whole host dashboard.
Verified: svelte-check 0 errors, 36 frontend unit tests (incl. new displacement guards).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Follows the perf + security + user-flow work with a role/persona audit (guest, host,
admin, projector) and fixes across three review rounds. Highlights:
HIGH
- Ban now replays on reconnect. A ban isn't a soft-delete, and the `user-hidden` SSE has
no replay, so a client that missed it (esp. the unattended diashow) kept cycling a
banned user's slides. New `uploads_hidden_at` (migration 013) + `hidden_user_ids` in
/feed/delta; feed + diashow evict those users. Applied even on a truncated delta.
MEDIUM
- Locked-upload data loss: a photo staged offline during a lock/release was purged as a
terminal 4xx and lost when the host reopened. New reversible `uploads_locked` error code;
the queue keeps the blob and auto-resumes on the `event-opened` SSE.
- Reopen after release now warns (ConfirmSheet) that it revokes the published keepsake.
- Host "forgotten-PIN" badge updates live (`pin-reset-requested` was broadcast but never
in KNOWN_EVENTS / subscribed); host page also refetches on `pin-reset` so a two-host
race can't hand out a conflicting PIN.
- Ban modal copy fixed (read-only ban, not "session ended"); Degradieren/Sperren/Entsperren
hidden on peer-host rows for non-admins (they always 403'd).
- Host dashboard shows live keepsake generation progress / ready state + link to /export.
- Admin JWT moved to sessionStorage (§11.1) to bound exposure on shared devices.
Export generation guard (H1 from the prior round, hardened): per-(event,type) `release_seq`
(migration 012) with seq-guarded claim/finalize/mark_failed/update_progress, per-generation
temp/final paths, download follows `file_path`, prune only strictly-older generations.
LOW: diashow coalesces upload-processed (avoids self-rate-limit); event-closed reconciles
galleryReleased; /recover gains a forgot-PIN request + drops a stale cached PIN on 401;
delta `>=` tie-break + 429 retry; misc copy/labels.
Adds e2e: ban-replay, upload-lock-code, and rewrites export-reopen-rerelease with a
data-completeness test. Reconciles USER_JOURNEYS §9/§11.
Verified: cargo build clean, 40 unit tests, svelte-check 0 errors, 33 frontend unit
tests, 155 e2e passing on chromium-desktop.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Security audit follow-up. No Critical/High existed; these close the
Medium/Low findings.
F1 [Med] Host privilege boundary: a host could demote a peer host to
guest and then ban / PIN-reset (→ account takeover via /recover) them,
because the ban/pin-reset peer guards key off the target's *current*
role. set_role now blocks a non-admin from demoting a host.
F2 [Med] Moderation now revokes preview/thumbnail access: they are served
through visibility-checked aliases (/api/v1/upload/{id}/{preview,
thumbnail}) that filter soft-deleted / ban-hidden uploads, and direct
/media/previews|thumbnails is 404-blocked. Feed emits the gated URLs;
Caddy keeps them privately cacheable (max-age=300, short so moderation
revokes promptly — the live feed already evicts cards via SSE). Uses a
lean find_visible_media() (paths+mime only) on the media hot path.
F3 [Med/Low] npm audit fix: svelte 5.55.1→5.56.4 (SSR-XSS advisories),
devalue 5.6.4→5.8.1 (DoS). Prod deps: 0 vulnerabilities.
F4 [Low] /recover no longer leaks account existence: unknown display name
returns the same 401 as a wrong PIN, and runs a dummy bcrypt verify so
timing matches — closing the enumeration + timing oracle.
F5 [Low] SSE streams re-validate the session every ~60s and close once it
is logged out / expired, instead of running until client disconnect.
F6 [Info] X-Content-Type-Options: nosniff set at the app layer on all
media responses (defense-in-depth alongside the edge).
Tests: new e2e specs for F1 (host cannot demote peer host), F2 (preview
gated + 404 after delete + direct /media blocked), F4 (uniform 401).
40 backend unit tests + 182 e2e passing.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Performance:
- Cache the runtime `config` table in-memory (ConfigCache) with synchronous
invalidation on every write (admin PATCH + test reseed). Was re-reading each
key from Postgres on every request (~8 round-trips per upload).
- Stream uploads chunk-by-chunk to a temp file instead of buffering the whole
body in RAM (peak was up to the per-class cap, e.g. 500 MB/video); only 512
sniff-bytes are kept for magic-byte detection, then atomic rename into place.
- Cache the media-filesystem disk snapshot (DiskCache, 15s TTL) shared by the
quota check and admin stats; drop the discarded System::refresh_all().
- HTML export streams video (and small-image) originals straight into the ZIP
via a manifest instead of copying them to a temp dir first (removed the
transient 2x disk usage) and drops the double directory scan.
- Auth extractor resolves session -> live user in one JOIN (was two queries),
touching last_seen_at by token hash.
Stability:
- SSE: on broadcast lag, emit a `resync` event so the client runs a delta
fetch instead of silently losing events; frontend reconciles adds, deletions,
and (via an in-place refresh) like/comment counts on visible cards.
- Storage quota fails OPEN when the disk can't be read (was a 0-byte limit that
locked out all uploads).
- Graceful shutdown drains in-flight requests on SIGTERM/SIGINT, bounded by a
10s backstop so open SSE streams can't stall a deploy.
- Upload removes the persisted file if the DB transaction fails (no orphaned
bytes with no row to reclaim them).
Tests:
- New pure select_disk() with 5 unit tests (longest-prefix, fallbacks, fail-open).
- New e2e export-video spec covering the HTML export's video-streaming branch.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A comprehensive role-based E2E audit (guest/host/admin, across browser
sessions) surfaced one critical and several smaller issues; this addresses
them and hardens the tests that missed them.
Critical
- The client upload pipeline was fully broken: the IndexedDB v1->v2 upgrade
opened a *new* transaction inside the upgrade callback, which throws during
a version-change transaction and aborted the whole upgrade, leaving the
queue object store uncreated -- so no UI upload ever fired. Reuse the
version-change transaction the callback provides, and bump the DB to v3 with
a contains() guard so installs already corrupted by the shipped bug
self-heal on next load. Re-enabled the previously-fixme'd UI upload E2E test.
High / Medium
- Event lock is uploads-only again: likes, comments and browsing stay open
while the event is locked (USER_JOURNEYS 9.3 / FEATURES) -- it was wrongly
freezing social interaction. Updated the event-lock spec accordingly.
- get_original now excludes soft-deleted and ban-hidden uploads, and direct
/media/originals/** serving is blocked, so a hidden user's originals can no
longer be pulled by UUID (all originals go through the checked alias).
- The upload handler reads the file field with an early-abort size cap chosen
from the declared content-type, instead of buffering the entire body before
the size check.
Low
- unban_user mirrors the ban role guard (a host can no longer unban a
host/admin banned by an admin).
- reset_user_pin's UPDATE is event-scoped.
- Admin login returns and stores a real identity (user_id + display name)
instead of a blank session.
- The host user list no longer renders target-actions (ban/promote/demote/PIN)
on the caller's own row, where the backend always rejected them.
- /diashow gains a client-side auth guard like the other protected routes.
- The join page shows the event name via a new public GET /api/v1/event.
Verified: backend cargo build clean, frontend svelte-check 0 errors, full
Playwright E2E suite 144 passed / 1 skipped.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Whole-stack review round 2: repair the broken comment button (CR1) and close
the unauthenticated export-archive leak (CR2); read-only ban model + failed-
compression cleanup + live SSE eviction (H1/H2/H3); config validation, a11y,
and hygiene (medium/low). Includes re-review follow-ups: ban guard on
edit/delete handlers, KNOWN_EVENTS registration for user-hidden/comment-deleted,
and a strengthened real-export leak test (+ truncate export-dir isolation).
Verified: backend 35 unit tests; svelte-check 0 errors; full chromium e2e
143 passed / 2 skipped / 0 failed.
The prior test asserted 404 on /media/exports/Gallery.zip against an empty
stack — it would pass even if exports were still written under /media, because
no archive was ever produced. Now it:
1. seeds an upload, releases the gallery, and polls until the real zip job
writes Gallery.zip to disk;
2. asserts the archive is NOT served from public /media (the CR2 leak); and
3. asserts it IS retrievable via the gated ticket endpoint (200 + PK zip
magic) — proving the 404 means "not public", not "no file".
Also fixes a test-isolation gap the CR2 relocation introduced: __truncate wiped
media_path but not export_path, so a real export would leave Gallery.zip on disk
and break export.spec's "ready-but-file-missing → 404" test. truncate_all now
purges export_path too. Full 06-export dir: 5/5 green, no contamination.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The round-2 re-review (full suite green) found two real defects the passing
tests missed, both now fixed and covered:
B1 — banned users could still edit/delete their OWN content: edit_upload,
delete_upload, delete_comment skipped the is_banned guard that upload/
like/comment got (round-2 removed the global extractor block and missed
these three). Added the guard (using auth.is_banned — no extra query).
The moderation ban test now asserts 403 on DELETE upload, PATCH upload,
and DELETE comment for a banned owner (+ upload survives) — it previously
only exercised POST /upload, which is why the gap shipped green.
B2 — H3 live-eviction was dead code: 'user-hidden' and 'comment-deleted' were
missing from KNOWN_EVENTS, so EventSource never listened and the handlers
never fired. Added both. New browser-driven sse-eviction test asserts a
hidden user's card actually evicts from an open feed with no reload — the
backend-only SseListener checks couldn't catch this.
Minor items folded in:
- admin dashboard bounces a mid-session-demoted admin to /feed via live
/me/context (mirrors the host page) instead of a dead error screen.
- feed "new posts" pill cleared on any full refresh (pull-to-refresh no longer
strands it).
- corrected the stale sse.rs comment (banned users may hold a read-only stream).
Verified: backend 35 unit tests; svelte-check 0 errors; e2e 04-host + comment-ui
+ export-leak 13/13 on chromium (incl. the two new regression tests).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- compression_concurrency wired to boot config (state.rs) and removed as a
dead admin control.
- patch_config gains per-key integer/range validation so numerically-valid-but-
nonsensical values (-1/NaN/3.5) are rejected instead of silently reverting to
default at read time.
- clearAuth now also clears the display name (shared-device residual).
- e2e/Caddyfile.test mirrors prod security headers + the SSE encode-exclusion so
the test stack is representative and can catch header regressions.
- .gitignore: ignore root-level Playwright artifacts (test-results/, report).
- docs: USER_JOURNEYS §10 and SECURITY-BACKLOG updated to match the implemented
read-only-ban behavior and the export-path fix.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
H1: corrected a round-1 over-reach. Bans are read-only per USER_JOURNEYS §10:
the base AuthUser extractor no longer rejects banned users (they keep read
access); Require{Host,Admin} and write handlers enforce the ban via
auth.is_banned → 403 (incl. self-unban). Demoted hosts still lose powers
immediately (live DB role) and are bounced off the dashboard. Also fixed the
login/recover redirect regression on unauthenticated 401.
H2: failed compression now self-heals instead of leaving a permanent broken
card — refund the quota, delete the orphaned original, soft-delete the row;
the frontend toasts the uploader and evicts the card on upload-error.
H3: self-delete, ban-with-hide (user-hidden), and comment-deletes now broadcast
SSE; feed, diashow, and lightbox evict the affected content live instead of
waiting for a reload. sse-eviction.spec.ts covers it.
Riders: feed/+page.svelte also carries the medium truncated-delta pill; host.rs
also carries the low atomic release_gallery claim; admin/+page.svelte also drops
the dead compression_concurrency control (medium).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
CR1: the lightbox comment button POSTed to /upload/{id}/comment (singular);
no such route exists, so every UI-submitted comment 404'd and was lost.
Fixed to /comments (plural). The prior e2e passed because its seed helper
POSTs the API directly — added comment-ui.spec.ts which drives the real
component so this can't regress silently again.
CR2: export archives (Gallery.zip / Memories.zip / HTML viewer) were written
under media_path, which is a public ServeDir — so GET /media/exports/
Gallery.zip served the entire event (every photo, caption, comment,
uploader name) to any anonymous visitor at a guessable URL, bypassing the
ticket + release gate. Moved exports to a separate EXPORT_PATH (=/exports)
on its own volume (Dockerfile chown, compose volume, gated handler reads
the new path). export-leak.spec.ts asserts /media/exports/Gallery.zip → 404.
Riders (git can't split hunks): LightboxModal also gains H3 live-eviction on
comment-deleted/upload-deleted; config.rs also wires compression_concurrency
from boot config (medium).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Re-review follow-ups (non-blocking quality items):
Tests:
- moderation H1 specs now assert exact `→ 403` instead of bare .rejects.toThrow(),
so a spurious 500 can no longer masquerade as "revocation worked".
- config: added case-insensitivity (upper/mixed-case placeholder) and the
len==32/31 boundary cases for validate_secrets.
- rate_limiter: added the trailing-comma empty-entry case for client_ip (must
fall back, not return "").
(Backend unit tests: 35 pass.)
Docs:
- README: note that with APP_ENV=production a placeholder .env makes the app
refuse to boot and Caddy wait unhealthy — reason is in `docker compose logs app`.
- SECURITY-BACKLOG + sse.rs comment: document that a mid-session ban does not
tear down an already-open SSE stream (new tickets are blocked; low blast radius).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Two items surfaced by the branch re-review:
CSP regression (blocking): script-src 'self' blocked the template-authored
anti-FOUC theme script in app.html — SvelteKit's mode:'auto' only hashes
scripts it injects. Added nonce="%sveltekit.nonce%" so it's substituted per
request and included in the CSP (survives future edits, unlike a pinned hash).
Verified: emitted CSP nonce matches the script tag; no violation, no flash.
feed_delta silent truncation: the LIMIT 200 (added earlier to kill the
stale-`since` DoS) returned only the newest slice with no signal, so a client
that missed 200+ uploads during a reconnect could not tell it should full-
refresh — the older missed uploads were dropped and unrecoverable (the next
delta advances `since` past them). DeltaResponse now carries `truncated`; the
feed's feed-delta handler calls loadFeed(true) to resync from page 1 instead
of merging a partial slice.
Verified: cargo check clean, svelte-check 0 errors, production build green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
H1: auth extractor re-reads the live user row — trusts the DB role (not the
JWT claim) and rejects banned users mid-session. e2e proves a demoted
host loses powers and a banned host is locked out and can't self-unban.
H2: client_ip takes the right-most XFF hop (the one Caddy appends); spoofed
left-most entries are ignored, restoring IP-based throttles.
H3: Caddy excludes /api/v1/stream from `encode` so SSE isn't buffered.
H4: upload — quota increment + row insert + hashtag links now one txn.
H5: feed keyset pagination tiebroken on (created_at, id) + composite index
(migration 010); feed_delta bounded with LIMIT.
H7: LightboxModal keys its comment load off upload.id, ending the
SSE-driven refetch storm.
H8: CSP via SvelteKit kit.csp (svelte.config.js) hardens the localStorage
token model against injection.
Migration 010 also adds the latent comment/comment_hashtag indexes.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
C1: reset_user_pin wrote to a non-existent column (pin_failed_attempts);
the real column is failed_pin_attempts, so every PIN reset 500'd. Fixed
the column name; new e2e (pin-reset.spec.ts) proves a reset returns a
usable PIN and the target can recover with it.
C2: config.rs::validate_secrets now rejects placeholder-ish secrets
(change_me/dev_secret/placeholder), enforces len>=32 in prod, and
requires a real ADMIN_PASSWORD_HASH. docker-compose.yml sets
APP_ENV=production so the guard actually runs. Corrected the false
"fixed" claim in SECURITY-BACKLOG.md. .env.example documents the rule.
Riders in these files (documented here since git can't split hunks):
- host.rs also carries the event-scoped ban_user fix and the
close_event/open_event no-op broadcast guard (medium).
- docker-compose.yml also adds ORIGIN (H6), app/frontend healthchecks with
Caddy waiting on health, and per-service memory limits (medium).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The two filter-search cases were test.fixme placeholders (expect(true).toBe(true)),
so the OR/AND chip rules were untested.
- Extract the grid-filter predicate from feed/+page.svelte into a pure
filterUploads(uploads, filters) in $lib/feed-filter (behavior-preserving) and
unit-test it (9 cases): tag OR, user OR, tag+user AND, AND-excludes-partial,
case-insensitive caption match, null caption.
- Replace the e2e fixmes with real tests that seed known captions/uploaders, switch
to grid view, activate chips via the search suggestions, and count grid tiles:
OR widens 1→2, AND narrows 2→1.
Frontend unit: 27 passing. filter-search e2e: 3 passing.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Follow-ups from the code review of the test-quality batches:
- Consolidate duplicated helpers into e2e/helpers/: seed.ts (seedUpload,
seedComment, listComments, findFeedRow) and sse.ts (mintSseTicket, openStream,
trackStreamOpens). Refactor authorization-deep, xss-injection, like-comment,
sse-ticket-abuse, ddos, sse-realtime, multi-tab, and SseListener to use them —
the upload/comment/ticket-flow contracts now live in one place each instead of
being re-inlined across 3–7 specs.
- xss-injection display-name loop: it navigated to /feed (which renders uploader
names, not the viewer's) so "nothing fired" passed vacuously — the payload was
never rendered. Now navigate to /account (the actual sink) and add a render
guard asserting the payload reached the DOM as escaped text before checking
__xssFired.
- sse-realtime reconnect: snapshot the stream-open count AFTER backgrounding, so
the "new connection" assertion is attributable to the foreground event and can't
be satisfied by a spurious native/error reconnect before the toggle.
- recover-page: correct the comment (auto-submit is the onPinInput handler, not an
$effect).
44 affected specs verified green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The "429 from server is surfaced (no infinite retry storm)" test routed
`**/api/v1/feed`, but the app requests `/api/v1/feed?limit=20` — a plain glob
without a trailing wildcard doesn't match a URL with a query string, so the
route never fired: `attempts` stayed 0 and `expect(attempts).toBeLessThan(15)`
passed trivially. The test never forced a 429 or exercised any retry behavior.
Fix: match with a regex `/\/api\/v1\/feed(\?|$)/` (catches the query-string URL,
excludes /feed/delta), and gate on `attempts >= 1` before judging retry
behavior so it can't pass again without actually hitting the throttled endpoint.
Found during self-review of the test-quality batches.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Stable data-testid for ContextSheet (drops animation-class coupling), aria-label
like-button locator, exact stats count, and poll-until-stable instead of a fixed
3s sleep in the 429 retry test.
- ContextSheet: add data-testid="context-sheet". longpress tests targeted the
open sheet via the `.translate-y-0` animation class (breaks on any animation
refactor) — now target `[data-testid="context-sheet"][aria-modal="true"]`,
which is stable and unambiguous vs. the centered LightboxModal (also aria-modal).
- toast-on-failure: the like button was `button.filter(hasText:/\d+/).first()`,
which could match any digit-bearing button (e.g. the comment count) → use the
stable aria-label "Gefällt mir".
- config stats: assert the exact user_count (4 = 3 seeded guests + admin) instead
of `>= 3` — deterministic after the per-test truncate, catches under/overcount.
- offline-network 429 test: replace the fixed 3s waitForTimeout with a
poll-until-the-retry-count-stabilizes (faster, and a real storm never stabilizes
→ the poll fails, which is the intended outcome).
Note: reviewed the "config restore not in try/finally" finding — it's a non-issue.
The truncate auto-fixture wipes+reseeds the whole config table (and clears the
rate limiter) before every test, so config state cannot leak between tests.
All affected specs verified green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Add a fast, DB-free unit layer: backend #[cfg(test)] modules for the rate
limiter, SSE ticket store, and hashtag boundaries; frontend Vitest (with an
$app/environment stub) for avatar and pickMediaUrl logic. 20 backend + 11
frontend tests, all green.
The suite was almost entirely e2e; pure logic had no direct coverage. Add fast,
DB-free unit tests on both sides.
Backend (cargo test — inline #[cfg(test)] modules):
- rate_limiter: allow-up-to-max-then-block, per-key independence, sliding-window
expiry, retry-after bounds, clear(), and client_ip X-Forwarded-For parsing
(first entry / whitespace-trim / fallback).
- sse_tickets: single-use consume (replay → None), unknown ticket, uniqueness +
hex shape, prune keeps fresh tickets, and an expired ticket (injected past-TTL
entry) consumes to None.
- hashtag: fill the boundary gaps the 3 existing tests missed — stop-at-non-word,
the 40-char cap (drops, doesn't truncate), no-dedup contract, and the German
umlaut truncation limitation (pinned so a future Unicode fix is deliberate).
Frontend (Vitest — new, standalone config that stubs $app/environment so
server-safe module paths import cleanly under node):
- avatar: avatarPalette (neutral for empty, deterministic, real palette entry) and
initials (?, single word, two words, whitespace collapse).
- data-mode-store: pickMediaUrl across original/saver modes and the
preview→thumbnail→original fallback chain.
- `npm run test:unit` script added.
Backend: 20 passing. Frontend: 11 passing. svelte-check: 0 errors.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Fix the SSE listener (ticket flow) and replace assert-nothing tests with real
coverage: like toggle/count semantics, comment→SSE delivery, SSE reconnect on
visibility change, per-tab SSE connection, and remove a safe-area no-op.
Several tests ran green while asserting nothing. Replace them with real
assertions, and fix the SSE helper they depend on.
sse-listener: exchange the JWT for a single-use ticket (POST /stream/ticket) and
connect via ?ticket= — the helper still used the dead ?token= scheme, so every
SSE-based assertion would have silently failed to receive events.
like-comment:
- "like is idempotent" asserted nothing (void feed; void b) → now seeds a real
upload and pins the like contract: counted once per user, toggles off on repeat
(guards double-count), and a second user's like is counted independently.
- "comment → SSE to B" asserted length >= 0 (always true) → B now subscribes to
the stream, A comments, and B must receive the new-comment event for that upload
(comment_count === 1). ~30s due to reverse-proxy SSE buffering; timeout raised.
sse-realtime: only checked a nav link was visible → now counts EventSource opens
and asserts a fresh stream connection after hidden→visible (also fixes the sim,
which set visibilityState but not document.hidden, so the close never fired).
multi-tab "SSE delivers to both": only checked nav links → now asserts each tab
opens its own stream connection (delivery isn't asserted — it hinges on the ~30s
proxy buffering; connection establishment is the reliable, honest signal).
safe-area: delete the /join probe whose only assertion was Array.isArray(x) ===
true (always true); the real sheet-level env() check already exists below it.
All verified green against the live backend.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Add stored-XSS coverage for captions and comments (inert-render assertions) and
a new SSE-ticket-abuse spec (auth-required mint, single-use replay rejection,
garbage-ticket rejection).
Close two malicious-input gaps flagged in the suite review: XSS was only fuzzed
through display_name, and the SSE ticket flow had no security assertions.
xss-injection:
- Stored XSS in captions — upload with each XSS payload as the caption, mark it
feed-visible, render /feed and assert window.__xssFired stays false, no dialog
fires, and no live `img[onerror]`/`<script>` element is produced (Svelte escaping
renders it as inert text). A trailing CAPMARK gates the assertion on the caption
actually having rendered, so it can't pass vacuously.
- Stored XSS in comments — post the two render-executing payloads as a comment,
open the lightbox (which loads comments) and assert the same inert-render props.
sse-ticket-abuse (new):
- Minting a ticket requires auth (POST /stream/ticket without Bearer → 401).
- Single-use: after the first open consumes the ticket, replaying it → 401 (a 200
would be capability replay). The first open (→200) also proves a fresh ticket works.
- An unminted/garbage ticket → 401.
All verified green against the live backend.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Turn accept-both-outcomes documentation tests into pinned secure-behavior
assertions (SVG stored-XSS→400, zero-byte→400, path-traversal→201, export→404),
and replace fake-UUID authz tests with real cross-user IDOR coverage (comment
delete, upload delete, caption edit all → 403 with no state change).
Turn "accept-both-outcomes" documentation tests — which pass whether the app is
secure or vulnerable — into assertions that pin the secure behavior, and replace
fake-UUID authz tests that 404'd before ever reaching the ownership guard with
real cross-user resources.
file-upload-attacks:
- SVG-with-<script> → pin 400 (infer returns None for text → stored-XSS defense);
was [201,400], which accepted the vulnerable outcome.
- zero-byte → pin 400; path-traversal → pin 201 with UUID-derived storage and a
no-path-echo check (both were [201,400]).
- Fix the application/octet-stream rationale (no "application bypass" exists — the
handler ignores the declared type and keys off magic bytes).
authorization-deep (IDOR):
- B deleting A's comment: seed a real upload+comment as A, assert 403, assert the
comment survives, and assert the owner (A) still gets 204 — proving the 403 is
about identity, not a broken route. (Was a DELETE on the all-zeros UUID → 404
before the user_id guard, so authorization was never exercised.)
- Add B-deletes-A's-upload (403, countUploads unchanged) and B-edits-A's-caption
(403, caption intact) — the find_by_id_and_event + ownership guards.
export: pin the ZIP-download 404 (was [404,200] — a 200 is a data-exposure
regression) and split into the two real branches: not-yet-ready, and
ready-but-file-missing (new db.setExportZipReady helper).
All 21 assertions verified green against the live secure backend.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Gate always-mounted sheet dialog semantics on open state; fix focus-trap Escape
drop and deep-link back navigation; update the e2e suite for shipped magic-byte
validation, SSE ticket flow and PIN auto-submit; gate Chromium-only permissions.
The running test container had been built from an older tree; rebuilding it to
pick up current app code surfaced several tests that predated shipped
security/UX features:
- file-upload-attacks / rate-limit: assert the magic-byte rejection wording and
upload a real decodable JPEG (a zero-buffer is now rejected at the boundary).
- ddos: open SSE via the single-use /stream/ticket flow, not the dead ?token=.
- recover-page / join: the PIN field auto-submits on the 4th digit, so don't
race an explicit submit click against the ensuing navigation.
- gestures-doubletap / sheet-escape: target the lightbox by aria-labelledby and
anchor the radio accessible-name match at the start (gated dialog semantics).
playwright.config: camera/mic/clipboard are Chromium-only permissions (they threw
"Unknown permission: camera" on firefox/webkit and failed the test at context
creation); grant them per-Chromium-project. firefox-android drops the
unsupported isMobile flag.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
focus-trap: focus the trapped container synchronously on mount instead of
only after a deferred rAF. The keydown listener is node-scoped, so an Escape
pressed before the rAF moved focus into the sheet landed on an element outside
the node and was silently dropped — a real keyboard-a11y gap (open a sheet,
immediately press Escape → nothing happened). The rAF still refines focus to
the first control once laid out.
recover: replace the `window.history.length > 1` back-chevron heuristic with
SvelteKit's afterNavigate `from` signal. history.length is 2 on a fresh-tab
deep link (about:blank + page), so history.back() landed on the blank entry.
`from` is null only on a full-page load, so deep-linked users now correctly
fall back to /join (or /feed when authed).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
ContextSheet and UploadSheet stay mounted (slid off-screen via translate-y) when
closed, but declared role="dialog" + aria-modal="true" — and kept their buttons
in the a11y tree + tab order — unconditionally. So a screen reader always saw
2+ simultaneous modal dialogs, and their controls (e.g. each sheet's "Abbrechen")
collided with real open dialogs.
Surfaced by the e2e a11y suite: focus-trap asserted exactly one [role=dialog]
[aria-modal] and got 2; upload-cancel-confirm's getByRole('button',{name:
'Abbrechen'}) matched the composer's X *and* a closed sheet's button.
Fix: when closed, drop role/aria-modal and mark the subtree aria-hidden + inert
so it's out of the a11y tree and tab order entirely. Open sheets are unchanged.
Verified: chromium-mobile a11y/gesture suite now 21 passed / 5 skipped / 0 a11y
failures (focus-trap + upload-cancel-confirm green); svelte-check 0 errors.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Ports the parts of the 2026-06-27 security audit that were not already absorbed
into main:
- compression.rs: image::Limits decode cap (decompression-bomb DoS guard)
- docs/SECURITY-BACKLOG.md: triaged backlog reconciled against main
- docs/DECISION-media-auth.md: unauthenticated-UUID vs signed-gateway writeup
Verified: cargo build clean.
From the 2026-06-27 audit branch (fix/audit-2026-06-27-critical-medium), whose
work was ~80% absorbed into main via the batch branches. This ports the pieces
that were NOT in main:
- compression.rs: cap image decode with image::Limits (12000x12000, 256 MiB
max_alloc) via ImageReader instead of image::open(). The upload body-size cap
bounds the file on disk but not the *decoded* dimensions, so a small
decompression-bomb image could OOM the box during decode/resize. Surgical port
of the audit's decode guard only (not its image/video semaphore split).
- docs/SECURITY-BACKLOG.md: the audit's triaged backlog, reconciled against main
(each item tagged done / open / contingent-on-signed-media). Records the still-
open items: host moderation UI gap, owner-delete SSE broadcast, quota
mount-detection (starts_with) + low-disk guard.
- docs/DECISION-media-auth.md: writes up the one real architectural divergence —
main serves media unauthenticated (ServeDir + UUID-capability) while the audit
built a signed/TTL'd gateway. Lays out the tradeoff (leaked URL = permanent vs
~24h access; banned-user access) and a recommendation, for a human decision.
Verified: cargo build clean.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>