30 Commits

Author SHA1 Message Date
fabi
5d21b3eefd Merge test/filter-search: grid filter OR/AND coverage (pure fn + unit + e2e)
Some checks failed
E2E / Playwright E2E (chromium-desktop) (push) Failing after 6m10s
E2E / Cross-UA smoke matrix (push) Failing after 2m25s
2026-07-01 20:08:28 +02:00
fabi
74849c8d50 test: cover grid filter OR/AND (extract pure fn + unit + real e2e)
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>
2026-07-01 20:08:28 +02:00
fabi
6ed0aaf0d7 Merge test/broaden-unit-coverage: quota formula + auth JWT decode unit tests 2026-07-01 19:53:03 +02:00
fabi
226e455328 test(unit): broaden coverage — quota formula + auth token/JWT decode
Backend: extract the per-user quota formula from compute_storage_quota into a
pure `quota_limit_bytes(free_disk, tolerance, active)` (behavior-preserving) and
unit-test it: tolerance scaling, floor of fractional results, active<1 clamped to
1 (divide-by-zero guard), zero free disk, single-uploader identity.

Frontend (jsdom + browser:true mock): auth.ts token storage and JWT claim decode
— setAuth/getToken/getPin round-trip, clearAuth keeps the PIN (for recovery),
clearPin, getExpiry (exp seconds→ms Date; null on missing/malformed), getRole
(role claim; null on absent/malformed). Adds jsdom devDependency.

Backend: 25 passing. Frontend: 18 passing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 19:53:03 +02:00
fabi
2c44006392 Merge test/review-followups: dedup helpers + XSS render guard + SSE hardening 2026-07-01 19:49:44 +02:00
fabi
b1e2e66305 test(e2e): address self-review follow-ups (dedup, XSS render guard, SSE hardening)
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>
2026-07-01 19:49:44 +02:00
fabi
ec64fc361b Merge test/fix-vacuous-429-test: 429 retry test now actually fires 2026-07-01 19:33:28 +02:00
fabi
5f523d55fe test(e2e): fix vacuous 429 retry test (route never matched the feed)
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>
2026-07-01 19:33:28 +02:00
fabi
bbdb45155e Merge test/robustness-cleanup: stable locators + deterministic assertions
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.
2026-07-01 19:24:03 +02:00
fabi
564104ae23 test(e2e): robustness — stable locators, exact assertions, no fixed sleep
- 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>
2026-07-01 19:24:03 +02:00
fabi
104c3dde16 Merge test/unit-layer: backend cargo + frontend vitest unit tests
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.
2026-07-01 19:14:33 +02:00
fabi
723a492d44 test(unit): add a unit-test layer (backend cargo + frontend vitest)
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>
2026-07-01 19:14:33 +02:00
fabi
fabc6af656 Merge test/deflake-vacuous-tests: make vacuous feed/SSE tests real
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.
2026-07-01 19:05:53 +02:00
fabi
136417d6b4 test(e2e): make vacuous feed/SSE tests assert real behavior
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>
2026-07-01 19:05:53 +02:00
fabi
d4aa7b4932 Merge test/stored-xss-sse-abuse: stored-XSS + SSE-ticket abuse coverage
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).
2026-07-01 07:34:56 +02:00
fabi
8f6e1d4ff7 test(e2e): stored-XSS (caption/comment) + SSE-ticket abuse coverage
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>
2026-07-01 07:34:55 +02:00
fabi
da586d0978 Merge test/pin-security-assertions: pin security assertions + real IDOR
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).
2026-07-01 07:28:23 +02:00
fabi
20125fb713 test(e2e): pin security assertions + real cross-user IDOR coverage
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>
2026-07-01 07:27:22 +02:00
fabi
6ccf2d0011 Merge fix/sheet-aria-modal-gating: sheet a11y gating + test-suite hygiene
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.
2026-06-30 22:12:11 +02:00
fabi
a3c0082c4b test(e2e): update suite for shipped features + gate Chromium-only perms
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>
2026-06-30 22:12:05 +02:00
fabi
792a4f0e4b fix(frontend): robust Escape handling + deep-link back navigation
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>
2026-06-30 22:12:05 +02:00
fabi
b32231d4f4 fix(a11y): gate always-mounted sheet dialog semantics on open state
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>
2026-06-30 21:23:05 +02:00
fabi
1c7495e568 Merge fix/security-audit-port: image-decode DoS cap + audit backlog/media-auth docs
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.
2026-06-30 20:27:59 +02:00
fabi
d9025f783a fix(security): port image-decode DoS cap + audit backlog/media-auth docs
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>
2026-06-30 20:26:57 +02:00
fabi
a490642f5f Merge fix/security-review-batch-2: cross-event authz + upload OOM backstop
Brings the batch-2 security hardening into main (forked from the same base as
the UX batch; auto-merged cleanly — verified both sides' edits to social.rs /
main.rs coexist):

- Cross-event authorization: toggle_like / list_comments / add_comment now
  event-scope the upload via Upload::find_by_id_and_event (404 on cross-event
  access); delete_comment uses Comment::soft_delete_in_event. Closes the gap
  where a guest could like/comment/list across events by upload UUID.
- Upload OOM backstop: the /upload route gets DefaultBodyLimit::max(576 MiB)
  instead of disable(), so a multi-GB body can't be buffered before the
  handler's per-class size checks run.
- upload.rs per-class size-limit refactor, XSS allowlist, deploy hardening
  (Caddyfile, Dockerfiles, docker-compose, .env.example), and a data-mode
  doc-comment clarifying the original-media route is capability-(UUID-)gated.

The event-scope checks sit before, and batch-3's best-effort count broadcasts
after, the like/comment mutations — both preserved.

Verified: cargo build clean, svelte-check 0 errors.
2026-06-30 20:02:47 +02:00
fabi
8f5afb9df7 Merge feat/ux-review-batch-3: feed virtualization + UX review batch fixes
Squash of the branch's two commits:
- feat(eventsnap): UX review batch-3 — feed DOM-windowing virtualization,
  global safe-area/PWA/lang fixes, in-place SSE feed patching (+ backend count
  broadcast), ConfirmSheet on destructive host/admin actions, streamed export
  download, shared IconButton + scrollLock primitives, and a11y/UX polish.
- fix(feed): width-change measurement invalidation + best-effort SSE counts.

Verified: svelte-check 0 errors, frontend build clean, cargo build clean.
2026-06-30 19:51:11 +02:00
fabi
0d7938aff5 fix(feed): width-change measurement invalidation + best-effort SSE counts
Post-commit review follow-ups for the batch-3 feed work.

Frontend — VirtualFeed: the guarded setOptions keyed only on (count, scrollMargin),
so a rotation (or the first-paint 0->real container width) changed colWidth / card
heights without invalidating the cached measurements, leaving getTotalSize and the
scrollbar stale until each row scrolled back through the window. Track appliedWidth
and call virtualizer.measure() on a width delta so heights re-estimate at the new
width (rendered rows re-measure immediately via their ResizeObserver). Covers list +
grid and the first-paint 120px-estimate case.

Backend — social.rs: the fresh like/comment count SELECT used `.await?`, so a
transient DB failure would 500 the request after the like/comment had already
committed. Make the count + broadcast best-effort (if let Ok { ... }); the mutation
succeeds regardless and the next event / pull-to-refresh reconciles the count.

Docs — FOLLOWUPS: record the review findings left as-is (grid-prepend tile reflow,
filtered-grid auto-load which is pre-existing, comment-delete stale count, and the
last-write-wins count ordering note).

Verified: svelte-check 0 errors, cargo build clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 19:32:32 +02:00
fabi
e79e020566 feat(eventsnap): UX review batch-3 — feed virtualization, a11y/UX fixes, shared primitives
Frontend
- Feed: DOM-windowing via @tanstack/svelte-virtual (new VirtualFeed). The window
  virtualizer keeps the sticky header, pull-to-refresh, infinite-scroll sentinel and
  bottom nav working. List = dynamic measured heights keyed by upload id +
  anchorTo:start so an SSE prepend doesn't jump a scrolled reader; grid = measured
  square rows. Drops the content-visibility band-aid and the old FeedGrid.
  measureElement(null) on row unmount prevents ResizeObserver retention; stable
  option callbacks + guarded setOptions avoid O(n) re-measure on like/comment patches.
- Global: viewport-fit=cover (activates safe-area insets), lang=de, PWA manifest +
  maskable icon + apple-touch metas, prefers-reduced-motion, safe-area-top headers.
- Feed reactivity: like/comment SSE patch the single card in place; upload-processed
  debounced in-place merge; IntersectionObserver leak fixed; shared 60s clock.
- CLS: list cards reserve the skeleton aspect box.
- Destructive actions (promote/demote/unban, gallery release) routed through
  ConfirmSheet (host + admin).
- Export OOM: streamed download via single-use ticket instead of res.blob().
- Shared primitives: IconButton (44px hit area), scrollLock action; UploadSheet a11y.
- Polish: api timeout + non-JSON guard, focus-trap offsetParent fix, pull-to-refresh
  passive:false + guards, diashow keyboard a11y, Toaster assertive errors, dark-mode
  gaps, aria-pressed on like/chip state, CameraCapture mic-on-video + retry,
  ConfirmSheet spinner, upload beforeunload warning, emoji->SVG icons.

Backend
- social.rs: like/comment SSE broadcasts now carry the fresh count so feed clients
  patch one card in place instead of refetching page 1.
- admin.rs / main.rs: supporting changes for the above.

Verified: svelte-check 0 errors, frontend build clean, /feed SSR 200. Runtime feed
scroll-feel validation still owed (documented in FOLLOWUPS.md).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 19:16:48 +02:00
fabi
1bb58b59ad fix(security): re-review follow-ups — drop HEIC/HEIF, fix stale comment
Address the two items from the adversarial re-review of batch-2.

- upload: remove image/heic + image/heif from ALLOWED_MEDIA. Neither the
  `image` crate nor the bundled ffmpeg 6.1 (Alpine 3.21 — HEIF demuxer
  only landed in ffmpeg 7.0) can decode them, so accepting them stored
  posts that never got a thumbnail. iOS Safari transcodes HEIC->JPEG on
  file-input selection, so this rejects only the rare HEIC-preserving
  path, now with a clear error instead of a silently broken post.
- data-mode-store: correct the stale "auth-gated" comment — the
  /original route is intentionally unauthenticated (UUID-as-capability)
  so it works from plain <img src> / <video src>.

Re-verified: cargo build (only the pre-existing middleware.rs warning).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 19:48:46 +02:00
fabi
edcef0258c fix(security): batch-2 hardening — XSS allowlist, event-scoping, deploy
Address the seven findings from the security & deployment review.

High:
- upload: make infer authoritative — reject files it can't identify
  (SVG/HTML/JS) and require the detected MIME to be on an ALLOWED_MEDIA
  allowlist; derive the stored MIME and on-disk extension from the
  detected type, ignoring client filename/Content-Type. Closes the
  stored-XSS vector via media served on-origin.
- deploy: rename docker-compose.override.yml -> docker-compose.dev.yml
  so the default `docker compose up -d` no longer publishes Postgres
  5432 to the host; the port map is now opt-in via -f. README updated.

Medium:
- upload: DefaultBodyLimit::disable() -> max(576 MiB) as an HTTP-level
  OOM backstop; handler still enforces precise per-class size limits.
- docker: run backend and frontend as non-root users.

Low:
- social/upload: event-scope toggle_like, list_comments, add_comment,
  delete_comment, edit_upload, delete_upload via find_by_id_and_event /
  soft_delete_in_event — cross-event IDs now resolve to 404.
- Caddy: site-wide HSTS / nosniff / X-Frame-Options / Referrer-Policy,
  plus Content-Disposition: attachment on /media/originals/*.
- .env.example: replace default Postgres password with a CHANGE_ME hint.

Out of scope: localStorage JWT (root cause fixed; httpOnly cookies are a
larger change tracked separately).

Verified: cargo build (no new warnings), cargo test (3 passed),
caddy validate, docker compose config (no 5432 published by default).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 19:39:29 +02:00
86 changed files with 3513 additions and 541 deletions

View File

@@ -6,9 +6,11 @@ DOMAIN=my-event.example.com
APP_PORT=3000
# ── Database ──────────────────────────────────────────────────────────────────
DATABASE_URL=postgres://eventsnap:secret@db:5432/eventsnap
# Set a strong password and keep it in sync between DATABASE_URL and
# POSTGRES_PASSWORD. Generate one with: openssl rand -hex 24
DATABASE_URL=postgres://eventsnap:CHANGE_ME_use_a_strong_password@db:5432/eventsnap
POSTGRES_USER=eventsnap
POSTGRES_PASSWORD=secret
POSTGRES_PASSWORD=CHANGE_ME_use_a_strong_password
POSTGRES_DB=eventsnap
# ── Authentication ────────────────────────────────────────────────────────────

View File

@@ -1,26 +1,38 @@
{$DOMAIN} {
encode zstd gzip
encode zstd gzip
# SvelteKit frontend — static assets with long-lived cache (content-hashed filenames)
@hashed_assets path_regexp hashed /_app/immutable/.*\.[a-f0-9]{8,}\.(js|css|woff2)$
header @hashed_assets Cache-Control "public, max-age=31536000, immutable"
# Site-wide security headers (defense-in-depth). HSTS is free since Caddy
# already terminates TLS. nosniff also covers all of /media/*.
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Content-Type-Options "nosniff"
X-Frame-Options "DENY"
Referrer-Policy "strict-origin-when-cross-origin"
}
# Media previews and thumbnails
@previews path /media/previews/* /media/thumbnails/*
header @previews Cache-Control "public, max-age=3600"
# SvelteKit frontend — static assets with long-lived cache (content-hashed filenames)
@hashed_assets path_regexp hashed /_app/immutable/.*\.[a-f0-9]{8,}\.(js|css|woff2)$
header @hashed_assets Cache-Control "public, max-age=31536000, immutable"
# Original media files (private — only host can download)
@originals path /media/originals/*
header @originals Cache-Control "private, max-age=86400"
# Media previews and thumbnails
@previews path /media/previews/* /media/thumbnails/*
header @previews Cache-Control "public, max-age=3600"
# API — never cache
@api path /api/*
header @api Cache-Control "no-store"
# Original media files (private — only host can download). Force download
# rather than inline rendering as defense-in-depth against any future
# content-type confusion (previews/thumbnails are re-encoded and stay inline).
@originals path /media/originals/*
header @originals Cache-Control "private, max-age=86400"
header @originals Content-Disposition "attachment"
# Route API and media requests to the Rust backend
reverse_proxy /api/* app:3000
reverse_proxy /media/* app:3000
# API — never cache
@api path /api/*
header @api Cache-Control "no-store"
# Everything else goes to SvelteKit frontend
reverse_proxy frontend:3001
# Route API and media requests to the Rust backend
reverse_proxy /api/* app:3000
reverse_proxy /media/* app:3000
# Everything else goes to SvelteKit frontend
reverse_proxy frontend:3001
}

View File

@@ -46,6 +46,90 @@ is the smallest patch.
- [frontend/src/lib/components/Toaster.svelte](frontend/src/lib/components/Toaster.svelte) — add passthrough marker (if approach 2) or move to a portal (if approach 1)
- [frontend/src/app.html](frontend/src/app.html) — add `<div id="modal-root">` (if approach 1)
## Feed — DOM-windowing virtualization (IMPLEMENTED — residual validation owed)
**Status.** Implemented in [frontend/src/lib/components/VirtualFeed.svelte](frontend/src/lib/components/VirtualFeed.svelte)
using `@tanstack/svelte-virtual`'s `createWindowVirtualizer`. Both the **list**
view (dynamic `measureElement` heights, keyed by upload id with `anchorTo:'start'`
so an SSE prepend doesn't yank a scrolled-down reader) and the **grid** view
(three measured square tiles per row) now keep only the on-screen window (+overscan)
in the DOM instead of one node per upload. The window virtualizer scrolls the
document, so the sticky header, pull-to-refresh, the infinite-scroll sentinel and
the bottom nav are untouched. The earlier `content-visibility` band-aid was removed
from `FeedListCard` (it interferes with real-height measurement), and the old
`FeedGrid.svelte` was deleted (its sole consumer migrated to `VirtualFeed`).
**Verified.** `svelte-check` 0 errors, production build clean. The integration
follows the library's documented window-virtualizer contract (confirmed against
`virtual-core` source: item `start` includes `scrollMargin`, `getTotalSize()`
excludes it; the SSR path is guarded by `getScrollElement()` returning null).
**Residual validation owed (needs the running app — could not be done headless).**
- Manual scroll testing on a ~1000-item event: confirm no jank, correct scrollbar
size, and that an SSE `new-upload` / `feed-delta` prepend while scrolled down does
not jump the viewport (the `anchorTo:'start'` + id-key path).
- `scrollMargin` re-measure when grid filter chips change the header height (handled
reactively via the `uploads`-length-driven effect, but unverified visually).
- A new e2e spec that scrolls far down, likes an item via SSE, and asserts scroll
position is retained — the existing suite only asserts a single card is visible,
so it cannot catch a scroll regression.
**Files.**
- [frontend/src/lib/components/VirtualFeed.svelte](frontend/src/lib/components/VirtualFeed.svelte) — new windowing component (list + grid)
- [frontend/src/routes/feed/+page.svelte](frontend/src/routes/feed/+page.svelte) — renders `VirtualFeed` for both views
- [frontend/src/lib/components/FeedListCard.svelte](frontend/src/lib/components/FeedListCard.svelte) — `content-visibility` removed
**Known limitations (surfaced in the post-commit review, left as-is — low impact).**
- **Grid prepend reflows tiles.** Grid rows are index-keyed and pack 3 tiles each, so
an SSE `new-upload` shifts every tile by one position; `anchorTo:'start'` can only
anchor a scrolled grid reader when the prepend crosses a 3-item boundary (it adds a
*row*). List view is unaffected (one id-keyed row per upload). A fix would key rows
by the first tile's id and accept partial-row churn; not worth it for the rarer
"new upload while browsing the grid" case.
- **Filtered grid can auto-load the whole feed.** When a grid filter matches few items
the `VirtualFeed` is short, so the infinite-scroll sentinel sits in-viewport and
`loadMore()` fires until `nextCursor` is null — pulling all pages to widen the
client-side search. This is pre-existing (the old `FeedGrid` had the same shape, and
the empty-filter copy even says "scrolle weiter"), not a virtualization regression.
If undesired, gate auto-load to list view or to actual user scroll.
## Feed — comment deletion leaves a stale live count
**Problem.** `add_comment` now broadcasts a fresh `comment_count` so feed clients patch
the card in place, but `delete_comment` and `host_delete_comment`
([backend/src/handlers/social.rs](backend/src/handlers/social.rs),
[host.rs](backend/src/handlers/host.rs)) soft-delete without broadcasting any
count/event. So a deletion leaves the count too high on every client until a full
refetch (pull-to-refresh or an unrelated `upload-processed` merge). `toggle_like`
already broadcasts on both add and remove, so likes are fine — the gap is
comments-on-delete. Pre-existing, but the in-place-patch scheme makes it observable.
**Fix.** Emit a `new-comment` (or a `comment-deleted`) event carrying the refreshed
`comment_count` from both delete paths, the same best-effort way `add_comment` does;
the frontend `patchCount(..., 'comment_count')` handler already consumes it.
**Note — count ordering.** The broadcast count is read just after the (auto-committed)
mutation, not inside it, so under concurrent likes/comments on one upload the SSE
messages are last-write-wins. The frontend *replaces* (not increments) the count, so
steady state is correct and self-healing; only document this if strict per-event
ordering is ever required (then compute the count in-tx with a monotonic sequence).
## Feed — per-image exact CLS reservation
**Problem.** `FeedListCard` now reserves a default `aspect-[4/5]` box for photos so
the card doesn't collapse to height 0 and reflow as images stream in (matching
`Skeleton`). But no image dimensions are stored anywhere (not on `FeedUpload`, the
`upload` table, or any migration), so the box is a uniform guess that crops to fit —
the original is one tap away in the lightbox.
**Acceptance criterion.** Extract image width/height during the compression worker,
store them on `upload`, expose them on `FeedUpload`, and have the card reserve the
*true* aspect ratio (no crop, zero shift).
**Files to touch.**
- backend: `services/compression.rs`, `models/upload.rs`, `handlers/feed.rs`, a migration
- [frontend/src/lib/types.ts](frontend/src/lib/types.ts), [FeedListCard.svelte](frontend/src/lib/components/FeedListCard.svelte)
## Smaller nits, optional
- **Auto-submit on retried 4th digit.** [recover/+page.svelte](frontend/src/routes/recover/+page.svelte), [join/+page.svelte](frontend/src/routes/join/+page.svelte) — after a wrong PIN, deleting one digit and retyping triggers an immediate submit. Backend's 3-attempts/15-min lockout makes this safe; could feel hair-trigger after a typo. Consider gating the second auto-submit per input session behind an explicit button press.

View File

@@ -77,6 +77,7 @@ eventsnap/
│ ├── svelte.config.js
│ └── Dockerfile
├── docker-compose.yml
├── docker-compose.dev.yml # opt-in dev overlay (publishes Postgres on the host)
├── Caddyfile
└── .env.example
```
@@ -107,6 +108,11 @@ docker compose up -d
Caddy automatically obtains a Let's Encrypt certificate on first start. The app is live at `https://DOMAIN` within ~30 seconds.
> **Production note:** `docker compose up -d` does **not** expose the database — Postgres is reachable only on the internal Docker network. For local development where you need host access to Postgres, opt into the dev overlay explicitly:
> ```bash
> docker compose -f docker-compose.yml -f docker-compose.dev.yml up
> ```
### Generate required secrets
```bash

View File

@@ -20,8 +20,16 @@ FROM alpine:3.21
RUN apk add --no-cache ca-certificates ffmpeg
# Run as a non-root user. Pre-create and chown the media mount path so the fresh
# named volume inherits the non-root ownership (Docker seeds an empty named volume
# from the image directory, preserving its uid/gid) and uploads can be written.
RUN addgroup -S app && adduser -S app -G app
WORKDIR /app
COPY --from=builder /app/target/release/eventsnap-backend ./
RUN mkdir -p /media && chown -R app:app /app /media
USER app
EXPOSE 3000
CMD ["./eventsnap-backend"]

View File

@@ -1,7 +1,7 @@
use std::collections::HashMap;
use std::time::Duration;
use axum::extract::State;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::Json;
use serde::{Deserialize, Serialize};
@@ -223,11 +223,44 @@ pub async fn get_export_jobs(
// ── Export download endpoints (authenticated guests) ─────────────────────────
#[derive(Deserialize)]
pub struct DownloadQuery {
pub ticket: String,
}
/// Mint a short-lived ticket for a browser-driven export download. The download
/// is a top-level navigation so the multi-GB ZIP streams straight to disk instead
/// of being buffered in memory by `fetch()` + `blob()` — but a navigation can't
/// carry an `Authorization` header, so the client exchanges its Bearer token for
/// an opaque ticket here, then hits `/export/zip?ticket=...`. Reuses the same
/// single-use, 30s-TTL store as the SSE stream.
pub async fn export_ticket(
State(state): State<AppState>,
auth: crate::auth::middleware::AuthUser,
) -> Json<serde_json::Value> {
let ticket = state.sse_tickets.issue(auth.token_hash);
Json(serde_json::json!({ "ticket": ticket }))
}
/// Validate a download ticket (single-use) and confirm its session still exists.
async fn authenticate_download_ticket(state: &AppState, ticket: &str) -> Result<(), AppError> {
let token_hash = state
.sse_tickets
.consume(ticket)
.ok_or_else(|| AppError::Unauthorized("Ticket ungültig oder abgelaufen.".into()))?;
crate::models::session::Session::find_by_token_hash(&state.pool, &token_hash)
.await
.map_err(|e| AppError::Internal(e.into()))?
.ok_or_else(|| AppError::Unauthorized("Sitzung nicht gefunden.".into()))?;
Ok(())
}
pub async fn download_zip(
State(state): State<AppState>,
_auth: crate::auth::middleware::AuthUser,
Query(q): Query<DownloadQuery>,
headers: HeaderMap,
) -> Result<axum::response::Response, AppError> {
authenticate_download_ticket(&state, &q.ticket).await?;
enforce_export_rate(&state, &headers).await?;
let event = crate::models::event::Event::find_by_slug(&state.pool, &state.config.event_slug)
@@ -250,9 +283,10 @@ pub async fn download_zip(
pub async fn download_html(
State(state): State<AppState>,
_auth: crate::auth::middleware::AuthUser,
Query(q): Query<DownloadQuery>,
headers: HeaderMap,
) -> Result<axum::response::Response, AppError> {
authenticate_download_ticket(&state, &q.ticket).await?;
enforce_export_rate(&state, &headers).await?;
let event = crate::models::event::Event::find_by_slug(&state.pool, &state.config.event_slug)

View File

@@ -9,6 +9,7 @@ use crate::auth::middleware::AuthUser;
use crate::error::AppError;
use crate::models::comment::{Comment, CommentDto};
use crate::models::hashtag::{self, Hashtag};
use crate::models::upload::Upload;
use crate::state::AppState;
pub async fn toggle_like(
@@ -24,6 +25,12 @@ pub async fn toggle_like(
return Err(AppError::Forbidden("Du bist gesperrt.".into()));
}
// Event-scope: the upload must belong to the caller's event (404 otherwise),
// matching the host handlers' find_by_id_and_event pattern.
Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id)
.await?
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
// Try to insert; if conflict, delete (toggle)
let result = sqlx::query(
"INSERT INTO \"like\" (upload_id, user_id) VALUES ($1, $2)
@@ -43,11 +50,23 @@ pub async fn toggle_like(
.await?;
}
// Broadcast SSE
let _ = state.sse_tx.send(crate::state::SseEvent {
event_type: "like-update".to_string(),
data: serde_json::json!({ "upload_id": upload_id }).to_string(),
});
// Fresh count so feed clients can patch the single card in place instead of
// refetching page 1 (mirrors v_feed.like_count = COUNT(DISTINCT user_id)). The
// count + broadcast are a UI optimisation — the like itself is already committed,
// so a failure here must not fail the request. Swallow the error and skip the
// broadcast; the next event or a pull-to-refresh reconciles the count.
if let Ok(like_count) = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(DISTINCT user_id) FROM \"like\" WHERE upload_id = $1",
)
.bind(upload_id)
.fetch_one(&state.pool)
.await
{
let _ = state.sse_tx.send(crate::state::SseEvent {
event_type: "like-update".to_string(),
data: serde_json::json!({ "upload_id": upload_id, "like_count": like_count }).to_string(),
});
}
Ok(StatusCode::NO_CONTENT)
}
@@ -64,10 +83,15 @@ const COMMENT_PAGE_SIZE: i64 = 50;
pub async fn list_comments(
State(state): State<AppState>,
_auth: AuthUser,
auth: AuthUser,
Path(upload_id): Path<Uuid>,
Query(q): Query<ListCommentsQuery>,
) -> Result<Json<Vec<CommentDto>>, AppError> {
// Event-scope: only list comments for an upload in the caller's event.
Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id)
.await?
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
let comments =
Comment::list_for_upload(&state.pool, upload_id, q.before, COMMENT_PAGE_SIZE).await?;
Ok(Json(comments))
@@ -91,6 +115,11 @@ pub async fn add_comment(
return Err(AppError::Forbidden("Du bist gesperrt.".into()));
}
// Event-scope: only comment on an upload that belongs to the caller's event.
Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id)
.await?
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
let text = body.body.trim();
let text_chars = text.chars().count();
if text_chars == 0 || text_chars > 500 {
@@ -114,11 +143,24 @@ pub async fn add_comment(
.await?;
}
// Broadcast SSE
let _ = state.sse_tx.send(crate::state::SseEvent {
event_type: "new-comment".to_string(),
data: serde_json::json!({ "upload_id": upload_id }).to_string(),
});
// Fresh count so feed clients can patch the single card in place instead of
// refetching page 1 (mirrors v_feed.comment_count = COUNT(DISTINCT c.id); COUNT(*)
// over the same deleted_at filter is identical since comment.id is the PK). The
// count + broadcast are a UI optimisation — the comment is already committed, so a
// failure here must not fail the request. Swallow the error and skip the broadcast.
if let Ok(comment_count) = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(*) FROM comment WHERE upload_id = $1 AND deleted_at IS NULL",
)
.bind(upload_id)
.fetch_one(&state.pool)
.await
{
let _ = state.sse_tx.send(crate::state::SseEvent {
event_type: "new-comment".to_string(),
data: serde_json::json!({ "upload_id": upload_id, "comment_count": comment_count })
.to_string(),
});
}
let dto = CommentDto {
id: comment.id,
@@ -145,6 +187,11 @@ pub async fn delete_comment(
return Err(AppError::Forbidden("Nur eigene Kommentare löschen.".into()));
}
Comment::soft_delete(&state.pool, comment_id).await?;
// Event-scope: soft_delete_in_event only matches comments whose upload is in
// the caller's event, so a cross-event comment_id resolves to a 404 here.
let deleted = Comment::soft_delete_in_event(&state.pool, comment_id, auth.event_id).await?;
if !deleted {
return Err(AppError::NotFound("Kommentar nicht gefunden.".into()));
}
Ok(StatusCode::NO_CONTENT)
}

View File

@@ -16,6 +16,27 @@ use crate::state::AppState;
const MAX_CAPTION_LENGTH: usize = 2000;
/// Allowlist of accepted media types, keyed by the MIME that `infer` derives from
/// the file's magic bytes. The detected MIME (not the client-declared one) is what
/// we trust, store, and hand to the compression pipeline — so a text-based payload
/// (SVG/HTML/JS) can never be stored or served on-origin. Each entry maps to the
/// server-controlled file extension we persist the original under.
///
/// HEIC/HEIF are deliberately excluded: the preview pipeline (`image` crate, and
/// the bundled ffmpeg 6.1) cannot decode them, so accepting them would store files
/// that never get a thumbnail. iOS Safari already transcodes HEIC→JPEG when a photo
/// is selected via a file input, so this rejects only the rare HEIC-preserving
/// upload path — with a clear error rather than a silently broken post.
const ALLOWED_MEDIA: &[(&str, &str)] = &[
("image/jpeg", "jpg"),
("image/png", "png"),
("image/webp", "webp"),
("image/gif", "gif"),
("video/mp4", "mp4"),
("video/quicktime", "mov"),
("video/webm", "webm"),
];
pub async fn upload(
State(state): State<AppState>,
auth: AuthUser,
@@ -62,8 +83,6 @@ pub async fn upload(
let max_video_mb: i64 = config::get_i64(&state.pool, "max_video_size_mb", 500).await;
let mut file_data: Option<Vec<u8>> = None;
let mut file_name: Option<String> = None;
let mut content_type: Option<String> = None;
let mut caption: Option<String> = None;
let mut hashtags_csv: Option<String> = None;
@@ -71,8 +90,9 @@ pub async fn upload(
let name = field.name().unwrap_or_default().to_string();
match name.as_str() {
"file" => {
file_name = field.file_name().map(|s| s.to_string());
content_type = field.content_type().map(|s| s.to_string());
// Note: the client-declared filename and Content-Type are intentionally
// ignored — the stored MIME and extension are derived from the file's
// magic bytes below, so a mislabelled payload can't influence them.
file_data = Some(
field.bytes().await
.map_err(|e| AppError::BadRequest(format!("Datei konnte nicht gelesen werden: {e}")))?
@@ -96,7 +116,6 @@ pub async fn upload(
}
let data = file_data.ok_or_else(|| AppError::BadRequest("Keine Datei hochgeladen.".into()))?;
let mime = content_type.unwrap_or_else(|| "application/octet-stream".to_string());
let size = data.len() as i64;
// Validate caption length. Counted in chars (code points) to match the
@@ -111,22 +130,23 @@ pub async fn upload(
}
}
// Validate file MIME type using magic bytes
let detected_mime = infer::get(&data);
if let Some(detected) = detected_mime {
let detected_type = detected.mime_type();
// Ensure detected type is compatible with declared MIME type
let declared_category = mime.split('/').next().unwrap_or("");
let detected_category = detected_type.split('/').next().unwrap_or("");
// Only reject if categories don't match (e.g., image vs video)
if declared_category != "application" && declared_category != detected_category {
return Err(AppError::BadRequest(format!(
"Dateiinhalt entspricht nicht dem deklarierten Typ. Erwartet: {}, erkannt: {}",
mime, detected_type
)));
}
}
// Determine the file type from its magic bytes and require it to be on the
// allowlist. `infer` returns None for text-based payloads (SVG/HTML/JS), so
// those are rejected outright — closing the stored-XSS vector. Both the MIME
// we persist and the on-disk extension come from the detected type, never from
// client-supplied values.
let kind = infer::get(&data)
.ok_or_else(|| AppError::BadRequest("Dateityp nicht erkannt oder nicht unterstützt.".into()))?;
let (mime, ext) = ALLOWED_MEDIA
.iter()
.find(|(allowed, _)| *allowed == kind.mime_type())
.map(|(m, e)| ((*m).to_string(), *e))
.ok_or_else(|| {
AppError::BadRequest(format!(
"Dateityp wird nicht unterstützt: {}.",
kind.mime_type()
))
})?;
// Validate file size
let max_bytes = if mime.starts_with("video/") {
@@ -159,12 +179,6 @@ pub async fn upload(
}
}
// Determine file extension
let ext = file_name
.as_deref()
.and_then(|n| n.rsplit('.').next())
.unwrap_or(if mime.starts_with("video/") { "mp4" } else { "jpg" });
let upload_id = Uuid::new_v4();
let event_slug = &state.config.event_slug;
let relative_path = format!("originals/{event_slug}/{upload_id}.{ext}");
@@ -257,7 +271,7 @@ pub async fn edit_upload(
Path(upload_id): Path<Uuid>,
Json(body): Json<EditUploadRequest>,
) -> Result<StatusCode, AppError> {
let upload = Upload::find_by_id(&state.pool, upload_id)
let upload = Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id)
.await?
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
@@ -285,7 +299,7 @@ pub async fn delete_upload(
auth: AuthUser,
Path(upload_id): Path<Uuid>,
) -> Result<StatusCode, AppError> {
let upload = Upload::find_by_id(&state.pool, upload_id)
let upload = Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id)
.await?
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
@@ -293,7 +307,7 @@ pub async fn delete_upload(
return Err(AppError::Forbidden("Nur eigene Uploads löschen.".into()));
}
Upload::soft_delete(&state.pool, upload_id).await?;
Upload::soft_delete_in_event(&state.pool, upload_id, auth.event_id).await?;
Ok(StatusCode::NO_CONTENT)
}
@@ -317,6 +331,13 @@ pub struct QuotaEstimate {
pub tolerance: f64,
}
/// Pure per-user quota formula: `floor((free_disk * tolerance) / max(active, 1))`.
/// Extracted from `compute_storage_quota` so it's unit-testable without a DB or disk.
fn quota_limit_bytes(free_disk: i64, tolerance: f64, active_uploaders: i64) -> i64 {
let active = active_uploaders.max(1);
((free_disk as f64 * tolerance) / active as f64).floor() as i64
}
/// Computes the per-user storage quota using
/// `floor((free_disk * tolerance) / max(active_uploaders, 1))`. Returns `limit_bytes =
/// None` whenever the storage quota is currently disabled — callers should skip the
@@ -348,7 +369,7 @@ pub async fn compute_storage_quota(state: &AppState) -> QuotaEstimate {
}) as i64;
let limit_bytes = if quota_on && storage_quota_on {
Some(((free_disk as f64 * tolerance) / active as f64).floor() as i64)
Some(quota_limit_bytes(free_disk, tolerance, active))
} else {
None
};
@@ -411,3 +432,37 @@ pub async fn get_original(
.body(Body::from_stream(stream))
.map_err(|e| AppError::Internal(e.into()))
}
#[cfg(test)]
mod tests {
use super::quota_limit_bytes;
#[test]
fn divides_free_space_by_uploaders_with_tolerance() {
// 1000 * 0.75 / 3 = 250
assert_eq!(quota_limit_bytes(1000, 0.75, 3), 250);
}
#[test]
fn floors_fractional_results() {
// 1000 * 0.75 / 7 = 107.14… → 107
assert_eq!(quota_limit_bytes(1000, 0.75, 7), 107);
}
#[test]
fn active_uploaders_below_one_is_clamped_to_one() {
// Guards against divide-by-zero when no one has uploaded yet.
assert_eq!(quota_limit_bytes(1000, 1.0, 0), 1000);
assert_eq!(quota_limit_bytes(1000, 1.0, -5), 1000);
}
#[test]
fn zero_free_disk_yields_zero() {
assert_eq!(quota_limit_bytes(0, 0.75, 3), 0);
}
#[test]
fn full_tolerance_is_identity_for_a_single_uploader() {
assert_eq!(quota_limit_bytes(500, 1.0, 1), 500);
}
}

View File

@@ -18,6 +18,10 @@ mod state;
use config::AppConfig;
use state::AppState;
/// Hard HTTP body cap for the upload endpoint (576 MiB). Backstop against
/// memory-exhaustion; precise per-class size limits are enforced in the handler.
const MAX_UPLOAD_BYTES: usize = 576 * 1024 * 1024;
#[tokio::main]
async fn main() -> Result<()> {
dotenvy::dotenv().ok();
@@ -57,9 +61,13 @@ async fn main() -> Result<()> {
.route("/api/v1/recover", post(auth::handlers::recover))
.route("/api/v1/admin/login", post(auth::handlers::admin_login))
.route("/api/v1/session", delete(auth::handlers::logout))
// Upload — body limit disabled; size validation is done inside the handler
// Upload — HTTP-level body cap as an OOM backstop. The handler still enforces
// the precise per-class limits from DB config (max_image/video_size_mb); this
// layer just stops a multi-GB body from being buffered into memory before that
// check runs. Sized generously above the default 500 MB video limit + multipart
// overhead — if an admin raises max_video_size_mb above this, bump MAX_UPLOAD_BYTES.
.route("/api/v1/upload", post(handlers::upload::upload)
.route_layer(DefaultBodyLimit::disable()))
.route_layer(DefaultBodyLimit::max(MAX_UPLOAD_BYTES)))
.route(
"/api/v1/upload/{id}",
patch(handlers::upload::edit_upload).delete(handlers::upload::delete_upload),
@@ -102,6 +110,7 @@ async fn main() -> Result<()> {
.route("/api/v1/host/comment/{id}", delete(handlers::host::host_delete_comment))
// Export (all authenticated users)
.route("/api/v1/export/status", get(handlers::admin::export_status))
.route("/api/v1/export/ticket", post(handlers::admin::export_ticket))
.route("/api/v1/export/zip", get(handlers::admin::download_zip))
.route("/api/v1/export/html", get(handlers::admin::download_html))
// Admin Dashboard

View File

@@ -109,4 +109,38 @@ mod tests {
fn empty_or_bare_hash_skipped() {
assert_eq!(extract_hashtags("# #"), Vec::<String>::new());
}
#[test]
fn tag_stops_at_first_non_word_char() {
// A tag runs until the first char that isn't ascii-alphanumeric or '_'.
assert_eq!(extract_hashtags("#foo#bar"), vec!["foo"]);
assert_eq!(extract_hashtags("#foo-bar"), vec!["foo"]);
assert_eq!(extract_hashtags("##tag"), Vec::<String>::new()); // '#' after the strip is non-word
}
#[test]
fn tag_length_is_capped_at_40_chars() {
let ok = "a".repeat(40);
assert_eq!(extract_hashtags(&format!("#{ok}")), vec![ok.clone()]);
// 41+ chars → dropped entirely (not truncated).
let too_long = "a".repeat(41);
assert_eq!(extract_hashtags(&format!("#{too_long}")), Vec::<String>::new());
}
#[test]
fn duplicate_tags_are_returned_verbatim_not_deduplicated() {
// Dedup is the DB's job (Hashtag::upsert ON CONFLICT); extraction returns each
// occurrence so callers can count/link them independently. Case folds to lower.
assert_eq!(extract_hashtags("#fun #Fun #fun!"), vec!["fun", "fun", "fun"]);
}
#[test]
fn non_ascii_word_chars_truncate_the_tag() {
// KNOWN LIMITATION for a German app: `is_ascii_alphanumeric` excludes umlauts
// and ß, so a tag truncates at the first non-ASCII letter. Pinned here so a
// future Unicode-aware change is a deliberate, test-visible decision.
assert_eq!(extract_hashtags("#Grüße"), vec!["gr"]);
assert_eq!(extract_hashtags("#Straße"), vec!["stra"]);
assert_eq!(extract_hashtags("#café"), vec!["caf"]);
}
}

View File

@@ -93,8 +93,21 @@ impl CompressionWorker {
// Run blocking image operations in a spawn_blocking task
tokio::task::spawn_blocking(move || -> Result<()> {
let img = image::open(&original)
.context("failed to open image")?;
// Reject decompression bombs *before* fully decoding: the upload body
// cap bounds the file size on disk, but a small file can still decode to
// enormous dimensions (e.g. a ~1 MB image expanding to 50k×50k px →
// gigabytes), OOM-ing the box during decode/resize. 12000×12000 covers
// any real phone photo; max_alloc hard-caps the decode allocation.
let mut reader = image::ImageReader::open(&original)
.context("failed to open image")?
.with_guessed_format()
.context("failed to read image header")?;
let mut limits = image::Limits::default();
limits.max_image_width = Some(12_000);
limits.max_image_height = Some(12_000);
limits.max_alloc = Some(256 * 1024 * 1024);
reader.limits(limits);
let img = reader.decode().context("failed to decode image")?;
// Resize to max 800px wide, preserving aspect ratio
let preview = img.resize(800, 800, image::imageops::FilterType::Lanczos3);

View File

@@ -81,3 +81,74 @@ pub fn client_ip(headers: &axum::http::HeaderMap, fallback: &str) -> String {
.map(|s| s.trim().to_owned())
.unwrap_or_else(|| fallback.to_owned())
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::HeaderMap;
const MIN: Duration = Duration::from_secs(60);
#[test]
fn allows_up_to_max_then_blocks() {
let rl = RateLimiter::new();
assert!(rl.check("k", 3, MIN));
assert!(rl.check("k", 3, MIN));
assert!(rl.check("k", 3, MIN));
assert!(!rl.check("k", 3, MIN), "the 4th request must be blocked");
}
#[test]
fn keys_are_independent() {
let rl = RateLimiter::new();
assert!(rl.check("a", 1, MIN));
assert!(!rl.check("a", 1, MIN));
assert!(rl.check("b", 1, MIN), "a different key has its own window");
}
#[test]
fn window_slides_and_allows_again_after_expiry() {
let rl = RateLimiter::new();
let w = Duration::from_millis(40);
assert!(rl.check("k", 1, w));
assert!(!rl.check("k", 1, w));
std::thread::sleep(Duration::from_millis(55));
assert!(rl.check("k", 1, w), "the slot should expire once the window passes");
}
#[test]
fn retry_after_is_between_one_and_window() {
let rl = RateLimiter::new();
assert!(rl.check_with_retry("k", 1, MIN).is_ok());
let retry = rl.check_with_retry("k", 1, MIN).unwrap_err();
assert!((1..=60).contains(&retry), "retry_after {retry} out of range");
}
#[test]
fn clear_resets_every_window() {
let rl = RateLimiter::new();
assert!(rl.check("k", 1, MIN));
assert!(!rl.check("k", 1, MIN));
rl.clear();
assert!(rl.check("k", 1, MIN), "clear() must free the window");
}
#[test]
fn client_ip_prefers_first_forwarded_for_entry() {
let mut h = HeaderMap::new();
h.insert("x-forwarded-for", "203.0.113.7, 10.0.0.1".parse().unwrap());
assert_eq!(client_ip(&h, "fallback"), "203.0.113.7");
}
#[test]
fn client_ip_trims_surrounding_whitespace() {
let mut h = HeaderMap::new();
h.insert("x-forwarded-for", " 198.51.100.5 ".parse().unwrap());
assert_eq!(client_ip(&h, "fb"), "198.51.100.5");
}
#[test]
fn client_ip_falls_back_when_header_absent() {
assert_eq!(client_ip(&HeaderMap::new(), "127.0.0.1"), "127.0.0.1");
}
}

View File

@@ -72,3 +72,58 @@ fn random_ticket() -> String {
rng.fill(&mut bytes);
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn issue_then_consume_returns_the_hash_exactly_once() {
let store = SseTicketStore::new();
let ticket = store.issue("hash-1".into());
assert_eq!(store.consume(&ticket).as_deref(), Some("hash-1"));
// Single-use: a replay of the same ticket is rejected.
assert_eq!(store.consume(&ticket), None, "a consumed ticket must not be reusable");
}
#[test]
fn unknown_ticket_consumes_to_none() {
let store = SseTicketStore::new();
assert_eq!(store.consume("never-issued"), None);
}
#[test]
fn issued_tickets_are_unique_and_hex() {
let store = SseTicketStore::new();
let a = store.issue("h".into());
let b = store.issue("h".into());
assert_ne!(a, b, "each ticket must be unique");
assert_eq!(a.len(), 48, "24 random bytes → 48 hex chars");
assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn fresh_ticket_survives_prune() {
let store = SseTicketStore::new();
let ticket = store.issue("h".into());
store.prune(); // not expired → kept
assert_eq!(store.consume(&ticket).as_deref(), Some("h"));
}
#[test]
fn expired_ticket_consumes_to_none() {
// Construct an entry that is already past the TTL and confirm consume() rejects it.
let store = SseTicketStore::new();
let stale = "stale-ticket".to_string();
store.inner.lock().unwrap().insert(
stale.clone(),
Entry {
token_hash: "h".into(),
issued_at: Instant::now()
.checked_sub(TTL + Duration::from_secs(1))
.expect("host uptime should exceed the ticket TTL"),
},
);
assert_eq!(store.consume(&stale), None, "an expired ticket must not authenticate");
}
}

8
docker-compose.dev.yml Normal file
View File

@@ -0,0 +1,8 @@
# Dev-only overlay. NOT loaded automatically (unlike docker-compose.override.yml).
# Opt in explicitly for local development when you need host access to Postgres:
# docker compose -f docker-compose.yml -f docker-compose.dev.yml up
# Never use this overlay in production — it publishes the database port on the host.
services:
db:
ports:
- "5432:5432"

View File

@@ -1,4 +0,0 @@
services:
db:
ports:
- "5432:5432"

View File

@@ -0,0 +1,79 @@
# Decision: media serving — unauthenticated UUID vs. signed gateway
**Status:** OPEN — needs a call. Written 2026-06-30 from the 2026-06-27 audit
(`fix/audit-2026-06-27-critical-medium`), which implemented the signed-gateway option that
`main` did not adopt.
**Scope:** how `main` serves uploaded photos/videos (originals + previews/thumbnails) to the
`<img>`/`<video>` tags in the feed, lightbox, and diashow.
---
## The two models
### A. Current `main` — unauthenticated, UUID-as-capability
- `/api/v1/upload/{id}/original`**no auth**; the unguessable upload UUID *is* the capability.
(Documented as intentional in `frontend/src/lib/data-mode-store.ts`.)
- `/media/*` — static `axum` `ServeDir`, **no auth layer**, serves preview/thumbnail files by path.
- No expiry, no signature, no per-request authorization on the bytes.
- **Works with** plain `<img src>` (no Authorization header needed) and browser caching, at zero
per-request backend cost.
### B. Audit branch — authenticated signed gateway
- `/media/{kind}/{id}?sig=…` via `handlers::media::serve`.
- HMAC signature (keyed off `jwt_secret`), **time-boxed** (~24 h, bucketed to a 1 h
URL-stability window so warm fetches stay cacheable).
- Authorizes by **signature + uploader visibility**, not requester identity.
- Still `<img>`-compatible (capability rides in the query string, not a header).
- Cost: token mint/verify, ~2 DB queries per *cold* fetch, and the HMAC key currently reuses
`jwt_secret` (see "Media HMAC domain separation" in [SECURITY-BACKLOG.md](SECURITY-BACKLOG.md)).
---
## What actually differs (the tradeoff)
| | A. UUID (main) | B. Signed gateway (audit) |
|---|---|---|
| Leaked URL/UUID (forwarded link, browser history, referer, logs) | **Permanent** full-res access | Access **expires** (~24 h); URL can't be re-minted |
| Banned / departed guest | Retains **permanent** access to every original whose UUID they hold | Can't mint new URLs; can replay **held** URLs ≤ TTL only |
| Revocation | None (UUID is forever) | Rotate the signing key → all outstanding URLs die |
| Enumeration | Mitigated by UUIDv4 unguessability | Same, plus signature |
| Per-request cost | Zero (static serve) | Token verify + ~2 DB queries (cold) |
| Plumbing / failure surface | Minimal | Token mint/verify, key mgmt, cache-bucket logic |
Neither model solves the fundamental `<img>`-can't-send-a-Bearer constraint: once a browser holds
a media URL, it is replayable for that URL's lifetime. Model B simply **bounds that lifetime** and
**adds revocability**; Model A's lifetime is *forever*.
## Threat model (this deployment)
Private single-box event app, ~100 guests, ~1 000 files, one event at a time. Media is **shared
with all guests by design** — it is personal but not secret *within* the event. The real risk is
**a URL escaping the event boundary** (a guest forwards a link; it lands in chat history, a public
post, or server/proxy logs) granting an outsider — or a removed guest — access.
## Recommendation
This is a judgment call, not a clear-cut bug, so it's yours to make. My leaning:
- **Adopt Model B (signed gateway)** if post-event link leakage or removed-guest access is a real
concern for you — it's the materially stronger posture (bounded exposure + key-rotation
revocation) and the implementation already exists on the audit branch. If adopted, also do the
cheap **HKDF domain-separation** for the HMAC key (backlog 🅱).
- **Keep Model A (UUID)** as an *explicitly accepted risk* if you're comfortable that a leaked
link = permanent access at this scale. If so, two cheap hardening steps are still worth doing:
1. **Log hygiene** — ensure the upload UUID never lands in access logs with enough context to
correlate (the `TraceLayer` logs the request *path*, and `/api/v1/upload/{id}/original`
puts the UUID *in the path*). Confirm logs aren't shipped/retained where that matters.
2. **Document the decision** in `README`/`PROJECT.md` so "unauthenticated media" is a recorded
choice, not an oversight.
**Sharpest single fact to decide on:** in Model A, a guest you *ban* keeps full-resolution access
to every original they ever loaded, forever. In Model B, that access dies within ~24 h. If that
asymmetry matters for your events, adopt the gateway.
## If you adopt B
The implementation lives on `origin/fix/audit-2026-06-27-critical-medium`:
`backend/src/handlers/media.rs` (+ `media_token`), the `/media/{kind}/{id}` route in `main.rs`, and
the feed/upload/host changes that emit signed URLs (`models/upload.rs`, `handlers/feed.rs`). It
would need re-basing onto current `main` (which has since diverged across ~80 files).

88
docs/SECURITY-BACKLOG.md Normal file
View File

@@ -0,0 +1,88 @@
# Security & Hardening Backlog
Tracks the deliberately-deferred items from the 2026-06-27 security audit and its review passes.
**Provenance & reconciliation.** This document was extracted from the
`fix/audit-2026-06-27-critical-medium` branch and reconciled against `main` on 2026-06-30.
That audit's Critical→Medium findings were **largely re-implemented into `main`** through the
later batch branches (security-review-followups, security-review-batch-2, the UX batches) rather
than by merging the audit branch — so `git` shows no merge, but the controls are present. Each
item below is tagged with its **current status in `main`**:
-**Done in main** — addressed (possibly via a different implementation).
-**Open** — still applies to `main`.
- 🔀 **Contingent** — only relevant if `main` adopts the audit's signed-media gateway (see
[DECISION-media-auth.md](DECISION-media-auth.md)).
> The audit branch additionally implemented an **authenticated, signed media gateway** that `main`
> did **not** adopt — `main` serves media unauthenticated (static `ServeDir` + UUID-capability
> `/api/v1/upload/{id}/original`). That architectural choice is written up separately in
> [DECISION-media-auth.md](DECISION-media-auth.md); the "by-design notes" at the bottom of this
> file describe the *audit branch's* model and apply to `main` only if that gateway is adopted.
---
## 🅱 Worth a tracked ticket (real, not one-liners)
-**Moderation UI gap** — the backend `DELETE /host/upload/{id}` and `DELETE /host/comment/{id}`
endpoints have **no frontend caller**, so a host cannot remove a *guest's* content from the UI
(the feed `ContextSheet` only offers delete for the viewer's *own* uploads —
`target.user_id === myUserId`). Still a functional hole in `main`. Needs a host-facing "remove"
action wired to those endpoints, gated on host/admin role.
- ✅/⬜ **Feed reactivity***Mostly fixed in `main`.* The full-reload-on-every-SSE-event problem
(a single `like-update`/`new-comment`/`upload-processed` calling `loadFeed(true)` and collapsing
a scrolled feed) was fixed in the UX batch: `main` now patches the affected card in place
(`patchCount`) and debounces processing (`scheduleInPlaceRefresh`). ⬜ **Remaining sub-item:**
owner-deleted uploads are still not broadcast — `delete_upload` returns `204` with no
`upload-deleted` SSE, so other clients keep showing a deleted post until refresh (only host
deletes broadcast). Emit `upload-deleted` from the owner delete path too.
- 🔀 **Media HMAC domain separation***Only applies if the signed-media gateway is adopted.* The
audit's signed-media tokens reuse `jwt_secret` as the HMAC key; a dedicated derived key
(`HKDF(jwt_secret, "media-url")`) would isolate the domains so a future change to one can't
weaken the other. N/A to `main` as it stands (no signed media).
-**Quota mount-detection + low-disk guard***Still applies to `main`.* `compute_storage_quota`
(`backend/src/handlers/upload.rs`) and `admin.rs` pick the disk via `starts_with`, so root (`/`)
is a wildcard prefix that can match the wrong device; and there's no hard min-free-space
precheck when the quota is disabled. Use longest-prefix match; add an unconditional 507/429 when
free space is critically low.
## ✅ Fixed in main since the audit (for the record)
These audit findings are present in `main` today (verified 2026-06-30): event-scoped social
handlers (cross-event authz), server-side MIME/ext allowlist on upload, recovery-PIN lockout
backoff, unspoofable client IP in the rate limiter, effective JWT production-secret guard, DB port
no longer publicly exposed, container healthchecks, bcrypt offloaded via `spawn_blocking`,
bounded compression concurrency (semaphore), bounded feed queries (`LIMIT ≤ 100`), and the
viewport-fit / reduced-motion / aria a11y pass. **New since the audit:** an image-decode
decompression-bomb cap (`image::Limits` 12000×12000 / 256 MiB) ported into
`backend/src/services/compression.rs`.
## 🅲 Consciously won't-fix at ~100-guest single-box scale
Diminishing returns vs. the deployment's actual threat model. Revisit only if the scale or
tenancy model changes.
- Rate-limiter `HashMap` key LRU/cap (attacker-chosen `recover:{ip}:{name}` keys accumulate up to
the 24h prune ceiling) — bounded and pruned; not worth an LRU.
- "Last host" / host↔host role-churn guard — operational, low blast radius.
- Performance micro-indexes (`idx_like_user_upload`, comment pagination index) — current queries
are sub-ms at this row count.
- Optimistic-like in-flight guard, ownership-snapshot-at-mount, assorted copy tweaks — UX polish.
## By-design notes (audit branch's signed-media model — see DECISION-media-auth.md)
> These describe the **audit branch's** signed-gateway model. `main` does **not** serve media this
> way; for `main`'s actual media-access posture and the tradeoff, see
> [DECISION-media-auth.md](DECISION-media-auth.md).
- **Banned user retains ≤24h media access via already-held signed URLs.** The audit's media gateway
authorizes by *signature + uploader visibility*, not requester identity, and signed URLs are
time-boxed (24h, bucketed). A banned/revoked-session user cannot mint new URLs (every API call
401/403s) but can replay URLs they already hold until expiry — only for content they already saw.
Accepted there: tightening would require per-request identity on every `<img>` load, which the
`<img>`-can't-send-a-Bearer constraint precludes.
- **Two DB queries per *cold* media fetch** (`upload` row + uploader row). Mitigated by browser
caching and the stable bucketed URL. Could be one JOIN if it ever shows up in profiling.

View File

@@ -68,6 +68,17 @@ export const db = {
);
},
/**
* Flip the `export_zip_ready` gate directly. The download handler serves bytes
* only when this boolean is true AND the file exists on disk, so setting it true
* without a file lets tests exercise the "ready but file missing" 404 branch.
*/
async setExportZipReady(slug: string, ready: boolean) {
await withClient((c) =>
c.query(`UPDATE event SET export_zip_ready = $2 WHERE slug = $1`, [slug, ready])
);
},
/** Insert a pre-baked export job row to skip the (slow) real compression path. */
async fakeExportJob(eventSlug: string, type: 'zip' | 'html', status: 'pending' | 'running' | 'done') {
await withClient(async (c) => {

55
e2e/helpers/seed.ts Normal file
View File

@@ -0,0 +1,55 @@
/**
* Shared seed helpers so specs don't each hand-roll the upload/comment create
* flow. Centralising the API contract (routes, field names, expected statuses)
* means an API change is a one-file edit, not a 7-file hunt.
*/
import { uploadRaw, JPEG_MAGIC } from './upload-client';
import { db } from '../fixtures/db';
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
export type SeedUploadOptions = {
caption?: string;
/** Mark compression done so the card is fully rendered in the feed. Default true. */
visible?: boolean;
};
/** Seed a real, accepted upload owned by `jwt` and return its id. */
export async function seedUpload(jwt: string, opts: SeedUploadOptions = {}): Promise<string> {
const body = new Uint8Array(1024);
body.set(JPEG_MAGIC, 0);
const res = await uploadRaw(jwt, body, {
filename: 'a.jpg',
contentType: 'image/jpeg',
caption: opts.caption,
});
if (res.status !== 201) throw new Error(`seedUpload failed: ${res.status} ${await res.text()}`);
const { id } = await res.json();
if (opts.visible !== false) await db.setUploadCompressionStatus(id, 'done');
return id;
}
/** Seed a comment on `uploadId` authored by `jwt`; return its id. */
export async function seedComment(jwt: string, uploadId: string, body: string): Promise<string> {
const res = await fetch(`${BASE}/api/v1/upload/${uploadId}/comments`, {
method: 'POST',
headers: { Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ body }),
});
if (res.status !== 201) throw new Error(`seedComment failed: ${res.status} ${await res.text()}`);
return (await res.json()).id;
}
/** Read the comments for an upload as `jwt`. */
export async function listComments(jwt: string, uploadId: string): Promise<any[]> {
const res = await fetch(`${BASE}/api/v1/upload/${uploadId}/comments`, {
headers: { Authorization: `Bearer ${jwt}` },
});
return res.json();
}
/** Resolve a single upload row from a feed response whose envelope shape isn't pinned. */
export function findFeedRow(feed: any, id: string): any {
const list: any[] = feed.uploads ?? feed.items ?? feed;
return Array.isArray(list) ? list.find((u: any) => u.id === id) : undefined;
}

View File

@@ -3,10 +3,13 @@
* `like-update` arrived for upload X within 5 seconds" without driving a
* second browser tab.
*
* The backend authenticates the SSE endpoint via `?token=` query param
* (the EventSource API can't set headers).
* The backend authenticates the SSE endpoint via a single-use `?ticket=` minted
* at POST /api/v1/stream/ticket (the raw JWT is never put in the URL). This helper
* does that exchange internally, so callers still just pass a JWT to `start()`.
*/
import { mintSseTicket } from './sse';
export type SseEvent = { type: string; data: any; receivedAt: number };
export class SseListener {
@@ -17,7 +20,10 @@ export class SseListener {
constructor(private baseUrl: string = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101') {}
async start(token: string): Promise<void> {
const url = `${this.baseUrl}/api/v1/stream?token=${encodeURIComponent(token)}`;
// Exchange the JWT for a single-use SSE ticket (the stream endpoint no longer
// accepts ?token=).
const ticket = await mintSseTicket(token);
const url = `${this.baseUrl}/api/v1/stream?ticket=${encodeURIComponent(ticket)}`;
// Use fetch with streaming since Node has no EventSource by default.
const res = await fetch(url, { signal: this.controller.signal });
if (!res.body) throw new Error('SSE response has no body');

43
e2e/helpers/sse.ts Normal file
View File

@@ -0,0 +1,43 @@
/**
* Shared SSE-flow helpers. The stream auth flow (mint a single-use ticket, open
* with `?ticket=`) is security-sensitive and recently changed from `?token=`, so
* it lives in one place instead of being re-inlined per spec.
*/
import type { Page } from '@playwright/test';
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
/** Exchange a JWT for a single-use SSE ticket via POST /api/v1/stream/ticket. */
export async function mintSseTicket(jwt: string): Promise<string> {
const res = await fetch(`${BASE}/api/v1/stream/ticket`, {
method: 'POST',
headers: { Authorization: `Bearer ${jwt}` },
});
if (res.status !== 200) throw new Error(`mintSseTicket failed: ${res.status} ${await res.text()}`);
return (await res.json()).ticket;
}
/** Open the SSE stream with a ticket, return the HTTP status, and tear the stream down. */
export async function openStream(ticket: string): Promise<number> {
const c = new AbortController();
try {
const res = await fetch(`${BASE}/api/v1/stream?ticket=${encodeURIComponent(ticket)}`, {
signal: c.signal,
});
return res.status;
} finally {
c.abort();
}
}
/**
* Count EventSource opens (GET /api/v1/stream?ticket=…) on a page — NOT the ticket
* POST. Returns a getter for the running count.
*/
export function trackStreamOpens(page: Page): () => number {
let n = 0;
page.on('request', (req) => {
if (req.method() === 'GET' && req.url().includes('/api/v1/stream?')) n++;
});
return () => n;
}

View File

@@ -21,7 +21,15 @@ export class RecoverPage {
async recover(name: string, pin: string) {
await this.nameInput.fill(name);
// Filling the 4th digit fires the form's auto-submit (the onPinInput handler
// calls handleRecover once pin.length === 4, see pin-auto-submit.spec). An explicit
// submit click would race the ensuing navigation and detach mid-click, so only click
// as a fallback if the button is still around (e.g. a partial / failed PIN).
await this.pinInput.fill(pin);
await this.submitButton.click();
if (await this.submitButton.isEnabled().catch(() => false)) {
await this.submitButton.click().catch(() => {
/* auto-submit already navigated — nothing to click */
});
}
}
}

View File

@@ -12,6 +12,12 @@ import { defineConfig, devices } from '@playwright/test';
* engine-level divergences. The rest of the suite only runs against
* `chromium-desktop` to keep the wall-clock reasonable.
*/
// camera/microphone/clipboard are Chromium-only permissions; passing them to
// firefox/webkit projects throws "Unknown permission: camera" and fails the
// whole test before it runs. Granted per-Chromium-project below instead of in
// the global `use` block.
const CHROMIUM_PERMISSIONS = ['camera', 'microphone', 'clipboard-read', 'clipboard-write'];
export default defineConfig({
testDir: './specs',
outputDir: './test-results',
@@ -35,9 +41,8 @@ export default defineConfig({
video: 'retain-on-failure',
actionTimeout: 10_000,
navigationTimeout: 30_000,
// Camera/mic permissions granted by default; the fake-media launch args
// (set per-project below for Chromium) supply the actual stream.
permissions: ['camera', 'microphone', 'clipboard-read', 'clipboard-write'],
// No camera/mic/clipboard here — those are Chromium-only and are granted on
// the Chromium projects below (see CHROMIUM_PERMISSIONS).
},
projects: [
@@ -49,6 +54,7 @@ export default defineConfig({
testIgnore: ['**/09-mobile/**'],
use: {
...devices['Desktop Chrome'],
permissions: CHROMIUM_PERMISSIONS,
launchOptions: {
args: [
'--use-fake-ui-for-media-stream',
@@ -68,13 +74,13 @@ export default defineConfig({
{
name: 'chromium-mobile',
testMatch: ['**/09-mobile/**/*.spec.ts'],
use: { ...devices['Pixel 7'] },
use: { ...devices['Pixel 7'], permissions: CHROMIUM_PERMISSIONS },
},
// ── Mobile UA smoke matrix (runs only @smoke specs in CI) ────────────
{
name: 'chromium-pixel7',
use: { ...devices['Pixel 7'] },
use: { ...devices['Pixel 7'], permissions: CHROMIUM_PERMISSIONS },
grep: /@smoke/,
},
{
@@ -84,6 +90,7 @@ export default defineConfig({
viewport: { width: 360, height: 780 },
userAgent:
'Mozilla/5.0 (Linux; Android 14; SM-S911B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36',
permissions: CHROMIUM_PERMISSIONS,
},
grep: /@smoke/,
},
@@ -94,6 +101,7 @@ export default defineConfig({
viewport: { width: 360, height: 780 },
userAgent:
'Mozilla/5.0 (Linux; Android 14; SM-S911B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/24.0 Chrome/124.0.0.0 Mobile Safari/537.36',
permissions: CHROMIUM_PERMISSIONS,
},
grep: /@smoke/,
},
@@ -103,6 +111,7 @@ export default defineConfig({
...devices['Pixel 7'],
userAgent:
'Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36 EdgA/124.0.0.0',
permissions: CHROMIUM_PERMISSIONS,
},
grep: /@smoke/,
},
@@ -125,6 +134,9 @@ export default defineConfig({
use: {
...devices['Pixel 7'],
defaultBrowserType: 'firefox',
// Firefox rejects `isMobile` (Chromium-only). Keep the phone viewport +
// Android UA for coverage, but drop the unsupported flag.
isMobile: false,
userAgent:
'Mozilla/5.0 (Android 14; Mobile; rv:124.0) Gecko/124.0 Firefox/124.0',
},

View File

@@ -54,9 +54,13 @@ test.describe('Auth — join flow', () => {
await expect(join.recoveryPinInput).toBeVisible();
await expect(page.getByText(/Charlie.*bereits vergeben/)).toBeVisible();
// Type correct PIN → land on /feed with a new JWT
// Type correct PIN → land on /feed with a new JWT. Filling the 4th digit
// auto-submits (see pin-auto-submit.spec), so an explicit submit click would
// race the navigation; click only as a fallback if the button is still around.
await join.recoveryPinInput.fill(original.pin);
await join.recoverySubmit.click();
if (await join.recoverySubmit.isEnabled().catch(() => false)) {
await join.recoverySubmit.click().catch(() => {});
}
await page.waitForURL('**/feed');
const storage = await readStorage(page);

View File

@@ -6,8 +6,12 @@
*/
import { test, expect } from '../../fixtures/test';
import { join } from 'node:path';
import { readFileSync } from 'node:fs';
const SAMPLE_JPG = join(process.cwd(), 'fixtures', 'media', 'sample.jpg');
// A real, decodable JPEG — the upload handler validates magic bytes, so a
// zero-filled buffer would be rejected with 400 before the rate limiter is reached.
const SAMPLE_BYTES = readFileSync(SAMPLE_JPG);
test.describe('Upload — rate limit', () => {
test('4th upload in one hour returns 429 with Retry-After', async ({ api, adminToken, guest }) => {
@@ -24,7 +28,7 @@ test.describe('Upload — rate limit', () => {
// Hit the API directly for speed — UI behavior is asserted in gallery-path.spec.
const upload = async (n: number) => {
const form = new FormData();
const blob = new Blob([new Uint8Array(640)], { type: 'image/jpeg' });
const blob = new Blob([SAMPLE_BYTES], { type: 'image/jpeg' });
form.append('file', blob, `file${n}.jpg`);
form.append('content_type', 'image/jpeg');
return fetch((process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101') + '/api/v1/upload', {
@@ -47,7 +51,6 @@ test.describe('Upload — rate limit', () => {
// The 429 response carries Retry-After.
const limited = responses.find((r) => r.status === 429)!;
expect(limited.headers.get('retry-after')).toBeTruthy();
void SAMPLE_JPG;
});
test('flipping upload_rate_enabled off bypasses the limit', async ({ api, adminToken, guest }) => {
@@ -56,7 +59,7 @@ test.describe('Upload — rate limit', () => {
const h = await guest('NoQuota');
const upload = async (n: number) => {
const form = new FormData();
const blob = new Blob([new Uint8Array(640)], { type: 'image/jpeg' });
const blob = new Blob([SAMPLE_BYTES], { type: 'image/jpeg' });
form.append('file', blob, `file${n}.jpg`);
form.append('content_type', 'image/jpeg');
return fetch((process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101') + '/api/v1/upload', {

View File

@@ -1,29 +1,68 @@
/**
* USER_JOURNEYS.md §8 — search and filter chips. Asserts the OR / AND
* combination rules described in the journey.
* USER_JOURNEYS.md §8 — grid-view search & filter chips. Verifies the OR / AND
* combination rules end-to-end by seeding uploads with known captions/uploaders,
* activating chips, and counting the resulting grid tiles.
*
* Most of this test currently drives the UI; the data-seeding happens
* via API once a Node-side upload helper lands. For now we ship the
* structure and the UI assertions, marked with `test.fixme` where they
* depend on seeded data we can't yet create.
* (The pure combination logic is also unit-tested in
* frontend/src/lib/feed-filter.test.ts.)
*/
import { test, expect } from '../../fixtures/test';
import { seedUpload } from '../../helpers/seed';
import type { Page } from '@playwright/test';
/** Grid tiles render as buttons labelled "Upload anzeigen". */
const tiles = (page: Page) => page.getByRole('button', { name: 'Upload anzeigen' });
async function switchToGrid(page: Page) {
await page.getByRole('button', { name: 'Rasteransicht' }).click();
}
/** Type a query into the grid search box and click the matching suggestion. */
async function addFilter(page: Page, query: string, suggestionName: string | RegExp) {
const search = page.getByPlaceholder('Nutzer oder #Tag suchen…');
await search.click();
await search.fill(query);
await page.getByRole('button', { name: suggestionName }).click();
}
test.describe('Feed — filter & search', () => {
test.fixme('two hashtag chips combine with OR', async ({ page, guest, signIn }) => {
const h = await guest('Searcher');
await signIn(page, h);
// TODO: seed 2 uploads with different hashtags, then activate two chips
// and assert both cards remain visible.
await page.goto('/feed');
expect(true).toBe(true);
test('two hashtag chips combine with OR', async ({ page, guest, signIn }) => {
const a = await guest('OrUser');
await seedUpload(a.jwt, { caption: 'pic #wedding' });
await seedUpload(a.jwt, { caption: 'pic #party' });
await seedUpload(a.jwt, { caption: 'pic #other' });
await signIn(page, a); // lands on /feed
await switchToGrid(page);
await expect(tiles(page)).toHaveCount(3);
// One tag → only its card.
await addFilter(page, '#wedding', /wedding/i);
await expect(tiles(page)).toHaveCount(1);
// Adding a second tag widens the result (OR), not narrows it.
await addFilter(page, '#party', /party/i);
await expect(tiles(page)).toHaveCount(2);
});
test.fixme('uploader chip + hashtag chip combines with AND', async ({ page, guest, signIn }) => {
const h = await guest('Searcher2');
await signIn(page, h);
await page.goto('/feed');
expect(true).toBe(true);
test('uploader chip + hashtag chip combines with AND', async ({ page, guest, signIn }) => {
const alice = await guest('AndAlice');
const bob = await guest('AndBob');
await seedUpload(alice.jwt, { caption: 'pic #wedding' }); // Alice + wedding
await seedUpload(bob.jwt, { caption: 'pic #wedding' }); // Bob + wedding
await seedUpload(alice.jwt, { caption: 'pic #party' }); // Alice + party
await signIn(page, alice); // feed is event-wide → sees all three
await switchToGrid(page);
await expect(tiles(page)).toHaveCount(3);
// Filter by uploader → Alice's two uploads.
await addFilter(page, 'AndAlice', 'AndAlice');
await expect(tiles(page)).toHaveCount(2);
// Add a tag → must satisfy BOTH (Alice AND #wedding) → just the one.
await addFilter(page, '#wedding', /wedding/i);
await expect(tiles(page)).toHaveCount(1);
});
test('feed page renders without crashing for an authed user', async ({ page, guest, signIn }) => {

View File

@@ -1,36 +1,80 @@
/**
* USER_JOURNEYS.md §7 — liking and commenting. SSE round-trip is
* asserted by opening a second tab as a different user.
* USER_JOURNEYS.md §7 — liking and commenting.
*
* Like behavior is asserted deterministically via the feed snapshot; the comment
* SSE round-trip is asserted by subscribing to the stream as a second user and
* waiting for the `new-comment` event to arrive.
*/
import { test, expect } from '../../fixtures/test';
import { SseListener } from '../../helpers/sse-listener';
import { seedUpload, seedComment, findFeedRow } from '../../helpers/seed';
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
async function like(jwt: string, uploadId: string): Promise<number> {
const res = await fetch(`${BASE}/api/v1/upload/${uploadId}/like`, {
method: 'POST',
headers: { Authorization: `Bearer ${jwt}` },
});
return res.status;
}
test.describe('Feed — like + comment', () => {
test('like is idempotent against rapid double-click', async ({ api, guest }) => {
const a = await guest('Liker');
// Seed an upload from a second user so `a` has something to like.
const b = await guest('Author');
// Without a multipart helper in Node, we exercise the like endpoint directly
// and assert behavior via the public feed snapshot.
// (Spec is a placeholder until we add a Node-side upload helper or do
// the seed via UI.)
const feed = await api.getFeed(a.jwt);
void feed;
void b;
test('a like counts once per user and toggles off on repeat (no double-count)', async ({ api, guest }) => {
const author = await guest('Author');
const liker = await guest('Liker');
const uploadId = await seedUpload(author.jwt);
// Baseline: nobody has liked yet.
let row = findFeedRow(await api.getFeed(liker.jwt), uploadId);
expect(row.like_count).toBe(0);
expect(row.liked_by_me).toBe(false);
// First like → counted exactly once.
expect(await like(liker.jwt, uploadId)).toBe(204);
row = findFeedRow(await api.getFeed(liker.jwt), uploadId);
expect(row.like_count).toBe(1);
expect(row.liked_by_me).toBe(true);
// Liking again is a toggle → back to zero (guards against a regression that
// double-counts a repeated like instead of removing it).
expect(await like(liker.jwt, uploadId)).toBe(204);
row = findFeedRow(await api.getFeed(liker.jwt), uploadId);
expect(row.like_count).toBe(0);
expect(row.liked_by_me).toBe(false);
// A second distinct user's like is counted independently (per-user semantics).
expect(await like(liker.jwt, uploadId)).toBe(204); // liker likes again → 1
expect(await like(author.jwt, uploadId)).toBe(204); // author likes too → 2
row = findFeedRow(await api.getFeed(liker.jwt), uploadId);
expect(row.like_count).toBe(2);
});
test('comment by user A → SSE new-comment delivered to user B', async ({ guest }) => {
const a = await guest('A');
const b = await guest('B');
// SSE frames can take a keep-alive tick to flush through the reverse proxy, so
// both the stream connect and the delivery may cost up to ~30s each.
test.setTimeout(120_000);
const a = await guest('CommenterA');
const b = await guest('ListenerB');
// B subscribes to the stream BEFORE A comments, so the broadcast is captured.
const sse = new SseListener();
await sse.start(b.jwt);
// Without an upload helper, this currently only verifies that the SSE stream
// *connects* for a guest. The comment send + receive assertion lands as soon
// as we add a backend-side helper to inject uploads bypassing multipart.
expect(sse.allEvents().length).toBeGreaterThanOrEqual(0);
sse.stop();
void a;
try {
const uploadId = await seedUpload(a.jwt, { caption: 'pic' });
await seedComment(a.jwt, uploadId, 'hello from A');
// B must receive the new-comment event for this upload. Generous timeout: SSE
// frames flush on the keep-alive tick through the compressing reverse proxy.
const evt = await sse.waitForEvent(
'new-comment',
(e) => e.data?.upload_id === uploadId,
45_000
);
expect(evt.data.comment_count).toBe(1);
} finally {
sse.stop();
}
});
});

View File

@@ -1,27 +1,49 @@
/**
* SSE reconnection after tab background. USER_JOURNEYS.md §17 / edge cases.
*
* The app closes the EventSource on `document.hidden` and reopens it (minting a
* fresh ticket + new EventSource) when the tab becomes visible again — see
* frontend/src/lib/sse.ts. We assert the reconnect by counting stream-open
* requests rather than event delivery, which keeps the test fast and independent
* of the reverse proxy's SSE buffering.
*/
import { test, expect } from '../../fixtures/test';
import { trackStreamOpens } from '../../helpers/sse';
test.describe('Feed — SSE behavior', () => {
test('SSE reconnects after tab visibility goes hidden then visible', async ({ page, guest, signIn }) => {
const h = await guest('SseReconnect');
await signIn(page, h);
await page.goto('/feed');
test('backgrounding then foregrounding the tab opens a fresh SSE connection', async ({ page, guest, signIn }) => {
const g = await guest('SseReconnect');
const streamOpens = trackStreamOpens(page);
// Force-fire a visibilitychange to hidden, then back to visible. The app's
// sse.ts is expected to close + reopen the EventSource around this.
await signIn(page, g); // lands on /feed, which calls connectSse() on mount
// Initial connection established.
await expect.poll(streamOpens, { timeout: 10_000 }).toBeGreaterThanOrEqual(1);
// Background: the visibility handler reads document.hidden, so override that
// (not just visibilityState) before dispatching, or the close never fires.
// disconnectSse() closes the EventSource and clears any reconnect timer, so no
// new stream opens while hidden.
await page.evaluate(() => {
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });
Object.defineProperty(document, 'hidden', { configurable: true, get: () => true });
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' });
document.dispatchEvent(new Event('visibilitychange'));
});
await page.waitForTimeout(500);
// Snapshot the count AFTER backgrounding — this baselines out the initial open (and
// any spurious native/error reconnect before now), so the assertion below can only
// be satisfied by a NEW open attributable to the foreground event itself.
const afterHidden = streamOpens();
// Foreground again → connectSse() mints a new ticket and opens a new EventSource.
await page.evaluate(() => {
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
Object.defineProperty(document, 'hidden', { configurable: true, get: () => false });
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' });
document.dispatchEvent(new Event('visibilitychange'));
});
// App should still be functional — assert the bottom nav remains visible.
// The reconnect is a brand-new stream GET that appears only after foregrounding.
await expect.poll(streamOpens, { timeout: 10_000 }).toBeGreaterThan(afterHidden);
// And the app is still functional.
await expect(page.getByRole('link', { name: 'Galerie' })).toBeVisible();
});
});

View File

@@ -41,8 +41,9 @@ test.describe('Feed — error toast on user action failures', () => {
const card = page.locator('article').filter({ hasText: author.displayName }).first();
await expect(card).toBeVisible({ timeout: 10_000 });
// Click the like button in the actions row — first visible match inside the card.
await card.locator('button').filter({ hasText: /\d+/ }).first().click();
// Click the like button by its stable aria-label (the liker hasn't liked yet).
// Avoids matching a different digit-bearing button (e.g. the comment count).
await card.getByRole('button', { name: 'Gefällt mir' }).click();
// The toast is rendered inside the global Toaster region with aria-live="polite".
const toast = page.getByTestId('toast').first();

View File

@@ -63,8 +63,10 @@ test.describe('Admin — stats', () => {
await guest('Stat2');
await guest('Stat3');
const stats = await api.getStats(adminToken);
// Three guests + the Admin account auto-created on first admin login = 4 users.
expect(stats.user_count).toBeGreaterThanOrEqual(3);
// Deterministic after the per-test truncate: 3 seeded guests + the Admin account
// (recreated by the adminToken fixture's login) = exactly 4. An exact assertion
// catches undercount/overcount regressions a `>= 3` lower bound would miss.
expect(stats.user_count).toBe(4);
expect(typeof stats.disk_total_bytes).toBe('number');
});
});

View File

@@ -42,16 +42,42 @@ test.describe('Export — release and download', () => {
expect(body.html.status).toBe('done');
});
test('ZIP download returns 404 when no file is on disk (export released but never compressed)', async ({ guest, db }) => {
const g = await guest('NoFile');
const base = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
// Browser downloads stream to disk via a top-level navigation, so the download
// endpoint authenticates with a single-use ticket (no Bearer header).
async function mintTicket(jwt: string): Promise<string> {
const res = await fetch(base + '/api/v1/export/ticket', {
method: 'POST',
headers: { Authorization: `Bearer ${jwt}` },
});
return (await res.json()).ticket;
}
test('ZIP download 404s when the export is not yet marked ready', async ({ guest, db }) => {
const g = await guest('NotReady');
// Released flag set, but export_zip_ready is still false → must refuse, never serve.
await db.setExportReleased(SLUG, true);
await db.fakeExportJob(SLUG, 'zip', 'done');
// Real backend additionally checks event.export_zip_ready. The faked row is
// enough for /status; the download path needs the boolean flag too.
const res = await fetch((process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101') + '/api/v1/export/zip', {
headers: { Authorization: `Bearer ${g.jwt}` },
});
// Either 404 ("not available" OR "file not found") — both are valid states for this setup.
expect([404, 200]).toContain(res.status);
const ticket = await mintTicket(g.jwt);
const res = await fetch(base + '/api/v1/export/zip?ticket=' + encodeURIComponent(ticket));
// Pinned to 404 (not [404,200]): a 200 here would mean serving an export that was
// never released for download — a data-exposure regression. This hits the
// `!export_zip_ready` guard.
expect(res.status).toBe(404);
});
test('ZIP download 404s when marked ready but the file is missing on disk', async ({ guest, db }) => {
const g = await guest('ReadyNoFile');
// Released AND ready, but no Gallery.zip on disk (we never ran a real export) →
// the handler must 404 on the missing-file check, not 200/500 or serve a stale file.
await db.setExportReleased(SLUG, true);
await db.setExportZipReady(SLUG, true);
await db.fakeExportJob(SLUG, 'zip', 'done');
const ticket = await mintTicket(g.jwt);
const res = await fetch(base + '/api/v1/export/zip?ticket=' + encodeURIComponent(ticket));
expect(res.status).toBe(404);
});
});

View File

@@ -5,26 +5,79 @@
* with cross-user and banned-user scenarios that span multiple resources.
*/
import { test, expect } from '../../fixtures/test';
import { seedUpload, seedComment, listComments, findFeedRow } from '../../helpers/seed';
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
test.describe('Adversarial — deep authorization', () => {
test('user A cannot delete user B\'s comment via /api/v1/comment/{id}', async ({ api, guest }) => {
const a = await guest('CommentA');
const b = await guest('CommentB');
// IDOR: user B must not be able to delete user A's REAL comment. This exercises the
// ownership guard (`comment.user_id != auth.user_id` → 403) — the previous version fired
// at the all-zeros UUID, which 404s at the lookup BEFORE that guard runs, so it never
// tested authorization at all.
test('user B cannot delete user A\'s comment (real resource → 403, comment survives)', async ({ guest }) => {
const a = await guest('CommentOwnerA');
const b = await guest('AttackerB');
// We need an upload first; without a multipart helper here we use a placeholder:
// post a comment on a non-existent upload to force the path to return 404 / 403 / 401.
// The real intent is verified once an upload helper feeds this test a real upload_id.
const fakeId = '00000000-0000-0000-0000-000000000000';
const res = await fetch(`${BASE}/api/v1/comment/${fakeId}`, {
const uploadId = await seedUpload(a.jwt);
const commentId = await seedComment(a.jwt, uploadId, 'A owns this');
const res = await fetch(`${BASE}/api/v1/comment/${commentId}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${b.jwt}` },
});
// Acceptable: 403 (not your comment), 404 (no such comment), 401.
expect([401, 403, 404]).toContain(res.status);
void a;
void api;
// Must be 403 specifically — the comment exists and is in B's event, so a 404 would
// mean the ownership check was skipped/reordered.
expect(res.status).toBe(403);
// No state change: the comment is still there.
const after = await listComments(a.jwt, uploadId);
expect(after.some((c: any) => c.id === commentId)).toBe(true);
// Control: the real owner CAN delete it (proves the 403 was about identity, not a broken route).
const ownerDel = await fetch(`${BASE}/api/v1/comment/${commentId}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${a.jwt}` },
});
expect(ownerDel.status).toBe(204);
});
// IDOR: user B must not be able to delete user A's REAL upload.
test('user B cannot delete user A\'s upload (403, upload survives)', async ({ guest, db }) => {
const a = await guest('UploadOwnerA');
const b = await guest('AttackerB2');
const uploadId = await seedUpload(a.jwt);
expect(await db.countUploadsForUser(a.userId)).toBe(1);
const res = await fetch(`${BASE}/api/v1/upload/${uploadId}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${b.jwt}` },
});
expect(res.status).toBe(403);
// No state change: A's upload is still present (not soft-deleted).
expect(await db.countUploadsForUser(a.userId)).toBe(1);
});
// IDOR: user B must not be able to edit (re-caption / re-tag) user A's upload.
test('user B cannot edit user A\'s upload caption (403, caption unchanged)', async ({ guest }) => {
const a = await guest('UploadOwnerA2');
const b = await guest('AttackerB3');
// seedUpload marks compression done, so the upload is feed-visible for the read-back.
const uploadId = await seedUpload(a.jwt, { caption: 'original caption' });
const res = await fetch(`${BASE}/api/v1/upload/${uploadId}`, {
method: 'PATCH',
headers: { Authorization: `Bearer ${b.jwt}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ caption: 'hacked by B' }),
});
expect(res.status).toBe(403);
// No state change: the caption A set is intact.
const feedRes = await fetch(`${BASE}/api/v1/feed`, { headers: { Authorization: `Bearer ${a.jwt}` } });
const row = findFeedRow(await feedRes.json(), uploadId);
expect(row?.caption).toBe('original caption');
});
test('banned user cannot toggle a like', async ({ api, host, guest }) => {

View File

@@ -4,6 +4,7 @@
* or rejected gracefully without crashing the backend.
*/
import { test, expect } from '../../fixtures/test';
import { mintSseTicket } from '../../helpers/sse';
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
@@ -46,9 +47,15 @@ test.describe('Adversarial — small-scale abuse', () => {
test('SSE: 10 concurrent streams from one user do not crash the server', async ({ guest }) => {
const g = await guest('SseFlood');
const controllers = Array.from({ length: 10 }, () => new AbortController());
const requests = controllers.map((c) =>
fetch(`${BASE}/api/v1/stream?token=${encodeURIComponent(g.jwt)}`, { signal: c.signal })
// The stream endpoint authenticates via single-use tickets (POST /stream/ticket),
// not the raw JWT — a `?token=` open is rejected with 400. Mint one ticket per stream.
// (These streams must be held open concurrently, so we can't use the openStream
// helper which opens-and-aborts a single stream.)
const tickets = await Promise.all(Array.from({ length: 10 }, () => mintSseTicket(g.jwt)));
const controllers = tickets.map(() => new AbortController());
const requests = tickets.map((ticket, i) =>
fetch(`${BASE}/api/v1/stream?ticket=${encodeURIComponent(ticket)}`, { signal: controllers[i].signal })
);
const responses = await Promise.all(requests);
// All accepted (or some rate-limited — both fine).

View File

@@ -0,0 +1,40 @@
/**
* Phase 2 adversarial — SSE ticket capability abuse.
*
* The stream endpoint authenticates via short-lived, single-use tickets minted at
* POST /api/v1/stream/ticket (never the raw JWT in the URL). These tests pin the
* security properties of that flow: minting requires auth, and a ticket is consumed
* on first use so it cannot be replayed.
*/
import { test, expect } from '../../fixtures/test';
import { mintSseTicket, openStream } from '../../helpers/sse';
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
test.describe('Adversarial — SSE ticket abuse', () => {
test('minting a ticket requires authentication', async () => {
const res = await fetch(`${BASE}/api/v1/stream/ticket`, { method: 'POST' });
expect(res.status).toBe(401);
});
test('a ticket is single-use: replay after first open is rejected', async ({ guest }) => {
const g = await guest('SseReplay');
const ticket = await mintSseTicket(g.jwt);
// First open consumes the ticket.
expect(await openStream(ticket)).toBe(200);
// Replaying the exact same ticket must fail — it was consumed, so `consume` returns
// None → 401. A 200 here would mean tickets are reusable (capability replay).
expect(await openStream(ticket)).toBe(401);
});
test('an unminted / garbage ticket is rejected', async () => {
// 24-byte-shaped hex string that was never issued.
const bogus = 'deadbeef'.repeat(6);
expect(await openStream(bogus)).toBe(401);
});
// Note: the replay test's first open (→ 200) already proves a freshly-minted ticket
// works, so there is no separate "fresh ticket" sanity test — a second successful open
// would just add ~30s (SSE headers flush on the keep-alive tick through Caddy).
});

View File

@@ -3,18 +3,25 @@
* browser process.
*/
import { test, expect } from '../../fixtures/test';
import { trackStreamOpens } from '../../helpers/sse';
test.describe('Browser chaos — multi-tab', () => {
test('same user in two tabs — SSE delivers to both', async ({ page, context, guest, signIn }) => {
test('same user in two tabs — each tab establishes its own SSE stream', async ({ page, context, guest, signIn }) => {
const g = await guest('Twin');
await signIn(page, g);
await page.goto('/feed');
// Count each tab's own EventSource open. Asserting *connection establishment* is
// fast and reliable; asserting event *delivery* would depend on the reverse proxy's
// ~30s SSE buffering and isn't worth the flake here.
const opens1 = trackStreamOpens(page);
await signIn(page, g); // → /feed, connectSse() on mount
await expect.poll(opens1, { timeout: 10_000 }).toBeGreaterThanOrEqual(1);
const tab2 = await context.newPage();
const opens2 = trackStreamOpens(tab2);
await signIn(tab2, g);
await tab2.goto('/feed');
await expect.poll(opens2, { timeout: 10_000 }).toBeGreaterThanOrEqual(1);
// Both tabs should mount the bottom nav.
// Both tabs mounted and each opened its own independent stream.
await expect(page.getByRole('link', { name: 'Galerie' })).toBeVisible();
await expect(tab2.getByRole('link', { name: 'Galerie' })).toBeVisible();
await tab2.close();

View File

@@ -61,7 +61,10 @@ test.describe('Browser chaos — network', () => {
const g = await guest('Throttled');
let attempts = 0;
await page.route('**/api/v1/feed', async (route) => {
// Match /api/v1/feed with or without a query string (the app requests
// `/feed?limit=20`), but NOT /api/v1/feed/delta. A plain `**/api/v1/feed` glob
// fails to match the query-string URL, so this route never fired before.
await page.route(/\/api\/v1\/feed(\?|$)/, async (route) => {
attempts++;
await route.fulfill({
status: 429,
@@ -72,9 +75,29 @@ test.describe('Browser chaos — network', () => {
await signIn(page, g);
await page.goto('/feed');
await page.waitForTimeout(3_000);
// First make sure the throttled endpoint was actually hit — otherwise the
// stabilize-poll below could settle at attempts=0 (feed request not yet fired)
// and pass vacuously without ever exercising the 429 path.
await expect.poll(() => attempts, { timeout: 8_000 }).toBeGreaterThanOrEqual(1);
// Then wait until the retry count stops climbing instead of sleeping a fixed 3s:
// a well-behaved client surfaces the 429 and stops, so the count settles quickly;
// a retry storm would keep incrementing and never stabilize (→ this poll times
// out and the test fails, which is the outcome we want).
let prev = -1;
await expect
.poll(
() => {
const stable = attempts === prev;
prev = attempts;
return stable;
},
{ timeout: 8_000, intervals: [300] }
)
.toBe(true);
// Sanity: client did not hammer the endpoint > a few times under throttle.
expect(attempts).toBeLessThan(15);
expect(attempts, `retry attempts=${attempts}`).toBeLessThan(15);
});
});

View File

@@ -75,10 +75,11 @@ test.describe('Mobile — double-tap gesture', () => {
await expect(imageButton).toBeVisible({ timeout: 10_000 });
await imageButton.click();
// LightboxModal is `role="dialog"` (no aria-modal). The other dialog on the
// page is the ContextSheet which has `aria-modal="true"` even when closed,
// so scope to NOT-aria-modal to pick the lightbox specifically.
const lightbox = page.locator('[role="dialog"]:not([aria-modal])');
// LightboxModal is the only dialog labelled by #lightbox-title, so target it
// directly. (Closed sheets no longer expose role=dialog — that semantics is
// gated on `open` — so a plain [role=dialog] match would be ambiguous only
// while a sheet is open; the labelledby scope keeps this unambiguous.)
const lightbox = page.locator('[role="dialog"][aria-labelledby="lightbox-title"]');
await expect(lightbox).toBeVisible();
// Find the inner image element to tap.

View File

@@ -2,7 +2,7 @@
* Phase 3 mobile — long-press gesture.
*
* The `longpress` action attaches to `<article>` in FeedListCard and to
* grid cells in FeedGrid. Holding for ≥ 500 ms fires `onlongpress`,
* grid cells in VirtualFeed (grid mode). Holding for ≥ 500 ms fires `onlongpress`,
* which opens the ContextSheet bottom sheet via the feed page's
* `contextTarget` state.
*
@@ -45,13 +45,11 @@ test.describe('Mobile — long-press gesture', () => {
await longPress(page, card, 600);
// The ContextSheet renders a dialog with role="dialog" + aria-modal="true".
// Multiple sheets (UploadSheet, ContextSheet) may be in the DOM — match the
// one that actually has aria-modal=true (i.e. the open one).
// ContextSheet is always mounted (it just translates off-screen when closed).
// Match the OPEN state by the `translate-y-0` class the component applies
// when `open === true`.
const sheet = page.locator('[role="dialog"][aria-modal="true"].translate-y-0');
// The ContextSheet is always mounted (it translates off-screen when closed).
// Target it by its stable data-testid, gated on aria-modal="true" which the
// component sets only while open — unambiguous vs. the centered LightboxModal
// (which also has aria-modal) and independent of the animation classes.
const sheet = page.locator('[data-testid="context-sheet"][aria-modal="true"]');
await expect(sheet).toBeVisible({ timeout: 2_000 });
await expect(sheet.getByRole('button', { name: /abbrechen/i })).toBeVisible();
});
@@ -68,10 +66,9 @@ test.describe('Mobile — long-press gesture', () => {
// Simulate a short press (200 ms — well under the 500 ms threshold).
await longPress(page, card, 200);
// Within 1 s, no aria-modal=true dialog should be open (the ContextSheet
// is "open" only when its aria-modal flag is true).
// The ContextSheet stays mounted but `translate-y-0` is only set when open.
await expect(page.locator('[role="dialog"][aria-modal="true"].translate-y-0')).toHaveCount(0, { timeout: 1_000 });
// Within 1 s, the ContextSheet must not be open (aria-modal is set only when
// open). A quick tap opens the lightbox instead, which is a different element.
await expect(page.locator('[data-testid="context-sheet"][aria-modal="true"]')).toHaveCount(0, { timeout: 1_000 });
});
test('long-press suppresses the click that lands at pointerup (no double-open of lightbox)', async ({ page, guest, signIn }) => {

View File

@@ -45,20 +45,8 @@ test.describe('Mobile — safe-area insets', () => {
expect(distanceFromBottom).toBeLessThanOrEqual(2);
});
test('context sheet (when opened) carries the same safe-area declaration', async ({ page }) => {
// We can't easily open the context sheet without a feed card to long-press,
// but the markup lives in the layout once the route mounts. We probe by
// scanning every element with a `style` attribute for the env() reference.
await page.goto('/join');
const candidateStyles: string[] = await page.evaluate(() => {
return Array.from(document.querySelectorAll<HTMLElement>('[style]'))
.map((el) => el.getAttribute('style') ?? '')
.filter((s) => s.includes('env(safe-area-inset-bottom)'));
});
// On /join there may be zero — the assertion is more of a sanity check.
// On /feed and /account it would be ≥ 1. We assert that on /feed below.
expect(Array.isArray(candidateStyles)).toBe(true);
});
// (A vacuous `/join` probe that only asserted `Array.isArray(...)` — always true —
// was removed; the real sheet-level env() check is the structural test below.)
test('upload sheet and context sheet both honor env() (structural check)', async ({ page, guest, signIn }) => {
const g = await guest('SafeAreaSheets');

View File

@@ -12,7 +12,9 @@ test.describe('Mobile a11y — sheets dismiss on Escape', () => {
await page.goto('/account');
// Click the "Original" radio in the Datennutzung section to open the warning sheet.
const originalRadio = page.getByRole('radio', { name: /Original$/i });
// The radio's accessible name is its title + description ("Original Lädt die
// Originaldateien…"), so anchor on the start, not the end.
const originalRadio = page.getByRole('radio', { name: /^Original/i });
await originalRadio.click();
const sheet = page.locator('[role="dialog"][aria-labelledby="data-mode-title"]');

View File

@@ -16,6 +16,10 @@ COPY --from=builder /app/build ./build
COPY --from=builder /app/package.json ./
RUN npm install --omit=dev
# Run as the image's built-in non-root `node` user.
RUN chown -R node:node /app
USER node
EXPOSE 3001
ENV PORT=3001 HOST=0.0.0.0
CMD ["node", "build"]

File diff suppressed because it is too large Load Diff

View File

@@ -9,7 +9,9 @@
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"test:unit": "vitest run",
"test:unit:watch": "vitest"
},
"devDependencies": {
"@sveltejs/adapter-auto": "^7.0.0",
@@ -18,13 +20,16 @@
"@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tailwindcss/vite": "^4.2.2",
"@types/qrcode": "^1.5.6",
"jsdom": "^29.1.1",
"svelte": "^5.54.0",
"svelte-check": "^4.4.2",
"tailwindcss": "^4.2.2",
"typescript": "^5.9.3",
"vite": "^7.3.1"
"vite": "^7.3.1",
"vitest": "^4.1.9"
},
"dependencies": {
"@tanstack/svelte-virtual": "^3.13.30",
"idb": "^8.0.3",
"qrcode": "^1.5.4"
}

View File

@@ -1 +1,15 @@
@import "./tailwind-theme.css";
/* Respect the OS "reduce motion" setting. Collapses every animation/transition
* (HeartBurst, Skeleton pulse, diashow cross-fades, sheet/FAB slides) to a
* near-instant change rather than removing them outright, so state still updates. */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}

View File

@@ -1,10 +1,21 @@
<!doctype html>
<html lang="en">
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- viewport-fit=cover activates the env(safe-area-inset-*) padding used by the
bottom nav, sheets, toasts and FAB on notched / home-indicator devices. -->
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="text-scale" content="scale" />
<meta name="theme-color" content="#ffffff" />
<!-- Light/dark theme-color so the browser chrome matches the active theme. -->
<meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)" />
<meta name="theme-color" content="#030712" media="(prefers-color-scheme: dark)" />
<!-- Installable PWA keepsake: manifest + Apple home-screen metadata. -->
<link rel="manifest" href="%sveltekit.assets%/manifest.webmanifest" />
<link rel="icon" href="%sveltekit.assets%/icon.svg" type="image/svg+xml" />
<link rel="apple-touch-icon" href="%sveltekit.assets%/icon.svg" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="EventSnap" />
<!--
FOUC guard: apply the dark class *before* paint, so reloads of pages with
theme=dark don't flash a white screen. Mirrors the logic in

View File

@@ -1,9 +1,14 @@
// Svelte action — fires a `doubletap` CustomEvent when two pointerup events occur
// within `interval` ms on roughly the same spot. Used in the lightbox for the
// Instagram-style "double-tap to like" gesture.
// Svelte action — the single source of truth for tap gestures on a media element.
// Fires a `doubletap` CustomEvent when two pointerup events occur within `interval`
// ms on roughly the same spot (Instagram-style "double-tap to like"), and a
// `singletap` CustomEvent once `interval` has elapsed with no second tap. Owning
// both gestures in one place means a component no longer juggles its own debounce
// timer alongside a separate onclick handler.
//
// Native `dblclick` exists, but on iOS Safari it also zooms the page; gating on
// pointer events lets us preventDefault selectively and avoid the zoom.
// pointer events lets us preventDefault selectively and avoid the zoom. Keyboard
// activation still arrives as a normal `click` (detail === 0) — handle that on the
// element itself for an immediate, latency-free open.
import type { ActionReturn } from 'svelte/action';
@@ -16,6 +21,7 @@ export interface DoubletapOptions {
interface DoubletapAttributes {
'ondoubletap'?: (event: CustomEvent<void>) => void;
'onsingletap'?: (event: CustomEvent<void>) => void;
}
export function doubletap(
@@ -26,12 +32,21 @@ export function doubletap(
let lastTime = 0;
let lastX = 0;
let lastY = 0;
let singleTimer: ReturnType<typeof setTimeout> | null = null;
const clearSingle = () => {
if (singleTimer) {
clearTimeout(singleTimer);
singleTimer = null;
}
};
const onPointerUp = (e: PointerEvent) => {
const now = performance.now();
const dx = Math.abs(e.clientX - lastX);
const dy = Math.abs(e.clientY - lastY);
if (now - lastTime < interval && dx < MOVE_THRESHOLD && dy < MOVE_THRESHOLD) {
clearSingle(); // the pending single-tap was actually the first of a double
e.preventDefault();
node.dispatchEvent(new CustomEvent('doubletap'));
lastTime = 0; // reset so a triple-tap doesn't re-fire
@@ -40,6 +55,12 @@ export function doubletap(
lastTime = now;
lastX = e.clientX;
lastY = e.clientY;
// Defer the single-tap action until we're sure no second tap follows.
clearSingle();
singleTimer = setTimeout(() => {
singleTimer = null;
node.dispatchEvent(new CustomEvent('singletap'));
}, interval);
};
node.addEventListener('pointerup', onPointerUp);
@@ -49,6 +70,7 @@ export function doubletap(
interval = newOptions.interval ?? INTERVAL_MS;
},
destroy() {
clearSingle();
node.removeEventListener('pointerup', onPointerUp);
}
};

View File

@@ -17,8 +17,11 @@ const FOCUSABLE =
'a[href], area[href], input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';
function focusables(root: HTMLElement): HTMLElement[] {
// `offsetParent` is null for any `position: fixed` element (and our sheets/modals
// are fixed), so it would wrongly drop their buttons. `getClientRects().length`
// is true whenever the element is actually rendered — fixed or not.
return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
(el) => !el.hasAttribute('disabled') && el.offsetParent !== null
(el) => !el.hasAttribute('disabled') && el.getClientRects().length > 0
);
}
@@ -61,11 +64,16 @@ export function focusTrap(
node.addEventListener('keydown', onKeyDown);
if (opts.autoFocus !== false) {
// Defer one frame so the element is fully laid out (sheets animate in).
// Focus the container synchronously on mount so the trap owns the keyboard
// immediately — otherwise an Escape pressed before the deferred focus below
// lands on an element *outside* the node, where this node-scoped listener
// never sees it (the keystroke is silently dropped). Then defer one frame to
// move focus onto the first control once the sheet has laid out / animated in.
if (!node.hasAttribute('tabindex')) node.setAttribute('tabindex', '-1');
node.focus({ preventScroll: true });
requestAnimationFrame(() => {
const list = focusables(node);
const target = list[0] ?? node;
if (!node.hasAttribute('tabindex')) node.setAttribute('tabindex', '-1');
target.focus({ preventScroll: true });
});
}

View File

@@ -22,8 +22,17 @@ export function pullToRefresh(
): ActionReturn<PullToRefreshOptions> {
let opts = options;
let startY = 0;
let startX = 0;
let pulling = false;
let triggered = false;
let intentLocked = false; // have we decided this gesture is a vertical pull?
// Distance the finger must travel before we commit to "this is a vertical pull"
// vs. a horizontal swipe or an incidental tap.
const INTENT_SLOP = 8;
// Rubber-band resistance: the sheet follows the finger at a fraction of 1:1 so
// the pull feels elastic rather than rigid.
const RESISTANCE = 0.5;
function scroller(): HTMLElement | (Window & typeof globalThis) {
return node.scrollHeight > node.clientHeight ? node : window;
@@ -40,17 +49,54 @@ export function pullToRefresh(
opts.onpull(Math.max(0, delta), Math.max(0, delta) / threshold);
}
function reset() {
pulling = false;
intentLocked = false;
}
function onTouchStart(e: TouchEvent) {
if (opts.disabled) return;
// Ignore pinch / multi-finger gestures entirely.
if (e.touches.length !== 1) {
reset();
return;
}
if (scrollTop() > 0) return;
startY = e.touches[0].clientY;
startX = e.touches[0].clientX;
pulling = true;
triggered = false;
intentLocked = false;
}
function onTouchMove(e: TouchEvent) {
if (!pulling || triggered) return;
const delta = e.touches[0].clientY - startY;
// A second finger landing mid-gesture cancels the pull.
if (e.touches.length !== 1) {
reset();
return;
}
const rawDy = e.touches[0].clientY - startY;
const dx = e.touches[0].clientX - startX;
// Decide intent once, after the finger has moved past the slop. A
// horizontal-dominant or upward move is not a pull — bail and let the
// browser scroll normally.
if (!intentLocked) {
if (Math.abs(rawDy) < INTENT_SLOP && Math.abs(dx) < INTENT_SLOP) return;
if (rawDy <= 0 || Math.abs(rawDy) <= Math.abs(dx)) {
reset();
return;
}
intentLocked = true;
}
// Committed vertical pull at the top edge: stop the browser's own
// overscroll / pull-to-refresh from competing for the gesture.
if (e.cancelable) e.preventDefault();
const delta = rawDy * RESISTANCE;
reportPull(delta);
if (delta > (opts.threshold ?? 60)) {
triggered = true;
@@ -60,11 +106,12 @@ export function pullToRefresh(
function onTouchEnd() {
if (pulling && !triggered) reportPull(0);
pulling = false;
reset();
}
node.addEventListener('touchstart', onTouchStart, { passive: true });
node.addEventListener('touchmove', onTouchMove, { passive: true });
// Non-passive so we can preventDefault() once a top-edge pull is in progress.
node.addEventListener('touchmove', onTouchMove, { passive: false });
node.addEventListener('touchend', onTouchEnd);
node.addEventListener('touchcancel', onTouchEnd);

View File

@@ -0,0 +1,50 @@
// Body scroll-lock for open dialogs/sheets. While any locker is active, the
// document body can't scroll behind the overlay. Ref-counted so that nested or
// stacked dialogs (e.g. a ConfirmSheet opened from the LightboxModal) don't let
// the first one to close unlock the page out from under the others. Compensates
// for the vanished scrollbar width so the layout doesn't jump on lock.
import type { ActionReturn } from 'svelte/action';
let lockCount = 0;
let savedOverflow = '';
let savedPaddingRight = '';
function lock() {
if (typeof document === 'undefined') return;
if (lockCount === 0) {
const body = document.body;
const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
savedOverflow = body.style.overflow;
savedPaddingRight = body.style.paddingRight;
body.style.overflow = 'hidden';
if (scrollbarWidth > 0) {
const current = parseFloat(getComputedStyle(body).paddingRight) || 0;
body.style.paddingRight = `${current + scrollbarWidth}px`;
}
}
lockCount++;
}
function unlock() {
if (typeof document === 'undefined') return;
lockCount = Math.max(0, lockCount - 1);
if (lockCount === 0) {
document.body.style.overflow = savedOverflow;
document.body.style.paddingRight = savedPaddingRight;
}
}
/**
* Locks body scroll for the lifetime of the node. Mount the node only while the
* dialog is open (e.g. inside `{#if open}` or alongside a `class:` toggle) so the
* action's create/destroy line up with open/close.
*/
export function scrollLock(node: HTMLElement): ActionReturn {
lock();
return {
destroy() {
unlock();
}
};
}

View File

@@ -13,6 +13,8 @@ export class ApiError extends Error {
}
}
const TIMEOUT_MS = 20_000;
async function request<T>(
method: string,
path: string,
@@ -27,23 +29,50 @@ async function request<T>(
headers['Content-Type'] = 'application/json';
}
const res = await fetch(`${BASE}${path}`, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined
});
// Abort hung requests so a dead connection surfaces as a friendly error
// instead of a spinner that never resolves.
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
let res: Response;
try {
res = await fetch(`${BASE}${path}`, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
signal: controller.signal
});
} catch (e) {
if (e instanceof DOMException && e.name === 'AbortError') {
throw new ApiError(0, 'timeout', 'Zeitüberschreitung bitte erneut versuchen.');
}
throw new ApiError(0, 'network', 'Netzwerkfehler bitte Verbindung prüfen.');
} finally {
clearTimeout(timer);
}
if (res.status === 204) {
return undefined as T;
}
const data = await res.json();
// A 5xx behind a proxy (or a crash page) can return HTML, not JSON — parsing
// it directly would throw an opaque SyntaxError. Read text, parse defensively.
const raw = await res.text();
let data: { error?: string; message?: string } | unknown = null;
if (raw) {
try {
data = JSON.parse(raw);
} catch {
data = null;
}
}
if (!res.ok) {
if (res.status === 401) {
clearAuth();
}
throw new ApiError(res.status, data.error ?? 'unknown', data.message ?? 'Fehler');
const d = (data ?? {}) as { error?: string; message?: string };
throw new ApiError(res.status, d.error ?? 'unknown', d.message ?? `Serverfehler (${res.status}).`);
}
return data as T;

View File

@@ -0,0 +1,68 @@
// @vitest-environment jsdom
import { describe, it, expect, beforeEach, vi } from 'vitest';
// auth.ts guards every localStorage access behind `browser`; force it true so the
// jsdom localStorage is actually used (the shared mock stubs it to false).
vi.mock('$app/environment', () => ({ browser: true, dev: false, building: false, version: 'test' }));
import { setAuth, getToken, getPin, getExpiry, getRole, clearAuth, clearPin } from './auth';
/** Build a JWT-shaped string (header.payload.sig) with the given claims. */
function makeJwt(claims: object): string {
const seg = (o: object) => btoa(JSON.stringify(o));
return `${seg({ alg: 'HS256', typ: 'JWT' })}.${seg(claims)}.sig`;
}
beforeEach(() => localStorage.clear());
describe('auth — token storage', () => {
it('setAuth then getToken/getPin round-trips', () => {
setAuth('a.b.c', '1234', 'uid-1', 'Alice');
expect(getToken()).toBe('a.b.c');
expect(getPin()).toBe('1234');
});
it('setAuth without a PIN leaves the PIN unset', () => {
setAuth('a.b.c', null, 'uid-1');
expect(getToken()).toBe('a.b.c');
expect(getPin()).toBeNull();
});
it('clearAuth removes the token but KEEPS the PIN (needed for recovery)', () => {
setAuth('a.b.c', '1234', 'uid');
clearAuth();
expect(getToken()).toBeNull();
expect(getPin()).toBe('1234');
});
it('clearPin removes the cached PIN', () => {
setAuth('a.b.c', '1234', 'uid');
clearPin();
expect(getPin()).toBeNull();
});
});
describe('auth — JWT claim decode', () => {
it('getExpiry decodes the exp claim (seconds → ms Date)', () => {
const exp = 2_000_000_000; // far-future unix seconds
setAuth(makeJwt({ exp }), null, 'u');
expect(getExpiry()?.getTime()).toBe(exp * 1000);
});
it('getExpiry is null with no token, no exp claim, or a malformed token', () => {
expect(getExpiry()).toBeNull(); // no token
setAuth(makeJwt({ role: 'guest' }), null, 'u'); // token without exp
expect(getExpiry()).toBeNull();
localStorage.setItem('eventsnap_jwt', 'not-a-jwt'); // unparseable
expect(getExpiry()).toBeNull();
});
it('getRole extracts the role claim; null when absent or malformed', () => {
setAuth(makeJwt({ role: 'host' }), null, 'u');
expect(getRole()).toBe('host');
setAuth(makeJwt({ exp: 1 }), null, 'u'); // no role claim
expect(getRole()).toBeNull();
localStorage.setItem('eventsnap_jwt', 'x.y.z'); // unparseable payload
expect(getRole()).toBeNull();
});
});

View File

@@ -0,0 +1,39 @@
import { describe, it, expect } from 'vitest';
import { avatarPalette, initials } from './avatar';
describe('avatarPalette', () => {
it('returns the neutral palette for empty / nullish names', () => {
expect(avatarPalette(null)).toContain('bg-gray-100');
expect(avatarPalette(undefined)).toContain('bg-gray-100');
expect(avatarPalette('')).toContain('bg-gray-100');
});
it('is deterministic for the same name', () => {
expect(avatarPalette('Alice')).toBe(avatarPalette('Alice'));
});
it('returns a real palette entry (not neutral) for a non-empty name', () => {
expect(avatarPalette('Bob')).toMatch(/bg-(blue|purple|green|amber|rose|teal)-100/);
});
});
describe('initials', () => {
it('returns "?" for empty / nullish / whitespace-only names', () => {
expect(initials(null)).toBe('?');
expect(initials(undefined)).toBe('?');
expect(initials('')).toBe('?');
expect(initials(' ')).toBe('?');
});
it('uses the first letter (uppercased) for a single word', () => {
expect(initials('alice')).toBe('A');
});
it('uses the first letters of the first two words', () => {
expect(initials('Alice Bob Carol')).toBe('AB');
});
it('collapses runs of whitespace between words', () => {
expect(initials(' john doe ')).toBe('JD');
});
});

View File

@@ -48,7 +48,9 @@
try {
stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode, width: { ideal: 1920 }, height: { ideal: 1080 } },
audio: true
// Only request the mic for video — a photo-only session shouldn't trigger
// a mic permission prompt (which also blocks capture on mic-less devices).
audio: mode === 'video'
});
if (videoEl) {
videoEl.srcObject = stream;
@@ -78,6 +80,14 @@
await startCamera();
}
// Switching between photo and video changes whether we need the mic, so
// re-acquire the stream (lazily adding the mic for video, dropping it for photo).
async function setMode(next: 'photo' | 'video') {
if (mode === next) return;
mode = next;
await startCamera();
}
function capturePhoto() {
if (!videoEl || !canvasEl) return;
const ctx = canvasEl.getContext('2d');
@@ -156,12 +166,20 @@
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M15 10l-4 4m0-4l4 4m6-4a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p class="text-sm text-white">{error}</p>
<button
onclick={onclose}
class="mt-4 rounded-lg bg-white/20 px-4 py-2 text-sm text-white"
>
Schliessen
</button>
<div class="mt-4 flex justify-center gap-2">
<button
onclick={startCamera}
class="rounded-lg bg-white px-4 py-2 text-sm font-medium text-gray-900"
>
Erneut versuchen
</button>
<button
onclick={onclose}
class="rounded-lg bg-white/20 px-4 py-2 text-sm text-white"
>
Schließen
</button>
</div>
</div>
</div>
{:else}
@@ -198,7 +216,7 @@
type="button"
role="tab"
aria-selected={mode === 'photo'}
onclick={() => (mode = 'photo')}
onclick={() => setMode('photo')}
data-testid="camera-mode-photo"
class="rounded-full px-4 py-1 text-sm font-medium transition {mode === 'photo' ? 'bg-white text-gray-900' : 'text-white/70 hover:text-white active:text-white'}"
>
@@ -208,7 +226,7 @@
type="button"
role="tab"
aria-selected={mode === 'video'}
onclick={() => (mode = 'video')}
onclick={() => setMode('video')}
data-testid="camera-mode-video"
class="rounded-full px-4 py-1 text-sm font-medium transition {mode === 'video' ? 'bg-white text-gray-900' : 'text-white/70 hover:text-white active:text-white'}"
>

View File

@@ -6,6 +6,7 @@
<script lang="ts">
import { focusTrap } from '$lib/actions/focus-trap';
import { scrollLock } from '$lib/actions/scroll-lock';
interface Props {
open: boolean;
@@ -50,6 +51,7 @@
class="fixed inset-0 z-50 bg-black/40"
aria-label="Schließen"
onclick={onCancel}
disabled={busy}
tabindex="-1"
></button>
<div
@@ -60,6 +62,7 @@
aria-labelledby={titleId}
data-testid="confirm-sheet"
use:focusTrap={{ onclose: onCancel }}
use:scrollLock
>
<div class="mb-4 flex justify-center">
<div class="h-1 w-10 rounded-full bg-gray-300 dark:bg-gray-600"></div>
@@ -77,17 +80,21 @@
onclick={handleConfirm}
disabled={busy}
data-testid="confirm-sheet-confirm"
class="mb-3 w-full rounded-xl py-3 text-sm font-semibold text-white transition disabled:opacity-60 {tone === 'danger'
class="mb-3 flex w-full items-center justify-center gap-2 rounded-xl py-3 text-sm font-semibold text-white transition disabled:opacity-60 {tone === 'danger'
? 'bg-red-600 hover:bg-red-700 active:bg-red-700 dark:bg-red-500 dark:hover:bg-red-400 dark:active:bg-red-400'
: 'bg-blue-600 hover:bg-blue-700 active:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400 dark:active:bg-blue-400'}"
>
{#if busy}
<span class="inline-block h-4 w-4 animate-spin rounded-full border-2 border-white/40 border-t-white" aria-hidden="true"></span>
{/if}
{confirmLabel}
</button>
<button
type="button"
onclick={onCancel}
disabled={busy}
data-testid="confirm-sheet-cancel"
class="w-full rounded-xl border border-gray-200 py-3 text-sm font-medium text-gray-700 transition hover:bg-gray-50 active:bg-gray-100 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800 dark:active:bg-gray-800"
class="w-full rounded-xl border border-gray-200 py-3 text-sm font-medium text-gray-700 transition hover:bg-gray-50 active:bg-gray-100 disabled:opacity-60 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800 dark:active:bg-gray-800"
>
{cancelLabel}
</button>

View File

@@ -22,6 +22,8 @@
title?: string;
}
import { scrollLock } from '$lib/actions/scroll-lock';
let { open, actions, onClose, title }: Props = $props();
let sheet = $state<HTMLDivElement | null>(null);
@@ -76,6 +78,12 @@
}
</script>
<!-- This sheet stays mounted (translate-y animation), so a sentinel that mounts only
while open drives the shared body scroll-lock. -->
{#if open}
<div use:scrollLock class="hidden"></div>
{/if}
<!-- Backdrop — real <button> so keyboard / switch-control users get parity. -->
<button
type="button"
@@ -95,9 +103,12 @@
class:translate-y-full={!open}
class:translate-y-0={open}
style="padding-bottom: env(safe-area-inset-bottom)"
role="dialog"
aria-modal="true"
role={open ? 'dialog' : undefined}
aria-modal={open ? 'true' : undefined}
aria-hidden={!open}
inert={!open}
tabindex="-1"
data-testid="context-sheet"
>
<div class="flex justify-center pt-3 pb-1">
<div class="h-1 w-10 rounded-full bg-gray-300 dark:bg-gray-600"></div>

View File

@@ -1,91 +0,0 @@
<script lang="ts">
import type { FeedUpload } from '$lib/types';
import { dataMode } from '$lib/data-mode-store';
import { longpress } from '$lib/actions/longpress';
interface Props {
uploads: FeedUpload[];
onlike: (id: string) => void;
oncomment: (id: string) => void;
onselect: (upload: FeedUpload) => void;
oncontextmenu?: (upload: FeedUpload) => void;
threeCol?: boolean;
}
let { uploads, onlike, oncomment, onselect, oncontextmenu, threeCol = false }: Props =
$props();
function isVideo(mime: string): boolean {
return mime.startsWith('video/');
}
// Grid uses small thumbnails by design even in Original mode — full media is one tap
// away in the lightbox, where the data-mode picker decides for real.
function tileUrl(upload: FeedUpload): string {
if (upload.thumbnail_url) return upload.thumbnail_url;
if (upload.preview_url) return upload.preview_url;
return $dataMode === 'original' ? `/api/v1/upload/${upload.id}/original` : '';
}
</script>
<div class="grid gap-0.5 {threeCol ? 'grid-cols-3' : 'grid-cols-2 sm:grid-cols-3'}">
{#each uploads as upload (upload.id)}
<div
class="group relative aspect-square cursor-pointer overflow-hidden rounded-lg bg-gray-100 dark:bg-gray-800"
use:longpress={{ duration: 500 }}
onlongpress={() => oncontextmenu?.(upload)}
>
<button
onclick={() => onselect(upload)}
class="block h-full w-full"
aria-label="Upload anzeigen"
>
{#if isVideo(upload.mime_type)}
<div class="flex h-full items-center justify-center bg-gray-800">
{#if tileUrl(upload)}
<img src={tileUrl(upload)} alt="" class="h-full w-full object-cover" />
{/if}
<div class="absolute inset-0 flex items-center justify-center">
<svg class="h-10 w-10 text-white/80" fill="currentColor" viewBox="0 0 24 24">
<path d="M8 5v14l11-7z" />
</svg>
</div>
</div>
{:else if tileUrl(upload)}
<img src={tileUrl(upload)} alt="" class="h-full w-full object-cover" loading="lazy" />
{:else}
<div class="flex h-full items-center justify-center text-gray-400">
<svg class="h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
</div>
{/if}
</button>
<!-- Overlay with name and stats -->
<div class="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/60 to-transparent p-2">
<p class="truncate text-xs font-medium text-white">{upload.uploader_name}</p>
<div class="mt-0.5 flex items-center gap-3 text-xs text-white/80">
<button
class="pointer-events-auto flex items-center gap-0.5"
onclick={(e) => { e.stopPropagation(); onlike(upload.id); }}
>
<svg class="h-3.5 w-3.5 {upload.liked_by_me ? 'fill-red-400 text-red-400' : ''}" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
</svg>
{upload.like_count}
</button>
<button
class="pointer-events-auto flex items-center gap-0.5"
onclick={(e) => { e.stopPropagation(); oncomment(upload.id); }}
>
<svg class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
</svg>
{upload.comment_count}
</button>
</div>
</div>
</div>
{/each}
</div>

View File

@@ -6,11 +6,9 @@
import { doubletap } from '$lib/actions/doubletap';
import { avatarPalette, initials } from '$lib/avatar';
import { vibrate } from '$lib/haptics';
import { now } from '$lib/now';
import HeartBurst from './HeartBurst.svelte';
// Single-tap debounce so a double-tap doesn't briefly open the lightbox.
const SINGLE_TAP_DELAY_MS = 260;
interface Props {
upload: FeedUpload;
isOwn?: boolean;
@@ -35,8 +33,8 @@
const mediaSrc = $derived(pickMediaUrl($dataMode, upload));
function relativeTime(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
function relativeTime(iso: string, nowMs: number): string {
const diff = nowMs - new Date(iso).getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return 'gerade eben';
if (mins < 60) return `vor ${mins} Min.`;
@@ -46,44 +44,35 @@
return `vor ${days} Tag${days === 1 ? '' : 'en'}`;
}
// Re-derives off the shared 60s clock so "vor 5 Min." actually advances.
const relTime = $derived(relativeTime(upload.created_at, $now));
function openContext() {
oncontextmenu?.(upload);
}
// Inline heart-burst on double-tap (consistent with the lightbox).
let heartBurst = $state(false);
let singleTapTimer: ReturnType<typeof setTimeout> | null = null;
function handleMediaClick() {
// Delay single-tap so a quick second tap (double-tap-to-like) wins.
if (singleTapTimer) clearTimeout(singleTapTimer);
singleTapTimer = setTimeout(() => {
singleTapTimer = null;
onselect(upload);
}, SINGLE_TAP_DELAY_MS);
}
let burstTimer: ReturnType<typeof setTimeout> | null = null;
function handleDoubleTap() {
if (singleTapTimer) {
clearTimeout(singleTapTimer);
singleTapTimer = null;
}
heartBurst = true;
vibrate(10);
onlike(upload.id);
setTimeout(() => (heartBurst = false), 700);
if (burstTimer) clearTimeout(burstTimer);
burstTimer = setTimeout(() => (heartBurst = false), 700);
}
// A feed-delta SSE event can remove this card mid-pending-tap. Clear the timer
// on unmount so we don't call onselect with a stale upload reference.
// Clear the burst timer on unmount (a feed-delta SSE event can remove this
// card mid-animation) so it can't fire against a stale component.
onDestroy(() => {
if (singleTapTimer) {
clearTimeout(singleTapTimer);
singleTapTimer = null;
}
if (burstTimer) clearTimeout(burstTimer);
});
</script>
<!-- Off-screen cards are removed from the DOM entirely by the parent VirtualFeed
window-virtualizer, so this card no longer needs content-visibility — and must
not use it, since the virtualizer measures each card's real rendered height. -->
<article
class="bg-white dark:bg-gray-900"
use:longpress={{ duration: 500 }}
@@ -100,7 +89,7 @@
</div>
<div class="min-w-0">
<p class="truncate text-sm font-semibold text-gray-900 dark:text-gray-100">{upload.uploader_name}</p>
<p class="text-xs text-gray-400 dark:text-gray-500">{relativeTime(upload.created_at)}</p>
<p class="text-xs text-gray-400 dark:text-gray-500">{relTime}</p>
</div>
</div>
@@ -120,9 +109,10 @@
<!-- Media -->
<button
class="relative block w-full"
onclick={handleMediaClick}
use:doubletap
onsingletap={() => onselect(upload)}
ondoubletap={handleDoubleTap}
onclick={(e) => { if (e.detail === 0) onselect(upload); }}
aria-label="Bild vergrößern"
>
<HeartBurst active={heartBurst} />
@@ -133,6 +123,8 @@
src={upload.thumbnail_url ?? upload.preview_url ?? ''}
alt=""
class="h-full w-full object-cover opacity-80"
loading="lazy"
decoding="async"
/>
{/if}
<div class="absolute inset-0 flex items-center justify-center">
@@ -144,13 +136,18 @@
</div>
</div>
{:else if mediaSrc}
<img
src={mediaSrc}
alt=""
class="w-full object-cover"
style="max-height: 80svh"
loading="lazy"
/>
<!-- Reserve the same 4/5 box the skeleton uses so the card doesn't collapse
to height 0 and reflow as images stream in. The uncropped original is one
tap away in the lightbox. -->
<div class="aspect-[4/5] w-full bg-gray-100 dark:bg-gray-800">
<img
src={mediaSrc}
alt=""
class="h-full w-full object-cover"
loading="lazy"
decoding="async"
/>
</div>
{:else}
<div class="flex aspect-square w-full items-center justify-center bg-gray-100 dark:bg-gray-800">
<svg class="h-12 w-12 text-gray-300 dark:text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
@@ -164,6 +161,8 @@
<div class="flex items-center gap-4 px-4 py-2">
<button
onclick={() => { vibrate(10); onlike(upload.id); }}
aria-pressed={upload.liked_by_me}
aria-label={upload.liked_by_me ? 'Gefällt mir nicht mehr' : 'Gefällt mir'}
class="flex items-center gap-1.5 text-sm font-medium transition-colors
{upload.liked_by_me ? 'text-red-500 dark:text-red-400' : 'text-gray-500 hover:text-red-400 active:text-red-400 dark:text-gray-400 dark:hover:text-red-400 dark:active:text-red-400'}"
>

View File

@@ -17,7 +17,8 @@
<div class="flex gap-2 overflow-x-auto pb-2">
<button
onclick={() => onselect(null)}
class="shrink-0 rounded-full px-3 py-1 text-sm font-medium transition {
aria-pressed={selected === null}
class="inline-flex min-h-11 shrink-0 items-center rounded-full px-4 py-2 text-sm font-medium transition {
selected === null
? 'bg-blue-600 text-white dark:bg-blue-500'
: 'bg-gray-200 text-gray-700 hover:bg-gray-300 active:bg-gray-300 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700 dark:active:bg-gray-700'
@@ -28,7 +29,8 @@
{#each hashtags as h (h.tag)}
<button
onclick={() => onselect(h.tag)}
class="shrink-0 rounded-full px-3 py-1 text-sm font-medium transition {
aria-pressed={selected === h.tag}
class="inline-flex min-h-11 shrink-0 items-center rounded-full px-4 py-2 text-sm font-medium transition {
selected === h.tag
? 'bg-blue-600 text-white dark:bg-blue-500'
: 'bg-gray-200 text-gray-700 hover:bg-gray-300 active:bg-gray-300 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700 dark:active:bg-gray-700'

View File

@@ -0,0 +1,55 @@
<script lang="ts">
// Icon-only button with a guaranteed ≥44px touch target (WCAG 2.5.5 / Apple HIG).
// The visible icon stays whatever size the caller renders; the hit area is
// enforced via min-h-11 min-w-11 (44px) so small glyphs are still comfortably
// tappable. Always require an `aria-label` since there's no text content.
import type { Snippet } from 'svelte';
interface Props {
/** Accessible name — required, the button has no visible text. */
label: string;
onclick?: (e: MouseEvent) => void;
disabled?: boolean;
title?: string;
type?: 'button' | 'submit';
tone?: 'neutral' | 'danger';
/** Marks toggle state for AT (e.g. like buttons). Omit for plain actions. */
pressed?: boolean;
/** Extra classes appended after the base styles. */
class?: string;
'data-testid'?: string;
children: Snippet;
}
let {
label,
onclick,
disabled = false,
title,
type = 'button',
tone = 'neutral',
pressed,
class: extra = '',
'data-testid': testid,
children
}: Props = $props();
const toneClass = $derived(
tone === 'danger'
? 'text-red-600 hover:bg-red-50 active:bg-red-100 dark:text-red-400 dark:hover:bg-red-950/40 dark:active:bg-red-950/60'
: 'text-gray-500 hover:bg-gray-100 active:bg-gray-200 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800 dark:active:bg-gray-700 dark:hover:text-gray-100'
);
</script>
<button
{type}
{onclick}
{disabled}
{title}
aria-label={label}
aria-pressed={pressed}
data-testid={testid}
class="inline-flex min-h-11 min-w-11 items-center justify-center rounded-full transition-colors disabled:opacity-50 disabled:pointer-events-none {toneClass} {extra}"
>
{@render children()}
</button>

View File

@@ -1,10 +1,12 @@
<script lang="ts">
import { onDestroy } from 'svelte';
import type { FeedUpload } from '$lib/types';
import { api } from '$lib/api';
import { getUserId } from '$lib/auth';
import { dataMode, pickMediaUrl } from '$lib/data-mode-store';
import { doubletap } from '$lib/actions/doubletap';
import { focusTrap } from '$lib/actions/focus-trap';
import { scrollLock } from '$lib/actions/scroll-lock';
import { toastError } from '$lib/toast-store';
import { vibrate } from '$lib/haptics';
import HeartBurst from './HeartBurst.svelte';
@@ -33,6 +35,7 @@
let loading = $state(false);
let userId = getUserId();
let heartBurst = $state(false);
let burstTimer: ReturnType<typeof setTimeout> | null = null;
const mediaSrc = $derived(pickMediaUrl($dataMode, upload));
@@ -40,9 +43,14 @@
heartBurst = true;
vibrate(10);
onlike(upload.id);
setTimeout(() => (heartBurst = false), 700);
if (burstTimer) clearTimeout(burstTimer);
burstTimer = setTimeout(() => (heartBurst = false), 700);
}
onDestroy(() => {
if (burstTimer) clearTimeout(burstTimer);
});
$effect(() => {
loadComments();
});
@@ -97,6 +105,7 @@
aria-modal="true"
aria-labelledby="lightbox-title"
use:focusTrap={{ onclose }}
use:scrollLock
>
<div class="flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl bg-white dark:bg-gray-900">
<!-- Media -->
@@ -104,7 +113,7 @@
<button
onclick={onclose}
aria-label="Schließen"
class="absolute right-2 top-2 z-10 rounded-full bg-black/50 p-1.5 text-white hover:bg-black/70 active:bg-black/70"
class="absolute right-2 top-2 z-10 inline-flex min-h-11 min-w-11 items-center justify-center rounded-full bg-black/50 text-white hover:bg-black/70 active:bg-black/70"
>
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />

View File

@@ -1,5 +1,6 @@
<script lang="ts">
import { focusTrap } from '$lib/actions/focus-trap';
import { scrollLock } from '$lib/actions/scroll-lock';
import type { Snippet } from 'svelte';
// Accessible name is REQUIRED. Pass `titleId` when the dialog renders its own
@@ -48,6 +49,7 @@
aria-labelledby={titleId}
aria-label={titleId ? undefined : ariaLabel}
use:focusTrap={{ onclose: onClose }}
use:scrollLock
>
<div class="pointer-events-auto w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900">
{@render children()}

View File

@@ -3,6 +3,7 @@
import { privacyNote } from '$lib/privacy-note-store';
import { themePreference, type ThemePreference } from '$lib/theme-store';
import { focusTrap } from '$lib/actions/focus-trap';
import { scrollLock } from '$lib/actions/scroll-lock';
import { vibrate } from '$lib/haptics';
const GUIDE_SEEN_KEY = 'eventsnap_guide_seen';
@@ -100,6 +101,7 @@
aria-modal="true"
aria-labelledby="onboarding-title"
use:focusTrap={{ onclose: dismiss }}
use:scrollLock
>
<!-- Step indicator — tap a pip to jump back. The visible dot is small but
the touch target is padded to ~44 px so it remains tappable on mobile. -->

View File

@@ -19,15 +19,17 @@
class="pointer-events-none fixed inset-x-0 z-[60] flex flex-col items-center gap-2 px-4"
style="bottom: calc(env(safe-area-inset-bottom) + 5rem)"
role="region"
aria-live="polite"
aria-label="Benachrichtigungen"
data-testid="toaster"
>
{#each $toasts as t (t.id)}
<!-- Errors/warnings interrupt (assertive/alert); successes wait their turn (polite/status). -->
<button
type="button"
onclick={() => dismissToast(t.id)}
class="pointer-events-auto w-full max-w-sm rounded-xl px-4 py-3 text-left text-sm font-medium shadow-lg transition active:scale-[0.98] {toneClasses(t.tone)}"
role={t.tone === 'error' || t.tone === 'warning' ? 'alert' : 'status'}
aria-live={t.tone === 'error' || t.tone === 'warning' ? 'assertive' : 'polite'}
data-testid="toast"
data-toast-tone={t.tone}
>

View File

@@ -19,10 +19,10 @@
function statusColor(status: QueueItem['status']): string {
switch (status) {
case 'pending': return 'text-gray-500';
case 'uploading': return 'text-blue-600';
case 'done': return 'text-green-600';
case 'error': return 'text-red-600';
case 'pending': return 'text-gray-500 dark:text-gray-400';
case 'uploading': return 'text-blue-600 dark:text-blue-400';
case 'done': return 'text-green-600 dark:text-green-400';
case 'error': return 'text-red-600 dark:text-red-400';
}
}
@@ -50,9 +50,9 @@
</script>
{#if items.length > 0}
<div class="mt-4 rounded-lg border border-gray-200 bg-white">
<div class="flex items-center justify-between border-b border-gray-100 px-4 py-3">
<h3 class="text-sm font-semibold text-gray-900">
<div class="mt-4 rounded-lg border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
<div class="flex items-center justify-between border-b border-gray-100 px-4 py-3 dark:border-gray-800">
<h3 class="text-sm font-semibold text-gray-900 dark:text-gray-100">
Upload-Warteschlange
{#if $isProcessing}
<span class="ml-2 inline-block h-2 w-2 animate-pulse rounded-full bg-blue-500"></span>
@@ -61,7 +61,7 @@
{#if hasCompleted}
<button
onclick={() => clearCompleted()}
class="text-xs text-gray-500 hover:text-gray-700"
class="inline-flex min-h-11 items-center px-1 text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
>
Fertige entfernen
</button>
@@ -69,18 +69,18 @@
</div>
{#if $rateLimitRetryAt && countdown > 0}
<div class="border-b border-amber-100 bg-amber-50 px-4 py-2 text-sm text-amber-800">
<div class="border-b border-amber-100 bg-amber-50 px-4 py-2 text-sm text-amber-800 dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-300">
Upload-Limit erreicht. Wird in {countdown} Sek. automatisch fortgesetzt.
</div>
{/if}
<ul class="divide-y divide-gray-100">
<ul class="divide-y divide-gray-100 dark:divide-gray-800">
{#each items as item (item.id)}
<li class="px-4 py-3">
<div class="flex items-center justify-between">
<div class="min-w-0 flex-1">
<p class="truncate text-sm font-medium text-gray-900">{item.fileName}</p>
<p class="text-xs text-gray-500">{formatSize(item.fileSize)}</p>
<p class="truncate text-sm font-medium text-gray-900 dark:text-gray-100">{item.fileName}</p>
<p class="text-xs text-gray-500 dark:text-gray-400">{formatSize(item.fileSize)}</p>
</div>
<div class="ml-3 flex items-center gap-2">
<span class="text-xs font-medium {statusColor(item.status)}">
@@ -89,7 +89,7 @@
{#if item.status === 'error'}
<button
onclick={() => retryItem(item.id)}
class="rounded bg-red-100 px-2 py-0.5 text-xs text-red-700 hover:bg-red-200"
class="inline-flex min-h-11 items-center rounded bg-red-100 px-3 text-xs font-medium text-red-700 hover:bg-red-200 dark:bg-red-950/40 dark:text-red-300 dark:hover:bg-red-950/60"
>
Erneut
</button>
@@ -97,7 +97,7 @@
{#if item.status === 'done' || item.status === 'error'}
<button
onclick={() => removeItem(item.id)}
class="text-gray-400 hover:text-gray-600"
class="inline-flex h-9 w-9 items-center justify-center text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300"
aria-label="Entfernen"
>
<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
@@ -109,17 +109,17 @@
</div>
{#if item.status === 'uploading'}
<div class="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-gray-200">
<div class="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-gray-700">
<div
class="h-full rounded-full bg-blue-500 transition-all duration-300"
style="width: {item.progress}%"
></div>
</div>
<p class="mt-1 text-right text-xs text-gray-400">{item.progress}%</p>
<p class="mt-1 text-right text-xs text-gray-400 dark:text-gray-500">{item.progress}%</p>
{/if}
{#if item.error}
<p class="mt-1 text-xs text-red-500">{item.error}</p>
<p class="mt-1 text-xs text-red-500 dark:text-red-400">{item.error}</p>
{/if}
</li>
{/each}

View File

@@ -2,11 +2,14 @@
import { goto } from '$app/navigation';
import { uploadSheetOpen } from '$lib/ui-store';
import { pendingFiles } from '$lib/pending-upload-store';
import { scrollLock } from '$lib/actions/scroll-lock';
import CameraCapture from '$lib/components/CameraCapture.svelte';
import type { PendingFile } from '$lib/pending-upload-store';
let showCamera = $state(false);
let fileInput: HTMLInputElement;
let sheet = $state<HTMLDivElement | null>(null);
let returnFocus: HTMLElement | null = null;
// Keep the sheet and backdrop always in the DOM for smooth CSS transitions.
let open = $derived($uploadSheetOpen);
@@ -15,6 +18,47 @@
uploadSheetOpen.set(false);
}
// Focus-trap + Escape, wired manually because the sheet stays mounted for its
// translate-y animation (so use:focusTrap, which activates on mount, won't do).
// Mirrors ContextSheet. Suspended while the camera overlay owns the screen.
function onKeyDown(e: KeyboardEvent) {
if (showCamera) return;
if (e.key === 'Escape') {
e.preventDefault();
close();
return;
}
if (e.key !== 'Tab' || !sheet) return;
const list = Array.from(sheet.querySelectorAll<HTMLElement>('button:not([disabled])'));
if (list.length === 0) return;
const first = list[0];
const last = list[list.length - 1];
const active = document.activeElement as HTMLElement | null;
if (e.shiftKey && (active === first || !sheet.contains(active))) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && active === last) {
e.preventDefault();
first.focus();
}
}
$effect(() => {
if (open) {
returnFocus = (document.activeElement as HTMLElement | null) ?? null;
requestAnimationFrame(() => {
if (showCamera) return;
const first = sheet?.querySelector<HTMLButtonElement>('button:not([disabled])');
first?.focus({ preventScroll: true });
});
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
} else if (returnFocus) {
try { returnFocus.focus({ preventScroll: true }); } catch { /* element gone */ }
returnFocus = null;
}
});
function openGallery() {
fileInput?.click();
}
@@ -68,22 +112,36 @@
onchange={handleFiles}
/>
<!-- Backdrop -->
<div
<!-- Lock body scroll only while open (sheet stays mounted for its animation). -->
{#if open && !showCamera}
<div use:scrollLock class="hidden"></div>
{/if}
<!-- Backdrop — real <button> so keyboard / switch-control users get parity. -->
<button
type="button"
class="fixed inset-0 z-40 bg-black/50 transition-opacity duration-300"
class:opacity-0={!open}
class:pointer-events-none={!open}
class:opacity-100={open}
onclick={close}
aria-hidden="true"
></div>
tabindex="-1"
aria-label="Schließen"
></button>
<!-- Sheet -->
<div
bind:this={sheet}
class="fixed inset-x-0 bottom-0 z-50 rounded-t-2xl bg-white transition-transform duration-300 dark:bg-gray-900"
class:translate-y-full={!open}
class:translate-y-0={open}
style="padding-bottom: env(safe-area-inset-bottom)"
role={open ? 'dialog' : undefined}
aria-modal={open ? 'true' : undefined}
aria-label="Hochladen"
aria-hidden={!open}
inert={!open}
tabindex="-1"
>
<!-- Drag handle -->
<div class="flex justify-center pt-3 pb-1">

View File

@@ -0,0 +1,305 @@
<script lang="ts">
// DOM-windowing for the feed. Only the cards/rows inside (and a small overscan
// around) the viewport are kept in the DOM — at ~1000 uploads this is the
// difference between ~1000 heavy cards (each with its own image, HeartBurst,
// long-press + double-tap listeners) and ~10-15.
//
// We use TanStack's *window* virtualizer (not an inner scroll container) on
// purpose: the feed scrolls the document, and the page's sticky header,
// pull-to-refresh, infinite-scroll sentinel and bottom nav all rely on that.
// The window virtualizer measures against `window` scroll, so every one of
// those keeps working untouched.
//
// Two layouts share one mechanism:
// list — one full-width FeedListCard per row, heights *measured* (captions
// make them variable). Keyed by upload id + `anchorTo:'start'` so an
// SSE prepend (new upload) doesn't yank a scrolled-down reader.
// grid — three square tiles per row, uniform height; still measured to shrug
// off sub-pixel drift over hundreds of rows.
import { createWindowVirtualizer } from '@tanstack/svelte-virtual';
import { untrack } from 'svelte';
import { get } from 'svelte/store';
import { browser } from '$app/environment';
import type { FeedUpload } from '$lib/types';
import { dataMode } from '$lib/data-mode-store';
import { longpress } from '$lib/actions/longpress';
import FeedListCard from './FeedListCard.svelte';
interface Props {
uploads: FeedUpload[];
mode: 'list' | 'grid';
myUserId: string | null;
onlike: (id: string) => void;
oncomment: (id: string) => void;
onselect: (upload: FeedUpload) => void;
oncontextmenu?: (upload: FeedUpload) => void;
}
let { uploads, mode, myUserId, onlike, oncomment, onselect, oncontextmenu }: Props =
$props();
const COLS = 3;
const GRID_GAP = 2; // px — matches the `gap-0.5` the non-virtual grid used.
const LIST_ESTIMATE = 700; // px — first-paint guess; real heights replace it on measure.
let listEl = $state<HTMLDivElement>();
let containerWidth = $state(0);
// Distance from the top of the document to the list container, i.e. the height
// of everything above it (sticky header + chips/search). Items' `start` values
// are document-absolute (they include this margin), so we feed it back as
// `scrollMargin` and subtract it again when positioning. Read live from layout
// (getBoundingClientRect + scrollY is scroll-independent) so it self-corrects
// when the header grows — e.g. grid filter chips appear.
let scrollMargin = $state(0);
const rowCount = $derived(mode === 'grid' ? Math.ceil(uploads.length / COLS) : uploads.length);
const colWidth = $derived(
containerWidth > 0 ? (containerWidth - (COLS - 1) * GRID_GAP) / COLS : 120
);
function isVideo(mime: string): boolean {
return mime.startsWith('video/');
}
// Grid tiles always use the small thumbnail — full media is one tap away in the
// lightbox where the data-mode picker decides for real.
function tileUrl(upload: FeedUpload): string {
if (upload.thumbnail_url) return upload.thumbnail_url;
if (upload.preview_url) return upload.preview_url;
return $dataMode === 'original' ? `/api/v1/upload/${upload.id}/original` : '';
}
// STABLE option callbacks — created once, never swapped. They read the live
// reactive values (`colWidth`, `uploads`, `mode`) at *call* time, so they stay
// current without needing a new function reference. This matters: `getItemKey`
// is a dependency of virtual-core's measurements memo, so handing it a fresh
// closure on every render would force an O(n) recompute. List keys by upload id
// (so an SSE prepend keeps measured heights attached to the right card); grid
// keys by row index (uniform rows, nothing to preserve).
const estimateSize = (_i: number) => (mode === 'grid' ? colWidth : LIST_ESTIMATE);
const getItemKey = (i: number) => (mode === 'list' ? (uploads[i]?.id ?? i) : i);
// `mode` is fixed for the lifetime of an instance (list and grid are rendered as
// separate <VirtualFeed> elements in the parent's {#if} branches, so toggling
// remounts rather than mutating this prop). Snapshot it without a reactive read
// to set the layout-constant options once.
const isGrid = untrack(() => mode === 'grid');
// Created with static placeholder count/margin; `applyOptions` pushes those.
const virtualizer = createWindowVirtualizer<HTMLDivElement>({
count: 0,
estimateSize,
getItemKey,
overscan: isGrid ? 4 : 3,
gap: isGrid ? GRID_GAP : 0,
anchorTo: 'start',
scrollMargin: 0
});
// Only `count` (load-more / prepend / delete) and `scrollMargin` (header height
// shifts) actually need to be pushed into the virtualizer. Like/comment SSE
// patches reassign `uploads` without changing its length — those must NOT
// trigger a setOptions (and its getBoundingClientRect reflow + store churn); the
// affected card re-renders through normal reactivity instead. We read the raw
// instance via `get()` rather than `$virtualizer` so writing never re-triggers
// this effect (that would loop).
let appliedCount = -1;
let appliedMargin = Number.NaN;
let appliedWidth = Number.NaN;
function applyOptions() {
const count = rowCount;
const width = containerWidth;
const margin = listEl ? listEl.getBoundingClientRect().top + window.scrollY : 0;
scrollMargin = margin; // drives the template transforms
// A width change (rotation, or the first 0→real clientWidth landing) changes
// every card's / tile-row's real height, so the heights cached from the old
// width are stale even when count and margin are unchanged. Invalidate the
// measurement cache so getTotalSize + positions recompute (rendered rows then
// re-measure immediately via their ResizeObserver) instead of trusting them.
const widthChanged = width > 0 && Math.abs(width - appliedWidth) > 0.5;
if (count === appliedCount && Math.abs(margin - appliedMargin) < 0.5 && !widthChanged) return;
appliedCount = count;
appliedMargin = margin;
appliedWidth = width;
get(virtualizer).setOptions({ count, scrollMargin: margin });
if (widthChanged) get(virtualizer).measure();
}
// Re-apply when the row count or container width changes (load-more, prepend,
// delete, filter, rotate). `containerWidth`/`rowCount` are the only tracked
// reads, so a length-stable like/comment patch doesn't re-run this.
$effect(() => {
void rowCount;
void containerWidth;
applyOptions();
});
// Header offset can also shift on resize without a count change (orientation,
// on-screen keyboard, font scaling).
$effect(() => {
if (!browser) return;
const onResize = () => applyOptions();
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
});
// Hand each rendered row to the virtualizer's ResizeObserver (it reads the row's
// `data-index` and caches the real height by item key). On `destroy` we call
// `measureElement(null)`, which sweeps now-disconnected nodes out of the
// internal cache + ResizeObserver — without it, every card that scrolls out of
// the window stays observed and retained, defeating the point of virtualizing.
function measure(node: HTMLDivElement) {
get(virtualizer).measureElement(node);
return {
update() {
get(virtualizer).measureElement(node);
},
destroy() {
get(virtualizer).measureElement(null);
}
};
}
</script>
<div bind:this={listEl} bind:clientWidth={containerWidth} class="w-full">
{#if browser}
<div style="position: relative; width: 100%; height: {$virtualizer.getTotalSize()}px;">
{#each $virtualizer.getVirtualItems() as item (item.key)}
{#if mode === 'list'}
{@const upload = uploads[item.index]}
<div
data-index={item.index}
use:measure
style="position: absolute; top: 0; left: 0; width: 100%; transform: translateY({item.start -
scrollMargin}px);"
>
{#if upload}
<FeedListCard
{upload}
isOwn={upload.user_id === myUserId}
{onlike}
{oncomment}
{onselect}
{oncontextmenu}
/>
{/if}
</div>
{:else}
<div
data-index={item.index}
use:measure
style="position: absolute; top: 0; left: 0; width: 100%; transform: translateY({item.start -
scrollMargin}px);"
>
<div class="grid grid-cols-3 gap-0.5">
{#each uploads.slice(item.index * COLS, item.index * COLS + COLS) as upload (upload.id)}
<!-- Tile — mirrors the markup the old FeedGrid used. -->
<div
class="group relative aspect-square cursor-pointer overflow-hidden rounded-lg bg-gray-100 dark:bg-gray-800"
use:longpress={{ duration: 500 }}
onlongpress={() => oncontextmenu?.(upload)}
>
<button
onclick={() => onselect(upload)}
class="block h-full w-full"
aria-label="Upload anzeigen"
>
{#if isVideo(upload.mime_type)}
<div class="flex h-full items-center justify-center bg-gray-800">
{#if tileUrl(upload)}
<img
src={tileUrl(upload)}
alt=""
class="h-full w-full object-cover"
loading="lazy"
decoding="async"
/>
{/if}
<div class="absolute inset-0 flex items-center justify-center">
<svg class="h-10 w-10 text-white/80" fill="currentColor" viewBox="0 0 24 24">
<path d="M8 5v14l11-7z" />
</svg>
</div>
</div>
{:else if tileUrl(upload)}
<img
src={tileUrl(upload)}
alt=""
class="h-full w-full object-cover"
loading="lazy"
decoding="async"
/>
{:else}
<div class="flex h-full items-center justify-center text-gray-400">
<svg class="h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="1.5"
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
/>
</svg>
</div>
{/if}
</button>
<div
class="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/60 to-transparent p-2"
>
<p class="truncate text-xs font-medium text-white">{upload.uploader_name}</p>
<div class="mt-0.5 flex items-center gap-3 text-xs text-white/80">
<button
class="pointer-events-auto -m-1 flex items-center gap-0.5 p-1"
onclick={(e) => {
e.stopPropagation();
onlike(upload.id);
}}
aria-pressed={upload.liked_by_me}
aria-label={upload.liked_by_me ? 'Gefällt mir nicht mehr' : 'Gefällt mir'}
>
<svg
class="h-4 w-4 {upload.liked_by_me ? 'fill-red-400 text-red-400' : ''}"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
/>
</svg>
{upload.like_count}
</button>
<button
class="pointer-events-auto -m-1 flex items-center gap-0.5 p-1"
onclick={(e) => {
e.stopPropagation();
oncomment(upload.id);
}}
aria-label="Kommentare anzeigen"
>
<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
/>
</svg>
{upload.comment_count}
</button>
</div>
</div>
</div>
{/each}
</div>
</div>
{/if}
{/each}
</div>
{/if}
</div>

View File

@@ -0,0 +1,28 @@
import { describe, it, expect } from 'vitest';
import { pickMediaUrl } from './data-mode-store';
const upload = {
id: 'abc-123',
preview_url: '/media/previews/p.jpg',
thumbnail_url: '/media/thumbnails/t.jpg',
};
describe('pickMediaUrl', () => {
it('original mode → the original API route, ignoring preview/thumbnail', () => {
expect(pickMediaUrl('original', upload)).toBe('/api/v1/upload/abc-123/original');
});
it('saver mode → preview_url when present', () => {
expect(pickMediaUrl('saver', upload)).toBe('/media/previews/p.jpg');
});
it('saver mode → thumbnail_url when preview is null', () => {
expect(pickMediaUrl('saver', { ...upload, preview_url: null })).toBe('/media/thumbnails/t.jpg');
});
it('saver mode → original route when both preview and thumbnail are null', () => {
expect(pickMediaUrl('saver', { id: 'x', preview_url: null, thumbnail_url: null })).toBe(
'/api/v1/upload/x/original'
);
});
});

View File

@@ -1,11 +1,13 @@
// Per-device "Datenmodus" — Saver loads compressed previews (default), Original loads
// the full file via the auth-gated `/api/v1/upload/{id}/original` endpoint.
// the full file via the `/api/v1/upload/{id}/original` endpoint. That route is
// intentionally unauthenticated (the UUID acts as the capability) so it works from
// plain `<img src>` / `<video src>` without an Authorization header.
//
// Stored per-device in localStorage (not per-user) because data plans are a property
// of the device the guest is currently holding, not their identity.
//
// Used by:
// - Feed cards (FeedListCard / FeedGrid) to pick which URL to render
// - Feed cards (FeedListCard / VirtualFeed grid tiles) to pick which URL to render
// - Lightbox
// - Diashow
// See [docs/FEATURES.md §2.5] for the user-facing model.

View File

@@ -0,0 +1,59 @@
import { describe, it, expect } from 'vitest';
import { filterUploads, type FeedFilter } from './feed-filter';
// filterUploads only reads `caption` and `uploader_name`, so a partial shape suffices.
const u = (id: string, uploader_name: string, caption: string | null) =>
({ id, uploader_name, caption }) as any;
const uploads = [
u('1', 'Alice', 'pic #wedding'),
u('2', 'Bob', 'party #party'),
u('3', 'Alice', 'more #wedding #party'),
u('4', 'Carol', 'no tags here'),
u('5', 'Bob', null), // no caption
];
const ids = (r: any[]) => r.map((x) => x.id);
const tag = (value: string): FeedFilter => ({ type: 'tag', value });
const user = (value: string): FeedFilter => ({ type: 'user', value });
describe('filterUploads', () => {
it('no filters → returns all uploads unchanged', () => {
expect(filterUploads(uploads, [])).toBe(uploads);
});
it('a single tag matches uploads whose caption contains it', () => {
expect(ids(filterUploads(uploads, [tag('wedding')]))).toEqual(['1', '3']);
});
it('two tags combine with OR', () => {
expect(ids(filterUploads(uploads, [tag('wedding'), tag('party')]))).toEqual(['1', '2', '3']);
});
it('a single user matches only that uploader', () => {
expect(ids(filterUploads(uploads, [user('Alice')]))).toEqual(['1', '3']);
});
it('two users combine with OR', () => {
expect(ids(filterUploads(uploads, [user('Alice'), user('Bob')]))).toEqual(['1', '2', '3', '5']);
});
it('a user chip and a tag chip combine with AND', () => {
// Alice AND #wedding → only Alice's wedding uploads (not Bob's #wedding, not Alice's #party-only)
expect(ids(filterUploads(uploads, [user('Alice'), tag('wedding')]))).toEqual(['1', '3']);
});
it('AND excludes an uploader-match that lacks the tag', () => {
// Bob AND #wedding → none (Bob has #party and a null caption, no #wedding)
expect(filterUploads(uploads, [user('Bob'), tag('wedding')])).toHaveLength(0);
});
it('tag matching is case-insensitive against the caption', () => {
expect(filterUploads([u('9', 'X', 'PIC #WeDDing')], [tag('wedding')])).toHaveLength(1);
});
it('a null caption never matches a tag but can match a user', () => {
expect(filterUploads([u('5', 'Bob', null)], [tag('party')])).toHaveLength(0);
expect(filterUploads([u('5', 'Bob', null)], [user('Bob')])).toHaveLength(1);
});
});

View File

@@ -0,0 +1,35 @@
// Grid-view feed filtering. Extracted from feed/+page.svelte so the OR/AND
// combination rules are unit-testable without mounting the page.
import type { FeedUpload } from './types';
export interface FeedFilter {
type: 'tag' | 'user';
value: string;
}
/**
* Apply the active grid filters to a list of uploads.
*
* Combination rules (mirroring the chip UI):
* - Tags combine with **OR**: a card passes the tag group if its caption contains
* ANY selected `#tag`.
* - Users combine with **OR** within the user group (uploader is one of the
* selected names).
* - The tag group and the user group combine with **AND**: a card must satisfy
* both groups. An empty group is a pass-through.
*
* Tags are matched against the caption text (the autocomplete source), so `value`
* is expected lowercase (as produced by the tag suggestions).
*/
export function filterUploads(uploads: FeedUpload[], filters: FeedFilter[]): FeedUpload[] {
if (filters.length === 0) return uploads;
const tags = filters.filter((f) => f.type === 'tag').map((f) => f.value);
const users = filters.filter((f) => f.type === 'user').map((f) => f.value);
return uploads.filter((u) => {
const cap = (u.caption ?? '').toLowerCase();
const passTag = !tags.length || tags.some((t) => cap.includes('#' + t));
const passUser = !users.length || users.includes(u.uploader_name);
return passTag && passUser;
});
}

10
frontend/src/lib/now.ts Normal file
View File

@@ -0,0 +1,10 @@
import { readable } from 'svelte/store';
// A single 60-second clock shared by every component that renders a relative
// timestamp ("vor 5 Min."). One interval for the whole app — not one per card —
// so a 1000-item feed stays cheap, and the interval is torn down automatically
// when the last subscriber unsubscribes.
export const now = readable(Date.now(), (set) => {
const id = setInterval(() => set(Date.now()), 60_000);
return () => clearInterval(id);
});

View File

@@ -1,7 +1,6 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { getToken } from '$lib/auth';
import { browser } from '$app/environment';
import { onMount } from 'svelte';
onMount(() => {
@@ -12,3 +11,11 @@
}
});
</script>
<!-- Brief branded splash so the redirect doesn't flash a blank page. -->
<div class="flex min-h-screen items-center justify-center bg-gray-50 dark:bg-gray-950">
<div class="flex flex-col items-center gap-3">
<div class="h-8 w-8 animate-spin rounded-full border-2 border-gray-300 border-t-blue-600 dark:border-gray-700 dark:border-t-blue-400"></div>
<p class="text-sm font-medium text-gray-400 dark:text-gray-500">EventSnap</p>
</div>
</div>

View File

@@ -127,9 +127,9 @@
function roleColor(r: string | null): string {
switch (r) {
case 'admin': return 'bg-red-100 text-red-700';
case 'host': return 'bg-purple-100 text-purple-700';
default: return 'bg-blue-100 text-blue-700';
case 'admin': return 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-200';
case 'host': return 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-200';
default: return 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-200';
}
}
@@ -137,7 +137,7 @@
<div class="min-h-screen bg-gray-50 pb-24 dark:bg-gray-950">
<!-- Header -->
<div class="border-b border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
<div class="border-b border-gray-200 bg-white pt-[env(safe-area-inset-top)] dark:border-gray-800 dark:bg-gray-900">
<div class="mx-auto flex max-w-lg items-center px-4 py-4">
<h1 class="text-xl font-bold text-gray-900 dark:text-gray-100">Mein Konto</h1>
</div>
@@ -213,7 +213,7 @@
<span class="font-mono text-4xl font-bold tracking-widest text-gray-900 dark:text-gray-100">{$pin}</span>
<button
onclick={copyPin}
class="rounded-md bg-amber-100 px-3 py-1.5 text-sm font-medium text-amber-800 transition hover:bg-amber-200 dark:bg-amber-900/40 dark:text-amber-200 dark:hover:bg-amber-900/60"
class="inline-flex min-h-11 items-center rounded-md bg-amber-100 px-4 py-2 text-sm font-medium text-amber-800 transition hover:bg-amber-200 dark:bg-amber-900/40 dark:text-amber-200 dark:hover:bg-amber-900/60"
>
{pinCopied ? 'Kopiert!' : 'Kopieren'}
</button>
@@ -250,9 +250,9 @@
</div>
<div class="grid grid-cols-3 gap-2 p-3" role="radiogroup" aria-label="Design">
{#each [
{ value: 'system', label: 'System', icon: '🖥️' },
{ value: 'light', label: 'Hell', icon: '☀️' },
{ value: 'dark', label: 'Dunkel', icon: '🌙' }
{ value: 'system', label: 'System' },
{ value: 'light', label: 'Hell' },
{ value: 'dark', label: 'Dunkel' }
] as opt (opt.value)}
{@const selected = $themePreference === opt.value}
<button
@@ -265,7 +265,16 @@
? 'border-blue-600 bg-blue-50 text-blue-700 dark:border-blue-500 dark:bg-blue-950/40 dark:text-blue-200'
: 'border-gray-200 text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-200 dark:hover:bg-gray-700/50'}"
>
<span class="text-2xl leading-none">{opt.icon}</span>
<!-- SVG icons render consistently everywhere (emoji show as tofu on some Android). -->
<svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
{#if opt.value === 'system'}
<path stroke-linecap="round" stroke-linejoin="round" d="M9 17.25v1.007a3 3 0 0 1-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0 1 15 18.257V17.25m6-12V15a2.25 2.25 0 0 1-2.25 2.25H5.25A2.25 2.25 0 0 1 3 15V5.25A2.25 2.25 0 0 1 5.25 3h13.5A2.25 2.25 0 0 1 21 5.25Z" />
{:else if opt.value === 'light'}
<path stroke-linecap="round" stroke-linejoin="round" d="M12 3v2.25m6.364.386-1.591 1.591M21 12h-2.25m-.386 6.364-1.591-1.591M12 18.75V21m-4.773-4.227-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z" />
{:else}
<path stroke-linecap="round" stroke-linejoin="round" d="M21.752 15.002A9.718 9.718 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998Z" />
{/if}
</svg>
<span class="font-medium">{opt.label}</span>
</button>
{/each}

View File

@@ -6,6 +6,7 @@
import { toast, toastError } from '$lib/toast-store';
import ConfirmSheet from '$lib/components/ConfirmSheet.svelte';
import Modal from '$lib/components/Modal.svelte';
import IconButton from '$lib/components/IconButton.svelte';
interface StatsDto {
user_count: number;
@@ -136,6 +137,24 @@
const myRole = getRole();
// Generic confirm-then-run for irreversible / privilege-changing actions
// (promote, demote, unban, release gallery). Reuses the shared ConfirmSheet.
interface PendingConfirm {
title: string;
message: string;
confirmLabel: string;
tone: 'default' | 'danger';
run: () => Promise<void>;
}
let confirmAction = $state<PendingConfirm | null>(null);
async function runConfirmAction() {
const action = confirmAction;
if (!action) return;
await action.run();
confirmAction = null;
}
onMount(async () => {
const token = getToken();
const role = getRole();
@@ -173,7 +192,20 @@
}
}
// Keys rendered as number inputs — used to reject empty/invalid numeric saves.
const NUMBER_KEYS = new Set(
CONFIG_GROUPS.flatMap((g) => g.fields.filter((f) => f.kind === 'number').map((f) => f.key))
);
async function saveConfig() {
// Don't let a cleared number field persist as an empty/NaN config value.
for (const key of NUMBER_KEYS) {
const v = configDraft[key];
if (v !== undefined && v !== config[key] && (String(v).trim() === '' || !Number.isFinite(Number(v)))) {
toastError(new Error('Bitte gib für alle Zahlenfelder einen gültigen Wert ein.'));
return;
}
}
saving = true;
try {
const changes: Record<string, string> = {};
@@ -323,6 +355,17 @@
}
</script>
<!-- Confirmation for irreversible / privilege-changing actions (promote/demote/unban/release). -->
<ConfirmSheet
open={confirmAction !== null}
title={confirmAction?.title ?? ''}
message={confirmAction?.message ?? ''}
confirmLabel={confirmAction?.confirmLabel ?? 'Bestätigen'}
tone={confirmAction?.tone ?? 'default'}
onConfirm={runConfirmAction}
onCancel={() => (confirmAction = null)}
/>
<!-- PIN reset confirmation — pure yes/no, uses the shared ConfirmSheet. -->
<ConfirmSheet
open={pinResetTarget !== null}
@@ -380,17 +423,13 @@
<div class="min-h-screen bg-gray-50 pb-24 dark:bg-gray-950">
<!-- Header -->
<div class="border-b border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
<div class="border-b border-gray-200 bg-white pt-[env(safe-area-inset-top)] dark:border-gray-800 dark:bg-gray-900">
<div class="mx-auto flex max-w-3xl items-center gap-3 px-4 py-4">
<button
onclick={() => goto('/account')}
class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-gray-500 transition hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-800"
aria-label="Zurück"
>
<IconButton label="Zurück" onclick={() => goto('/account')} class="shrink-0">
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18" />
</svg>
</button>
</IconButton>
<h1 class="text-xl font-bold text-gray-900 dark:text-gray-100">Admin-Dashboard</h1>
</div>
</div>
@@ -414,7 +453,7 @@
{#if loading}
<div class="py-16 text-center text-gray-400 dark:text-gray-500">Laden…</div>
{:else if error}
<div class="rounded-lg bg-red-50 p-4 text-sm text-red-700">{error}</div>
<div role="alert" class="rounded-lg bg-red-50 p-4 text-sm text-red-700 dark:bg-red-950/40 dark:text-red-300">{error}</div>
{:else}
<!-- ── Stats tab ────────────────────────────────────────────────── -->
@@ -500,6 +539,8 @@
id={field.key}
type="number"
step="any"
min="0"
inputmode="decimal"
bind:value={configDraft[field.key]}
class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-200 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-100"
/>
@@ -532,7 +573,13 @@
<div class="rounded-xl border border-gray-200 bg-white p-5 dark:border-gray-700 dark:bg-gray-800">
<h3 class="mb-3 font-semibold text-gray-900 dark:text-gray-100">Galerie</h3>
<button
onclick={releaseGallery}
onclick={() => (confirmAction = {
title: 'Galerie freigeben?',
message: 'Gäste können dann alle Fotos herunterladen. Das kann nicht rückgängig gemacht werden.',
confirmLabel: 'Freigeben',
tone: 'danger',
run: releaseGallery
})}
class="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400"
>
Galerie freigeben
@@ -625,17 +672,35 @@
<div class="flex shrink-0 flex-wrap justify-end gap-1.5">
{#if user.role !== 'admin'}
{#if user.is_banned}
<button onclick={() => unban(user)} class="rounded-lg bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600">
<button onclick={() => (confirmAction = {
title: 'Sperre aufheben?',
message: `${user.display_name} kann danach wieder hochladen, liken und kommentieren.`,
confirmLabel: 'Entsperren',
tone: 'default',
run: () => unban(user)
})} class="rounded-lg bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600">
Entsperren
</button>
{:else}
{#if user.role === 'guest'}
<button onclick={() => promoteToHost(user)} class="rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-medium text-blue-700 hover:bg-blue-100 dark:bg-blue-900/40 dark:text-blue-200 dark:hover:bg-blue-900/60">
<button onclick={() => (confirmAction = {
title: 'Zum Host befördern?',
message: `${user.display_name} erhält Host-Rechte: sperren, PIN zurücksetzen und Galerie verwalten. Das lässt sich nur durch Degradieren rückgängig machen.`,
confirmLabel: 'Befördern',
tone: 'default',
run: () => promoteToHost(user)
})} class="rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-medium text-blue-700 hover:bg-blue-100 dark:bg-blue-900/40 dark:text-blue-200 dark:hover:bg-blue-900/60">
Host
</button>
{/if}
{#if user.role === 'host'}
<button onclick={() => demoteToGuest(user)} class="rounded-lg bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600">
<button onclick={() => (confirmAction = {
title: 'Zum Gast degradieren?',
message: `${user.display_name} verliert alle Host-Rechte.`,
confirmLabel: 'Degradieren',
tone: 'danger',
run: () => demoteToGuest(user)
})} class="rounded-lg bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600">
Degradieren
</button>
{/if}

View File

@@ -98,6 +98,14 @@
overlayHideTimer = setTimeout(() => (showOverlay = false), 4000);
}
// Manual toggle from the always-visible control button — stays open (no
// auto-hide) so keyboard users can tab through the controls without them
// vanishing mid-interaction.
function toggleOverlay() {
if (overlayHideTimer) clearTimeout(overlayHideTimer);
showOverlay = !showOverlay;
}
function togglePause() {
paused = !paused;
if (paused) {
@@ -166,19 +174,52 @@
<div class="text-white/60">Lade…</div>
{/if}
<!-- Always-visible controls: keyboard-reachable, so the show is never a trap and
the controls are reachable without a pointer. Honours the notch. -->
<div
class="absolute right-0 top-0 z-10 flex gap-2 p-3"
style="padding-top: calc(env(safe-area-inset-top) + 0.75rem)"
>
<button
type="button"
onclick={(e) => { e.stopPropagation(); toggleOverlay(); }}
aria-label="Steuerung anzeigen"
aria-expanded={showOverlay}
class="inline-flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/20"
>
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
<path stroke-linecap="round" stroke-linejoin="round" d="M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75" />
</svg>
</button>
<button
type="button"
onclick={(e) => { e.stopPropagation(); exit(); }}
aria-label="Diashow beenden"
class="inline-flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/20"
>
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
</button>
</div>
{#if showOverlay}
<!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions -->
<div
class="absolute inset-x-0 bottom-0 flex flex-col gap-3 bg-gradient-to-t from-black/90 via-black/60 to-transparent p-6 pb-10"
onclick={(e) => e.stopPropagation()}
>
<div class="flex flex-wrap items-center gap-2">
<button
type="button"
onclick={togglePause}
class="rounded-full bg-white/10 px-4 py-2 text-sm font-medium hover:bg-white/20"
class="inline-flex items-center gap-1.5 rounded-full bg-white/10 px-4 py-2 text-sm font-medium hover:bg-white/20"
>
{paused ? '▶ Fortsetzen' : '⏸ Pause'}
{#if paused}
<svg class="h-4 w-4" fill="currentColor" viewBox="0 0 24 24"><path d="M8 5v14l11-7z" /></svg>
Fortsetzen
{:else}
<svg class="h-4 w-4" fill="currentColor" viewBox="0 0 24 24"><path d="M6 5h4v14H6zM14 5h4v14h-4z" /></svg>
Pause
{/if}
</button>
<label class="flex items-center gap-2 rounded-full bg-white/10 px-3 py-2 text-sm">
@@ -206,9 +247,10 @@
<button
type="button"
onclick={exit}
class="ml-auto rounded-full bg-white/10 px-4 py-2 text-sm font-medium hover:bg-white/20"
class="ml-auto inline-flex items-center gap-1.5 rounded-full bg-white/10 px-4 py-2 text-sm font-medium hover:bg-white/20"
>
✕ Beenden
<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
Beenden
</button>
</div>

View File

@@ -6,6 +6,7 @@
import { connectSse, disconnectSse, onSseEvent } from '$lib/sse';
import { toastError } from '$lib/toast-store';
import { focusTrap } from '$lib/actions/focus-trap';
import IconButton from '$lib/components/IconButton.svelte';
interface JobStatus {
status: 'locked' | 'pending' | 'running' | 'done' | 'failed';
@@ -75,35 +76,33 @@
}
}
async function downloadFile(endpoint: string, filename: string) {
// Stream the (potentially multi-GB) archive straight to disk via a top-level
// download navigation instead of fetch()+blob() — buffering the whole ZIP in
// memory crashes mobile Safari/Chrome. The navigation can't send the Bearer
// header, so we first exchange the token for a single-use ticket and pass it
// as a query param; the server responds with Content-Disposition: attachment,
// so the browser downloads it and we stay on the page.
async function downloadFile(endpoint: string) {
try {
const token = getToken();
const res = await fetch(endpoint, {
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
if (!res.ok) {
toastError(new Error(`Download fehlgeschlagen (${res.status}).`));
return;
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const { ticket } = await api.post<{ ticket: string }>('/export/ticket');
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.href = `${endpoint}?ticket=${encodeURIComponent(ticket)}`;
a.rel = 'noopener';
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(url);
a.remove();
} catch (e) {
toastError(e);
}
}
function downloadZip() {
downloadFile('/api/v1/export/zip', 'Gallery.zip');
downloadFile('/api/v1/export/zip');
}
function downloadHtml() {
if (localStorage.getItem(HTML_GUIDE_KEY)) {
downloadFile('/api/v1/export/html', 'Memories.zip');
downloadFile('/api/v1/export/html');
} else {
showHtmlGuide = true;
}
@@ -112,7 +111,7 @@
function confirmHtmlDownload() {
localStorage.setItem(HTML_GUIDE_KEY, '1');
showHtmlGuide = false;
downloadFile('/api/v1/export/html', 'Memories.zip');
downloadFile('/api/v1/export/html');
}
</script>
@@ -154,19 +153,13 @@
{/if}
<div class="min-h-screen bg-gray-50 pb-24 dark:bg-gray-950">
<div class="border-b border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
<div class="border-b border-gray-200 bg-white pt-[env(safe-area-inset-top)] dark:border-gray-800 dark:bg-gray-900">
<div class="mx-auto flex max-w-lg items-center gap-2 px-4 py-4">
<button
type="button"
onclick={() => goto('/feed')}
data-testid="export-back"
class="-ml-2 flex h-9 w-9 items-center justify-center rounded-full text-gray-500 transition hover:bg-gray-100 active:bg-gray-200 dark:text-gray-400 dark:hover:bg-gray-800 dark:active:bg-gray-700"
aria-label="Zurück"
>
<IconButton label="Zurück" onclick={() => goto('/feed')} data-testid="export-back" class="-ml-2">
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5 8.25 12l7.5-7.5" />
</svg>
</button>
</IconButton>
<h1 class="text-xl font-bold text-gray-900 dark:text-gray-100">Export</h1>
</div>
</div>

View File

@@ -4,8 +4,7 @@
import { api } from '$lib/api';
import { connectSse, disconnectSse, onSseEvent } from '$lib/sse';
import { onMount, onDestroy } from 'svelte';
import FeedGrid from '$lib/components/FeedGrid.svelte';
import FeedListCard from '$lib/components/FeedListCard.svelte';
import VirtualFeed from '$lib/components/VirtualFeed.svelte';
import HashtagChips from '$lib/components/HashtagChips.svelte';
import LightboxModal from '$lib/components/LightboxModal.svelte';
import OnboardingGuide from '$lib/components/OnboardingGuide.svelte';
@@ -16,6 +15,7 @@
import { toast, toastError } from '$lib/toast-store';
import { pullToRefresh } from '$lib/actions/pull-to-refresh';
import { vibrate } from '$lib/haptics';
import { filterUploads } from '$lib/feed-filter';
import type { FeedUpload, FeedResponse, HashtagCount, DeltaResponse } from '$lib/types';
let uploads = $state<FeedUpload[]>([]);
@@ -28,6 +28,8 @@
let pullProgress = $state(0); // 01+ during the drag, 0 when idle
let selectedUpload = $state<FeedUpload | null>(null);
let sentinel: HTMLDivElement;
let feedObserver: IntersectionObserver | null = null;
let inPlaceRefreshTimer: ReturnType<typeof setTimeout> | null = null;
let pendingDeleteId = $state<string | null>(null);
// ─────────────────────────────────────────────────────────────────────────
@@ -148,14 +150,7 @@
// ── Filtered uploads for grid view ───────────────────────────────────────
let displayUploads = $derived.by(() => {
if (viewMode === 'list' || activeFilters.length === 0) return uploads;
const tags = activeFilters.filter((f) => f.type === 'tag').map((f) => f.value);
const users = activeFilters.filter((f) => f.type === 'user').map((f) => f.value);
return uploads.filter((u) => {
const cap = (u.caption ?? '').toLowerCase();
const passTag = !tags.length || tags.some((t) => cap.includes('#' + t));
const passUser = !users.length || users.includes(u.uploader_name);
return passTag && passUser;
});
return filterUploads(uploads, activeFilters);
});
// ─────────────────────────────────────────────────────────────────────────
@@ -190,7 +185,10 @@
uploads = [upload, ...uploads];
} catch { /* ignore */ }
}),
onSseEvent('upload-processed', () => loadFeed(true)),
// A processed upload gains preview/thumbnail URLs. Coalesce bursts (bulk
// uploads fire one per file) into a single in-place merge so the feed
// neither hammers the server nor collapses to page 1 / loses scroll.
onSseEvent('upload-processed', () => scheduleInPlaceRefresh()),
onSseEvent('upload-deleted', (data) => {
try {
const payload = JSON.parse(data) as { upload_id: string };
@@ -198,8 +196,11 @@
if (selectedUpload?.id === payload.upload_id) selectedUpload = null;
} catch { /* ignore */ }
}),
onSseEvent('like-update', () => loadFeed(true)),
onSseEvent('new-comment', () => loadFeed(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.
onSseEvent('like-update', (data) => patchCount(data, 'like_count')),
onSseEvent('new-comment', (data) => patchCount(data, 'comment_count')),
// Synthetic event from the SSE client after a foreground reconnect — merge
// any uploads + deletions we missed while the tab was hidden.
onSseEvent('feed-delta', (data) => {
@@ -219,21 +220,68 @@
);
if (sentinel) {
const observer = new IntersectionObserver(
feedObserver = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && nextCursor && !loadingMore) loadMore();
},
{ rootMargin: '200px' }
);
observer.observe(sentinel);
feedObserver.observe(sentinel);
}
});
onDestroy(() => {
disconnectSse();
for (const unsub of unsubscribers) unsub();
feedObserver?.disconnect();
if (inPlaceRefreshTimer) clearTimeout(inPlaceRefreshTimer);
});
// Patch a single upload's like/comment count from an SSE payload without
// disturbing scroll position or the rest of the loaded feed.
function patchCount(data: string, field: 'like_count' | 'comment_count') {
try {
const payload = JSON.parse(data) as {
upload_id: string;
like_count?: number;
comment_count?: number;
};
const value = payload[field];
if (value === undefined) return;
uploads = uploads.map((u) => (u.id === payload.upload_id ? { ...u, [field]: value } : u));
if (selectedUpload?.id === payload.upload_id) {
selectedUpload = { ...selectedUpload, [field]: value };
}
} catch { /* ignore malformed payloads */ }
}
// Debounced page-1 fetch that *merges* (updates existing cards in place, prepends
// genuinely new ones) rather than replacing the array — preserves scroll and any
// pages already loaded below the fold.
function scheduleInPlaceRefresh() {
if (inPlaceRefreshTimer) return;
inPlaceRefreshTimer = setTimeout(() => {
inPlaceRefreshTimer = null;
void refreshFeedInPlace();
}, 800);
}
async function refreshFeedInPlace() {
try {
const params = new URLSearchParams();
if (selectedHashtag) params.set('hashtag', selectedHashtag);
params.set('limit', '20');
const res = await api.get<FeedResponse>(`/feed?${params}`);
const byId = new Map(res.uploads.map((u) => [u.id, u]));
const known = new Set(uploads.map((u) => u.id));
uploads = uploads.map((u) => byId.get(u.id) ?? u);
const fresh = res.uploads.filter((u) => !known.has(u.id));
if (fresh.length) uploads = [...fresh, ...uploads];
} catch {
// Background refresh — stay quiet, the next event or pull-to-refresh retries.
}
}
async function loadFeed(refresh = false) {
try {
const params = new URLSearchParams();
@@ -359,7 +407,7 @@
<!-- Live pull-progress indicator: grows during the drag, rotates past threshold,
swaps to a spinner once the network refresh kicks off. -->
{#if refreshing || pullProgress > 0}
<div class="pointer-events-none fixed left-0 right-0 top-2 z-40 flex justify-center">
<div class="pointer-events-none fixed left-0 right-0 top-[calc(env(safe-area-inset-top)+0.5rem)] z-40 flex justify-center">
<div
class="rounded-full bg-white/90 px-3 py-1 text-xs font-medium text-blue-600 shadow transition-opacity dark:bg-gray-900/90 dark:text-blue-300"
style="opacity: {refreshing ? 1 : Math.min(1, pullProgress)}"
@@ -386,7 +434,7 @@
</div>
{/if}
<!-- Sticky header — opaque fallback for browsers without backdrop-filter. -->
<div class="sticky top-0 z-30 border-b border-gray-200 bg-white/95 backdrop-blur supports-[not(backdrop-filter:blur(0))]:bg-white dark:border-gray-800 dark:bg-gray-900/95 dark:supports-[not(backdrop-filter:blur(0))]:bg-gray-900">
<div class="sticky top-0 z-30 border-b border-gray-200 bg-white/95 pt-[env(safe-area-inset-top)] backdrop-blur supports-[not(backdrop-filter:blur(0))]:bg-white dark:border-gray-800 dark:bg-gray-900/95 dark:supports-[not(backdrop-filter:blur(0))]:bg-gray-900">
<div class="mx-auto flex max-w-2xl items-center justify-between px-4 py-3">
<h1 class="text-lg font-bold text-gray-900 dark:text-gray-100">Galerie</h1>
@@ -538,35 +586,38 @@
<p class="mt-1 text-sm text-gray-400 dark:text-gray-500">Tippe auf den Plus-Button unten!</p>
</div>
{:else if viewMode === 'list'}
<!-- List view: chronological full-width cards -->
<!-- List view: chronological full-width cards (DOM-windowed) -->
<div class="mx-auto max-w-2xl">
{#each uploads as upload (upload.id)}
<FeedListCard
{upload}
isOwn={upload.user_id === myUserId}
onlike={handleLike}
oncomment={openComments}
onselect={(u) => (selectedUpload = u)}
oncontextmenu={openContextSheet}
/>
{/each}
<VirtualFeed
mode="list"
uploads={uploads}
{myUserId}
onlike={handleLike}
oncomment={openComments}
onselect={(u) => (selectedUpload = u)}
oncontextmenu={openContextSheet}
/>
</div>
{:else}
<!-- Grid view: 3-col, filters applied -->
<!-- Grid view: 3-col, filters applied (DOM-windowed by row) -->
<div class="mx-auto max-w-2xl">
{#if displayUploads.length === 0}
<div class="py-16 text-center">
<p class="text-sm text-gray-400 dark:text-gray-500">Keine Treffer für die gewählten Filter.</p>
{#if nextCursor}
<p class="mt-1 text-xs text-gray-400 dark:text-gray-500">Es sind noch nicht alle Beiträge geladen — scrolle weiter, um mehr zu durchsuchen.</p>
{/if}
<button onclick={clearFilters} class="mt-2 text-sm text-blue-600 hover:underline dark:text-blue-400">Filter zurücksetzen</button>
</div>
{:else}
<FeedGrid
<VirtualFeed
mode="grid"
uploads={displayUploads}
{myUserId}
onlike={handleLike}
oncomment={openComments}
onselect={(u) => (selectedUpload = u)}
oncontextmenu={openContextSheet}
threeCol={true}
/>
{/if}
</div>

View File

@@ -6,6 +6,7 @@
import { toast, toastError } from '$lib/toast-store';
import ConfirmSheet from '$lib/components/ConfirmSheet.svelte';
import Modal from '$lib/components/Modal.svelte';
import IconButton from '$lib/components/IconButton.svelte';
interface UserSummary {
id: string;
@@ -56,6 +57,25 @@
const myRole = getRole();
// Generic confirm-then-run for the irreversible / privilege-changing actions
// (promote, demote, unban, release gallery) that previously fired on one tap.
// Reuses the shared ConfirmSheet; the wrapped fns keep their own toast/reload.
interface PendingConfirm {
title: string;
message: string;
confirmLabel: string;
tone: 'default' | 'danger';
run: () => Promise<void>;
}
let confirmAction = $state<PendingConfirm | null>(null);
async function runConfirmAction() {
const action = confirmAction;
if (!action) return;
await action.run();
confirmAction = null;
}
/** Mirrors backend `handlers::host::reset_user_pin` authorisation rules. */
function canResetPinFor(target: UserSummary): boolean {
if (target.role === 'admin') return false;
@@ -196,6 +216,17 @@
}
</script>
<!-- Confirmation for irreversible / privilege-changing actions (promote/demote/unban/release). -->
<ConfirmSheet
open={confirmAction !== null}
title={confirmAction?.title ?? ''}
message={confirmAction?.message ?? ''}
confirmLabel={confirmAction?.confirmLabel ?? 'Bestätigen'}
tone={confirmAction?.tone ?? 'default'}
onConfirm={runConfirmAction}
onCancel={() => (confirmAction = null)}
/>
<!-- PIN reset confirmation — pure yes/no, uses the shared ConfirmSheet. -->
<ConfirmSheet
open={pinResetTarget !== null}
@@ -266,17 +297,13 @@
<div class="min-h-screen bg-gray-50 pb-24 dark:bg-gray-950">
<!-- Header -->
<div class="border-b border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
<div class="border-b border-gray-200 bg-white pt-[env(safe-area-inset-top)] dark:border-gray-800 dark:bg-gray-900">
<div class="mx-auto flex max-w-3xl items-center gap-3 px-4 py-4">
<button
onclick={() => goto('/account')}
class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-gray-500 transition hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-800"
aria-label="Zurück"
>
<IconButton label="Zurück" onclick={() => goto('/account')} class="shrink-0">
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18" />
</svg>
</button>
</IconButton>
<div class="min-w-0">
<h1 class="text-xl font-bold text-gray-900 dark:text-gray-100">Host-Dashboard</h1>
{#if event}
@@ -297,6 +324,7 @@
<div class="overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800">
<button
onclick={() => (statsOpen = !statsOpen)}
aria-expanded={statsOpen}
class="flex w-full items-center justify-between px-5 py-4"
>
<h2 class="font-semibold text-gray-900 dark:text-gray-100">Statistiken</h2>
@@ -337,6 +365,7 @@
<div class="overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800">
<button
onclick={() => (settingsOpen = !settingsOpen)}
aria-expanded={settingsOpen}
class="flex w-full items-center justify-between px-5 py-4"
>
<h2 class="font-semibold text-gray-900 dark:text-gray-100">Event-Einstellungen</h2>
@@ -357,7 +386,13 @@
{event.uploads_locked ? 'Uploads wieder öffnen' : 'Uploads sperren'}
</button>
<button
onclick={releaseGallery}
onclick={() => (confirmAction = {
title: 'Galerie freigeben?',
message: 'Gäste können dann alle Fotos herunterladen. Das kann nicht rückgängig gemacht werden.',
confirmLabel: 'Freigeben',
tone: 'danger',
run: releaseGallery
})}
disabled={event.export_released}
class="rounded-lg px-4 py-2 text-sm font-medium transition
{event.export_released ? 'cursor-default bg-gray-100 text-gray-400 dark:bg-gray-800 dark:text-gray-500' : 'bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400'}"
@@ -372,6 +407,7 @@
<div class="overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800">
<button
onclick={() => (usersOpen = !usersOpen)}
aria-expanded={usersOpen}
class="flex w-full items-center justify-between px-5 py-4"
>
<h2 class="font-semibold text-gray-900 dark:text-gray-100">Nutzerverwaltung</h2>
@@ -424,7 +460,13 @@
{#if user.role !== 'admin'}
{#if user.is_banned}
<button
onclick={() => unban(user)}
onclick={() => (confirmAction = {
title: 'Sperre aufheben?',
message: `${user.display_name} kann danach wieder hochladen, liken und kommentieren.`,
confirmLabel: 'Entsperren',
tone: 'default',
run: () => unban(user)
})}
class="rounded-lg bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600"
>
Entsperren
@@ -432,7 +474,13 @@
{:else}
{#if user.role === 'guest' && (myRole === 'host' || myRole === 'admin')}
<button
onclick={() => promoteToHost(user)}
onclick={() => (confirmAction = {
title: 'Zum Host befördern?',
message: `${user.display_name} erhält Host-Rechte: sperren, PIN zurücksetzen und Galerie verwalten. Das lässt sich nur durch Degradieren rückgängig machen.`,
confirmLabel: 'Befördern',
tone: 'default',
run: () => promoteToHost(user)
})}
class="rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-medium text-blue-700 hover:bg-blue-100 dark:bg-blue-900/40 dark:text-blue-200 dark:hover:bg-blue-900/60"
>
Host
@@ -441,7 +489,13 @@
{#if user.role === 'host'}
<!-- Hosts may demote other Hosts (never themselves); backend enforces. -->
<button
onclick={() => demoteToGuest(user)}
onclick={() => (confirmAction = {
title: 'Zum Gast degradieren?',
message: `${user.display_name} verliert alle Host-Rechte.`,
confirmLabel: 'Degradieren',
tone: 'danger',
run: () => demoteToGuest(user)
})}
class="rounded-lg bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600"
>
Degradieren

View File

@@ -1,13 +1,23 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { goto, afterNavigate } from '$app/navigation';
import { api, ApiError } from '$lib/api';
import { setAuth, getPin, getToken } from '$lib/auth';
import { browser } from '$app/environment';
import IconButton from '$lib/components/IconButton.svelte';
// `from` is non-null only when we arrived here via in-app (client-side)
// navigation; on a full-page load (deep link, new tab) it's null. Using
// history.length is unreliable — a fresh tab keeps `about:blank` as the prior
// entry, so history.back() would land there instead of inside the app.
let cameFromApp = $state(false);
afterNavigate(({ from }) => {
cameFromApp = from !== null;
});
function goBack() {
// Prefer the actual previous page (most users land here from /join or /account).
// Fall back to a sensible default based on auth state for deep-linked users.
if (browser && window.history.length > 1) {
if (cameFromApp) {
window.history.back();
return;
}
@@ -67,19 +77,13 @@
}
</script>
<div class="flex min-h-screen flex-col bg-gray-50 px-4 dark:bg-gray-950">
<div class="flex min-h-screen flex-col bg-gray-50 px-4 pt-[env(safe-area-inset-top)] dark:bg-gray-950">
<div class="-mx-4 flex items-center px-2 py-3">
<button
type="button"
onclick={goBack}
data-testid="recover-back"
class="flex h-9 w-9 items-center justify-center rounded-full text-gray-500 transition hover:bg-gray-100 active:bg-gray-200 dark:text-gray-400 dark:hover:bg-gray-800 dark:active:bg-gray-700"
aria-label="Zurück"
>
<IconButton label="Zurück" onclick={goBack} data-testid="recover-back">
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5 8.25 12l7.5-7.5" />
</svg>
</button>
</IconButton>
</div>
<div class="m-auto w-full max-w-sm">
<h1 class="mb-2 text-center text-2xl font-bold text-gray-900 dark:text-gray-100">Konto wiederherstellen</h1>

View File

@@ -8,6 +8,7 @@
import { onMount, onDestroy } from 'svelte';
import { quotaStore, refreshQuota } from '$lib/quota-store';
import ConfirmSheet from '$lib/components/ConfirmSheet.svelte';
import IconButton from '$lib/components/IconButton.svelte';
import { vibrate } from '$lib/haptics';
import type { PendingFile } from '$lib/pending-upload-store';
@@ -47,9 +48,14 @@
// Auto-focus caption textarea after a short delay (let layout settle)
setTimeout(() => captionEl?.focus(), 80);
// Revoke blob URLs if user abandons the upload page
const handleBeforeUnload = () => {
clearPending();
// Warn before a hard browser navigation (close / reload / external link) drops
// staged files or an unsent caption. In-app navigation is already guarded by
// the discard ConfirmSheet in cancel().
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
if (stagedFiles.length > 0 || caption.trim().length > 0) {
e.preventDefault();
e.returnValue = '';
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
@@ -60,6 +66,9 @@
onDestroy(() => {
showBottomNav.set(true);
// Revoke any staged preview blob URLs on leave so they don't leak. The queue
// holds the underlying File objects, so this is safe after submit too.
for (const sf of stagedFiles) URL.revokeObjectURL(sf.previewUrl);
});
function removeFile(idx: number) {
@@ -118,16 +127,12 @@
<!-- Full-screen composer — bottom nav is suppressed -->
<div class="flex min-h-screen flex-col bg-white dark:bg-gray-950">
<!-- Header -->
<div class="flex items-center justify-between border-b border-gray-100 px-4 py-3 dark:border-gray-800">
<button
onclick={cancel}
class="flex h-9 w-9 items-center justify-center rounded-full text-gray-500 transition hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-800"
aria-label="Abbrechen"
>
<div class="flex items-center justify-between border-b border-gray-100 px-4 py-3 pt-[calc(env(safe-area-inset-top)+0.75rem)] dark:border-gray-800">
<IconButton label="Abbrechen" onclick={cancel}>
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
</button>
</IconButton>
<h1 class="text-base font-semibold text-gray-900 dark:text-gray-100">Neuer Beitrag</h1>
<!-- Submit button in header for desktop convenience -->
<button
@@ -158,10 +163,10 @@
{/if}
<button
onclick={() => removeFile(i)}
class="absolute right-1 top-1 flex h-5 w-5 items-center justify-center rounded-full bg-black/60 text-white"
class="absolute right-1 top-1 flex h-8 w-8 items-center justify-center rounded-full bg-black/60 text-white"
aria-label="Entfernen"
>
<svg class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3">
<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
</button>

View File

@@ -0,0 +1,7 @@
// Test stub for SvelteKit's `$app/environment` virtual module (which only exists
// during dev/build). `browser: false` makes modules like data-mode-store take their
// server-safe path (no localStorage access) when imported under Vitest's node env.
export const browser = false;
export const dev = false;
export const building = false;
export const version = 'test';

12
frontend/static/icon.svg Normal file
View File

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="EventSnap">
<!-- Full-bleed brand background keeps the icon "maskable": safe content sits within the centre 80%. -->
<rect width="512" height="512" fill="#2563eb"/>
<g fill="none" stroke="#ffffff" stroke-width="22" stroke-linejoin="round" stroke-linecap="round">
<!-- Camera body -->
<rect x="116" y="172" width="280" height="200" rx="34"/>
<!-- Viewfinder bump -->
<path d="M212 172l24-34h40l24 34" fill="#ffffff" stroke="none"/>
<!-- Lens -->
<circle cx="256" cy="276" r="58"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 634 B

View File

@@ -0,0 +1,20 @@
{
"name": "EventSnap",
"short_name": "EventSnap",
"description": "Teile und sammle Fotos eures Events an einem Ort.",
"lang": "de",
"start_url": "/",
"scope": "/",
"display": "standalone",
"orientation": "portrait",
"background_color": "#ffffff",
"theme_color": "#2563eb",
"icons": [
{
"src": "/icon.svg",
"type": "image/svg+xml",
"sizes": "any",
"purpose": "any maskable"
}
]
}

18
frontend/vitest.config.ts Normal file
View File

@@ -0,0 +1,18 @@
import { defineConfig } from 'vitest/config';
import { fileURLToPath } from 'node:url';
// Standalone Vitest config (separate from vite.config.ts so it doesn't pull in the
// full SvelteKit plugin). It only needs to resolve the two aliases our pure-logic
// modules use: `$lib` and SvelteKit's `$app/environment` virtual module (stubbed).
export default defineConfig({
resolve: {
alias: {
'$app/environment': fileURLToPath(new URL('./src/test/mocks/app-environment.ts', import.meta.url)),
$lib: fileURLToPath(new URL('./src/lib', import.meta.url)),
},
},
test: {
environment: 'node',
include: ['src/**/*.test.ts'],
},
});