From 2eea1042a5cb63d31e7b1b1dae212f4c9aaa153b Mon Sep 17 00:00:00 2001 From: feco Date: Sat, 21 Nov 2026 20:31:45 +0000 Subject: [PATCH] Public sign calculator and the twelve sign pages, SEO basics /aszcendens-kalkulator: Sun, Moon and Ascendant signs from birth data without an account. A calculation only (no AI, nothing saved), limited to 30 calculations and 300 place searches an hour per visitor address (POST /v1/public/signs, GET /v1/public/geo/*). Without a birth time there is no Ascendant, and signs near a border are marked uncertain. /csillagjegyek and /csillagjegyek/{jegy}: the twelve signs with facts, Sun, Moon and Ascendant, love, work, a common misbelief and an offer, each written on its own. Links to the calculator and sign-up. SEO: metadataBase and canonical addresses, hreflang between the Hungarian and English privacy pages, Organization and WebSite JSON-LD on the home page, FAQPage on the calculator, BreadcrumbList on the sign pages; the sitemap lists the new pages, the footers link them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- crates/horoscope-client/src/lib.rs | 25 ++ services/backend/README.md | 2 + services/backend/src/auth.rs | 11 +- services/backend/src/main.rs | 6 + services/backend/src/routes/calculator.rs | 124 +++++++ services/backend/src/routes/mod.rs | 4 + services/backend/src/tests.rs | 58 ++- services/frontend/src/app/Landing.tsx | 2 + .../frontend/src/app/adatvedelem/page.tsx | 1 + .../aszcendens-kalkulator/SignCalculator.tsx | 310 ++++++++++++++++ .../src/app/aszcendens-kalkulator/page.tsx | 106 ++++++ .../src/app/csillagjegyek/[jegy]/page.tsx | 159 ++++++++ .../frontend/src/app/csillagjegyek/page.tsx | 63 ++++ services/frontend/src/app/globals.css | 46 +++ services/frontend/src/app/layout.tsx | 13 +- services/frontend/src/app/page.tsx | 32 +- services/frontend/src/app/privacy/page.tsx | 1 + .../frontend/src/app/profil/BirthForm.tsx | 59 +-- services/frontend/src/app/sitemap.ts | 4 + .../frontend/src/components/PublicFooter.tsx | 30 ++ services/frontend/src/content/zodiac.ts | 347 ++++++++++++++++++ services/frontend/src/lib/birth.ts | 39 ++ 22 files changed, 1395 insertions(+), 47 deletions(-) create mode 100644 services/backend/src/routes/calculator.rs create mode 100644 services/frontend/src/app/aszcendens-kalkulator/SignCalculator.tsx create mode 100644 services/frontend/src/app/aszcendens-kalkulator/page.tsx create mode 100644 services/frontend/src/app/csillagjegyek/[jegy]/page.tsx create mode 100644 services/frontend/src/app/csillagjegyek/page.tsx create mode 100644 services/frontend/src/components/PublicFooter.tsx create mode 100644 services/frontend/src/content/zodiac.ts create mode 100644 services/frontend/src/lib/birth.ts diff --git a/crates/horoscope-client/src/lib.rs b/crates/horoscope-client/src/lib.rs index f7df0d1..66a097c 100644 --- a/crates/horoscope-client/src/lib.rs +++ b/crates/horoscope-client/src/lib.rs @@ -48,6 +48,27 @@ impl HoroscopeClient { self.post("/v1/forecast", request).await } + /// `GET /v1/countries` + pub async fn countries(&self) -> Result { + self.get("/v1/countries", &[]).await + } + + /// `GET /v1/places?country=&q=&limit=` + pub async fn places(&self, country: &str, query: &str, limit: u32) -> Result { + self.get("/v1/places", &[("country", country), ("q", query), ("limit", &limit.to_string())]).await + } + + async fn get(&self, path: &str, query: &[(&str, &str)]) -> Result { + let response = self + .http + .get(format!("{}{path}", self.base_url)) + .query(query) + .send() + .await + .map_err(|e| HoroscopeError::Unavailable(e.to_string()))?; + Self::answer(response).await + } + async fn post(&self, path: &str, body: &Value) -> Result { let response = self .http @@ -56,6 +77,10 @@ impl HoroscopeClient { .send() .await .map_err(|e| HoroscopeError::Unavailable(e.to_string()))?; + Self::answer(response).await + } + + async fn answer(response: reqwest::Response) -> Result { let status = response.status(); let body: Value = response.json().await.map_err(|e| HoroscopeError::Unavailable(e.to_string()))?; if status.is_success() { diff --git a/services/backend/README.md b/services/backend/README.md index e7b2c11..1129aa2 100644 --- a/services/backend/README.md +++ b/services/backend/README.md @@ -68,6 +68,8 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh | `POST /v1/auth/logout`, `/logout-all` | user | kijelentkezés erről, illetve minden eszközről | | `POST /v1/auth/password-reset` | – | `{email}`; mindig 202 | | `POST /v1/auth/set-password` | – | `{token, password}` a levélben kapott linkből (regisztráció vagy elfelejtett jelszó); a cím megerősítetté válik, minden más munkamenet megszűnik, és belép | +| `POST /v1/public/signs` | – | a nyilvános kalkulátor: `{date, time?, country, geonames_id, ambiguous_time?}` → Nap-, Hold- és aszcendensjegy (idő nélkül aszcendens nélkül, a határ közeli jegyek `uncertain` jelöléssel); csak számítás, AI nélkül, nem ment semmit; IP-címenként óránként 30 | +| `GET /v1/public/geo/countries`, `/v1/public/geo/places?country=&q=` | – | országlista és helykereső a kalkulátorhoz (a helykereső IP-címenként óránként 300 kérés) | | `GET`/`PATCH`/`DELETE /v1/me` | user | profil (`display_name`, `locale`); törlés: `{confirm: "DELETE"}` | | `POST /v1/me/password` | user | `{current_password?, new_password}`; Google-fiókhoz jelszót is ad | | `GET /v1/me/export` | user | GDPR: minden adat egy JSON-ban | diff --git a/services/backend/src/auth.rs b/services/backend/src/auth.rs index 8305e7d..024f59a 100644 --- a/services/backend/src/auth.rs +++ b/services/backend/src/auth.rs @@ -186,7 +186,8 @@ pub static DUMMY_HASH: std::sync::LazyLock = std::sync::LazyLock::new(|| // --- brute-force protection ---------------------------------------------------------- /// Counts failed logins per e-mail address in a sliding window (in memory, -/// per backend instance). +/// per backend instance). Also counts the calls of public endpoints per +/// address ([`LoginLimiter::hit`]). pub struct LoginLimiter { max_failures: u32, window: Duration, @@ -222,6 +223,14 @@ impl LoginLimiter { entry.0 += 1; } + /// Counts one use of a public endpoint (every call, not just failures): + /// 429 once `max_failures` calls were made in the window. + pub fn hit(&self, key: &str) -> Result<(), ApiError> { + self.check(key)?; + self.failed(key); + Ok(()) + } + pub fn succeeded(&self, key: &str) { self.failures.lock().expect("limiter lock").remove(key); } diff --git a/services/backend/src/main.rs b/services/backend/src/main.rs index fe7d6b8..8e552c8 100644 --- a/services/backend/src/main.rs +++ b/services/backend/src/main.rs @@ -43,6 +43,10 @@ pub struct AppState { pub google: IdTokenVerifier, pub apple: IdTokenVerifier, pub login_limiter: LoginLimiter, + /// The public sign calculator, per visitor address. + pub calculator_limiter: LoginLimiter, + /// The public place search (typing makes several calls), per visitor address. + pub places_limiter: LoginLimiter, pub models: models::Catalog, pub stripe: stripe::Client, } @@ -54,6 +58,8 @@ impl AppState { google: IdTokenVerifier::google(config.google_client_ids.clone(), config.google_jwks_url.clone()), apple: IdTokenVerifier::apple(config.apple_client_ids.clone(), config.apple_jwks_url.clone()), login_limiter: LoginLimiter::new(10, Duration::from_secs(15 * 60)), + calculator_limiter: LoginLimiter::new(30, Duration::from_secs(60 * 60)), + places_limiter: LoginLimiter::new(300, Duration::from_secs(60 * 60)), models: models::Catalog::new(&config.openrouter_models_url), stripe: stripe::Client::default(), db, diff --git a/services/backend/src/routes/calculator.rs b/services/backend/src/routes/calculator.rs new file mode 100644 index 0000000..d95c444 --- /dev/null +++ b/services/backend/src/routes/calculator.rs @@ -0,0 +1,124 @@ +//! The public sign calculator (`/aszcendens-kalkulator`): the Sun, Moon and +//! Ascendant signs from birth data, without an account, plus the country list +//! and place search it needs. Nothing is stored. Each visitor address may +//! make a limited number of calculations and place searches an hour, so the +//! endpoints cannot serve as a free calculation service for other apps. + +use axum::Json; +use axum::extract::{Query, State}; +use axum::http::HeaderMap; +use axum_extra::extract::WithRejection; +use serde::Deserialize; +use serde_json::{Value, json}; + +use super::{Body, St, client_ip}; +use crate::error::{ApiError, ApiResult}; + +/// The limiter key of the visitor (all unknown addresses share one). +fn visitor(headers: &HeaderMap) -> String { + client_ip(headers).map_or_else(|| "unknown".to_string(), |ip| format!("ip:{ip}")) +} + +fn valid_country(country: &str) -> bool { + country.len() == 2 && country.chars().all(|c| c.is_ascii_uppercase()) +} + +pub async fn countries(State(state): St) -> ApiResult> { + Ok(Json(state.horoscope.countries().await?)) +} + +#[derive(Deserialize)] +pub struct PlacesQuery { + country: String, + q: String, + limit: Option, +} + +pub async fn places( + State(state): St, + headers: HeaderMap, + WithRejection(Query(query), _): WithRejection, ApiError>, +) -> ApiResult> { + let q = query.q.trim(); + if !valid_country(&query.country) || q.chars().count() < 2 || q.chars().count() > 80 { + return Err(ApiError::BadRequest("a country code and 2 to 80 characters of a place name are needed".into())); + } + state.places_limiter.hit(&visitor(&headers))?; + Ok(Json(state.horoscope.places(&query.country, q, query.limit.unwrap_or(8).min(10)).await?)) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SignsRequest { + date: String, + /// "HH:MM"; without it there is no Ascendant. + time: Option, + country: String, + geonames_id: i64, + /// "earlier" or "later", for a time that occurred twice (clocks set back). + ambiguous_time: Option, +} + +/// One sign of the answer. `uncertain`: without a birth time the point may +/// have been in the neighbouring sign at the start or the end of the day. +fn sign(point: &Value, time_known: bool, default_speed: f64) -> Value { + let degree = point["degree_in_sign"].as_f64(); + let speed = point["speed"].as_f64().unwrap_or(default_speed).abs(); + let uncertain = !time_known && degree.is_some_and(|d| d < speed / 2.0 || 30.0 - d < speed / 2.0); + json!({ "sign": point["sign"], "degree": degree.map(|d| d.floor()), "uncertain": uncertain }) +} + +/// The Sun, Moon and Ascendant signs of the birth data. +pub async fn signs( + State(state): St, + headers: HeaderMap, + WithRejection(Json(req), _): Body, +) -> ApiResult> { + if !valid_country(&req.country) { + return Err(ApiError::BadRequest("invalid country code".into())); + } + if req.ambiguous_time.as_deref().is_some_and(|a| a != "earlier" && a != "later") { + return Err(ApiError::BadRequest("ambiguous_time is 'earlier' or 'later'".into())); + } + state.calculator_limiter.hit(&visitor(&headers))?; + let mut birth = json!({ "date": req.date, "country": req.country, "geonames_id": req.geonames_id }); + if let Some(time) = &req.time { + birth["time"] = json!(time); + } + if let Some(ambiguous) = &req.ambiguous_time { + birth["ambiguous_time"] = json!(ambiguous); + } + let chart = state.horoscope.natal(&birth).await?; + let time_known = req.time.is_some(); + let point = |id: &str| { + chart["points"] + .as_array() + .and_then(|points| points.iter().find(|p| p["id"] == id)) + .cloned() + .unwrap_or(Value::Null) + }; + let ascendant = &chart["angles"]["ascendant"]; + Ok(Json(json!({ + "sun": sign(&point("sun"), time_known, 1.0), + "moon": sign(&point("moon"), time_known, 13.2), + "ascendant": (time_known && ascendant["sign"].is_string()).then(|| sign(ascendant, true, 0.0)), + "time_known": time_known, + "place": chart["location"]["place"]["name"], + }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn signs_near_a_border_are_uncertain_without_a_time() { + let moon = json!({"sign": "pisces", "degree_in_sign": 3.2, "speed": 12.6}); + assert_eq!(sign(&moon, false, 13.2)["uncertain"], true); + assert_eq!(sign(&moon, true, 13.2)["uncertain"], false); + let middle = json!({"sign": "pisces", "degree_in_sign": 15.0, "speed": 12.6}); + assert_eq!(sign(&middle, false, 13.2), json!({"sign": "pisces", "degree": 15.0, "uncertain": false})); + let sun = json!({"sign": "cancer", "degree_in_sign": 29.8}); + assert_eq!(sign(&sun, false, 1.0)["uncertain"], true); + } +} diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index ab9cda1..3a23ac7 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -9,6 +9,7 @@ mod account; mod admin; mod analyses; mod auth; +mod calculator; mod charts; mod errors; mod forecasts; @@ -125,6 +126,9 @@ pub fn router(state: Arc) -> Router { .route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe)) .route("/v1/public/invitations/{token}", get(invitations::public_view)) .route("/v1/public/waitlist", post(invitations::join_waitlist)) + .route("/v1/public/signs", post(calculator::signs)) + .route("/v1/public/geo/countries", get(calculator::countries)) + .route("/v1/public/geo/places", get(calculator::places)) // administration .route("/v1/admin/users", get(admin::list_users)) .route("/v1/admin/users/{id}", patch(admin::update_user)) diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 4f8c9fe..cdd39b2 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -175,6 +175,14 @@ async fn fake_services() -> String { .route("/v1/checkout/sessions", post(fake_stripe_create)) .route("/v1/checkout/sessions/{id}", get(fake_stripe_get)) .route("/v1/natal", post(fake_natal)) + .route("/v1/countries", get(|| async { Json(json!({"countries": [{"iso2": "HU", "name": "Hungary"}]})) })) + .route( + "/v1/places", + get(|axum::extract::Query(q): axum::extract::Query>| async move { + Json(json!({"places": [{"geonames_id": 715429, "name": format!("{}ed", q["q"]), "country_code": q["country"], + "region": null, "population": 160000}], "limit": q["limit"]})) + }), + ) .route("/v1/synastry", post(fake_synastry)) .route("/v1/forecast", post(fake_forecast)) .route("/jwks", get(fake_jwks)); @@ -933,7 +941,7 @@ async fn export_and_delete_account(pool: PgPool) { /// config and catalog, shared links, invitation pages, the waitlist and /// unsubscribing. Every other route (charts, calculations, analyses) needs a /// logged-in user, so other apps cannot use them. -const PUBLIC_ROUTES: [&str; 16] = [ +const PUBLIC_ROUTES: [&str; 19] = [ "/healthz", // Stripe calls it; the signature proves it. "/v1/payments/stripe/webhook", @@ -951,8 +959,56 @@ const PUBLIC_ROUTES: [&str; 16] = [ "/v1/public/invitations/unsubscribe", "/v1/public/invitations/{token}", "/v1/public/waitlist", + // The sign calculator (limited per visitor address). + "/v1/public/signs", + "/v1/public/geo/countries", + "/v1/public/geo/places", ]; +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn the_public_sign_calculator(pool: PgPool) { + let app = TestApp::new(pool).await; + let visitor = ("x-real-ip", "203.0.113.9"); + let birth = json!({"date": "1990-06-21", "time": "14:30", "country": "HU", "geonames_id": 715429}); + let r = app.call_with("POST", "/v1/public/signs", None, Some(birth.clone()), &[visitor]).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!( + (&r.body["sun"]["sign"], &r.body["moon"]["sign"], &r.body["ascendant"]["sign"]), + (&json!("cancer"), &json!("pisces"), &json!("aries")) + ); + // Without a birth time there is no Ascendant. + let r = app + .call_with( + "POST", + "/v1/public/signs", + None, + Some(json!({"date": "1990-06-21", "country": "HU", "geonames_id": 715429})), + &[visitor], + ) + .await; + assert_eq!((r.status, &r.body["ascendant"], &r.body["time_known"]), (StatusCode::OK, &Value::Null, &json!(false))); + let r = app.call_with("POST", "/v1/public/signs", None, Some(json!({"date": "1990-06-21"})), &[visitor]).await; + assert_eq!(r.status, StatusCode::BAD_REQUEST); + + // The place search passes the query on, with a capped limit. + let r = app.call_with("GET", "/v1/public/geo/places?country=HU&q=Szeg&limit=50", None, None, &[visitor]).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!((&r.body["places"][0]["name"], &r.body["limit"]), (&json!("Szeged"), &json!("10"))); + let r = app.call_with("GET", "/v1/public/geo/places?country=hu&q=S", None, None, &[visitor]).await; + assert_eq!(r.status, StatusCode::BAD_REQUEST); + assert_eq!(app.get("/v1/public/geo/countries", None).await.body["countries"][0]["iso2"], "HU"); + + // 30 calculations an hour per address (the malformed request did not count). + for _ in 0..28 { + let r = app.call_with("POST", "/v1/public/signs", None, Some(birth.clone()), &[visitor]).await; + assert_eq!(r.status, StatusCode::OK); + } + let r = app.call_with("POST", "/v1/public/signs", None, Some(birth.clone()), &[visitor]).await; + assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS); + let r = app.call_with("POST", "/v1/public/signs", None, Some(birth), &[("x-real-ip", "198.51.100.2")]).await; + assert_eq!(r.status, StatusCode::OK); +} + #[sqlx::test(migrator = "db::MIGRATOR")] async fn a_visit_by_someone_else_earns_one_question_once(pool: PgPool) { let app = TestApp::new(pool).await; diff --git a/services/frontend/src/app/Landing.tsx b/services/frontend/src/app/Landing.tsx index 6fbba09..0c144d0 100644 --- a/services/frontend/src/app/Landing.tsx +++ b/services/frontend/src/app/Landing.tsx @@ -480,6 +480,8 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {