diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index f16caca..c6732b9 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -110,6 +110,9 @@ services: S3_ENDPOINT: ${S3_ENDPOINT:-} S3_BUCKET: ${S3_BUCKET:-} S3_REGION: ${S3_REGION:-us-east-1} + # Cloudflare Turnstile on the e-mail sign-up and reset forms (the + # TURNSTILE_SECRET_KEY is in .env.secrets). Without both: no check. + TURNSTILE_SITE_KEY: ${TURNSTILE_SITE_KEY:-} # The log also goes to the logs volume, one file a day, kept 30 days # (deploy/README.md: Logs). LOG_DIR: /logs diff --git a/docker-compose.yml b/docker-compose.yml index 13c2108..62c8fcf 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -54,6 +54,10 @@ services: SUMMARY_MODEL: ${SUMMARY_MODEL:-} # E-mail + password login; off by default (Google, Apple and Facebook only). PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false} + # Cloudflare Turnstile (off without both keys; Cloudflare's test keys + # 1x00000000000000000000AA / 1x0000000000000000000000000000000AA always pass). + TURNSTILE_SITE_KEY: ${TURNSTILE_SITE_KEY:-} + TURNSTILE_SECRET_KEY: ${TURNSTILE_SECRET_KEY:-} # Stand-in payment (adds an analysis unit at once) until Stripe is connected. MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true} # Stripe purchases for everyone (false: admins only, until the opening; diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs index 8906619..8ba6e0b 100644 --- a/services/backend/src/config.rs +++ b/services/backend/src/config.rs @@ -110,6 +110,10 @@ pub struct Config { /// Object storage of the uploaded photos (see [`crate::storage`]); `None` /// when `S3_ENDPOINT` is not set (photo uploads are then refused). pub storage: Option, + /// `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET_KEY`: Cloudflare Turnstile + /// on the e-mail sign-up and password reset forms (see [`crate::turnstile`]); + /// `None` without both (development): no check. + pub turnstile: Option, /// `S3_CREATE_BUCKET` (default false): create the bucket at startup if it /// is missing (development; in production it is made in the console). pub storage_create_bucket: bool, @@ -226,6 +230,14 @@ impl Config { Some("open") => SignupMode::Open, Some(other) => bail!("invalid SIGNUP_MODE '{other}': use 'invite' or 'open'"), }, + turnstile: match (var("TURNSTILE_SITE_KEY"), var("TURNSTILE_SECRET_KEY")) { + (Some(site_key), Some(secret)) => Some(crate::turnstile::TurnstileConfig { + site_key, + secret, + verify_url: var("TURNSTILE_VERIFY_URL").unwrap_or_else(|| crate::turnstile::VERIFY_URL.to_string()), + }), + _ => None, + }, storage: match var("S3_ENDPOINT") { None => None, Some(endpoint) => Some(crate::storage::StorageConfig { @@ -279,6 +291,7 @@ impl Config { max_charts_per_user: 50, free_person_slots: 5, signup_mode: SignupMode::Open, + turnstile: None, storage: Some(crate::storage::StorageConfig { endpoint: format!("{horoscope_api_url}/s3"), bucket: "photos".into(), diff --git a/services/backend/src/main.rs b/services/backend/src/main.rs index 034138c..9684092 100644 --- a/services/backend/src/main.rs +++ b/services/backend/src/main.rs @@ -23,6 +23,7 @@ mod storage; mod stripe; #[cfg(test)] mod tests; +mod turnstile; mod views; use std::sync::Arc; @@ -49,6 +50,9 @@ pub struct AppState { pub calculator_limiter: LoginLimiter, /// The public place search (typing makes several calls), per visitor address. pub places_limiter: LoginLimiter, + /// E-mail sign-ups and password reset requests, per visitor address (each + /// sends an e-mail, so a script must not send thousands). + pub signup_limiter: LoginLimiter, /// Share visits already counted (link and visitor address, for half an hour): /// a reload is not a new visit, without storing anything in the browser. pub share_visits: LoginLimiter, @@ -70,6 +74,7 @@ impl AppState { calculator_limiter: LoginLimiter::new(30, Duration::from_secs(60 * 60)), places_limiter: LoginLimiter::new(300, Duration::from_secs(60 * 60)), share_visits: LoginLimiter::new(1, Duration::from_secs(30 * 60)), + signup_limiter: LoginLimiter::new(10, Duration::from_secs(60 * 60)), models: models::Catalog::new(&config.openrouter_models_url), stripe: stripe::Client::default(), storage: config.storage.clone().map(storage::Storage::new), diff --git a/services/backend/src/routes/auth.rs b/services/backend/src/routes/auth.rs index 74e5e85..2877397 100644 --- a/services/backend/src/routes/auth.rs +++ b/services/backend/src/routes/auth.rs @@ -227,6 +227,19 @@ pub struct RegisterRequest { invite_token: Option, /// The slug of the shared link the visitor came from. referral: Option, + /// Cloudflare Turnstile's token (see [`crate::turnstile`]). + #[serde(default)] + turnstile_token: Option, +} + +/// Before a sign-up or reset e-mail goes out: at most a few per visitor +/// address an hour, and Cloudflare Turnstile's check when it is set up. +async fn not_a_robot(state: &AppState, headers: &axum::http::HeaderMap, token: Option<&str>) -> Result<(), ApiError> { + let ip = super::client_ip(headers); + if let Some(ip) = &ip { + state.signup_limiter.hit(ip)?; + } + crate::turnstile::verify(state.config.turnstile.as_ref(), token, ip.as_deref()).await } /// Password endpoints answer 403 while `PASSWORD_LOGIN` is off. @@ -244,10 +257,12 @@ pub fn password_login_enabled(state: &crate::AppState) -> Result<(), ApiError> { /// password instead), so the form does not reveal who is registered. pub async fn register( State(state): St, + headers: axum::http::HeaderMap, WithRejection(Json(req), _): Body, ) -> ApiResult { password_login_enabled(&state)?; let email = normalize_email(&req.email)?; + not_a_robot(&state, &headers, req.turnstile_token.as_deref()).await?; let locale = validate_locale(&state, req.locale.as_deref())?; let mut tx = state.db.begin().await?; @@ -553,6 +568,9 @@ pub async fn logout_all(State(state): St, auth: AuthUser, jar: CookieJar) -> Api #[serde(deny_unknown_fields)] pub struct ResetRequest { email: String, + /// Cloudflare Turnstile's token (see [`crate::turnstile`]). + #[serde(default)] + turnstile_token: Option, } /// Forgotten password: a link to set a new one (also adds a password to a @@ -560,9 +578,11 @@ pub struct ResetRequest { /// whether the address is registered. pub async fn request_password_reset( State(state): St, + headers: axum::http::HeaderMap, WithRejection(Json(req), _): Body, ) -> ApiResult { password_login_enabled(&state)?; + not_a_robot(&state, &headers, req.turnstile_token.as_deref()).await?; let Ok(email) = normalize_email(&req.email) else { return Ok(StatusCode::ACCEPTED) }; let mut tx = state.db.begin().await?; let user: Option = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1 FOR UPDATE")) diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 5d7b731..4435698 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -233,5 +233,7 @@ async fn public_config(State(state): St) -> Json { "referral_rewards": c.referral_rewards, "signup_mode": c.signup_mode.as_str(), "password_min_length": crate::auth::MIN_PASSWORD_LEN, + // Cloudflare Turnstile on the e-mail sign-up and reset forms (null: none). + "turnstile_site_key": c.turnstile.as_ref().map(|t| t.site_key.clone()), })) } diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 3647eec..46b3dd6 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -226,12 +226,20 @@ async fn fake_s3( } } +/// Cloudflare Turnstile: the token "ok" with the test secret passes. +async fn fake_turnstile(axum::Form(form): axum::Form>) -> Json { + let ok = form.get("secret").map(String::as_str) == Some("test-secret") + && form.get("response").map(String::as_str) == Some("ok"); + Json(json!({ "success": ok, "error-codes": if ok { json!([]) } else { json!(["invalid-input-response"]) } })) +} + async fn fake_services_with(s3: FakeS3) -> String { let objects = Router::new().route("/s3/photos/{*key}", get(fake_s3).put(fake_s3).delete(fake_s3)).with_state(s3); let app = Router::new() .merge(objects) .route("/billingo/documents/{id}/download", get(fake_billingo_pdf)) .route("/openrouter/models", get(fake_openrouter_models)) + .route("/turnstile/siteverify", post(fake_turnstile)) .route("/v1/checkout/sessions", post(fake_stripe_create)) .route("/v1/checkout/sessions/{id}", get(fake_stripe_get)) .route("/v1/refunds", post(fake_stripe_refund)) @@ -4031,3 +4039,42 @@ async fn a_gift_can_be_e_mailed_at_a_chosen_time(pool: PgPool) { assert_eq!(r.status, StatusCode::OK, "{}", r.body); assert_eq!(app.outbox_count("cili@example.com", "gift_package").await, 0); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn email_sign_up_checks_turnstile_and_limits_each_address(pool: PgPool) { + let app = TestApp::with_config(pool, |c| { + c.turnstile = Some(crate::turnstile::TurnstileConfig { + site_key: "site-key".into(), + secret: "test-secret".into(), + verify_url: format!("{}/turnstile/siteverify", c.horoscope_api_url), + }); + }) + .await; + assert_eq!(app.get("/v1/config", None).await.body["turnstile_site_key"], "site-key"); + let ip = [("x-real-ip", "203.0.113.50")]; + let sign_up = |token: Option<&str>| json!({ "email": "anna@example.com", "turnstile_token": token }); + + // No token or a wrong one: no account, no e-mail. + for token in [None, Some("rossz")] { + let r = app.call_with("POST", "/v1/auth/register", None, Some(sign_up(token)), &ip).await; + assert_eq!(r.status, StatusCode::BAD_REQUEST, "{}", r.body); + } + let users: i64 = sqlx::query_scalar("SELECT count(*) FROM users").fetch_one(&app.pool).await.unwrap(); + assert_eq!(users, 0); + let r = app.call_with("POST", "/v1/auth/register", None, Some(sign_up(Some("ok"))), &ip).await; + assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body); + let reset = |token: Option<&str>| json!({ "email": "anna@example.com", "turnstile_token": token }); + let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(None)), &ip).await; + assert_eq!(r.status, StatusCode::BAD_REQUEST); + + // Ten e-mail requests an hour from one address (the four above count too). + for _ in 0..6 { + let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &ip).await; + assert_eq!(r.status, StatusCode::ACCEPTED); + } + let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &ip).await; + assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS); + let elsewhere = [("x-real-ip", "198.51.100.60")]; + let r = app.call_with("POST", "/v1/auth/password-reset", None, Some(reset(Some("ok"))), &elsewhere).await; + assert_eq!(r.status, StatusCode::ACCEPTED); +} diff --git a/services/backend/src/turnstile.rs b/services/backend/src/turnstile.rs new file mode 100644 index 0000000..e601b57 --- /dev/null +++ b/services/backend/src/turnstile.rs @@ -0,0 +1,63 @@ +//! Cloudflare Turnstile: the e-mail sign-up and the password reset forms +//! carry a token from Cloudflare's widget (usually invisible), checked here +//! before an e-mail goes out. Without the keys (development) there is no +//! check. Cloudflare not answering counts as a failed check. + +use std::sync::OnceLock; +use std::time::Duration; + +use serde::Deserialize; + +use crate::error::ApiError; + +pub const VERIFY_URL: &str = "https://challenges.cloudflare.com/turnstile/v0/siteverify"; + +#[derive(Clone, Debug)] +pub struct TurnstileConfig { + /// Public: the page's widget uses it (`/v1/config`). + pub site_key: String, + pub secret: String, + pub verify_url: String, +} + +#[derive(Deserialize)] +struct Answer { + success: bool, + #[serde(default, rename = "error-codes")] + error_codes: Vec, +} + +fn client() -> &'static reqwest::Client { + static CLIENT: OnceLock = OnceLock::new(); + CLIENT.get_or_init(|| reqwest::Client::builder().timeout(Duration::from_secs(8)).build().expect("an HTTP client")) +} + +fn refused() -> ApiError { + ApiError::BadRequest("Kérjük, igazold, hogy nem robot vagy (az ellenőrzés nem sikerült), és próbáld újra.".into()) +} + +/// Checks the widget's token (with the visitor's address, when known). +pub async fn verify(config: Option<&TurnstileConfig>, token: Option<&str>, ip: Option<&str>) -> Result<(), ApiError> { + let Some(config) = config else { return Ok(()) }; + let token = token.map(str::trim).filter(|t| !t.is_empty() && t.len() <= 2048).ok_or_else(refused)?; + let mut form = vec![("secret", config.secret.as_str()), ("response", token)]; + if let Some(ip) = ip { + form.push(("remoteip", ip)); + } + let answer: Answer = match client().post(&config.verify_url).form(&form).send().await { + Ok(res) => res.json().await.map_err(|e| { + tracing::warn!(error = %e, "turnstile answer not understood"); + refused() + })?, + Err(e) => { + tracing::warn!(error = %e, "turnstile not reachable"); + return Err(refused()); + } + }; + if answer.success { + Ok(()) + } else { + tracing::info!(codes = ?answer.error_codes, "turnstile check failed"); + Err(refused()) + } +} diff --git a/services/frontend/src/app/adatvedelem/page.tsx b/services/frontend/src/app/adatvedelem/page.tsx index 7e7dfb0..ba8b63a 100644 --- a/services/frontend/src/app/adatvedelem/page.tsx +++ b/services/frontend/src/app/adatvedelem/page.tsx @@ -254,7 +254,9 @@ export default async function PrivacyPage() {
  • Cloudflare, Inc. – a forgalom továbbítása és a támadások elleni védelem; az oldal - letöltésekor kezeli az IP-címedet és a kérés adatait. + letöltésekor kezeli az IP-címedet és a kérés adatait. Az e-mailes regisztrációnál és a jelszókérésnél a + Turnstile szolgáltatásával ellenőrzi, hogy nem gép küldi az űrlapot (ehhez a böngésző jellemzőit is + vizsgálja).
  • Google LLC – bejelentkezés Google-fiókkal. diff --git a/services/frontend/src/app/belepes/PasswordLogin.tsx b/services/frontend/src/app/belepes/PasswordLogin.tsx index ad53be0..aaaf61b 100644 --- a/services/frontend/src/app/belepes/PasswordLogin.tsx +++ b/services/frontend/src/app/belepes/PasswordLogin.tsx @@ -3,6 +3,7 @@ import { useRouter } from "next/navigation"; import { useState } from "react"; +import { Turnstile } from "@/components/Turnstile"; import { ApiError, api, errorText } from "@/lib/api"; type Mode = "login" | "register" | "forgot"; @@ -25,9 +26,12 @@ export function PasswordLogin({ inviteToken = null, referral = null, initialMode = "login", + turnstileKey = null, }: { target: string; inviteToken?: string | null; + /** Cloudflare Turnstile on the sign-up and reset forms (null: none). */ + turnstileKey?: string | null; /** The shared link the visitor came from (in the login link: `?ref=`), for the sharer's reward. */ referral?: string | null; initialMode?: Mode; @@ -41,6 +45,10 @@ export function PasswordLogin({ const [error, setError] = useState(null); const [sent, setSent] = useState(null); const [uninvited, setUninvited] = useState(false); + // Turnstile's token (sign-up and reset only); a new round after each try. + const [token, setToken] = useState(null); + const [round, setRound] = useState(0); + const checked = mode === "login" || !turnstileKey; function switchTo(next: Mode) { setMode(next); @@ -63,10 +71,17 @@ export function PasswordLogin({ } if (mode === "register") { await api("/auth/register", { - body: { email, display_name: name.trim() || null, locale: "hu", invite_token: inviteToken, referral }, + body: { + email, + display_name: name.trim() || null, + locale: "hu", + invite_token: inviteToken, + referral, + turnstile_token: token, + }, }); } else { - await api("/auth/password-reset", { body: { email } }); + await api("/auth/password-reset", { body: { email, turnstile_token: token } }); } setSent(mode); } catch (err) { @@ -74,6 +89,8 @@ export function PasswordLogin({ else setError(mode === "login" ? loginError(err) : errorText(err)); } finally { setBusy(false); + // A token works once. + if (mode !== "login" && turnstileKey) setRound((r) => r + 1); } } @@ -156,14 +173,17 @@ export function PasswordLogin({ jelszót is beállíthatsz.

    )} - {error && (

    diff --git a/services/frontend/src/app/belepes/page.tsx b/services/frontend/src/app/belepes/page.tsx index 720b922..4241f52 100644 --- a/services/frontend/src/app/belepes/page.tsx +++ b/services/frontend/src/app/belepes/page.tsx @@ -169,7 +169,13 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis )} {password && ( - + )} ) : ( diff --git a/services/frontend/src/app/privacy/page.tsx b/services/frontend/src/app/privacy/page.tsx index c34176f..f4c6a09 100644 --- a/services/frontend/src/app/privacy/page.tsx +++ b/services/frontend/src/app/privacy/page.tsx @@ -242,7 +242,8 @@ export default async function PrivacyPolicyPage() {

  • Cloudflare, Inc.: delivering traffic and protecting against attacks; processes your IP - address and request data when the site loads. + address and request data when the site loads. On the e-mail sign-up and password request forms its + Turnstile service checks that a person, not a script, sends the form (looking at browser features too).
  • Google LLC: signing in with a Google account. diff --git a/services/frontend/src/components/Turnstile.tsx b/services/frontend/src/components/Turnstile.tsx new file mode 100644 index 0000000..f673b5d --- /dev/null +++ b/services/frontend/src/components/Turnstile.tsx @@ -0,0 +1,86 @@ +"use client"; + +import { useEffect, useRef } from "react"; + +type TurnstileApi = { + render: (el: HTMLElement, options: Record) => string; + reset: (id: string) => void; + remove: (id: string) => void; +}; + +declare global { + interface Window { + turnstile?: TurnstileApi; + } +} + +const SCRIPT = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"; +let loading: Promise | null = null; + +function load(): Promise { + if (window.turnstile) return Promise.resolve(window.turnstile); + loading ??= new Promise((resolve, reject) => { + const script = document.createElement("script"); + script.src = SCRIPT; + script.async = true; + script.onload = () => (window.turnstile ? resolve(window.turnstile) : reject(new Error("turnstile"))); + script.onerror = () => { + loading = null; + reject(new Error("turnstile")); + }; + document.head.appendChild(script); + }); + return loading; +} + +/** + * Cloudflare Turnstile ("nem robot vagy?"): usually invisible, it shows a box + * only when Cloudflare wants a click. `onToken` gets the token (null when it + * expires); a new `round` asks for a fresh one (a token works once). + */ +export function Turnstile({ + siteKey, + onToken, + round = 0, +}: { + siteKey: string; + onToken: (token: string | null) => void; + round?: number; +}) { + const box = useRef(null); + const widget = useRef(null); + const callback = useRef(onToken); + callback.current = onToken; + + useEffect(() => { + let gone = false; + load() + .then((api) => { + if (gone || !box.current || widget.current) return; + widget.current = api.render(box.current, { + sitekey: siteKey, + appearance: "interaction-only", + language: "hu", + theme: "auto", + callback: (token: string) => callback.current(token), + "expired-callback": () => callback.current(null), + "error-callback": () => callback.current(null), + }); + }) + .catch(() => callback.current(null)); + return () => { + gone = true; + if (widget.current && window.turnstile) window.turnstile.remove(widget.current); + widget.current = null; + }; + }, [siteKey]); + + useEffect(() => { + if (round > 0 && widget.current && window.turnstile) { + callback.current(null); + window.turnstile.reset(widget.current); + } + }, [round]); + + return
    ; +} diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts index 517bc3e..8209827 100644 --- a/services/frontend/src/lib/types.ts +++ b/services/frontend/src/lib/types.ts @@ -98,6 +98,8 @@ export interface Question { export interface PublicConfig { google_login: { enabled: boolean; client_id: string | null }; + /** Cloudflare Turnstile on the e-mail sign-up and reset forms (null: none). */ + turnstile_site_key?: string | null; /** Sign in with Apple; `client_id` is the Services ID. */ apple_login?: { enabled: boolean; client_id: string | null }; locales: string[];