Compare commits
12 Commits
5d21b3eefd
...
14c667c694
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14c667c694 | ||
|
|
3f6dafba05 | ||
|
|
0ed97f45cf | ||
|
|
b3d876fa85 | ||
|
|
80179357a7 | ||
|
|
dba4d3f932 | ||
|
|
239459bb91 | ||
|
|
41ac742af8 | ||
|
|
a084ba86c5 | ||
|
|
91ff961850 | ||
|
|
f08d858281 | ||
|
|
498b4e256b |
@@ -4,6 +4,10 @@ DOMAIN=my-event.example.com
|
|||||||
|
|
||||||
# ── App server ────────────────────────────────────────────────────────────────
|
# ── App server ────────────────────────────────────────────────────────────────
|
||||||
APP_PORT=3000
|
APP_PORT=3000
|
||||||
|
# Set to `production` in real deployments. This activates the secret guard that
|
||||||
|
# refuses to boot with placeholder JWT_SECRET / ADMIN_PASSWORD_HASH values.
|
||||||
|
# (docker-compose.yml already sets APP_ENV=production for the app service.)
|
||||||
|
APP_ENV=production
|
||||||
|
|
||||||
# ── Database ──────────────────────────────────────────────────────────────────
|
# ── Database ──────────────────────────────────────────────────────────────────
|
||||||
# Set a strong password and keep it in sync between DATABASE_URL and
|
# Set a strong password and keep it in sync between DATABASE_URL and
|
||||||
@@ -28,6 +32,9 @@ EVENT_SLUG=max-maria-2026
|
|||||||
|
|
||||||
# ── Storage ───────────────────────────────────────────────────────────────────
|
# ── Storage ───────────────────────────────────────────────────────────────────
|
||||||
MEDIA_PATH=/media
|
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 ─────────────────────────────────────────────────────────────
|
# ── Upload limits ─────────────────────────────────────────────────────────────
|
||||||
DEFAULT_MAX_IMAGE_SIZE_MB=20
|
DEFAULT_MAX_IMAGE_SIZE_MB=20
|
||||||
|
|||||||
45
.env.test
45
.env.test
@@ -1,45 +0,0 @@
|
|||||||
# ── Domain ────────────────────────────────────────────────────────────────────
|
|
||||||
# Public domain Caddy will serve and obtain a TLS certificate for.
|
|
||||||
DOMAIN=my-event.example.com
|
|
||||||
|
|
||||||
# ── App server ────────────────────────────────────────────────────────────────
|
|
||||||
APP_PORT=3000
|
|
||||||
|
|
||||||
# ── Database ──────────────────────────────────────────────────────────────────
|
|
||||||
DATABASE_URL=postgres://eventsnap:secret@db:5432/eventsnap
|
|
||||||
POSTGRES_USER=eventsnap
|
|
||||||
POSTGRES_PASSWORD=secret
|
|
||||||
POSTGRES_DB=eventsnap
|
|
||||||
|
|
||||||
# ── Authentication ────────────────────────────────────────────────────────────
|
|
||||||
# Generate with: openssl rand -hex 64
|
|
||||||
JWT_SECRET=change_me_to_a_random_64_byte_hex_string
|
|
||||||
SESSION_EXPIRY_DAYS=30
|
|
||||||
|
|
||||||
# Admin dashboard password (bcrypt hash).
|
|
||||||
# Generate with: htpasswd -bnBC 12 "" yourpassword | tr -d ':\n'
|
|
||||||
ADMIN_PASSWORD_HASH=$2y$12$placeholder_replace_me
|
|
||||||
|
|
||||||
# ── Event ─────────────────────────────────────────────────────────────────────
|
|
||||||
EVENT_NAME=Max & Maria's Wedding
|
|
||||||
EVENT_SLUG=max-maria-2026
|
|
||||||
|
|
||||||
# ── Storage ───────────────────────────────────────────────────────────────────
|
|
||||||
MEDIA_PATH=/media
|
|
||||||
|
|
||||||
# ── Upload limits ─────────────────────────────────────────────────────────────
|
|
||||||
DEFAULT_MAX_IMAGE_SIZE_MB=20
|
|
||||||
DEFAULT_MAX_VIDEO_SIZE_MB=500
|
|
||||||
|
|
||||||
# ── Rate limiting ─────────────────────────────────────────────────────────────
|
|
||||||
DEFAULT_UPLOAD_RATE_PER_HOUR=10
|
|
||||||
DEFAULT_FEED_RATE_PER_MIN=60
|
|
||||||
DEFAULT_EXPORT_RATE_PER_DAY=3
|
|
||||||
|
|
||||||
# ── Capacity ──────────────────────────────────────────────────────────────────
|
|
||||||
DEFAULT_ESTIMATED_GUEST_COUNT=100
|
|
||||||
# Fraction of total storage that triggers the "low storage" warning (0.0–1.0)
|
|
||||||
DEFAULT_QUOTA_TOLERANCE=0.75
|
|
||||||
|
|
||||||
# ── Workers ───────────────────────────────────────────────────────────────────
|
|
||||||
COMPRESSION_WORKER_CONCURRENCY=2
|
|
||||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -1,5 +1,7 @@
|
|||||||
# Environment secrets — never commit the real .env
|
# Environment secrets — never commit the real .env
|
||||||
.env
|
.env
|
||||||
|
# Stale local scratch copy of .env.example; nothing in the test stack reads it.
|
||||||
|
.env.test
|
||||||
|
|
||||||
# Rust
|
# Rust
|
||||||
backend/target/
|
backend/target/
|
||||||
@@ -20,6 +22,9 @@ e2e/playwright-report/
|
|||||||
e2e/test-results/
|
e2e/test-results/
|
||||||
e2e/.cache/
|
e2e/.cache/
|
||||||
e2e/.env.test
|
e2e/.env.test
|
||||||
|
# Playwright artifacts when run from the repo root instead of e2e/
|
||||||
|
/test-results/
|
||||||
|
/playwright-report/
|
||||||
|
|
||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
{$DOMAIN} {
|
{$DOMAIN} {
|
||||||
encode zstd gzip
|
# Compress everything EXCEPT the SSE stream — gzip buffering delays
|
||||||
|
# "real-time" likes/comments until the ~30s keep-alive tick.
|
||||||
|
@compressible not path /api/v1/stream
|
||||||
|
encode @compressible zstd gzip
|
||||||
|
|
||||||
# Site-wide security headers (defense-in-depth). HSTS is free since Caddy
|
# Site-wide security headers (defense-in-depth). HSTS is free since Caddy
|
||||||
# already terminates TLS. nosniff also covers all of /media/*.
|
# already terminates TLS. nosniff also covers all of /media/*.
|
||||||
|
|||||||
@@ -94,9 +94,9 @@ eventsnap/
|
|||||||
### Deploy on a fresh VPS
|
### Deploy on a fresh VPS
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 1. Clone the repository
|
# 1. Clone the repository (into a lowercase dir, matching the paths used below)
|
||||||
git clone https://git.mc02.dev/fabi/EventSnap.git
|
git clone https://git.mc02.dev/fabi/EventSnap.git eventsnap
|
||||||
cd EventSnap
|
cd eventsnap
|
||||||
|
|
||||||
# 2. Configure environment
|
# 2. Configure environment
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
@@ -108,6 +108,8 @@ docker compose up -d
|
|||||||
|
|
||||||
Caddy automatically obtains a Let's Encrypt certificate on first start. The app is live at `https://DOMAIN` within ~30 seconds.
|
Caddy automatically obtains a Let's Encrypt certificate on first start. The app is live at `https://DOMAIN` within ~30 seconds.
|
||||||
|
|
||||||
|
> **If the site never comes up:** with `APP_ENV=production` the backend **refuses to boot** while `JWT_SECRET`/`ADMIN_PASSWORD_HASH` still hold the `.env.example` placeholders (this is deliberate — a publicly-known signing key is worse than downtime). Caddy then waits on the unhealthy `app` container and never serves. Check `docker compose logs app` — a "Refusing to start … placeholder …" line means you skipped step 2. Rotate the secrets (see below) and restart.
|
||||||
|
|
||||||
> **Production note:** `docker compose up -d` does **not** expose the database — Postgres is reachable only on the internal Docker network. For local development where you need host access to Postgres, opt into the dev overlay explicitly:
|
> **Production note:** `docker compose up -d` does **not** expose the database — Postgres is reachable only on the internal Docker network. For local development where you need host access to Postgres, opt into the dev overlay explicitly:
|
||||||
> ```bash
|
> ```bash
|
||||||
> docker compose -f docker-compose.yml -f docker-compose.dev.yml up
|
> docker compose -f docker-compose.yml -f docker-compose.dev.yml up
|
||||||
|
|||||||
@@ -20,15 +20,17 @@ FROM alpine:3.21
|
|||||||
|
|
||||||
RUN apk add --no-cache ca-certificates ffmpeg
|
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
|
# Run as a non-root user. Pre-create and chown the media + export mount paths so
|
||||||
# named volume inherits the non-root ownership (Docker seeds an empty named volume
|
# the fresh named volumes inherit the non-root ownership (Docker seeds an empty
|
||||||
# from the image directory, preserving its uid/gid) and uploads can be written.
|
# 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
|
RUN addgroup -S app && adduser -S app -G app
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=builder /app/target/release/eventsnap-backend ./
|
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
|
USER app
|
||||||
|
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
|
|||||||
3
backend/migrations/010_review_indexes.down.sql
Normal file
3
backend/migrations/010_review_indexes.down.sql
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
DROP INDEX IF EXISTS idx_comment_hashtag_hashtag;
|
||||||
|
DROP INDEX IF EXISTS idx_comment_user;
|
||||||
|
DROP INDEX IF EXISTS idx_upload_event_created_id;
|
||||||
17
backend/migrations/010_review_indexes.up.sql
Normal file
17
backend/migrations/010_review_indexes.up.sql
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
-- Composite feed index with an id tiebreaker so keyset pagination
|
||||||
|
-- (ORDER BY created_at DESC, id DESC) stays index-covered and stable when
|
||||||
|
-- multiple uploads share a created_at timestamp.
|
||||||
|
CREATE INDEX idx_upload_event_created_id
|
||||||
|
ON upload(event_id, created_at DESC, id DESC)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
-- A user's own comments (moderation, "who commented"). The sibling
|
||||||
|
-- idx_upload_user already exists for uploads; comment(user_id) was missing.
|
||||||
|
CREATE INDEX idx_comment_user
|
||||||
|
ON comment(user_id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
-- Hashtag filtering over comments — mirrors idx_upload_hashtag_hashtag, which
|
||||||
|
-- only covered upload_hashtag.
|
||||||
|
CREATE INDEX idx_comment_hashtag_hashtag
|
||||||
|
ON comment_hashtag(hashtag_id);
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use axum::extract::{FromRequestParts, State};
|
use axum::extract::FromRequestParts;
|
||||||
use axum::http::request::Parts;
|
use axum::http::request::Parts;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
@@ -13,6 +13,10 @@ pub struct AuthUser {
|
|||||||
pub user_id: Uuid,
|
pub user_id: Uuid,
|
||||||
pub event_id: Uuid,
|
pub event_id: Uuid,
|
||||||
pub role: UserRole,
|
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,
|
pub token_hash: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,6 +47,16 @@ impl FromRequestParts<AppState> for AuthUser {
|
|||||||
.map_err(|e| AppError::Internal(e.into()))?
|
.map_err(|e| AppError::Internal(e.into()))?
|
||||||
.ok_or_else(|| AppError::Unauthorized("Sitzung nicht gefunden oder abgelaufen.".into()))?;
|
.ok_or_else(|| AppError::Unauthorized("Sitzung nicht gefunden oder abgelaufen.".into()))?;
|
||||||
|
|
||||||
|
// 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 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()))?;
|
||||||
|
|
||||||
// Update last_seen_at in the background (fire-and-forget). Failures are
|
// Update last_seen_at in the background (fire-and-forget). Failures are
|
||||||
// non-fatal but worth surfacing — silent swallowing hides DB connection
|
// non-fatal but worth surfacing — silent swallowing hides DB connection
|
||||||
// pressure that would otherwise be the first symptom of a real problem.
|
// pressure that would otherwise be the first symptom of a real problem.
|
||||||
@@ -55,9 +69,10 @@ impl FromRequestParts<AppState> for AuthUser {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
user_id: claims.sub,
|
user_id: user.id,
|
||||||
event_id: claims.event_id,
|
event_id: user.event_id,
|
||||||
role: claims.role,
|
role: user.role,
|
||||||
|
is_banned: user.is_banned,
|
||||||
token_hash,
|
token_hash,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -74,6 +89,9 @@ impl FromRequestParts<AppState> for RequireHost {
|
|||||||
state: &AppState,
|
state: &AppState,
|
||||||
) -> Result<Self, Self::Rejection> {
|
) -> Result<Self, Self::Rejection> {
|
||||||
let auth = AuthUser::from_request_parts(parts, state).await?;
|
let auth = AuthUser::from_request_parts(parts, state).await?;
|
||||||
|
if auth.is_banned {
|
||||||
|
return Err(AppError::Forbidden("Du bist gesperrt.".into()));
|
||||||
|
}
|
||||||
match auth.role {
|
match auth.role {
|
||||||
UserRole::Host | UserRole::Admin => Ok(Self(auth)),
|
UserRole::Host | UserRole::Admin => Ok(Self(auth)),
|
||||||
_ => Err(AppError::Forbidden("Nur für Hosts und Admins.".into())),
|
_ => Err(AppError::Forbidden("Nur für Hosts und Admins.".into())),
|
||||||
@@ -92,6 +110,9 @@ impl FromRequestParts<AppState> for RequireAdmin {
|
|||||||
state: &AppState,
|
state: &AppState,
|
||||||
) -> Result<Self, Self::Rejection> {
|
) -> Result<Self, Self::Rejection> {
|
||||||
let auth = AuthUser::from_request_parts(parts, state).await?;
|
let auth = AuthUser::from_request_parts(parts, state).await?;
|
||||||
|
if auth.is_banned {
|
||||||
|
return Err(AppError::Forbidden("Du bist gesperrt.".into()));
|
||||||
|
}
|
||||||
match auth.role {
|
match auth.role {
|
||||||
UserRole::Admin => Ok(Self(auth)),
|
UserRole::Admin => Ok(Self(auth)),
|
||||||
_ => Err(AppError::Forbidden("Nur für Admins.".into())),
|
_ => Err(AppError::Forbidden("Nur für Admins.".into())),
|
||||||
|
|||||||
@@ -6,6 +6,47 @@ use anyhow::{anyhow, Context, Result};
|
|||||||
/// we refuse to start with this value; otherwise we warn loudly.
|
/// we refuse to start with this value; otherwise we warn loudly.
|
||||||
const DEV_JWT_SECRET_SENTINEL: &str = "dev_secret_do_not_use_in_production_32byteslong_aaaa";
|
const DEV_JWT_SECRET_SENTINEL: &str = "dev_secret_do_not_use_in_production_32byteslong_aaaa";
|
||||||
|
|
||||||
|
/// A secret is "placeholder-ish" if it's the shipped dev sentinel or still carries
|
||||||
|
/// the tell-tale scaffolding substrings from `.env.example`. Length alone is not
|
||||||
|
/// enough — the shipped `change_me_...` placeholder is >32 chars.
|
||||||
|
fn looks_placeholder(s: &str) -> bool {
|
||||||
|
let lower = s.to_ascii_lowercase();
|
||||||
|
s == DEV_JWT_SECRET_SENTINEL
|
||||||
|
|| lower.contains("change_me")
|
||||||
|
|| lower.contains("dev_secret")
|
||||||
|
|| lower.contains("placeholder")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enforce secret hygiene. In production every guard is hard-fail: a booting app
|
||||||
|
/// with a publicly-known signing key is worse than one that refuses to start.
|
||||||
|
/// Outside production the dev sentinel is tolerated (warned) so local dev is frictionless.
|
||||||
|
fn validate_secrets(is_prod: bool, jwt_secret: &str, admin_password_hash: &str) -> Result<()> {
|
||||||
|
if is_prod {
|
||||||
|
if looks_placeholder(jwt_secret) {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"Refusing to start in production with a placeholder JWT_SECRET — \
|
||||||
|
rotate it (openssl rand -hex 64)."
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if jwt_secret.len() < 32 {
|
||||||
|
return Err(anyhow!("JWT_SECRET must be at least 32 characters."));
|
||||||
|
}
|
||||||
|
if admin_password_hash.is_empty() || looks_placeholder(admin_password_hash) {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"Refusing to start in production without a real ADMIN_PASSWORD_HASH — \
|
||||||
|
generate one (htpasswd -bnBC 12 '' <password> | tr -d ':\\n')."
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else if jwt_secret == DEV_JWT_SECRET_SENTINEL {
|
||||||
|
tracing::warn!(
|
||||||
|
"JWT_SECRET is the dev sentinel — fine for local development, NEVER ship this."
|
||||||
|
);
|
||||||
|
} else if jwt_secret.len() < 32 {
|
||||||
|
return Err(anyhow!("JWT_SECRET must be at least 32 characters."));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct AppConfig {
|
pub struct AppConfig {
|
||||||
pub database_url: String,
|
pub database_url: String,
|
||||||
@@ -15,7 +56,13 @@ pub struct AppConfig {
|
|||||||
pub event_name: String,
|
pub event_name: String,
|
||||||
pub event_slug: String,
|
pub event_slug: String,
|
||||||
pub media_path: PathBuf,
|
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,
|
pub app_port: u16,
|
||||||
|
/// Number of concurrent media compression workers (read once at boot).
|
||||||
|
pub compression_concurrency: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppConfig {
|
impl AppConfig {
|
||||||
@@ -25,19 +72,9 @@ impl AppConfig {
|
|||||||
let is_prod = app_env.eq_ignore_ascii_case("production");
|
let is_prod = app_env.eq_ignore_ascii_case("production");
|
||||||
|
|
||||||
let jwt_secret = std::env::var("JWT_SECRET").context("JWT_SECRET must be set")?;
|
let jwt_secret = std::env::var("JWT_SECRET").context("JWT_SECRET must be set")?;
|
||||||
if jwt_secret == DEV_JWT_SECRET_SENTINEL {
|
let admin_password_hash = std::env::var("ADMIN_PASSWORD_HASH").unwrap_or_default();
|
||||||
if is_prod {
|
|
||||||
return Err(anyhow!(
|
validate_secrets(is_prod, &jwt_secret, &admin_password_hash)?;
|
||||||
"Refusing to start in production with the well-known dev JWT_SECRET — \
|
|
||||||
rotate it (openssl rand -hex 64)."
|
|
||||||
));
|
|
||||||
}
|
|
||||||
tracing::warn!(
|
|
||||||
"JWT_SECRET is the dev sentinel — fine for local development, NEVER ship this."
|
|
||||||
);
|
|
||||||
} else if jwt_secret.len() < 32 {
|
|
||||||
return Err(anyhow!("JWT_SECRET must be at least 32 characters."));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
database_url: std::env::var("DATABASE_URL")
|
database_url: std::env::var("DATABASE_URL")
|
||||||
@@ -47,8 +84,7 @@ impl AppConfig {
|
|||||||
.unwrap_or_else(|_| "30".to_string())
|
.unwrap_or_else(|_| "30".to_string())
|
||||||
.parse()
|
.parse()
|
||||||
.context("SESSION_EXPIRY_DAYS must be a number")?,
|
.context("SESSION_EXPIRY_DAYS must be a number")?,
|
||||||
admin_password_hash: std::env::var("ADMIN_PASSWORD_HASH")
|
admin_password_hash,
|
||||||
.unwrap_or_default(),
|
|
||||||
event_name: std::env::var("EVENT_NAME")
|
event_name: std::env::var("EVENT_NAME")
|
||||||
.unwrap_or_else(|_| "EventSnap".to_string()),
|
.unwrap_or_else(|_| "EventSnap".to_string()),
|
||||||
event_slug: std::env::var("EVENT_SLUG")
|
event_slug: std::env::var("EVENT_SLUG")
|
||||||
@@ -56,10 +92,80 @@ impl AppConfig {
|
|||||||
media_path: PathBuf::from(
|
media_path: PathBuf::from(
|
||||||
std::env::var("MEDIA_PATH").unwrap_or_else(|_| "/media".to_string()),
|
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")
|
app_port: std::env::var("APP_PORT")
|
||||||
.unwrap_or_else(|_| "3000".to_string())
|
.unwrap_or_else(|_| "3000".to_string())
|
||||||
.parse()
|
.parse()
|
||||||
.context("APP_PORT must be a number")?,
|
.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),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const REAL_SECRET: &str = "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2";
|
||||||
|
const REAL_HASH: &str = "$2y$12$abcdefghijklmnopqrstuv.wxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prod_rejects_shipped_placeholder_secret() {
|
||||||
|
// The exact string shipped in `.env` — >32 chars, so it must be caught by
|
||||||
|
// the substring guard, not the length check.
|
||||||
|
let err = validate_secrets(true, "change_me_to_a_random_64_byte_hex_string", REAL_HASH);
|
||||||
|
assert!(err.is_err(), "placeholder JWT_SECRET must be rejected in prod");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prod_rejects_dev_sentinel_and_short_secret() {
|
||||||
|
assert!(validate_secrets(true, DEV_JWT_SECRET_SENTINEL, REAL_HASH).is_err());
|
||||||
|
assert!(validate_secrets(true, "tooshort", REAL_HASH).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prod_rejects_missing_or_placeholder_admin_hash() {
|
||||||
|
assert!(validate_secrets(true, REAL_SECRET, "").is_err());
|
||||||
|
assert!(validate_secrets(true, REAL_SECRET, "$2y$12$placeholder_replace_me").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prod_accepts_real_secrets() {
|
||||||
|
assert!(validate_secrets(true, REAL_SECRET, REAL_HASH).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn non_prod_tolerates_dev_sentinel() {
|
||||||
|
assert!(validate_secrets(false, DEV_JWT_SECRET_SENTINEL, "").is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn non_prod_still_rejects_short_non_sentinel_secret() {
|
||||||
|
assert!(validate_secrets(false, "tooshort", "").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn placeholder_detection_is_case_insensitive() {
|
||||||
|
// looks_placeholder lowercases before matching — an upper/mixed-case
|
||||||
|
// placeholder must still be rejected in prod.
|
||||||
|
assert!(validate_secrets(true, "CHANGE_ME_TO_A_RANDOM_64_BYTE_HEX_STRING", REAL_HASH).is_err());
|
||||||
|
assert!(validate_secrets(true, REAL_SECRET, "$2Y$12$PLACEHOLDER_replace_me").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prod_len_boundary_at_32() {
|
||||||
|
// Exactly 32 non-placeholder chars is the minimum accepted; 31 is rejected.
|
||||||
|
const LEN_32: &str = "abcdefghijklmnopqrstuvwxyz012345";
|
||||||
|
const LEN_31: &str = "abcdefghijklmnopqrstuvwxyz01234";
|
||||||
|
assert_eq!(LEN_32.len(), 32);
|
||||||
|
assert_eq!(LEN_31.len(), 31);
|
||||||
|
assert!(validate_secrets(true, LEN_32, REAL_HASH).is_ok());
|
||||||
|
assert!(validate_secrets(true, LEN_31, REAL_HASH).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -121,15 +121,18 @@ pub async fn patch_config(
|
|||||||
// Numeric keys validated as f64; boolean keys validated as truthy strings; the
|
// 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
|
// privacy note is free text. Splitting these explicitly is verbose but makes the
|
||||||
// failure mode for typos obvious (`Unbekannter Schlüssel: ...`).
|
// failure mode for typos obvious (`Unbekannter Schlüssel: ...`).
|
||||||
const NUMERIC_KEYS: &[&str] = &[
|
// (key, integer_only, min, max). Ranges reject values that `parse::<f64>` would
|
||||||
"max_image_size_mb",
|
// accept but that silently revert to the hardcoded default at read time
|
||||||
"max_video_size_mb",
|
// (get_usize/get_i64 can't parse negatives/NaN/fractionals). `compression_concurrency`
|
||||||
"upload_rate_per_hour",
|
// is intentionally absent — it's read once at boot, so a live edit was a no-op.
|
||||||
"feed_rate_per_min",
|
const NUMERIC_SPECS: &[(&str, bool, f64, f64)] = &[
|
||||||
"export_rate_per_day",
|
("max_image_size_mb", true, 1.0, 1024.0),
|
||||||
"quota_tolerance",
|
("max_video_size_mb", true, 1.0, 10240.0),
|
||||||
"estimated_guest_count",
|
("upload_rate_per_hour", true, 1.0, 100_000.0),
|
||||||
"compression_concurrency",
|
("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] = &[
|
const BOOL_KEYS: &[&str] = &[
|
||||||
"rate_limits_enabled",
|
"rate_limits_enabled",
|
||||||
@@ -146,12 +149,30 @@ pub async fn patch_config(
|
|||||||
|
|
||||||
let mut privacy_note_changed = false;
|
let mut privacy_note_changed = false;
|
||||||
|
|
||||||
|
// Validate every key first so a bad value in the batch can't leave a partial
|
||||||
|
// update behind — validation must fully precede any write.
|
||||||
for (key, value) in &body {
|
for (key, value) in &body {
|
||||||
let key_str = key.as_str();
|
let key_str = key.as_str();
|
||||||
if NUMERIC_KEYS.contains(&key_str) {
|
if let Some(&(_, integer_only, min, max)) =
|
||||||
if value.parse::<f64>().is_err() {
|
NUMERIC_SPECS.iter().find(|(k, ..)| *k == key_str)
|
||||||
|
{
|
||||||
|
let n = value.trim().parse::<f64>().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!(
|
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) {
|
} else if BOOL_KEYS.contains(&key_str) {
|
||||||
@@ -164,7 +185,9 @@ pub async fn patch_config(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if TEXT_KEYS.contains(&key_str) {
|
} else if TEXT_KEYS.contains(&key_str) {
|
||||||
if value.len() > PRIVACY_NOTE_MAX_LEN {
|
// Count characters, not bytes — the message says "Zeichen" and a
|
||||||
|
// multi-byte grapheme shouldn't count against the limit multiple times.
|
||||||
|
if value.chars().count() > PRIVACY_NOTE_MAX_LEN {
|
||||||
return Err(AppError::BadRequest(format!(
|
return Err(AppError::BadRequest(format!(
|
||||||
"Wert für {key} ist zu lang (max. {PRIVACY_NOTE_MAX_LEN} Zeichen)."
|
"Wert für {key} ist zu lang (max. {PRIVACY_NOTE_MAX_LEN} Zeichen)."
|
||||||
)));
|
)));
|
||||||
@@ -177,16 +200,21 @@ pub async fn patch_config(
|
|||||||
"Unbekannter Konfigurationsschlüssel: {key}"
|
"Unbekannter Konfigurationsschlüssel: {key}"
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply all writes in one transaction — the batch is all-or-nothing.
|
||||||
|
let mut tx = state.pool.begin().await?;
|
||||||
|
for (key, value) in &body {
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO config (key, value, updated_at) VALUES ($1, $2, NOW())
|
"INSERT INTO config (key, value, updated_at) VALUES ($1, $2, NOW())
|
||||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()",
|
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()",
|
||||||
)
|
)
|
||||||
.bind(key)
|
.bind(key)
|
||||||
.bind(value)
|
.bind(value)
|
||||||
.execute(&state.pool)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
|
||||||
// Notify all clients that a publicly-readable config value changed so their stores
|
// Notify all clients that a publicly-readable config value changed so their stores
|
||||||
// (e.g. the privacy note in My Account) refresh without a manual reload.
|
// (e.g. the privacy note in My Account) refresh without a manual reload.
|
||||||
@@ -273,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() {
|
if !path.exists() {
|
||||||
return Err(AppError::NotFound("Exportdatei nicht gefunden.".into()));
|
return Err(AppError::NotFound("Exportdatei nicht gefunden.".into()));
|
||||||
}
|
}
|
||||||
@@ -299,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() {
|
if !path.exists() {
|
||||||
return Err(AppError::NotFound("Exportdatei nicht gefunden.".into()));
|
return Err(AppError::NotFound("Exportdatei nicht gefunden.".into()));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,6 +79,17 @@ pub async fn feed(
|
|||||||
|
|
||||||
let limit = q.limit.unwrap_or(20).min(100);
|
let limit = q.limit.unwrap_or(20).min(100);
|
||||||
|
|
||||||
|
// Resolve the cursor to a (created_at, id) position. The pair is compared as a
|
||||||
|
// tuple so ties on created_at break on id — keyset pagination on created_at
|
||||||
|
// alone would silently drop rows sharing a timestamp across a page boundary.
|
||||||
|
let (cursor_time, cursor_id) = match q.cursor {
|
||||||
|
Some(c) => match get_cursor_pos(&state.pool, c).await {
|
||||||
|
Some((t, id)) => (Some(t), Some(id)),
|
||||||
|
None => (None, None),
|
||||||
|
},
|
||||||
|
None => (None, None),
|
||||||
|
};
|
||||||
|
|
||||||
let rows = if let Some(hashtag) = &q.hashtag {
|
let rows = if let Some(hashtag) = &q.hashtag {
|
||||||
let tag = hashtag.trim().trim_start_matches('#').to_lowercase();
|
let tag = hashtag.trim().trim_start_matches('#').to_lowercase();
|
||||||
sqlx::query_as::<_, FeedRow>(
|
sqlx::query_as::<_, FeedRow>(
|
||||||
@@ -88,19 +99,14 @@ pub async fn feed(
|
|||||||
JOIN upload_hashtag uh ON uh.upload_id = v.id
|
JOIN upload_hashtag uh ON uh.upload_id = v.id
|
||||||
JOIN hashtag h ON h.id = uh.hashtag_id AND h.tag = $1
|
JOIN hashtag h ON h.id = uh.hashtag_id AND h.tag = $1
|
||||||
WHERE v.event_id = $2
|
WHERE v.event_id = $2
|
||||||
AND ($3::timestamptz IS NULL OR v.created_at < $3)
|
AND ($3::timestamptz IS NULL OR (v.created_at, v.id) < ($3, $4))
|
||||||
ORDER BY v.created_at DESC
|
ORDER BY v.created_at DESC, v.id DESC
|
||||||
LIMIT $4",
|
LIMIT $5",
|
||||||
)
|
)
|
||||||
.bind(&tag)
|
.bind(&tag)
|
||||||
.bind(auth.event_id)
|
.bind(auth.event_id)
|
||||||
.bind(
|
.bind(cursor_time)
|
||||||
if let Some(cursor) = q.cursor {
|
.bind(cursor_id)
|
||||||
get_cursor_time(&state.pool, cursor).await
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.bind(limit + 1)
|
.bind(limit + 1)
|
||||||
.fetch_all(&state.pool)
|
.fetch_all(&state.pool)
|
||||||
.await?
|
.await?
|
||||||
@@ -110,18 +116,13 @@ pub async fn feed(
|
|||||||
mime_type, caption, like_count, comment_count, created_at
|
mime_type, caption, like_count, comment_count, created_at
|
||||||
FROM v_feed
|
FROM v_feed
|
||||||
WHERE event_id = $1
|
WHERE event_id = $1
|
||||||
AND ($2::timestamptz IS NULL OR created_at < $2)
|
AND ($2::timestamptz IS NULL OR (created_at, id) < ($2, $3))
|
||||||
ORDER BY created_at DESC
|
ORDER BY created_at DESC, id DESC
|
||||||
LIMIT $3",
|
LIMIT $4",
|
||||||
)
|
)
|
||||||
.bind(auth.event_id)
|
.bind(auth.event_id)
|
||||||
.bind(
|
.bind(cursor_time)
|
||||||
if let Some(cursor) = q.cursor {
|
.bind(cursor_id)
|
||||||
get_cursor_time(&state.pool, cursor).await
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.bind(limit + 1)
|
.bind(limit + 1)
|
||||||
.fetch_all(&state.pool)
|
.fetch_all(&state.pool)
|
||||||
.await?
|
.await?
|
||||||
@@ -171,6 +172,11 @@ pub struct DeltaQuery {
|
|||||||
pub struct DeltaResponse {
|
pub struct DeltaResponse {
|
||||||
pub uploads: Vec<FeedUpload>,
|
pub uploads: Vec<FeedUpload>,
|
||||||
pub deleted_ids: Vec<Uuid>,
|
pub deleted_ids: Vec<Uuid>,
|
||||||
|
/// True when the upload query hit `DELTA_LIMIT`: the response carries only the
|
||||||
|
/// newest slice of the gap, so the client must fall back to a full feed refresh
|
||||||
|
/// rather than merging (the older missed uploads are absent and unrecoverable
|
||||||
|
/// via a later delta, which advances `since` past them).
|
||||||
|
pub truncated: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn feed_delta(
|
pub async fn feed_delta(
|
||||||
@@ -178,18 +184,28 @@ pub async fn feed_delta(
|
|||||||
auth: AuthUser,
|
auth: AuthUser,
|
||||||
Query(q): Query<DeltaQuery>,
|
Query(q): Query<DeltaQuery>,
|
||||||
) -> Result<Json<DeltaResponse>, AppError> {
|
) -> Result<Json<DeltaResponse>, AppError> {
|
||||||
|
// Bounded like the paginated feed: a stale `since` could otherwise pull the
|
||||||
|
// entire event's uploads in one response. If a client hits the cap it should
|
||||||
|
// fall back to a full feed refresh rather than another delta.
|
||||||
|
const DELTA_LIMIT: i64 = 200;
|
||||||
let rows = sqlx::query_as::<_, FeedRow>(
|
let rows = sqlx::query_as::<_, FeedRow>(
|
||||||
"SELECT id, user_id, uploader_name, preview_path, thumbnail_path,
|
"SELECT id, user_id, uploader_name, preview_path, thumbnail_path,
|
||||||
mime_type, caption, like_count, comment_count, created_at
|
mime_type, caption, like_count, comment_count, created_at
|
||||||
FROM v_feed
|
FROM v_feed
|
||||||
WHERE event_id = $1 AND created_at > $2
|
WHERE event_id = $1 AND created_at > $2
|
||||||
ORDER BY created_at DESC",
|
ORDER BY created_at DESC, id DESC
|
||||||
|
LIMIT $3",
|
||||||
)
|
)
|
||||||
.bind(auth.event_id)
|
.bind(auth.event_id)
|
||||||
.bind(q.since)
|
.bind(q.since)
|
||||||
|
.bind(DELTA_LIMIT)
|
||||||
.fetch_all(&state.pool)
|
.fetch_all(&state.pool)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
// Hit the cap => this is only the newest slice of a larger gap. Signal the
|
||||||
|
// client to full-refresh instead of merging a partial delta.
|
||||||
|
let truncated = rows.len() as i64 >= DELTA_LIMIT;
|
||||||
|
|
||||||
let deleted_ids: Vec<(Uuid,)> = sqlx::query_as(
|
let deleted_ids: Vec<(Uuid,)> = sqlx::query_as(
|
||||||
"SELECT id FROM upload
|
"SELECT id FROM upload
|
||||||
WHERE event_id = $1 AND deleted_at IS NOT NULL AND deleted_at > $2",
|
WHERE event_id = $1 AND deleted_at IS NOT NULL AND deleted_at > $2",
|
||||||
@@ -222,6 +238,7 @@ pub async fn feed_delta(
|
|||||||
Ok(Json(DeltaResponse {
|
Ok(Json(DeltaResponse {
|
||||||
uploads,
|
uploads,
|
||||||
deleted_ids: deleted_ids.into_iter().map(|r| r.0).collect(),
|
deleted_ids: deleted_ids.into_iter().map(|r| r.0).collect(),
|
||||||
|
truncated,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -249,14 +266,17 @@ pub async fn hashtags(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_cursor_time(pool: &sqlx::PgPool, cursor_id: Uuid) -> Option<DateTime<Utc>> {
|
/// Resolve a cursor id to its `(created_at, id)` position. Both are needed:
|
||||||
let row: Option<(DateTime<Utc>,)> =
|
/// `created_at` alone isn't unique, so pagination must break ties on `id` to
|
||||||
sqlx::query_as("SELECT created_at FROM upload WHERE id = $1")
|
/// avoid silently dropping rows that share a timestamp across a page boundary.
|
||||||
|
async fn get_cursor_pos(pool: &sqlx::PgPool, cursor_id: Uuid) -> Option<(DateTime<Utc>, Uuid)> {
|
||||||
|
let row: Option<(DateTime<Utc>, Uuid)> =
|
||||||
|
sqlx::query_as("SELECT created_at, id FROM upload WHERE id = $1")
|
||||||
.bind(cursor_id)
|
.bind(cursor_id)
|
||||||
.fetch_optional(pool)
|
.fetch_optional(pool)
|
||||||
.await
|
.await
|
||||||
.ok()?;
|
.ok()?;
|
||||||
row.map(|r| r.0)
|
row
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_liked_set(
|
async fn get_liked_set(
|
||||||
|
|||||||
@@ -113,13 +113,23 @@ pub async fn ban_user(
|
|||||||
}
|
}
|
||||||
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"UPDATE \"user\" SET is_banned = TRUE, uploads_hidden = $2 WHERE id = $1",
|
"UPDATE \"user\" SET is_banned = TRUE, uploads_hidden = $2 WHERE id = $1 AND event_id = $3",
|
||||||
)
|
)
|
||||||
.bind(user_id)
|
.bind(user_id)
|
||||||
.bind(body.hide_uploads)
|
.bind(body.hide_uploads)
|
||||||
|
.bind(auth.event_id)
|
||||||
.execute(&state.pool)
|
.execute(&state.pool)
|
||||||
.await?;
|
.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!(
|
tracing::info!(
|
||||||
actor_user_id = %auth.user_id,
|
actor_user_id = %auth.user_id,
|
||||||
target_user_id = %user_id,
|
target_user_id = %user_id,
|
||||||
@@ -263,7 +273,7 @@ pub async fn reset_user_pin(
|
|||||||
sqlx::query(
|
sqlx::query(
|
||||||
"UPDATE \"user\"
|
"UPDATE \"user\"
|
||||||
SET recovery_pin_hash = $1,
|
SET recovery_pin_hash = $1,
|
||||||
pin_failed_attempts = 0,
|
failed_pin_attempts = 0,
|
||||||
pin_locked_until = NULL
|
pin_locked_until = NULL
|
||||||
WHERE id = $2",
|
WHERE id = $2",
|
||||||
)
|
)
|
||||||
@@ -328,6 +338,10 @@ pub async fn host_delete_comment(
|
|||||||
if !deleted {
|
if !deleted {
|
||||||
return Err(AppError::NotFound("Kommentar nicht gefunden.".into()));
|
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!(
|
tracing::info!(
|
||||||
actor_user_id = %auth.user_id,
|
actor_user_id = %auth.user_id,
|
||||||
event_id = %auth.event_id,
|
event_id = %auth.event_id,
|
||||||
@@ -341,14 +355,18 @@ pub async fn close_event(
|
|||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
RequireHost(_auth): RequireHost,
|
RequireHost(_auth): RequireHost,
|
||||||
) -> Result<StatusCode, AppError> {
|
) -> Result<StatusCode, AppError> {
|
||||||
sqlx::query(
|
let result = sqlx::query(
|
||||||
"UPDATE event SET uploads_locked_at = NOW() WHERE slug = $1 AND uploads_locked_at IS NULL",
|
"UPDATE event SET uploads_locked_at = NOW() WHERE slug = $1 AND uploads_locked_at IS NULL",
|
||||||
)
|
)
|
||||||
.bind(&state.config.event_slug)
|
.bind(&state.config.event_slug)
|
||||||
.execute(&state.pool)
|
.execute(&state.pool)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let _ = state.sse_tx.send(SseEvent::new("event-closed", "{}"));
|
// Only broadcast when this call actually flipped the lock — closing an
|
||||||
|
// already-closed event is a no-op and shouldn't spam listeners.
|
||||||
|
if result.rows_affected() > 0 {
|
||||||
|
let _ = state.sse_tx.send(SseEvent::new("event-closed", "{}"));
|
||||||
|
}
|
||||||
|
|
||||||
Ok(StatusCode::NO_CONTENT)
|
Ok(StatusCode::NO_CONTENT)
|
||||||
}
|
}
|
||||||
@@ -357,14 +375,16 @@ pub async fn open_event(
|
|||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
RequireHost(_auth): RequireHost,
|
RequireHost(_auth): RequireHost,
|
||||||
) -> Result<StatusCode, AppError> {
|
) -> Result<StatusCode, AppError> {
|
||||||
sqlx::query(
|
let result = sqlx::query(
|
||||||
"UPDATE event SET uploads_locked_at = NULL WHERE slug = $1",
|
"UPDATE event SET uploads_locked_at = NULL WHERE slug = $1 AND uploads_locked_at IS NOT NULL",
|
||||||
)
|
)
|
||||||
.bind(&state.config.event_slug)
|
.bind(&state.config.event_slug)
|
||||||
.execute(&state.pool)
|
.execute(&state.pool)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let _ = state.sse_tx.send(SseEvent::new("event-opened", "{}"));
|
if result.rows_affected() > 0 {
|
||||||
|
let _ = state.sse_tx.send(SseEvent::new("event-opened", "{}"));
|
||||||
|
}
|
||||||
|
|
||||||
Ok(StatusCode::NO_CONTENT)
|
Ok(StatusCode::NO_CONTENT)
|
||||||
}
|
}
|
||||||
@@ -373,19 +393,33 @@ pub async fn release_gallery(
|
|||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
RequireHost(_auth): RequireHost,
|
RequireHost(_auth): RequireHost,
|
||||||
) -> Result<StatusCode, AppError> {
|
) -> Result<StatusCode, AppError> {
|
||||||
|
// 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)
|
let event = Event::find_by_slug(&state.pool, &state.config.event_slug)
|
||||||
.await?
|
.await?
|
||||||
.ok_or_else(|| AppError::NotFound("Event nicht gefunden.".into()))?;
|
.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
|
// Enqueue export jobs
|
||||||
for export_type in ["zip", "html"] {
|
for export_type in ["zip", "html"] {
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
@@ -404,6 +438,7 @@ pub async fn release_gallery(
|
|||||||
event.name,
|
event.name,
|
||||||
state.pool.clone(),
|
state.pool.clone(),
|
||||||
state.config.media_path.clone(),
|
state.config.media_path.clone(),
|
||||||
|
state.config.export_path.clone(),
|
||||||
state.sse_tx.clone(),
|
state.sse_tx.clone(),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,18 @@ use crate::models::hashtag::{self, Hashtag};
|
|||||||
use crate::models::upload::Upload;
|
use crate::models::upload::Upload;
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
|
|
||||||
|
/// Reject the request when the event's uploads (and, by extension, social
|
||||||
|
/// interaction) are locked. Mirrors the guard in the upload handler.
|
||||||
|
async fn require_event_open(state: &AppState) -> Result<(), AppError> {
|
||||||
|
let event = crate::models::event::Event::find_by_slug(&state.pool, &state.config.event_slug)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| AppError::NotFound("Event nicht gefunden.".into()))?;
|
||||||
|
if event.uploads_locked_at.is_some() {
|
||||||
|
return Err(AppError::Forbidden("Das Event ist geschlossen.".into()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn toggle_like(
|
pub async fn toggle_like(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
auth: AuthUser,
|
auth: AuthUser,
|
||||||
@@ -31,6 +43,9 @@ pub async fn toggle_like(
|
|||||||
.await?
|
.await?
|
||||||
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
||||||
|
|
||||||
|
// A closed event freezes social interaction too, matching the upload handler.
|
||||||
|
require_event_open(&state).await?;
|
||||||
|
|
||||||
// Try to insert; if conflict, delete (toggle)
|
// Try to insert; if conflict, delete (toggle)
|
||||||
let result = sqlx::query(
|
let result = sqlx::query(
|
||||||
"INSERT INTO \"like\" (upload_id, user_id) VALUES ($1, $2)
|
"INSERT INTO \"like\" (upload_id, user_id) VALUES ($1, $2)
|
||||||
@@ -120,6 +135,9 @@ pub async fn add_comment(
|
|||||||
.await?
|
.await?
|
||||||
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
||||||
|
|
||||||
|
// A closed event freezes social interaction too, matching the upload handler.
|
||||||
|
require_event_open(&state).await?;
|
||||||
|
|
||||||
let text = body.body.trim();
|
let text = body.body.trim();
|
||||||
let text_chars = text.chars().count();
|
let text_chars = text.chars().count();
|
||||||
if text_chars == 0 || text_chars > 500 {
|
if text_chars == 0 || text_chars > 500 {
|
||||||
@@ -128,20 +146,22 @@ pub async fn add_comment(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let comment = Comment::create(&state.pool, upload_id, auth.user_id, text).await?;
|
// Insert the comment and link its hashtags atomically, so a crash mid-loop
|
||||||
|
// can't leave a committed comment with only some of its tags indexed.
|
||||||
// Process hashtags in comment body
|
|
||||||
let tags = hashtag::extract_hashtags(text);
|
let tags = hashtag::extract_hashtags(text);
|
||||||
|
let mut tx = state.pool.begin().await?;
|
||||||
|
let comment = Comment::create(&mut *tx, upload_id, auth.user_id, text).await?;
|
||||||
for tag in &tags {
|
for tag in &tags {
|
||||||
let h = Hashtag::upsert(&state.pool, auth.event_id, tag).await?;
|
let h = Hashtag::upsert(&mut *tx, auth.event_id, tag).await?;
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO comment_hashtag (comment_id, hashtag_id) VALUES ($1, $2) ON CONFLICT DO NOTHING",
|
"INSERT INTO comment_hashtag (comment_id, hashtag_id) VALUES ($1, $2) ON CONFLICT DO NOTHING",
|
||||||
)
|
)
|
||||||
.bind(comment.id)
|
.bind(comment.id)
|
||||||
.bind(h.id)
|
.bind(h.id)
|
||||||
.execute(&state.pool)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
|
||||||
// Fresh count so feed clients can patch the single card in place instead of
|
// Fresh count so feed clients can patch the single card in place instead of
|
||||||
// refetching page 1 (mirrors v_feed.comment_count = COUNT(DISTINCT c.id); COUNT(*)
|
// refetching page 1 (mirrors v_feed.comment_count = COUNT(DISTINCT c.id); COUNT(*)
|
||||||
@@ -179,6 +199,10 @@ pub async fn delete_comment(
|
|||||||
auth: AuthUser,
|
auth: AuthUser,
|
||||||
Path(comment_id): Path<Uuid>,
|
Path(comment_id): Path<Uuid>,
|
||||||
) -> Result<StatusCode, AppError> {
|
) -> Result<StatusCode, AppError> {
|
||||||
|
// 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)
|
let comment = Comment::find_by_id(&state.pool, comment_id)
|
||||||
.await?
|
.await?
|
||||||
.ok_or_else(|| AppError::NotFound("Kommentar nicht gefunden.".into()))?;
|
.ok_or_else(|| AppError::NotFound("Kommentar nicht gefunden.".into()))?;
|
||||||
@@ -193,5 +217,9 @@ pub async fn delete_comment(
|
|||||||
if !deleted {
|
if !deleted {
|
||||||
return Err(AppError::NotFound("Kommentar nicht gefunden.".into()));
|
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)
|
Ok(StatusCode::NO_CONTENT)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,6 +48,10 @@ pub async fn stream(
|
|||||||
.consume(&q.ticket)
|
.consume(&q.ticket)
|
||||||
.ok_or_else(|| AppError::Unauthorized("Ticket ungültig oder abgelaufen.".into()))?;
|
.ok_or_else(|| AppError::Unauthorized("Ticket ungültig oder abgelaufen.".into()))?;
|
||||||
|
|
||||||
|
// 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)
|
Session::find_by_token_hash(&state.pool, &token_hash)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::Internal(e.into()))?
|
.map_err(|e| AppError::Internal(e.into()))?
|
||||||
|
|||||||
@@ -70,6 +70,12 @@ pub async fn truncate_all(
|
|||||||
let _ = tokio::fs::remove_dir_all(&state.config.media_path).await;
|
let _ = tokio::fs::remove_dir_all(&state.config.media_path).await;
|
||||||
let _ = tokio::fs::create_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
|
// The rate limiter holds an in-memory HashMap; clear it so a previous test's
|
||||||
// counters don't leak into the next one.
|
// counters don't leak into the next one.
|
||||||
state.rate_limiter.clear();
|
state.rate_limiter.clear();
|
||||||
|
|||||||
@@ -190,25 +190,6 @@ pub async fn upload(
|
|||||||
}
|
}
|
||||||
tokio::fs::write(&absolute_path, &data).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")
|
|
||||||
.bind(auth.user_id)
|
|
||||||
.bind(size)
|
|
||||||
.execute(&state.pool)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Insert upload record
|
|
||||||
let upload = Upload::create(
|
|
||||||
&state.pool,
|
|
||||||
auth.event_id,
|
|
||||||
auth.user_id,
|
|
||||||
&relative_path,
|
|
||||||
&mime,
|
|
||||||
size,
|
|
||||||
caption.as_deref(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Process hashtags from caption and explicit CSV
|
// Process hashtags from caption and explicit CSV
|
||||||
let mut tags: Vec<String> = Vec::new();
|
let mut tags: Vec<String> = Vec::new();
|
||||||
if let Some(ref cap) = caption {
|
if let Some(ref cap) = caption {
|
||||||
@@ -225,10 +206,30 @@ pub async fn upload(
|
|||||||
tags.sort();
|
tags.sort();
|
||||||
tags.dedup();
|
tags.dedup();
|
||||||
|
|
||||||
|
// Quota accounting, the upload row, and its hashtag links must be atomic: a
|
||||||
|
// crash between the bytes increment and the insert would permanently charge
|
||||||
|
// bytes with no row to reclaim them (silent quota erosion / spurious lockout).
|
||||||
|
let mut tx = state.pool.begin().await?;
|
||||||
|
sqlx::query("UPDATE \"user\" SET total_upload_bytes = total_upload_bytes + $2 WHERE id = $1")
|
||||||
|
.bind(auth.user_id)
|
||||||
|
.bind(size)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
let upload = Upload::create(
|
||||||
|
&mut *tx,
|
||||||
|
auth.event_id,
|
||||||
|
auth.user_id,
|
||||||
|
&relative_path,
|
||||||
|
&mime,
|
||||||
|
size,
|
||||||
|
caption.as_deref(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
for tag in &tags {
|
for tag in &tags {
|
||||||
let h = Hashtag::upsert(&state.pool, auth.event_id, tag).await?;
|
let h = Hashtag::upsert(&mut *tx, auth.event_id, tag).await?;
|
||||||
Hashtag::link_to_upload(&state.pool, upload.id, h.id).await?;
|
Hashtag::link_to_upload(&mut *tx, upload.id, h.id).await?;
|
||||||
}
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
|
||||||
// Spawn compression task
|
// Spawn compression task
|
||||||
state
|
state
|
||||||
@@ -271,6 +272,10 @@ pub async fn edit_upload(
|
|||||||
Path(upload_id): Path<Uuid>,
|
Path(upload_id): Path<Uuid>,
|
||||||
Json(body): Json<EditUploadRequest>,
|
Json(body): Json<EditUploadRequest>,
|
||||||
) -> Result<StatusCode, AppError> {
|
) -> Result<StatusCode, AppError> {
|
||||||
|
// 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)
|
let upload = Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id)
|
||||||
.await?
|
.await?
|
||||||
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
||||||
@@ -279,17 +284,20 @@ pub async fn edit_upload(
|
|||||||
return Err(AppError::Forbidden("Nur eigene Uploads bearbeiten.".into()));
|
return Err(AppError::Forbidden("Nur eigene Uploads bearbeiten.".into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Caption update + hashtag wipe-then-relink in one transaction, so a crash
|
||||||
|
// mid-relink can't leave the upload with its hashtags stripped.
|
||||||
|
let mut tx = state.pool.begin().await?;
|
||||||
if let Some(ref caption) = body.caption {
|
if let Some(ref caption) = body.caption {
|
||||||
Upload::update_caption(&state.pool, upload_id, Some(caption)).await?;
|
Upload::update_caption(&mut *tx, upload_id, Some(caption)).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(ref hashtags) = body.hashtags {
|
if let Some(ref hashtags) = body.hashtags {
|
||||||
Hashtag::unlink_all_from_upload(&state.pool, upload_id).await?;
|
Hashtag::unlink_all_from_upload(&mut *tx, upload_id).await?;
|
||||||
for tag in hashtags {
|
for tag in hashtags {
|
||||||
let h = Hashtag::upsert(&state.pool, auth.event_id, tag).await?;
|
let h = Hashtag::upsert(&mut *tx, auth.event_id, tag).await?;
|
||||||
Hashtag::link_to_upload(&state.pool, upload_id, h.id).await?;
|
Hashtag::link_to_upload(&mut *tx, upload_id, h.id).await?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
Ok(StatusCode::OK)
|
||||||
}
|
}
|
||||||
@@ -299,6 +307,10 @@ pub async fn delete_upload(
|
|||||||
auth: AuthUser,
|
auth: AuthUser,
|
||||||
Path(upload_id): Path<Uuid>,
|
Path(upload_id): Path<Uuid>,
|
||||||
) -> Result<StatusCode, AppError> {
|
) -> Result<StatusCode, AppError> {
|
||||||
|
// 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)
|
let upload = Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id)
|
||||||
.await?
|
.await?
|
||||||
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
||||||
@@ -309,6 +321,14 @@ pub async fn delete_upload(
|
|||||||
|
|
||||||
Upload::soft_delete_in_event(&state.pool, upload_id, auth.event_id).await?;
|
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)
|
Ok(StatusCode::NO_CONTENT)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,19 +24,24 @@ pub struct CommentDto {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Comment {
|
impl Comment {
|
||||||
pub async fn create(
|
/// Takes any executor so the caller can insert the comment and link its
|
||||||
pool: &PgPool,
|
/// hashtags inside a single transaction.
|
||||||
|
pub async fn create<'e, E>(
|
||||||
|
executor: E,
|
||||||
upload_id: Uuid,
|
upload_id: Uuid,
|
||||||
user_id: Uuid,
|
user_id: Uuid,
|
||||||
body: &str,
|
body: &str,
|
||||||
) -> Result<Self, sqlx::Error> {
|
) -> Result<Self, sqlx::Error>
|
||||||
|
where
|
||||||
|
E: sqlx::PgExecutor<'e>,
|
||||||
|
{
|
||||||
sqlx::query_as::<_, Self>(
|
sqlx::query_as::<_, Self>(
|
||||||
"INSERT INTO comment (upload_id, user_id, body) VALUES ($1, $2, $3) RETURNING *",
|
"INSERT INTO comment (upload_id, user_id, body) VALUES ($1, $2, $3) RETURNING *",
|
||||||
)
|
)
|
||||||
.bind(upload_id)
|
.bind(upload_id)
|
||||||
.bind(user_id)
|
.bind(user_id)
|
||||||
.bind(body)
|
.bind(body)
|
||||||
.fetch_one(pool)
|
.fetch_one(executor)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,13 @@ pub struct Hashtag {
|
|||||||
|
|
||||||
impl Hashtag {
|
impl Hashtag {
|
||||||
/// Upsert a hashtag (insert if not exists, return existing if it does).
|
/// Upsert a hashtag (insert if not exists, return existing if it does).
|
||||||
pub async fn upsert(pool: &PgPool, event_id: Uuid, tag: &str) -> Result<Self, sqlx::Error> {
|
///
|
||||||
|
/// Takes any executor so callers can run it inside a transaction (atomic
|
||||||
|
/// upload/comment writes) or standalone against the pool.
|
||||||
|
pub async fn upsert<'e, E>(executor: E, event_id: Uuid, tag: &str) -> Result<Self, sqlx::Error>
|
||||||
|
where
|
||||||
|
E: sqlx::PgExecutor<'e>,
|
||||||
|
{
|
||||||
let normalized = tag.trim().trim_start_matches('#').to_lowercase();
|
let normalized = tag.trim().trim_start_matches('#').to_lowercase();
|
||||||
sqlx::query_as::<_, Self>(
|
sqlx::query_as::<_, Self>(
|
||||||
"INSERT INTO hashtag (event_id, tag) VALUES ($1, $2)
|
"INSERT INTO hashtag (event_id, tag) VALUES ($1, $2)
|
||||||
@@ -19,33 +25,39 @@ impl Hashtag {
|
|||||||
)
|
)
|
||||||
.bind(event_id)
|
.bind(event_id)
|
||||||
.bind(&normalized)
|
.bind(&normalized)
|
||||||
.fetch_one(pool)
|
.fetch_one(executor)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn link_to_upload(
|
pub async fn link_to_upload<'e, E>(
|
||||||
pool: &PgPool,
|
executor: E,
|
||||||
upload_id: Uuid,
|
upload_id: Uuid,
|
||||||
hashtag_id: Uuid,
|
hashtag_id: Uuid,
|
||||||
) -> Result<(), sqlx::Error> {
|
) -> Result<(), sqlx::Error>
|
||||||
|
where
|
||||||
|
E: sqlx::PgExecutor<'e>,
|
||||||
|
{
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO upload_hashtag (upload_id, hashtag_id) VALUES ($1, $2)
|
"INSERT INTO upload_hashtag (upload_id, hashtag_id) VALUES ($1, $2)
|
||||||
ON CONFLICT DO NOTHING",
|
ON CONFLICT DO NOTHING",
|
||||||
)
|
)
|
||||||
.bind(upload_id)
|
.bind(upload_id)
|
||||||
.bind(hashtag_id)
|
.bind(hashtag_id)
|
||||||
.execute(pool)
|
.execute(executor)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn unlink_all_from_upload(
|
pub async fn unlink_all_from_upload<'e, E>(
|
||||||
pool: &PgPool,
|
executor: E,
|
||||||
upload_id: Uuid,
|
upload_id: Uuid,
|
||||||
) -> Result<(), sqlx::Error> {
|
) -> Result<(), sqlx::Error>
|
||||||
|
where
|
||||||
|
E: sqlx::PgExecutor<'e>,
|
||||||
|
{
|
||||||
sqlx::query("DELETE FROM upload_hashtag WHERE upload_id = $1")
|
sqlx::query("DELETE FROM upload_hashtag WHERE upload_id = $1")
|
||||||
.bind(upload_id)
|
.bind(upload_id)
|
||||||
.execute(pool)
|
.execute(executor)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,15 +36,20 @@ pub struct UploadDto {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Upload {
|
impl Upload {
|
||||||
pub async fn create(
|
/// Takes any executor so the caller can run it inside a transaction (atomic
|
||||||
pool: &PgPool,
|
/// quota + insert) or standalone against the pool.
|
||||||
|
pub async fn create<'e, E>(
|
||||||
|
executor: E,
|
||||||
event_id: Uuid,
|
event_id: Uuid,
|
||||||
user_id: Uuid,
|
user_id: Uuid,
|
||||||
original_path: &str,
|
original_path: &str,
|
||||||
mime_type: &str,
|
mime_type: &str,
|
||||||
original_size_bytes: i64,
|
original_size_bytes: i64,
|
||||||
caption: Option<&str>,
|
caption: Option<&str>,
|
||||||
) -> Result<Self, sqlx::Error> {
|
) -> Result<Self, sqlx::Error>
|
||||||
|
where
|
||||||
|
E: sqlx::PgExecutor<'e>,
|
||||||
|
{
|
||||||
sqlx::query_as::<_, Self>(
|
sqlx::query_as::<_, Self>(
|
||||||
"INSERT INTO upload (event_id, user_id, original_path, mime_type, original_size_bytes, caption)
|
"INSERT INTO upload (event_id, user_id, original_path, mime_type, original_size_bytes, caption)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6)
|
VALUES ($1, $2, $3, $4, $5, $6)
|
||||||
@@ -56,7 +61,7 @@ impl Upload {
|
|||||||
.bind(mime_type)
|
.bind(mime_type)
|
||||||
.bind(original_size_bytes)
|
.bind(original_size_bytes)
|
||||||
.bind(caption)
|
.bind(caption)
|
||||||
.fetch_one(pool)
|
.fetch_one(executor)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,15 +187,18 @@ impl Upload {
|
|||||||
Ok(deleted)
|
Ok(deleted)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn update_caption(
|
pub async fn update_caption<'e, E>(
|
||||||
pool: &PgPool,
|
executor: E,
|
||||||
id: Uuid,
|
id: Uuid,
|
||||||
caption: Option<&str>,
|
caption: Option<&str>,
|
||||||
) -> Result<(), sqlx::Error> {
|
) -> Result<(), sqlx::Error>
|
||||||
|
where
|
||||||
|
E: sqlx::PgExecutor<'e>,
|
||||||
|
{
|
||||||
sqlx::query("UPDATE upload SET caption = $2 WHERE id = $1")
|
sqlx::query("UPDATE upload SET caption = $2 WHERE id = $1")
|
||||||
.bind(id)
|
.bind(id)
|
||||||
.bind(caption)
|
.bind(caption)
|
||||||
.execute(pool)
|
.execute(executor)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,11 +42,28 @@ impl CompressionWorker {
|
|||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::error!("compression failed for upload {upload_id}: {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 {
|
let _ = worker.sse_tx.send(SseEvent {
|
||||||
event_type: "upload-error".to_string(),
|
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": 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(),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -87,15 +87,17 @@ pub fn spawn_export_jobs(
|
|||||||
event_name: String,
|
event_name: String,
|
||||||
pool: PgPool,
|
pool: PgPool,
|
||||||
media_path: PathBuf,
|
media_path: PathBuf,
|
||||||
|
export_path: PathBuf,
|
||||||
sse_tx: broadcast::Sender<SseEvent>,
|
sse_tx: broadcast::Sender<SseEvent>,
|
||||||
) {
|
) {
|
||||||
let pool2 = pool.clone();
|
let pool2 = pool.clone();
|
||||||
let media_path2 = media_path.clone();
|
let media_path2 = media_path.clone();
|
||||||
|
let export_path2 = export_path.clone();
|
||||||
let sse_tx2 = sse_tx.clone();
|
let sse_tx2 = sse_tx.clone();
|
||||||
let event_name2 = event_name.clone();
|
let event_name2 = event_name.clone();
|
||||||
|
|
||||||
tokio::spawn(async move {
|
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:#}");
|
tracing::error!("ZIP export failed for event {event_id}: {e:#}");
|
||||||
mark_failed(&pool, event_id, "zip", &e.to_string()).await;
|
mark_failed(&pool, event_id, "zip", &e.to_string()).await;
|
||||||
}
|
}
|
||||||
@@ -104,7 +106,7 @@ pub fn spawn_export_jobs(
|
|||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
if let Err(e) =
|
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:#}");
|
tracing::error!("HTML export failed for event {event_id}: {e:#}");
|
||||||
mark_failed(&pool2, event_id, "html", &e.to_string()).await;
|
mark_failed(&pool2, event_id, "html", &e.to_string()).await;
|
||||||
@@ -119,6 +121,7 @@ async fn run_zip_export(
|
|||||||
event_id: Uuid,
|
event_id: Uuid,
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
media_path: &Path,
|
media_path: &Path,
|
||||||
|
export_path: &Path,
|
||||||
sse_tx: &broadcast::Sender<SseEvent>,
|
sse_tx: &broadcast::Sender<SseEvent>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
mark_running(pool, event_id, "zip").await;
|
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 uploads = query_uploads(pool, event_id).await?;
|
||||||
let total = uploads.len().max(1) as f32;
|
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?;
|
tokio::fs::create_dir_all(&exports_dir).await?;
|
||||||
|
|
||||||
let tmp_path = exports_dir.join("Gallery.zip.tmp");
|
let tmp_path = exports_dir.join("Gallery.zip.tmp");
|
||||||
@@ -193,6 +197,7 @@ async fn run_html_export(
|
|||||||
event_name: &str,
|
event_name: &str,
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
media_path: &Path,
|
media_path: &Path,
|
||||||
|
export_path: &Path,
|
||||||
sse_tx: &broadcast::Sender<SseEvent>,
|
sse_tx: &broadcast::Sender<SseEvent>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
mark_running(pool, event_id, "html").await;
|
mark_running(pool, event_id, "html").await;
|
||||||
@@ -205,7 +210,8 @@ async fn run_html_export(
|
|||||||
|
|
||||||
update_progress(pool, event_id, "html", 5).await;
|
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?;
|
tokio::fs::create_dir_all(&exports_dir).await?;
|
||||||
|
|
||||||
// 2. Create temp directory for media processing
|
// 2. Create temp directory for media processing
|
||||||
|
|||||||
@@ -71,14 +71,21 @@ impl RateLimiter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Extract the client IP from X-Forwarded-For (Caddy sets this) or fall back
|
/// Extract the client IP from X-Forwarded-For or fall back to a provided socket
|
||||||
/// to a provided socket address string.
|
/// address string.
|
||||||
|
///
|
||||||
|
/// We take the **right-most** entry, not the left-most. Caddy is the sole ingress
|
||||||
|
/// and the app port is only `expose`d (never published), so the last hop Caddy
|
||||||
|
/// appends is the real client. A client can prepend arbitrary spoofed values to
|
||||||
|
/// the left of XFF to dodge throttles — those are ignored here. This assumes
|
||||||
|
/// exactly one trusted proxy (Caddy); revisit if that changes.
|
||||||
pub fn client_ip(headers: &axum::http::HeaderMap, fallback: &str) -> String {
|
pub fn client_ip(headers: &axum::http::HeaderMap, fallback: &str) -> String {
|
||||||
headers
|
headers
|
||||||
.get("x-forwarded-for")
|
.get("x-forwarded-for")
|
||||||
.and_then(|v| v.to_str().ok())
|
.and_then(|v| v.to_str().ok())
|
||||||
.and_then(|s| s.split(',').next())
|
.and_then(|s| s.rsplit(',').next())
|
||||||
.map(|s| s.trim().to_owned())
|
.map(|s| s.trim().to_owned())
|
||||||
|
.filter(|s| !s.is_empty())
|
||||||
.unwrap_or_else(|| fallback.to_owned())
|
.unwrap_or_else(|| fallback.to_owned())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,9 +141,18 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn client_ip_prefers_first_forwarded_for_entry() {
|
fn client_ip_takes_rightmost_forwarded_for_entry() {
|
||||||
|
// The right-most entry is the hop our trusted proxy (Caddy) appended.
|
||||||
let mut h = HeaderMap::new();
|
let mut h = HeaderMap::new();
|
||||||
h.insert("x-forwarded-for", "203.0.113.7, 10.0.0.1".parse().unwrap());
|
h.insert("x-forwarded-for", "10.0.0.1, 203.0.113.7".parse().unwrap());
|
||||||
|
assert_eq!(client_ip(&h, "fallback"), "203.0.113.7");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_ip_ignores_spoofed_leftmost_entry() {
|
||||||
|
// A client prepending a fake IP to dodge throttles must not win.
|
||||||
|
let mut h = HeaderMap::new();
|
||||||
|
h.insert("x-forwarded-for", "1.2.3.4, 9.9.9.9, 203.0.113.7".parse().unwrap());
|
||||||
assert_eq!(client_ip(&h, "fallback"), "203.0.113.7");
|
assert_eq!(client_ip(&h, "fallback"), "203.0.113.7");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,4 +167,14 @@ mod tests {
|
|||||||
fn client_ip_falls_back_when_header_absent() {
|
fn client_ip_falls_back_when_header_absent() {
|
||||||
assert_eq!(client_ip(&HeaderMap::new(), "127.0.0.1"), "127.0.0.1");
|
assert_eq!(client_ip(&HeaderMap::new(), "127.0.0.1"), "127.0.0.1");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_ip_falls_back_on_trailing_comma_empty_entry() {
|
||||||
|
// A trailing comma leaves an empty right-most segment after trimming; the
|
||||||
|
// `.filter(!is_empty)` must reject it and fall through to the fallback
|
||||||
|
// rather than returning "" (which would collapse callers into one bucket).
|
||||||
|
let mut h = HeaderMap::new();
|
||||||
|
h.insert("x-forwarded-for", "203.0.113.7, ".parse().unwrap());
|
||||||
|
assert_eq!(client_ip(&h, "127.0.0.1"), "127.0.0.1");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,8 +36,12 @@ pub struct AppState {
|
|||||||
impl AppState {
|
impl AppState {
|
||||||
pub fn new(pool: PgPool, config: AppConfig) -> Self {
|
pub fn new(pool: PgPool, config: AppConfig) -> Self {
|
||||||
let (sse_tx, _) = broadcast::channel(256);
|
let (sse_tx, _) = broadcast::channel(256);
|
||||||
let compression =
|
let compression = CompressionWorker::new(
|
||||||
CompressionWorker::new(pool.clone(), config.media_path.clone(), 2, sse_tx.clone());
|
pool.clone(),
|
||||||
|
config.media_path.clone(),
|
||||||
|
config.compression_concurrency,
|
||||||
|
sse_tx.clone(),
|
||||||
|
);
|
||||||
Self {
|
Self {
|
||||||
pool,
|
pool,
|
||||||
config,
|
config,
|
||||||
|
|||||||
@@ -6,3 +6,8 @@ services:
|
|||||||
db:
|
db:
|
||||||
ports:
|
ports:
|
||||||
- "5432:5432"
|
- "5432:5432"
|
||||||
|
app:
|
||||||
|
# Relax the production secret guard for local dev — the dev sentinel JWT_SECRET
|
||||||
|
# is tolerated (warned) rather than rejected.
|
||||||
|
environment:
|
||||||
|
APP_ENV: development
|
||||||
|
|||||||
@@ -14,6 +14,10 @@ services:
|
|||||||
interval: 5s
|
interval: 5s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 10
|
retries: 10
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 512M
|
||||||
|
|
||||||
app:
|
app:
|
||||||
build:
|
build:
|
||||||
@@ -21,13 +25,32 @@ services:
|
|||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
env_file: .env
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
# Activates the production secret guard in config.rs — refuses to boot with
|
||||||
|
# placeholder JWT_SECRET / ADMIN_PASSWORD_HASH.
|
||||||
|
APP_ENV: production
|
||||||
depends_on:
|
depends_on:
|
||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
volumes:
|
volumes:
|
||||||
- media_data:/media
|
- 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:
|
expose:
|
||||||
- "3000"
|
- "3000"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "wget -q -O- http://localhost:3000/health || exit 1"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
start_period: 20s
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
# Bounds a runaway ffmpeg transcode (large uploads, 2 workers) so it can't
|
||||||
|
# OOM the single box and take down Postgres.
|
||||||
|
memory: 1G
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
build:
|
build:
|
||||||
@@ -35,10 +58,24 @@ services:
|
|||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
env_file: .env
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
# adapter-node behind Caddy TLS needs the public origin for CSRF checks on
|
||||||
|
# POST form actions — without it they fail only in production.
|
||||||
|
ORIGIN: "https://${DOMAIN}"
|
||||||
depends_on:
|
depends_on:
|
||||||
- app
|
- app
|
||||||
expose:
|
expose:
|
||||||
- "3001"
|
- "3001"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "wget -q -O- http://localhost:3001/ >/dev/null 2>&1 || exit 1"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
start_period: 15s
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 256M
|
||||||
|
|
||||||
caddy:
|
caddy:
|
||||||
image: caddy:2-alpine
|
image: caddy:2-alpine
|
||||||
@@ -50,10 +87,17 @@ services:
|
|||||||
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
||||||
- caddy_data:/data
|
- caddy_data:/data
|
||||||
depends_on:
|
depends_on:
|
||||||
- app
|
app:
|
||||||
- frontend
|
condition: service_healthy
|
||||||
|
frontend:
|
||||||
|
condition: service_healthy
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
memory: 256M
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres_data:
|
postgres_data:
|
||||||
media_data:
|
media_data:
|
||||||
|
exports_data:
|
||||||
caddy_data:
|
caddy_data:
|
||||||
|
|||||||
@@ -51,15 +51,28 @@ item below is tagged with its **current status in `main`**:
|
|||||||
|
|
||||||
## ✅ Fixed in main since the audit (for the record)
|
## ✅ Fixed in main since the audit (for the record)
|
||||||
|
|
||||||
These audit findings are present in `main` today (verified 2026-06-30): event-scoped social
|
These audit findings are present in `main` today (verified 2026-06-30): server-side MIME/ext
|
||||||
handlers (cross-event authz), server-side MIME/ext allowlist on upload, recovery-PIN lockout
|
allowlist on upload, recovery-PIN lockout backoff, DB port no longer publicly exposed, bcrypt
|
||||||
backoff, unspoofable client IP in the rate limiter, effective JWT production-secret guard, DB port
|
offloaded via `spawn_blocking`, bounded compression concurrency (semaphore), bounded feed queries
|
||||||
no longer publicly exposed, container healthchecks, bcrypt offloaded via `spawn_blocking`,
|
(`LIMIT ≤ 100`), and the viewport-fit / reduced-motion / aria a11y pass. An image-decode
|
||||||
bounded compression concurrency (semaphore), bounded feed queries (`LIMIT ≤ 100`), and the
|
decompression-bomb cap (`image::Limits` 12000×12000 / 256 MiB) lives in
|
||||||
viewport-fit / reduced-motion / aria a11y pass. **New since the audit:** an image-decode
|
|
||||||
decompression-bomb cap (`image::Limits` 12000×12000 / 256 MiB) ported into
|
|
||||||
`backend/src/services/compression.rs`.
|
`backend/src/services/compression.rs`.
|
||||||
|
|
||||||
|
**Fixed in the 2026-07 review pass** (previously *claimed* fixed here but were not — corrected):
|
||||||
|
- **Effective JWT production-secret guard** — `APP_ENV=production` is now set for the app service,
|
||||||
|
and `config.rs::validate_secrets` rejects any placeholder-ish `JWT_SECRET`/`ADMIN_PASSWORD_HASH`
|
||||||
|
(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, 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.
|
||||||
|
|
||||||
## 🅲 Consciously won't-fix at ~100-guest single-box scale
|
## 🅲 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
|
Diminishing returns vs. the deployment's actual threat model. Revisit only if the scale or
|
||||||
@@ -71,6 +84,12 @@ tenancy model changes.
|
|||||||
- Performance micro-indexes (`idx_like_user_upload`, comment pagination index) — current queries
|
- Performance micro-indexes (`idx_like_user_upload`, comment pagination index) — current queries
|
||||||
are sub-ms at this row count.
|
are sub-ms at this row count.
|
||||||
- Optimistic-like in-flight guard, ownership-snapshot-at-mount, assorted copy tweaks — UX polish.
|
- Optimistic-like in-flight guard, ownership-snapshot-at-mount, assorted copy tweaks — UX polish.
|
||||||
|
- **Mid-session ban does not tear down an already-open SSE stream.** The live-ban check lives in the
|
||||||
|
`AuthUser` extractor, but the stream authenticates via ticket→session (`handlers/sse.rs::stream`),
|
||||||
|
so a user banned while connected keeps receiving broadcast events until their stream drops. New
|
||||||
|
tickets *are* blocked (`issue_ticket` uses `AuthUser`), so they cannot reconnect. Low blast radius
|
||||||
|
(read-only feed events, no re-subscribe); tearing live streams down would need a per-session
|
||||||
|
broadcast filter. Revisit only if bans must take effect within seconds.
|
||||||
|
|
||||||
## By-design notes (audit branch's signed-media model — see DECISION-media-auth.md)
|
## By-design notes (audit branch's signed-media model — see DECISION-media-auth.md)
|
||||||
|
|
||||||
|
|||||||
@@ -147,12 +147,18 @@ the Host can clean up later).
|
|||||||
|
|
||||||
## 10. Banned-guest experience
|
## 10. Banned-guest experience
|
||||||
|
|
||||||
1. The banned user's next authenticated request returns HTTP 403 with a clear message
|
1. The ban takes effect immediately on the banned user's existing session — the auth
|
||||||
("Du bist gesperrt.").
|
layer re-reads the live `is_banned` flag on every request rather than trusting the
|
||||||
2. They can still browse the read-only feed (and download the export once it's released).
|
JWT, so there's no 30-day token-lifetime window.
|
||||||
3. They cannot upload, like, or comment.
|
2. Their next authenticated *write* request returns HTTP 403 with a clear message
|
||||||
4. If `hide_uploads` was set on the ban, their existing uploads are filtered out of the
|
("Du bist gesperrt."). Ban enforcement lives on the write handlers and the
|
||||||
feed for everyone (the `v_feed` view already enforces this).
|
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
|
## 11. Admin — instance configuration
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,17 @@
|
|||||||
# of HTTPS/Let's Encrypt.
|
# of HTTPS/Let's Encrypt.
|
||||||
|
|
||||||
:3101 {
|
: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 /api/* app:3000
|
||||||
reverse_proxy /media/* app:3000
|
reverse_proxy /media/* app:3000
|
||||||
|
|||||||
@@ -117,6 +117,25 @@ export class ApiClient {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async unbanUser(token: string, userId: string, opts: { expectedStatus?: number | number[] } = {}) {
|
||||||
|
return this.request<void>('POST', `/host/users/${userId}/unban`, {
|
||||||
|
token,
|
||||||
|
expectedStatus: opts.expectedStatus ?? [200, 204],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reset another user's PIN. Returns the plaintext PIN the host must relay once. */
|
||||||
|
async resetUserPin(
|
||||||
|
token: string,
|
||||||
|
userId: string,
|
||||||
|
opts: { expectedStatus?: number | number[] } = {}
|
||||||
|
): Promise<{ status: number; body: { pin?: string } }> {
|
||||||
|
return this.request<{ pin?: string }>('POST', `/host/users/${userId}/pin-reset`, {
|
||||||
|
token,
|
||||||
|
expectedStatus: opts.expectedStatus ?? [200],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async closeEvent(token: string) {
|
async closeEvent(token: string) {
|
||||||
return this.request<void>('POST', '/host/event/close', { token, expectedStatus: [200, 204] });
|
return this.request<void>('POST', '/host/event/close', { token, expectedStatus: [200, 204] });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,11 +3,26 @@
|
|||||||
* flow. Centralising the API contract (routes, field names, expected statuses)
|
* flow. Centralising the API contract (routes, field names, expected statuses)
|
||||||
* means an API change is a one-file edit, not a 7-file hunt.
|
* 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';
|
import { db } from '../fixtures/db';
|
||||||
|
|
||||||
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
|
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 = {
|
export type SeedUploadOptions = {
|
||||||
caption?: string;
|
caption?: string;
|
||||||
/** Mark compression done so the card is fully rendered in the feed. Default true. */
|
/** 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. */
|
/** Seed a real, accepted upload owned by `jwt` and return its id. */
|
||||||
export async function seedUpload(jwt: string, opts: SeedUploadOptions = {}): Promise<string> {
|
export async function seedUpload(jwt: string, opts: SeedUploadOptions = {}): Promise<string> {
|
||||||
const body = new Uint8Array(1024);
|
const res = await uploadRaw(jwt, sampleImage(), {
|
||||||
body.set(JPEG_MAGIC, 0);
|
|
||||||
const res = await uploadRaw(jwt, body, {
|
|
||||||
filename: 'a.jpg',
|
filename: 'a.jpg',
|
||||||
contentType: 'image/jpeg',
|
contentType: 'image/jpeg',
|
||||||
caption: opts.caption,
|
caption: opts.caption,
|
||||||
|
|||||||
53
e2e/specs/03-feed/comment-ui.spec.ts
Normal file
53
e2e/specs/03-feed/comment-ui.spec.ts
Normal file
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -33,4 +33,39 @@ test.describe('Host — event lock', () => {
|
|||||||
// Currently no UI consumes the event-closed SSE on /feed. Add this banner
|
// Currently no UI consumes the event-closed SSE on /feed. Add this banner
|
||||||
// and flip fixme to test once it lands.
|
// and flip fixme to test once it lands.
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Regression for the review: likes/comments used to ignore uploads_locked_at,
|
||||||
|
// so social writes still landed on a closed event. They now share the upload
|
||||||
|
// handler's lock guard.
|
||||||
|
test('a closed event rejects likes and comments', async ({ api, host, guest }) => {
|
||||||
|
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
|
||||||
|
const g = await guest('SocialLocked');
|
||||||
|
|
||||||
|
// Upload while still open so there's a target to interact with.
|
||||||
|
const { uploadRaw } = await import('../../helpers/upload-client');
|
||||||
|
const { readFileSync } = await import('node:fs');
|
||||||
|
const { join } = await import('node:path');
|
||||||
|
const sample = join(process.cwd(), 'fixtures', 'media', 'sample.jpg');
|
||||||
|
const upRes = await uploadRaw(g.jwt, readFileSync(sample), {
|
||||||
|
filename: 'x.jpg',
|
||||||
|
contentType: 'image/jpeg',
|
||||||
|
});
|
||||||
|
expect(upRes.status).toBe(201);
|
||||||
|
const { id } = await upRes.json();
|
||||||
|
|
||||||
|
await api.closeEvent(host.jwt);
|
||||||
|
|
||||||
|
const likeRes = await fetch(`${BASE}/api/v1/upload/${id}/like`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { Authorization: `Bearer ${g.jwt}` },
|
||||||
|
});
|
||||||
|
expect(likeRes.status).toBe(403);
|
||||||
|
|
||||||
|
const commentRes = await fetch(`${BASE}/api/v1/upload/${id}/comments`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { Authorization: `Bearer ${g.jwt}`, 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ body: 'sollte blockiert sein' }),
|
||||||
|
});
|
||||||
|
expect(commentRes.status).toBe(403);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
* coverage of the buttons lives in a separate UI-focused spec.
|
* coverage of the buttons lives in a separate UI-focused spec.
|
||||||
*/
|
*/
|
||||||
import { test, expect } from '../../fixtures/test';
|
import { test, expect } from '../../fixtures/test';
|
||||||
|
import { seedUpload, seedComment } from '../../helpers/seed';
|
||||||
|
|
||||||
test.describe('Host — moderation API', () => {
|
test.describe('Host — moderation API', () => {
|
||||||
test('ban with hide_uploads=true sets the right flags', async ({ api, host, guest }) => {
|
test('ban with hide_uploads=true sets the right flags', async ({ api, host, guest }) => {
|
||||||
@@ -45,3 +46,111 @@ test.describe('Host — moderation API', () => {
|
|||||||
expect(row?.role).toBe('host');
|
expect(row?.role).toBe('host');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression for the review's H1: role & ban used to be trusted from the JWT and
|
||||||
|
* never re-checked against the DB, so a demoted/banned host kept full powers for
|
||||||
|
* the life of their token (up to 30d) and a banned host could even unban
|
||||||
|
* themselves. The auth extractor now re-reads the live user row, so these take
|
||||||
|
* effect on the *existing* session with no re-login.
|
||||||
|
*/
|
||||||
|
test.describe('Host — live role/ban revocation (H1)', () => {
|
||||||
|
test('a demoted host loses host powers on their existing session', async ({
|
||||||
|
api,
|
||||||
|
adminToken,
|
||||||
|
guest,
|
||||||
|
}) => {
|
||||||
|
const u = await guest('DemoteMidSession');
|
||||||
|
await api.setRole(adminToken, u.userId, 'host');
|
||||||
|
// Fresh host token (role is encoded at mint time).
|
||||||
|
const { body } = await api.recover(u.displayName, u.pin);
|
||||||
|
const hostJwt = body.jwt;
|
||||||
|
|
||||||
|
// Sanity: the token currently has host powers.
|
||||||
|
await api.listUsers(hostJwt);
|
||||||
|
|
||||||
|
// Demote via admin — the host does NOT re-login.
|
||||||
|
await api.setRole(adminToken, u.userId, 'guest');
|
||||||
|
|
||||||
|
// Same token is now rejected with exactly 403 (RequireHost sees the DB role,
|
||||||
|
// not the JWT claim). Asserting the status guards against a spurious 500
|
||||||
|
// masquerading as "revoked".
|
||||||
|
await expect(api.listUsers(hostJwt)).rejects.toThrow(/→ 403/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a banned host is locked out immediately on their existing session', async ({
|
||||||
|
api,
|
||||||
|
adminToken,
|
||||||
|
host,
|
||||||
|
}) => {
|
||||||
|
// Sanity: host token works.
|
||||||
|
await api.listUsers(host.jwt);
|
||||||
|
|
||||||
|
await api.banUser(adminToken, host.userId, false);
|
||||||
|
|
||||||
|
// Banned users are rejected with 403 by the auth extractor before any handler runs.
|
||||||
|
await expect(api.listUsers(host.jwt)).rejects.toThrow(/→ 403/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a banned host cannot unban themselves', async ({ api, adminToken, host }) => {
|
||||||
|
await api.banUser(adminToken, host.userId, false);
|
||||||
|
await expect(
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
43
e2e/specs/04-host/pin-reset.spec.ts
Normal file
43
e2e/specs/04-host/pin-reset.spec.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
/**
|
||||||
|
* Regression for the review's C1: `reset_user_pin` wrote to a non-existent
|
||||||
|
* column (`pin_failed_attempts` vs the real `failed_pin_attempts`), so the
|
||||||
|
* endpoint 500'd every time and never returned a PIN — the feature had never
|
||||||
|
* worked against a real DB and no test caught it. These specs pin the contract:
|
||||||
|
* a successful reset returns a fresh 4-digit PIN, and the target can recover
|
||||||
|
* with it.
|
||||||
|
*/
|
||||||
|
import { test, expect } from '../../fixtures/test';
|
||||||
|
|
||||||
|
test.describe('Host — reset guest PIN (C1)', () => {
|
||||||
|
test('resetting a guest PIN returns a fresh 4-digit PIN', async ({ api, host, guest }) => {
|
||||||
|
const target = await guest('ResetMe');
|
||||||
|
|
||||||
|
const { status, body } = await api.resetUserPin(host.jwt, target.userId);
|
||||||
|
|
||||||
|
expect(status).toBe(200);
|
||||||
|
expect(body.pin).toMatch(/^\d{4}$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the target can recover with the newly reset PIN (and not the old one)', async ({
|
||||||
|
api,
|
||||||
|
host,
|
||||||
|
guest,
|
||||||
|
}) => {
|
||||||
|
const target = await guest('RecoverWithNewPin');
|
||||||
|
|
||||||
|
const { body } = await api.resetUserPin(host.jwt, target.userId);
|
||||||
|
const newPin = body.pin!;
|
||||||
|
|
||||||
|
// New PIN works.
|
||||||
|
await api.recover(target.displayName, newPin, { expectedStatus: [200] });
|
||||||
|
|
||||||
|
// Old PIN no longer works (overwritten). 401 = wrong PIN.
|
||||||
|
if (target.pin !== newPin) {
|
||||||
|
await api.recover(target.displayName, target.pin, { expectedStatus: [401] });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a host cannot reset their own PIN via this endpoint', async ({ api, host }) => {
|
||||||
|
await api.resetUserPin(host.jwt, host.userId, { expectedStatus: [400] });
|
||||||
|
});
|
||||||
|
});
|
||||||
75
e2e/specs/04-host/sse-eviction.spec.ts
Normal file
75
e2e/specs/04-host/sse-eviction.spec.ts
Normal file
@@ -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 });
|
||||||
|
});
|
||||||
|
});
|
||||||
60
e2e/specs/06-export/export-leak.spec.ts
Normal file
60
e2e/specs/06-export/export-leak.spec.ts
Normal file
@@ -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"
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -21,7 +21,10 @@
|
|||||||
theme=dark don't flash a white screen. Mirrors the logic in
|
theme=dark don't flash a white screen. Mirrors the logic in
|
||||||
`src/lib/theme-store.ts`; kept in sync by hand (it's 6 lines).
|
`src/lib/theme-store.ts`; kept in sync by hand (it's 6 lines).
|
||||||
-->
|
-->
|
||||||
<script>
|
<!-- nonce is required: our CSP sets script-src 'self', and SvelteKit's
|
||||||
|
mode:'auto' only hashes scripts *it* injects, not this template-authored
|
||||||
|
one. %sveltekit.nonce% is substituted per request and added to the CSP. -->
|
||||||
|
<script nonce="%sveltekit.nonce%">
|
||||||
(function () {
|
(function () {
|
||||||
try {
|
try {
|
||||||
var pref = localStorage.getItem('eventsnap_theme') || 'system';
|
var pref = localStorage.getItem('eventsnap_theme') || 'system';
|
||||||
|
|||||||
29
frontend/src/lib/actions/modal-inert.ts
Normal file
29
frontend/src/lib/actions/modal-inert.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
// Make everything *outside* a modal's subtree inert while it's open, so screen
|
||||||
|
// readers and tab order can't reach the background (focus-trap only covers
|
||||||
|
// keyboard focus; `inert` also hides the content from assistive tech).
|
||||||
|
//
|
||||||
|
// Walks from the node up to <body> and marks every sibling along the path as
|
||||||
|
// inert, then restores exactly those it changed on teardown. Applying it to a
|
||||||
|
// `display: contents` wrapper keeps the modal's own backdrop + dialog interactive.
|
||||||
|
export function modalInert(node: HTMLElement) {
|
||||||
|
const changed: HTMLElement[] = [];
|
||||||
|
|
||||||
|
let el: HTMLElement | null = node;
|
||||||
|
while (el && el !== document.body) {
|
||||||
|
const parent: HTMLElement | null = el.parentElement;
|
||||||
|
if (!parent) break;
|
||||||
|
for (const sib of Array.from(parent.children)) {
|
||||||
|
if (sib !== el && sib instanceof HTMLElement && !sib.hasAttribute('inert')) {
|
||||||
|
sib.setAttribute('inert', '');
|
||||||
|
changed.push(sib);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
el = parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
destroy() {
|
||||||
|
for (const sib of changed) sib.removeAttribute('inert');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -68,6 +68,9 @@ async function request<T>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!res.ok) {
|
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) {
|
if (res.status === 401) {
|
||||||
clearAuth();
|
clearAuth();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,6 +83,9 @@ export function clearAuth(): void {
|
|||||||
if (!browser) return;
|
if (!browser) return;
|
||||||
localStorage.removeItem(TOKEN_KEY);
|
localStorage.removeItem(TOKEN_KEY);
|
||||||
localStorage.removeItem(USER_ID_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
|
// PIN is intentionally kept so the user can recover
|
||||||
isAuthenticated.set(false);
|
isAuthenticated.set(false);
|
||||||
// Hooks fire in registration order. Keep them dependency-free of each other —
|
// Hooks fire in registration order. Keep them dependency-free of each other —
|
||||||
|
|||||||
@@ -2,11 +2,13 @@
|
|||||||
import { onDestroy } from 'svelte';
|
import { onDestroy } from 'svelte';
|
||||||
import type { FeedUpload } from '$lib/types';
|
import type { FeedUpload } from '$lib/types';
|
||||||
import { api } from '$lib/api';
|
import { api } from '$lib/api';
|
||||||
|
import { onSseEvent } from '$lib/sse';
|
||||||
import { getUserId } from '$lib/auth';
|
import { getUserId } from '$lib/auth';
|
||||||
import { dataMode, pickMediaUrl } from '$lib/data-mode-store';
|
import { dataMode, pickMediaUrl } from '$lib/data-mode-store';
|
||||||
import { doubletap } from '$lib/actions/doubletap';
|
import { doubletap } from '$lib/actions/doubletap';
|
||||||
import { focusTrap } from '$lib/actions/focus-trap';
|
import { focusTrap } from '$lib/actions/focus-trap';
|
||||||
import { scrollLock } from '$lib/actions/scroll-lock';
|
import { scrollLock } from '$lib/actions/scroll-lock';
|
||||||
|
import { modalInert } from '$lib/actions/modal-inert';
|
||||||
import { toastError } from '$lib/toast-store';
|
import { toastError } from '$lib/toast-store';
|
||||||
import { vibrate } from '$lib/haptics';
|
import { vibrate } from '$lib/haptics';
|
||||||
import HeartBurst from './HeartBurst.svelte';
|
import HeartBurst from './HeartBurst.svelte';
|
||||||
@@ -47,17 +49,33 @@
|
|||||||
burstTimer = setTimeout(() => (heartBurst = false), 700);
|
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(() => {
|
onDestroy(() => {
|
||||||
if (burstTimer) clearTimeout(burstTimer);
|
if (burstTimer) clearTimeout(burstTimer);
|
||||||
|
unsubCommentDeleted();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Only refetch when a *different* upload is shown. The feed reassigns the
|
||||||
|
// `upload` prop object on every SSE like/comment count update; keying the
|
||||||
|
// effect off the memoized id avoids a refetch storm that would also clobber
|
||||||
|
// a just-posted optimistic comment.
|
||||||
|
const uploadId = $derived(upload.id);
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
loadComments();
|
loadComments(uploadId);
|
||||||
});
|
});
|
||||||
|
|
||||||
async function loadComments() {
|
async function loadComments(id: string) {
|
||||||
try {
|
try {
|
||||||
comments = await api.get<CommentDto[]>(`/upload/${upload.id}/comments`);
|
comments = await api.get<CommentDto[]>(`/upload/${id}/comments`);
|
||||||
} catch {
|
} catch {
|
||||||
// Background fetch — failure leaves the panel empty; reopening the lightbox retries.
|
// Background fetch — failure leaves the panel empty; reopening the lightbox retries.
|
||||||
}
|
}
|
||||||
@@ -67,7 +85,7 @@
|
|||||||
if (!newComment.trim()) return;
|
if (!newComment.trim()) return;
|
||||||
loading = true;
|
loading = true;
|
||||||
try {
|
try {
|
||||||
const comment = await api.post<CommentDto>(`/upload/${upload.id}/comment`, {
|
const comment = await api.post<CommentDto>(`/upload/${upload.id}/comments`, {
|
||||||
body: newComment.trim()
|
body: newComment.trim()
|
||||||
});
|
});
|
||||||
comments = [...comments, comment];
|
comments = [...comments, comment];
|
||||||
@@ -106,6 +124,7 @@
|
|||||||
aria-labelledby="lightbox-title"
|
aria-labelledby="lightbox-title"
|
||||||
use:focusTrap={{ onclose }}
|
use:focusTrap={{ onclose }}
|
||||||
use:scrollLock
|
use:scrollLock
|
||||||
|
use:modalInert
|
||||||
>
|
>
|
||||||
<div class="flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl bg-white dark:bg-gray-900">
|
<div class="flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl bg-white dark:bg-gray-900">
|
||||||
<!-- Media -->
|
<!-- Media -->
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { focusTrap } from '$lib/actions/focus-trap';
|
import { focusTrap } from '$lib/actions/focus-trap';
|
||||||
import { scrollLock } from '$lib/actions/scroll-lock';
|
import { scrollLock } from '$lib/actions/scroll-lock';
|
||||||
|
import { modalInert } from '$lib/actions/modal-inert';
|
||||||
import type { Snippet } from 'svelte';
|
import type { Snippet } from 'svelte';
|
||||||
|
|
||||||
// Accessible name is REQUIRED. Pass `titleId` when the dialog renders its own
|
// Accessible name is REQUIRED. Pass `titleId` when the dialog renders its own
|
||||||
@@ -35,24 +36,29 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if open}
|
{#if open}
|
||||||
<button
|
<!-- display:contents wrapper: keeps the backdrop + dialog visually unchanged
|
||||||
type="button"
|
while giving `modalInert` a single node whose siblings (the background
|
||||||
class="fixed inset-0 z-50 bg-black/50"
|
page, nav, etc.) get inerted for assistive tech. -->
|
||||||
aria-label="Schließen"
|
<div class="contents" use:modalInert>
|
||||||
tabindex="-1"
|
<button
|
||||||
onclick={closeOnBackdrop ? onClose : () => {}}
|
type="button"
|
||||||
></button>
|
class="fixed inset-0 z-50 bg-black/50"
|
||||||
<div
|
aria-label="Schließen"
|
||||||
class="pointer-events-none fixed inset-0 z-50 flex items-center justify-center p-4"
|
tabindex="-1"
|
||||||
role="dialog"
|
onclick={closeOnBackdrop ? onClose : () => {}}
|
||||||
aria-modal="true"
|
></button>
|
||||||
aria-labelledby={titleId}
|
<div
|
||||||
aria-label={titleId ? undefined : ariaLabel}
|
class="pointer-events-none fixed inset-0 z-50 flex items-center justify-center p-4"
|
||||||
use:focusTrap={{ onclose: onClose }}
|
role="dialog"
|
||||||
use:scrollLock
|
aria-modal="true"
|
||||||
>
|
aria-labelledby={titleId}
|
||||||
<div class="pointer-events-auto w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900">
|
aria-label={titleId ? undefined : ariaLabel}
|
||||||
{@render children()}
|
use:focusTrap={{ onclose: onClose }}
|
||||||
|
use:scrollLock
|
||||||
|
>
|
||||||
|
<div class="pointer-events-auto w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-900">
|
||||||
|
{@render children()}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -73,6 +73,23 @@ export class SlideQueue {
|
|||||||
return { wasCurrent: currentId === id };
|
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. */
|
/** Look up a slide by id — for the diashow page to render the current slide. */
|
||||||
get(id: string): FeedUpload | undefined {
|
get(id: string): FeedUpload | undefined {
|
||||||
return this.allKnown.get(id);
|
return this.allKnown.get(id);
|
||||||
|
|||||||
@@ -7,9 +7,11 @@
|
|||||||
src: string;
|
src: string;
|
||||||
isVideo: boolean;
|
isVideo: boolean;
|
||||||
durationMs: number;
|
durationMs: number;
|
||||||
|
/** Fired when a video slide finishes so the parent can advance early. */
|
||||||
|
onended?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
let { src, isVideo, durationMs }: Props = $props();
|
let { src, isVideo, durationMs, onended }: Props = $props();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
@@ -23,6 +25,7 @@
|
|||||||
autoplay
|
autoplay
|
||||||
muted
|
muted
|
||||||
playsinline
|
playsinline
|
||||||
|
{onended}
|
||||||
class="h-full w-full object-contain"
|
class="h-full w-full object-contain"
|
||||||
></video>
|
></video>
|
||||||
{:else}
|
{:else}
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ export interface TransitionProps {
|
|||||||
src: string;
|
src: string;
|
||||||
isVideo: boolean;
|
isVideo: boolean;
|
||||||
durationMs: number;
|
durationMs: number;
|
||||||
|
/** Fired when a video slide finishes so the parent can advance early. */
|
||||||
|
onended?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const transitions: SlideTransition[] = [
|
export const transitions: SlideTransition[] = [
|
||||||
|
|||||||
@@ -6,9 +6,11 @@
|
|||||||
src: string;
|
src: string;
|
||||||
isVideo: boolean;
|
isVideo: boolean;
|
||||||
durationMs: number;
|
durationMs: number;
|
||||||
|
/** Fired when a video slide finishes so the parent can advance early. */
|
||||||
|
onended?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
let { src, isVideo, durationMs }: Props = $props();
|
let { src, isVideo, durationMs, onended }: Props = $props();
|
||||||
|
|
||||||
// Mild random pan so each slide feels different. Range chosen so the image never
|
// Mild random pan so each slide feels different. Range chosen so the image never
|
||||||
// pans out of frame given the object-fit: cover.
|
// pans out of frame given the object-fit: cover.
|
||||||
@@ -27,6 +29,7 @@
|
|||||||
autoplay
|
autoplay
|
||||||
muted
|
muted
|
||||||
playsinline
|
playsinline
|
||||||
|
{onended}
|
||||||
class="h-full w-full object-contain"
|
class="h-full w-full object-contain"
|
||||||
></video>
|
></video>
|
||||||
{:else}
|
{:else}
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ const KNOWN_EVENTS = [
|
|||||||
'upload-deleted',
|
'upload-deleted',
|
||||||
'like-update',
|
'like-update',
|
||||||
'new-comment',
|
'new-comment',
|
||||||
|
'comment-deleted',
|
||||||
|
'user-hidden',
|
||||||
'event-closed',
|
'event-closed',
|
||||||
'event-opened',
|
'event-opened',
|
||||||
'event-updated',
|
'event-updated',
|
||||||
@@ -174,15 +176,31 @@ async function deltaFetchAndFan(since: string): Promise<void> {
|
|||||||
|
|
||||||
// Page Visibility API: close while hidden, reopen on focus. On reopen `connectSse`'s
|
// Page Visibility API: close while hidden, reopen on focus. On reopen `connectSse`'s
|
||||||
// `onopen` runs the delta fetch.
|
// `onopen` runs the delta fetch.
|
||||||
if (typeof document !== 'undefined') {
|
function handleVisibilityChange() {
|
||||||
document.addEventListener('visibilitychange', () => {
|
if (document.hidden) {
|
||||||
if (document.hidden) {
|
disconnectSse();
|
||||||
disconnectSse();
|
} else {
|
||||||
} else {
|
// User-initiated reconnect — clear backoff so we don't wait out a long
|
||||||
// User-initiated reconnect — clear backoff so we don't wait out a long
|
// retry delay that was scheduled from a prior background error.
|
||||||
// retry delay that was scheduled from a prior background error.
|
reconnectAttempt = 0;
|
||||||
reconnectAttempt = 0;
|
connectSse();
|
||||||
connectSse();
|
}
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let visibilityBound = false;
|
||||||
|
|
||||||
|
/** Idempotent: safe to call more than once; only the first registration sticks. */
|
||||||
|
function bindVisibility() {
|
||||||
|
if (visibilityBound || typeof document === 'undefined') return;
|
||||||
|
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||||
|
visibilityBound = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove the visibility listener (e.g. on teardown / test cleanup). */
|
||||||
|
export function teardownVisibility() {
|
||||||
|
if (!visibilityBound || typeof document === 'undefined') return;
|
||||||
|
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||||
|
visibilityBound = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bindVisibility();
|
||||||
|
|||||||
@@ -27,6 +27,9 @@ export interface FeedResponse {
|
|||||||
export interface DeltaResponse {
|
export interface DeltaResponse {
|
||||||
uploads: FeedUpload[];
|
uploads: FeedUpload[];
|
||||||
deleted_ids: string[];
|
deleted_ids: string[];
|
||||||
|
// True when the delta hit the backend cap and is only the newest slice of the
|
||||||
|
// gap — the client must full-refresh rather than merge (see feed-delta handler).
|
||||||
|
truncated: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
// mirrors backend/src/handlers/feed.rs::HashtagCount
|
// mirrors backend/src/handlers/feed.rs::HashtagCount
|
||||||
|
|||||||
@@ -57,8 +57,9 @@
|
|||||||
title: 'Limits & Größen',
|
title: 'Limits & Größen',
|
||||||
fields: [
|
fields: [
|
||||||
{ key: 'max_image_size_mb', label: 'Max. Bildgröße (MB)', kind: 'number' },
|
{ 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: 'max_video_size_mb', label: 'Max. Videogröße (MB)', kind: 'number' }
|
||||||
{ key: 'compression_concurrency', label: 'Kompressions-Worker', 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 () => {
|
onMount(async () => {
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
const role = getRole();
|
if (!token) {
|
||||||
if (!token || role !== 'admin') {
|
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');
|
goto('/admin/login');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,6 +52,13 @@
|
|||||||
if (current) scheduleNext();
|
if (current) scheduleNext();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A video finished before its dwell/12s cap — advance immediately (unless paused).
|
||||||
|
// The {#key current.id} block destroys the old <video> on advance, so a fallback
|
||||||
|
// timer that already fired can't trigger this handler for a stale slide.
|
||||||
|
function handleVideoEnded() {
|
||||||
|
if (!paused) advance();
|
||||||
|
}
|
||||||
|
|
||||||
async function loadInitial() {
|
async function loadInitial() {
|
||||||
try {
|
try {
|
||||||
const feed = await api.get<FeedResponse>('/feed?limit=200');
|
const feed = await api.get<FeedResponse>('/feed?limit=200');
|
||||||
@@ -92,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() {
|
function revealOverlay() {
|
||||||
showOverlay = true;
|
showOverlay = true;
|
||||||
if (overlayHideTimer) clearTimeout(overlayHideTimer);
|
if (overlayHideTimer) clearTimeout(overlayHideTimer);
|
||||||
@@ -138,6 +155,7 @@
|
|||||||
void acquireWakeLock();
|
void acquireWakeLock();
|
||||||
unsubs.push(onSseEvent('upload-processed', handleUploadProcessed));
|
unsubs.push(onSseEvent('upload-processed', handleUploadProcessed));
|
||||||
unsubs.push(onSseEvent('upload-deleted', handleUploadDeleted));
|
unsubs.push(onSseEvent('upload-deleted', handleUploadDeleted));
|
||||||
|
unsubs.push(onSseEvent('user-hidden', handleUserHidden));
|
||||||
void loadInitial();
|
void loadInitial();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -163,6 +181,7 @@
|
|||||||
src={mediaSrc}
|
src={mediaSrc}
|
||||||
{isVideo}
|
{isVideo}
|
||||||
durationMs={transitionDef.defaultDurationMs}
|
durationMs={transitionDef.defaultDurationMs}
|
||||||
|
onended={handleVideoEnded}
|
||||||
/>
|
/>
|
||||||
{/key}
|
{/key}
|
||||||
{:else if isEmpty()}
|
{:else if isEmpty()}
|
||||||
|
|||||||
@@ -27,6 +27,9 @@
|
|||||||
let refreshing = $state(false);
|
let refreshing = $state(false);
|
||||||
let pullProgress = $state(0); // 0–1+ during the drag, 0 when idle
|
let pullProgress = $state(0); // 0–1+ during the drag, 0 when idle
|
||||||
let selectedUpload = $state<FeedUpload | null>(null);
|
let selectedUpload = $state<FeedUpload | null>(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 sentinel: HTMLDivElement;
|
||||||
let feedObserver: IntersectionObserver | null = null;
|
let feedObserver: IntersectionObserver | null = null;
|
||||||
let inPlaceRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
let inPlaceRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
@@ -196,6 +199,28 @@
|
|||||||
if (selectedUpload?.id === payload.upload_id) selectedUpload = null;
|
if (selectedUpload?.id === payload.upload_id) selectedUpload = null;
|
||||||
} catch { /* ignore */ }
|
} 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
|
// 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
|
// 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.
|
// would yank every scrolled-down user back to the top on each reaction.
|
||||||
@@ -206,6 +231,15 @@
|
|||||||
onSseEvent('feed-delta', (data) => {
|
onSseEvent('feed-delta', (data) => {
|
||||||
try {
|
try {
|
||||||
const delta = JSON.parse(data) as DeltaResponse;
|
const delta = JSON.parse(data) as DeltaResponse;
|
||||||
|
if (delta.truncated) {
|
||||||
|
// 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.
|
||||||
|
// 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) {
|
if (delta.uploads.length) {
|
||||||
const seen = new Set(uploads.map((u) => u.id));
|
const seen = new Set(uploads.map((u) => u.id));
|
||||||
const fresh = delta.uploads.filter((u) => !seen.has(u.id));
|
const fresh = delta.uploads.filter((u) => !seen.has(u.id));
|
||||||
@@ -283,6 +317,10 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function loadFeed(refresh = false) {
|
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 {
|
try {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
if (!refresh && nextCursor) params.set('cursor', nextCursor);
|
if (!refresh && nextCursor) params.set('cursor', nextCursor);
|
||||||
@@ -433,6 +471,17 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
{#if feedStale}
|
||||||
|
<div class="pointer-events-none fixed left-0 right-0 top-[calc(env(safe-area-inset-top)+0.5rem)] z-40 flex justify-center">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="pointer-events-auto rounded-full bg-blue-600 px-4 py-1.5 text-xs font-semibold text-white shadow-lg hover:bg-blue-700"
|
||||||
|
onclick={() => { feedStale = false; void loadFeed(true); }}
|
||||||
|
>
|
||||||
|
Neue Beiträge – tippen zum Aktualisieren
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
<!-- Sticky header — opaque fallback for browsers without backdrop-filter. -->
|
<!-- Sticky header — opaque fallback for browsers without backdrop-filter. -->
|
||||||
<div class="sticky top-0 z-30 border-b border-gray-200 bg-white/95 pt-[env(safe-area-inset-top)] backdrop-blur supports-[not(backdrop-filter:blur(0))]:bg-white dark:border-gray-800 dark:bg-gray-900/95 dark:supports-[not(backdrop-filter:blur(0))]:bg-gray-900">
|
<div class="sticky top-0 z-30 border-b border-gray-200 bg-white/95 pt-[env(safe-area-inset-top)] backdrop-blur supports-[not(backdrop-filter:blur(0))]:bg-white dark:border-gray-800 dark:bg-gray-900/95 dark:supports-[not(backdrop-filter:blur(0))]:bg-gray-900">
|
||||||
<div class="mx-auto flex max-w-2xl items-center justify-between px-4 py-3">
|
<div class="mx-auto flex max-w-2xl items-center justify-between px-4 py-3">
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation';
|
||||||
import { getToken, getRole } from '$lib/auth';
|
import { getToken, getRole } from '$lib/auth';
|
||||||
import { api } from '$lib/api';
|
import { api } from '$lib/api';
|
||||||
|
import type { MeContextDto } from '$lib/types';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import { toast, toastError } from '$lib/toast-store';
|
import { toast, toastError } from '$lib/toast-store';
|
||||||
import ConfirmSheet from '$lib/components/ConfirmSheet.svelte';
|
import ConfirmSheet from '$lib/components/ConfirmSheet.svelte';
|
||||||
@@ -86,8 +87,22 @@
|
|||||||
|
|
||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
const role = getRole();
|
if (!token) {
|
||||||
if (!token || (role !== 'host' && role !== 'admin')) {
|
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<MeContextDto>('/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');
|
goto('/join');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,28 @@ const config = {
|
|||||||
runes: true
|
runes: true
|
||||||
},
|
},
|
||||||
kit: {
|
kit: {
|
||||||
adapter: adapter()
|
adapter: adapter(),
|
||||||
|
// Content-Security-Policy — the highest-value header for this UGC app and the
|
||||||
|
// cheapest hardening of the localStorage-based auth (the whole model rests on
|
||||||
|
// never having an XSS). `mode: 'auto'` lets SvelteKit nonce/hash its own inline
|
||||||
|
// hydration script, so script-src stays free of 'unsafe-inline'.
|
||||||
|
csp: {
|
||||||
|
mode: 'auto',
|
||||||
|
directives: {
|
||||||
|
'default-src': ['self'],
|
||||||
|
'script-src': ['self'],
|
||||||
|
// Svelte emits inline style attributes (style: directives); allow them.
|
||||||
|
'style-src': ['self', 'unsafe-inline'],
|
||||||
|
'img-src': ['self', 'data:', 'blob:'],
|
||||||
|
'media-src': ['self', 'blob:'],
|
||||||
|
'font-src': ['self'],
|
||||||
|
'connect-src': ['self'],
|
||||||
|
'object-src': ['none'],
|
||||||
|
'base-uri': ['self'],
|
||||||
|
'form-action': ['self'],
|
||||||
|
'frame-ancestors': ['none']
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user