Compare commits
17 Commits
b241ba6415
...
fix/audit-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77d55e941c | ||
|
|
a895bebdc2 | ||
|
|
2d7169e971 | ||
|
|
db1e5b8833 | ||
|
|
d4181b1119 | ||
|
|
23a7d89a89 | ||
|
|
8272197cea | ||
|
|
0737288ed9 | ||
|
|
5bd008591b | ||
|
|
cf428725b9 | ||
|
|
ae6c496f94 | ||
|
|
9364cb624a | ||
|
|
8faf702208 | ||
|
|
ab9f1d89b2 | ||
|
|
2068e8c1f3 | ||
|
|
bbec815854 | ||
|
|
309c25bc06 |
12
.env.example
12
.env.example
@@ -4,15 +4,21 @@ DOMAIN=my-event.example.com
|
||||
|
||||
# ── App server ────────────────────────────────────────────────────────────────
|
||||
APP_PORT=3000
|
||||
# docker-compose.yml already forces APP_ENV=production for the `app` service.
|
||||
# Only set this for a non-compose (bare cargo) run; leave unset for local dev.
|
||||
# APP_ENV=production
|
||||
|
||||
# ── Database ──────────────────────────────────────────────────────────────────
|
||||
DATABASE_URL=postgres://eventsnap:secret@db:5432/eventsnap
|
||||
# Set a strong password and keep it identical in DATABASE_URL and POSTGRES_PASSWORD.
|
||||
DATABASE_URL=postgres://eventsnap:CHANGE_ME_strong_db_password@db:5432/eventsnap
|
||||
POSTGRES_USER=eventsnap
|
||||
POSTGRES_PASSWORD=secret
|
||||
POSTGRES_PASSWORD=CHANGE_ME_strong_db_password
|
||||
POSTGRES_DB=eventsnap
|
||||
|
||||
# ── Authentication ────────────────────────────────────────────────────────────
|
||||
# Generate with: openssl rand -hex 64
|
||||
# REQUIRED in production: generate with `openssl rand -hex 64` (128 hex chars).
|
||||
# The backend refuses to start in production with this placeholder or any value
|
||||
# that is short or contains change/example/placeholder/replace.
|
||||
JWT_SECRET=change_me_to_a_random_64_byte_hex_string
|
||||
SESSION_EXPIRY_DAYS=30
|
||||
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -24,3 +24,7 @@ e2e/.env.test
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Local audit/review reports — generated working artifacts, kept out of git
|
||||
docs/AUDIT-2026-06-27.md
|
||||
docs/FIX-VERIFICATION-2026-06-27.md
|
||||
|
||||
25
Caddyfile
25
Caddyfile
@@ -5,21 +5,24 @@
|
||||
@hashed_assets path_regexp hashed /_app/immutable/.*\.[a-f0-9]{8,}\.(js|css|woff2)$
|
||||
header @hashed_assets Cache-Control "public, max-age=31536000, immutable"
|
||||
|
||||
# Media previews and thumbnails
|
||||
@previews path /media/previews/* /media/thumbnails/*
|
||||
header @previews Cache-Control "public, max-age=3600"
|
||||
|
||||
# Original media files (private — only host can download)
|
||||
@originals path /media/originals/*
|
||||
header @originals Cache-Control "private, max-age=86400"
|
||||
|
||||
# API — never cache
|
||||
@api path /api/*
|
||||
header @api Cache-Control "no-store"
|
||||
|
||||
# Route API and media requests to the Rust backend
|
||||
reverse_proxy /api/* app:3000
|
||||
reverse_proxy /media/* app:3000
|
||||
# Media is served by the authenticated gateway at /media/{kind}/{id}, which
|
||||
# sets its own Cache-Control (private) and security headers per response — no
|
||||
# Caddy-side cache rules (the old /media/previews|originals matchers were for
|
||||
# the retired static mount).
|
||||
|
||||
# Route API and media requests to the Rust backend. Set X-Real-IP from the
|
||||
# real TCP peer and overwrite any client-supplied value so the backend's
|
||||
# rate-limit keys can't be spoofed via a forged X-Forwarded-For.
|
||||
reverse_proxy /api/* app:3000 {
|
||||
header_up X-Real-IP {remote_host}
|
||||
}
|
||||
reverse_proxy /media/* app:3000 {
|
||||
header_up X-Real-IP {remote_host}
|
||||
}
|
||||
|
||||
# Everything else goes to SvelteKit frontend
|
||||
reverse_proxy frontend:3001
|
||||
|
||||
53
FOLLOWUPS.md
Normal file
53
FOLLOWUPS.md
Normal file
@@ -0,0 +1,53 @@
|
||||
# Follow-ups
|
||||
|
||||
Tracked work that was deferred during the multi-round UI/UX review pass.
|
||||
Each item has a clear acceptance criterion so a future pass can land it
|
||||
without re-deriving the context.
|
||||
|
||||
## A11y — assistive-tech containment inside modals
|
||||
|
||||
**Problem.** Open modals (LightboxModal, ConfirmSheet, Modal, OnboardingGuide,
|
||||
join PIN modal, account data-mode sheet, export HTML guide) trap keyboard Tab
|
||||
via `focusTrap`, but VoiceOver rotor / TalkBack arrow-key navigation can still
|
||||
escape into the page content behind the dialog. Screen-reader users hear the
|
||||
wrong context.
|
||||
|
||||
**Why deferred.** A naive sibling-walk that sets `inert` on direct children of
|
||||
the modal's parent silences the global `<Toaster>` (`aria-live="polite"` region
|
||||
mounted in `+layout.svelte`) and the `<BottomNav>` while a modal is open —
|
||||
breaking toast announcements and the visible nav state. SvelteKit has no
|
||||
built-in portal mechanism, so dialogs render inside the route tree alongside
|
||||
the Toaster.
|
||||
|
||||
**Acceptance criterion.** With any modal open:
|
||||
- VoiceOver rotor (iOS Safari) and TalkBack swipe navigation (Android Chrome)
|
||||
cannot leave the dialog subtree.
|
||||
- Toasts that fire while a modal is open are still announced.
|
||||
- Nested modals (e.g. ConfirmSheet opened from inside ContextSheet) maintain
|
||||
correct containment when the inner closes.
|
||||
|
||||
**Sketch of an approach.** One of:
|
||||
1. **Portal pattern.** Render dialogs into a dedicated `<div id="modal-root">`
|
||||
that's a sibling of the main app root in `app.html`. `focusTrap` then sets
|
||||
`inert` on the main root, leaving the modal root and the toast region (also
|
||||
moved to its own portal root) untouched.
|
||||
2. **Opt-out marker.** Walk siblings and inert them, but skip any node carrying
|
||||
a `data-modal-passthrough` attribute. Mark `<Toaster>` with it. Document
|
||||
the contract.
|
||||
3. **Stack-aware containment.** Maintain a module-level stack of open dialog
|
||||
nodes; the topmost owns the inert state, popped dialogs restore the
|
||||
previous layer. Avoids the nested-modal restoration bug.
|
||||
|
||||
Approach 1 is the cleanest long-term but the highest blast radius. Approach 2
|
||||
is the smallest patch.
|
||||
|
||||
**Files to touch.**
|
||||
- [frontend/src/lib/actions/focus-trap.ts](frontend/src/lib/actions/focus-trap.ts) — add inert logic
|
||||
- [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)
|
||||
|
||||
## 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.
|
||||
- **Onboarding pip tap target on the vertical axis.** [OnboardingGuide.svelte](frontend/src/lib/components/OnboardingGuide.svelte) — current `p-2.5` yields ~26 px height, meets WCAG 2.2 AA (≥24 px) but below iOS HIG / Material's 44 / 48 dp recommendation. Bumping to `p-3` is the easy improvement; further increases start crowding the row.
|
||||
- **Migrate bespoke focus-trapped dialogs to `<Modal>`.** Join PIN modal, OnboardingGuide, LightboxModal, HTML guide, account data-mode sheet — all currently roll their own shell with `focusTrap`. They're correct, just not using the canonical primitive. Migrate when `<Modal>` gains features (e.g. the inert work above) you'd want everywhere.
|
||||
@@ -18,10 +18,18 @@ RUN touch src/main.rs && cargo build --release
|
||||
# --- Runtime stage ---
|
||||
FROM alpine:3.21
|
||||
|
||||
RUN apk add --no-cache ca-certificates ffmpeg
|
||||
# Run as an unprivileged user (defense-in-depth). The media volume mounts at
|
||||
# /media; creating it here as `app` means a fresh named volume inherits app
|
||||
# ownership and is writable without running as root. (An existing root-owned
|
||||
# volume from a prior deploy needs a one-time `chown -R app:app` — see deploy notes.)
|
||||
RUN apk add --no-cache ca-certificates ffmpeg \
|
||||
&& addgroup -S app && adduser -S -G app app \
|
||||
&& mkdir -p /media && chown app:app /media
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=builder /app/target/release/eventsnap-backend ./
|
||||
RUN chown -R app:app /app
|
||||
|
||||
USER app
|
||||
EXPOSE 3000
|
||||
CMD ["./eventsnap-backend"]
|
||||
|
||||
23
backend/migrations/010_feed_view_perf.down.sql
Normal file
23
backend/migrations/010_feed_view_perf.down.sql
Normal file
@@ -0,0 +1,23 @@
|
||||
-- Restore the original join-based v_feed definition.
|
||||
CREATE OR REPLACE VIEW v_feed AS
|
||||
SELECT
|
||||
u.id,
|
||||
u.event_id,
|
||||
u.user_id,
|
||||
usr.display_name AS uploader_name,
|
||||
usr.is_banned,
|
||||
usr.uploads_hidden,
|
||||
u.preview_path,
|
||||
u.thumbnail_path,
|
||||
u.mime_type,
|
||||
u.caption,
|
||||
u.created_at,
|
||||
COUNT(DISTINCT l.user_id) AS like_count,
|
||||
COUNT(DISTINCT c.id) AS comment_count
|
||||
FROM upload u
|
||||
JOIN "user" usr ON u.user_id = usr.id
|
||||
LEFT JOIN "like" l ON l.upload_id = u.id
|
||||
LEFT JOIN comment c ON c.upload_id = u.id AND c.deleted_at IS NULL
|
||||
WHERE u.deleted_at IS NULL
|
||||
AND usr.uploads_hidden = FALSE
|
||||
GROUP BY u.id, usr.display_name, usr.is_banned, usr.uploads_hidden;
|
||||
26
backend/migrations/010_feed_view_perf.up.sql
Normal file
26
backend/migrations/010_feed_view_perf.up.sql
Normal file
@@ -0,0 +1,26 @@
|
||||
-- H6: replace v_feed's double LEFT JOIN + COUNT(DISTINCT) (which materializes a
|
||||
-- likes×comments Cartesian per upload before de-duping) with correlated scalar
|
||||
-- subqueries. Each count now uses its own index (idx_like_upload /
|
||||
-- idx_comment_upload) and there is no GROUP BY. The output columns are
|
||||
-- unchanged, so every consumer keeps working.
|
||||
CREATE OR REPLACE VIEW v_feed AS
|
||||
SELECT
|
||||
u.id,
|
||||
u.event_id,
|
||||
u.user_id,
|
||||
usr.display_name AS uploader_name,
|
||||
usr.is_banned,
|
||||
usr.uploads_hidden,
|
||||
u.preview_path,
|
||||
u.thumbnail_path,
|
||||
u.mime_type,
|
||||
u.caption,
|
||||
u.created_at,
|
||||
(SELECT COUNT(*) FROM "like" l
|
||||
WHERE l.upload_id = u.id) AS like_count,
|
||||
(SELECT COUNT(*) FROM comment c
|
||||
WHERE c.upload_id = u.id AND c.deleted_at IS NULL) AS comment_count
|
||||
FROM upload u
|
||||
JOIN "user" usr ON u.user_id = usr.id
|
||||
WHERE u.deleted_at IS NULL
|
||||
AND usr.uploads_hidden = FALSE;
|
||||
@@ -15,6 +15,7 @@ use crate::models::event::Event;
|
||||
use crate::models::session::Session;
|
||||
use crate::models::user::{User, UserRole};
|
||||
use crate::services::config;
|
||||
use crate::services::password;
|
||||
use crate::services::rate_limiter::client_ip;
|
||||
use crate::state::AppState;
|
||||
|
||||
@@ -39,13 +40,23 @@ pub async fn join(
|
||||
let ip = client_ip(&headers, "unknown");
|
||||
let rate_limits_on = config::get_bool(&state.pool, "rate_limits_enabled", true).await;
|
||||
let join_rate_on = config::get_bool(&state.pool, "join_rate_enabled", true).await;
|
||||
if rate_limits_on && join_rate_on
|
||||
&& !state.rate_limiter.check(format!("join:{ip}"), 5, Duration::from_secs(60))
|
||||
{
|
||||
return Err(AppError::TooManyRequests(
|
||||
"Zu viele Anfragen. Bitte warte kurz und versuche es erneut.".into(),
|
||||
None,
|
||||
));
|
||||
if rate_limits_on && join_rate_on {
|
||||
// Short burst cap (typos / double-taps) AND a generous per-IP daily cap
|
||||
// on account creation. The daily cap bounds mass account-minting (which
|
||||
// otherwise resets the per-user upload budget, see the event-wide count
|
||||
// quota in the upload handler) while staying well above a real ~100-guest
|
||||
// venue sharing one NAT'd IP.
|
||||
let burst_ok =
|
||||
state.rate_limiter.check(format!("join:{ip}"), 5, Duration::from_secs(60));
|
||||
let daily_ok = state
|
||||
.rate_limiter
|
||||
.check(format!("join_day:{ip}"), 200, Duration::from_secs(86_400));
|
||||
if !burst_ok || !daily_ok {
|
||||
return Err(AppError::TooManyRequests(
|
||||
"Zu viele Anfragen. Bitte warte kurz und versuche es erneut.".into(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let display_name = body.display_name.trim();
|
||||
@@ -78,10 +89,10 @@ pub async fn join(
|
||||
)));
|
||||
}
|
||||
|
||||
// Generate a 4-digit PIN
|
||||
let pin: String = format!("{:04}", rand::rng().random_range(0..10000u32));
|
||||
let pin_hash =
|
||||
bcrypt::hash(&pin, 12).map_err(|e| AppError::Internal(anyhow::anyhow!(e)))?;
|
||||
// Generate a 6-digit PIN (≈20 bits vs the old ~13.3, so brute-forcing it
|
||||
// against the 3-strike lockout is far harder).
|
||||
let pin: String = format!("{:06}", rand::rng().random_range(0..1_000_000u32));
|
||||
let pin_hash = password::hash(pin.clone(), 12).await?;
|
||||
|
||||
let user = User::create(&state.pool, event.id, display_name, &pin_hash).await?;
|
||||
|
||||
@@ -164,24 +175,22 @@ pub async fn recover(
|
||||
}
|
||||
|
||||
for user in &users {
|
||||
// Check PIN lockout. If the lockout has expired, also reset the failed-attempt
|
||||
// counter so the user gets a fresh 3-strike window — otherwise the counter
|
||||
// stays at 3+ and every subsequent wrong PIN immediately re-locks them, even
|
||||
// after waiting out the cooldown. Without this reset, a once-locked account
|
||||
// is effectively permanently fragile.
|
||||
// Check PIN lockout. The failed-attempt counter is deliberately NOT reset
|
||||
// when the window expires — it drives the *escalating* backoff below, so a
|
||||
// determined guesser faces an exponentially growing wait. A successful
|
||||
// recovery (and a host PIN reset) is what clears it. The counter only ever
|
||||
// grows on a *wrong* PIN, so a legitimate user is unaffected.
|
||||
if let Some(locked_until) = user.pin_locked_until {
|
||||
if Utc::now() < locked_until {
|
||||
return Err(AppError::TooManyRequests(
|
||||
"Zu viele Versuche. Bitte warte 15 Minuten.".into(),
|
||||
"Zu viele Versuche. Bitte warte und versuche es später erneut.".into(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
// Lockout window expired — wipe the counter and the timestamp.
|
||||
User::reset_pin_attempts(&state.pool, user.id).await?;
|
||||
}
|
||||
|
||||
let pin_matches = bcrypt::verify(&body.pin, &user.recovery_pin_hash)
|
||||
.unwrap_or(false);
|
||||
let pin_matches =
|
||||
password::verify(body.pin.clone(), user.recovery_pin_hash.clone()).await;
|
||||
|
||||
if pin_matches {
|
||||
// Reset failed attempts on success
|
||||
@@ -216,13 +225,19 @@ pub async fn recover(
|
||||
"recover: wrong PIN"
|
||||
);
|
||||
if attempts >= 3 {
|
||||
let lockout = Utc::now() + chrono::Duration::minutes(15);
|
||||
// Escalating backoff: 15min, 30, 60, … doubling per failure past the
|
||||
// threshold, capped at 24h. Makes sustained guessing against the
|
||||
// 6-digit space (1M combinations) astronomically slow.
|
||||
let exp = (attempts as u32).saturating_sub(3).min(10);
|
||||
let minutes = 15i64.saturating_mul(1i64 << exp).min(24 * 60);
|
||||
let lockout = Utc::now() + chrono::Duration::minutes(minutes);
|
||||
User::lock_pin(&state.pool, user.id, lockout).await?;
|
||||
tracing::warn!(
|
||||
user_id = %user.id,
|
||||
event_id = %event.id,
|
||||
ip = %ip,
|
||||
"recover: account locked for 15 minutes"
|
||||
minutes,
|
||||
"recover: account locked (escalating backoff)"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -256,6 +271,22 @@ pub async fn admin_login(
|
||||
// a long-running guess campaign. 5 attempts / minute / IP is plenty for
|
||||
// honest typos.
|
||||
let ip = client_ip(&headers, "unknown");
|
||||
|
||||
// Hard, non-disableable floor: admin_login is the one credential endpoint
|
||||
// whose brute-force protection must survive the DB rate-limit master toggle
|
||||
// being turned off. 30 attempts / 5 min / IP is generous for typos but caps
|
||||
// sustained guessing regardless of config.
|
||||
if !state.rate_limiter.check(
|
||||
format!("admin_login_floor:{ip}"),
|
||||
30,
|
||||
Duration::from_secs(300),
|
||||
) {
|
||||
return Err(AppError::TooManyRequests(
|
||||
"Zu viele Anmeldeversuche. Bitte warte kurz und versuche es erneut.".into(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
|
||||
let rate_limits_on = config::get_bool(&state.pool, "rate_limits_enabled", true).await;
|
||||
let admin_rate_on = config::get_bool(&state.pool, "admin_login_rate_enabled", true).await;
|
||||
if rate_limits_on && admin_rate_on
|
||||
@@ -271,8 +302,11 @@ pub async fn admin_login(
|
||||
));
|
||||
}
|
||||
|
||||
let valid = bcrypt::verify(&body.password, &state.config.admin_password_hash)
|
||||
.unwrap_or(false);
|
||||
let valid = password::verify(
|
||||
body.password.clone(),
|
||||
state.config.admin_password_hash.clone(),
|
||||
)
|
||||
.await;
|
||||
|
||||
if !valid {
|
||||
tracing::warn!(ip = %ip, "admin_login: wrong password");
|
||||
@@ -298,8 +332,7 @@ pub async fn admin_login(
|
||||
let dummy_pin: String = (0..32)
|
||||
.map(|_| rand::rng().random_range(b'a'..=b'z') as char)
|
||||
.collect();
|
||||
let dummy_hash = bcrypt::hash(&dummy_pin, 4)
|
||||
.map_err(|e| AppError::Internal(anyhow::anyhow!(e)))?;
|
||||
let dummy_hash = password::hash(dummy_pin, 4).await?;
|
||||
let user = User::create(&state.pool, event.id, admin_name, &dummy_hash).await?;
|
||||
sqlx::query("UPDATE \"user\" SET role = 'admin' WHERE id = $1")
|
||||
.bind(user.id)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use axum::extract::{FromRequestParts, State};
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::http::request::Parts;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -38,16 +38,32 @@ impl FromRequestParts<AppState> for AuthUser {
|
||||
|
||||
let token_hash = jwt::hash_token(token);
|
||||
|
||||
let session = Session::find_by_token_hash(&state.pool, &token_hash)
|
||||
// Reconcile the session against the live `user` row. We do NOT trust the
|
||||
// JWT claims for role/ban/event — a token can outlive a ban or demotion
|
||||
// (default lifetime 30 days). The single JOIN query is the same number
|
||||
// of round-trips as the old existence check.
|
||||
let ctx = Session::find_auth_context(&state.pool, &token_hash)
|
||||
.await
|
||||
.map_err(|e| AppError::Internal(e.into()))?
|
||||
.ok_or_else(|| AppError::Unauthorized("Sitzung nicht gefunden oder abgelaufen.".into()))?;
|
||||
|
||||
// Ban takes effect immediately on the next request, regardless of the
|
||||
// token's remaining lifetime.
|
||||
if ctx.is_banned {
|
||||
return Err(AppError::Forbidden("Du bist gesperrt.".into()));
|
||||
}
|
||||
|
||||
// Defend against a JWT that was issued for a different user/event than
|
||||
// the session's DB row points at (e.g. a swapped or replayed token).
|
||||
if claims.sub != ctx.user_id || claims.event_id != ctx.event_id {
|
||||
return Err(AppError::Unauthorized("Token passt nicht zur Sitzung.".into()));
|
||||
}
|
||||
|
||||
// Update last_seen_at in the background (fire-and-forget). Failures are
|
||||
// non-fatal but worth surfacing — silent swallowing hides DB connection
|
||||
// pressure that would otherwise be the first symptom of a real problem.
|
||||
let pool = state.pool.clone();
|
||||
let session_id = session.id;
|
||||
let session_id = ctx.session_id;
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = Session::touch(&pool, session_id).await {
|
||||
tracing::warn!(error = ?e, session_id = %session_id, "session touch failed");
|
||||
@@ -55,9 +71,11 @@ impl FromRequestParts<AppState> for AuthUser {
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
user_id: claims.sub,
|
||||
event_id: claims.event_id,
|
||||
role: claims.role,
|
||||
user_id: ctx.user_id,
|
||||
event_id: ctx.event_id,
|
||||
// Live role from the DB, not the claim — demotion/promotion takes
|
||||
// effect on the next request.
|
||||
role: ctx.role,
|
||||
token_hash,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -25,18 +25,30 @@ impl AppConfig {
|
||||
let is_prod = app_env.eq_ignore_ascii_case("production");
|
||||
|
||||
let jwt_secret = std::env::var("JWT_SECRET").context("JWT_SECRET must be set")?;
|
||||
if jwt_secret == DEV_JWT_SECRET_SENTINEL {
|
||||
if is_prod {
|
||||
// A weak/placeholder signing key lets anyone forge any token (including
|
||||
// admin). Detect the known dev sentinel, the `.env.example` placeholder,
|
||||
// and anything that smells like an unreplaced template value.
|
||||
let lower = jwt_secret.to_ascii_lowercase();
|
||||
let looks_placeholder = jwt_secret == DEV_JWT_SECRET_SENTINEL
|
||||
|| lower.contains("change")
|
||||
|| lower.contains("example")
|
||||
|| lower.contains("placeholder")
|
||||
|| lower.contains("replace");
|
||||
|
||||
if is_prod {
|
||||
// Production must use a real, strong secret — no placeholders, ≥64
|
||||
// chars (an `openssl rand -hex 64` is 128 hex chars).
|
||||
if looks_placeholder || jwt_secret.len() < 64 {
|
||||
return Err(anyhow!(
|
||||
"Refusing to start in production with the well-known dev JWT_SECRET — \
|
||||
rotate it (openssl rand -hex 64)."
|
||||
"Refusing to start in production: JWT_SECRET is a placeholder or too short. \
|
||||
Generate a real one (openssl rand -hex 64) and set it in the prod environment."
|
||||
));
|
||||
}
|
||||
} else if looks_placeholder || jwt_secret.len() < 32 {
|
||||
tracing::warn!(
|
||||
"JWT_SECRET is the dev sentinel — fine for local development, NEVER ship this."
|
||||
"JWT_SECRET looks like a dev/placeholder value — fine for local development, \
|
||||
NEVER ship this to production."
|
||||
);
|
||||
} else if jwt_secret.len() < 32 {
|
||||
return Err(anyhow!("JWT_SECRET must be at least 32 characters."));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
|
||||
@@ -10,6 +10,7 @@ use uuid::Uuid;
|
||||
use crate::auth::middleware::AuthUser;
|
||||
use crate::error::AppError;
|
||||
use crate::services::config;
|
||||
use crate::services::media_token;
|
||||
use crate::services::rate_limiter::client_ip;
|
||||
use crate::state::AppState;
|
||||
|
||||
@@ -27,6 +28,8 @@ pub struct FeedUpload {
|
||||
pub uploader_name: String,
|
||||
pub preview_url: Option<String>,
|
||||
pub thumbnail_url: Option<String>,
|
||||
/// Signed gateway URL for the full-resolution original. Always present.
|
||||
pub original_url: Option<String>,
|
||||
pub mime_type: String,
|
||||
pub caption: Option<String>,
|
||||
pub like_count: i64,
|
||||
@@ -55,6 +58,33 @@ struct FeedRow {
|
||||
created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// Build a feed DTO, minting fresh signed gateway URLs for each artifact. The
|
||||
/// preview/thumbnail URLs are present only when the derivative exists so the
|
||||
/// client can show a skeleton while compression is still running; the original
|
||||
/// URL is always present.
|
||||
fn to_feed_upload(r: FeedRow, liked: bool, secret: &str, now: i64) -> FeedUpload {
|
||||
FeedUpload {
|
||||
liked_by_me: liked,
|
||||
preview_url: r
|
||||
.preview_path
|
||||
.as_ref()
|
||||
.map(|_| media_token::signed_url(secret, "preview", r.id, now)),
|
||||
thumbnail_url: r
|
||||
.thumbnail_path
|
||||
.as_ref()
|
||||
.map(|_| media_token::signed_url(secret, "thumbnail", r.id, now)),
|
||||
original_url: Some(media_token::signed_url(secret, "original", r.id, now)),
|
||||
id: r.id,
|
||||
user_id: r.user_id,
|
||||
uploader_name: r.uploader_name,
|
||||
mime_type: r.mime_type,
|
||||
caption: r.caption,
|
||||
like_count: r.like_count,
|
||||
comment_count: r.comment_count,
|
||||
created_at: r.created_at,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn feed(
|
||||
State(state): State<AppState>,
|
||||
auth: AuthUser,
|
||||
@@ -135,24 +165,13 @@ pub async fn feed(
|
||||
let upload_ids: Vec<Uuid> = rows.iter().map(|r| r.id).collect();
|
||||
let liked_set = get_liked_set(&state.pool, auth.user_id, &upload_ids).await;
|
||||
|
||||
let now = Utc::now().timestamp();
|
||||
let secret = &state.config.jwt_secret;
|
||||
let uploads = rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let preview_url = r.preview_path.map(|p| format!("/media/{p}"));
|
||||
let thumbnail_url = r.thumbnail_path.map(|p| format!("/media/{p}"));
|
||||
FeedUpload {
|
||||
liked_by_me: liked_set.contains(&r.id),
|
||||
id: r.id,
|
||||
user_id: r.user_id,
|
||||
uploader_name: r.uploader_name,
|
||||
preview_url,
|
||||
thumbnail_url,
|
||||
mime_type: r.mime_type,
|
||||
caption: r.caption,
|
||||
like_count: r.like_count,
|
||||
comment_count: r.comment_count,
|
||||
created_at: r.created_at,
|
||||
}
|
||||
let liked = liked_set.contains(&r.id);
|
||||
to_feed_upload(r, liked, secret, now)
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -171,57 +190,90 @@ pub struct DeltaQuery {
|
||||
pub struct DeltaResponse {
|
||||
pub uploads: Vec<FeedUpload>,
|
||||
pub deleted_ids: Vec<Uuid>,
|
||||
/// Set when the delta was clamped (too-old cursor) or hit the row cap — the
|
||||
/// client should do a full feed reload instead of trusting the partial set.
|
||||
pub reload_required: bool,
|
||||
}
|
||||
|
||||
/// Hard cap on how many uploads one delta returns. Beyond this the client is
|
||||
/// told to reload rather than streaming the whole gallery through the view.
|
||||
const DELTA_LIMIT: i64 = 200;
|
||||
/// How far back a client-supplied `since` may reach. A tab backgrounded for days
|
||||
/// must not pull the entire event on reconnect.
|
||||
const DELTA_MAX_LOOKBACK_DAYS: i64 = 7;
|
||||
|
||||
pub async fn feed_delta(
|
||||
State(state): State<AppState>,
|
||||
auth: AuthUser,
|
||||
Query(q): Query<DeltaQuery>,
|
||||
) -> Result<Json<DeltaResponse>, AppError> {
|
||||
// H7: feed_delta runs the (expensive) feed query and fires on every tab
|
||||
// refocus, so it needs the same rate limit as feed(), keyed per user.
|
||||
let rate_limits_on = config::get_bool(&state.pool, "rate_limits_enabled", true).await;
|
||||
let feed_rate_on = config::get_bool(&state.pool, "feed_rate_enabled", true).await;
|
||||
if rate_limits_on && feed_rate_on {
|
||||
let rate_limit = config::get_usize(&state.pool, "feed_rate_per_min", 60).await;
|
||||
if !state.rate_limiter.check(
|
||||
format!("feed_delta:{}", auth.user_id),
|
||||
rate_limit,
|
||||
Duration::from_secs(60),
|
||||
) {
|
||||
return Err(AppError::TooManyRequests(
|
||||
"Zu viele Anfragen. Bitte warte kurz und versuche es erneut.".into(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Clamp the lookback server-side; signal a full reload if we had to.
|
||||
let min_since = Utc::now() - chrono::Duration::days(DELTA_MAX_LOOKBACK_DAYS);
|
||||
let clamped = q.since < min_since;
|
||||
let since = if clamped { min_since } else { q.since };
|
||||
|
||||
let rows = sqlx::query_as::<_, FeedRow>(
|
||||
"SELECT id, user_id, uploader_name, preview_path, thumbnail_path,
|
||||
mime_type, caption, like_count, comment_count, created_at
|
||||
FROM v_feed
|
||||
WHERE event_id = $1 AND created_at > $2
|
||||
ORDER BY created_at DESC",
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $3",
|
||||
)
|
||||
.bind(auth.event_id)
|
||||
.bind(q.since)
|
||||
.bind(since)
|
||||
.bind(DELTA_LIMIT + 1)
|
||||
.fetch_all(&state.pool)
|
||||
.await?;
|
||||
|
||||
let capped = rows.len() as i64 > DELTA_LIMIT;
|
||||
let rows: Vec<FeedRow> = rows.into_iter().take(DELTA_LIMIT as usize).collect();
|
||||
let reload_required = clamped || capped;
|
||||
|
||||
let deleted_ids: Vec<(Uuid,)> = sqlx::query_as(
|
||||
"SELECT id FROM upload
|
||||
WHERE event_id = $1 AND deleted_at IS NOT NULL AND deleted_at > $2",
|
||||
)
|
||||
.bind(auth.event_id)
|
||||
.bind(q.since)
|
||||
.bind(since)
|
||||
.fetch_all(&state.pool)
|
||||
.await?;
|
||||
|
||||
let upload_ids: Vec<Uuid> = rows.iter().map(|r| r.id).collect();
|
||||
let liked_set = get_liked_set(&state.pool, auth.user_id, &upload_ids).await;
|
||||
|
||||
let now = Utc::now().timestamp();
|
||||
let secret = &state.config.jwt_secret;
|
||||
let uploads = rows
|
||||
.into_iter()
|
||||
.map(|r| FeedUpload {
|
||||
liked_by_me: liked_set.contains(&r.id),
|
||||
id: r.id,
|
||||
user_id: r.user_id,
|
||||
uploader_name: r.uploader_name,
|
||||
preview_url: r.preview_path.map(|p| format!("/media/{p}")),
|
||||
thumbnail_url: r.thumbnail_path.map(|p| format!("/media/{p}")),
|
||||
mime_type: r.mime_type,
|
||||
caption: r.caption,
|
||||
like_count: r.like_count,
|
||||
comment_count: r.comment_count,
|
||||
created_at: r.created_at,
|
||||
.map(|r| {
|
||||
let liked = liked_set.contains(&r.id);
|
||||
to_feed_upload(r, liked, secret, now)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Json(DeltaResponse {
|
||||
uploads,
|
||||
deleted_ids: deleted_ids.into_iter().map(|r| r.0).collect(),
|
||||
reload_required,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -9,10 +9,21 @@ use crate::auth::middleware::RequireHost;
|
||||
use crate::error::AppError;
|
||||
use crate::models::comment::Comment;
|
||||
use crate::models::event::Event;
|
||||
use crate::models::session::Session;
|
||||
use crate::models::upload::Upload;
|
||||
use crate::models::user::UserRole;
|
||||
use crate::state::{AppState, SseEvent};
|
||||
|
||||
/// Revoke all of a user's sessions (best-effort). A failure here is logged but
|
||||
/// never fails the surrounding admin action — the live-role/ban reconciliation
|
||||
/// in `AuthUser` is the authoritative gate; revocation is defense-in-depth.
|
||||
async fn revoke_sessions(pool: &sqlx::PgPool, user_id: Uuid, action: &str) {
|
||||
match Session::delete_by_user_id(pool, user_id).await {
|
||||
Ok(n) => tracing::info!(target_user_id = %user_id, revoked = n, action, "sessions revoked"),
|
||||
Err(e) => tracing::warn!(error = ?e, target_user_id = %user_id, action, "session revoke failed"),
|
||||
}
|
||||
}
|
||||
|
||||
// ── DTOs ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Serialize, sqlx::FromRow)]
|
||||
@@ -120,6 +131,14 @@ pub async fn ban_user(
|
||||
.execute(&state.pool)
|
||||
.await?;
|
||||
|
||||
revoke_sessions(&state.pool, user_id, "ban_user").await;
|
||||
|
||||
// Tell the banned user's online devices to log out immediately.
|
||||
let _ = state.sse_tx.send(SseEvent::new(
|
||||
"user-banned",
|
||||
serde_json::json!({ "user_id": user_id }).to_string(),
|
||||
));
|
||||
|
||||
tracing::info!(
|
||||
actor_user_id = %auth.user_id,
|
||||
target_user_id = %user_id,
|
||||
@@ -201,6 +220,13 @@ pub async fn set_role(
|
||||
.bind(auth.event_id)
|
||||
.execute(&state.pool)
|
||||
.await?;
|
||||
|
||||
// Force a clean re-auth so the new role can't be cached client-side and so
|
||||
// any in-flight tokens carrying the old role are invalidated. The live-role
|
||||
// reconciliation in AuthUser already prevents privilege escalation, but
|
||||
// revoking is cheaper to reason about.
|
||||
revoke_sessions(&state.pool, user_id, "set_role").await;
|
||||
|
||||
tracing::info!(
|
||||
actor_user_id = %auth.user_id,
|
||||
target_user_id = %user_id,
|
||||
@@ -256,14 +282,13 @@ pub async fn reset_user_pin(
|
||||
}
|
||||
}
|
||||
|
||||
let pin: String = format!("{:04}", rand::rng().random_range(0..10000u32));
|
||||
let pin_hash =
|
||||
bcrypt::hash(&pin, 12).map_err(|e| AppError::Internal(anyhow::anyhow!(e)))?;
|
||||
let pin: String = format!("{:06}", rand::rng().random_range(0..1_000_000u32));
|
||||
let pin_hash = crate::services::password::hash(pin.clone(), 12).await?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE \"user\"
|
||||
SET recovery_pin_hash = $1,
|
||||
pin_failed_attempts = 0,
|
||||
failed_pin_attempts = 0,
|
||||
pin_locked_until = NULL
|
||||
WHERE id = $2",
|
||||
)
|
||||
@@ -272,6 +297,10 @@ pub async fn reset_user_pin(
|
||||
.execute(&state.pool)
|
||||
.await?;
|
||||
|
||||
// A PIN reset must invalidate existing sessions so a compromised/old token
|
||||
// can't outlive the reset.
|
||||
revoke_sessions(&state.pool, user_id, "reset_user_pin").await;
|
||||
|
||||
// Notify the *recipient* device(s) if they happen to be online so they can clear
|
||||
// their cached local PIN. They'll save the new one on the next /recover.
|
||||
let _ = state.sse_tx.send(SseEvent::new(
|
||||
@@ -294,24 +323,21 @@ pub async fn host_delete_upload(
|
||||
RequireHost(auth): RequireHost,
|
||||
Path(upload_id): Path<Uuid>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
let upload = Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id)
|
||||
let paths = Upload::soft_delete_in_event(&state.pool, upload_id, auth.event_id)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
||||
|
||||
let deleted = Upload::soft_delete_in_event(&state.pool, upload_id, auth.event_id).await?;
|
||||
if !deleted {
|
||||
return Err(AppError::NotFound("Upload nicht gefunden.".into()));
|
||||
}
|
||||
crate::services::media_fs::unlink_media(&state.config.media_path, &paths).await;
|
||||
|
||||
let _ = state.sse_tx.send(SseEvent::new(
|
||||
"upload-deleted",
|
||||
serde_json::json!({ "upload_id": upload.id }).to_string(),
|
||||
serde_json::json!({ "upload_id": upload_id }).to_string(),
|
||||
));
|
||||
|
||||
tracing::info!(
|
||||
actor_user_id = %auth.user_id,
|
||||
event_id = %auth.event_id,
|
||||
upload_id = %upload.id,
|
||||
upload_id = %upload_id,
|
||||
"host: host_delete_upload"
|
||||
);
|
||||
|
||||
@@ -377,28 +403,65 @@ pub async fn release_gallery(
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound("Event nicht gefunden.".into()))?;
|
||||
|
||||
if event.export_released_at.is_some() {
|
||||
return Err(AppError::BadRequest("Galerie wurde bereits freigegeben.".into()));
|
||||
// Atomically claim the release AND enqueue the jobs in one transaction (M8).
|
||||
// The claim UPDATE row-locks the event row and the lock is held until commit
|
||||
// — *after* the export_job rows exist — so a second concurrent press re-reads
|
||||
// the now-present jobs and matches 0 rows (clean 400). Doing the UPDATE and
|
||||
// INSERTs as separate autocommit statements left a cross-table TOCTOU window
|
||||
// where both presses could win and race the same output files.
|
||||
//
|
||||
// Re-release guard (M8-3): allow when never released, OR nothing is currently
|
||||
// in progress and at least one job terminally failed. The old "every job
|
||||
// failed" guard left a one-sided failure (zip done, html failed) permanently
|
||||
// unrecoverable.
|
||||
let mut tx = state.pool.begin().await?;
|
||||
|
||||
let claim = sqlx::query(
|
||||
"UPDATE event SET export_released_at = NOW()
|
||||
WHERE slug = $1
|
||||
AND (
|
||||
export_released_at IS NULL
|
||||
OR (
|
||||
NOT EXISTS (
|
||||
SELECT 1 FROM export_job j
|
||||
WHERE j.event_id = event.id AND j.status IN ('running', 'pending')
|
||||
)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM export_job j
|
||||
WHERE j.event_id = event.id AND j.status = 'failed'
|
||||
)
|
||||
)
|
||||
)",
|
||||
)
|
||||
.bind(&state.config.event_slug)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
if claim.rows_affected() == 0 {
|
||||
tx.rollback().await.ok();
|
||||
return Err(AppError::BadRequest(
|
||||
"Galerie wurde bereits freigegeben.".into(),
|
||||
));
|
||||
}
|
||||
|
||||
sqlx::query("UPDATE event SET export_released_at = NOW() WHERE slug = $1")
|
||||
.bind(&state.config.event_slug)
|
||||
.execute(&state.pool)
|
||||
.await?;
|
||||
|
||||
// Enqueue export jobs
|
||||
// Enqueue export jobs, resetting any prior terminal rows so the workers
|
||||
// re-run cleanly (including an already-`done` sibling on re-release).
|
||||
for export_type in ["zip", "html"] {
|
||||
sqlx::query(
|
||||
"INSERT INTO export_job (event_id, type) VALUES ($1, $2::export_type)
|
||||
ON CONFLICT (event_id, type) DO NOTHING",
|
||||
ON CONFLICT (event_id, type)
|
||||
DO UPDATE SET status = 'pending', progress_pct = 0,
|
||||
error_message = NULL, completed_at = NULL",
|
||||
)
|
||||
.bind(event.id)
|
||||
.bind(export_type)
|
||||
.execute(&state.pool)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
// Spawn export workers
|
||||
tx.commit().await?;
|
||||
|
||||
// Spawn export workers only after the claim+enqueue is durably committed.
|
||||
crate::services::export::spawn_export_jobs(
|
||||
event.id,
|
||||
event.name,
|
||||
|
||||
@@ -55,6 +55,9 @@ pub struct MeContextDto {
|
||||
pub privacy_note: String,
|
||||
pub quota_enabled: bool,
|
||||
pub storage_quota_enabled: bool,
|
||||
/// Whether uploads are currently locked for the event, so the client can show
|
||||
/// a banner + disable the upload affordance on load (not just via SSE).
|
||||
pub uploads_locked: bool,
|
||||
}
|
||||
|
||||
pub async fn get_context(
|
||||
@@ -68,6 +71,10 @@ pub async fn get_context(
|
||||
let privacy_note = config::get_str(&state.pool, "privacy_note", "").await;
|
||||
let quota_enabled = config::get_bool(&state.pool, "quota_enabled", true).await;
|
||||
let storage_quota_enabled = config::get_bool(&state.pool, "storage_quota_enabled", true).await;
|
||||
let uploads_locked = crate::models::event::Event::find_by_slug(&state.pool, &state.config.event_slug)
|
||||
.await?
|
||||
.map(|e| e.uploads_locked_at.is_some())
|
||||
.unwrap_or(false);
|
||||
|
||||
Ok(Json(MeContextDto {
|
||||
user_id: user.id,
|
||||
@@ -76,5 +83,6 @@ pub async fn get_context(
|
||||
privacy_note,
|
||||
quota_enabled,
|
||||
storage_quota_enabled,
|
||||
uploads_locked,
|
||||
}))
|
||||
}
|
||||
|
||||
117
backend/src/handlers/media.rs
Normal file
117
backend/src/handlers/media.rs
Normal file
@@ -0,0 +1,117 @@
|
||||
//! Authenticated media gateway.
|
||||
//!
|
||||
//! Replaces the raw `/media` `ServeDir`. Every media byte now flows through a
|
||||
//! signature check plus a DB lookup, so:
|
||||
//! - soft-deleted uploads 404 (`find_by_id` filters `deleted_at`) — closes C3,
|
||||
//! - ban-hidden uploaders' artifacts 404 (mirrors the `v_feed` rule) — H2,
|
||||
//! - the export archives (which have no `upload` row) are unreachable — C1,
|
||||
//! - HTML/SVG can't be served as an active document — the response carries
|
||||
//! `nosniff` + a locked-down CSP (defense-in-depth behind the upload-time
|
||||
//! allowlist) — C2 sink.
|
||||
//!
|
||||
//! Access is authorized by the embedded HMAC signature (see `media_token`), not
|
||||
//! a Bearer header, because `<img>`/`<video>` cannot send one.
|
||||
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::response::Response;
|
||||
use chrono::Utc;
|
||||
use serde::Deserialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::upload::Upload;
|
||||
use crate::models::user::User;
|
||||
use crate::services::media_token;
|
||||
use crate::state::AppState;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct MediaQuery {
|
||||
pub exp: i64,
|
||||
pub sig: String,
|
||||
}
|
||||
|
||||
pub async fn serve(
|
||||
State(state): State<AppState>,
|
||||
Path((kind, id)): Path<(String, Uuid)>,
|
||||
Query(q): Query<MediaQuery>,
|
||||
) -> Result<Response, AppError> {
|
||||
if !media_token::verify(
|
||||
&state.config.jwt_secret,
|
||||
&kind,
|
||||
id,
|
||||
q.exp,
|
||||
&q.sig,
|
||||
Utc::now().timestamp(),
|
||||
) {
|
||||
return Err(AppError::Unauthorized(
|
||||
"Ungültige oder abgelaufene Medien-URL.".into(),
|
||||
));
|
||||
}
|
||||
|
||||
// `find_by_id` filters `deleted_at IS NULL`, so soft-deleted uploads 404.
|
||||
let upload = Upload::find_by_id(&state.pool, id)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound("Datei nicht gefunden.".into()))?;
|
||||
|
||||
// Hide artifacts of users whose uploads were hidden by a host (ban + hide),
|
||||
// matching the `usr.uploads_hidden = FALSE` predicate in `v_feed`.
|
||||
let uploader = User::find_by_id(&state.pool, upload.user_id)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound("Datei nicht gefunden.".into()))?;
|
||||
if uploader.uploads_hidden {
|
||||
return Err(AppError::NotFound("Datei nicht gefunden.".into()));
|
||||
}
|
||||
|
||||
let (rel_path, content_type) = match kind.as_str() {
|
||||
"original" => (upload.original_path.clone(), upload.mime_type.clone()),
|
||||
"preview" => (
|
||||
upload
|
||||
.preview_path
|
||||
.clone()
|
||||
.ok_or_else(|| AppError::NotFound("Vorschau nicht verfügbar.".into()))?,
|
||||
"image/jpeg".to_string(),
|
||||
),
|
||||
"thumbnail" => (
|
||||
upload
|
||||
.thumbnail_path
|
||||
.clone()
|
||||
.ok_or_else(|| AppError::NotFound("Vorschau nicht verfügbar.".into()))?,
|
||||
"image/jpeg".to_string(),
|
||||
),
|
||||
_ => return Err(AppError::NotFound("Unbekannter Medientyp.".into())),
|
||||
};
|
||||
|
||||
stream_file(&state.config.media_path.join(&rel_path), &content_type).await
|
||||
}
|
||||
|
||||
async fn stream_file(path: &std::path::Path, content_type: &str) -> Result<Response, AppError> {
|
||||
use axum::body::Body;
|
||||
use axum::http::{header, StatusCode};
|
||||
use tokio_util::io::ReaderStream;
|
||||
|
||||
let file = tokio::fs::File::open(path)
|
||||
.await
|
||||
.map_err(|_| AppError::NotFound("Datei nicht gefunden.".into()))?;
|
||||
let metadata = file
|
||||
.metadata()
|
||||
.await
|
||||
.map_err(|e| AppError::Internal(e.into()))?;
|
||||
let stream = ReaderStream::new(file);
|
||||
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, content_type)
|
||||
.header(header::CONTENT_LENGTH, metadata.len())
|
||||
// URLs are signed + time-boxed; cache only privately, aligned to the
|
||||
// 1h URL-stability bucket.
|
||||
.header(header::CACHE_CONTROL, "private, max-age=3600")
|
||||
// Defense-in-depth against any active content slipping past the
|
||||
// upload-time allowlist: never sniff, never script.
|
||||
.header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
|
||||
.header(
|
||||
header::CONTENT_SECURITY_POLICY,
|
||||
"default-src 'none'; sandbox; frame-ancestors 'none'",
|
||||
)
|
||||
.body(Body::from_stream(stream))
|
||||
.map_err(|e| AppError::Internal(e.into()))
|
||||
}
|
||||
@@ -2,6 +2,7 @@ pub mod admin;
|
||||
pub mod feed;
|
||||
pub mod host;
|
||||
pub mod me;
|
||||
pub mod media;
|
||||
pub mod social;
|
||||
pub mod sse;
|
||||
pub mod test_admin;
|
||||
|
||||
@@ -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(
|
||||
@@ -16,13 +17,12 @@ pub async fn toggle_like(
|
||||
auth: AuthUser,
|
||||
Path(upload_id): Path<Uuid>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
// Check if user is banned
|
||||
let user = crate::models::user::User::find_by_id(&state.pool, auth.user_id)
|
||||
// Ban is already rejected by the AuthUser extractor. Scope the target to the
|
||||
// caller's event and reject deleted uploads (M1: no cross-event IDOR, no
|
||||
// likes on soft-deleted posts).
|
||||
Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound("Benutzer nicht gefunden.".into()))?;
|
||||
if user.is_banned {
|
||||
return Err(AppError::Forbidden("Du bist gesperrt.".into()));
|
||||
}
|
||||
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
||||
|
||||
// Try to insert; if conflict, delete (toggle)
|
||||
let result = sqlx::query(
|
||||
@@ -64,10 +64,16 @@ 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> {
|
||||
// M1: a pure read behind any valid token must still be scoped to the
|
||||
// caller's event and must not leak comments on soft-deleted uploads.
|
||||
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))
|
||||
@@ -84,12 +90,15 @@ pub async fn add_comment(
|
||||
Path(upload_id): Path<Uuid>,
|
||||
Json(body): Json<AddCommentRequest>,
|
||||
) -> Result<(StatusCode, Json<CommentDto>), AppError> {
|
||||
// M1: scope the target upload to the caller's event and reject deleted
|
||||
// posts. (Ban is already handled by the AuthUser extractor.)
|
||||
Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
||||
|
||||
let user = crate::models::user::User::find_by_id(&state.pool, auth.user_id)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound("Benutzer nicht gefunden.".into()))?;
|
||||
if user.is_banned {
|
||||
return Err(AppError::Forbidden("Du bist gesperrt.".into()));
|
||||
}
|
||||
|
||||
let text = body.body.trim();
|
||||
let text_chars = text.chars().count();
|
||||
|
||||
@@ -16,6 +16,35 @@ use crate::state::AppState;
|
||||
|
||||
const MAX_CAPTION_LENGTH: usize = 2000;
|
||||
|
||||
/// Derive the canonical MIME type and a *safe* file extension purely from the
|
||||
/// file's magic bytes, against a strict allowlist. The client-declared
|
||||
/// `Content-Type` and the client filename are never trusted: the old code
|
||||
/// skipped validation entirely for `application/*` and copied the extension
|
||||
/// verbatim from the filename, which allowed storing `{uuid}.html`/`.svg` with
|
||||
/// a script payload (stored XSS) and `/`-bearing extensions (path pollution +
|
||||
/// export DoS).
|
||||
///
|
||||
/// `infer` cannot fingerprint HTML/SVG, so the reject-by-default arm is exactly
|
||||
/// what closes the XSS vector — anything not positively identified as an allowed
|
||||
/// raster image or video is refused. Returns `(canonical_mime, safe_ext, is_video)`.
|
||||
fn classify(data: &[u8]) -> Result<(&'static str, &'static str, bool), AppError> {
|
||||
let kind = infer::get(data)
|
||||
.ok_or_else(|| AppError::BadRequest("Dateityp konnte nicht erkannt werden.".into()))?;
|
||||
match kind.mime_type() {
|
||||
"image/jpeg" => Ok(("image/jpeg", "jpg", false)),
|
||||
"image/png" => Ok(("image/png", "png", false)),
|
||||
"image/webp" => Ok(("image/webp", "webp", false)),
|
||||
// infer reports HEIC/HEIF as image/heif
|
||||
"image/heif" | "image/heic" => Ok(("image/heic", "heic", false)),
|
||||
"video/mp4" => Ok(("video/mp4", "mp4", true)),
|
||||
"video/quicktime" => Ok(("video/quicktime", "mov", true)),
|
||||
"video/webm" => Ok(("video/webm", "webm", true)),
|
||||
other => Err(AppError::BadRequest(format!(
|
||||
"Dateityp nicht erlaubt: {other}. Erlaubt sind JPEG, PNG, WebP, HEIC, MP4, MOV, WebM."
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn upload(
|
||||
State(state): State<AppState>,
|
||||
auth: AuthUser,
|
||||
@@ -39,14 +68,11 @@ pub async fn upload(
|
||||
}
|
||||
}
|
||||
|
||||
// Check if user is banned
|
||||
// Ban is already rejected by the AuthUser extractor. We still load the user
|
||||
// for the uploader's display name in the response DTO.
|
||||
let user = User::find_by_id(&state.pool, auth.user_id)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound("Benutzer nicht gefunden.".into()))?;
|
||||
if user.is_banned {
|
||||
drain_multipart(multipart).await;
|
||||
return Err(AppError::Forbidden("Du bist gesperrt.".into()));
|
||||
}
|
||||
|
||||
// Check if uploads are locked
|
||||
let event = crate::models::event::Event::find_by_slug(&state.pool, &state.config.event_slug)
|
||||
@@ -61,9 +87,17 @@ pub async fn upload(
|
||||
let max_image_mb: i64 = config::get_i64(&state.pool, "max_image_size_mb", 20).await;
|
||||
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;
|
||||
// Bound concurrent upload-body buffering to cap aggregate RAM (H3). Acquired
|
||||
// *before* the multipart body is read, so requests waiting on a permit hold
|
||||
// only a connection, not a buffered ~550 MB file. The permit is held for the
|
||||
// rest of the handler (body read + write) and released on return.
|
||||
let _upload_permit = state
|
||||
.upload_limiter
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|e| AppError::Internal(e.into()))?;
|
||||
|
||||
let mut file_data: Option<axum::body::Bytes> = None;
|
||||
let mut caption: Option<String> = None;
|
||||
let mut hashtags_csv: Option<String> = None;
|
||||
|
||||
@@ -71,12 +105,13 @@ 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());
|
||||
// The client-declared filename and Content-Type are deliberately
|
||||
// ignored — the stored MIME and extension are derived from the
|
||||
// file's magic bytes (see `classify`). Kept as `Bytes` (one copy
|
||||
// off the wire) rather than an extra `.to_vec()`.
|
||||
file_data = Some(
|
||||
field.bytes().await
|
||||
.map_err(|e| AppError::BadRequest(format!("Datei konnte nicht gelesen werden: {e}")))?
|
||||
.to_vec(),
|
||||
.map_err(|e| AppError::BadRequest(format!("Datei konnte nicht gelesen werden: {e}")))?,
|
||||
);
|
||||
}
|
||||
"caption" => {
|
||||
@@ -96,7 +131,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,25 +145,13 @@ 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("");
|
||||
// Derive canonical MIME + safe extension from magic bytes against a strict
|
||||
// allowlist. The client Content-Type and filename are never trusted.
|
||||
let (canonical_mime, safe_ext, is_video) = classify(&data)?;
|
||||
let canonical_mime = canonical_mime.to_string();
|
||||
|
||||
// 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
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
// Validate file size
|
||||
let max_bytes = if mime.starts_with("video/") {
|
||||
// Validate file size against the per-category limit.
|
||||
let max_bytes = if is_video {
|
||||
max_video_mb * 1024 * 1024
|
||||
} else {
|
||||
max_image_mb * 1024 * 1024
|
||||
@@ -141,59 +163,120 @@ pub async fn upload(
|
||||
)));
|
||||
}
|
||||
|
||||
let upload_id = Uuid::new_v4();
|
||||
let event_slug = &state.config.event_slug;
|
||||
let relative_path = format!("originals/{event_slug}/{upload_id}.{safe_ext}");
|
||||
let absolute_path = state.config.media_path.join(&relative_path);
|
||||
|
||||
// Per-user storage quota — dynamic formula based on available disk space and the
|
||||
// number of active uploaders. Gated by master + per-area toggles so the admin can
|
||||
// disable it on trusted instances.
|
||||
// disable it on trusted instances. `None` ⇒ enforcement off.
|
||||
let quota_on = config::get_bool(&state.pool, "quota_enabled", true).await;
|
||||
let storage_quota_on = config::get_bool(&state.pool, "storage_quota_enabled", true).await;
|
||||
if quota_on && storage_quota_on {
|
||||
let estimate = compute_storage_quota(&state).await;
|
||||
if let Some(limit) = estimate.limit_bytes {
|
||||
let prospective_total = user.total_upload_bytes.saturating_add(size);
|
||||
if prospective_total > limit {
|
||||
return Err(AppError::TooManyRequests(
|
||||
"Du hast dein Upload-Limit für dieses Event erreicht.".into(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
let quota_limit: Option<i64> = if quota_on && storage_quota_on {
|
||||
compute_storage_quota(&state).await.limit_bytes
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Event-wide file-count cap. Unlike the per-user budget, this can't be reset
|
||||
// by minting a fresh account via /join, so it bounds total uploads no matter
|
||||
// how many accounts an abuser creates. Wires up the previously-dead
|
||||
// `upload_count_quota_*` config (default off to preserve existing behavior).
|
||||
if quota_on && config::get_bool(&state.pool, "upload_count_quota_enabled", false).await {
|
||||
let max_count = config::get_i64(&state.pool, "upload_count_quota_max", 10_000).await;
|
||||
let (count,): (i64,) = sqlx::query_as(
|
||||
"SELECT COUNT(*) FROM upload WHERE event_id = $1 AND deleted_at IS NULL",
|
||||
)
|
||||
.bind(auth.event_id)
|
||||
.fetch_one(&state.pool)
|
||||
.await?;
|
||||
if count >= max_count {
|
||||
return Err(AppError::TooManyRequests(
|
||||
"Das Upload-Limit für dieses Event ist erreicht.".into(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// 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" });
|
||||
// Reserve quota and insert the row in a single transaction so the byte
|
||||
// counter and the upload row are atomic (M6: no quota leak if we crash
|
||||
// between them) and the reservation is a conditional UPDATE that row-locks
|
||||
// (M5: concurrent uploads can no longer all pass a stale snapshot and
|
||||
// overshoot the limit). The file is written before commit and unlinked on
|
||||
// any rollback so a failed transaction leaves nothing behind.
|
||||
let mut tx = state.pool.begin().await?;
|
||||
|
||||
let upload_id = Uuid::new_v4();
|
||||
let event_slug = &state.config.event_slug;
|
||||
let relative_path = format!("originals/{event_slug}/{upload_id}.{ext}");
|
||||
let absolute_path = state.config.media_path.join(&relative_path);
|
||||
|
||||
// Ensure directory exists and write file
|
||||
if let Some(parent) = absolute_path.parent() {
|
||||
tokio::fs::create_dir_all(parent).await.map_err(|e| AppError::Internal(e.into()))?;
|
||||
}
|
||||
tokio::fs::write(&absolute_path, &data).await.map_err(|e| AppError::Internal(e.into()))?;
|
||||
|
||||
// Update user's total upload bytes
|
||||
sqlx::query("UPDATE \"user\" SET total_upload_bytes = total_upload_bytes + $2 WHERE id = $1")
|
||||
let reserved: Option<(Uuid,)> = if let Some(limit) = quota_limit {
|
||||
sqlx::query_as(
|
||||
"UPDATE \"user\"
|
||||
SET total_upload_bytes = total_upload_bytes + $2
|
||||
WHERE id = $1 AND total_upload_bytes + $2 <= $3
|
||||
RETURNING id",
|
||||
)
|
||||
.bind(auth.user_id)
|
||||
.bind(size)
|
||||
.execute(&state.pool)
|
||||
.await?;
|
||||
.bind(limit)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"UPDATE \"user\"
|
||||
SET total_upload_bytes = total_upload_bytes + $2
|
||||
WHERE id = $1
|
||||
RETURNING id",
|
||||
)
|
||||
.bind(auth.user_id)
|
||||
.bind(size)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
};
|
||||
if reserved.is_none() {
|
||||
// The user exists (checked above), so a missing row here means the
|
||||
// conditional limit guard rejected the reservation → over quota.
|
||||
tx.rollback().await.ok();
|
||||
return Err(AppError::TooManyRequests(
|
||||
"Du hast dein Upload-Limit für dieses Event erreicht.".into(),
|
||||
None,
|
||||
));
|
||||
}
|
||||
|
||||
// Insert upload record
|
||||
let upload = Upload::create(
|
||||
&state.pool,
|
||||
// Write the file. On any failure, roll back (releasing the reservation) and
|
||||
// remove a possibly-partial file.
|
||||
if let Some(parent) = absolute_path.parent() {
|
||||
if let Err(e) = tokio::fs::create_dir_all(parent).await {
|
||||
tx.rollback().await.ok();
|
||||
return Err(AppError::Internal(e.into()));
|
||||
}
|
||||
}
|
||||
if let Err(e) = tokio::fs::write(&absolute_path, data.as_ref()).await {
|
||||
tx.rollback().await.ok();
|
||||
return Err(AppError::Internal(e.into()));
|
||||
}
|
||||
|
||||
let upload = match Upload::create(
|
||||
&mut *tx,
|
||||
auth.event_id,
|
||||
auth.user_id,
|
||||
&relative_path,
|
||||
&mime,
|
||||
&canonical_mime,
|
||||
size,
|
||||
caption.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
{
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
tx.rollback().await.ok();
|
||||
let _ = tokio::fs::remove_file(&absolute_path).await;
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = tx.commit().await {
|
||||
let _ = tokio::fs::remove_file(&absolute_path).await;
|
||||
return Err(e.into());
|
||||
}
|
||||
|
||||
// Process hashtags from caption and explicit CSV
|
||||
let mut tags: Vec<String> = Vec::new();
|
||||
@@ -219,7 +302,7 @@ pub async fn upload(
|
||||
// Spawn compression task
|
||||
state
|
||||
.compression
|
||||
.process(upload.id, relative_path, mime.clone());
|
||||
.process(upload.id, relative_path, canonical_mime.clone());
|
||||
|
||||
// Broadcast SSE event
|
||||
let dto = UploadDto {
|
||||
@@ -228,7 +311,13 @@ pub async fn upload(
|
||||
uploader_name: user.display_name,
|
||||
preview_url: None,
|
||||
thumbnail_url: None,
|
||||
mime_type: mime,
|
||||
original_url: Some(crate::services::media_token::signed_url(
|
||||
&state.config.jwt_secret,
|
||||
"original",
|
||||
upload.id,
|
||||
chrono::Utc::now().timestamp(),
|
||||
)),
|
||||
mime_type: canonical_mime,
|
||||
caption,
|
||||
hashtags: tags,
|
||||
like_count: 0,
|
||||
@@ -293,7 +382,15 @@ pub async fn delete_upload(
|
||||
return Err(AppError::Forbidden("Nur eigene Uploads löschen.".into()));
|
||||
}
|
||||
|
||||
Upload::soft_delete(&state.pool, upload_id).await?;
|
||||
if let Some(paths) = Upload::soft_delete(&state.pool, upload_id).await? {
|
||||
crate::services::media_fs::unlink_media(&state.config.media_path, &paths).await;
|
||||
}
|
||||
|
||||
// Tell other clients to drop the photo immediately (mirrors host delete).
|
||||
let _ = state.sse_tx.send(crate::state::SseEvent::new(
|
||||
"upload-deleted",
|
||||
serde_json::json!({ "upload_id": upload_id }).to_string(),
|
||||
));
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
@@ -361,53 +458,44 @@ pub async fn compute_storage_quota(state: &AppState) -> QuotaEstimate {
|
||||
}
|
||||
}
|
||||
|
||||
/// Streaming download of the original file behind an upload. Used by:
|
||||
/// - the per-post "Original anzeigen" context action (`window.open`)
|
||||
/// - `<img src>` / `<video src>` in the feed, lightbox, and diashow when the user is in
|
||||
/// Data Mode = Original
|
||||
///
|
||||
/// **Auth model:** the route is intentionally unauthenticated, matching how the rest of
|
||||
/// `/media/*` is served (preview + thumbnail variants). The URL contains the upload's
|
||||
/// UUID, which is unguessable — same security posture as `/media/originals/{slug}/{id}`.
|
||||
/// Adding `Authorization: Bearer` here would make the endpoint unusable from `<img src>`
|
||||
/// and `window.open`, defeating the purpose of having the alias.
|
||||
pub async fn get_original(
|
||||
State(state): State<AppState>,
|
||||
Path(upload_id): Path<Uuid>,
|
||||
) -> Result<axum::response::Response, AppError> {
|
||||
let upload = Upload::find_by_id(&state.pool, upload_id)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
||||
// The original-file download is now served by the authenticated, signed media
|
||||
// gateway (`handlers::media::serve`). The old unauthenticated `get_original`
|
||||
// alias was the H2 vulnerability and has been removed.
|
||||
|
||||
let absolute = state.config.media_path.join(&upload.original_path);
|
||||
if !absolute.exists() {
|
||||
return Err(AppError::NotFound("Datei nicht gefunden.".into()));
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::classify;
|
||||
|
||||
#[test]
|
||||
fn classify_accepts_allowed_image_types() {
|
||||
// PNG signature
|
||||
let png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0];
|
||||
let (mime, ext, is_video) = classify(&png).expect("png allowed");
|
||||
assert_eq!(mime, "image/png");
|
||||
assert_eq!(ext, "png");
|
||||
assert!(!is_video);
|
||||
|
||||
// JPEG signature
|
||||
let jpeg = [0xFF, 0xD8, 0xFF, 0xE0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
let (mime, ext, _) = classify(&jpeg).expect("jpeg allowed");
|
||||
assert_eq!(mime, "image/jpeg");
|
||||
assert_eq!(ext, "jpg");
|
||||
}
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{header, Response, StatusCode};
|
||||
use tokio_util::io::ReaderStream;
|
||||
#[test]
|
||||
fn classify_rejects_unrecognized_and_html_svg() {
|
||||
// Plain HTML / script payload — infer cannot fingerprint it, so it must
|
||||
// be rejected (this is the stored-XSS vector the old code let through
|
||||
// via a declared `application/*` Content-Type).
|
||||
let html = b"<html><script>alert(1)</script></html>";
|
||||
assert!(classify(html).is_err());
|
||||
|
||||
let file = tokio::fs::File::open(&absolute)
|
||||
.await
|
||||
.map_err(|e| AppError::Internal(e.into()))?;
|
||||
let metadata = file
|
||||
.metadata()
|
||||
.await
|
||||
.map_err(|e| AppError::Internal(e.into()))?;
|
||||
let stream = ReaderStream::new(file);
|
||||
// SVG (text-based) is likewise unrecognized → rejected.
|
||||
let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><script>x</script></svg>";
|
||||
assert!(classify(svg).is_err());
|
||||
|
||||
let filename = absolute
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or("original");
|
||||
let disposition = format!("attachment; filename=\"{filename}\"");
|
||||
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, upload.mime_type)
|
||||
.header(header::CONTENT_DISPOSITION, disposition)
|
||||
.header(header::CONTENT_LENGTH, metadata.len())
|
||||
.body(Body::from_stream(stream))
|
||||
.map_err(|e| AppError::Internal(e.into()))
|
||||
// Empty / garbage.
|
||||
assert!(classify(&[]).is_err());
|
||||
assert!(classify(&[0x00, 0x01, 0x02, 0x03]).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ use anyhow::Result;
|
||||
use axum::extract::DefaultBodyLimit;
|
||||
use axum::routing::{delete, get, patch, post};
|
||||
use axum::Router;
|
||||
use tower_http::services::ServeDir;
|
||||
use tower_http::trace::TraceLayer;
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||
|
||||
@@ -46,6 +45,7 @@ async fn main() -> Result<()> {
|
||||
pool,
|
||||
state.rate_limiter.clone(),
|
||||
state.sse_tickets.clone(),
|
||||
config.media_path.clone(),
|
||||
);
|
||||
|
||||
// Ensure media directories exist
|
||||
@@ -57,17 +57,15 @@ 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 — cap the request body so a single request can't buffer the box
|
||||
// into OOM. Sized to the largest allowed video (500 MB) plus multipart
|
||||
// overhead; the per-category limit is still enforced inside the handler.
|
||||
.route("/api/v1/upload", post(handlers::upload::upload)
|
||||
.route_layer(DefaultBodyLimit::disable()))
|
||||
.route_layer(DefaultBodyLimit::max(550 * 1024 * 1024)))
|
||||
.route(
|
||||
"/api/v1/upload/{id}",
|
||||
patch(handlers::upload::edit_upload).delete(handlers::upload::delete_upload),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/upload/{id}/original",
|
||||
get(handlers::upload::get_original),
|
||||
)
|
||||
// Current-user endpoints (live quota estimate, profile + privacy note bundle)
|
||||
.route("/api/v1/me/context", get(handlers::me::get_context))
|
||||
.route("/api/v1/me/quota", get(handlers::me::get_quota))
|
||||
@@ -129,14 +127,28 @@ async fn main() -> Result<()> {
|
||||
api
|
||||
};
|
||||
|
||||
// Serve media files from disk
|
||||
let media_service = ServeDir::new(&config.media_path);
|
||||
// Media is served exclusively through the authenticated, signed gateway —
|
||||
// there is no raw static mount. The gateway verifies an HMAC signature and
|
||||
// consults the DB (deleted / ban-hidden / type), so private artifacts and
|
||||
// the export archives are never reachable by guessing a path.
|
||||
// Trace spans log the request *path* only, never the query string — signed
|
||||
// media URLs carry a replayable `?sig=` capability that must not land in
|
||||
// access logs.
|
||||
let trace_layer = TraceLayer::new_for_http().make_span_with(
|
||||
|req: &axum::http::Request<axum::body::Body>| {
|
||||
tracing::info_span!(
|
||||
"request",
|
||||
method = %req.method(),
|
||||
path = %req.uri().path(),
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
let router = Router::new()
|
||||
.route("/health", get(|| async { "ok" }))
|
||||
.merge(api)
|
||||
.nest_service("/media", media_service)
|
||||
.layer(TraceLayer::new_for_http())
|
||||
.route("/media/{kind}/{id}", get(handlers::media::serve))
|
||||
.layer(trace_layer)
|
||||
.with_state(state);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(("0.0.0.0", config.app_port)).await?;
|
||||
|
||||
@@ -2,6 +2,8 @@ use chrono::{DateTime, Utc};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::models::user::UserRole;
|
||||
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
pub struct Session {
|
||||
pub id: Uuid,
|
||||
@@ -12,6 +14,18 @@ pub struct Session {
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// Live identity reconciled from the DB for a valid, unexpired session. Used by
|
||||
/// the `AuthUser` extractor so role/ban/event are sourced from the `user` row
|
||||
/// rather than trusted from (potentially stale) JWT claims.
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
pub struct AuthContext {
|
||||
pub session_id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
pub event_id: Uuid,
|
||||
pub role: UserRole,
|
||||
pub is_banned: bool,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub async fn create(
|
||||
pool: &PgPool,
|
||||
@@ -43,6 +57,25 @@ impl Session {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Reconcile a session against the live `user` row in a single round-trip.
|
||||
/// Returns `None` when the session is missing/expired. The PK join to
|
||||
/// `"user"` is cheap and lets the extractor read the *current* role/ban
|
||||
/// state instead of the JWT claim.
|
||||
pub async fn find_auth_context(
|
||||
pool: &PgPool,
|
||||
token_hash: &str,
|
||||
) -> Result<Option<AuthContext>, sqlx::Error> {
|
||||
sqlx::query_as::<_, AuthContext>(
|
||||
"SELECT s.id AS session_id, u.id AS user_id, u.event_id, u.role, u.is_banned
|
||||
FROM session s
|
||||
JOIN \"user\" u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > NOW()",
|
||||
)
|
||||
.bind(token_hash)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn touch(pool: &PgPool, id: Uuid) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE session SET last_seen_at = NOW() WHERE id = $1")
|
||||
.bind(id)
|
||||
@@ -61,4 +94,15 @@ impl Session {
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Revoke every session belonging to a user — used on ban, role change, and
|
||||
/// PIN reset so existing JWTs stop working immediately. Returns the number
|
||||
/// of sessions removed. Best-effort: callers log but do not fail on error.
|
||||
pub async fn delete_by_user_id(pool: &PgPool, user_id: Uuid) -> Result<u64, sqlx::Error> {
|
||||
let result = sqlx::query("DELETE FROM session WHERE user_id = $1")
|
||||
.bind(user_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(result.rows_affected())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,15 @@ pub struct Upload {
|
||||
pub deleted_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// On-disk artifact paths returned by the soft-delete methods so the caller can
|
||||
/// unlink the files after the DB commit.
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
pub struct DeletedPaths {
|
||||
pub original: String,
|
||||
pub preview: Option<String>,
|
||||
pub thumbnail: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct UploadDto {
|
||||
pub id: Uuid,
|
||||
@@ -26,6 +35,8 @@ pub struct UploadDto {
|
||||
pub uploader_name: String,
|
||||
pub preview_url: Option<String>,
|
||||
pub thumbnail_url: Option<String>,
|
||||
/// Signed gateway URL for the full-resolution original. Always present.
|
||||
pub original_url: Option<String>,
|
||||
pub mime_type: String,
|
||||
pub caption: Option<String>,
|
||||
pub hashtags: Vec<String>,
|
||||
@@ -36,15 +47,21 @@ pub struct UploadDto {
|
||||
}
|
||||
|
||||
impl Upload {
|
||||
pub async fn create(
|
||||
pool: &PgPool,
|
||||
/// Generic over the executor so it can run inside the upload transaction
|
||||
/// (`&mut *tx`) alongside the quota-counter reservation, keeping the
|
||||
/// byte-counter and the row atomic (no quota leak on a mid-write crash).
|
||||
pub async fn create<'e, E>(
|
||||
executor: E,
|
||||
event_id: Uuid,
|
||||
user_id: Uuid,
|
||||
original_path: &str,
|
||||
mime_type: &str,
|
||||
original_size_bytes: i64,
|
||||
caption: Option<&str>,
|
||||
) -> Result<Self, sqlx::Error> {
|
||||
) -> Result<Self, sqlx::Error>
|
||||
where
|
||||
E: sqlx::PgExecutor<'e>,
|
||||
{
|
||||
sqlx::query_as::<_, Self>(
|
||||
"INSERT INTO upload (event_id, user_id, original_path, mime_type, original_size_bytes, caption)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
@@ -56,7 +73,7 @@ impl Upload {
|
||||
.bind(mime_type)
|
||||
.bind(original_size_bytes)
|
||||
.bind(caption)
|
||||
.fetch_one(pool)
|
||||
.fetch_one(executor)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -119,18 +136,21 @@ impl Upload {
|
||||
///
|
||||
/// No-op if the row is already deleted — protects against a double-tap on the
|
||||
/// delete action double-decrementing the counter.
|
||||
pub async fn soft_delete(pool: &PgPool, id: Uuid) -> Result<(), sqlx::Error> {
|
||||
///
|
||||
/// Returns the artifact paths of the row that was deleted (`None` if nothing
|
||||
/// matched) so the caller can unlink the files after the commit.
|
||||
pub async fn soft_delete(pool: &PgPool, id: Uuid) -> Result<Option<DeletedPaths>, sqlx::Error> {
|
||||
let mut tx = pool.begin().await?;
|
||||
let row: Option<(Uuid, i64)> = sqlx::query_as(
|
||||
let row: Option<(Uuid, i64, String, Option<String>, Option<String>)> = sqlx::query_as(
|
||||
"UPDATE upload
|
||||
SET deleted_at = NOW()
|
||||
WHERE id = $1 AND deleted_at IS NULL
|
||||
RETURNING user_id, original_size_bytes",
|
||||
RETURNING user_id, original_size_bytes, original_path, preview_path, thumbnail_path",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
if let Some((user_id, bytes)) = row {
|
||||
let paths = if let Some((user_id, bytes, original, preview, thumbnail)) = row {
|
||||
sqlx::query(
|
||||
"UPDATE \"user\"
|
||||
SET total_upload_bytes = GREATEST(0, total_upload_bytes - $2)
|
||||
@@ -140,31 +160,34 @@ impl Upload {
|
||||
.bind(bytes)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
Some(DeletedPaths { original, preview, thumbnail })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
/// Event-scoped variant of [`Self::soft_delete`]. Returns `false` if no row
|
||||
/// Event-scoped variant of [`Self::soft_delete`]. Returns `None` if no row
|
||||
/// matched (already deleted, wrong event, or unknown id) so host handlers
|
||||
/// can return a clean 404 instead of silently no-op'ing.
|
||||
/// can return a clean 404, and the artifact paths otherwise.
|
||||
pub async fn soft_delete_in_event(
|
||||
pool: &PgPool,
|
||||
id: Uuid,
|
||||
event_id: Uuid,
|
||||
) -> Result<bool, sqlx::Error> {
|
||||
) -> Result<Option<DeletedPaths>, sqlx::Error> {
|
||||
let mut tx = pool.begin().await?;
|
||||
let row: Option<(Uuid, i64)> = sqlx::query_as(
|
||||
let row: Option<(Uuid, i64, String, Option<String>, Option<String>)> = sqlx::query_as(
|
||||
"UPDATE upload
|
||||
SET deleted_at = NOW()
|
||||
WHERE id = $1 AND event_id = $2 AND deleted_at IS NULL
|
||||
RETURNING user_id, original_size_bytes",
|
||||
RETURNING user_id, original_size_bytes, original_path, preview_path, thumbnail_path",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(event_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let deleted = if let Some((user_id, bytes)) = row {
|
||||
let paths = if let Some((user_id, bytes, original, preview, thumbnail)) = row {
|
||||
sqlx::query(
|
||||
"UPDATE \"user\"
|
||||
SET total_upload_bytes = GREATEST(0, total_upload_bytes - $2)
|
||||
@@ -174,12 +197,12 @@ impl Upload {
|
||||
.bind(bytes)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
true
|
||||
Some(DeletedPaths { original, preview, thumbnail })
|
||||
} else {
|
||||
false
|
||||
None
|
||||
};
|
||||
tx.commit().await?;
|
||||
Ok(deleted)
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
pub async fn update_caption(
|
||||
|
||||
@@ -11,16 +11,27 @@ use crate::state::SseEvent;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CompressionWorker {
|
||||
semaphore: Arc<Semaphore>,
|
||||
/// Separate permit pools for images and videos so a couple of slow/large
|
||||
/// videos (each holding a permit across the full ffmpeg wait) can never
|
||||
/// starve image-preview generation, and vice versa.
|
||||
image_sem: Arc<Semaphore>,
|
||||
video_sem: Arc<Semaphore>,
|
||||
pool: PgPool,
|
||||
media_path: PathBuf,
|
||||
sse_tx: broadcast::Sender<SseEvent>,
|
||||
}
|
||||
|
||||
impl CompressionWorker {
|
||||
pub fn new(pool: PgPool, media_path: PathBuf, concurrency: usize, sse_tx: broadcast::Sender<SseEvent>) -> Self {
|
||||
pub fn new(
|
||||
pool: PgPool,
|
||||
media_path: PathBuf,
|
||||
image_concurrency: usize,
|
||||
video_concurrency: usize,
|
||||
sse_tx: broadcast::Sender<SseEvent>,
|
||||
) -> Self {
|
||||
Self {
|
||||
semaphore: Arc::new(Semaphore::new(concurrency)),
|
||||
image_sem: Arc::new(Semaphore::new(image_concurrency)),
|
||||
video_sem: Arc::new(Semaphore::new(video_concurrency)),
|
||||
pool,
|
||||
media_path,
|
||||
sse_tx,
|
||||
@@ -31,7 +42,9 @@ impl CompressionWorker {
|
||||
pub fn process(&self, upload_id: Uuid, original_path: String, mime_type: String) {
|
||||
let worker = self.clone();
|
||||
tokio::spawn(async move {
|
||||
let _permit = worker.semaphore.acquire().await;
|
||||
let is_video = mime_type.starts_with("video/");
|
||||
let sem = if is_video { &worker.video_sem } else { &worker.image_sem };
|
||||
let _permit = sem.acquire().await;
|
||||
match worker.do_process(upload_id, &original_path, &mime_type).await {
|
||||
Ok(_) => {
|
||||
tracing::info!("compression completed for upload {upload_id}");
|
||||
@@ -41,10 +54,16 @@ impl CompressionWorker {
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
// Log the detailed error (incl. paths) server-side only; the
|
||||
// SSE channel is broadcast to every client, so send a generic
|
||||
// message — never leak absolute filesystem paths.
|
||||
tracing::error!("compression failed for upload {upload_id}: {e:#}");
|
||||
let _ = worker.sse_tx.send(SseEvent {
|
||||
event_type: "upload-error".to_string(),
|
||||
data: serde_json::json!({ "upload_id": upload_id, "error": e.to_string() }).to_string(),
|
||||
data: serde_json::json!({
|
||||
"upload_id": upload_id,
|
||||
"error": "Verarbeitung fehlgeschlagen."
|
||||
}).to_string(),
|
||||
});
|
||||
let _ = Upload::set_compression_status(&worker.pool, upload_id, "failed").await;
|
||||
}
|
||||
@@ -91,10 +110,25 @@ impl CompressionWorker {
|
||||
let preview_path_clone = preview_path.clone();
|
||||
let mime_owned = mime_type.to_string();
|
||||
|
||||
// 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")?;
|
||||
// Run blocking image operations in a spawn_blocking task, bounded by a
|
||||
// hard timeout (mirrors the ffmpeg guard) so a pathological decode can't
|
||||
// hold the permit forever.
|
||||
let handle = tokio::task::spawn_blocking(move || -> Result<()> {
|
||||
use image::ImageReader;
|
||||
|
||||
// Reject decompression bombs *before* fully decoding: a small file can
|
||||
// otherwise expand to enormous dimensions and a very expensive resize.
|
||||
// 12000×12000 covers any real phone photo; max_alloc caps memory.
|
||||
let mut reader = 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);
|
||||
@@ -115,8 +149,12 @@ impl CompressionWorker {
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.await??;
|
||||
});
|
||||
|
||||
match tokio::time::timeout(std::time::Duration::from_secs(120), handle).await {
|
||||
Ok(join) => join.context("image task panicked")??,
|
||||
Err(_) => anyhow::bail!("image processing timeout after 120s"),
|
||||
}
|
||||
|
||||
Ok(format!("previews/{preview_filename}"))
|
||||
}
|
||||
|
||||
@@ -94,8 +94,14 @@ pub fn spawn_export_jobs(
|
||||
let sse_tx2 = sse_tx.clone();
|
||||
let event_name2 = event_name.clone();
|
||||
|
||||
// Per-run id so two runs (e.g. a re-release after a crash mid-export, where
|
||||
// startup_recovery marked the old run 'failed' but its task may still be
|
||||
// winding down) write to distinct temp paths and can't truncate each other's
|
||||
// output (M8). The final served filenames stay fixed.
|
||||
let run_id = Uuid::new_v4();
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = run_zip_export(event_id, &pool, &media_path, &sse_tx).await {
|
||||
if let Err(e) = run_zip_export(event_id, run_id, &pool, &media_path, &sse_tx).await {
|
||||
tracing::error!("ZIP export failed for event {event_id}: {e:#}");
|
||||
mark_failed(&pool, event_id, "zip", &e.to_string()).await;
|
||||
}
|
||||
@@ -104,7 +110,7 @@ pub fn spawn_export_jobs(
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) =
|
||||
run_html_export(event_id, &event_name2, &pool2, &media_path2, &sse_tx2).await
|
||||
run_html_export(event_id, run_id, &event_name2, &pool2, &media_path2, &sse_tx2).await
|
||||
{
|
||||
tracing::error!("HTML export failed for event {event_id}: {e:#}");
|
||||
mark_failed(&pool2, event_id, "html", &e.to_string()).await;
|
||||
@@ -117,6 +123,7 @@ pub fn spawn_export_jobs(
|
||||
|
||||
async fn run_zip_export(
|
||||
event_id: Uuid,
|
||||
run_id: Uuid,
|
||||
pool: &PgPool,
|
||||
media_path: &Path,
|
||||
sse_tx: &broadcast::Sender<SseEvent>,
|
||||
@@ -129,7 +136,8 @@ async fn run_zip_export(
|
||||
let exports_dir = media_path.join("exports");
|
||||
tokio::fs::create_dir_all(&exports_dir).await?;
|
||||
|
||||
let tmp_path = exports_dir.join("Gallery.zip.tmp");
|
||||
// Per-run temp name; final served name stays fixed.
|
||||
let tmp_path = exports_dir.join(format!("Gallery.{run_id}.zip.tmp"));
|
||||
let out_path = exports_dir.join("Gallery.zip");
|
||||
|
||||
{
|
||||
@@ -190,6 +198,7 @@ async fn run_zip_export(
|
||||
|
||||
async fn run_html_export(
|
||||
event_id: Uuid,
|
||||
run_id: Uuid,
|
||||
event_name: &str,
|
||||
pool: &PgPool,
|
||||
media_path: &Path,
|
||||
@@ -208,8 +217,8 @@ async fn run_html_export(
|
||||
let exports_dir = media_path.join("exports");
|
||||
tokio::fs::create_dir_all(&exports_dir).await?;
|
||||
|
||||
// 2. Create temp directory for media processing
|
||||
let tmp_dir = exports_dir.join(format!("viewer_tmp_{event_id}"));
|
||||
// 2. Create temp directory for media processing (per-run, see run_id).
|
||||
let tmp_dir = exports_dir.join(format!("viewer_tmp_{event_id}_{run_id}"));
|
||||
let media_tmp = tmp_dir.join("media");
|
||||
tokio::fs::create_dir_all(&media_tmp).await?;
|
||||
|
||||
@@ -370,8 +379,8 @@ async fn run_html_export(
|
||||
|
||||
update_progress(pool, event_id, "html", 72).await;
|
||||
|
||||
// 5. Create ZIP
|
||||
let tmp_path = exports_dir.join("Memories.zip.tmp");
|
||||
// 5. Create ZIP (per-run temp name; final served name stays fixed).
|
||||
let tmp_path = exports_dir.join(format!("Memories.{run_id}.zip.tmp"));
|
||||
let out_path = exports_dir.join("Memories.zip");
|
||||
|
||||
{
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
//! rate-limiter's in-memory windows (so keys for IPs that left long ago don't
|
||||
//! accumulate).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use sqlx::PgPool;
|
||||
@@ -76,6 +77,7 @@ pub fn spawn_periodic_tasks(
|
||||
pool: PgPool,
|
||||
rate_limiter: RateLimiter,
|
||||
sse_tickets: SseTicketStore,
|
||||
media_path: PathBuf,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
let mut tick = tokio::time::interval(Duration::from_secs(3600));
|
||||
@@ -86,6 +88,9 @@ pub fn spawn_periodic_tasks(
|
||||
cleanup_sessions(&pool).await;
|
||||
rate_limiter.prune();
|
||||
sse_tickets.prune();
|
||||
// Reclaim disk for uploads soft-deleted more than the grace period
|
||||
// ago, and hard-delete those rows (FKs cascade).
|
||||
crate::services::media_fs::reap_deleted(&pool, &media_path).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
83
backend/src/services/media_fs.rs
Normal file
83
backend/src/services/media_fs.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
//! Filesystem lifecycle for media artifacts.
|
||||
//!
|
||||
//! The DB-aware gateway hides deleted/hidden uploads, but the bytes still sit on
|
||||
//! a fixed-size disk until something removes them. This module is that
|
||||
//! something: best-effort unlinking on delete, plus a periodic reaper that
|
||||
//! sweeps files belonging to soft-deleted rows (catching anything an in-process
|
||||
//! unlink missed — e.g. a crash between the DB commit and the unlink).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::models::upload::DeletedPaths;
|
||||
|
||||
/// Best-effort removal of an upload's three on-disk artifacts. A missing file is
|
||||
/// not an error (it may already be gone, or never existed for videos without a
|
||||
/// preview); anything else is logged but never propagated — losing the bytes
|
||||
/// must not fail the user's delete.
|
||||
pub async fn unlink_media(media_path: &Path, paths: &DeletedPaths) {
|
||||
let candidates = [
|
||||
Some(&paths.original),
|
||||
paths.preview.as_ref(),
|
||||
paths.thumbnail.as_ref(),
|
||||
];
|
||||
for rel in candidates.into_iter().flatten() {
|
||||
let abs = media_path.join(rel);
|
||||
match tokio::fs::remove_file(&abs).await {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => tracing::warn!(path = %rel, error = ?e, "media unlink failed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reaper: remove on-disk files for uploads that were soft-deleted more than
|
||||
/// `grace` ago, then hard-delete those rows so they don't accumulate. Strictly
|
||||
/// DB-row-driven — it never walks the filesystem, so it can never remove a file
|
||||
/// belonging to a live upload.
|
||||
pub async fn reap_deleted(pool: &PgPool, media_path: &Path) {
|
||||
// Snapshot the exact rows (id + paths) we are about to unlink, and delete by
|
||||
// those ids — NOT by re-evaluating the `deleted_at < now - 1 day` predicate.
|
||||
// A row that crosses the 1-day line *during* the unlink loop would otherwise
|
||||
// be hard-deleted by the second predicate without ever having its files
|
||||
// unlinked → a permanent orphan.
|
||||
let rows: Vec<(uuid::Uuid, String, Option<String>, Option<String>)> = match sqlx::query_as(
|
||||
"SELECT id, original_path, preview_path, thumbnail_path
|
||||
FROM upload
|
||||
WHERE deleted_at IS NOT NULL AND deleted_at < NOW() - INTERVAL '1 day'",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
{
|
||||
Ok(rows) => rows,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = ?e, "media reaper: query failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut ids = Vec::with_capacity(rows.len());
|
||||
for (id, original, preview, thumbnail) in &rows {
|
||||
unlink_media(media_path, &DeletedPaths {
|
||||
original: original.clone(),
|
||||
preview: preview.clone(),
|
||||
thumbnail: thumbnail.clone(),
|
||||
})
|
||||
.await;
|
||||
ids.push(*id);
|
||||
}
|
||||
|
||||
match sqlx::query("DELETE FROM upload WHERE id = ANY($1)")
|
||||
.bind(&ids)
|
||||
.execute(pool)
|
||||
.await
|
||||
{
|
||||
Ok(r) => tracing::info!("media reaper: removed {} deleted upload(s)", r.rows_affected()),
|
||||
Err(e) => tracing::warn!(error = ?e, "media reaper: row delete failed"),
|
||||
}
|
||||
}
|
||||
122
backend/src/services/media_token.rs
Normal file
122
backend/src/services/media_token.rs
Normal file
@@ -0,0 +1,122 @@
|
||||
//! Stateless signed URLs for the authenticated media gateway.
|
||||
//!
|
||||
//! Media (`<img>`/`<video>` sources) cannot carry an `Authorization` header, so
|
||||
//! access is granted by an HMAC-SHA256 signature embedded in the URL. The
|
||||
//! feed/upload DTOs are serialized for an already-authenticated event member, so
|
||||
//! that is where fresh signatures are minted; the gateway handler verifies them
|
||||
//! without any DB/session state.
|
||||
//!
|
||||
//! HMAC is implemented over the in-tree `sha2` crate (no new dependency). The
|
||||
//! key is the app's `jwt_secret`.
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Validity window of a signed URL.
|
||||
const TTL_SECS: i64 = 24 * 3600;
|
||||
/// Issue-time bucket. Expiry (and therefore the URL) is stable within this
|
||||
/// window so the browser caches image bytes across feed polls instead of
|
||||
/// re-downloading on every refresh.
|
||||
const BUCKET_SECS: i64 = 3600;
|
||||
|
||||
fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] {
|
||||
const BLOCK: usize = 64;
|
||||
let mut key_block = [0u8; BLOCK];
|
||||
if key.len() > BLOCK {
|
||||
let digest = Sha256::digest(key);
|
||||
key_block[..32].copy_from_slice(&digest);
|
||||
} else {
|
||||
key_block[..key.len()].copy_from_slice(key);
|
||||
}
|
||||
|
||||
let mut ipad = [0x36u8; BLOCK];
|
||||
let mut opad = [0x5cu8; BLOCK];
|
||||
for i in 0..BLOCK {
|
||||
ipad[i] ^= key_block[i];
|
||||
opad[i] ^= key_block[i];
|
||||
}
|
||||
|
||||
let mut inner = Sha256::new();
|
||||
inner.update(ipad);
|
||||
inner.update(msg);
|
||||
let inner_digest = inner.finalize();
|
||||
|
||||
let mut outer = Sha256::new();
|
||||
outer.update(opad);
|
||||
outer.update(inner_digest);
|
||||
outer.finalize().into()
|
||||
}
|
||||
|
||||
fn sign(secret: &str, kind: &str, id: Uuid, exp: i64) -> String {
|
||||
let msg = format!("{kind}:{id}:{exp}");
|
||||
let mac = hmac_sha256(secret.as_bytes(), msg.as_bytes());
|
||||
let mut hex = String::with_capacity(64);
|
||||
for b in mac {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(hex, "{b:02x}");
|
||||
}
|
||||
hex
|
||||
}
|
||||
|
||||
/// Build a signed, time-boxed gateway URL for one of an upload's artifacts.
|
||||
/// `kind` is `original` | `preview` | `thumbnail`.
|
||||
pub fn signed_url(secret: &str, kind: &str, id: Uuid, now: i64) -> String {
|
||||
let exp = ((now / BUCKET_SECS) * BUCKET_SECS) + TTL_SECS;
|
||||
let sig = sign(secret, kind, id, exp);
|
||||
format!("/media/{kind}/{id}?exp={exp}&sig={sig}")
|
||||
}
|
||||
|
||||
/// Verify a signed URL: signature must match and the expiry must not have
|
||||
/// passed. Signature comparison is constant-time.
|
||||
pub fn verify(secret: &str, kind: &str, id: Uuid, exp: i64, sig: &str, now: i64) -> bool {
|
||||
if exp < now {
|
||||
return false;
|
||||
}
|
||||
let expected = sign(secret, kind, id, exp);
|
||||
constant_time_eq(expected.as_bytes(), sig.as_bytes())
|
||||
}
|
||||
|
||||
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let mut diff = 0u8;
|
||||
for (x, y) in a.iter().zip(b.iter()) {
|
||||
diff |= x ^ y;
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sign_verify_roundtrip() {
|
||||
let secret = "test_secret_at_least_32_chars_long_xxxx";
|
||||
let id = Uuid::new_v4();
|
||||
let now = 1_700_000_000;
|
||||
let url = signed_url(secret, "original", id, now);
|
||||
// Extract exp + sig from the query string.
|
||||
let (_, query) = url.split_once('?').unwrap();
|
||||
let mut exp = 0i64;
|
||||
let mut sig = String::new();
|
||||
for pair in query.split('&') {
|
||||
let (k, v) = pair.split_once('=').unwrap();
|
||||
match k {
|
||||
"exp" => exp = v.parse().unwrap(),
|
||||
"sig" => sig = v.to_string(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(verify(secret, "original", id, exp, &sig, now));
|
||||
// Tampered kind / id / sig must fail.
|
||||
assert!(!verify(secret, "preview", id, exp, &sig, now));
|
||||
assert!(!verify(secret, "original", Uuid::new_v4(), exp, &sig, now));
|
||||
assert!(!verify(secret, "original", id, exp, "deadbeef", now));
|
||||
// Wrong secret must fail.
|
||||
assert!(!verify("other_secret_at_least_32_chars_long_yy", "original", id, exp, &sig, now));
|
||||
// Expired must fail.
|
||||
assert!(!verify(secret, "original", id, exp, &sig, exp + 1));
|
||||
}
|
||||
}
|
||||
@@ -3,5 +3,8 @@ pub mod config;
|
||||
pub mod export;
|
||||
pub mod jobs;
|
||||
pub mod maintenance;
|
||||
pub mod media_fs;
|
||||
pub mod media_token;
|
||||
pub mod password;
|
||||
pub mod rate_limiter;
|
||||
pub mod sse_tickets;
|
||||
|
||||
25
backend/src/services/password.rs
Normal file
25
backend/src/services/password.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
//! bcrypt hashing/verification offloaded to the blocking pool.
|
||||
//!
|
||||
//! bcrypt cost-12 is ~250–400ms of synchronous CPU. Called directly in an async
|
||||
//! handler it pins a Tokio worker for that whole time, so a handful of
|
||||
//! concurrent joins/recovers/admin-logins can starve every other request
|
||||
//! (feed, SSE, upload). Routing the work through `spawn_blocking` keeps the
|
||||
//! async reactor responsive.
|
||||
|
||||
use crate::error::AppError;
|
||||
|
||||
/// Hash a secret with the given bcrypt cost, off the async reactor.
|
||||
pub async fn hash(plain: String, cost: u32) -> Result<String, AppError> {
|
||||
tokio::task::spawn_blocking(move || bcrypt::hash(&plain, cost))
|
||||
.await
|
||||
.map_err(|e| AppError::Internal(anyhow::anyhow!(e)))?
|
||||
.map_err(|e| AppError::Internal(anyhow::anyhow!(e)))
|
||||
}
|
||||
|
||||
/// Verify a secret against a bcrypt hash, off the async reactor. Returns `false`
|
||||
/// on any error (mirrors the previous `unwrap_or(false)` fail-closed behavior).
|
||||
pub async fn verify(plain: String, hash: String) -> bool {
|
||||
tokio::task::spawn_blocking(move || bcrypt::verify(&plain, &hash).unwrap_or(false))
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
}
|
||||
@@ -71,13 +71,55 @@ impl RateLimiter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the client IP from X-Forwarded-For (Caddy sets this) or fall back
|
||||
/// to a provided socket address string.
|
||||
/// Extract the client IP for rate-limit keys.
|
||||
///
|
||||
/// Prefers `X-Real-IP`, which our reverse proxy (Caddy) overwrites with the real
|
||||
/// TCP peer (`header_up X-Real-IP {remote_host}`) — a client cannot spoof it.
|
||||
/// Falls back to the **rightmost** `X-Forwarded-For` token (the entry the proxy
|
||||
/// appended), never the leftmost: the leftmost is fully client-controlled, and
|
||||
/// trusting it let an attacker rotate the key to bypass the join cap, the
|
||||
/// recover throttle, and the admin-login floor.
|
||||
pub fn client_ip(headers: &axum::http::HeaderMap, fallback: &str) -> String {
|
||||
if let Some(ip) = headers
|
||||
.get("x-real-ip")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(|s| s.trim())
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
return ip.to_owned();
|
||||
}
|
||||
headers
|
||||
.get("x-forwarded-for")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.split(',').next())
|
||||
.and_then(|s| s.split(',').next_back())
|
||||
.map(|s| s.trim().to_owned())
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or_else(|| fallback.to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::client_ip;
|
||||
use axum::http::HeaderMap;
|
||||
|
||||
#[test]
|
||||
fn prefers_x_real_ip() {
|
||||
let mut h = HeaderMap::new();
|
||||
h.insert("x-real-ip", "9.9.9.9".parse().unwrap());
|
||||
h.insert("x-forwarded-for", "1.1.1.1, 9.9.9.9".parse().unwrap());
|
||||
assert_eq!(client_ip(&h, "fb"), "9.9.9.9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xff_uses_rightmost_not_spoofable_leftmost() {
|
||||
// Attacker prepends a forged entry; the proxy-appended real peer is last.
|
||||
let mut h = HeaderMap::new();
|
||||
h.insert("x-forwarded-for", "1.2.3.4, 203.0.113.7".parse().unwrap());
|
||||
assert_eq!(client_ip(&h, "fb"), "203.0.113.7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_when_no_headers() {
|
||||
assert_eq!(client_ip(&HeaderMap::new(), "fb"), "fb");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use sqlx::PgPool;
|
||||
use tokio::sync::broadcast;
|
||||
use tokio::sync::{broadcast, Semaphore};
|
||||
|
||||
use crate::config::AppConfig;
|
||||
use crate::services::compression::CompressionWorker;
|
||||
use crate::services::rate_limiter::RateLimiter;
|
||||
use crate::services::sse_tickets::SseTicketStore;
|
||||
|
||||
/// Max concurrent in-flight `/upload` requests. Each holds its whole file in
|
||||
/// memory while reading the multipart body, so this bounds aggregate upload RAM
|
||||
/// to ~N × the 550 MB body cap (≈2.2 GB here) — keeping headroom for Postgres +
|
||||
/// the app on an 8 GB box. The per-user rate limiter is a *count* limiter
|
||||
/// (10/hr), not a concurrency cap, so this is the actual OOM guard. Tunable.
|
||||
pub const UPLOAD_MAX_CONCURRENCY: usize = 4;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SseEvent {
|
||||
pub event_type: String,
|
||||
@@ -31,13 +40,21 @@ pub struct AppState {
|
||||
pub compression: CompressionWorker,
|
||||
pub rate_limiter: RateLimiter,
|
||||
pub sse_tickets: SseTicketStore,
|
||||
/// Caps concurrent upload-body buffering (see UPLOAD_MAX_CONCURRENCY).
|
||||
pub upload_limiter: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(pool: PgPool, config: AppConfig) -> Self {
|
||||
let (sse_tx, _) = broadcast::channel(256);
|
||||
let compression =
|
||||
CompressionWorker::new(pool.clone(), config.media_path.clone(), 2, sse_tx.clone());
|
||||
// Independent image (2) and video (2) permit pools — see CompressionWorker.
|
||||
let compression = CompressionWorker::new(
|
||||
pool.clone(),
|
||||
config.media_path.clone(),
|
||||
2,
|
||||
2,
|
||||
sse_tx.clone(),
|
||||
);
|
||||
Self {
|
||||
pool,
|
||||
config,
|
||||
@@ -45,6 +62,7 @@ impl AppState {
|
||||
compression,
|
||||
rate_limiter: RateLimiter::new(),
|
||||
sse_tickets: SseTicketStore::new(),
|
||||
upload_limiter: Arc::new(Semaphore::new(UPLOAD_MAX_CONCURRENCY)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
# Auto-merged by `docker compose up`. Exposes Postgres for LOCAL tooling only —
|
||||
# bound to 127.0.0.1 so that even when this committed file lands on the prod host
|
||||
# the DB is NOT reachable on the public IP (a `0.0.0.0` publish would also bypass
|
||||
# ufw). Never widen this to 0.0.0.0.
|
||||
services:
|
||||
db:
|
||||
ports:
|
||||
- "5432:5432"
|
||||
- "127.0.0.1:5432:5432"
|
||||
|
||||
@@ -21,6 +21,13 @@ services:
|
||||
dockerfile: Dockerfile
|
||||
restart: unless-stopped
|
||||
env_file: .env
|
||||
# Force production mode here (not via .env, which is easy to forget) so the
|
||||
# backend's JWT-secret guard actually fires on this deployment.
|
||||
environment:
|
||||
APP_ENV: production
|
||||
# Backstop the in-app upload RAM caps: if anything slips the per-request
|
||||
# bounds, the container is OOM-killed instead of the 8 GB host.
|
||||
mem_limit: 3g
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
@@ -28,6 +35,13 @@ services:
|
||||
- media_data:/media
|
||||
expose:
|
||||
- "3000"
|
||||
# /health is unauthenticated; start_period covers the boot-time migrations.
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://localhost:3000/health"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
|
||||
frontend:
|
||||
build:
|
||||
@@ -36,9 +50,16 @@ services:
|
||||
restart: unless-stopped
|
||||
env_file: .env
|
||||
depends_on:
|
||||
- app
|
||||
app:
|
||||
condition: service_healthy
|
||||
expose:
|
||||
- "3001"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://localhost:3001/"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 15s
|
||||
|
||||
caddy:
|
||||
image: caddy:2-alpine
|
||||
@@ -49,9 +70,13 @@ services:
|
||||
volumes:
|
||||
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
||||
- caddy_data:/data
|
||||
# Gate on readiness so Caddy doesn't proxy to a not-yet-listening upstream
|
||||
# (which otherwise shows brief 502s on boot/restart).
|
||||
depends_on:
|
||||
- app
|
||||
- frontend
|
||||
app:
|
||||
condition: service_healthy
|
||||
frontend:
|
||||
condition: service_healthy
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
|
||||
51
docs/SECURITY-BACKLOG.md
Normal file
51
docs/SECURITY-BACKLOG.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Security & Hardening Backlog
|
||||
|
||||
Tracks the deliberately-deferred items from the 2026-06-27 audit and its review passes. The
|
||||
Critical→Medium findings and the cheap "bucket 🅰" LOWs are fixed on
|
||||
`fix/audit-2026-06-27-critical-medium`. What remains is recorded here so the decisions are
|
||||
explicit, not forgotten.
|
||||
|
||||
## 🅱 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.
|
||||
This is a functional hole, not polish. Needs a host-facing "remove" action wired to those
|
||||
endpoints (a `ContextSheet` action gated on host role).
|
||||
- **Feed reactivity** — a single global SSE event (`like-update`/`new-comment`/`upload-processed`)
|
||||
triggers `loadFeed(true)`, which full-replaces the list with the first 20, collapsing a
|
||||
scrolled feed; and owner-deleted uploads aren't broadcast to other clients (only host deletes
|
||||
are). Patch the affected item from the SSE payload instead of full-reloading; emit
|
||||
`upload-deleted` from the owner `delete_upload` path too.
|
||||
- **Media HMAC domain separation** — the signed-media tokens reuse `jwt_secret` as the HMAC key.
|
||||
Correct today (different message structure), but a dedicated derived key
|
||||
(`HKDF(jwt_secret, "media-url")`) would isolate the domains so a future change to one can't
|
||||
weaken the other.
|
||||
- **Quota mount-detection + low-disk guard** — `compute_storage_quota` picks the disk via
|
||||
`starts_with` (root is a wildcard prefix → 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.
|
||||
|
||||
## 🅲 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 (documented, not bugs)
|
||||
|
||||
- **Banned user retains ≤24h media access via already-held signed URLs.** The 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: tightening this would require per-request identity on every `<img>` load, which
|
||||
the `<img>`-can't-send-a-Bearer constraint precludes. Shorten the TTL in `media_token.rs` if a
|
||||
stricter bound is ever needed.
|
||||
- **Two DB queries per *cold* media fetch** (`upload` row + uploader row). Mitigated by browser
|
||||
caching and the stable bucketed URL (so warm fetches don't hit the backend at all). Could be one
|
||||
JOIN if it ever shows up in profiling.
|
||||
28
e2e/specs/01-auth/back-chevron.spec.ts
Normal file
28
e2e/specs/01-auth/back-chevron.spec.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* UX polish — back chevrons on /recover and /export. Both pages used to be
|
||||
* dead-ends for deep-linked users; the chevron mirrors the upload-composer
|
||||
* header pattern and routes back to /feed.
|
||||
*/
|
||||
import { test, expect } from '../../fixtures/test';
|
||||
|
||||
test.describe('Navigation — back chevrons', () => {
|
||||
test('/recover back chevron navigates to /feed (which redirects to /join when unauth)', async ({ page }) => {
|
||||
await page.goto('/recover');
|
||||
const back = page.getByTestId('recover-back');
|
||||
await expect(back).toBeVisible();
|
||||
await back.click();
|
||||
// Unauthenticated → /feed mounts and redirects to /join.
|
||||
await page.waitForURL(/\/(join|feed)$/);
|
||||
});
|
||||
|
||||
test('/export back chevron returns the authenticated guest to /feed', async ({ page, guest, signIn }) => {
|
||||
const g = await guest('ExportBack');
|
||||
await signIn(page, g);
|
||||
await page.goto('/export');
|
||||
|
||||
const back = page.getByTestId('export-back');
|
||||
await expect(back).toBeVisible();
|
||||
await back.click();
|
||||
await page.waitForURL('**/feed');
|
||||
});
|
||||
});
|
||||
44
e2e/specs/01-auth/pin-auto-submit.spec.ts
Normal file
44
e2e/specs/01-auth/pin-auto-submit.spec.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* UX polish — PIN inputs auto-submit on the 4th digit. Both the inline
|
||||
* recovery on /join (name-taken state) and the standalone /recover route
|
||||
* share the same auto-submit pattern: a $effect watching `pin.length === 4`.
|
||||
*
|
||||
* Coverage:
|
||||
* - Inline recovery on /join: typing 4 digits navigates to /feed without
|
||||
* a tap on Anmelden.
|
||||
* - Standalone /recover: typing 4 digits navigates to /feed.
|
||||
*/
|
||||
import { test, expect } from '../../fixtures/test';
|
||||
import { JoinPage, RecoverPage } from '../../page-objects';
|
||||
import { clearAllStorage } from '../../helpers/storage-helpers';
|
||||
|
||||
test.describe('Auth — PIN auto-submit', () => {
|
||||
test('inline recovery: 4th digit auto-submits and navigates to /feed', async ({ page, guest }) => {
|
||||
const original = await guest('AutoInline');
|
||||
await clearAllStorage(page);
|
||||
|
||||
const join = new JoinPage(page);
|
||||
await join.goto();
|
||||
await join.fillName('AutoInline');
|
||||
await join.submit();
|
||||
|
||||
// Name-taken state: type the PIN one digit at a time, do NOT click submit.
|
||||
await expect(join.recoveryPinInput).toBeVisible();
|
||||
await join.recoveryPinInput.pressSequentially(original.pin, { delay: 30 });
|
||||
|
||||
// Auto-submit must fire on the 4th digit.
|
||||
await page.waitForURL('**/feed', { timeout: 5_000 });
|
||||
});
|
||||
|
||||
test('/recover: 4th digit auto-submits when the name is already filled in', async ({ page, guest }) => {
|
||||
const original = await guest('AutoRecover');
|
||||
await clearAllStorage(page);
|
||||
|
||||
const recover = new RecoverPage(page);
|
||||
await recover.goto();
|
||||
await recover.nameInput.fill('AutoRecover');
|
||||
await recover.pinInput.pressSequentially(original.pin, { delay: 30 });
|
||||
|
||||
await page.waitForURL('**/feed', { timeout: 5_000 });
|
||||
});
|
||||
});
|
||||
62
e2e/specs/03-feed/confirm-sheet-delete.spec.ts
Normal file
62
e2e/specs/03-feed/confirm-sheet-delete.spec.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Critical UX fix — delete confirmation is now a branded bottom-sheet, not
|
||||
* the native window.confirm(). Long-press on an own upload → Löschen
|
||||
* → ConfirmSheet opens. Cancel keeps the post; Confirm removes it.
|
||||
*
|
||||
* The window.confirm path was jarring on mobile and broke the consistent
|
||||
* bottom-sheet design language; the ConfirmSheet uses the same shell as
|
||||
* ContextSheet and traps focus while open.
|
||||
*/
|
||||
import { test, expect } from '../../fixtures/test';
|
||||
import { uploadRaw } from '../../helpers/upload-client';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const SAMPLE_JPG = join(process.cwd(), 'fixtures', 'media', 'sample.jpg');
|
||||
|
||||
async function seedUpload(token: string): Promise<{ id: string }> {
|
||||
const res = await uploadRaw(token, readFileSync(SAMPLE_JPG), {
|
||||
filename: 'cs.jpg',
|
||||
contentType: 'image/jpeg',
|
||||
caption: 'Confirm-sheet fixture',
|
||||
});
|
||||
if (res.status !== 201) throw new Error(`Upload seed failed (${res.status})`);
|
||||
return (await res.json()) as { id: string };
|
||||
}
|
||||
|
||||
test.describe('Feed — ConfirmSheet replaces window.confirm for deletion', () => {
|
||||
test('Cancel keeps the post; Confirm removes it', async ({ page, guest, signIn }) => {
|
||||
const g = await guest('CSDelete');
|
||||
await seedUpload(g.jwt);
|
||||
await signIn(page, g);
|
||||
await page.goto('/feed');
|
||||
|
||||
const card = page.locator('article').filter({ hasText: g.displayName }).first();
|
||||
await expect(card).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
// Open the desktop kebab (long-press is exercised in 09-mobile; we want
|
||||
// both code paths covered without depending on touch).
|
||||
await card.getByRole('button', { name: 'Mehr Aktionen' }).click();
|
||||
|
||||
// Context sheet appears. The Löschen action is wired to set pendingDeleteId,
|
||||
// which opens the ConfirmSheet (data-testid="confirm-sheet").
|
||||
await page.getByRole('button', { name: /löschen/i }).click();
|
||||
|
||||
const confirmSheet = page.getByTestId('confirm-sheet');
|
||||
await expect(confirmSheet).toBeVisible();
|
||||
await expect(confirmSheet).toContainText(/beitrag löschen/i);
|
||||
|
||||
// Cancel — sheet closes, post stays.
|
||||
await page.getByTestId('confirm-sheet-cancel').click();
|
||||
await expect(confirmSheet).not.toBeVisible();
|
||||
await expect(card).toBeVisible();
|
||||
|
||||
// Reopen, confirm — post is removed from the DOM.
|
||||
await card.getByRole('button', { name: 'Mehr Aktionen' }).click();
|
||||
await page.getByRole('button', { name: /löschen/i }).click();
|
||||
await expect(page.getByTestId('confirm-sheet')).toBeVisible();
|
||||
await page.getByTestId('confirm-sheet-confirm').click();
|
||||
await expect(page.getByTestId('confirm-sheet')).not.toBeVisible();
|
||||
await expect(card).not.toBeVisible({ timeout: 5_000 });
|
||||
});
|
||||
});
|
||||
53
e2e/specs/03-feed/toast-on-failure.spec.ts
Normal file
53
e2e/specs/03-feed/toast-on-failure.spec.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* The toast store + <Toaster> primitive surfaces ApiError messages on
|
||||
* user-initiated actions that previously failed silently (catch { ignore }).
|
||||
* This spec intercepts the like POST and forces a 429 to assert the German
|
||||
* error message reaches the user via the global toast region.
|
||||
*/
|
||||
import { test, expect } from '../../fixtures/test';
|
||||
import { uploadRaw } from '../../helpers/upload-client';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const SAMPLE_JPG = join(process.cwd(), 'fixtures', 'media', 'sample.jpg');
|
||||
|
||||
async function seedUpload(token: string): Promise<{ id: string }> {
|
||||
const res = await uploadRaw(token, readFileSync(SAMPLE_JPG), {
|
||||
filename: 'tf.jpg',
|
||||
contentType: 'image/jpeg',
|
||||
caption: 'Toast fixture',
|
||||
});
|
||||
if (res.status !== 201) throw new Error(`Upload seed failed (${res.status})`);
|
||||
return (await res.json()) as { id: string };
|
||||
}
|
||||
|
||||
test.describe('Feed — error toast on user action failures', () => {
|
||||
test('like POST 429 surfaces a German error toast', async ({ page, guest, signIn }) => {
|
||||
const author = await guest('ToastAuthor');
|
||||
const liker = await guest('ToastLiker');
|
||||
await seedUpload(author.jwt);
|
||||
await signIn(page, liker);
|
||||
|
||||
// Intercept the like endpoint with a forced rate-limit response.
|
||||
await page.route('**/api/v1/upload/*/like', (route) =>
|
||||
route.fulfill({
|
||||
status: 429,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: 'rate_limited', message: 'Zu viele Anfragen — bitte kurz warten.' }),
|
||||
})
|
||||
);
|
||||
|
||||
await page.goto('/feed');
|
||||
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();
|
||||
|
||||
// The toast is rendered inside the global Toaster region with aria-live="polite".
|
||||
const toast = page.getByTestId('toast').first();
|
||||
await expect(toast).toBeVisible({ timeout: 3_000 });
|
||||
await expect(toast).toContainText(/Zu viele Anfragen/i);
|
||||
await expect(toast).toHaveAttribute('data-toast-tone', 'error');
|
||||
});
|
||||
});
|
||||
54
e2e/specs/09-mobile/focus-trap.spec.ts
Normal file
54
e2e/specs/09-mobile/focus-trap.spec.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Critical a11y fix — the focusTrap action keeps Tab within open modals
|
||||
* and lets Escape dismiss them, then restores focus to the originating
|
||||
* element. This spec covers the LightboxModal, which is the most-used
|
||||
* focus-trap consumer in the app.
|
||||
*/
|
||||
import { test, expect } from '../../fixtures/test';
|
||||
import { uploadRaw } from '../../helpers/upload-client';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const SAMPLE_JPG = join(process.cwd(), 'fixtures', 'media', 'sample.jpg');
|
||||
|
||||
async function seedUpload(token: string): Promise<{ id: string }> {
|
||||
const res = await uploadRaw(token, readFileSync(SAMPLE_JPG), {
|
||||
filename: 'ft.jpg',
|
||||
contentType: 'image/jpeg',
|
||||
caption: 'Focus-trap fixture',
|
||||
});
|
||||
if (res.status !== 201) throw new Error(`Upload seed failed (${res.status})`);
|
||||
return (await res.json()) as { id: string };
|
||||
}
|
||||
|
||||
test.describe('Mobile a11y — focus trap on LightboxModal', () => {
|
||||
test('Escape closes the lightbox and Tab cycles inside', async ({ page, guest, signIn }) => {
|
||||
const g = await guest('FocusTrap');
|
||||
await seedUpload(g.jwt);
|
||||
await signIn(page, g);
|
||||
await page.goto('/feed');
|
||||
|
||||
const card = page.locator('article').filter({ hasText: g.displayName }).first();
|
||||
const trigger = card.getByRole('button', { name: 'Bild vergrößern' });
|
||||
await expect(trigger).toBeVisible({ timeout: 10_000 });
|
||||
await trigger.click();
|
||||
|
||||
// Lightbox is role="dialog" aria-modal="true".
|
||||
const lightbox = page.locator('[role="dialog"][aria-modal="true"]').filter({ has: page.locator('img, video') });
|
||||
await expect(lightbox).toBeVisible();
|
||||
|
||||
// After opening, focus should be inside the lightbox (trap autoFocus moves
|
||||
// focus to the first focusable). Verify by checking activeElement is
|
||||
// contained.
|
||||
await expect.poll(async () => {
|
||||
return await page.evaluate(() => {
|
||||
const dlg = document.querySelector('[role="dialog"][aria-modal="true"]');
|
||||
return !!dlg && dlg.contains(document.activeElement);
|
||||
});
|
||||
}, { timeout: 2_000 }).toBe(true);
|
||||
|
||||
// Escape dismisses the lightbox.
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(lightbox).not.toBeVisible({ timeout: 2_000 });
|
||||
});
|
||||
});
|
||||
37
e2e/specs/09-mobile/sheet-escape.spec.ts
Normal file
37
e2e/specs/09-mobile/sheet-escape.spec.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Critical a11y fix — bottom sheets on /account (data-mode warning and
|
||||
* leave-confirm) now respond to Escape via the focusTrap action. They were
|
||||
* previously click-only, blocking keyboard / switch-control users.
|
||||
*/
|
||||
import { test, expect } from '../../fixtures/test';
|
||||
|
||||
test.describe('Mobile a11y — sheets dismiss on Escape', () => {
|
||||
test('data-mode warning sheet closes on Escape', async ({ page, guest, signIn }) => {
|
||||
const g = await guest('SheetEsc');
|
||||
await signIn(page, g);
|
||||
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 });
|
||||
await originalRadio.click();
|
||||
|
||||
const sheet = page.locator('[role="dialog"][aria-labelledby="data-mode-title"]');
|
||||
await expect(sheet).toBeVisible();
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(sheet).not.toBeVisible({ timeout: 2_000 });
|
||||
});
|
||||
|
||||
test('leave-confirm sheet (built on ConfirmSheet) closes on Escape', async ({ page, guest, signIn }) => {
|
||||
const g = await guest('LeaveEsc');
|
||||
await signIn(page, g);
|
||||
await page.goto('/account');
|
||||
|
||||
await page.getByRole('button', { name: /Event verlassen/i }).click();
|
||||
const sheet = page.getByTestId('confirm-sheet');
|
||||
await expect(sheet).toBeVisible();
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(sheet).not.toBeVisible({ timeout: 2_000 });
|
||||
});
|
||||
});
|
||||
42
e2e/specs/09-mobile/upload-cancel-confirm.spec.ts
Normal file
42
e2e/specs/09-mobile/upload-cancel-confirm.spec.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* UX fix — tapping X on the upload composer used to silently discard
|
||||
* staged files + caption. Now opens a ConfirmSheet so a mistap from the
|
||||
* corner is recoverable.
|
||||
*/
|
||||
import { test, expect } from '../../fixtures/test';
|
||||
|
||||
test.describe('Mobile — upload composer cancel confirmation', () => {
|
||||
test('typing a caption then tapping X opens the discard ConfirmSheet', async ({ page, guest, signIn }) => {
|
||||
const g = await guest('CancelConf');
|
||||
await signIn(page, g);
|
||||
|
||||
// Land on /upload directly (no staged files; the pending-upload-store is
|
||||
// empty). Typing into the caption flips the dirty flag.
|
||||
await page.goto('/upload');
|
||||
|
||||
const caption = page.getByTestId('upload-caption');
|
||||
await expect(caption).toBeVisible();
|
||||
await caption.fill('a meaningful caption that I do not want to lose');
|
||||
|
||||
// Tap the close (X) button in the composer header.
|
||||
await page.getByRole('button', { name: 'Abbrechen' }).click();
|
||||
|
||||
const sheet = page.getByTestId('confirm-sheet');
|
||||
await expect(sheet).toBeVisible();
|
||||
await expect(sheet).toContainText(/Verwerfen/);
|
||||
|
||||
// Cancel — sheet closes, caption is preserved.
|
||||
await page.getByTestId('confirm-sheet-cancel').click();
|
||||
await expect(sheet).not.toBeVisible();
|
||||
await expect(caption).toHaveValue(/a meaningful caption/);
|
||||
});
|
||||
|
||||
test('with no content, tapping X navigates directly to /feed', async ({ page, guest, signIn }) => {
|
||||
const g = await guest('CancelEmpty');
|
||||
await signIn(page, g);
|
||||
await page.goto('/upload');
|
||||
|
||||
await page.getByRole('button', { name: 'Abbrechen' }).click();
|
||||
await page.waitForURL('**/feed', { timeout: 3_000 });
|
||||
});
|
||||
});
|
||||
@@ -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 unprivileged `node` user (defense-in-depth). The
|
||||
# adapter-node server only reads from /app, so no chown is needed.
|
||||
USER node
|
||||
|
||||
EXPOSE 3001
|
||||
ENV PORT=3001 HOST=0.0.0.0
|
||||
CMD ["node", "build"]
|
||||
|
||||
@@ -1 +1,18 @@
|
||||
@import "./tailwind-theme.css";
|
||||
|
||||
/*
|
||||
* Respect the OS "reduce motion" setting (WCAG 2.3.3 / 2.2.2). Neutralizes the
|
||||
* decorative animations — Ken Burns zoom, slideshow crossfade, HeartBurst — and
|
||||
* snaps transitions, which is a vestibular/migraine safeguard especially for the
|
||||
* big-screen diashow. Auto-advance timing is additionally slowed in JS.
|
||||
*/
|
||||
@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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<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" />
|
||||
<!--
|
||||
|
||||
84
frontend/src/lib/actions/focus-trap.ts
Normal file
84
frontend/src/lib/actions/focus-trap.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
// Focus management for modals/sheets. On mount: focuses the first focusable
|
||||
// (or the node itself) and stores the previously-focused element. Tab/Shift+Tab
|
||||
// wrap inside the node. Escape calls `onclose` when set. On destroy: restores
|
||||
// focus to the originating element so screen-reader / keyboard users land back
|
||||
// where they were.
|
||||
|
||||
import type { ActionReturn } from 'svelte/action';
|
||||
|
||||
export interface FocusTrapOptions {
|
||||
onclose?: () => void;
|
||||
closeOnEscape?: boolean;
|
||||
/** When true, focus the first focusable on mount. Defaults true. */
|
||||
autoFocus?: boolean;
|
||||
}
|
||||
|
||||
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[] {
|
||||
return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
|
||||
(el) => !el.hasAttribute('disabled') && el.offsetParent !== null
|
||||
);
|
||||
}
|
||||
|
||||
export function focusTrap(
|
||||
node: HTMLElement,
|
||||
options: FocusTrapOptions = {}
|
||||
): ActionReturn<FocusTrapOptions> {
|
||||
let opts = options;
|
||||
const previouslyFocused = (typeof document !== 'undefined' ? document.activeElement : null) as HTMLElement | null;
|
||||
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape' && opts.closeOnEscape !== false && opts.onclose) {
|
||||
e.preventDefault();
|
||||
opts.onclose();
|
||||
return;
|
||||
}
|
||||
if (e.key !== 'Tab') return;
|
||||
const list = focusables(node);
|
||||
if (list.length === 0) {
|
||||
e.preventDefault();
|
||||
node.focus();
|
||||
return;
|
||||
}
|
||||
const first = list[0];
|
||||
const last = list[list.length - 1];
|
||||
const active = document.activeElement as HTMLElement | null;
|
||||
if (e.shiftKey) {
|
||||
if (active === first || !node.contains(active)) {
|
||||
e.preventDefault();
|
||||
last.focus();
|
||||
}
|
||||
} else {
|
||||
if (active === last) {
|
||||
e.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
node.addEventListener('keydown', onKeyDown);
|
||||
|
||||
if (opts.autoFocus !== false) {
|
||||
// Defer one frame so the element is fully laid out (sheets animate in).
|
||||
requestAnimationFrame(() => {
|
||||
const list = focusables(node);
|
||||
const target = list[0] ?? node;
|
||||
if (!node.hasAttribute('tabindex')) node.setAttribute('tabindex', '-1');
|
||||
target.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
update(newOptions) {
|
||||
opts = newOptions;
|
||||
},
|
||||
destroy() {
|
||||
node.removeEventListener('keydown', onKeyDown);
|
||||
if (previouslyFocused && typeof previouslyFocused.focus === 'function') {
|
||||
try { previouslyFocused.focus({ preventScroll: true }); } catch { /* element may have unmounted */ }
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
82
frontend/src/lib/actions/pull-to-refresh.ts
Normal file
82
frontend/src/lib/actions/pull-to-refresh.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
// Pull-to-refresh gesture. Only engages when the page is scrolled to the top.
|
||||
// Calls `onrefresh` once `threshold` px of overscroll have been pulled. The
|
||||
// element should set `overscroll-behavior-y: contain` so the browser doesn't
|
||||
// hijack the gesture (mobile Chrome's built-in refresh).
|
||||
//
|
||||
// `onpull` fires during the drag with `delta` (px pulled, clamped ≥ 0) and a
|
||||
// `progress` ratio (0–1+). Consumers can use it to render a growing indicator
|
||||
// that closes the visual loop before the refresh actually starts.
|
||||
|
||||
import type { ActionReturn } from 'svelte/action';
|
||||
|
||||
export interface PullToRefreshOptions {
|
||||
onrefresh: () => void | Promise<void>;
|
||||
onpull?: (delta: number, progress: number) => void;
|
||||
threshold?: number;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function pullToRefresh(
|
||||
node: HTMLElement,
|
||||
options: PullToRefreshOptions
|
||||
): ActionReturn<PullToRefreshOptions> {
|
||||
let opts = options;
|
||||
let startY = 0;
|
||||
let pulling = false;
|
||||
let triggered = false;
|
||||
|
||||
function scroller(): HTMLElement | (Window & typeof globalThis) {
|
||||
return node.scrollHeight > node.clientHeight ? node : window;
|
||||
}
|
||||
|
||||
function scrollTop(): number {
|
||||
const s = scroller();
|
||||
return s instanceof Window ? window.scrollY : s.scrollTop;
|
||||
}
|
||||
|
||||
function reportPull(delta: number) {
|
||||
if (!opts.onpull) return;
|
||||
const threshold = opts.threshold ?? 60;
|
||||
opts.onpull(Math.max(0, delta), Math.max(0, delta) / threshold);
|
||||
}
|
||||
|
||||
function onTouchStart(e: TouchEvent) {
|
||||
if (opts.disabled) return;
|
||||
if (scrollTop() > 0) return;
|
||||
startY = e.touches[0].clientY;
|
||||
pulling = true;
|
||||
triggered = false;
|
||||
}
|
||||
|
||||
function onTouchMove(e: TouchEvent) {
|
||||
if (!pulling || triggered) return;
|
||||
const delta = e.touches[0].clientY - startY;
|
||||
reportPull(delta);
|
||||
if (delta > (opts.threshold ?? 60)) {
|
||||
triggered = true;
|
||||
void opts.onrefresh();
|
||||
}
|
||||
}
|
||||
|
||||
function onTouchEnd() {
|
||||
if (pulling && !triggered) reportPull(0);
|
||||
pulling = false;
|
||||
}
|
||||
|
||||
node.addEventListener('touchstart', onTouchStart, { passive: true });
|
||||
node.addEventListener('touchmove', onTouchMove, { passive: true });
|
||||
node.addEventListener('touchend', onTouchEnd);
|
||||
node.addEventListener('touchcancel', onTouchEnd);
|
||||
|
||||
return {
|
||||
update(newOptions) {
|
||||
opts = newOptions;
|
||||
},
|
||||
destroy() {
|
||||
node.removeEventListener('touchstart', onTouchStart);
|
||||
node.removeEventListener('touchmove', onTouchMove);
|
||||
node.removeEventListener('touchend', onTouchEnd);
|
||||
node.removeEventListener('touchcancel', onTouchEnd);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { goto } from '$app/navigation';
|
||||
import { browser } from '$app/environment';
|
||||
import { getToken, clearAuth } from './auth';
|
||||
|
||||
const BASE = '/api/v1';
|
||||
@@ -42,6 +44,11 @@ async function request<T>(
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) {
|
||||
clearAuth();
|
||||
// Don't strand the user on a now-unauthenticated page with no nav —
|
||||
// send them to /join. Guard against loops on the auth screens.
|
||||
if (browser && !/^\/(join|recover|admin\/login)/.test(window.location.pathname)) {
|
||||
void goto('/join');
|
||||
}
|
||||
}
|
||||
throw new ApiError(res.status, data.error ?? 'unknown', data.message ?? 'Fehler');
|
||||
}
|
||||
|
||||
@@ -69,12 +69,28 @@ export function setAuth(jwt: string, pin: string | null, userId: string, display
|
||||
isAuthenticated.set(true);
|
||||
}
|
||||
|
||||
// Hook registry: cross-cutting stores (export-status, etc.) register a callback
|
||||
// here at import-time so they get reset on every clearAuth path — both the
|
||||
// explicit "Event verlassen" button and the api.ts 401 auto-clear. Keeps
|
||||
// clearAuth the single source of truth without baking dependencies on every
|
||||
// downstream store into this module (which would create circular imports).
|
||||
const clearAuthHooks: Array<() => void> = [];
|
||||
export function onClearAuth(fn: () => void): void {
|
||||
clearAuthHooks.push(fn);
|
||||
}
|
||||
|
||||
export function clearAuth(): void {
|
||||
if (!browser) return;
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem(USER_ID_KEY);
|
||||
// PIN is intentionally kept so the user can recover
|
||||
isAuthenticated.set(false);
|
||||
// Hooks fire in registration order. Keep them dependency-free of each other —
|
||||
// if you ever need ordering, introduce a priority field rather than relying
|
||||
// on import-load timing, which is fragile across refactors.
|
||||
for (const fn of clearAuthHooks) {
|
||||
try { fn(); } catch { /* hook failure is non-fatal */ }
|
||||
}
|
||||
}
|
||||
|
||||
export function getRole(): 'guest' | 'host' | 'admin' | null {
|
||||
|
||||
28
frontend/src/lib/avatar.ts
Normal file
28
frontend/src/lib/avatar.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
// Deterministic avatar palette + initials, used by feed cards and the account page.
|
||||
// Dark variants are baked in so the palette reads correctly on both themes.
|
||||
|
||||
const PALETTE = [
|
||||
'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-200',
|
||||
'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-200',
|
||||
'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-200',
|
||||
'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-200',
|
||||
'bg-rose-100 text-rose-700 dark:bg-rose-900/40 dark:text-rose-200',
|
||||
'bg-teal-100 text-teal-700 dark:bg-teal-900/40 dark:text-teal-200'
|
||||
];
|
||||
|
||||
const NEUTRAL = 'bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400';
|
||||
|
||||
export function avatarPalette(name: string | null | undefined): string {
|
||||
if (!name) return NEUTRAL;
|
||||
let hash = 0;
|
||||
for (const ch of name) hash = (hash * 31 + ch.charCodeAt(0)) & 0xff;
|
||||
return PALETTE[hash % PALETTE.length];
|
||||
}
|
||||
|
||||
export function initials(name: string | null | undefined): string {
|
||||
if (!name) return '?';
|
||||
const words = name.trim().split(/\s+/).filter(Boolean);
|
||||
if (words.length === 0) return '?';
|
||||
if (words.length === 1) return words[0][0].toUpperCase();
|
||||
return (words[0][0] + words[1][0]).toUpperCase();
|
||||
}
|
||||
@@ -1,16 +1,30 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { page } from '$app/stores';
|
||||
import { uploadSheetOpen, uploadBadgeCount } from '$lib/ui-store';
|
||||
import { exportStatus, initExportStatus } from '$lib/export-status-store';
|
||||
import { uploadsLocked } from '$lib/event-state-store';
|
||||
|
||||
function isActive(path: string): boolean {
|
||||
return $page.url.pathname.startsWith(path);
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
// Hydrate export status once when the bottom nav first mounts (i.e. the user
|
||||
// is authenticated). Subsequent SSE events update the snapshot live so the
|
||||
// Export tab can fade in mid-session.
|
||||
initExportStatus();
|
||||
});
|
||||
|
||||
let showExport = $derived($exportStatus.released);
|
||||
let zipReady = $derived($exportStatus.zip?.status === 'done');
|
||||
</script>
|
||||
|
||||
<!-- Bottom navigation bar — fixed, full-width, safe-area aware -->
|
||||
<nav
|
||||
class="fixed bottom-0 left-0 right-0 z-40 border-t border-gray-200 bg-white/90 backdrop-blur-md dark:border-gray-800 dark:bg-gray-900/90"
|
||||
style="padding-bottom: env(safe-area-inset-bottom)"
|
||||
data-testid="bottom-nav"
|
||||
>
|
||||
<div class="mx-auto flex h-14 max-w-2xl items-end justify-around px-4 pb-1">
|
||||
<!-- Feed tab -->
|
||||
@@ -30,8 +44,9 @@
|
||||
<div class="relative -translate-y-3">
|
||||
<button
|
||||
onclick={() => ($uploadSheetOpen = true)}
|
||||
class="relative flex h-14 w-14 items-center justify-center rounded-full bg-blue-600 text-white shadow-lg transition active:scale-95 hover:bg-blue-700"
|
||||
aria-label="Hochladen"
|
||||
disabled={$uploadsLocked}
|
||||
class="relative flex h-14 w-14 items-center justify-center rounded-full bg-blue-600 text-white shadow-lg transition active:scale-95 hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-blue-600 disabled:active:scale-100"
|
||||
aria-label={$uploadsLocked ? 'Uploads gesperrt' : 'Hochladen'}
|
||||
>
|
||||
<!-- Camera + plus icon -->
|
||||
<svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
||||
@@ -49,6 +64,25 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Export tab — appears only when the host has released the export. -->
|
||||
{#if showExport}
|
||||
<a
|
||||
href="/export"
|
||||
data-testid="bottom-nav-export"
|
||||
class="relative flex flex-col items-center gap-0.5 px-4 py-1 text-xs font-medium transition-colors
|
||||
{isActive('/export') ? 'text-blue-600 dark:text-blue-400' : 'text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300'}"
|
||||
aria-label="Export"
|
||||
>
|
||||
<svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3" />
|
||||
</svg>
|
||||
<span>Export</span>
|
||||
{#if zipReady}
|
||||
<span class="absolute right-2 top-0 h-2 w-2 rounded-full bg-blue-500" aria-hidden="true"></span>
|
||||
{/if}
|
||||
</a>
|
||||
{/if}
|
||||
|
||||
<!-- Account tab -->
|
||||
<a
|
||||
href="/account"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { vibrate } from '$lib/haptics';
|
||||
|
||||
interface Props {
|
||||
oncapture: (blob: Blob, type: 'photo' | 'video') => void;
|
||||
@@ -12,6 +13,7 @@
|
||||
let canvasEl: HTMLCanvasElement = $state()!;
|
||||
let stream: MediaStream | null = $state(null);
|
||||
let facingMode = $state<'environment' | 'user'>('environment');
|
||||
let mode = $state<'photo' | 'video'>('photo');
|
||||
let recording = $state(false);
|
||||
let recordingTime = $state(0);
|
||||
let error = $state<string | null>(null);
|
||||
@@ -19,6 +21,17 @@
|
||||
let recordedChunks: Blob[] = [];
|
||||
let recordingInterval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
function handleShutter() {
|
||||
vibrate(15);
|
||||
if (mode === 'photo') {
|
||||
capturePhoto();
|
||||
} else if (recording) {
|
||||
stopRecording();
|
||||
} else {
|
||||
startRecording();
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
startCamera();
|
||||
});
|
||||
@@ -172,44 +185,74 @@
|
||||
|
||||
<!-- Controls -->
|
||||
{#if !error}
|
||||
<div class="flex items-center justify-center gap-8 bg-black/80 px-4 py-6">
|
||||
<!-- Mode toggle — segmented control above the shutter. Hidden while recording. -->
|
||||
{#if !recording}
|
||||
<div class="flex justify-center bg-black/80 pt-3 pb-1">
|
||||
<div
|
||||
class="inline-flex rounded-full bg-white/10 p-0.5"
|
||||
role="tablist"
|
||||
aria-label="Aufnahmemodus"
|
||||
data-testid="camera-mode"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={mode === 'photo'}
|
||||
onclick={() => (mode = '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'}"
|
||||
>
|
||||
Foto
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={mode === 'video'}
|
||||
onclick={() => (mode = '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'}"
|
||||
>
|
||||
Video
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex items-center justify-center gap-8 bg-black/80 px-4 pt-4 pb-6" style="padding-bottom: calc(env(safe-area-inset-bottom) + 1.5rem)">
|
||||
<!-- Close -->
|
||||
<button
|
||||
onclick={onclose}
|
||||
class="flex h-12 w-12 items-center justify-center rounded-full bg-white/20 text-white"
|
||||
aria-label="Schliessen"
|
||||
class="flex h-12 w-12 items-center justify-center rounded-full bg-white/20 text-white transition active:bg-white/30"
|
||||
aria-label="Schließen"
|
||||
>
|
||||
<svg class="h-6 w-6" 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" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- Capture photo / record video -->
|
||||
{#if recording}
|
||||
<button
|
||||
onclick={stopRecording}
|
||||
class="flex h-16 w-16 items-center justify-center rounded-full border-4 border-white bg-red-600"
|
||||
aria-label="Aufnahme stoppen"
|
||||
>
|
||||
<div class="h-6 w-6 rounded-sm bg-white"></div>
|
||||
</button>
|
||||
{:else}
|
||||
<button
|
||||
onclick={capturePhoto}
|
||||
class="flex h-16 w-16 items-center justify-center rounded-full border-4 border-white bg-white/20 transition active:bg-white/40"
|
||||
aria-label="Foto aufnehmen"
|
||||
>
|
||||
<!-- Shutter — single button, behaviour depends on mode + recording state. -->
|
||||
<button
|
||||
onclick={handleShutter}
|
||||
data-testid="camera-shutter"
|
||||
class="flex h-16 w-16 items-center justify-center rounded-full border-4 border-white transition active:scale-95 {recording ? 'bg-red-600' : 'bg-white/20'}"
|
||||
aria-label={mode === 'photo' ? 'Foto aufnehmen' : recording ? 'Aufnahme stoppen' : 'Video aufnehmen'}
|
||||
>
|
||||
{#if mode === 'photo'}
|
||||
<div class="h-12 w-12 rounded-full bg-white"></div>
|
||||
</button>
|
||||
{/if}
|
||||
{:else if recording}
|
||||
<div class="h-6 w-6 rounded-sm bg-white"></div>
|
||||
{:else}
|
||||
<div class="h-10 w-10 rounded-full bg-red-500"></div>
|
||||
{/if}
|
||||
</button>
|
||||
|
||||
<!-- Toggle camera / start recording -->
|
||||
<!-- Toggle camera (hidden while recording to discourage interruption). -->
|
||||
{#if recording}
|
||||
<div class="h-12 w-12"></div>
|
||||
{:else}
|
||||
<button
|
||||
onclick={toggleCamera}
|
||||
class="flex h-12 w-12 items-center justify-center rounded-full bg-white/20 text-white"
|
||||
class="flex h-12 w-12 items-center justify-center rounded-full bg-white/20 text-white transition active:bg-white/30"
|
||||
aria-label="Kamera wechseln"
|
||||
>
|
||||
<svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
@@ -218,19 +261,6 @@
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Video record button -->
|
||||
{#if !recording}
|
||||
<div class="flex justify-center bg-black/80 pb-4">
|
||||
<button
|
||||
onclick={startRecording}
|
||||
class="flex items-center gap-2 rounded-full bg-red-600/80 px-4 py-2 text-sm text-white transition hover:bg-red-600"
|
||||
>
|
||||
<div class="h-2.5 w-2.5 rounded-full bg-white"></div>
|
||||
Video aufnehmen
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
|
||||
95
frontend/src/lib/components/ConfirmSheet.svelte
Normal file
95
frontend/src/lib/components/ConfirmSheet.svelte
Normal file
@@ -0,0 +1,95 @@
|
||||
<script lang="ts" module>
|
||||
// Per-instance id counter so two ConfirmSheets coexisting (e.g. one closing
|
||||
// as another opens) don't share the same aria-labelledby target and confuse AT.
|
||||
let nextId = 0;
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { focusTrap } from '$lib/actions/focus-trap';
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
title: string;
|
||||
message?: string;
|
||||
confirmLabel?: string;
|
||||
cancelLabel?: string;
|
||||
tone?: 'default' | 'danger';
|
||||
onConfirm: () => void | Promise<void>;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
let {
|
||||
open,
|
||||
title,
|
||||
message,
|
||||
confirmLabel = 'Bestätigen',
|
||||
cancelLabel = 'Abbrechen',
|
||||
tone = 'default',
|
||||
onConfirm,
|
||||
onCancel
|
||||
}: Props = $props();
|
||||
|
||||
const titleId = `confirm-sheet-title-${++nextId}`;
|
||||
let busy = $state(false);
|
||||
|
||||
async function handleConfirm() {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
await onConfirm();
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if open}
|
||||
<!-- Backdrop is a real <button> so keyboard / switch-control users get parity with the mouse path. -->
|
||||
<button
|
||||
type="button"
|
||||
class="fixed inset-0 z-50 bg-black/40"
|
||||
aria-label="Schließen"
|
||||
onclick={onCancel}
|
||||
tabindex="-1"
|
||||
></button>
|
||||
<div
|
||||
class="fixed inset-x-0 bottom-0 z-50 rounded-t-2xl bg-white px-5 pb-10 pt-6 dark:bg-gray-900"
|
||||
style="padding-bottom: calc(env(safe-area-inset-bottom) + 1.5rem)"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
data-testid="confirm-sheet"
|
||||
use:focusTrap={{ onclose: onCancel }}
|
||||
>
|
||||
<div class="mb-4 flex justify-center">
|
||||
<div class="h-1 w-10 rounded-full bg-gray-300 dark:bg-gray-600"></div>
|
||||
</div>
|
||||
<h3 id={titleId} class="mb-1 text-center text-lg font-bold text-gray-900 dark:text-gray-100">
|
||||
{title}
|
||||
</h3>
|
||||
{#if message}
|
||||
<p class="mb-6 text-center text-sm text-gray-500 dark:text-gray-400">{message}</p>
|
||||
{:else}
|
||||
<div class="mb-4"></div>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
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'
|
||||
? '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'}"
|
||||
>
|
||||
{confirmLabel}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={onCancel}
|
||||
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"
|
||||
>
|
||||
{cancelLabel}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -24,6 +24,48 @@
|
||||
|
||||
let { open, actions, onClose, title }: Props = $props();
|
||||
|
||||
let sheet = $state<HTMLDivElement | null>(null);
|
||||
let returnFocus: HTMLElement | null = null;
|
||||
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
onClose();
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
// Focus the first action and attach a global keydown listener only while open.
|
||||
// The sheet stays mounted (translate-y animation), so this is wired via $effect
|
||||
// rather than use:focusTrap (which would activate on first mount).
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
returnFocus = (document.activeElement as HTMLElement | null) ?? null;
|
||||
requestAnimationFrame(() => {
|
||||
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;
|
||||
}
|
||||
});
|
||||
|
||||
async function handle(action: ContextAction) {
|
||||
if (action.disabled) return;
|
||||
try {
|
||||
@@ -34,24 +76,28 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Backdrop -->
|
||||
<div
|
||||
<!-- 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-200"
|
||||
class:opacity-0={!open}
|
||||
class:pointer-events-none={!open}
|
||||
class:opacity-100={open}
|
||||
onclick={onClose}
|
||||
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-200 dark:bg-gray-900"
|
||||
class:translate-y-full={!open}
|
||||
class:translate-y-0={open}
|
||||
style="padding-bottom: env(safe-area-inset-bottom)"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
tabindex="-1"
|
||||
>
|
||||
<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>
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
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` : '';
|
||||
return $dataMode === 'original' ? (upload.original_url ?? '') : '';
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -67,7 +67,9 @@
|
||||
<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"
|
||||
class="pointer-events-auto -m-2 flex min-h-11 min-w-11 items-center justify-center gap-0.5 p-2"
|
||||
aria-pressed={upload.liked_by_me}
|
||||
aria-label="Gefällt mir ({upload.like_count})"
|
||||
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">
|
||||
@@ -76,7 +78,8 @@
|
||||
{upload.like_count}
|
||||
</button>
|
||||
<button
|
||||
class="pointer-events-auto flex items-center gap-0.5"
|
||||
class="pointer-events-auto -m-2 flex min-h-11 min-w-11 items-center justify-center gap-0.5 p-2"
|
||||
aria-label="Kommentare ({upload.comment_count})"
|
||||
onclick={(e) => { e.stopPropagation(); oncomment(upload.id); }}
|
||||
>
|
||||
<svg class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy } from 'svelte';
|
||||
import type { FeedUpload } from '$lib/types';
|
||||
import { dataMode, pickMediaUrl } from '$lib/data-mode-store';
|
||||
import { longpress } from '$lib/actions/longpress';
|
||||
import { doubletap } from '$lib/actions/doubletap';
|
||||
import { avatarPalette, initials } from '$lib/avatar';
|
||||
import { vibrate } from '$lib/haptics';
|
||||
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;
|
||||
@@ -39,28 +46,42 @@
|
||||
return `vor ${days} Tag${days === 1 ? '' : 'en'}`;
|
||||
}
|
||||
|
||||
function initial(name: string): string {
|
||||
return name[0]?.toUpperCase() ?? '?';
|
||||
}
|
||||
|
||||
// Deterministic color from name
|
||||
const COLORS = [
|
||||
'bg-blue-100 text-blue-700',
|
||||
'bg-purple-100 text-purple-700',
|
||||
'bg-green-100 text-green-700',
|
||||
'bg-amber-100 text-amber-700',
|
||||
'bg-rose-100 text-rose-700',
|
||||
'bg-teal-100 text-teal-700'
|
||||
];
|
||||
function avatarColor(name: string): string {
|
||||
let hash = 0;
|
||||
for (const ch of name) hash = (hash * 31 + ch.charCodeAt(0)) & 0xff;
|
||||
return COLORS[hash % COLORS.length];
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
function handleDoubleTap() {
|
||||
if (singleTapTimer) {
|
||||
clearTimeout(singleTapTimer);
|
||||
singleTapTimer = null;
|
||||
}
|
||||
heartBurst = true;
|
||||
vibrate(10);
|
||||
onlike(upload.id);
|
||||
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.
|
||||
onDestroy(() => {
|
||||
if (singleTapTimer) {
|
||||
clearTimeout(singleTapTimer);
|
||||
singleTapTimer = null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<article
|
||||
@@ -73,13 +94,13 @@
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<div
|
||||
class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-sm font-bold
|
||||
{avatarColor(upload.uploader_name)}"
|
||||
{avatarPalette(upload.uploader_name)}"
|
||||
>
|
||||
{initial(upload.uploader_name)}
|
||||
{initials(upload.uploader_name)}
|
||||
</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-500 dark:text-gray-400">{relativeTime(upload.created_at)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -88,7 +109,7 @@
|
||||
<button
|
||||
type="button"
|
||||
onclick={(e) => { e.stopPropagation(); openContext(); }}
|
||||
class="rounded-full p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
|
||||
class="rounded-full p-1 text-gray-400 hover:bg-gray-100 active:bg-gray-200 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:active:bg-gray-800 dark:hover:text-gray-200"
|
||||
aria-label="Mehr Aktionen"
|
||||
>
|
||||
<svg class="h-5 w-5" fill="currentColor" viewBox="0 0 24 24"><circle cx="5" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="19" cy="12" r="2"/></svg>
|
||||
@@ -98,12 +119,13 @@
|
||||
|
||||
<!-- Media -->
|
||||
<button
|
||||
class="block w-full"
|
||||
onclick={() => onselect(upload)}
|
||||
class="relative block w-full"
|
||||
onclick={handleMediaClick}
|
||||
use:doubletap
|
||||
ondoubletap={() => onlike(upload.id)}
|
||||
ondoubletap={handleDoubleTap}
|
||||
aria-label="Bild vergrößern"
|
||||
>
|
||||
<HeartBurst active={heartBurst} />
|
||||
{#if isVideo(upload.mime_type)}
|
||||
<div class="relative aspect-video w-full bg-gray-900">
|
||||
{#if upload.thumbnail_url || upload.preview_url}
|
||||
@@ -141,9 +163,11 @@
|
||||
<!-- Actions row -->
|
||||
<div class="flex items-center gap-4 px-4 py-2">
|
||||
<button
|
||||
onclick={() => onlike(upload.id)}
|
||||
onclick={() => { vibrate(10); onlike(upload.id); }}
|
||||
aria-pressed={upload.liked_by_me}
|
||||
aria-label="Gefällt mir ({upload.like_count})"
|
||||
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 dark:text-gray-400 dark:hover:text-red-400'}"
|
||||
{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'}"
|
||||
>
|
||||
<svg
|
||||
class="h-5 w-5 {upload.liked_by_me ? 'fill-red-500' : ''}"
|
||||
@@ -158,7 +182,7 @@
|
||||
</button>
|
||||
<button
|
||||
onclick={() => oncomment(upload.id)}
|
||||
class="flex items-center gap-1.5 text-sm font-medium text-gray-500 transition-colors hover:text-blue-500 dark:text-gray-400 dark:hover:text-blue-400"
|
||||
class="flex items-center gap-1.5 text-sm font-medium text-gray-500 transition-colors hover:text-blue-500 active:text-blue-500 dark:text-gray-400 dark:hover:text-blue-400 dark:active:text-blue-400"
|
||||
>
|
||||
<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="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" />
|
||||
@@ -166,7 +190,7 @@
|
||||
{upload.comment_count}
|
||||
</button>
|
||||
{#if isOwn}
|
||||
<span class="ml-auto text-xs text-gray-400 dark:text-gray-500">Eigener Beitrag</span>
|
||||
<span class="ml-auto text-xs text-gray-500 dark:text-gray-400">Eigener Beitrag</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
class="shrink-0 rounded-full px-3 py-1 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 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700'
|
||||
: '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'
|
||||
}"
|
||||
>
|
||||
Alle
|
||||
@@ -30,8 +30,8 @@
|
||||
onclick={() => onselect(h.tag)}
|
||||
class="shrink-0 rounded-full px-3 py-1 text-sm font-medium transition {
|
||||
selected === h.tag
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-gray-200 text-gray-700 hover:bg-gray-300'
|
||||
? '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'
|
||||
}"
|
||||
>
|
||||
#{h.tag}
|
||||
|
||||
32
frontend/src/lib/components/HeartBurst.svelte
Normal file
32
frontend/src/lib/components/HeartBurst.svelte
Normal file
@@ -0,0 +1,32 @@
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
active: boolean;
|
||||
}
|
||||
let { active }: Props = $props();
|
||||
</script>
|
||||
|
||||
<style>
|
||||
@keyframes heart-burst {
|
||||
0% { transform: scale(0.5); opacity: 0; }
|
||||
30% { transform: scale(1.2); opacity: 1; }
|
||||
70% { transform: scale(1); opacity: 1; }
|
||||
100% { transform: scale(1.4); opacity: 0; }
|
||||
}
|
||||
</style>
|
||||
|
||||
{#if active}
|
||||
<span
|
||||
class="pointer-events-none absolute inset-0 flex items-center justify-center"
|
||||
aria-hidden="true"
|
||||
data-testid="heart-burst"
|
||||
>
|
||||
<svg
|
||||
class="h-24 w-24 text-red-500 drop-shadow-lg"
|
||||
style="animation: heart-burst 700ms ease-out forwards;"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path d="M12 21s-7-4.534-9.5-9.034C.5 9.466 2.5 5 7 5c2.09 0 3.534 1.083 5 3 1.466-1.917 2.91-3 5-3 4.5 0 6.5 4.466 4.5 6.966C19 16.466 12 21 12 21z" />
|
||||
</svg>
|
||||
</span>
|
||||
{/if}
|
||||
@@ -4,6 +4,12 @@
|
||||
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 { toastError } from '$lib/toast-store';
|
||||
import { vibrate } from '$lib/haptics';
|
||||
import HeartBurst from './HeartBurst.svelte';
|
||||
|
||||
const COMMENT_MAX = 500;
|
||||
|
||||
interface CommentDto {
|
||||
id: string;
|
||||
@@ -32,6 +38,7 @@
|
||||
|
||||
function triggerHeartBurst() {
|
||||
heartBurst = true;
|
||||
vibrate(10);
|
||||
onlike(upload.id);
|
||||
setTimeout(() => (heartBurst = false), 700);
|
||||
}
|
||||
@@ -44,7 +51,7 @@
|
||||
try {
|
||||
comments = await api.get<CommentDto[]>(`/upload/${upload.id}/comments`);
|
||||
} catch {
|
||||
// Ignore
|
||||
// Background fetch — failure leaves the panel empty; reopening the lightbox retries.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,13 +59,13 @@
|
||||
if (!newComment.trim()) return;
|
||||
loading = true;
|
||||
try {
|
||||
const comment = await api.post<CommentDto>(`/upload/${upload.id}/comment`, {
|
||||
const comment = await api.post<CommentDto>(`/upload/${upload.id}/comments`, {
|
||||
body: newComment.trim()
|
||||
});
|
||||
comments = [...comments, comment];
|
||||
newComment = '';
|
||||
} catch {
|
||||
// Ignore
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
@@ -68,8 +75,8 @@
|
||||
try {
|
||||
await api.delete(`/comment/${id}`);
|
||||
comments = comments.filter((c) => c.id !== id);
|
||||
} catch {
|
||||
// Ignore
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,10 +84,6 @@
|
||||
return mime.startsWith('video/');
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') onclose();
|
||||
}
|
||||
|
||||
function formatTime(iso: string): string {
|
||||
return new Date(iso).toLocaleString('de-DE', {
|
||||
day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit'
|
||||
@@ -88,22 +91,21 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
@keyframes heart-burst {
|
||||
0% { transform: scale(0.5); opacity: 0; }
|
||||
30% { transform: scale(1.2); opacity: 1; }
|
||||
70% { transform: scale(1); opacity: 1; }
|
||||
100% { transform: scale(1.4); opacity: 0; }
|
||||
}
|
||||
</style>
|
||||
|
||||
<svelte:window onkeydown={handleKeydown} />
|
||||
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4" role="dialog">
|
||||
<div
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="lightbox-title"
|
||||
use:focusTrap={{ onclose }}
|
||||
>
|
||||
<div class="flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl bg-white dark:bg-gray-900">
|
||||
<!-- Media -->
|
||||
<div class="relative bg-black">
|
||||
<button onclick={onclose} class="absolute right-2 top-2 z-10 rounded-full bg-black/50 p-1.5 text-white hover:bg-black/70">
|
||||
<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"
|
||||
>
|
||||
<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" />
|
||||
</svg>
|
||||
@@ -117,33 +119,19 @@
|
||||
<video
|
||||
src={mediaSrc}
|
||||
controls
|
||||
class="max-h-[50vh] w-full object-contain"
|
||||
class="max-h-[60vh] w-full object-contain"
|
||||
poster={upload.thumbnail_url ?? undefined}
|
||||
></video>
|
||||
{:else}
|
||||
<img
|
||||
src={mediaSrc}
|
||||
alt=""
|
||||
class="max-h-[50vh] w-full object-contain select-none"
|
||||
class="max-h-[60vh] w-full object-contain select-none"
|
||||
draggable="false"
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if heartBurst}
|
||||
<span
|
||||
class="pointer-events-none absolute inset-0 flex items-center justify-center"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<svg
|
||||
class="h-24 w-24 text-red-500 drop-shadow-lg"
|
||||
style="animation: heart-burst 700ms ease-out forwards;"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path d="M12 21s-7-4.534-9.5-9.034C.5 9.466 2.5 5 7 5c2.09 0 3.534 1.083 5 3 1.466-1.917 2.91-3 5-3 4.5 0 6.5 4.466 4.5 6.966C19 16.466 12 21 12 21z" />
|
||||
</svg>
|
||||
</span>
|
||||
{/if}
|
||||
<HeartBurst active={heartBurst} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -152,11 +140,13 @@
|
||||
<div class="border-b border-gray-100 p-3 dark:border-gray-800">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{upload.uploader_name}</span>
|
||||
<span class="ml-2 text-xs text-gray-400 dark:text-gray-500">{formatTime(upload.created_at)}</span>
|
||||
<span id="lightbox-title" class="font-medium text-gray-900 dark:text-gray-100">{upload.uploader_name}</span>
|
||||
<span class="ml-2 text-xs text-gray-500 dark:text-gray-400">{formatTime(upload.created_at)}</span>
|
||||
</div>
|
||||
<button
|
||||
onclick={() => onlike(upload.id)}
|
||||
aria-pressed={upload.liked_by_me}
|
||||
aria-label="Gefällt mir ({upload.like_count})"
|
||||
class="flex items-center gap-1 rounded-full px-2.5 py-1 text-sm transition {
|
||||
upload.liked_by_me
|
||||
? 'bg-red-50 text-red-600 dark:bg-red-950/40 dark:text-red-300'
|
||||
@@ -177,7 +167,7 @@
|
||||
<!-- Comments list -->
|
||||
<div class="flex-1 overflow-y-auto p-3">
|
||||
{#if comments.length === 0}
|
||||
<p class="text-center text-sm text-gray-400 dark:text-gray-500">Noch keine Kommentare.</p>
|
||||
<p class="text-center text-sm text-gray-500 dark:text-gray-400">Noch keine Kommentare.</p>
|
||||
{:else}
|
||||
<div class="space-y-3">
|
||||
{#each comments as comment (comment.id)}
|
||||
@@ -185,7 +175,7 @@
|
||||
<div class="flex-1">
|
||||
<span class="text-sm font-medium text-gray-900 dark:text-gray-100">{comment.uploader_name}</span>
|
||||
<span class="ml-1 text-sm text-gray-700 dark:text-gray-300">{comment.body}</span>
|
||||
<div class="mt-0.5 text-xs text-gray-400 dark:text-gray-500">{formatTime(comment.created_at)}</div>
|
||||
<div class="mt-0.5 text-xs text-gray-500 dark:text-gray-400">{formatTime(comment.created_at)}</div>
|
||||
</div>
|
||||
{#if comment.user_id === userId}
|
||||
<button
|
||||
@@ -207,22 +197,36 @@
|
||||
<!-- Comment input -->
|
||||
<form
|
||||
onsubmit={(e) => { e.preventDefault(); submitComment(); }}
|
||||
class="flex gap-2 border-t border-gray-100 p-3 dark:border-gray-800"
|
||||
class="border-t border-gray-100 p-3 dark:border-gray-800"
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
bind:value={newComment}
|
||||
placeholder="Kommentar schreiben..."
|
||||
maxlength={500}
|
||||
class="flex-1 rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:outline-none dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100 dark:placeholder-gray-500"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !newComment.trim()}
|
||||
class="rounded-lg bg-blue-600 px-3 py-2 text-sm font-medium text-white transition hover:bg-blue-700 disabled:opacity-50 dark:bg-blue-500 dark:hover:bg-blue-400"
|
||||
<div class="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
bind:value={newComment}
|
||||
aria-label="Kommentar schreiben"
|
||||
placeholder="Kommentar schreiben..."
|
||||
maxlength={COMMENT_MAX}
|
||||
class="flex-1 rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:outline-none dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100 dark:placeholder-gray-500"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !newComment.trim()}
|
||||
class="rounded-lg bg-blue-600 px-3 py-2 text-sm font-medium text-white transition hover:bg-blue-700 active:bg-blue-700 disabled:opacity-50 dark:bg-blue-500 dark:hover:bg-blue-400 dark:active:bg-blue-400"
|
||||
>
|
||||
Senden
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
class="mt-1 text-right text-xs"
|
||||
class:text-gray-500={newComment.length < 450}
|
||||
class:dark:text-gray-400={newComment.length < 450}
|
||||
class:text-amber-600={newComment.length >= 450 && newComment.length < COMMENT_MAX}
|
||||
class:dark:text-amber-400={newComment.length >= 450 && newComment.length < COMMENT_MAX}
|
||||
class:text-red-600={newComment.length >= COMMENT_MAX}
|
||||
class:dark:text-red-400={newComment.length >= COMMENT_MAX}
|
||||
>
|
||||
Senden
|
||||
</button>
|
||||
{newComment.length}/{COMMENT_MAX}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
56
frontend/src/lib/components/Modal.svelte
Normal file
56
frontend/src/lib/components/Modal.svelte
Normal file
@@ -0,0 +1,56 @@
|
||||
<script lang="ts">
|
||||
import { focusTrap } from '$lib/actions/focus-trap';
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
// Accessible name is REQUIRED. Pass `titleId` when the dialog renders its own
|
||||
// visible heading (the common case — link aria-labelledby to that heading's id),
|
||||
// or `ariaLabel` for dialogs without a visible title (e.g. an image preview).
|
||||
// Failing to provide either leaves the dialog without an accessible name,
|
||||
// which screen readers announce as just "dialog" — useless. The runtime
|
||||
// warning below catches missed cases during dev.
|
||||
interface Props {
|
||||
open: boolean;
|
||||
titleId?: string;
|
||||
ariaLabel?: string;
|
||||
onClose: () => void;
|
||||
closeOnBackdrop?: boolean;
|
||||
children: Snippet;
|
||||
}
|
||||
|
||||
let {
|
||||
open,
|
||||
titleId,
|
||||
ariaLabel,
|
||||
onClose,
|
||||
closeOnBackdrop = true,
|
||||
children
|
||||
}: Props = $props();
|
||||
|
||||
$effect(() => {
|
||||
if (open && !titleId && !ariaLabel && typeof console !== 'undefined') {
|
||||
console.warn('<Modal> opened without titleId or ariaLabel — dialog has no accessible name.');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if open}
|
||||
<button
|
||||
type="button"
|
||||
class="fixed inset-0 z-50 bg-black/50"
|
||||
aria-label="Schließen"
|
||||
tabindex="-1"
|
||||
onclick={closeOnBackdrop ? onClose : () => {}}
|
||||
></button>
|
||||
<div
|
||||
class="pointer-events-none fixed inset-0 z-50 flex items-center justify-center p-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
aria-label={titleId ? undefined : ariaLabel}
|
||||
use:focusTrap={{ onclose: onClose }}
|
||||
>
|
||||
<div class="pointer-events-auto w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900">
|
||||
{@render children()}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -2,6 +2,8 @@
|
||||
import { browser } from '$app/environment';
|
||||
import { privacyNote } from '$lib/privacy-note-store';
|
||||
import { themePreference, type ThemePreference } from '$lib/theme-store';
|
||||
import { focusTrap } from '$lib/actions/focus-trap';
|
||||
import { vibrate } from '$lib/haptics';
|
||||
|
||||
const GUIDE_SEEN_KEY = 'eventsnap_guide_seen';
|
||||
|
||||
@@ -36,6 +38,12 @@
|
||||
title: 'Hashtags nutzen',
|
||||
body: 'Füge in deiner Bildunterschrift #hashtags ein, um Fotos zu gruppieren — z.B. #tanz, #buffet oder #reden. Du kannst danach filtern.'
|
||||
},
|
||||
{
|
||||
kind: 'text',
|
||||
icon: '👆',
|
||||
title: 'Lange tippen für mehr',
|
||||
body: 'Tippe lange auf ein Bild im Feed, um zusätzliche Aktionen zu öffnen — zum Beispiel das Original anzeigen oder eigene Beiträge löschen.'
|
||||
},
|
||||
{
|
||||
kind: 'theme',
|
||||
icon: '🌗',
|
||||
@@ -74,29 +82,49 @@
|
||||
|
||||
function dismiss() {
|
||||
if (browser) localStorage.setItem(GUIDE_SEEN_KEY, '1');
|
||||
vibrate([0, 8, 60, 8]);
|
||||
visible = false;
|
||||
}
|
||||
|
||||
function goToStep(i: number) {
|
||||
if (i >= 0 && i < steps.length) step = i;
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if visible}
|
||||
<!-- Backdrop -->
|
||||
<div class="fixed inset-0 z-50 flex items-end justify-center bg-black/60 sm:items-center">
|
||||
<div class="w-full max-w-sm rounded-t-3xl bg-white p-6 shadow-2xl dark:bg-gray-900 sm:rounded-2xl">
|
||||
<!-- Step indicator -->
|
||||
<div class="mb-5 flex justify-center gap-1.5">
|
||||
<div
|
||||
class="w-full max-w-sm rounded-t-3xl bg-white p-6 shadow-2xl dark:bg-gray-900 sm:rounded-2xl"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="onboarding-title"
|
||||
use:focusTrap={{ onclose: dismiss }}
|
||||
>
|
||||
<!-- 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. -->
|
||||
<div class="mb-3 flex justify-center">
|
||||
{#each steps as _, i}
|
||||
<div
|
||||
class="h-1.5 rounded-full transition-all {i === step
|
||||
? 'w-6 bg-blue-600 dark:bg-blue-500'
|
||||
: 'w-1.5 bg-gray-200 dark:bg-gray-700'}"
|
||||
></div>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => goToStep(i)}
|
||||
aria-label={`Schritt ${i + 1}`}
|
||||
aria-current={i === step ? 'step' : undefined}
|
||||
class="flex items-center justify-center p-2.5"
|
||||
>
|
||||
<span
|
||||
class="block rounded-full transition-all {i === step
|
||||
? 'h-1.5 w-6 bg-blue-600 dark:bg-blue-500'
|
||||
: 'h-1.5 w-1.5 bg-gray-200 dark:bg-gray-700'}"
|
||||
></span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="mb-6 text-center">
|
||||
<div class="mb-3 text-5xl">{currentStep.icon}</div>
|
||||
<h2 class="mb-2 text-xl font-bold text-gray-900 dark:text-gray-100">
|
||||
<h2 id="onboarding-title" class="mb-2 text-xl font-bold text-gray-900 dark:text-gray-100">
|
||||
{currentStep.title}
|
||||
</h2>
|
||||
|
||||
@@ -148,13 +176,13 @@
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
onclick={dismiss}
|
||||
class="flex-1 rounded-xl border border-gray-200 py-3 text-sm text-gray-500 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800"
|
||||
class="flex-1 rounded-xl border border-gray-200 py-3 text-sm text-gray-600 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"
|
||||
>
|
||||
Überspringen
|
||||
</button>
|
||||
<button
|
||||
onclick={next}
|
||||
class="flex-1 rounded-xl bg-blue-600 py-3 text-sm font-semibold text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400"
|
||||
class="flex-1 rounded-xl bg-blue-600 py-3 text-sm font-semibold text-white hover:bg-blue-700 active:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400 dark:active:bg-blue-400"
|
||||
>
|
||||
{step < steps.length - 1 ? 'Weiter' : 'Los geht\'s!'}
|
||||
</button>
|
||||
|
||||
27
frontend/src/lib/components/Skeleton.svelte
Normal file
27
frontend/src/lib/components/Skeleton.svelte
Normal file
@@ -0,0 +1,27 @@
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
variant?: 'card' | 'tile';
|
||||
}
|
||||
let { variant = 'card' }: Props = $props();
|
||||
</script>
|
||||
|
||||
{#if variant === 'card'}
|
||||
<article class="animate-pulse bg-white dark:bg-gray-900" aria-hidden="true">
|
||||
<div class="flex items-center gap-3 px-4 py-3">
|
||||
<div class="h-9 w-9 rounded-full bg-gray-200 dark:bg-gray-800"></div>
|
||||
<div class="flex-1 space-y-1.5">
|
||||
<div class="h-3 w-32 rounded bg-gray-200 dark:bg-gray-800"></div>
|
||||
<div class="h-2.5 w-20 rounded bg-gray-200 dark:bg-gray-800"></div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 4:5 matches the typical portrait card better than a square; reduces layout shift on first paint. -->
|
||||
<div class="aspect-[4/5] w-full bg-gray-200 dark:bg-gray-800"></div>
|
||||
<div class="flex gap-4 px-4 py-3">
|
||||
<div class="h-4 w-10 rounded bg-gray-200 dark:bg-gray-800"></div>
|
||||
<div class="h-4 w-10 rounded bg-gray-200 dark:bg-gray-800"></div>
|
||||
</div>
|
||||
<div class="border-b border-gray-100 dark:border-gray-800"></div>
|
||||
</article>
|
||||
{:else}
|
||||
<div class="aspect-square animate-pulse bg-gray-200 dark:bg-gray-800" aria-hidden="true"></div>
|
||||
{/if}
|
||||
37
frontend/src/lib/components/Toaster.svelte
Normal file
37
frontend/src/lib/components/Toaster.svelte
Normal file
@@ -0,0 +1,37 @@
|
||||
<script lang="ts">
|
||||
import { toasts, dismissToast, type Toast } from '$lib/toast-store';
|
||||
|
||||
function toneClasses(tone: Toast['tone']): string {
|
||||
switch (tone) {
|
||||
case 'success':
|
||||
return 'bg-green-600 text-white dark:bg-green-500';
|
||||
case 'warning':
|
||||
return 'bg-amber-500 text-white dark:bg-amber-400 dark:text-gray-900';
|
||||
case 'error':
|
||||
return 'bg-red-600 text-white dark:bg-red-500';
|
||||
default:
|
||||
return 'bg-gray-900 text-white dark:bg-gray-800';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div
|
||||
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)}
|
||||
<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)}"
|
||||
data-testid="toast"
|
||||
data-toast-tone={t.tone}
|
||||
>
|
||||
{t.message}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
@@ -7,6 +7,8 @@
|
||||
|
||||
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 +17,50 @@
|
||||
uploadSheetOpen.set(false);
|
||||
}
|
||||
|
||||
// Modal contract (mirrors ContextSheet): trap Tab within the sheet, close on
|
||||
// Escape, and restore focus on close. The sheet is permanently mounted (CSS
|
||||
// translate animation), so this is wired via $effect — and `inert`/`aria-hidden`
|
||||
// below keep its controls out of the tab order + AT tree while closed.
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
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(() => {
|
||||
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();
|
||||
}
|
||||
@@ -80,10 +126,17 @@
|
||||
|
||||
<!-- 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}
|
||||
class:pointer-events-none={!open}
|
||||
style="padding-bottom: env(safe-area-inset-bottom)"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Hochladen"
|
||||
tabindex="-1"
|
||||
inert={!open}
|
||||
>
|
||||
<!-- Drag handle -->
|
||||
<div class="flex justify-center pt-3 pb-1">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// 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 signed `original_url` from the media gateway.
|
||||
//
|
||||
// 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.
|
||||
@@ -40,17 +40,24 @@ if (browser) {
|
||||
* Build the URL for a feed upload given the current data mode and the URL variants
|
||||
* the backend returned. Centralised so every consumer (cards, lightbox, diashow)
|
||||
* follows the same fallback rule:
|
||||
* Original mode → original API route. Falls back to preview if no upload id is
|
||||
* available (defensive — shouldn't happen in practice).
|
||||
* Original mode → signed original URL, falling back to preview/thumbnail.
|
||||
* Saver mode → preview URL (compressed), falling back to thumbnail and then
|
||||
* original.
|
||||
* the signed original.
|
||||
*
|
||||
* All URLs are minted (and signed) by the backend; the client never constructs
|
||||
* a media path itself.
|
||||
*/
|
||||
export function pickMediaUrl(
|
||||
mode: DataMode,
|
||||
upload: { id: string; preview_url: string | null; thumbnail_url: string | null }
|
||||
upload: {
|
||||
id: string;
|
||||
preview_url: string | null;
|
||||
thumbnail_url: string | null;
|
||||
original_url: string | null;
|
||||
}
|
||||
): string {
|
||||
if (mode === 'original') {
|
||||
return `/api/v1/upload/${upload.id}/original`;
|
||||
return upload.original_url ?? upload.preview_url ?? upload.thumbnail_url ?? '';
|
||||
}
|
||||
return upload.preview_url ?? upload.thumbnail_url ?? `/api/v1/upload/${upload.id}/original`;
|
||||
return upload.preview_url ?? upload.thumbnail_url ?? upload.original_url ?? '';
|
||||
}
|
||||
|
||||
10
frontend/src/lib/event-state-store.ts
Normal file
10
frontend/src/lib/event-state-store.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
// Shared, reactive event state pushed from the backend.
|
||||
//
|
||||
// `uploadsLocked` is seeded from `/me/context` on boot and kept live by the
|
||||
// `event-closed` / `event-opened` SSE events (wired in the root layout). Pages
|
||||
// read it to show an "Uploads gesperrt" banner and disable the upload FAB, so a
|
||||
// locked event stops inviting uploads that would only fail server-side.
|
||||
|
||||
import { writable } from 'svelte/store';
|
||||
|
||||
export const uploadsLocked = writable<boolean>(false);
|
||||
62
frontend/src/lib/export-status-store.ts
Normal file
62
frontend/src/lib/export-status-store.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
// Single source of truth for "is export released and is the ZIP ready?". Used
|
||||
// by the BottomNav to surface the Export tab on demand, and by the export
|
||||
// page to render status. Hydrates lazily on first subscribe; reacts to the
|
||||
// `export-progress` / `export-available` SSE events so the nav updates live.
|
||||
|
||||
import { writable } from 'svelte/store';
|
||||
import { api } from './api';
|
||||
import { onSseEvent } from './sse';
|
||||
import { getToken, onClearAuth } from './auth';
|
||||
|
||||
export interface ExportJob {
|
||||
status: 'locked' | 'pending' | 'running' | 'done' | 'failed';
|
||||
progress_pct: number;
|
||||
}
|
||||
|
||||
export interface ExportStatusSnapshot {
|
||||
released: boolean;
|
||||
zip: ExportJob | null;
|
||||
html: ExportJob | null;
|
||||
}
|
||||
|
||||
const empty: ExportStatusSnapshot = { released: false, zip: null, html: null };
|
||||
|
||||
export const exportStatus = writable<ExportStatusSnapshot>(empty);
|
||||
|
||||
let hydrated = false;
|
||||
let sseUnsubs: Array<() => void> = [];
|
||||
|
||||
export async function refreshExportStatus(): Promise<void> {
|
||||
if (!getToken()) return;
|
||||
try {
|
||||
const data = await api.get<ExportStatusSnapshot>('/export/status');
|
||||
exportStatus.set(data);
|
||||
} catch {
|
||||
// /export/status can 403 for guests on locked events; that's expected.
|
||||
exportStatus.set(empty);
|
||||
}
|
||||
}
|
||||
|
||||
export function initExportStatus(): void {
|
||||
if (hydrated) return;
|
||||
hydrated = true;
|
||||
void refreshExportStatus();
|
||||
sseUnsubs.push(onSseEvent('export-progress', () => { void refreshExportStatus(); }));
|
||||
sseUnsubs.push(onSseEvent('export-available', () => { void refreshExportStatus(); }));
|
||||
}
|
||||
|
||||
export function teardownExportStatus(): void {
|
||||
for (const u of sseUnsubs) u();
|
||||
sseUnsubs = [];
|
||||
hydrated = false;
|
||||
exportStatus.set(empty);
|
||||
}
|
||||
|
||||
// Auto-reset on every clearAuth path (explicit logout + api.ts 401 auto-clear).
|
||||
// Imported for side-effect by anyone who pulls in this module — the BottomNav
|
||||
// does that statically, and BottomNav itself is statically imported by
|
||||
// +layout.svelte, so this side-effect runs at app boot, well before any API
|
||||
// call can 401. If a future refactor lazy-loads the BottomNav (dynamic import,
|
||||
// route-level code-split), move the side-effect to +layout.svelte's onMount
|
||||
// so the hook isn't gated on a conditional component.
|
||||
onClearAuth(teardownExportStatus);
|
||||
7
frontend/src/lib/haptics.ts
Normal file
7
frontend/src/lib/haptics.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
// Mobile haptic ticks. No-ops on browsers without navigator.vibrate (iOS Safari).
|
||||
|
||||
export function vibrate(pattern: number | number[]): void {
|
||||
if (typeof navigator === 'undefined') return;
|
||||
if (typeof navigator.vibrate !== 'function') return;
|
||||
try { navigator.vibrate(pattern); } catch { /* permission denied / not supported */ }
|
||||
}
|
||||
@@ -38,6 +38,7 @@ const KNOWN_EVENTS = [
|
||||
'upload-deleted',
|
||||
'like-update',
|
||||
'new-comment',
|
||||
'user-banned',
|
||||
'event-closed',
|
||||
'event-opened',
|
||||
'event-updated',
|
||||
@@ -50,7 +51,18 @@ const KNOWN_EVENTS = [
|
||||
* Synthetic event types — not emitted by the server, dispatched locally to fan out
|
||||
* cross-cutting state changes (e.g. delta-fetch results after a reconnect).
|
||||
*/
|
||||
export type SyntheticEvent = 'feed-delta';
|
||||
export type SyntheticEvent = 'feed-delta' | 'feed-reload';
|
||||
|
||||
/**
|
||||
* Advance the reconnect cursor using a **server** timestamp (an upload's
|
||||
* `created_at`), never the client clock. A phone clock skewed ahead would
|
||||
* otherwise make the cursor jump past events that happened while the tab was
|
||||
* backgrounded. ISO-8601 UTC strings compare correctly lexicographically.
|
||||
*/
|
||||
function noteServerTime(ts: string | null | undefined): void {
|
||||
if (!ts) return;
|
||||
if (!lastEventTime || ts > lastEventTime) lastEventTime = ts;
|
||||
}
|
||||
|
||||
export function onSseEvent(eventType: string, handler: EventHandler): () => void {
|
||||
if (!handlers.has(eventType)) {
|
||||
@@ -93,12 +105,13 @@ export function connectSse(): void {
|
||||
eventSource.onopen = () => {
|
||||
// Successful connection — reset the backoff counter.
|
||||
reconnectAttempt = 0;
|
||||
// If we have a previous timestamp this is a reconnect — fetch the gap.
|
||||
// If we have a previous (server-derived) timestamp this is a reconnect
|
||||
// — fetch the gap. The cursor is only ever advanced from server
|
||||
// timestamps (noteServerTime), so client clock skew can't drop events.
|
||||
const since = lastEventTime;
|
||||
if (since) {
|
||||
void deltaFetchAndFan(since);
|
||||
}
|
||||
lastEventTime = new Date().toISOString();
|
||||
};
|
||||
|
||||
for (const eventName of KNOWN_EVENTS) {
|
||||
@@ -146,7 +159,15 @@ export function setLastEventTime(time: string): void {
|
||||
}
|
||||
|
||||
function dispatch(eventType: string, data: string): void {
|
||||
lastEventTime = new Date().toISOString();
|
||||
// Advance the cursor from the server timestamp carried by a new upload.
|
||||
// Other event types don't carry one and must not bump it off the client clock.
|
||||
if (eventType === 'new-upload') {
|
||||
try {
|
||||
noteServerTime((JSON.parse(data) as { created_at?: string }).created_at);
|
||||
} catch {
|
||||
// payload not JSON — ignore
|
||||
}
|
||||
}
|
||||
const list = handlers.get(eventType);
|
||||
if (list) {
|
||||
for (const handler of list) {
|
||||
@@ -166,6 +187,14 @@ async function deltaFetchAndFan(since: string): Promise<void> {
|
||||
const response = await api.get<DeltaResponse>(
|
||||
`/feed/delta?since=${encodeURIComponent(since)}`
|
||||
);
|
||||
// Advance the cursor from the newest server timestamp in the delta.
|
||||
for (const u of response.uploads) noteServerTime(u.created_at);
|
||||
// The server clamped the window or hit the row cap — the partial delta
|
||||
// can't be trusted, so ask the page to do a full reload instead.
|
||||
if (response.reload_required) {
|
||||
dispatch('feed-reload', '{}');
|
||||
return;
|
||||
}
|
||||
dispatch('feed-delta', JSON.stringify(response));
|
||||
} catch {
|
||||
// non-fatal
|
||||
|
||||
40
frontend/src/lib/toast-store.ts
Normal file
40
frontend/src/lib/toast-store.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { writable } from 'svelte/store';
|
||||
import { ApiError } from './api';
|
||||
|
||||
export type ToastTone = 'info' | 'success' | 'warning' | 'error';
|
||||
|
||||
export interface Toast {
|
||||
id: number;
|
||||
message: string;
|
||||
tone: ToastTone;
|
||||
ttl: number;
|
||||
}
|
||||
|
||||
let nextId = 0;
|
||||
const timers = new Map<number, ReturnType<typeof setTimeout>>();
|
||||
|
||||
export const toasts = writable<Toast[]>([]);
|
||||
|
||||
export function toast(message: string, tone: ToastTone = 'info', ttl = 4000): number {
|
||||
const id = ++nextId;
|
||||
const entry: Toast = { id, message, tone, ttl };
|
||||
toasts.update((list) => [...list, entry]);
|
||||
if (ttl > 0 && typeof window !== 'undefined') {
|
||||
timers.set(id, setTimeout(() => dismissToast(id), ttl));
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
export function dismissToast(id: number): void {
|
||||
const t = timers.get(id);
|
||||
if (t) { clearTimeout(t); timers.delete(id); }
|
||||
toasts.update((list) => list.filter((x) => x.id !== id));
|
||||
}
|
||||
|
||||
// User-action error surface. Pulls the German message off ApiError; for
|
||||
// anything else, falls back to a generic line so the user sees *something*.
|
||||
export function toastError(err: unknown, fallback = 'Etwas ist schiefgelaufen.'): number {
|
||||
if (err instanceof ApiError) return toast(err.message || fallback, 'error', 5000);
|
||||
if (err instanceof Error && err.message) return toast(err.message, 'error', 5000);
|
||||
return toast(fallback, 'error', 5000);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export interface FeedUpload {
|
||||
uploader_name: string;
|
||||
preview_url: string | null;
|
||||
thumbnail_url: string | null;
|
||||
original_url: string | null;
|
||||
mime_type: string;
|
||||
caption: string | null;
|
||||
like_count: number;
|
||||
@@ -27,6 +28,7 @@ export interface FeedResponse {
|
||||
export interface DeltaResponse {
|
||||
uploads: FeedUpload[];
|
||||
deleted_ids: string[];
|
||||
reload_required: boolean;
|
||||
}
|
||||
|
||||
// mirrors backend/src/handlers/feed.rs::HashtagCount
|
||||
@@ -53,6 +55,7 @@ export interface MeContextDto {
|
||||
privacy_note: string;
|
||||
quota_enabled: boolean;
|
||||
storage_quota_enabled: boolean;
|
||||
uploads_locked: boolean;
|
||||
}
|
||||
|
||||
// mirrors backend/src/handlers/host.rs::PinResetResponse
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
<script lang="ts">
|
||||
import favicon from '$lib/assets/favicon.svg';
|
||||
import '../app.css';
|
||||
import { initAuth, getToken, getUserId, clearPin } from '$lib/auth';
|
||||
import { initAuth, getToken, getUserId, clearPin, clearAuth } from '$lib/auth';
|
||||
import { initTheme } from '$lib/theme-store';
|
||||
import { goto } from '$app/navigation';
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import BottomNav from '$lib/components/BottomNav.svelte';
|
||||
import UploadSheet from '$lib/components/UploadSheet.svelte';
|
||||
import Toaster from '$lib/components/Toaster.svelte';
|
||||
import { showBottomNav } from '$lib/ui-store';
|
||||
import { isAuthenticated } from '$lib/auth';
|
||||
import { queueItems, isProcessing } from '$lib/upload-queue';
|
||||
@@ -13,12 +15,28 @@
|
||||
import { refreshQuota } from '$lib/quota-store';
|
||||
import { onSseEvent } from '$lib/sse';
|
||||
import { api } from '$lib/api';
|
||||
import { toast } from '$lib/toast-store';
|
||||
import { uploadsLocked } from '$lib/event-state-store';
|
||||
import type { MeContextDto } from '$lib/types';
|
||||
|
||||
let { children } = $props();
|
||||
|
||||
let unsubs: Array<() => void> = [];
|
||||
|
||||
// H12: surface upload failures. The queue marks failed items 'error' in
|
||||
// IndexedDB but nothing rendered them, so a banned/locked/over-quota guest saw
|
||||
// the composer close to a normal feed and assumed success. Toast each item the
|
||||
// first time it transitions to 'error'.
|
||||
let toastedErrors = new Set<string>();
|
||||
$effect(() => {
|
||||
for (const item of $queueItems) {
|
||||
if (item.status === 'error' && !toastedErrors.has(item.id)) {
|
||||
toastedErrors.add(item.id);
|
||||
toast(item.error ?? 'Upload fehlgeschlagen.', 'error');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Slim progress bar: ratio of completed items to total, shown while processing.
|
||||
let progressPct = $derived.by(() => {
|
||||
const total = $queueItems.length;
|
||||
@@ -38,8 +56,10 @@
|
||||
try {
|
||||
const ctx = await api.get<MeContextDto>('/me/context');
|
||||
privacyNote.set(ctx.privacy_note);
|
||||
uploadsLocked.set(ctx.uploads_locked);
|
||||
} catch {
|
||||
// non-fatal; users without a session land on /join anyway
|
||||
// Cross-cutting hydration on boot — failure is non-fatal; users without
|
||||
// a session land on /join anyway, and the per-page mount will retry.
|
||||
}
|
||||
void refreshQuota();
|
||||
}
|
||||
@@ -49,14 +69,36 @@
|
||||
// `currentPin` store carries the change into any page that reads it (My
|
||||
// Account in particular).
|
||||
unsubs.push(
|
||||
// Server contract: `data` is a JSON string of the shape `{ user_id: UUID }`.
|
||||
// We clear the cached PIN only for our own user; admin resets for other guests
|
||||
// arrive on the same channel but aren't ours to act on.
|
||||
onSseEvent('pin-reset', (data) => {
|
||||
try {
|
||||
const payload = JSON.parse(data) as { user_id: string };
|
||||
if (payload.user_id === getUserId()) clearPin();
|
||||
} catch {
|
||||
// ignore malformed payload
|
||||
// Malformed payload — discard; nothing actionable for the user.
|
||||
}
|
||||
})
|
||||
}),
|
||||
// M11: a host banned someone. If it's us, the session has already been
|
||||
// revoked server-side — drop local auth and send us to /join so the UI
|
||||
// doesn't keep pretending we're signed in.
|
||||
onSseEvent('user-banned', (data) => {
|
||||
try {
|
||||
const payload = JSON.parse(data) as { user_id: string };
|
||||
if (payload.user_id === getUserId()) {
|
||||
clearAuth();
|
||||
toast('Du wurdest vom Event entfernt.', 'error');
|
||||
void goto('/join');
|
||||
}
|
||||
} catch {
|
||||
/* malformed — ignore */
|
||||
}
|
||||
}),
|
||||
// M11: reflect event lock state live so the feed/upload pages can toggle
|
||||
// their "Uploads gesperrt" banner and disable the FAB.
|
||||
onSseEvent('event-closed', () => uploadsLocked.set(true)),
|
||||
onSseEvent('event-opened', () => uploadsLocked.set(false))
|
||||
);
|
||||
});
|
||||
|
||||
@@ -90,3 +132,5 @@
|
||||
{#if $showBottomNav && $isAuthenticated}
|
||||
<BottomNav />
|
||||
{/if}
|
||||
|
||||
<Toaster />
|
||||
|
||||
@@ -9,6 +9,10 @@
|
||||
import { privacyNote } from '$lib/privacy-note-store';
|
||||
import { quotaStore, refreshQuota } from '$lib/quota-store';
|
||||
import { onSseEvent } from '$lib/sse';
|
||||
import { focusTrap } from '$lib/actions/focus-trap';
|
||||
import { avatarPalette, initials } from '$lib/avatar';
|
||||
import ConfirmSheet from '$lib/components/ConfirmSheet.svelte';
|
||||
import { vibrate } from '$lib/haptics';
|
||||
import type { MeContextDto } from '$lib/types';
|
||||
|
||||
let displayName = $state<string | null>(null);
|
||||
@@ -91,15 +95,20 @@
|
||||
if (!value) return;
|
||||
navigator.clipboard.writeText(value);
|
||||
pinCopied = true;
|
||||
vibrate([0, 8, 60, 8]);
|
||||
setTimeout(() => (pinCopied = false), 2000);
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
try { await api.delete('/session'); } catch { /* ignore */ }
|
||||
// Session-delete is best-effort: the JWT is going away on this device either way,
|
||||
// so a network failure shouldn't block the user from leaving the event.
|
||||
try { await api.delete('/session'); } catch { /* best-effort logout */ }
|
||||
// Wipe the IndexedDB upload queue so a second guest using the same device can't
|
||||
// inherit (or be blamed for) this guest's pending uploads. Not done on a 401
|
||||
// auto-clear — that path preserves the queue in case the user re-authenticates.
|
||||
try { await clearQueue(); } catch { /* ignore */ }
|
||||
try { await clearQueue(); } catch { /* best-effort cleanup */ }
|
||||
// Note: export-status teardown is wired via the onClearAuth hook in
|
||||
// export-status-store, so it runs for both this explicit path and api.ts's 401.
|
||||
clearAuth();
|
||||
goto('/join');
|
||||
}
|
||||
@@ -124,13 +133,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
function avatarColor(name: string | null): string {
|
||||
if (!name) return 'bg-gray-100 text-gray-500';
|
||||
const COLORS = ['bg-blue-100 text-blue-700','bg-purple-100 text-purple-700','bg-green-100 text-green-700','bg-amber-100 text-amber-700','bg-rose-100 text-rose-700'];
|
||||
let hash = 0;
|
||||
for (const ch of name) hash = (hash * 31 + ch.charCodeAt(0)) & 0xff;
|
||||
return COLORS[hash % COLORS.length];
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="min-h-screen bg-gray-50 pb-24 dark:bg-gray-950">
|
||||
@@ -147,9 +149,9 @@
|
||||
<div class="flex items-center gap-4">
|
||||
<div
|
||||
class="flex h-14 w-14 shrink-0 items-center justify-center rounded-full text-xl font-bold
|
||||
{avatarColor(displayName)}"
|
||||
{avatarPalette(displayName)}"
|
||||
>
|
||||
{displayName ? displayName[0].toUpperCase() : '?'}
|
||||
{initials(displayName)}
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<p class="truncate text-lg font-bold text-gray-900 dark:text-gray-100">{displayName ?? 'Unbekannt'}</p>
|
||||
@@ -159,7 +161,7 @@
|
||||
</div>
|
||||
</div>
|
||||
{#if expiry}
|
||||
<p class="mt-3 text-xs text-gray-400 dark:text-gray-500">Sitzung gültig bis {formatDate(expiry)}</p>
|
||||
<p class="mt-3 text-xs text-gray-500 dark:text-gray-400">Sitzung gültig bis {formatDate(expiry)}</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -217,7 +219,7 @@
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="rounded-lg bg-white px-4 py-3 text-sm text-gray-400 shadow-sm dark:bg-gray-900 dark:text-gray-500">
|
||||
<div class="rounded-lg bg-white px-4 py-3 text-sm text-gray-500 shadow-sm dark:bg-gray-900 dark:text-gray-400">
|
||||
PIN nicht gespeichert. Nutze die Wiederherstellungs-Seite, um dich mit deinem PIN anzumelden.
|
||||
</div>
|
||||
{/if}
|
||||
@@ -332,7 +334,7 @@
|
||||
style="width: {quotaPercent}%"
|
||||
></div>
|
||||
</div>
|
||||
<p class="mt-2 text-xs text-gray-400 dark:text-gray-500">
|
||||
<p class="mt-2 text-xs text-gray-500 dark:text-gray-400">
|
||||
Geschätzt für {$quotaStore.active_uploaders} aktive Beitragende.
|
||||
</p>
|
||||
</div>
|
||||
@@ -359,7 +361,7 @@
|
||||
href="/recover"
|
||||
class="flex items-center gap-3 px-5 py-4 transition hover:bg-gray-50 dark:hover:bg-gray-700/50"
|
||||
>
|
||||
<svg class="h-5 w-5 text-gray-400 dark:text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
||||
<svg class="h-5 w-5 text-gray-500 dark:text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M10.5 1.5H8.25A2.25 2.25 0 006 3.75v16.5a2.25 2.25 0 002.25 2.25h7.5A2.25 2.25 0 0018 20.25V3.75a2.25 2.25 0 00-2.25-2.25H13.5m-3 0V3h3V1.5m-3 0h3m-3 8.25h3m-3 3h3m-3 3h3" />
|
||||
</svg>
|
||||
<span class="flex-1 text-sm font-medium text-gray-700 dark:text-gray-300">Gerät wechseln / PIN nutzen</span>
|
||||
@@ -384,68 +386,50 @@
|
||||
|
||||
<!-- Data-mode warning bottom sheet — shown once when the user picks Original. -->
|
||||
{#if dataModeWarningOpen}
|
||||
<div class="fixed inset-0 z-50 flex items-end bg-black/40" onclick={() => (dataModeWarningOpen = false)}>
|
||||
<div
|
||||
class="w-full rounded-t-2xl bg-white px-5 pb-10 pt-6 dark:bg-gray-900"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
onkeydown={(e) => e.stopPropagation()}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div class="mb-4 flex justify-center">
|
||||
<div class="h-1 w-10 rounded-full bg-gray-300 dark:bg-gray-600"></div>
|
||||
</div>
|
||||
<h3 class="mb-1 text-center text-lg font-bold text-gray-900 dark:text-gray-100">Original-Dateien laden?</h3>
|
||||
<p class="mb-6 text-center text-sm text-gray-500 dark:text-gray-400">
|
||||
Original-Dateien können deutlich mehr Datenvolumen verbrauchen. Am besten im WLAN aktivieren.
|
||||
</p>
|
||||
<button
|
||||
onclick={confirmOriginalMode}
|
||||
class="mb-3 w-full rounded-xl bg-blue-600 py-3 text-sm font-semibold text-white transition hover:bg-blue-700"
|
||||
>
|
||||
Aktivieren
|
||||
</button>
|
||||
<button
|
||||
onclick={() => (dataModeWarningOpen = false)}
|
||||
class="w-full rounded-xl border border-gray-200 py-3 text-sm font-medium text-gray-700 transition hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="fixed inset-0 z-50 bg-black/40"
|
||||
aria-label="Schließen"
|
||||
tabindex="-1"
|
||||
onclick={() => (dataModeWarningOpen = false)}
|
||||
></button>
|
||||
<div
|
||||
class="fixed inset-x-0 bottom-0 z-50 rounded-t-2xl bg-white px-5 pt-6 dark:bg-gray-900"
|
||||
style="padding-bottom: calc(env(safe-area-inset-bottom) + 1.5rem)"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="data-mode-title"
|
||||
use:focusTrap={{ onclose: () => (dataModeWarningOpen = false) }}
|
||||
>
|
||||
<div class="mb-4 flex justify-center">
|
||||
<div class="h-1 w-10 rounded-full bg-gray-300 dark:bg-gray-600"></div>
|
||||
</div>
|
||||
<h3 id="data-mode-title" class="mb-1 text-center text-lg font-bold text-gray-900 dark:text-gray-100">Original-Dateien laden?</h3>
|
||||
<p class="mb-6 text-center text-sm text-gray-500 dark:text-gray-400">
|
||||
Original-Dateien können deutlich mehr Datenvolumen verbrauchen. Am besten im WLAN aktivieren.
|
||||
</p>
|
||||
<button
|
||||
onclick={confirmOriginalMode}
|
||||
class="mb-3 w-full rounded-xl bg-blue-600 py-3 text-sm font-semibold text-white transition hover:bg-blue-700 active:bg-blue-700"
|
||||
>
|
||||
Aktivieren
|
||||
</button>
|
||||
<button
|
||||
onclick={() => (dataModeWarningOpen = false)}
|
||||
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"
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Leave-confirm bottom sheet -->
|
||||
{#if leaveConfirmOpen}
|
||||
<div class="fixed inset-0 z-50 flex items-end bg-black/40" onclick={() => (leaveConfirmOpen = false)}>
|
||||
<div
|
||||
class="w-full rounded-t-2xl bg-white px-5 pb-10 pt-6 dark:bg-gray-900"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
onkeydown={(e) => e.stopPropagation()}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div class="mb-4 flex justify-center">
|
||||
<div class="h-1 w-10 rounded-full bg-gray-300 dark:bg-gray-600"></div>
|
||||
</div>
|
||||
<h3 class="mb-1 text-center text-lg font-bold text-gray-900 dark:text-gray-100">Event verlassen?</h3>
|
||||
<p class="mb-6 text-center text-sm text-gray-500 dark:text-gray-400">
|
||||
Du wirst abgemeldet. Mit deinem PIN kannst du jederzeit zurückkehren.
|
||||
</p>
|
||||
<button
|
||||
onclick={handleLogout}
|
||||
class="mb-3 w-full rounded-xl bg-red-600 py-3 text-sm font-semibold text-white transition hover:bg-red-700 dark:bg-red-500 dark:hover:bg-red-400"
|
||||
>
|
||||
Abmelden
|
||||
</button>
|
||||
<button
|
||||
onclick={() => (leaveConfirmOpen = false)}
|
||||
class="w-full rounded-xl border border-gray-200 py-3 text-sm font-medium text-gray-700 transition hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<ConfirmSheet
|
||||
open={leaveConfirmOpen}
|
||||
title="Event verlassen?"
|
||||
message="Du wirst abgemeldet. Mit deinem PIN kannst du jederzeit zurückkehren."
|
||||
confirmLabel="Abmelden"
|
||||
tone="danger"
|
||||
onConfirm={handleLogout}
|
||||
onCancel={() => (leaveConfirmOpen = false)}
|
||||
/>
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
import { getToken, getRole } from '$lib/auth';
|
||||
import { api } from '$lib/api';
|
||||
import { onMount } from 'svelte';
|
||||
import { toast, toastError } from '$lib/toast-store';
|
||||
import ConfirmSheet from '$lib/components/ConfirmSheet.svelte';
|
||||
import Modal from '$lib/components/Modal.svelte';
|
||||
|
||||
interface StatsDto {
|
||||
user_count: number;
|
||||
@@ -110,7 +113,6 @@
|
||||
let loading = $state(true);
|
||||
let saving = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
let toast = $state<string | null>(null);
|
||||
let exportJobsRefreshing = $state(false);
|
||||
|
||||
// Nutzer tab state
|
||||
@@ -171,11 +173,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
function showToast(msg: string) {
|
||||
toast = msg;
|
||||
setTimeout(() => (toast = null), 3000);
|
||||
}
|
||||
|
||||
async function saveConfig() {
|
||||
saving = true;
|
||||
try {
|
||||
@@ -186,14 +183,14 @@
|
||||
}
|
||||
}
|
||||
if (Object.keys(changes).length === 0) {
|
||||
showToast('Keine Änderungen.');
|
||||
toast('Keine Änderungen.', 'info');
|
||||
return;
|
||||
}
|
||||
await api.patch('/admin/config', changes);
|
||||
config = { ...configDraft };
|
||||
showToast('Konfiguration gespeichert.');
|
||||
toast('Konfiguration gespeichert.', 'success');
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler beim Speichern.');
|
||||
toastError(e);
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
@@ -202,9 +199,9 @@
|
||||
async function releaseGallery() {
|
||||
try {
|
||||
await api.post('/host/gallery/release');
|
||||
showToast('Galerie wurde freigegeben. Export wird vorbereitet…');
|
||||
toast('Galerie wurde freigegeben. Export wird vorbereitet…', 'success');
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler.');
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,11 +215,11 @@
|
||||
banSubmitting = true;
|
||||
try {
|
||||
await api.post(`/host/users/${banTarget.id}/ban`, { hide_uploads: banHideUploads });
|
||||
showToast(`${banTarget.display_name} wurde gesperrt.`);
|
||||
toast(`${banTarget.display_name} wurde gesperrt.`, 'success');
|
||||
banTarget = null;
|
||||
users = await api.get<UserSummary[]>('/host/users');
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler.');
|
||||
toastError(e);
|
||||
} finally {
|
||||
banSubmitting = false;
|
||||
}
|
||||
@@ -231,30 +228,30 @@
|
||||
async function unban(user: UserSummary) {
|
||||
try {
|
||||
await api.post(`/host/users/${user.id}/unban`);
|
||||
showToast(`Sperre für ${user.display_name} aufgehoben.`);
|
||||
toast(`Sperre für ${user.display_name} aufgehoben.`, 'success');
|
||||
users = await api.get<UserSummary[]>('/host/users');
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler.');
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function promoteToHost(user: UserSummary) {
|
||||
try {
|
||||
await api.patch(`/host/users/${user.id}/role`, { role: 'host' });
|
||||
showToast(`${user.display_name} ist jetzt Host.`);
|
||||
toast(`${user.display_name} ist jetzt Host.`, 'success');
|
||||
users = await api.get<UserSummary[]>('/host/users');
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler.');
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function demoteToGuest(user: UserSummary) {
|
||||
try {
|
||||
await api.patch(`/host/users/${user.id}/role`, { role: 'guest' });
|
||||
showToast(`${user.display_name} ist jetzt Gast.`);
|
||||
toast(`${user.display_name} ist jetzt Gast.`, 'success');
|
||||
users = await api.get<UserSummary[]>('/host/users');
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler.');
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,7 +267,7 @@
|
||||
pinModal = { name: pinResetTarget.display_name, pin: res.pin };
|
||||
pinResetTarget = null;
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler beim Zurücksetzen.');
|
||||
toastError(e);
|
||||
} finally {
|
||||
pinResetSubmitting = false;
|
||||
}
|
||||
@@ -279,7 +276,7 @@
|
||||
function copyPinModal() {
|
||||
if (!pinModal) return;
|
||||
navigator.clipboard.writeText(pinModal.pin);
|
||||
showToast('PIN kopiert.');
|
||||
toast('PIN kopiert.', 'success');
|
||||
}
|
||||
|
||||
/** True iff the current caller may reset this target's PIN. Mirrors the backend
|
||||
@@ -326,76 +323,60 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- PIN reset confirmation -->
|
||||
{#if pinResetTarget}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||
<div class="w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900">
|
||||
<h2 class="mb-1 text-lg font-bold text-gray-900 dark:text-gray-100">PIN zurücksetzen</h2>
|
||||
<p class="mb-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
Eine neue PIN für <strong>{pinResetTarget.display_name}</strong> wird erzeugt. Die alte PIN funktioniert dann nicht mehr.
|
||||
</p>
|
||||
<div class="flex gap-2">
|
||||
<button onclick={() => (pinResetTarget = null)} class="flex-1 rounded-lg border border-gray-300 py-2 text-sm text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800">Abbrechen</button>
|
||||
<button onclick={confirmResetPin} disabled={pinResetSubmitting} class="flex-1 rounded-lg bg-amber-500 py-2 text-sm font-medium text-white hover:bg-amber-600 disabled:opacity-50 dark:bg-amber-500 dark:hover:bg-amber-400">
|
||||
{pinResetSubmitting ? 'Wird erzeugt…' : 'Neue PIN erzeugen'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<!-- PIN reset confirmation — pure yes/no, uses the shared ConfirmSheet. -->
|
||||
<ConfirmSheet
|
||||
open={pinResetTarget !== null}
|
||||
title="PIN zurücksetzen"
|
||||
message={pinResetTarget
|
||||
? `Eine neue PIN für ${pinResetTarget.display_name} wird erzeugt. Die alte PIN funktioniert dann nicht mehr.`
|
||||
: ''}
|
||||
confirmLabel={pinResetSubmitting ? 'Wird erzeugt…' : 'Neue PIN erzeugen'}
|
||||
tone="danger"
|
||||
onConfirm={confirmResetPin}
|
||||
onCancel={() => (pinResetTarget = null)}
|
||||
/>
|
||||
|
||||
<!-- One-time PIN display modal -->
|
||||
{#if pinModal}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
|
||||
<div class="w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900">
|
||||
<h2 class="mb-1 text-lg font-bold text-gray-900 dark:text-gray-100">Neue PIN für {pinModal.name}</h2>
|
||||
<p class="mb-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
Zeige diese PIN dem Benutzer. Sie wird nur einmal angezeigt — beim Schließen wird sie verworfen.
|
||||
</p>
|
||||
<div class="mb-4 flex items-center justify-between rounded-lg bg-amber-50 px-4 py-3 dark:bg-amber-950/30">
|
||||
<span class="font-mono text-3xl font-bold tracking-widest text-gray-900 dark:text-gray-100">{pinModal.pin}</span>
|
||||
<button onclick={copyPinModal} class="rounded-md bg-amber-100 px-3 py-1.5 text-sm font-medium text-amber-800 hover:bg-amber-200 dark:bg-amber-900/40 dark:text-amber-200 dark:hover:bg-amber-900/60">
|
||||
Kopieren
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
onclick={() => (pinModal = null)}
|
||||
class="w-full rounded-lg bg-blue-600 py-2 text-sm font-semibold text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400"
|
||||
>
|
||||
Schließen
|
||||
<!-- One-time PIN display modal — focus-trapped, aria-modal, Escape-dismissable. -->
|
||||
<Modal open={pinModal !== null} titleId="admin-pin-modal-title" onClose={() => (pinModal = null)}>
|
||||
{#if pinModal}
|
||||
<h2 id="admin-pin-modal-title" class="mb-1 text-lg font-bold text-gray-900 dark:text-gray-100">Neue PIN für {pinModal.name}</h2>
|
||||
<p class="mb-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
Zeige diese PIN dem Benutzer. Sie wird nur einmal angezeigt — beim Schließen wird sie verworfen.
|
||||
</p>
|
||||
<div class="mb-4 flex items-center justify-between rounded-lg bg-amber-50 px-4 py-3 dark:bg-amber-950/30">
|
||||
<span class="font-mono text-3xl font-bold tracking-widest text-gray-900 dark:text-gray-100">{pinModal.pin}</span>
|
||||
<button onclick={copyPinModal} class="rounded-md bg-amber-100 px-3 py-1.5 text-sm font-medium text-amber-800 hover:bg-amber-200 active:bg-amber-200 dark:bg-amber-900/40 dark:text-amber-200 dark:hover:bg-amber-900/60 dark:active:bg-amber-900/60">
|
||||
Kopieren
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<button
|
||||
onclick={() => (pinModal = null)}
|
||||
class="w-full rounded-lg bg-blue-600 py-2 text-sm font-semibold text-white hover:bg-blue-700 active:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400 dark:active:bg-blue-400"
|
||||
>
|
||||
Schließen
|
||||
</button>
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<!-- Ban modal -->
|
||||
{#if banTarget}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||
<div class="w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900">
|
||||
<h2 class="mb-1 text-lg font-bold text-gray-900 dark:text-gray-100">Benutzer sperren</h2>
|
||||
<p class="mb-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
Was soll mit den Uploads von <strong>{banTarget.display_name}</strong> passieren?
|
||||
</p>
|
||||
<label class="mb-4 flex cursor-pointer items-center gap-3 rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<input type="checkbox" bind:checked={banHideUploads} class="h-4 w-4 rounded border-gray-300 text-red-600 focus:ring-red-500 dark:border-gray-600" />
|
||||
<span class="text-sm text-gray-700 dark:text-gray-300">Uploads aus der Galerie ausblenden</span>
|
||||
</label>
|
||||
<div class="flex gap-2">
|
||||
<button onclick={() => (banTarget = null)} class="flex-1 rounded-lg border border-gray-300 py-2 text-sm text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800">Abbrechen</button>
|
||||
<button onclick={confirmBan} disabled={banSubmitting} class="flex-1 rounded-lg bg-red-600 py-2 text-sm font-medium text-white hover:bg-red-700 disabled:opacity-50 dark:bg-red-500 dark:hover:bg-red-400">
|
||||
{banSubmitting ? 'Wird gesperrt…' : 'Sperren'}
|
||||
</button>
|
||||
</div>
|
||||
<!-- Ban modal — checkbox-bearing, so uses the Modal shell instead of ConfirmSheet. -->
|
||||
<Modal open={banTarget !== null} titleId="admin-ban-modal-title" onClose={() => (banTarget = null)}>
|
||||
{#if banTarget}
|
||||
<h2 id="admin-ban-modal-title" class="mb-1 text-lg font-bold text-gray-900 dark:text-gray-100">Benutzer sperren</h2>
|
||||
<p class="mb-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
Was soll mit den Uploads von <strong>{banTarget.display_name}</strong> passieren?
|
||||
</p>
|
||||
<label class="mb-4 flex cursor-pointer items-center gap-3 rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<input type="checkbox" bind:checked={banHideUploads} class="h-4 w-4 rounded border-gray-300 text-red-600 focus:ring-red-500 dark:border-gray-600" />
|
||||
<span class="text-sm text-gray-700 dark:text-gray-300">Uploads aus der Galerie ausblenden</span>
|
||||
</label>
|
||||
<div class="flex gap-2">
|
||||
<button onclick={() => (banTarget = null)} class="flex-1 rounded-lg border border-gray-300 py-2 text-sm text-gray-700 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">Abbrechen</button>
|
||||
<button onclick={confirmBan} disabled={banSubmitting} class="flex-1 rounded-lg bg-red-600 py-2 text-sm font-medium text-white hover:bg-red-700 active:bg-red-700 disabled:opacity-50 dark:bg-red-500 dark:hover:bg-red-400 dark:active:bg-red-400">
|
||||
{banSubmitting ? 'Wird gesperrt…' : 'Sperren'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Toast -->
|
||||
{#if toast}
|
||||
<div class="fixed bottom-24 left-1/2 z-50 -translate-x-1/2 rounded-full bg-gray-900 px-5 py-2.5 text-sm text-white shadow-lg dark:bg-gray-100 dark:text-gray-900">
|
||||
{toast}
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<div class="min-h-screen bg-gray-50 pb-24 dark:bg-gray-950">
|
||||
<!-- Header -->
|
||||
@@ -431,7 +412,7 @@
|
||||
|
||||
<div class="mx-auto max-w-3xl p-4">
|
||||
{#if loading}
|
||||
<div class="py-16 text-center text-gray-400 dark:text-gray-500">Laden…</div>
|
||||
<div class="py-16 text-center text-gray-500 dark:text-gray-400">Laden…</div>
|
||||
{:else if error}
|
||||
<div class="rounded-lg bg-red-50 p-4 text-sm text-red-700">{error}</div>
|
||||
{:else}
|
||||
@@ -470,7 +451,7 @@
|
||||
style="width: {diskPct(stats)}%"
|
||||
></div>
|
||||
</div>
|
||||
<p class="mt-1.5 text-xs text-gray-400 dark:text-gray-500">{formatBytes(stats.disk_free_bytes)} frei</p>
|
||||
<p class="mt-1.5 text-xs text-gray-500 dark:text-gray-400">{formatBytes(stats.disk_free_bytes)} frei</p>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -571,7 +552,7 @@
|
||||
</button>
|
||||
</div>
|
||||
{#if exportJobs.length === 0}
|
||||
<p class="text-sm text-gray-400 dark:text-gray-500">Noch keine Export-Jobs.</p>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Noch keine Export-Jobs.</p>
|
||||
{:else}
|
||||
<div class="space-y-3">
|
||||
{#each exportJobs as job}
|
||||
@@ -608,7 +589,7 @@
|
||||
<!-- Search -->
|
||||
<div class="p-4">
|
||||
<div class="flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 dark:border-gray-700 dark:bg-gray-900">
|
||||
<svg class="h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<svg class="h-4 w-4 shrink-0 text-gray-500 dark:text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
|
||||
</svg>
|
||||
<input
|
||||
@@ -620,7 +601,7 @@
|
||||
</div>
|
||||
</div>
|
||||
{#if filteredUsers.length === 0}
|
||||
<p class="px-5 py-8 text-center text-sm text-gray-400 dark:text-gray-500">Keine Treffer.</p>
|
||||
<p class="px-5 py-8 text-center text-sm text-gray-500 dark:text-gray-400">Keine Treffer.</p>
|
||||
{:else}
|
||||
<div class="divide-y divide-gray-100 dark:divide-gray-700">
|
||||
{#each filteredUsers as user}
|
||||
@@ -637,7 +618,7 @@
|
||||
<span class="rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700 dark:bg-red-900/40 dark:text-red-200">Gesperrt</span>
|
||||
{/if}
|
||||
</div>
|
||||
<p class="text-xs text-gray-400 dark:text-gray-500">
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400">
|
||||
{user.upload_count} Upload{user.upload_count !== 1 ? 's' : ''} · {formatBytes(user.total_upload_bytes)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -35,7 +35,15 @@
|
||||
clearTimer();
|
||||
if (paused) return;
|
||||
// Videos: advance on `ended` or after `max(dwell, 12s)` — whichever first.
|
||||
const ms = isVideo ? Math.max(dwellMs, 12000) : dwellMs;
|
||||
let ms = isVideo ? Math.max(dwellMs, 12000) : dwellMs;
|
||||
// Reduced-motion: slow auto-advance to a ≥30s floor so content doesn't
|
||||
// auto-change rapidly (WCAG 2.2.2); the CSS already snaps the transitions.
|
||||
if (
|
||||
typeof window !== 'undefined' &&
|
||||
window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
|
||||
) {
|
||||
ms = Math.max(ms, 30000);
|
||||
}
|
||||
advanceTimer = setTimeout(advance, ms);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
import { api } from '$lib/api';
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { connectSse, disconnectSse, onSseEvent } from '$lib/sse';
|
||||
import { toastError } from '$lib/toast-store';
|
||||
import { focusTrap } from '$lib/actions/focus-trap';
|
||||
|
||||
interface JobStatus {
|
||||
status: 'locked' | 'pending' | 'running' | 'done' | 'failed';
|
||||
@@ -21,6 +23,7 @@
|
||||
let status = $state<ExportStatus | null>(null);
|
||||
let showHtmlGuide = $state(false);
|
||||
let loading = $state(true);
|
||||
let loadError = $state(false);
|
||||
|
||||
let unsubscribers: (() => void)[] = [];
|
||||
|
||||
@@ -51,8 +54,12 @@
|
||||
async function loadStatus() {
|
||||
try {
|
||||
status = await api.get<ExportStatus>('/export/status');
|
||||
loadError = false;
|
||||
} catch {
|
||||
// ignore
|
||||
// M19: a fetch failure must not masquerade as "not yet released" — only
|
||||
// flag an error when we have nothing to show; a background SSE poll that
|
||||
// fails while we already have a status stays silent.
|
||||
if (!status) loadError = true;
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
@@ -73,18 +80,25 @@
|
||||
}
|
||||
|
||||
async function downloadFile(endpoint: string, filename: string) {
|
||||
const token = getToken();
|
||||
const res = await fetch(endpoint, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
});
|
||||
if (!res.ok) return;
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
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 a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
function downloadZip() {
|
||||
@@ -109,8 +123,14 @@
|
||||
<!-- HTML guide modal -->
|
||||
{#if showHtmlGuide}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||
<div class="w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900">
|
||||
<h2 class="mb-3 text-lg font-bold text-gray-900 dark:text-gray-100">Hinweis zum HTML-Viewer</h2>
|
||||
<div
|
||||
class="w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="html-guide-title"
|
||||
use:focusTrap={{ onclose: () => (showHtmlGuide = false) }}
|
||||
>
|
||||
<h2 id="html-guide-title" class="mb-3 text-lg font-bold text-gray-900 dark:text-gray-100">Hinweis zum HTML-Viewer</h2>
|
||||
<ol class="mb-4 space-y-2 text-sm text-gray-700 dark:text-gray-300">
|
||||
<li class="flex gap-2"><span class="font-bold text-blue-600 dark:text-blue-400">1.</span> ZIP-Datei entpacken (Windows: Rechtsklick → "Alle extrahieren"; Mac: Doppelklick).</li>
|
||||
<li class="flex gap-2"><span class="font-bold text-blue-600 dark:text-blue-400">2.</span> <strong>index.html</strong> im Browser öffnen.</li>
|
||||
@@ -139,14 +159,35 @@
|
||||
|
||||
<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="mx-auto flex max-w-lg items-center px-4 py-4">
|
||||
<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"
|
||||
>
|
||||
<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>
|
||||
<h1 class="text-xl font-bold text-gray-900 dark:text-gray-100">Export</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mx-auto max-w-lg space-y-4 p-4">
|
||||
{#if loading}
|
||||
<div class="py-16 text-center text-gray-400 dark:text-gray-500">Laden…</div>
|
||||
<div class="py-16 text-center text-gray-500 dark:text-gray-400">Laden…</div>
|
||||
{:else if loadError}
|
||||
<div class="rounded-xl border border-gray-200 bg-white p-6 text-center dark:border-gray-700 dark:bg-gray-800">
|
||||
<p class="font-medium text-gray-700 dark:text-gray-300">Status konnte nicht geladen werden.</p>
|
||||
<button
|
||||
onclick={() => { loading = true; loadStatus(); }}
|
||||
class="mt-3 rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-blue-700"
|
||||
>
|
||||
Erneut versuchen
|
||||
</button>
|
||||
</div>
|
||||
{:else if !status?.released}
|
||||
<div class="rounded-xl border border-gray-200 bg-white p-6 text-center dark:border-gray-700 dark:bg-gray-800">
|
||||
<svg class="mx-auto mb-3 h-12 w-12 text-gray-300 dark:text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
@@ -164,7 +205,7 @@
|
||||
<div class="min-w-0">
|
||||
<h2 class="font-semibold text-gray-900 dark:text-gray-100">ZIP-Archiv</h2>
|
||||
<p class="mt-0.5 text-sm text-gray-500 dark:text-gray-400">Alle Original-Fotos und Videos in strukturierten Ordnern.</p>
|
||||
<p class="mt-1 text-xs {status.zip.status === 'done' ? 'text-green-600 dark:text-green-400' : status.zip.status === 'failed' ? 'text-red-500 dark:text-red-400' : 'text-gray-400 dark:text-gray-500'}">
|
||||
<p class="mt-1 text-xs {status.zip.status === 'done' ? 'text-green-600 dark:text-green-400' : status.zip.status === 'failed' ? 'text-red-500 dark:text-red-400' : 'text-gray-500 dark:text-gray-400'}">
|
||||
{statusText(status.zip)}
|
||||
</p>
|
||||
</div>
|
||||
@@ -191,7 +232,7 @@
|
||||
<div class="min-w-0">
|
||||
<h2 class="font-semibold text-gray-900 dark:text-gray-100">HTML-Viewer</h2>
|
||||
<p class="mt-0.5 text-sm text-gray-500 dark:text-gray-400">Schöne Offline-Galerie mit Filterung, Kommentaren und Likes — kein Internet nötig.</p>
|
||||
<p class="mt-1 text-xs {status.html.status === 'done' ? 'text-green-600 dark:text-green-400' : status.html.status === 'failed' ? 'text-red-500 dark:text-red-400' : 'text-gray-400 dark:text-gray-500'}">
|
||||
<p class="mt-1 text-xs {status.html.status === 'done' ? 'text-green-600 dark:text-green-400' : status.html.status === 'failed' ? 'text-red-500 dark:text-red-400' : 'text-gray-500 dark:text-gray-400'}">
|
||||
{statusText(status.html)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { goto } from '$app/navigation';
|
||||
import { getToken, getUserId } from '$lib/auth';
|
||||
import { api } from '$lib/api';
|
||||
import { connectSse, disconnectSse, onSseEvent } from '$lib/sse';
|
||||
import { connectSse, disconnectSse, onSseEvent, setLastEventTime } from '$lib/sse';
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import FeedGrid from '$lib/components/FeedGrid.svelte';
|
||||
import FeedListCard from '$lib/components/FeedListCard.svelte';
|
||||
@@ -10,7 +10,13 @@
|
||||
import LightboxModal from '$lib/components/LightboxModal.svelte';
|
||||
import OnboardingGuide from '$lib/components/OnboardingGuide.svelte';
|
||||
import ContextSheet, { type ContextAction } from '$lib/components/ContextSheet.svelte';
|
||||
import ConfirmSheet from '$lib/components/ConfirmSheet.svelte';
|
||||
import Skeleton from '$lib/components/Skeleton.svelte';
|
||||
import { refreshQuota } from '$lib/quota-store';
|
||||
import { toast, toastError } from '$lib/toast-store';
|
||||
import { pullToRefresh } from '$lib/actions/pull-to-refresh';
|
||||
import { vibrate } from '$lib/haptics';
|
||||
import { uploadsLocked } from '$lib/event-state-store';
|
||||
import type { FeedUpload, FeedResponse, HashtagCount, DeltaResponse } from '$lib/types';
|
||||
|
||||
let uploads = $state<FeedUpload[]>([]);
|
||||
@@ -18,8 +24,27 @@
|
||||
let selectedHashtag = $state<string | null>(null);
|
||||
let nextCursor = $state<string | null>(null);
|
||||
let loadingMore = $state(false);
|
||||
let initialLoading = $state(true);
|
||||
let loadError = $state(false);
|
||||
let refreshing = $state(false);
|
||||
let pullProgress = $state(0); // 0–1+ during the drag, 0 when idle
|
||||
let selectedUpload = $state<FeedUpload | null>(null);
|
||||
let sentinel: HTMLDivElement;
|
||||
let pendingDeleteId = $state<string | null>(null);
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// onMount A — DOM side-effects only (overscroll lock). Synchronous, returns
|
||||
// its own cleanup. Kept separate from the data-loading onMount below so its
|
||||
// cleanup can't be accidentally clobbered when someone edits the async one.
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
onMount(() => {
|
||||
if (typeof document === 'undefined') return;
|
||||
const prev = document.documentElement.style.overscrollBehaviorY;
|
||||
document.documentElement.style.overscrollBehaviorY = 'contain';
|
||||
return () => {
|
||||
document.documentElement.style.overscrollBehaviorY = prev;
|
||||
};
|
||||
});
|
||||
|
||||
// View mode
|
||||
let viewMode = $state<'list' | 'grid'>('list');
|
||||
@@ -45,7 +70,7 @@
|
||||
label: 'Original anzeigen',
|
||||
icon: '⤓',
|
||||
onClick: () => {
|
||||
window.open(`/api/v1/upload/${target.id}/original`, '_blank');
|
||||
if (target.original_url) window.open(target.original_url, '_blank');
|
||||
}
|
||||
}
|
||||
];
|
||||
@@ -54,7 +79,7 @@
|
||||
label: 'Löschen',
|
||||
icon: '🗑',
|
||||
tone: 'danger',
|
||||
onClick: () => deleteUpload(target.id)
|
||||
onClick: () => { pendingDeleteId = target.id; }
|
||||
});
|
||||
}
|
||||
return actions;
|
||||
@@ -64,15 +89,17 @@
|
||||
contextTarget = upload;
|
||||
}
|
||||
|
||||
async function deleteUpload(id: string) {
|
||||
if (!confirm('Diesen Beitrag wirklich löschen?')) return;
|
||||
async function confirmDelete() {
|
||||
const id = pendingDeleteId;
|
||||
if (!id) return;
|
||||
pendingDeleteId = null;
|
||||
try {
|
||||
await api.delete(`/upload/${id}`);
|
||||
uploads = uploads.filter((u) => u.id !== id);
|
||||
if (selectedUpload?.id === id) selectedUpload = null;
|
||||
void refreshQuota();
|
||||
} catch {
|
||||
// ignore — toast handled by ApiError elsewhere
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,12 +160,28 @@
|
||||
});
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
// onMount B — auth gate, recovery toast, data load, SSE subscriptions,
|
||||
// infinite-scroll observer. Cleanup of the SSE handlers lives in onDestroy
|
||||
// below (not in a returned cleanup) because this callback is async.
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
onMount(async () => {
|
||||
if (!getToken()) {
|
||||
goto('/join');
|
||||
return;
|
||||
}
|
||||
|
||||
// Surface the welcome-back toast set by /recover. Lives here (not on /account)
|
||||
// because /feed is the first hydrated route after a successful PIN recovery —
|
||||
// the toast should land in the same beat as the "you're in" feeling.
|
||||
if (typeof sessionStorage !== 'undefined') {
|
||||
const welcome = sessionStorage.getItem('eventsnap_just_recovered');
|
||||
if (welcome) {
|
||||
sessionStorage.removeItem('eventsnap_just_recovered');
|
||||
toast(`Willkommen zurück, ${welcome}!`, 'success');
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all([loadFeed(), loadHashtags()]);
|
||||
connectSse();
|
||||
|
||||
@@ -159,6 +202,9 @@
|
||||
}),
|
||||
onSseEvent('like-update', () => loadFeed(true)),
|
||||
onSseEvent('new-comment', () => loadFeed(true)),
|
||||
// Delta was clamped/capped server-side (H7) — do a full reload instead
|
||||
// of trusting a partial set.
|
||||
onSseEvent('feed-reload', () => loadFeed(true)),
|
||||
// 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) => {
|
||||
@@ -202,7 +248,21 @@
|
||||
const res = await api.get<FeedResponse>(`/feed?${params}`);
|
||||
uploads = res.uploads;
|
||||
nextCursor = res.next_cursor;
|
||||
} catch { /* ignore */ }
|
||||
loadError = false;
|
||||
// Seed the SSE reconnect cursor from the newest server timestamp so the
|
||||
// delta on the next reconnect is based on server time, not the client
|
||||
// clock (M9).
|
||||
if (uploads.length) setLastEventTime(uploads[0].created_at);
|
||||
} catch (e) {
|
||||
// M19: distinguish a load failure from a genuinely empty gallery so the
|
||||
// template can offer a retry instead of showing "nobody posted yet".
|
||||
if (!refresh) {
|
||||
loadError = true;
|
||||
toastError(e);
|
||||
}
|
||||
} finally {
|
||||
initialLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMore() {
|
||||
@@ -216,7 +276,9 @@
|
||||
const res = await api.get<FeedResponse>(`/feed?${params}`);
|
||||
uploads = [...uploads, ...res.uploads];
|
||||
nextCursor = res.next_cursor;
|
||||
} catch { /* ignore */ } finally {
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
loadingMore = false;
|
||||
}
|
||||
}
|
||||
@@ -224,7 +286,22 @@
|
||||
async function loadHashtags() {
|
||||
try {
|
||||
hashtags = await api.get<HashtagCount[]>('/hashtags');
|
||||
} catch { /* ignore */ }
|
||||
} catch {
|
||||
// Hashtag panel is a discoverability nicety — silent fail is acceptable; the feed still works.
|
||||
}
|
||||
}
|
||||
|
||||
async function pullRefresh() {
|
||||
if (refreshing) return;
|
||||
refreshing = true;
|
||||
pullProgress = 0;
|
||||
vibrate(10);
|
||||
try {
|
||||
nextCursor = null;
|
||||
await Promise.all([loadFeed(true), loadHashtags()]);
|
||||
} finally {
|
||||
refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
function selectHashtag(tag: string | null) {
|
||||
@@ -236,6 +313,7 @@
|
||||
async function handleLike(id: string) {
|
||||
try {
|
||||
await api.post(`/upload/${id}/like`);
|
||||
vibrate(10);
|
||||
uploads = uploads.map((u) =>
|
||||
u.id === id
|
||||
? { ...u, liked_by_me: !u.liked_by_me, like_count: u.liked_by_me ? u.like_count - 1 : u.like_count + 1 }
|
||||
@@ -248,7 +326,9 @@
|
||||
like_count: selectedUpload.liked_by_me ? selectedUpload.like_count - 1 : selectedUpload.like_count + 1,
|
||||
};
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
function openComments(id: string) {
|
||||
@@ -282,9 +362,45 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="min-h-screen bg-gray-50 pb-24 dark:bg-gray-950">
|
||||
<!-- Sticky header -->
|
||||
<div class="sticky top-0 z-30 border-b border-gray-200 bg-white/95 backdrop-blur dark:border-gray-800 dark:bg-gray-900/95">
|
||||
<div
|
||||
class="min-h-screen bg-gray-50 pb-24 dark:bg-gray-950"
|
||||
use:pullToRefresh={{
|
||||
onrefresh: pullRefresh,
|
||||
onpull: (_, progress) => (pullProgress = progress),
|
||||
disabled: initialLoading
|
||||
}}
|
||||
>
|
||||
<!-- 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="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)}"
|
||||
>
|
||||
{#if refreshing}
|
||||
<span class="inline-flex items-center gap-2">
|
||||
<span class="inline-block h-3 w-3 animate-spin rounded-full border-2 border-blue-200 border-t-blue-600 dark:border-blue-700 dark:border-t-blue-300"></span>
|
||||
Aktualisiere…
|
||||
</span>
|
||||
{:else}
|
||||
<svg
|
||||
class="inline-block h-4 w-4 transition-transform"
|
||||
style="transform: rotate({Math.min(180, pullProgress * 180)}deg)"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
stroke-width="2.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 13.5L12 21m0 0l-7.5-7.5M12 21V3" />
|
||||
</svg>
|
||||
{/if}
|
||||
</div>
|
||||
</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="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>
|
||||
|
||||
@@ -340,14 +456,19 @@
|
||||
<div class="mx-auto max-w-2xl px-4 pb-3">
|
||||
<div class="relative">
|
||||
<div class="flex items-center gap-2 rounded-xl border border-gray-200 bg-gray-50 px-3 py-2 focus-within:border-blue-400 focus-within:bg-white focus-within:ring-1 focus-within:ring-blue-200 dark:border-gray-700 dark:bg-gray-800 dark:focus-within:border-blue-500 dark:focus-within:bg-gray-800">
|
||||
<svg class="h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<svg class="h-4 w-4 shrink-0 text-gray-500 dark:text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z" />
|
||||
</svg>
|
||||
<input
|
||||
type="search"
|
||||
aria-label="Nutzer oder Hashtag suchen"
|
||||
placeholder="Nutzer oder #Tag suchen…"
|
||||
bind:value={searchQuery}
|
||||
onfocus={() => (showAutocomplete = true)}
|
||||
onfocus={(e) => {
|
||||
showAutocomplete = true;
|
||||
// Push the input above the virtual keyboard so suggestions stay visible.
|
||||
(e.currentTarget as HTMLInputElement).scrollIntoView({ block: 'center', behavior: 'smooth' });
|
||||
}}
|
||||
onblur={() => setTimeout(() => (showAutocomplete = false), 150)}
|
||||
class="min-w-0 flex-1 bg-transparent text-sm text-gray-900 placeholder-gray-400 outline-none dark:text-gray-100 dark:placeholder-gray-500"
|
||||
/>
|
||||
@@ -373,7 +494,7 @@
|
||||
onmousedown={() => selectSuggestion(item)}
|
||||
>
|
||||
{#if item.type === 'user'}
|
||||
<svg class="h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
||||
<svg class="h-4 w-4 shrink-0 text-gray-500 dark:text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z" />
|
||||
</svg>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{item.value}</span>
|
||||
@@ -411,11 +532,45 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Uploads-locked banner (M11) -->
|
||||
{#if $uploadsLocked}
|
||||
<div
|
||||
class="mx-auto mb-2 max-w-2xl rounded-lg bg-amber-100 px-4 py-2 text-center text-sm font-medium text-amber-800 dark:bg-amber-900/40 dark:text-amber-200"
|
||||
role="status"
|
||||
>
|
||||
Uploads sind aktuell gesperrt.
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Content -->
|
||||
{#if uploads.length === 0}
|
||||
{#if initialLoading && uploads.length === 0}
|
||||
<div class="mx-auto max-w-2xl" data-testid="feed-skeleton">
|
||||
{#if viewMode === 'list'}
|
||||
{#each Array(3) as _}
|
||||
<Skeleton variant="card" />
|
||||
{/each}
|
||||
{:else}
|
||||
<div class="grid grid-cols-3 gap-0.5">
|
||||
{#each Array(9) as _}
|
||||
<Skeleton variant="tile" />
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if uploads.length === 0 && loadError}
|
||||
<div class="py-20 text-center">
|
||||
<p class="text-lg text-gray-400 dark:text-gray-500">Noch keine Fotos.</p>
|
||||
<p class="mt-1 text-sm text-gray-400 dark:text-gray-500">Tippe auf den Plus-Button unten!</p>
|
||||
<p class="text-lg text-gray-600 dark:text-gray-300">Galerie konnte nicht geladen werden.</p>
|
||||
<button
|
||||
onclick={() => loadFeed()}
|
||||
class="mt-3 rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-blue-700"
|
||||
>
|
||||
Erneut versuchen
|
||||
</button>
|
||||
</div>
|
||||
{:else if uploads.length === 0}
|
||||
<div class="py-20 text-center">
|
||||
<p class="text-lg text-gray-500 dark:text-gray-400">Noch keine Fotos.</p>
|
||||
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Tippe auf den Plus-Button unten!</p>
|
||||
</div>
|
||||
{:else if viewMode === 'list'}
|
||||
<!-- List view: chronological full-width cards -->
|
||||
@@ -436,7 +591,7 @@
|
||||
<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>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Keine Treffer für die gewählten Filter.</p>
|
||||
<button onclick={clearFilters} class="mt-2 text-sm text-blue-600 hover:underline dark:text-blue-400">Filter zurücksetzen</button>
|
||||
</div>
|
||||
{:else}
|
||||
@@ -479,5 +634,16 @@
|
||||
onClose={() => (contextTarget = null)}
|
||||
/>
|
||||
|
||||
<!-- Branded delete confirmation — replaces window.confirm() -->
|
||||
<ConfirmSheet
|
||||
open={pendingDeleteId !== null}
|
||||
title="Beitrag löschen?"
|
||||
message="Diese Aktion kann nicht rückgängig gemacht werden."
|
||||
confirmLabel="Löschen"
|
||||
tone="danger"
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={() => (pendingDeleteId = null)}
|
||||
/>
|
||||
|
||||
<!-- First-visit onboarding guide -->
|
||||
<OnboardingGuide />
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
import { getToken, getRole } from '$lib/auth';
|
||||
import { api } from '$lib/api';
|
||||
import { onMount } from 'svelte';
|
||||
import { toast, toastError } from '$lib/toast-store';
|
||||
import ConfirmSheet from '$lib/components/ConfirmSheet.svelte';
|
||||
import Modal from '$lib/components/Modal.svelte';
|
||||
|
||||
interface UserSummary {
|
||||
id: string;
|
||||
@@ -51,8 +54,6 @@
|
||||
let pinResetSubmitting = $state(false);
|
||||
let pinModal = $state<{ name: string; pin: string } | null>(null);
|
||||
|
||||
let toast = $state<string | null>(null);
|
||||
|
||||
const myRole = getRole();
|
||||
|
||||
/** Mirrors backend `handlers::host::reset_user_pin` authorisation rules. */
|
||||
@@ -88,34 +89,29 @@
|
||||
}
|
||||
}
|
||||
|
||||
function showToast(msg: string) {
|
||||
toast = msg;
|
||||
setTimeout(() => (toast = null), 3000);
|
||||
}
|
||||
|
||||
async function toggleEventLock() {
|
||||
if (!event) return;
|
||||
try {
|
||||
if (event.uploads_locked) {
|
||||
await api.post('/host/event/open');
|
||||
showToast('Uploads wurden wieder geöffnet.');
|
||||
toast('Uploads wurden wieder geöffnet.', 'success');
|
||||
} else {
|
||||
await api.post('/host/event/close');
|
||||
showToast('Uploads wurden gesperrt.');
|
||||
toast('Uploads wurden gesperrt.', 'success');
|
||||
}
|
||||
await reload();
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler.');
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function releaseGallery() {
|
||||
try {
|
||||
await api.post('/host/gallery/release');
|
||||
showToast('Galerie wurde freigegeben. Export wird vorbereitet…');
|
||||
toast('Galerie wurde freigegeben. Export wird vorbereitet…', 'success');
|
||||
await reload();
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler.');
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,11 +125,11 @@
|
||||
banSubmitting = true;
|
||||
try {
|
||||
await api.post(`/host/users/${banTarget.id}/ban`, { hide_uploads: banHideUploads });
|
||||
showToast(`${banTarget.display_name} wurde gesperrt.`);
|
||||
toast(`${banTarget.display_name} wurde gesperrt.`, 'success');
|
||||
banTarget = null;
|
||||
await reload();
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler.');
|
||||
toastError(e);
|
||||
} finally {
|
||||
banSubmitting = false;
|
||||
}
|
||||
@@ -142,30 +138,30 @@
|
||||
async function unban(user: UserSummary) {
|
||||
try {
|
||||
await api.post(`/host/users/${user.id}/unban`);
|
||||
showToast(`Sperre für ${user.display_name} aufgehoben.`);
|
||||
toast(`Sperre für ${user.display_name} aufgehoben.`, 'success');
|
||||
await reload();
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler.');
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function promoteToHost(user: UserSummary) {
|
||||
try {
|
||||
await api.patch(`/host/users/${user.id}/role`, { role: 'host' });
|
||||
showToast(`${user.display_name} ist jetzt Host.`);
|
||||
toast(`${user.display_name} ist jetzt Host.`, 'success');
|
||||
await reload();
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler.');
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function demoteToGuest(user: UserSummary) {
|
||||
try {
|
||||
await api.patch(`/host/users/${user.id}/role`, { role: 'guest' });
|
||||
showToast(`${user.display_name} ist jetzt Gast.`);
|
||||
toast(`${user.display_name} ist jetzt Gast.`, 'success');
|
||||
await reload();
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler.');
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,7 +177,7 @@
|
||||
pinModal = { name: pinResetTarget.display_name, pin: res.pin };
|
||||
pinResetTarget = null;
|
||||
} catch (e: unknown) {
|
||||
showToast(e instanceof Error ? e.message : 'Fehler beim Zurücksetzen.');
|
||||
toastError(e);
|
||||
} finally {
|
||||
pinResetSubmitting = false;
|
||||
}
|
||||
@@ -190,7 +186,7 @@
|
||||
function copyPinModal() {
|
||||
if (!pinModal) return;
|
||||
navigator.clipboard.writeText(pinModal.pin);
|
||||
showToast('PIN kopiert.');
|
||||
toast('PIN kopiert.', 'success');
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
@@ -200,89 +196,73 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- PIN reset confirmation -->
|
||||
{#if pinResetTarget}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||
<div class="w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900">
|
||||
<h2 class="mb-1 text-lg font-bold text-gray-900 dark:text-gray-100">PIN zurücksetzen</h2>
|
||||
<p class="mb-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
Eine neue PIN für <strong>{pinResetTarget.display_name}</strong> wird erzeugt. Die alte PIN funktioniert dann nicht mehr.
|
||||
</p>
|
||||
<div class="flex gap-2">
|
||||
<button onclick={() => (pinResetTarget = null)} class="flex-1 rounded-lg border border-gray-300 py-2 text-sm text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800">Abbrechen</button>
|
||||
<button onclick={confirmResetPin} disabled={pinResetSubmitting} class="flex-1 rounded-lg bg-amber-500 py-2 text-sm font-medium text-white hover:bg-amber-600 disabled:opacity-50 dark:bg-amber-500 dark:hover:bg-amber-400">
|
||||
{pinResetSubmitting ? 'Wird erzeugt…' : 'Neue PIN erzeugen'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<!-- PIN reset confirmation — pure yes/no, uses the shared ConfirmSheet. -->
|
||||
<ConfirmSheet
|
||||
open={pinResetTarget !== null}
|
||||
title="PIN zurücksetzen"
|
||||
message={pinResetTarget
|
||||
? `Eine neue PIN für ${pinResetTarget.display_name} wird erzeugt. Die alte PIN funktioniert dann nicht mehr.`
|
||||
: ''}
|
||||
confirmLabel={pinResetSubmitting ? 'Wird erzeugt…' : 'Neue PIN erzeugen'}
|
||||
tone="danger"
|
||||
onConfirm={confirmResetPin}
|
||||
onCancel={() => (pinResetTarget = null)}
|
||||
/>
|
||||
|
||||
<!-- One-time PIN display modal -->
|
||||
{#if pinModal}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
|
||||
<div class="w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900">
|
||||
<h2 class="mb-1 text-lg font-bold text-gray-900 dark:text-gray-100">Neue PIN für {pinModal.name}</h2>
|
||||
<p class="mb-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
Zeige diese PIN dem Benutzer. Sie wird nur einmal angezeigt — beim Schließen wird sie verworfen.
|
||||
</p>
|
||||
<div class="mb-4 flex items-center justify-between rounded-lg bg-amber-50 px-4 py-3 dark:bg-amber-950/30">
|
||||
<span class="font-mono text-3xl font-bold tracking-widest text-gray-900 dark:text-gray-100">{pinModal.pin}</span>
|
||||
<button onclick={copyPinModal} class="rounded-md bg-amber-100 px-3 py-1.5 text-sm font-medium text-amber-800 hover:bg-amber-200 dark:bg-amber-900/40 dark:text-amber-200 dark:hover:bg-amber-900/60">
|
||||
Kopieren
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
onclick={() => (pinModal = null)}
|
||||
class="w-full rounded-lg bg-blue-600 py-2 text-sm font-semibold text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400"
|
||||
>
|
||||
Schließen
|
||||
<!-- One-time PIN display modal — focus-trapped, aria-modal, Escape-dismissable. -->
|
||||
<Modal open={pinModal !== null} titleId="host-pin-modal-title" onClose={() => (pinModal = null)}>
|
||||
{#if pinModal}
|
||||
<h2 id="host-pin-modal-title" class="mb-1 text-lg font-bold text-gray-900 dark:text-gray-100">Neue PIN für {pinModal.name}</h2>
|
||||
<p class="mb-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
Zeige diese PIN dem Benutzer. Sie wird nur einmal angezeigt — beim Schließen wird sie verworfen.
|
||||
</p>
|
||||
<div class="mb-4 flex items-center justify-between rounded-lg bg-amber-50 px-4 py-3 dark:bg-amber-950/30">
|
||||
<span class="font-mono text-3xl font-bold tracking-widest text-gray-900 dark:text-gray-100">{pinModal.pin}</span>
|
||||
<button onclick={copyPinModal} class="rounded-md bg-amber-100 px-3 py-1.5 text-sm font-medium text-amber-800 hover:bg-amber-200 active:bg-amber-200 dark:bg-amber-900/40 dark:text-amber-200 dark:hover:bg-amber-900/60 dark:active:bg-amber-900/60">
|
||||
Kopieren
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<button
|
||||
onclick={() => (pinModal = null)}
|
||||
class="w-full rounded-lg bg-blue-600 py-2 text-sm font-semibold text-white hover:bg-blue-700 active:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400 dark:active:bg-blue-400"
|
||||
>
|
||||
Schließen
|
||||
</button>
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<!-- Ban modal -->
|
||||
{#if banTarget}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||
<div class="w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900">
|
||||
<h2 class="mb-1 text-lg font-bold text-gray-900 dark:text-gray-100">Benutzer sperren</h2>
|
||||
<p class="mb-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
Was soll mit den Uploads von <strong>{banTarget.display_name}</strong> passieren?
|
||||
</p>
|
||||
<label class="mb-4 flex cursor-pointer items-center gap-3 rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<input
|
||||
type="checkbox"
|
||||
bind:checked={banHideUploads}
|
||||
class="h-4 w-4 rounded border-gray-300 text-red-600 focus:ring-red-500 dark:border-gray-600"
|
||||
/>
|
||||
<span class="text-sm text-gray-700 dark:text-gray-300">Uploads aus der Galerie ausblenden</span>
|
||||
</label>
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
onclick={() => (banTarget = null)}
|
||||
class="flex-1 rounded-lg border border-gray-300 py-2 text-sm text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
onclick={confirmBan}
|
||||
disabled={banSubmitting}
|
||||
class="flex-1 rounded-lg bg-red-600 py-2 text-sm font-medium text-white hover:bg-red-700 disabled:opacity-50 dark:bg-red-500 dark:hover:bg-red-400"
|
||||
>
|
||||
{banSubmitting ? 'Wird gesperrt…' : 'Sperren'}
|
||||
</button>
|
||||
</div>
|
||||
<!-- Ban modal — needs a checkbox so it's not a pure ConfirmSheet, but still gets the same a11y shell. -->
|
||||
<Modal open={banTarget !== null} titleId="host-ban-modal-title" onClose={() => (banTarget = null)}>
|
||||
{#if banTarget}
|
||||
<h2 id="host-ban-modal-title" class="mb-1 text-lg font-bold text-gray-900 dark:text-gray-100">Benutzer sperren</h2>
|
||||
<p class="mb-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
Was soll mit den Uploads von <strong>{banTarget.display_name}</strong> passieren?
|
||||
</p>
|
||||
<label class="mb-4 flex cursor-pointer items-center gap-3 rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<input
|
||||
type="checkbox"
|
||||
bind:checked={banHideUploads}
|
||||
class="h-4 w-4 rounded border-gray-300 text-red-600 focus:ring-red-500 dark:border-gray-600"
|
||||
/>
|
||||
<span class="text-sm text-gray-700 dark:text-gray-300">Uploads aus der Galerie ausblenden</span>
|
||||
</label>
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
onclick={() => (banTarget = null)}
|
||||
class="flex-1 rounded-lg border border-gray-300 py-2 text-sm text-gray-700 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"
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
onclick={confirmBan}
|
||||
disabled={banSubmitting}
|
||||
class="flex-1 rounded-lg bg-red-600 py-2 text-sm font-medium text-white hover:bg-red-700 active:bg-red-700 disabled:opacity-50 dark:bg-red-500 dark:hover:bg-red-400 dark:active:bg-red-400"
|
||||
>
|
||||
{banSubmitting ? 'Wird gesperrt…' : 'Sperren'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Toast -->
|
||||
{#if toast}
|
||||
<div class="fixed bottom-24 left-1/2 z-50 -translate-x-1/2 rounded-full bg-gray-900 px-5 py-2.5 text-sm text-white shadow-lg dark:bg-gray-100 dark:text-gray-900">
|
||||
{toast}
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<div class="min-h-screen bg-gray-50 pb-24 dark:bg-gray-950">
|
||||
<!-- Header -->
|
||||
@@ -308,7 +288,7 @@
|
||||
|
||||
<div class="mx-auto max-w-3xl space-y-3 p-4">
|
||||
{#if loading}
|
||||
<div class="py-16 text-center text-gray-400 dark:text-gray-500">Laden…</div>
|
||||
<div class="py-16 text-center text-gray-500 dark:text-gray-400">Laden…</div>
|
||||
{:else if error}
|
||||
<div class="rounded-lg bg-red-50 p-4 text-sm text-red-700 dark:bg-red-950/30 dark:text-red-300">{error}</div>
|
||||
{:else if event}
|
||||
@@ -321,7 +301,7 @@
|
||||
>
|
||||
<h2 class="font-semibold text-gray-900 dark:text-gray-100">Statistiken</h2>
|
||||
<svg
|
||||
class="h-5 w-5 text-gray-400 dark:text-gray-500 transition-transform duration-200 {statsOpen ? 'rotate-180' : ''}"
|
||||
class="h-5 w-5 text-gray-500 dark:text-gray-400 transition-transform duration-200 {statsOpen ? 'rotate-180' : ''}"
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
|
||||
@@ -344,7 +324,7 @@
|
||||
<p class="mt-0.5 text-xs text-gray-500 dark:text-gray-400">Uploads</p>
|
||||
</div>
|
||||
<div class="rounded-xl bg-gray-50 p-4 text-center dark:bg-gray-900/60">
|
||||
<p class="text-2xl font-bold {event.export_released ? 'text-blue-600 dark:text-blue-400' : 'text-gray-400 dark:text-gray-500'}">
|
||||
<p class="text-2xl font-bold {event.export_released ? 'text-blue-600 dark:text-blue-400' : 'text-gray-500 dark:text-gray-400'}">
|
||||
{event.export_released ? 'Ja' : 'Nein'}
|
||||
</p>
|
||||
<p class="mt-0.5 text-xs text-gray-500 dark:text-gray-400">Freigegeben</p>
|
||||
@@ -361,7 +341,7 @@
|
||||
>
|
||||
<h2 class="font-semibold text-gray-900 dark:text-gray-100">Event-Einstellungen</h2>
|
||||
<svg
|
||||
class="h-5 w-5 text-gray-400 dark:text-gray-500 transition-transform duration-200 {settingsOpen ? 'rotate-180' : ''}"
|
||||
class="h-5 w-5 text-gray-500 dark:text-gray-400 transition-transform duration-200 {settingsOpen ? 'rotate-180' : ''}"
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
|
||||
@@ -396,7 +376,7 @@
|
||||
>
|
||||
<h2 class="font-semibold text-gray-900 dark:text-gray-100">Nutzerverwaltung</h2>
|
||||
<svg
|
||||
class="h-5 w-5 text-gray-400 dark:text-gray-500 transition-transform duration-200 {usersOpen ? 'rotate-180' : ''}"
|
||||
class="h-5 w-5 text-gray-500 dark:text-gray-400 transition-transform duration-200 {usersOpen ? 'rotate-180' : ''}"
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
|
||||
@@ -407,7 +387,7 @@
|
||||
<!-- Search -->
|
||||
<div class="px-4 py-3">
|
||||
<div class="flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 dark:border-gray-700 dark:bg-gray-900">
|
||||
<svg class="h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<svg class="h-4 w-4 shrink-0 text-gray-500 dark:text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
|
||||
</svg>
|
||||
<input
|
||||
@@ -419,7 +399,7 @@
|
||||
</div>
|
||||
</div>
|
||||
{#if filteredUsers.length === 0}
|
||||
<p class="px-5 py-8 text-center text-sm text-gray-400 dark:text-gray-500">Keine Treffer.</p>
|
||||
<p class="px-5 py-8 text-center text-sm text-gray-500 dark:text-gray-400">Keine Treffer.</p>
|
||||
{:else}
|
||||
<div class="divide-y divide-gray-100 dark:divide-gray-700">
|
||||
{#each filteredUsers as user}
|
||||
@@ -436,7 +416,7 @@
|
||||
<span class="rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700 dark:bg-red-900/40 dark:text-red-200">Gesperrt</span>
|
||||
{/if}
|
||||
</div>
|
||||
<p class="text-xs text-gray-400 dark:text-gray-500">
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400">
|
||||
{user.upload_count} Upload{user.upload_count !== 1 ? 's' : ''} · {formatBytes(user.total_upload_bytes)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { goto } from '$app/navigation';
|
||||
import { api, ApiError } from '$lib/api';
|
||||
import { setAuth } from '$lib/auth';
|
||||
import { focusTrap } from '$lib/actions/focus-trap';
|
||||
|
||||
let displayName = $state('');
|
||||
let error = $state('');
|
||||
@@ -84,6 +85,28 @@
|
||||
function goToFeed() {
|
||||
goto('/feed');
|
||||
}
|
||||
|
||||
function closePinModal() {
|
||||
// setAuth has already run on join success — the user is authenticated.
|
||||
// Closing the PIN reminder while leaving them on /join would render the
|
||||
// (already-completed) join form again. Honor the dismissal by routing
|
||||
// them where they actually want to be.
|
||||
showPinModal = false;
|
||||
goto('/feed');
|
||||
}
|
||||
|
||||
// Strip non-digits synchronously in the input handler so paste of "1234X"
|
||||
// never flashes the longer string. Auto-submits on the 4th digit so the
|
||||
// user doesn't have to chase the (now cosmetic) Anmelden button.
|
||||
function onRecoveryPinInput(e: Event) {
|
||||
const el = e.currentTarget as HTMLInputElement;
|
||||
const cleaned = el.value.replace(/\D/g, '').slice(0, 6);
|
||||
if (cleaned !== el.value) el.value = cleaned;
|
||||
recoveryPin = cleaned;
|
||||
if (recoveryPin.length === 6 && !recoveryLoading) {
|
||||
handleInlineRecover();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex min-h-screen items-center justify-center bg-gray-50 px-4 dark:bg-gray-950">
|
||||
@@ -106,9 +129,11 @@
|
||||
<form onsubmit={(e) => { e.preventDefault(); handleInlineRecover(); }}>
|
||||
<input
|
||||
type="text"
|
||||
bind:value={recoveryPin}
|
||||
placeholder="4-stelliger PIN"
|
||||
maxlength={4}
|
||||
value={recoveryPin}
|
||||
oninput={onRecoveryPinInput}
|
||||
aria-label="Wiederherstellungs-PIN"
|
||||
placeholder="6-stelliger PIN"
|
||||
maxlength={6}
|
||||
inputmode="numeric"
|
||||
pattern="[0-9]*"
|
||||
data-testid="recovery-pin-input"
|
||||
@@ -146,6 +171,7 @@
|
||||
<input
|
||||
type="text"
|
||||
bind:value={displayName}
|
||||
aria-label="Dein Name"
|
||||
placeholder="Dein Name"
|
||||
maxlength={50}
|
||||
data-testid="join-name-input"
|
||||
@@ -176,8 +202,14 @@
|
||||
|
||||
{#if showPinModal}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4" data-testid="pin-modal">
|
||||
<div class="w-full max-w-sm rounded-xl bg-white p-6 shadow-lg dark:bg-gray-900">
|
||||
<h2 class="mb-2 text-xl font-bold text-gray-900 dark:text-gray-100">Dein Wiederherstellungs-PIN</h2>
|
||||
<div
|
||||
class="w-full max-w-sm rounded-xl bg-white p-6 shadow-lg dark:bg-gray-900"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="pin-modal-title"
|
||||
use:focusTrap={{ onclose: closePinModal }}
|
||||
>
|
||||
<h2 id="pin-modal-title" class="mb-2 text-xl font-bold text-gray-900 dark:text-gray-100">Dein Wiederherstellungs-PIN</h2>
|
||||
<p class="mb-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
Merke dir diesen PIN! Du brauchst ihn, um dein Konto auf einem anderen Gerät wiederherzustellen.
|
||||
</p>
|
||||
@@ -187,7 +219,7 @@
|
||||
<button
|
||||
onclick={copyPin}
|
||||
data-testid="pin-copy"
|
||||
class="min-h-11 min-w-11 rounded-md bg-gray-200 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-300 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600"
|
||||
class="min-h-11 min-w-11 rounded-md bg-gray-200 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-300 active:bg-gray-300 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600 dark:active:bg-gray-600"
|
||||
>
|
||||
{copied ? 'Kopiert!' : 'Kopieren'}
|
||||
</button>
|
||||
@@ -196,10 +228,17 @@
|
||||
<button
|
||||
onclick={goToFeed}
|
||||
data-testid="continue-to-feed"
|
||||
class="w-full rounded-lg bg-blue-600 px-4 py-3 font-medium text-white transition hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400"
|
||||
class="mb-2 w-full rounded-lg bg-blue-600 px-4 py-3 font-medium text-white transition hover:bg-blue-700 active:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-400 dark:active:bg-blue-400"
|
||||
>
|
||||
Weiter zur Galerie
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={closePinModal}
|
||||
class="w-full rounded-lg py-2 text-sm text-gray-500 hover:text-gray-700 active:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 dark:active:text-gray-200"
|
||||
>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { api, ApiError } from '$lib/api';
|
||||
import { setAuth, getPin } from '$lib/auth';
|
||||
import { setAuth, getPin, getToken } from '$lib/auth';
|
||||
import { browser } from '$app/environment';
|
||||
|
||||
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) {
|
||||
window.history.back();
|
||||
return;
|
||||
}
|
||||
goto(getToken() ? '/feed' : '/join');
|
||||
}
|
||||
|
||||
let displayName = $state('');
|
||||
let pin = $state('');
|
||||
let error = $state('');
|
||||
@@ -26,6 +36,9 @@
|
||||
}>('/recover', { display_name: displayName.trim(), pin: pin.trim() });
|
||||
|
||||
setAuth(res.jwt, pin.trim(), res.user_id, displayName.trim());
|
||||
// Surface a welcome-back toast on /feed after navigation. sessionStorage
|
||||
// scopes the cue to the next page load so it doesn't replay on refresh.
|
||||
if (browser) sessionStorage.setItem('eventsnap_just_recovered', displayName.trim());
|
||||
goto('/feed');
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError) {
|
||||
@@ -37,10 +50,38 @@
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Strip non-digits synchronously in the input handler (not via $effect on
|
||||
// bind:value) so a paste of "1234X" doesn't flash the longer string between
|
||||
// the bind setting `pin` and the reactive cleanup reassigning it. Mutating
|
||||
// el.value before Svelte's next render means the field never displays the
|
||||
// invalid intermediate state.
|
||||
function onPinInput(e: Event) {
|
||||
const el = e.currentTarget as HTMLInputElement;
|
||||
const cleaned = el.value.replace(/\D/g, '').slice(0, 6);
|
||||
if (cleaned !== el.value) el.value = cleaned;
|
||||
pin = cleaned;
|
||||
if (pin.length === 6 && displayName.trim() && !loading) {
|
||||
handleRecover();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex min-h-screen items-center justify-center bg-gray-50 px-4 dark:bg-gray-950">
|
||||
<div class="w-full max-w-sm">
|
||||
<div class="flex min-h-screen flex-col bg-gray-50 px-4 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"
|
||||
>
|
||||
<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>
|
||||
</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>
|
||||
<p class="mb-6 text-center text-gray-600 dark:text-gray-400">Gib deinen Namen und deinen PIN ein.</p>
|
||||
|
||||
@@ -48,6 +89,7 @@
|
||||
<input
|
||||
type="text"
|
||||
bind:value={displayName}
|
||||
aria-label="Dein Name"
|
||||
placeholder="Dein Name"
|
||||
maxlength={50}
|
||||
data-testid="recover-name-input"
|
||||
@@ -55,9 +97,11 @@
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
bind:value={pin}
|
||||
placeholder="4-stelliger PIN"
|
||||
maxlength={4}
|
||||
value={pin}
|
||||
oninput={onPinInput}
|
||||
aria-label="Wiederherstellungs-PIN"
|
||||
placeholder="6-stelliger PIN"
|
||||
maxlength={6}
|
||||
inputmode="numeric"
|
||||
pattern="[0-9]*"
|
||||
data-testid="recover-pin-input"
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
import { get } from 'svelte/store';
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { quotaStore, refreshQuota } from '$lib/quota-store';
|
||||
import ConfirmSheet from '$lib/components/ConfirmSheet.svelte';
|
||||
import { vibrate } from '$lib/haptics';
|
||||
import type { PendingFile } from '$lib/pending-upload-store';
|
||||
|
||||
interface StagedFile extends PendingFile {
|
||||
@@ -17,6 +19,7 @@
|
||||
let caption = $state('');
|
||||
let submitting = $state(false);
|
||||
let captionEl: HTMLTextAreaElement;
|
||||
let discardConfirmOpen = $state(false);
|
||||
|
||||
const MAX_CAPTION_LENGTH = 2000;
|
||||
|
||||
@@ -66,6 +69,16 @@
|
||||
}
|
||||
|
||||
function cancel() {
|
||||
if (stagedFiles.length > 0 || caption.trim().length > 0) {
|
||||
discardConfirmOpen = true;
|
||||
return;
|
||||
}
|
||||
clearPending();
|
||||
goto('/feed');
|
||||
}
|
||||
|
||||
function confirmDiscard() {
|
||||
discardConfirmOpen = false;
|
||||
clearPending();
|
||||
goto('/feed');
|
||||
}
|
||||
@@ -74,6 +87,7 @@
|
||||
if (stagedFiles.length === 0 || submitting) return;
|
||||
if (caption.length > MAX_CAPTION_LENGTH) return;
|
||||
submitting = true;
|
||||
vibrate(10);
|
||||
const hashtagsString = captionTags.join(',');
|
||||
for (const sf of stagedFiles) {
|
||||
await addToQueue(sf.file, caption, hashtagsString);
|
||||
@@ -163,7 +177,7 @@
|
||||
</svg>
|
||||
<div>
|
||||
<p class="font-medium text-gray-500 dark:text-gray-400">Keine Dateien ausgewählt</p>
|
||||
<p class="mt-1 text-sm text-gray-400 dark:text-gray-500">Geh zurück und tippe auf den Plus-Button.</p>
|
||||
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Geh zurück und tippe auf den Plus-Button.</p>
|
||||
</div>
|
||||
<button
|
||||
onclick={cancel}
|
||||
@@ -181,6 +195,7 @@
|
||||
bind:value={caption}
|
||||
maxlength={MAX_CAPTION_LENGTH}
|
||||
data-testid="upload-caption"
|
||||
aria-label="Beschreibung"
|
||||
placeholder="Beschreibung hinzufügen… (#hashtags möglich)"
|
||||
rows="4"
|
||||
class="w-full resize-none rounded-xl border border-gray-200 bg-gray-50 px-4 py-3 text-sm text-gray-900
|
||||
@@ -221,12 +236,29 @@
|
||||
style="width: {quotaPercent}%"
|
||||
></div>
|
||||
</div>
|
||||
{#if quotaPercent >= 100}
|
||||
<p class="mt-1 font-medium text-red-600 dark:text-red-400">Limit erreicht — bitte alte Beiträge löschen.</p>
|
||||
{:else if quotaPercent >= 95}
|
||||
<p class="mt-1 font-medium text-amber-600 dark:text-amber-400">Fast voll.</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="h-8"></div>
|
||||
</div>
|
||||
|
||||
<!-- Discard confirmation — appears only when the composer has unsaved content. -->
|
||||
<ConfirmSheet
|
||||
open={discardConfirmOpen}
|
||||
title="Verwerfen?"
|
||||
message="Deine Auswahl und der Text gehen verloren."
|
||||
confirmLabel="Verwerfen"
|
||||
cancelLabel="Weiter bearbeiten"
|
||||
tone="danger"
|
||||
onConfirm={confirmDiscard}
|
||||
onCancel={() => (discardConfirmOpen = false)}
|
||||
/>
|
||||
|
||||
<!-- Sticky submit button at bottom (mobile-primary) -->
|
||||
<div class="border-t border-gray-100 px-4 py-3 dark:border-gray-800">
|
||||
<button
|
||||
|
||||
Reference in New Issue
Block a user