diff --git a/.env.example b/.env.example index f0203d9..ce778bf 100644 --- a/.env.example +++ b/.env.example @@ -32,6 +32,9 @@ EVENT_SLUG=max-maria-2026 # ── Storage ─────────────────────────────────────────────────────────────────── MEDIA_PATH=/media +# Export archives (Gallery.zip / Memories.zip). MUST be outside MEDIA_PATH — +# /media is publicly served, so exports here would be downloadable without auth. +EXPORT_PATH=/exports # ── Upload limits ───────────────────────────────────────────────────────────── DEFAULT_MAX_IMAGE_SIZE_MB=20 diff --git a/.gitignore b/.gitignore index d03afd4..a34803d 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,9 @@ e2e/playwright-report/ e2e/test-results/ e2e/.cache/ e2e/.env.test +# Playwright artifacts when run from the repo root instead of e2e/ +/test-results/ +/playwright-report/ # OS .DS_Store diff --git a/backend/Dockerfile b/backend/Dockerfile index 3dc6159..4af576f 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -20,15 +20,17 @@ FROM alpine:3.21 RUN apk add --no-cache ca-certificates ffmpeg -# Run as a non-root user. Pre-create and chown the media mount path so the fresh -# named volume inherits the non-root ownership (Docker seeds an empty named volume -# from the image directory, preserving its uid/gid) and uploads can be written. +# Run as a non-root user. Pre-create and chown the media + export mount paths so +# the fresh named volumes inherit the non-root ownership (Docker seeds an empty +# named volume from the image directory, preserving its uid/gid) and uploads + +# export archives can be written. Exports live OUTSIDE /media on purpose so the +# public media ServeDir can't reach them. RUN addgroup -S app && adduser -S app -G app WORKDIR /app COPY --from=builder /app/target/release/eventsnap-backend ./ -RUN mkdir -p /media && chown -R app:app /app /media +RUN mkdir -p /media /exports && chown -R app:app /app /media /exports USER app EXPOSE 3000 diff --git a/backend/src/auth/middleware.rs b/backend/src/auth/middleware.rs index 17de8f8..d7051ae 100644 --- a/backend/src/auth/middleware.rs +++ b/backend/src/auth/middleware.rs @@ -13,6 +13,10 @@ pub struct AuthUser { pub user_id: Uuid, pub event_id: Uuid, pub role: UserRole, + /// Live ban flag. Banned users keep *read* access (per USER_JOURNEYS §10), so + /// the base extractor does NOT reject them — write handlers and the + /// Require{Host,Admin} extractors enforce the ban instead. + pub is_banned: bool, pub token_hash: String, } @@ -45,15 +49,13 @@ impl FromRequestParts for AuthUser { // Trust *live* DB state, not the JWT: a role/ban stored in the token would // survive a demote/ban for the full session lifetime (up to 30d). Re-read - // the user row so a demoted host loses host powers and a banned user is - // locked out immediately on their next request. + // the user row so a demoted host loses host powers immediately. We do NOT + // reject banned users here — they retain read access by design; writes and + // host/admin actions enforce the ban downstream. let user = crate::models::user::User::find_by_id(&state.pool, claims.sub) .await .map_err(|e| AppError::Internal(e.into()))? .ok_or_else(|| AppError::Unauthorized("Benutzer nicht gefunden.".into()))?; - if user.is_banned { - return Err(AppError::Forbidden("Dein Zugang wurde gesperrt.".into())); - } // Update last_seen_at in the background (fire-and-forget). Failures are // non-fatal but worth surfacing — silent swallowing hides DB connection @@ -70,6 +72,7 @@ impl FromRequestParts for AuthUser { user_id: user.id, event_id: user.event_id, role: user.role, + is_banned: user.is_banned, token_hash, }) } @@ -86,6 +89,9 @@ impl FromRequestParts for RequireHost { state: &AppState, ) -> Result { let auth = AuthUser::from_request_parts(parts, state).await?; + if auth.is_banned { + return Err(AppError::Forbidden("Du bist gesperrt.".into())); + } match auth.role { UserRole::Host | UserRole::Admin => Ok(Self(auth)), _ => Err(AppError::Forbidden("Nur für Hosts und Admins.".into())), @@ -104,6 +110,9 @@ impl FromRequestParts for RequireAdmin { state: &AppState, ) -> Result { let auth = AuthUser::from_request_parts(parts, state).await?; + if auth.is_banned { + return Err(AppError::Forbidden("Du bist gesperrt.".into())); + } match auth.role { UserRole::Admin => Ok(Self(auth)), _ => Err(AppError::Forbidden("Nur für Admins.".into())), diff --git a/backend/src/config.rs b/backend/src/config.rs index d35e8a7..3cffe02 100644 --- a/backend/src/config.rs +++ b/backend/src/config.rs @@ -56,7 +56,13 @@ pub struct AppConfig { pub event_name: String, pub event_slug: String, pub media_path: PathBuf, + /// Where export archives are written. MUST be outside `media_path` — that + /// directory is served by a public `ServeDir`, so a predictable archive name + /// under it would leak the whole gallery to anonymous visitors. + pub export_path: PathBuf, pub app_port: u16, + /// Number of concurrent media compression workers (read once at boot). + pub compression_concurrency: usize, } impl AppConfig { @@ -86,10 +92,18 @@ impl AppConfig { media_path: PathBuf::from( std::env::var("MEDIA_PATH").unwrap_or_else(|_| "/media".to_string()), ), + export_path: PathBuf::from( + std::env::var("EXPORT_PATH").unwrap_or_else(|_| "/exports".to_string()), + ), app_port: std::env::var("APP_PORT") .unwrap_or_else(|_| "3000".to_string()) .parse() .context("APP_PORT must be a number")?, + compression_concurrency: std::env::var("COMPRESSION_WORKER_CONCURRENCY") + .ok() + .and_then(|v| v.parse().ok()) + .filter(|&n| n >= 1) + .unwrap_or(2), }) } } diff --git a/backend/src/handlers/admin.rs b/backend/src/handlers/admin.rs index 987a1f0..f687255 100644 --- a/backend/src/handlers/admin.rs +++ b/backend/src/handlers/admin.rs @@ -121,15 +121,18 @@ pub async fn patch_config( // Numeric keys validated as f64; boolean keys validated as truthy strings; the // privacy note is free text. Splitting these explicitly is verbose but makes the // failure mode for typos obvious (`Unbekannter Schlüssel: ...`). - const NUMERIC_KEYS: &[&str] = &[ - "max_image_size_mb", - "max_video_size_mb", - "upload_rate_per_hour", - "feed_rate_per_min", - "export_rate_per_day", - "quota_tolerance", - "estimated_guest_count", - "compression_concurrency", + // (key, integer_only, min, max). Ranges reject values that `parse::` would + // accept but that silently revert to the hardcoded default at read time + // (get_usize/get_i64 can't parse negatives/NaN/fractionals). `compression_concurrency` + // is intentionally absent — it's read once at boot, so a live edit was a no-op. + const NUMERIC_SPECS: &[(&str, bool, f64, f64)] = &[ + ("max_image_size_mb", true, 1.0, 1024.0), + ("max_video_size_mb", true, 1.0, 10240.0), + ("upload_rate_per_hour", true, 1.0, 100_000.0), + ("feed_rate_per_min", true, 1.0, 100_000.0), + ("export_rate_per_day", true, 1.0, 100_000.0), + ("quota_tolerance", false, 0.0, 1.0), + ("estimated_guest_count", true, 1.0, 1_000_000.0), ]; const BOOL_KEYS: &[&str] = &[ "rate_limits_enabled", @@ -150,10 +153,26 @@ pub async fn patch_config( // update behind — validation must fully precede any write. for (key, value) in &body { let key_str = key.as_str(); - if NUMERIC_KEYS.contains(&key_str) { - if value.parse::().is_err() { + if let Some(&(_, integer_only, min, max)) = + NUMERIC_SPECS.iter().find(|(k, ..)| *k == key_str) + { + let n = value.trim().parse::().ok().filter(|n| n.is_finite()); + let n = match n { + Some(n) => n, + None => { + return Err(AppError::BadRequest(format!( + "Ungültiger Wert für {key}: muss eine Zahl sein." + ))) + } + }; + if integer_only && n.fract() != 0.0 { return Err(AppError::BadRequest(format!( - "Ungültiger Wert für {key}: muss eine Zahl sein." + "Ungültiger Wert für {key}: muss eine ganze Zahl sein." + ))); + } + if n < min || n > max { + return Err(AppError::BadRequest(format!( + "Wert für {key} liegt außerhalb des zulässigen Bereichs ({min}–{max})." ))); } } else if BOOL_KEYS.contains(&key_str) { @@ -282,7 +301,7 @@ pub async fn download_zip( )); } - let path = state.config.media_path.join("exports").join("Gallery.zip"); + let path = state.config.export_path.join("Gallery.zip"); if !path.exists() { return Err(AppError::NotFound("Exportdatei nicht gefunden.".into())); } @@ -308,7 +327,7 @@ pub async fn download_html( )); } - let path = state.config.media_path.join("exports").join("Memories.zip"); + let path = state.config.export_path.join("Memories.zip"); if !path.exists() { return Err(AppError::NotFound("Exportdatei nicht gefunden.".into())); } diff --git a/backend/src/handlers/host.rs b/backend/src/handlers/host.rs index 7994c9a..5fc4d1a 100644 --- a/backend/src/handlers/host.rs +++ b/backend/src/handlers/host.rs @@ -121,6 +121,15 @@ pub async fn ban_user( .execute(&state.pool) .await?; + // If we hid their uploads, evict them live from every feed + the diashow so a + // banned guest's content disappears without each viewer having to reload. + if body.hide_uploads { + let _ = state.sse_tx.send(SseEvent::new( + "user-hidden", + serde_json::json!({ "user_id": user_id }).to_string(), + )); + } + tracing::info!( actor_user_id = %auth.user_id, target_user_id = %user_id, @@ -329,6 +338,10 @@ pub async fn host_delete_comment( if !deleted { return Err(AppError::NotFound("Kommentar nicht gefunden.".into())); } + let _ = state.sse_tx.send(SseEvent::new( + "comment-deleted", + serde_json::json!({ "comment_id": comment_id }).to_string(), + )); tracing::info!( actor_user_id = %auth.user_id, event_id = %auth.event_id, @@ -380,19 +393,33 @@ pub async fn release_gallery( State(state): State, RequireHost(_auth): RequireHost, ) -> Result { + // Atomic claim: the conditional UPDATE is the sole gate, so two concurrent + // release calls can't both pass a check-then-set and double-enqueue exports. + // rows_affected == 0 means someone already released. + let result = sqlx::query( + "UPDATE event SET export_released_at = NOW() + WHERE slug = $1 AND export_released_at IS NULL", + ) + .bind(&state.config.event_slug) + .execute(&state.pool) + .await?; + if result.rows_affected() == 0 { + // Distinguish "no such event" from "already released" for a clean error. + let exists = Event::find_by_slug(&state.pool, &state.config.event_slug) + .await? + .is_some(); + return Err(if exists { + AppError::BadRequest("Galerie wurde bereits freigegeben.".into()) + } else { + AppError::NotFound("Event nicht gefunden.".into()) + }); + } + + // We won the claim — load the event for its id/name to enqueue export jobs. let event = Event::find_by_slug(&state.pool, &state.config.event_slug) .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())); - } - - sqlx::query("UPDATE event SET export_released_at = NOW() WHERE slug = $1") - .bind(&state.config.event_slug) - .execute(&state.pool) - .await?; - // Enqueue export jobs for export_type in ["zip", "html"] { sqlx::query( @@ -411,6 +438,7 @@ pub async fn release_gallery( event.name, state.pool.clone(), state.config.media_path.clone(), + state.config.export_path.clone(), state.sse_tx.clone(), ); diff --git a/backend/src/handlers/social.rs b/backend/src/handlers/social.rs index 168f6e0..c7a6621 100644 --- a/backend/src/handlers/social.rs +++ b/backend/src/handlers/social.rs @@ -199,6 +199,10 @@ pub async fn delete_comment( auth: AuthUser, Path(comment_id): Path, ) -> Result { + // Banned users keep read access but cannot mutate (USER_JOURNEYS §10). + if auth.is_banned { + return Err(AppError::Forbidden("Du bist gesperrt.".into())); + } let comment = Comment::find_by_id(&state.pool, comment_id) .await? .ok_or_else(|| AppError::NotFound("Kommentar nicht gefunden.".into()))?; @@ -213,5 +217,9 @@ pub async fn delete_comment( if !deleted { return Err(AppError::NotFound("Kommentar nicht gefunden.".into())); } + let _ = state.sse_tx.send(crate::state::SseEvent::new( + "comment-deleted", + serde_json::json!({ "comment_id": comment_id, "upload_id": comment.upload_id }).to_string(), + )); Ok(StatusCode::NO_CONTENT) } diff --git a/backend/src/handlers/sse.rs b/backend/src/handlers/sse.rs index ed63d05..394017b 100644 --- a/backend/src/handlers/sse.rs +++ b/backend/src/handlers/sse.rs @@ -48,10 +48,10 @@ pub async fn stream( .consume(&q.ticket) .ok_or_else(|| AppError::Unauthorized("Ticket ungültig oder abgelaufen.".into()))?; - // NOTE: this authenticates via ticket→session, not the `AuthUser` extractor, so - // it does not re-check `is_banned`. A user banned mid-stream keeps receiving - // events until the connection drops; they cannot reconnect (issue_ticket uses - // AuthUser, which rejects banned users). Documented in docs/SECURITY-BACKLOG.md. + // NOTE: this authenticates via ticket→session, not the `AuthUser` extractor. The + // SSE stream is read-only, and under the read-only-ban model (USER_JOURNEYS §10) + // banned users retain read access — so both minting a ticket and holding a stream + // open are intentionally allowed for banned users; only writes are blocked. Session::find_by_token_hash(&state.pool, &token_hash) .await .map_err(|e| AppError::Internal(e.into()))? diff --git a/backend/src/handlers/test_admin.rs b/backend/src/handlers/test_admin.rs index f3d0cc4..0d6b2e6 100644 --- a/backend/src/handlers/test_admin.rs +++ b/backend/src/handlers/test_admin.rs @@ -70,6 +70,12 @@ pub async fn truncate_all( let _ = tokio::fs::remove_dir_all(&state.config.media_path).await; let _ = tokio::fs::create_dir_all(&state.config.media_path).await; + // Wipe the export directory too. Exports moved OUT of media_path (CR2 fix), so + // the media wipe above no longer covers them — without this a real export in + // one test would leave Gallery.zip on disk and contaminate the next. + let _ = tokio::fs::remove_dir_all(&state.config.export_path).await; + let _ = tokio::fs::create_dir_all(&state.config.export_path).await; + // The rate limiter holds an in-memory HashMap; clear it so a previous test's // counters don't leak into the next one. state.rate_limiter.clear(); diff --git a/backend/src/handlers/upload.rs b/backend/src/handlers/upload.rs index f2043f6..29f05c9 100644 --- a/backend/src/handlers/upload.rs +++ b/backend/src/handlers/upload.rs @@ -272,6 +272,10 @@ pub async fn edit_upload( Path(upload_id): Path, Json(body): Json, ) -> Result { + // Banned users keep read access but cannot mutate (USER_JOURNEYS §10). + if auth.is_banned { + return Err(AppError::Forbidden("Du bist gesperrt.".into())); + } let upload = Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id) .await? .ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?; @@ -303,6 +307,10 @@ pub async fn delete_upload( auth: AuthUser, Path(upload_id): Path, ) -> Result { + // Banned users keep read access but cannot mutate (USER_JOURNEYS §10). + if auth.is_banned { + return Err(AppError::Forbidden("Du bist gesperrt.".into())); + } let upload = Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id) .await? .ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?; @@ -313,6 +321,14 @@ pub async fn delete_upload( Upload::soft_delete_in_event(&state.pool, upload_id, auth.event_id).await?; + // Evict the card live on every other feed + the projector diashow — otherwise + // a self-deleted post lingers until each viewer manually reloads. Same event + // the host-delete path already emits and the frontend already handles. + let _ = state.sse_tx.send(crate::state::SseEvent::new( + "upload-deleted", + serde_json::json!({ "upload_id": upload_id }).to_string(), + )); + Ok(StatusCode::NO_CONTENT) } diff --git a/backend/src/services/compression.rs b/backend/src/services/compression.rs index 504f278..44813c0 100644 --- a/backend/src/services/compression.rs +++ b/backend/src/services/compression.rs @@ -42,11 +42,28 @@ impl CompressionWorker { } Err(e) => { tracing::error!("compression failed for upload {upload_id}: {e:#}"); + // Auto-cleanup: a failed transcode would otherwise leave a + // permanently broken feed card, silently charge the uploader's + // quota, and orphan the original on disk. Refund + soft-delete + // (one tx, so v_feed excludes it), remove the orphan file, then + // tell the uploader (upload-error toast) and evict the card + // everywhere (upload-deleted, already handled by the feed). + let _ = Upload::set_compression_status(&worker.pool, upload_id, "failed").await; + if let Err(del) = Upload::soft_delete(&worker.pool, upload_id).await { + tracing::warn!(error = ?del, %upload_id, "failed to soft-delete after compression failure"); + } + let orphan = worker.media_path.join(&original_path); + if let Err(rm) = tokio::fs::remove_file(&orphan).await { + tracing::warn!(error = ?rm, path = %orphan.display(), "failed to remove orphaned original"); + } 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(), }); - let _ = Upload::set_compression_status(&worker.pool, upload_id, "failed").await; + let _ = worker.sse_tx.send(SseEvent { + event_type: "upload-deleted".to_string(), + data: serde_json::json!({ "upload_id": upload_id }).to_string(), + }); } } }); diff --git a/backend/src/services/export.rs b/backend/src/services/export.rs index 0665f16..ad908de 100644 --- a/backend/src/services/export.rs +++ b/backend/src/services/export.rs @@ -87,15 +87,17 @@ pub fn spawn_export_jobs( event_name: String, pool: PgPool, media_path: PathBuf, + export_path: PathBuf, sse_tx: broadcast::Sender, ) { let pool2 = pool.clone(); let media_path2 = media_path.clone(); + let export_path2 = export_path.clone(); let sse_tx2 = sse_tx.clone(); let event_name2 = event_name.clone(); 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, &pool, &media_path, &export_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 +106,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, &event_name2, &pool2, &media_path2, &export_path2, &sse_tx2).await { tracing::error!("HTML export failed for event {event_id}: {e:#}"); mark_failed(&pool2, event_id, "html", &e.to_string()).await; @@ -119,6 +121,7 @@ async fn run_zip_export( event_id: Uuid, pool: &PgPool, media_path: &Path, + export_path: &Path, sse_tx: &broadcast::Sender, ) -> Result<()> { mark_running(pool, event_id, "zip").await; @@ -126,7 +129,8 @@ async fn run_zip_export( let uploads = query_uploads(pool, event_id).await?; let total = uploads.len().max(1) as f32; - let exports_dir = media_path.join("exports"); + // Written OUTSIDE media_path: the public /media ServeDir must never reach these. + let exports_dir = export_path.to_path_buf(); tokio::fs::create_dir_all(&exports_dir).await?; let tmp_path = exports_dir.join("Gallery.zip.tmp"); @@ -193,6 +197,7 @@ async fn run_html_export( event_name: &str, pool: &PgPool, media_path: &Path, + export_path: &Path, sse_tx: &broadcast::Sender, ) -> Result<()> { mark_running(pool, event_id, "html").await; @@ -205,7 +210,8 @@ async fn run_html_export( update_progress(pool, event_id, "html", 5).await; - let exports_dir = media_path.join("exports"); + // Written OUTSIDE media_path: the public /media ServeDir must never reach these. + let exports_dir = export_path.to_path_buf(); tokio::fs::create_dir_all(&exports_dir).await?; // 2. Create temp directory for media processing diff --git a/backend/src/state.rs b/backend/src/state.rs index d4e3e05..7743bf4 100644 --- a/backend/src/state.rs +++ b/backend/src/state.rs @@ -36,8 +36,12 @@ pub struct AppState { 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()); + let compression = CompressionWorker::new( + pool.clone(), + config.media_path.clone(), + config.compression_concurrency, + sse_tx.clone(), + ); Self { pool, config, diff --git a/docker-compose.yml b/docker-compose.yml index 57f1fa7..6baec40 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -34,6 +34,9 @@ services: condition: service_healthy volumes: - media_data:/media + # Export archives live OUTSIDE /media so the public media ServeDir can't + # serve them — downloads go only through the ticket-gated handler. + - exports_data:/exports expose: - "3000" healthcheck: @@ -96,4 +99,5 @@ services: volumes: postgres_data: media_data: + exports_data: caddy_data: diff --git a/docs/SECURITY-BACKLOG.md b/docs/SECURITY-BACKLOG.md index cbb8ab4..e90ab40 100644 --- a/docs/SECURITY-BACKLOG.md +++ b/docs/SECURITY-BACKLOG.md @@ -64,8 +64,11 @@ decompression-bomb cap (`image::Limits` 12000×12000 / 256 MiB) lives in (not just the exact dev sentinel) and enforces `len ≥ 32` unconditionally in prod. - **Unspoofable client IP in the rate limiter** — `client_ip` now takes the right-most `X-Forwarded-For` entry (the hop Caddy appends), so a client-supplied left-most value is ignored. -- **Live role/ban re-check** — the auth extractor re-reads the user row and trusts the DB role and - `is_banned` flag rather than the JWT claim, revoking demoted/banned sessions immediately. +- **Live role/ban re-check** — the auth extractor re-reads the user row and trusts the DB `role` + and `is_banned` flag rather than the JWT claim, so a demote/ban takes effect immediately (no + 30-day token window). Bans are enforced on write handlers + the host/admin extractors, preserving + the documented read-only access for banned guests (USER_JOURNEYS §10); demoted hosts lose host + powers at once. - **Container healthchecks** — `app` and `frontend` now have healthchecks and Caddy waits on `service_healthy`. - **Event-scoped `ban_user`** — the ban UPDATE is now scoped by `event_id` like its siblings. diff --git a/docs/USER_JOURNEYS.md b/docs/USER_JOURNEYS.md index b69e989..6031d34 100644 --- a/docs/USER_JOURNEYS.md +++ b/docs/USER_JOURNEYS.md @@ -147,12 +147,18 @@ the Host can clean up later). ## 10. Banned-guest experience -1. The banned user's next authenticated request returns HTTP 403 with a clear message - ("Du bist gesperrt."). -2. They can still browse the read-only feed (and download the export once it's released). -3. They cannot upload, like, or comment. -4. If `hide_uploads` was set on the ban, their existing uploads are filtered out of the - feed for everyone (the `v_feed` view already enforces this). +1. The ban takes effect immediately on the banned user's existing session — the auth + layer re-reads the live `is_banned` flag on every request rather than trusting the + JWT, so there's no 30-day token-lifetime window. +2. Their next authenticated *write* request returns HTTP 403 with a clear message + ("Du bist gesperrt."). Ban enforcement lives on the write handlers and the + host/admin extractors, not the base auth extractor. +3. They can still browse the read-only feed (and download the export once it's released). +4. They cannot upload, like, or comment; a banned host also loses all host/admin + actions (including unbanning themselves). +5. If `hide_uploads` was set on the ban, their existing uploads are filtered out of the + feed for everyone (`v_feed` enforces this), and a live `user-hidden` SSE event evicts + their cards from every open feed + the diashow without a reload. ## 11. Admin — instance configuration diff --git a/e2e/Caddyfile.test b/e2e/Caddyfile.test index 84d505b..02fb85c 100644 --- a/e2e/Caddyfile.test +++ b/e2e/Caddyfile.test @@ -4,7 +4,17 @@ # of HTTPS/Let's Encrypt. :3101 { - encode zstd gzip + # Mirror prod: exclude the SSE stream from compression so buffering doesn't + # delay real-time events (and so the test stack exercises the real behavior). + @compressible not path /api/v1/stream + encode @compressible zstd gzip + + # Mirror prod's security headers (minus HSTS, which is HTTPS-only). + header { + X-Content-Type-Options "nosniff" + X-Frame-Options "DENY" + Referrer-Policy "strict-origin-when-cross-origin" + } reverse_proxy /api/* app:3000 reverse_proxy /media/* app:3000 diff --git a/e2e/helpers/seed.ts b/e2e/helpers/seed.ts index 5b97741..a243e2e 100644 --- a/e2e/helpers/seed.ts +++ b/e2e/helpers/seed.ts @@ -3,11 +3,26 @@ * flow. Centralising the API contract (routes, field names, expected statuses) * means an API change is a one-file edit, not a 7-file hunt. */ -import { uploadRaw, JPEG_MAGIC } from './upload-client'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { uploadRaw } from './upload-client'; import { db } from '../fixtures/db'; const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101'; +// A real, decodable JPEG. Magic-bytes-only fakes now get auto-cleaned by the +// backend when compression fails (a failed transcode refunds quota + deletes the +// row), which would delete the seeded upload out from under the test. Read lazily +// at call time (cwd is the e2e dir at runtime, like the gallery-path spec) so test +// collection can't trip on a module-load read. +let sampleJpg: Buffer | null = null; +function sampleImage(): Buffer { + if (!sampleJpg) { + sampleJpg = readFileSync(join(process.cwd(), 'fixtures', 'media', 'sample.jpg')); + } + return sampleJpg; +} + export type SeedUploadOptions = { caption?: string; /** Mark compression done so the card is fully rendered in the feed. Default true. */ @@ -16,9 +31,7 @@ export type SeedUploadOptions = { /** Seed a real, accepted upload owned by `jwt` and return its id. */ export async function seedUpload(jwt: string, opts: SeedUploadOptions = {}): Promise { - const body = new Uint8Array(1024); - body.set(JPEG_MAGIC, 0); - const res = await uploadRaw(jwt, body, { + const res = await uploadRaw(jwt, sampleImage(), { filename: 'a.jpg', contentType: 'image/jpeg', caption: opts.caption, diff --git a/e2e/specs/03-feed/comment-ui.spec.ts b/e2e/specs/03-feed/comment-ui.spec.ts new file mode 100644 index 0000000..f0d118e --- /dev/null +++ b/e2e/specs/03-feed/comment-ui.spec.ts @@ -0,0 +1,53 @@ +/** + * Regression for the review's CR1: the LightboxModal posted comments to + * `/upload/{id}/comment` (singular) while the only route is `/comments` (plural), + * so every comment submitted through the UI 404'd and was silently lost. The + * earlier "comment → SSE" spec passed by posting via a fetch helper, bypassing + * the component — a false green. This drives the real component end-to-end. + */ +import { test, expect } from '../../fixtures/test'; +import { seedUpload } from '../../helpers/seed'; + +const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101'; + +test.describe('Comments — UI round-trip (CR1)', () => { + test('a comment typed in the lightbox persists to the backend', async ({ + page, + guest, + signIn, + }) => { + const author = await guest('CommentAuthor'); + const commenter = await guest('Commenter'); + const uploadId = await seedUpload(author.jwt, { caption: 'Comment target' }); + + await signIn(page, commenter); + await page.goto('/feed'); + + // Open the lightbox. Only one upload exists, so the first open-button is it. + const imageButton = page.getByRole('button', { name: 'Bild vergrößern' }).first(); + await expect(imageButton).toBeVisible({ timeout: 15_000 }); + await imageButton.click(); + + const lightbox = page.locator('[role="dialog"][aria-labelledby="lightbox-title"]'); + await expect(lightbox).toBeVisible(); + + const text = `Wunderschönes Foto ${Date.now()}`; + await lightbox.getByPlaceholder(/kommentar/i).fill(text); + await lightbox.getByRole('button', { name: /senden/i }).click(); + + // The component appends the comment only on a 2xx — with the old singular path + // it threw and nothing appeared. Assert it's visible in the panel... + await expect(lightbox.getByText(text)).toBeVisible(); + + // ...and that it actually persisted server-side (the crux CR1 broke). + await expect + .poll(async () => { + const res = await fetch(`${BASE}/api/v1/upload/${uploadId}/comments`, { + headers: { Authorization: `Bearer ${commenter.jwt}` }, + }); + const body = await res.json(); + return Array.isArray(body) && body.some((c: { body: string }) => c.body === text); + }) + .toBe(true); + }); +}); diff --git a/e2e/specs/04-host/moderation.spec.ts b/e2e/specs/04-host/moderation.spec.ts index 13e0f74..a1a3e53 100644 --- a/e2e/specs/04-host/moderation.spec.ts +++ b/e2e/specs/04-host/moderation.spec.ts @@ -4,6 +4,7 @@ * coverage of the buttons lives in a separate UI-focused spec. */ import { test, expect } from '../../fixtures/test'; +import { seedUpload, seedComment } from '../../helpers/seed'; test.describe('Host — moderation API', () => { test('ban with hide_uploads=true sets the right flags', async ({ api, host, guest }) => { @@ -97,4 +98,59 @@ test.describe('Host — live role/ban revocation (H1)', () => { api.unbanUser(host.jwt, host.userId, { expectedStatus: [204] }) ).rejects.toThrow(/→ 403/); }); + + // H1 / USER_JOURNEYS §10: a banned user keeps *read* access but every write is + // rejected with 403. The ban is enforced on write handlers + Require{Host,Admin}, + // NOT in the base extractor (which would wrongly block reads too). + test('a banned user keeps read access but is blocked from writes', async ({ api, host, guest }) => { + const base = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101'; + const target = await guest('BannedRW'); + const auth = (jwt: string) => ({ Authorization: `Bearer ${jwt}` }); + + // Seed content the target OWNS *before* the ban, so the delete/edit paths get + // past the ownership check and it's genuinely the ban guard being exercised. + const ownUpload = await seedUpload(target.jwt, { caption: 'mine' }); + const ownComment = await seedComment(target.jwt, ownUpload, 'my comment'); + + await api.banUser(host.jwt, target.userId, false); + + // Reads still succeed. + const read = await fetch(base + '/api/v1/me/context', { headers: auth(target.jwt) }); + expect(read.status).toBe(200); + + // Every write is rejected — cover ALL guest-reachable mutations, not just + // /upload. delete_upload / delete_comment / edit_upload previously skipped the + // ban guard (a banned owner could still delete/edit their own content). + const create = await fetch(base + '/api/v1/upload', { + method: 'POST', + headers: auth(target.jwt), + body: new FormData(), + }); + expect(create.status).toBe(403); + + const delUpload = await fetch(base + `/api/v1/upload/${ownUpload}`, { + method: 'DELETE', + headers: auth(target.jwt), + }); + expect(delUpload.status).toBe(403); + + const editUpload = await fetch(base + `/api/v1/upload/${ownUpload}`, { + method: 'PATCH', + headers: { ...auth(target.jwt), 'Content-Type': 'application/json' }, + body: JSON.stringify({ caption: 'edited while banned' }), + }); + expect(editUpload.status).toBe(403); + + const delComment = await fetch(base + `/api/v1/comment/${ownComment}`, { + method: 'DELETE', + headers: auth(target.jwt), + }); + expect(delComment.status).toBe(403); + + // The upload survived every blocked write (still fetchable via the feed). + const feed = await fetch(base + '/api/v1/feed', { headers: auth(host.jwt) }); + const body = await feed.json(); + const rows = body.uploads ?? body.items ?? body; + expect(Array.isArray(rows) && rows.some((u: any) => u.id === ownUpload)).toBe(true); + }); }); diff --git a/e2e/specs/04-host/sse-eviction.spec.ts b/e2e/specs/04-host/sse-eviction.spec.ts new file mode 100644 index 0000000..a7f698c --- /dev/null +++ b/e2e/specs/04-host/sse-eviction.spec.ts @@ -0,0 +1,75 @@ +/** + * Regression for the review's H3: self-deleting an upload and banning a user with + * hide_uploads mutated visibility server-side but broadcast nothing, so the + * content lingered on every other viewer's feed (and the projector diashow) until + * a manual reload. Both now emit SSE so clients evict live. + */ +import { test, expect } from '../../fixtures/test'; +import { seedUpload } from '../../helpers/seed'; +import { SseListener } from '../../helpers/sse-listener'; + +const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101'; + +test.describe('Host — live SSE eviction (H3)', () => { + test('self-deleting an upload broadcasts upload-deleted', async ({ guest }) => { + const g = await guest('SelfDeleter'); + const uploadId = await seedUpload(g.jwt, { caption: 'delete me' }); + + const sse = new SseListener(); + await sse.start(g.jwt); + + const res = await fetch(`${BASE}/api/v1/upload/${uploadId}`, { + method: 'DELETE', + headers: { Authorization: `Bearer ${g.jwt}` }, + }); + expect(res.status).toBe(204); + + await sse.waitForEvent( + 'upload-deleted', + (e) => e.data.upload_id === uploadId + ); + }); + + test('banning a user with hide_uploads broadcasts user-hidden', async ({ + api, + host, + guest, + }) => { + const target = await guest('HideTarget'); + await seedUpload(target.jwt, { caption: 'should vanish' }); + + const sse = new SseListener(); + await sse.start(host.jwt); + + await api.banUser(host.jwt, target.userId, true); + + await sse.waitForEvent( + 'user-hidden', + (e) => e.data.user_id === target.userId + ); + }); + + // Frontend regression: the broadcasts above are inert if the client never + // registers the event name (the KNOWN_EVENTS gap that shipped both eviction + // handlers as dead code). Drive a real browser feed and assert LIVE eviction — + // this fails if 'user-hidden' is missing from KNOWN_EVENTS, unlike the + // backend-only SseListener checks above. + test('a hidden user is evicted from an open feed without reload (frontend)', async ({ + page, + api, + host, + guest, + signIn, + }) => { + const viewer = await guest('LiveEvictViewer'); + const target = await guest('LiveEvictTarget'); + await seedUpload(target.jwt, { caption: 'evict-me-live-xyz' }); + + await signIn(page, viewer); // lands on the event-wide /feed + await expect(page.getByText('evict-me-live-xyz').first()).toBeVisible(); + + // Host hides the target — the viewer's feed must drop the card via SSE, no reload. + await api.banUser(host.jwt, target.userId, true); + await expect(page.getByText('evict-me-live-xyz')).toHaveCount(0, { timeout: 15_000 }); + }); +}); diff --git a/e2e/specs/06-export/export-leak.spec.ts b/e2e/specs/06-export/export-leak.spec.ts new file mode 100644 index 0000000..4515d2a --- /dev/null +++ b/e2e/specs/06-export/export-leak.spec.ts @@ -0,0 +1,60 @@ +/** + * Regression for the review's CR2: export archives (Gallery.zip / Memories.zip) + * were written under media_path/exports, and /media is a public ServeDir — so + * anyone could GET /media/exports/Gallery.zip and download the whole gallery, + * bypassing the ticket + export_*_ready gate. Exports now live OUTSIDE media_path + * and are reachable only via the gated /api/v1/export/{zip,html} handlers. + * + * This drives a REAL export (release → job runs → archive on disk) and then + * asserts the archive is NOT public but IS gated. Asserting a 404 on an empty + * stack would pass even if exports were still under /media (the file just wouldn't + * exist yet) — so we produce a real file first, then prove it can't leak. + */ +import { test, expect } from '../../fixtures/test'; +import { seedUpload } from '../../helpers/seed'; + +const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101'; + +test.describe('Export — no public leak (CR2)', () => { + test('a real export is downloadable only via the gated endpoint, never via /media', async ({ + host, + }) => { + test.setTimeout(60_000); + const bearer = { Authorization: `Bearer ${host.jwt}` }; + + // Seed content so the archive actually contains a file. + await seedUpload(host.jwt, { caption: 'in the export' }); + + // Host releases the gallery → spawns the real zip/html export jobs. + const rel = await fetch(`${BASE}/api/v1/host/gallery/release`, { method: 'POST', headers: bearer }); + expect(rel.status).toBe(204); + + // Wait for the real zip job to finish writing the archive to disk. + await expect + .poll( + async () => { + const res = await fetch(`${BASE}/api/v1/export/status`, { headers: bearer }); + return (await res.json()).zip?.status; + }, + { timeout: 45_000, intervals: [500] } + ) + .toBe('done'); + + // The archive now EXISTS on disk. It must NOT be reachable via public /media… + for (const name of ['Gallery.zip', 'Memories.zip']) { + const leak = await fetch(`${BASE}/media/exports/${name}`); + // A 200 here = the whole-gallery archive is downloadable with no auth (CR2). + expect(leak.status, `${name} must not be served from public /media`).toBe(404); + } + + // …but IS retrievable via the gated single-use ticket endpoint. This proves the + // 404 above means "not public", not merely "no file was produced". + const ticketRes = await fetch(`${BASE}/api/v1/export/ticket`, { method: 'POST', headers: bearer }); + const { ticket } = await ticketRes.json(); + const dl = await fetch(`${BASE}/api/v1/export/zip?ticket=${encodeURIComponent(ticket)}`); + expect(dl.status).toBe(200); + // Real ZIP payload: the archive starts with the PK local-file-header magic. + const head = new Uint8Array(await dl.arrayBuffer()).subarray(0, 2); + expect(Array.from(head)).toEqual([0x50, 0x4b]); // "PK" + }); +}); diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index ee78d9c..76604ee 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -68,6 +68,9 @@ async function request( } if (!res.ok) { + // An expired/invalid token (401) clears the dead session. Banned users are + // NOT logged out — they keep read access by design (USER_JOURNEYS §10) and + // simply get a 403 "gesperrt" toast on writes. if (res.status === 401) { clearAuth(); } diff --git a/frontend/src/lib/auth.ts b/frontend/src/lib/auth.ts index 3b85167..252a35f 100644 --- a/frontend/src/lib/auth.ts +++ b/frontend/src/lib/auth.ts @@ -83,6 +83,9 @@ export function clearAuth(): void { if (!browser) return; localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(USER_ID_KEY); + // Clear the display name too — on a shared device the next user shouldn't see + // the previous guest's name pre-filled on /join. + localStorage.removeItem(DISPLAY_NAME_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 — diff --git a/frontend/src/lib/components/LightboxModal.svelte b/frontend/src/lib/components/LightboxModal.svelte index 7de599f..1c81612 100644 --- a/frontend/src/lib/components/LightboxModal.svelte +++ b/frontend/src/lib/components/LightboxModal.svelte @@ -2,6 +2,7 @@ import { onDestroy } from 'svelte'; import type { FeedUpload } from '$lib/types'; import { api } from '$lib/api'; + import { onSseEvent } from '$lib/sse'; import { getUserId } from '$lib/auth'; import { dataMode, pickMediaUrl } from '$lib/data-mode-store'; import { doubletap } from '$lib/actions/doubletap'; @@ -48,8 +49,18 @@ burstTimer = setTimeout(() => (heartBurst = false), 700); } + // Drop a comment live when it's deleted elsewhere (host moderation or the + // author on another device), so the open panel doesn't show a ghost comment. + const unsubCommentDeleted = onSseEvent('comment-deleted', (data) => { + try { + const { comment_id } = JSON.parse(data) as { comment_id: string }; + comments = comments.filter((c) => c.id !== comment_id); + } catch { /* ignore */ } + }); + onDestroy(() => { if (burstTimer) clearTimeout(burstTimer); + unsubCommentDeleted(); }); // Only refetch when a *different* upload is shown. The feed reassigns the @@ -74,7 +85,7 @@ if (!newComment.trim()) return; loading = true; try { - const comment = await api.post(`/upload/${upload.id}/comment`, { + const comment = await api.post(`/upload/${upload.id}/comments`, { body: newComment.trim() }); comments = [...comments, comment]; diff --git a/frontend/src/lib/diashow/queue.ts b/frontend/src/lib/diashow/queue.ts index 433110f..0b7db9a 100644 --- a/frontend/src/lib/diashow/queue.ts +++ b/frontend/src/lib/diashow/queue.ts @@ -73,6 +73,23 @@ export class SlideQueue { return { wasCurrent: currentId === id }; } + /** + * Remove every slide belonging to a user (banned with hide_uploads). Returns + * true if the current head was one of them so the caller advances immediately. + */ + removeByUser(userId: string, currentId: string | null): { wasCurrent: boolean } { + let wasCurrent = false; + for (const [id, slide] of this.allKnown) { + if (slide.user_id === userId) { + if (id === currentId) wasCurrent = true; + this.allKnown.delete(id); + } + } + this.liveQueue = this.liveQueue.filter((s) => s.user_id !== userId); + this.shuffleQueue = this.shuffleQueue.filter((s) => s.user_id !== userId); + return { wasCurrent }; + } + /** Look up a slide by id — for the diashow page to render the current slide. */ get(id: string): FeedUpload | undefined { return this.allKnown.get(id); diff --git a/frontend/src/lib/sse.ts b/frontend/src/lib/sse.ts index a5ca62f..1fc2fa7 100644 --- a/frontend/src/lib/sse.ts +++ b/frontend/src/lib/sse.ts @@ -38,6 +38,8 @@ const KNOWN_EVENTS = [ 'upload-deleted', 'like-update', 'new-comment', + 'comment-deleted', + 'user-hidden', 'event-closed', 'event-opened', 'event-updated', diff --git a/frontend/src/routes/admin/+page.svelte b/frontend/src/routes/admin/+page.svelte index eaa6b0d..85f3dfe 100644 --- a/frontend/src/routes/admin/+page.svelte +++ b/frontend/src/routes/admin/+page.svelte @@ -57,8 +57,9 @@ title: 'Limits & Größen', fields: [ { key: 'max_image_size_mb', label: 'Max. Bildgröße (MB)', kind: 'number' }, - { key: 'max_video_size_mb', label: 'Max. Videogröße (MB)', kind: 'number' }, - { key: 'compression_concurrency', label: 'Kompressions-Worker', kind: 'number' } + { key: 'max_video_size_mb', label: 'Max. Videogröße (MB)', kind: 'number' } + // compression_concurrency is set via COMPRESSION_WORKER_CONCURRENCY at + // boot, not live — omitted so it isn't a dead no-op control. ] }, { @@ -157,8 +158,22 @@ onMount(async () => { const token = getToken(); - const role = getRole(); - if (!token || role !== 'admin') { + if (!token) { + goto('/admin/login'); + return; + } + // Trust the *live* role, not the JWT claim: a mid-session demote leaves a + // stale 'admin' in the token, but the backend now 403s every admin call. + // Bounce a demoted admin to the feed instead of leaving them on a dashboard + // that errors on load (mirrors the host page). + try { + const ctx = await api.get<{ role: string }>('/me/context'); + if (ctx.role !== 'admin') { + goto('/feed'); + return; + } + } catch { + // Expired/invalid session (api.ts cleared it) — send them to re-auth. goto('/admin/login'); return; } diff --git a/frontend/src/routes/diashow/+page.svelte b/frontend/src/routes/diashow/+page.svelte index 87e25cd..37b1e67 100644 --- a/frontend/src/routes/diashow/+page.svelte +++ b/frontend/src/routes/diashow/+page.svelte @@ -99,6 +99,16 @@ } } + function handleUserHidden(data: string) { + try { + const payload = JSON.parse(data) as { user_id: string }; + const result = queue.removeByUser(payload.user_id, current?.id ?? null); + if (result.wasCurrent) advance(); + } catch { + // ignore + } + } + function revealOverlay() { showOverlay = true; if (overlayHideTimer) clearTimeout(overlayHideTimer); @@ -145,6 +155,7 @@ void acquireWakeLock(); unsubs.push(onSseEvent('upload-processed', handleUploadProcessed)); unsubs.push(onSseEvent('upload-deleted', handleUploadDeleted)); + unsubs.push(onSseEvent('user-hidden', handleUserHidden)); void loadInitial(); }); diff --git a/frontend/src/routes/feed/+page.svelte b/frontend/src/routes/feed/+page.svelte index f3ffdc3..4b731c5 100644 --- a/frontend/src/routes/feed/+page.svelte +++ b/frontend/src/routes/feed/+page.svelte @@ -27,6 +27,9 @@ let refreshing = $state(false); let pullProgress = $state(0); // 0–1+ during the drag, 0 when idle let selectedUpload = $state(null); + // Set when a truncated feed-delta means we missed too much to merge — shows a + // tap-to-refresh pill instead of yanking the user's scroll to page 1. + let feedStale = $state(false); let sentinel: HTMLDivElement; let feedObserver: IntersectionObserver | null = null; let inPlaceRefreshTimer: ReturnType | null = null; @@ -196,6 +199,28 @@ if (selectedUpload?.id === payload.upload_id) selectedUpload = null; } catch { /* ignore */ } }), + // A background transcode failed: the backend already cleaned up (refunded + // quota, removed the row) and an upload-deleted evicts the card. Only the + // uploader gets a toast — registered before upload-deleted so the card is + // still present to check ownership. + onSseEvent('upload-error', (data) => { + try { + const { upload_id } = JSON.parse(data) as { upload_id: string }; + const mine = uploads.find((u) => u.id === upload_id && u.user_id === myUserId); + if (mine) { + toast('Ein Upload konnte nicht verarbeitet werden.', 'error'); + void refreshQuota(); + } + } catch { /* ignore */ } + }), + // A banned user's uploads were hidden — drop all their cards live. + onSseEvent('user-hidden', (data) => { + try { + const { user_id } = JSON.parse(data) as { user_id: string }; + uploads = uploads.filter((u) => u.user_id !== user_id); + if (selectedUpload && selectedUpload.user_id === user_id) selectedUpload = null; + } catch { /* ignore */ } + }), // Patch the single affected card in place from the SSE payload instead of // refetching page 1 — a busy event fires these constantly and a full reload // would yank every scrolled-down user back to the top on each reaction. @@ -210,7 +235,9 @@ // Missed more than the backend delta cap while backgrounded — the // delta is only the newest slice, so merging would leave a silent gap // of older-but-still-new uploads. Resync from page 1 instead. - void loadFeed(true); + // Rather than involuntarily yank the user to page 1, surface a + // tap-to-refresh pill so they keep scroll until they resync. + feedStale = true; return; } if (delta.uploads.length) { @@ -290,6 +317,10 @@ } async function loadFeed(refresh = false) { + // Any full refresh (pill tap, pull-to-refresh, filter change) resyncs page 1, + // so the "new posts" pill is no longer relevant — clear it here rather than + // only in the pill's own onclick, or a pull-to-refresh leaves it stranded. + if (refresh) feedStale = false; try { const params = new URLSearchParams(); if (!refresh && nextCursor) params.set('cursor', nextCursor); @@ -440,6 +471,17 @@ {/if} + {#if feedStale} +
+ +
+ {/if}
diff --git a/frontend/src/routes/host/+page.svelte b/frontend/src/routes/host/+page.svelte index a68fd0e..16faa6e 100644 --- a/frontend/src/routes/host/+page.svelte +++ b/frontend/src/routes/host/+page.svelte @@ -2,6 +2,7 @@ import { goto } from '$app/navigation'; import { getToken, getRole } from '$lib/auth'; import { api } from '$lib/api'; + import type { MeContextDto } from '$lib/types'; import { onMount } from 'svelte'; import { toast, toastError } from '$lib/toast-store'; import ConfirmSheet from '$lib/components/ConfirmSheet.svelte'; @@ -86,8 +87,22 @@ onMount(async () => { const token = getToken(); - const role = getRole(); - if (!token || (role !== 'host' && role !== 'admin')) { + if (!token) { + goto('/join'); + return; + } + // Trust the *live* role, not the JWT claim: a mid-session demote leaves a + // stale 'host' in the token, but the backend now 403s every host call. Fetch + // the current role and bounce a demoted host to the feed instead of leaving + // them on a dashboard that errors on load. + try { + const ctx = await api.get('/me/context'); + if (ctx.role !== 'host' && ctx.role !== 'admin') { + goto('/feed'); + return; + } + } catch { + // Expired/invalid session (api.ts cleared it) — send them to re-auth. goto('/join'); return; }