diff --git a/crates/db/migrations/0033_checkout_notified.sql b/crates/db/migrations/0033_checkout_notified.sql new file mode 100644 index 0000000..3ed0c08 --- /dev/null +++ b/crates/db/migrations/0033_checkout_notified.sql @@ -0,0 +1,4 @@ +-- When the operator's Telegram notice about a paid checkout went out (the +-- worker's `notify` task). Earlier purchases count as notified. +ALTER TABLE stripe_checkouts ADD COLUMN notified_at timestamptz; +UPDATE stripe_checkouts SET notified_at = now() WHERE completed_at IS NOT NULL; diff --git a/crates/email-templates/src/lib.rs b/crates/email-templates/src/lib.rs index d2b11ab..387b60f 100644 --- a/crates/email-templates/src/lib.rs +++ b/crates/email-templates/src/lib.rs @@ -91,20 +91,36 @@ pub fn render(template: &str, locale: &str, payload: &Value) -> Result Content::simple( - "Erősítsd meg az e-mail-címed".into(), + "Add meg a jelszavad".into(), greeting(name(payload, "display_name")), - "Köszönjük, hogy regisztráltál a Sorsfonalakon! Az alábbi gombbal erősítsd meg az e-mail-címed.".into(), - "E-mail-cím megerősítése", + "Köszönjük, hogy regisztráltál a Sorsfonalakon! Az alábbi gombbal megerősíted az e-mail-címed, és megadhatod a jelszavad. Utána már be is vagy lépve.".into(), + "Jelszó megadása", url, - "A link 3 napig érvényes. Ha nem te regisztráltál, nyugodtan hagyd figyelmen kívül ezt a levelet.", + "A link 3 napig érvényes, és csak egyszer használható. Ha nem te regisztráltál, nyugodtan hagyd figyelmen kívül ezt a levelet.", ), ("verify_email", Lang::En) => Content::simple( - "Confirm your e-mail address".into(), + "Set your password".into(), greeting(name(payload, "display_name")), - "Thanks for signing up for Sorsfonalak! Please confirm your e-mail address with the button below.".into(), - "Confirm e-mail address", + "Thanks for signing up for Sorsfonalak! The button below confirms your e-mail address and lets you set your password. You will be logged in right after.".into(), + "Set password", url, - "The link is valid for 3 days. If you did not sign up, you can safely ignore this e-mail.", + "The link is valid for 3 days and can be used once. If you did not sign up, you can safely ignore this e-mail.", + ), + ("account_exists", Lang::Hu) => Content::simple( + "Már van fiókod a Sorsfonalakon".into(), + greeting(name(payload, "display_name")), + "Ezzel az e-mail-címmel regisztrációt kezdtek a Sorsfonalakon, de neked már van fiókod. Beléphetsz úgy, ahogy eddig (például Google-lel), vagy az alábbi gombbal jelszót adhatsz meg.".into(), + "Jelszó megadása", + url, + "A link 1 óráig érvényes, és csak egyszer használható. Ha nem te voltál, hagyd figyelmen kívül ezt a levelet: a fiókod nem változik.", + ), + ("account_exists", Lang::En) => Content::simple( + "You already have a Sorsfonalak account".into(), + greeting(name(payload, "display_name")), + "Someone started signing up for Sorsfonalak with this e-mail address, but you already have an account. Log in as before (e.g. with Google), or set a password with the button below.".into(), + "Set password", + url, + "The link is valid for 1 hour and can be used once. If it was not you, ignore this e-mail: your account stays the same.", ), ("reset_password", Lang::Hu) => Content::simple( "Új jelszó megadása".into(), 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/deploy/.env.example b/deploy/.env.example index 7f97a1d..9391397 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -28,3 +28,7 @@ TAG=latest # Beszel monitoring agent (deploy/README.md): the hub's public key. # COMPOSE_PROFILES=monitoring # BESZEL_KEY=ssh-ed25519 AAAA... + +# Purchase notices to Telegram (worker notify task); the bot token +# (TELEGRAM_BOT_TOKEN) goes to .env.secrets. +# TELEGRAM_CHAT_ID=123456789 diff --git a/deploy/README.md b/deploy/README.md index a8cf47d..7e26fa4 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -77,6 +77,7 @@ A Docker által kinyitott portokat az ufw magától nem szűri, ezért a 80-as - SSL/TLS mód: **Full (strict)**. - **Always Use HTTPS: ki.** A Let's Encrypt a Cloudflare-en át, sima HTTP-n ellenőrzi a domaint, a tanúsítvány megújításakor is. A HTTP→HTTPS átirányítást a Caddy maga végzi. - A Caddy a Cloudflare címtartományaiban megbízik, ezért a naplókban és a backendnél a látogató valódi IP-címe látszik (`CF-Connecting-IP`). +- AI-robotok: Security → Settings → Bot traffic → *AI Crawler and Agent access policies*: **Training: Block**, **Search: Allow**, **Agents: Allow** (a részletek: `docs/megosztas.md`, Robotok). Bot Fight Mode: ki, mert a link-előnézeteket is elrontja. A Google OAuth kliensnél a `https://sorsfonalak.hu` címet fel kell venni az engedélyezett JavaScript-források közé. @@ -88,5 +89,6 @@ A Google OAuth kliensnél a `https://sorsfonalak.hu` címet fel kell venni az en - A worker két konténerben fut, ugyanabból az image-ből: a `worker` küldi az e-maileket és takarít (`WORKER_TASKS=email,cleanup`, ide kerülnek a további háttérfeladatok is), a `worker-ai` írja az elemzéseket és a válaszokat (`WORKER_TASKS=analyses`, gyors és lassú sáv). A sávok mérete a szerver `.env` fájljában állítható (`QUICK_CONCURRENCY`, `ANALYSIS_CONCURRENCY`). - Visszaállás korábbi verzióra: `.env`-ben `TAG=`, utána `docker compose up -d` - Mentés: naponta egy `pg_dump` a `/opt/sorsfonalak/backups` mappába, 14 napig megmarad. Az otthoni TrueNAS naponta lehúzza (Rsync Task, Pull, SSH) a `nasbackup` felhasználóval, aki csak ezt a mappát olvashatja (`authorized_keys`: `command="/usr/bin/rrsync -ro /opt/sorsfonalak/backups",restrict`); a NAS-on a régi mentések is megmaradnak. +- Vásárlási értesítő: a `worker` `notify` feladata minden kifizetett vásárlásról egyszer szól Telegramon („🛒 Vásárlás: Páros csomag, 6 000 Ft”, a vevő adatai nélkül), a számlázástól függetlenül. Beállítás: `TELEGRAM_BOT_TOKEN` a `.env.secrets`-ben, `TELEGRAM_CHAT_ID` a `.env`-ben; ha bármelyik hiányzik, nincs értesítés. - Monitorozás: a `beszel-agent` (Beszel, CPU/memória/lemez/konténerek) a NAS-on futó Beszel hubnak ad adatot, Tailscale-en át. Csak a szerver Tailscale-címén figyel (`100.69.226.118:45876`), az internet felé nem nyit portot; a hub kapcsolódik hozzá. Bekapcsolás a `.env`-ben: `COMPOSE_PROFILES=monitoring` és `BESZEL_KEY=`, utána `docker compose up -d beszel-agent`. A hubban a rendszer címe `100.69.226.118`, port `45876`. - Visszatöltés: `gunzip -c backups/sorsfonalak-.sql.gz | docker compose exec -T postgres psql -U sorsfonalak sorsfonalak` diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 65bbaa6..dd91d15 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -129,7 +129,9 @@ services: image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest} environment: DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak - WORKER_TASKS: email,cleanup,invoices + WORKER_TASKS: email,cleanup,invoices,notify + # Purchase notices to Telegram; the bot token (TELEGRAM_BOT_TOKEN) is in .env.secrets. + TELEGRAM_CHAT_ID: ${TELEGRAM_CHAT_ID:-} # SMTP_URL or the SES credentials come from .env.secrets (docs/levelkuldes.md); # listing them here with an empty default would override that file. SES_REGION: ${SES_REGION:-eu-central-1} diff --git a/docker-compose.yml b/docker-compose.yml index ebf9da0..32cdc4c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -90,6 +90,8 @@ services: SMTP_URL: ${SMTP_URL:-} MAIL_FROM: ${MAIL_FROM:-Sorsfonalak } PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:3001} + # Purchase notices to Telegram (TELEGRAM_BOT_TOKEN in .env.secrets). + TELEGRAM_CHAT_ID: ${TELEGRAM_CHAT_ID:-} # OPENROUTER_API_KEY (not in git); without it analyses stay pending. env_file: - path: .env.secrets diff --git a/docs/fizetes.md b/docs/fizetes.md index 7459fe2..11956c0 100644 --- a/docs/fizetes.md +++ b/docs/fizetes.md @@ -34,7 +34,7 @@ A sorok a fiók törlése után is megmaradnak (`user_id` → NULL), mert a szá ## Számla -Fizetéskor a backend egy `invoices` sort is létrehoz a számla minden adatával: a vevő (név, e-mail, ország, irányítószám, város, cím, Billingo-adótípus: `HAS_TAX_NUMBER` / `NO_TAX_NUMBER` / `FOREIGN`, adószám) és a tétel (név, végösszeg, nettó, áfa, áfakód). Az áfakód az `INVOICE_VAT` (a backend `.env`-je): alapból `AAM` (alanyi adómentes: nettó = végösszeg, áfa 0, a számla megjegyzésében „Alanyi adómentes.”), vagy egy kulcs, pl. `27%`. A tétel a törvény szerint azonosítja a szolgáltatást (Áfa tv. 169. § e): megnevezése pl. „Online tartalomszolgáltatás – Páros csomag”, egysége `csomag`, megjegyzése a tartalom („Hozzáférés a sorsfonalak.hu szoftveresen előállított, személyre szabott szöveges tartalmaihoz: 2 képletelemzés, … Digitális tartalom.”; `Package::invoice_item`). Szándékosan nem „asztrológiai”: a szolgáltatás egy weboldal programmal előállított tartalma, nem személyes szakmai tanácsadás. Cégnél a `business_name` és a magyar adószám (`hu_tin`, ennek híján `eu_vat`) kerül a számlára. +Fizetéskor a backend egy `invoices` sort is létrehoz a számla minden adatával: a vevő (név, e-mail, ország, irányítószám, város, cím, Billingo-adótípus: `HAS_TAX_NUMBER` / `NO_TAX_NUMBER` / `FOREIGN`, adószám) és a tétel (név, végösszeg, nettó, áfa, áfakód). Az áfakód az `INVOICE_VAT` (a backend `.env`-je): alapból `AAM` (alanyi adómentes: nettó = végösszeg, áfa 0, a számla megjegyzésében „Alanyi adómentes.”), vagy egy kulcs, pl. `27%`. A tétel a törvény szerint azonosítja a szolgáltatást (Áfa tv. 169. § e): megnevezése a fő csomagoknál pl. „Online tartalomszolgáltatás – Páros csomag”, a kiegészítőknél egységesen „Online tartalomszolgáltatás – kiegészítő csomag”, egysége `csomag`, megjegyzése a tartalom („Hozzáférés a sorsfonalak.hu szoftveresen előállított, személyre szabott szöveges tartalmaihoz: 2 képletelemzés, … Digitális tartalom.”; `Package::invoice_item`). Szándékosan semleges: nem „asztrológiai”, és nem „jóslás” vagy „kártya” (a kártyajóslás a megjegyzésben „egyedi szöveges tartalom”), mert a szolgáltatás egy weboldal programmal előállított tartalma, nem személyes szakmai tanácsadás. A Stripe fizetési oldalán és nyugtáján a csomag neve és leírása áll, ott a „kártyajóslás” helyett „kártya” (`Package::checkout_text`). A Telegram-értesítő a kiegészítőknél a csomag azonosítóját is kiírja („kiegészítő csomag (addon_tarot)”). Cégnél a `business_name` és a magyar adószám (`hu_tin`, ennek híján `eu_vat`) kerül a számlára. Minden igazolt fizetéshez készül számla, a teszt módúakhoz (`sk_test_…`) is: így a teljes folyamat próbálható egy teszt Billingo-fiókkal. Éles Billingo-fiók mellett ezért prodon már ne legyen teszt Stripe-kulcs (a kettőt megnyitáskor együtt kell élesre cserélni). diff --git a/docs/kartyajoslas.md b/docs/kartyajoslas.md index 572365a..cfca3c1 100644 --- a/docs/kartyajoslas.md +++ b/docs/kartyajoslas.md @@ -14,4 +14,4 @@ A `/kartyajoslas` oldalon a felhasználó témát (Általános, Párkapcsolat, M ## Csomagok -Egy elemzés: 2, Páros: 5, Család: 10 jóslás; külön: „+5 kártyajóslás” 1 000 Ft. A számlán a tétel leírásában „kártyaértelmezés” szerepel (nem „jóslás”). +Egy elemzés: 2, Páros: 5, Család: 10 jóslás; külön: „+5 kártyajóslás” 1 000 Ft. A számlán a kiegészítő neve „Online tartalomszolgáltatás – kiegészítő csomag”, a tétel leírásában „egyedi szöveges tartalom” szerepel (sem „jóslás”, sem „kártya”). A Stripe fizetési oldalán „+5 kártya”. diff --git a/docs/levelkuldes.md b/docs/levelkuldes.md index e6dda5c..dcfef63 100644 --- a/docs/levelkuldes.md +++ b/docs/levelkuldes.md @@ -1,6 +1,6 @@ # Levélküldés élesben: Amazon SES -Élesben most nincs levélküldő beállítva (`SMTP_URL` üres), így minden levél az `email_outbox` táblában vár. Amíg ez így van, a meghívót kézzel is továbbadhatod: az admin „Meghívók” oldala küldés után kiírja a linket („Link másolása”). +Élesben az Amazon SES küldi a leveleket (`noreply@sorsfonalak.hu`, eu-central-1, 2587-es port). Ha a küldés nincs beállítva (`SMTP_URL` és SES-kulcs nélkül), a levelek az `email_outbox` táblában várnak; a meghívót ilyenkor kézzel is továbbadhatod: az admin „Meghívók” oldala küldés után kiírja a linket („Link másolása”). A meghívó a legkényesebb levéltípus, mert a címzett nem kérte. A spammappát elsősorban a feladó hírneve és a domain hitelesítése dönti el, a sablon csak ezután számít. Ezért kellenek a lenti lépések. diff --git a/docs/megosztas.md b/docs/megosztas.md index ce3150e..0407dee 100644 --- a/docs/megosztas.md +++ b/docs/megosztas.md @@ -25,7 +25,7 @@ Egy kattintás önmagában semmit nem bizonyít, ezért kétféle jutalom van: **Új felhasználó:** -- **Megjegyzés:** a megosztott oldal a böngészőben megjegyzi a link kódját (`localStorage` `sf_ref`). A Google-regisztráció elküldi (`referral`), és a backend a `referrals` táblába írja, hogy kit ki hozott. Saját link, visszavont link vagy kikapcsolt jutalom esetén nem írja be. +- **Megjegyzés:** a megosztott oldal belépés linkje viszi a link kódját (`/belepes?ref=`), a böngészőben semmi nem tárolódik. A regisztráció (Google, Apple, e-mail) elküldi (`referral`), és a backend a `referrals` táblába írja, hogy kit ki hozott. Saját link, visszavont link vagy kikapcsolt jutalom esetén nem írja be. - **Jutalom:** amikor az új felhasználó elkészíti a saját képletét, a megosztó +1 képletelemzést kap (`referral_reward`), ha még nem érte el a hármat. Új felhasználónként egyszer. - **`/v1/me`:** a `share_reward_granted` és a `referral_rewards` (`{earned, limit}`) mezők mutatják az állapotot. @@ -33,8 +33,12 @@ Egy kattintás önmagában semmit nem bizonyít, ezért kétféle jutalom van: - **Az olvasás nem ír.** A megosztott tartalom lekérése (`GET /v1/public/shares/{slug}`) semmit nem ír az adatbázisba. - **Gyorsítótár:** a frontend 5 percig tartja (`fetch` `revalidate: 300`, `shares` tag), így a sűrűn visszatérő robotok el sem jutnak a backendig. Visszavonáskor az `/api/v1` proxy azonnal törli a taget. -- **robots.txt** (`src/app/robots.ts`): kitiltja az ismert AI-robotokat (GPTBot, ClaudeBot, CCBot, PerplexityBot, Bytespider, meta-externalagent stb.). Az előnézet-robotok (facebookexternalhit, Slackbot, WhatsApp, Twitterbot, LinkedInBot) engedélyezve maradnak. -- **Cloudflare:** a robots.txt-t be nem tartó robotokra a Cloudflare „Block AI bots” beállítása való (Security → Bots). Ez az előnézet-robotokat nem tiltja le. A „Bot Fight Mode” viszont az előnézeteket is elronthatja, azt ne kapcsoljuk be. +- **robots.txt** (`src/app/robots.ts`), három csoport: + - **Tanító robotok: kitiltva.** Amelyek AI-modell tanításához gyűjtenek, vagy tanítóadatnak adják el a tartalmat (GPTBot, ClaudeBot, CCBot, Google-Extended, Applebot-Extended, Bytespider, meta-externalagent stb.), plusz a nehéz és itt haszontalan PetalBot és Scrapy. A Google-Extended csak a Gemini-tanítást tiltja, a Google-keresést és az AI-áttekintést nem érinti. + - **AI-keresők és -ügynökök: jöhetnek, legfeljebb 10 másodpercenként egy oldal** (`Crawl-delay: 10`, amelyik betartja). OAI-SearchBot, ChatGPT-User, Claude-SearchBot, Claude-User, PerplexityBot, Perplexity-User, DuckAssistBot stb. Ezek idézhetik az oldalt, és látogatót hozhatnak. + - **Mindenki más** (Googlebot, Bingbot, az előnézet-robotok: facebookexternalhit, Slackbot, WhatsApp, Twitterbot, LinkedInBot): jöhet, a belépés mögötti útvonalak kivételével. +- **Kis terhelés:** belépési süti nélkül a nyilvános oldalak nem hívják a backendet, a horoszkópszámítást pedig csak a böngészőben futó szkript indítja (IP-címenként óránként 30). Egy robotlátogatás így csak egy HTML-oldal előállítása. +- **Cloudflare:** a robots.txt-t be nem tartó robotokra a Security → Settings → Bot traffic → *AI Crawler and Agent access policies* való: **Training: Block**, **Search: Allow**, **Agents: Allow**. Ez az előnézet-robotokat nem érinti. A „Bot Fight Mode” viszont az előnézeteket is elronthatja, azt ne kapcsoljuk be. ## Előnézet (Facebook, Messenger, WhatsApp, LinkedIn, X) diff --git a/services/backend/README.md b/services/backend/README.md index 4f2536d..93f4b51 100644 --- a/services/backend/README.md +++ b/services/backend/README.md @@ -32,6 +32,11 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh - **Munkamenet:** véletlen token, HttpOnly + SameSite=Lax sütiben (`sf_session`). A belépési válasz törzsében is ott van, hogy nem böngészős kliens `Authorization: Bearer ` fejléccel küldhesse vissza. Az adatbázis csak a token SHA-256 hash-ét tárolja, így a munkamenet visszavonható (kijelentkezés, jelszócsere, fióktörlés). - **E-mail + jelszó** (csak `PASSWORD_LOGIN=true` mellett; élesben csak közösségi belépés lesz, hogy ne lehessen tömegesen ingyenes fiókokat nyitni): + - a regisztráció nem kér jelszót: a címre megy egy link (`verify_email`, 3 napig él), és jelszót csak ezen lehet megadni. Az elfelejtett jelszó linkje (`reset_password`, 1 óra) ugyanoda visz (`/jelszo?token=…`). Így jelszót csak az állíthat be, aki a postafiókot olvassa, és mindig ő maga választja: senki nem regisztrálhat más címére jelszót, ezért a Google- vagy Apple-fiók összekötése az azonos című fiókkal biztonságos; + - a link megnyitásakor a cím megerősítettnek számít, minden korábbi munkamenet megszűnik, és a felhasználó be is lép; + - már regisztrált címre a regisztráció ugyanúgy 202-t ad (nem derül ki, ki van regisztrálva), a tulajdonos pedig egy „Már van fiókod” levelet kap jelszómegadó linkkel (`account_exists`); + - jelszavas link címenként és fajtánként percenként egy, összesen óránként öt mehet ki; + - megerősítetlen címmel (a linkes regisztráció előtti fiók) nem lehet jelszóval belépni; - a jelszó legalább 10 karakter, Argon2id hash-sel tárolva; - címenként 15 percen belül 10 hibás próbálkozás után átmenetileg tiltás jár; - ismeretlen címnél is ugyanannyi ideig tart a válasz. @@ -57,14 +62,14 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh |---|---|---| | `GET /v1/config` | – | Google kliens-azonosító, `password_login`, `signup_mode`, nyelvek, elemző és összefoglaló modell | | `GET /v1/packages` | – | a csomagkatalógus árral, tartalommal, megtakarítással, elemzésenkénti árral (lásd `docs/csomagok.md`) | -| `POST /v1/auth/register` | – | `{email, password, display_name?, locale?, invite_token?}` → munkamenet; megerősítő e-mailt küld | +| `POST /v1/auth/register` | – | `{email, display_name?, locale?, invite_token?, referral?}` → 202; jelszómegadó linket küld | | `POST /v1/auth/login` | – | `{email, password}` | | `POST /v1/auth/google` | – | `{id_token, invite_token?}`; `created: true`, ha most jött létre a fiók; meghívó nélkül 403 `not_invited` | | `POST /v1/auth/logout`, `/logout-all` | user | kijelentkezés erről, illetve minden eszközről | -| `POST /v1/auth/verify-email` | – | `{token}` az e-mailben kapott linkből | -| `POST /v1/auth/resend-verification` | user | | | `POST /v1/auth/password-reset` | – | `{email}`; mindig 202 | -| `POST /v1/auth/password-reset/confirm` | – | `{token, password}`; minden munkamenet megszűnik | +| `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/chart` | – | a nyilvános születési horoszkóp: `{date, time?, country, geonames_id, ambiguous_time?}` → a teljes képlet (`chart`), `highlights` és `uncertain` (idő nélkül a határ közeli Nap és Hold); 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 nyilvános horoszkóphoz (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..93572c5 100644 --- a/services/backend/src/main.rs +++ b/services/backend/src/main.rs @@ -43,6 +43,13 @@ 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, + /// 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, pub models: models::Catalog, pub stripe: stripe::Client, } @@ -54,6 +61,9 @@ 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)), + share_visits: LoginLimiter::new(1, Duration::from_secs(30 * 60)), models: models::Catalog::new(&config.openrouter_models_url), stripe: stripe::Client::default(), db, diff --git a/services/backend/src/packages.rs b/services/backend/src/packages.rs index 8c6a13d..1a47aed 100644 --- a/services/backend/src/packages.rs +++ b/services/backend/src/packages.rs @@ -245,11 +245,13 @@ impl Package { /// The invoice item: a name that says what the service is (online, /// software-made content; no profession implied), and what the package - /// contains (Áfa tv. 169. § e). + /// contains (Áfa tv. 169. § e). Kept neutral: the main packages keep + /// their plain names, the add-ons share one name, and tarot readings are + /// listed as text content. pub fn invoice_item(&self) -> (String, String) { let name = match self.tier { Tier::Main => format!("Online tartalomszolgáltatás – {} csomag", self.name), - Tier::Addon => format!("Online tartalomszolgáltatás – {} kiegészítő", self.name), + Tier::Addon => "Online tartalomszolgáltatás – kiegészítő csomag".to_string(), }; let lines: Vec = [ (self.natal, "képletelemzés"), @@ -257,7 +259,7 @@ impl Package { (self.forecast, "éves előrejelzés"), (self.persons, "további személy felvétele"), (self.questions, "kérdés"), - (self.tarot, "kártyaértelmezés"), + (self.tarot, "egyedi szöveges tartalom"), ] .into_iter() .filter(|&(n, _)| n > 0) @@ -271,6 +273,13 @@ impl Package { (name, comment) } + /// The name and description on Stripe's payment page and receipt: as on + /// the site, but tarot readings are called "kártya" there. + pub fn checkout_text(&self) -> (String, String) { + let plain = |s: &str| s.replace("kártyajóslás", "kártya"); + (format!("Sorsfonalak – {}", plain(self.name)), plain(self.tagline)) + } + /// What the package gives, unit by unit. pub fn contents(&self) -> [(Unit, i64); 6] { [ @@ -420,12 +429,24 @@ mod tests { comment, "Hozzáférés a sorsfonalak.hu szoftveresen előállított, személyre szabott szöveges tartalmaihoz: \ 2 képletelemzés, 1 kapcsolati elemzés, 2 éves előrejelzés, 1 további személy felvétele, 3 kérdés, \ - 5 kártyaértelmezés. Digitális tartalom." + 5 egyedi szöveges tartalom. Digitális tartalom." ); let (name, comment) = find("addon_persons").unwrap().invoice_item(); - assert_eq!(name, "Online tartalomszolgáltatás – +5 személy kiegészítő"); + assert_eq!(name, "Online tartalomszolgáltatás – kiegészítő csomag"); assert!(comment.ends_with("tartalmaihoz: 5 további személy felvétele. Digitális tartalom."), "{comment}"); - // No profession is implied. - assert!(CATALOG.iter().all(|p| !format!("{:?}", p.invoice_item()).to_lowercase().contains("asztrol"))); + // No profession and no fortune-telling is implied. + for package in &CATALOG { + let item = format!("{:?}", package.invoice_item()).to_lowercase(); + assert!(!item.contains("asztrol") && !item.contains("jóslás") && !item.contains("kártya"), "{item}"); + } + } + + #[test] + fn stripe_says_kartya_instead_of_kartyajoslas() { + let (name, description) = find("addon_tarot").unwrap().checkout_text(); + assert_eq!(name, "Sorsfonalak – +5 kártya"); + assert_eq!(description, "Öt újabb kártya a saját kérdéseidre."); + assert_eq!(find("couple").unwrap().checkout_text().0, "Sorsfonalak – Páros"); + assert!(CATALOG.iter().all(|p| !format!("{:?}", p.checkout_text()).contains("jóslás"))); } } diff --git a/services/backend/src/routes/auth.rs b/services/backend/src/routes/auth.rs index ed856ac..7bb6a9c 100644 --- a/services/backend/src/routes/auth.rs +++ b/services/backend/src/routes/auth.rs @@ -1,5 +1,10 @@ -//! Registration and login: e-mail + password, Google; e-mail verification, -//! password reset, logout. +//! Registration and login: e-mail + password, Google, Apple; password links, +//! logout. +//! +//! A password can only be set through a link sent to the address (sign-up, +//! forgotten password), by whoever opens it. So every password account has a +//! confirmed address, and nobody can set a password for someone else's +//! address: linking a Google or Apple account with the same address is safe. use axum::Json; use axum::extract::State; @@ -100,14 +105,14 @@ async fn issue_token( Ok(token) } -/// Uses a one-time token; returns its user. -async fn consume_token(conn: &mut PgConnection, token: &str, purpose: &str) -> Result { +/// Uses a one-time token of one of `purposes`; returns its user. +async fn consume_token(conn: &mut PgConnection, token: &str, purposes: &[&str]) -> Result { let row: Option<(Uuid,)> = sqlx::query_as( "UPDATE auth_tokens SET used_at = now() \ - WHERE token_hash = $1 AND purpose = $2 AND used_at IS NULL AND expires_at > now() RETURNING user_id", + WHERE token_hash = $1 AND purpose = ANY($2) AND used_at IS NULL AND expires_at > now() RETURNING user_id", ) .bind(db::token_hash(token.trim())) - .bind(purpose) + .bind(purposes) .fetch_optional(conn) .await?; row.map(|(id,)| id).ok_or(ApiError::InvalidToken) @@ -141,10 +146,44 @@ pub async fn queue_email_to( Ok(()) } -async fn queue_verification(state: &AppState, conn: &mut PgConnection, user: &User) -> Result<(), ApiError> { - let token = issue_token(conn, user.id, "verify_email", VERIFY_EMAIL_TTL).await?; - let url = format!("{}/verify-email?token={token}", state.config.public_base_url); - queue_email(conn, user, "verify_email", json!({ "url": url, "display_name": user.display_name })).await +/// The e-mails that carry a password link. +const LINK_TEMPLATES: [&str; 3] = ["verify_email", "reset_password", "account_exists"]; + +/// Whether another password link may go to `email` now: one per kind a +/// minute and five an hour, so the forms cannot flood a mailbox. +async fn may_send_link(conn: &mut PgConnection, email: &str, template: &str) -> Result { + let (same_kind, total): (i64, i64) = sqlx::query_as( + "SELECT count(*) FILTER (WHERE template = $2 AND created_at > now() - interval '1 minute'), count(*) \ + FROM email_outbox WHERE to_email = $1 AND template = ANY($3) AND created_at > now() - interval '1 hour'", + ) + .bind(email) + .bind(template) + .bind(&LINK_TEMPLATES[..]) + .fetch_one(conn) + .await?; + Ok(same_kind == 0 && total < 5) +} + +/// Sends a link that sets the password: `verify_email` (sign-up, valid for 3 +/// days), `reset_password` (forgotten password) or `account_exists` (sign-up +/// with an address that already has an account), the latter two for 1 hour. +async fn queue_password_link( + state: &AppState, + conn: &mut PgConnection, + user: &User, + template: &'static str, +) -> Result<(), ApiError> { + if !may_send_link(conn, &user.email, template).await? { + tracing::info!(user = %user.id, template, "password link not sent: one went out a moment ago"); + return Ok(()); + } + let (purpose, ttl) = match template { + "verify_email" => ("verify_email", VERIFY_EMAIL_TTL), + _ => ("reset_password", RESET_PASSWORD_TTL), + }; + let token = issue_token(conn, user.id, purpose, ttl).await?; + let url = format!("{}/jelszo?token={token}", state.config.public_base_url); + queue_email(conn, user, template, json!({ "url": url, "display_name": user.display_name })).await } fn login_response( @@ -165,7 +204,6 @@ fn login_response( #[serde(deny_unknown_fields)] pub struct RegisterRequest { email: String, - password: String, display_name: Option, locale: Option, /// The invitation link's token, while sign-up needs an invitation. @@ -183,57 +221,57 @@ pub fn password_login_enabled(state: &crate::AppState) -> Result<(), ApiError> { } } +/// Sign-up with an e-mail address: no password yet, only a link to the +/// address, where the password is set. Answers 202 the same way whether or +/// not the address already has an account (that one gets a link to set a +/// password instead), so the form does not reveal who is registered. pub async fn register( State(state): St, - headers: HeaderMap, - jar: CookieJar, WithRejection(Json(req), _): Body, ) -> ApiResult { password_login_enabled(&state)?; let email = normalize_email(&req.email)?; - validate_password(&req.password)?; let locale = validate_locale(&state, req.locale.as_deref())?; - let hash = hash_password(req.password).await?; let mut tx = state.db.begin().await?; - let exists: Option<(Uuid,)> = - sqlx::query_as("SELECT id FROM users WHERE email = $1").bind(&email).fetch_optional(&mut *tx).await?; - if exists.is_some() { - return Err(ApiError::conflict("email_taken", "an account with this e-mail address already exists")); + let existing: Option = + sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1 FOR UPDATE")) + .bind(&email) + .fetch_optional(&mut *tx) + .await?; + match existing { + Some(user) if user.email_verified_at.is_none() => { + queue_password_link(&state, &mut tx, &user, "verify_email").await?; + } + Some(user) => queue_password_link(&state, &mut tx, &user, "account_exists").await?, + None => { + super::invitations::admit(&state, &mut tx, &email, req.invite_token.as_deref()).await?; + let user_id = Uuid::now_v7(); + sqlx::query("INSERT INTO users (id, email, display_name, locale) VALUES ($1, $2, $3, $4)") + .bind(user_id) + .bind(&email) + .bind(clean_name(req.display_name)) + .bind(&locale) + .execute(&mut *tx) + .await?; + // Packages of invitations go to this account; only whoever opens + // the link in the mailbox can ever log in to it. + super::invitations::mark_accepted( + &mut tx, + user_id, + &email, + req.invite_token.as_deref(), + state.config.free_person_slots, + ) + .await?; + super::shares::record_referral(&mut tx, state.config.referral_rewards, user_id, req.referral.as_deref()) + .await?; + let user = load_user(&mut tx, user_id).await?; + queue_password_link(&state, &mut tx, &user, "verify_email").await?; + } } - super::invitations::admit(&state, &mut tx, &email, req.invite_token.as_deref()).await?; - let user_id = Uuid::now_v7(); - sqlx::query("INSERT INTO users (id, email, display_name, locale) VALUES ($1, $2, $3, $4)") - .bind(user_id) - .bind(&email) - .bind(clean_name(req.display_name)) - .bind(&locale) - .execute(&mut *tx) - .await?; - sqlx::query("INSERT INTO auth_identities (id, user_id, provider, subject, password_hash, email) VALUES ($1, $2, 'password', $3, $4, $5)") - .bind(Uuid::now_v7()) - .bind(user_id) - .bind(user_id.to_string()) - .bind(hash) - .bind(&email) - .execute(&mut *tx) - .await?; - super::invitations::mark_accepted( - &mut tx, - user_id, - &email, - req.invite_token.as_deref(), - state.config.free_person_slots, - ) - .await?; - super::shares::record_referral(&mut tx, state.config.referral_rewards, user_id, req.referral.as_deref()).await?; - let mut user = load_user(&mut tx, user_id).await?; - apply_bootstrap_admin(&state, &mut tx, &mut user).await?; - queue_verification(&state, &mut tx, &user).await?; tx.commit().await?; - - let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?; - Ok(login_response(&state, jar, &user, session, true)) + Ok((StatusCode::ACCEPTED, Json(json!({ "sent": true })))) } #[derive(Deserialize)] @@ -254,9 +292,12 @@ pub async fn login( let email = normalize_email(&req.email).map_err(|_| invalid())?; state.login_limiter.check(&email)?; + // Passwords are set through e-mailed links, so every password account has + // a confirmed address; an unconfirmed one (made before that) cannot log in. let row: Option<(Uuid, String)> = sqlx::query_as( "SELECT u.id, i.password_hash FROM users u \ - JOIN auth_identities i ON i.user_id = u.id AND i.provider = 'password' WHERE u.email = $1", + JOIN auth_identities i ON i.user_id = u.id AND i.provider = 'password' \ + WHERE u.email = $1 AND u.email_verified_at IS NOT NULL", ) .bind(&email) .fetch_optional(&state.db) @@ -487,34 +528,7 @@ pub async fn logout_all(State(state): St, auth: AuthUser, jar: CookieJar) -> Api Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config)))) } -// --- e-mail verification and password reset ------------------------------------------------ - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -pub struct TokenRequest { - token: String, -} - -pub async fn verify_email(State(state): St, WithRejection(Json(req), _): Body) -> ApiResult> { - let mut tx = state.db.begin().await?; - let user_id = consume_token(&mut tx, &req.token, "verify_email").await?; - sqlx::query("UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1") - .bind(user_id) - .execute(&mut *tx) - .await?; - tx.commit().await?; - Ok(Json(json!({ "verified": true }))) -} - -pub async fn resend_verification(State(state): St, auth: AuthUser) -> ApiResult { - if auth.user.email_verified_at.is_some() { - return Err(ApiError::conflict("already_verified", "the e-mail address is already verified")); - } - let mut tx = state.db.begin().await?; - queue_verification(&state, &mut tx, &auth.user).await?; - tx.commit().await?; - Ok(StatusCode::ACCEPTED) -} +// --- password links --------------------------------------------------------------------- #[derive(Deserialize)] #[serde(deny_unknown_fields)] @@ -522,7 +536,9 @@ pub struct ResetRequest { email: String, } -/// Always 202, so the response does not reveal whether the address is registered. +/// Forgotten password: a link to set a new one (also adds a password to a +/// Google or Apple account). Always 202, so the response does not reveal +/// whether the address is registered. pub async fn request_password_reset( State(state): St, WithRejection(Json(req), _): Body, @@ -530,14 +546,12 @@ pub async fn request_password_reset( password_login_enabled(&state)?; 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")) + let user: Option = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1 FOR UPDATE")) .bind(&email) .fetch_optional(&mut *tx) .await?; if let Some(user) = user { - let token = issue_token(&mut tx, user.id, "reset_password", RESET_PASSWORD_TTL).await?; - let url = format!("{}/reset-password?token={token}", state.config.public_base_url); - queue_email(&mut tx, &user, "reset_password", json!({ "url": url, "display_name": user.display_name })).await?; + queue_password_link(&state, &mut tx, &user, "reset_password").await?; } tx.commit().await?; Ok(StatusCode::ACCEPTED) @@ -545,31 +559,38 @@ pub async fn request_password_reset( #[derive(Deserialize)] #[serde(deny_unknown_fields)] -pub struct ResetConfirmRequest { +pub struct SetPasswordRequest { token: String, password: String, } -/// Sets a new password (adding the password login if the user had only -/// Google) and ends all sessions. -pub async fn confirm_password_reset( +/// Sets the password with an e-mailed link (sign-up or forgotten password): +/// the address counts as confirmed, every other session ends, and this one +/// is logged in. +pub async fn set_password_with_link( State(state): St, - WithRejection(Json(req), _): Body, -) -> ApiResult { + headers: HeaderMap, + jar: CookieJar, + WithRejection(Json(req), _): Body, +) -> ApiResult { password_login_enabled(&state)?; validate_password(&req.password)?; let hash = hash_password(req.password).await?; let mut tx = state.db.begin().await?; - let user_id = consume_token(&mut tx, &req.token, "reset_password").await?; + let user_id = consume_token(&mut tx, &req.token, &["verify_email", "reset_password"]).await?; set_password(&mut tx, user_id, &hash).await?; - // The link arrived in the mailbox, so the address is verified. sqlx::query("UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1") .bind(user_id) .execute(&mut *tx) .await?; sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(user_id).execute(&mut *tx).await?; + let mut user = load_user(&mut tx, user_id).await?; + apply_bootstrap_admin(&state, &mut tx, &mut user).await?; tx.commit().await?; - Ok(StatusCode::NO_CONTENT) + state.login_limiter.succeeded(&user.email); + + let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?; + Ok(login_response(&state, jar, &user, session, false)) } /// Creates or replaces the password identity. diff --git a/services/backend/src/routes/calculator.rs b/services/backend/src/routes/calculator.rs new file mode 100644 index 0000000..a735473 --- /dev/null +++ b/services/backend/src/routes/calculator.rs @@ -0,0 +1,117 @@ +//! The public birth chart (`/szuletesi-horoszkop`): the whole natal chart from +//! birth data, without an account, plus the country list and place search it +//! needs. A calculation only: no AI, 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}; +use crate::views::chart_highlights; + +/// 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 ChartRequest { + 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, +} + +/// Whether a point may have been in the neighbouring sign at the start or the +/// end of the birth day (when the birth time is unknown). +fn uncertain(point: &Value, default_speed: f64) -> bool { + let speed = point["speed"].as_f64().unwrap_or(default_speed).abs(); + point["degree_in_sign"].as_f64().is_some_and(|d| d < speed / 2.0 || 30.0 - d < speed / 2.0) +} + +/// The natal chart of the birth data, as the chart pages show it. +pub async fn chart( + 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 uncertain = json!({ + "sun": !time_known && uncertain(&point("sun"), 1.0), + "moon": !time_known && uncertain(&point("moon"), 13.2), + }); + Ok(Json(json!({ "highlights": chart_highlights(&chart), "uncertain": uncertain, "chart": chart }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn signs_near_a_border_are_uncertain() { + assert!(uncertain(&json!({"degree_in_sign": 3.2, "speed": 12.6}), 13.2)); + assert!(!uncertain(&json!({"degree_in_sign": 15.0, "speed": 12.6}), 13.2)); + assert!(uncertain(&json!({"degree_in_sign": 29.8}), 1.0)); + assert!(!uncertain(&json!({"degree_in_sign": 29.0}), 1.0)); + } +} diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 7ba868d..1331e37 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; @@ -78,10 +79,8 @@ pub fn router(state: Arc) -> Router { .route("/v1/auth/apple", post(auth::apple)) .route("/v1/auth/logout", post(auth::logout)) .route("/v1/auth/logout-all", post(auth::logout_all)) - .route("/v1/auth/verify-email", post(auth::verify_email)) - .route("/v1/auth/resend-verification", post(auth::resend_verification)) .route("/v1/auth/password-reset", post(auth::request_password_reset)) - .route("/v1/auth/password-reset/confirm", post(auth::confirm_password_reset)) + .route("/v1/auth/set-password", post(auth::set_password_with_link)) // own account (GDPR export and deletion included) .route("/v1/me", get(account::me).patch(account::update_me).delete(account::delete_me)) .route("/v1/me/password", post(account::change_password)) @@ -127,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/chart", post(calculator::chart)) + .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/routes/payments.rs b/services/backend/src/routes/payments.rs index 65ed79d..8cddc3e 100644 --- a/services/backend/src/routes/payments.rs +++ b/services/backend/src/routes/payments.rs @@ -86,7 +86,7 @@ pub fn method(config: &crate::config::Config) -> Option<&'static str> { } /// The terms (ÁSZF) version a purchase accepts; the frontend's `TERMS_UPDATED`. -pub const TERMS_VERSION: &str = "2026-11-20"; +pub const TERMS_VERSION: &str = "2026-11-22"; /// Only admins can buy through Stripe: until purchases open, and always with a /// test key (nobody gets packages with Stripe's test cards, nobody types a @@ -132,6 +132,7 @@ pub async fn checkout( let config = stripe_for(&state, &auth)?; let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?; let back = format!("{}{}", state.config.public_base_url, return_path(req.return_path.as_deref())); + let (checkout_name, checkout_description) = package.checkout_text(); let field = |k: &str, v: &str| (k.to_string(), v.to_string()); let mut form = vec![ field("mode", "payment"), @@ -147,11 +148,11 @@ pub async fn checkout( field("line_items[0][price_data][currency]", "huf"), // Stripe counts forints in fillér. field("line_items[0][price_data][unit_amount]", &(package.price_huf * 100).to_string()), - field("line_items[0][price_data][product_data][name]", &format!("Sorsfonalak – {}", package.name)), - field("line_items[0][price_data][product_data][description]", package.tagline), + field("line_items[0][price_data][product_data][name]", &checkout_name), + field("line_items[0][price_data][product_data][description]", &checkout_description), field("metadata[package]", package.id), field("metadata[user_id]", &auth.id().to_string()), - field("payment_intent_data[description]", &format!("Sorsfonalak – {}", package.name)), + field("payment_intent_data[description]", &checkout_name), field("payment_intent_data[metadata][package]", package.id), field("success_url", &format!("{back}?fizetes={{CHECKOUT_SESSION_ID}}")), field("cancel_url", &format!("{back}?fizetes=megszakitva")), diff --git a/services/backend/src/routes/shares.rs b/services/backend/src/routes/shares.rs index 31e9b61..9bf91b1 100644 --- a/services/backend/src/routes/shares.rs +++ b/services/backend/src/routes/shares.rs @@ -326,6 +326,11 @@ pub async fn visit( if sharer || same_place || is_robot(user_agent(&headers).as_deref()) { return Ok(Json(json!({ "counted": false }))); } + // The same visitor again within half an hour (a reload, back and forth). + let visitor = format!("{}:{}", share.slug, client_ip(&headers).unwrap_or_default()); + if state.share_visits.hit(&visitor).is_err() { + return Ok(Json(json!({ "counted": false }))); + } let mut tx = state.db.begin().await?; sqlx::query("UPDATE shares SET view_count = view_count + 1 WHERE id = $1").bind(share.id).execute(&mut *tx).await?; let rewarded = sqlx::query( diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 743474a..d2b981a 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)); @@ -278,17 +286,32 @@ impl TestApp { /// Registers a user; returns the session token. async fn register(&self, email: &str, name: &str) -> String { + self.register_with(json!({"email": email, "display_name": name})).await + } + + /// Signs up with `body` and sets the password through the e-mailed link; + /// returns the session token. + async fn register_with(&self, body: Value) -> String { + let r = self.post("/v1/auth/register", None, body.clone()).await; + assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body); + let email = body["email"].as_str().unwrap().trim().to_lowercase(); + let url = self.outbox_url(&email, "verify_email").await; let r = self - .post( - "/v1/auth/register", - None, - json!({"email": email, "password": "titkos-jelszo-123", "display_name": name}), - ) + .post("/v1/auth/set-password", None, json!({"token": token_param(&url), "password": "titkos-jelszo-123"})) .await; - assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + assert_eq!(r.status, StatusCode::OK, "{}", r.body); r.body["session"]["token"].as_str().unwrap().to_string() } + async fn outbox_count(&self, email: &str, template: &str) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM email_outbox WHERE to_email = $1 AND template = $2") + .bind(email) + .bind(template) + .fetch_one(&self.pool) + .await + .unwrap() + } + /// An admin adds units to their own account (admins use units too). async fn add_own_units(&self, admin: &str, unit: &str, delta: i32) { let id = self.get("/v1/me", Some(admin)).await.body["user"]["id"].as_str().unwrap().to_string(); @@ -333,38 +356,48 @@ fn token_param(url: &str) -> &str { #[sqlx::test(migrator = "db::MIGRATOR")] async fn register_login_verify_logout(pool: PgPool) { let app = TestApp::new(pool).await; - let r = app - .post("/v1/auth/register", None, json!({"email": "Anna@Example.com", "password": "titkos-jelszo-123"})) - .await; - assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + // Sign-up takes no password: it is set through the e-mailed link. + let r = + app.post("/v1/auth/register", None, json!({"email": "x@example.com", "password": "titkos-jelszo-123"})).await; + assert_eq!(r.status, StatusCode::BAD_REQUEST); + let r = app.post("/v1/auth/register", None, json!({"email": "Anna@Example.com", "display_name": "Anna"})).await; + assert_eq!((r.status, &r.body["sent"]), (StatusCode::ACCEPTED, &json!(true)), "{}", r.body); + assert!(r.headers.get("set-cookie").is_none(), "no session before the link"); + let url = app.outbox_url("anna@example.com", "verify_email").await; + assert!(url.starts_with("https://sorsfonalak.test/jelszo?token=")); + + // no login before the password is set + let r = + app.post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"})).await; + assert_eq!(r.status, StatusCode::UNAUTHORIZED); + + // a too short password does not use up the link + let set = |password: &'static str| { + app.post("/v1/auth/set-password", None, json!({"token": token_param(&url), "password": password})) + }; + assert_eq!(set("rovid").await.status, StatusCode::BAD_REQUEST); + let r = set("titkos-jelszo-123").await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); let cookie = r.headers.get("set-cookie").unwrap().to_str().unwrap(); assert!(cookie.starts_with("sf_session=") && cookie.contains("HttpOnly") && cookie.contains("Secure")); assert_eq!(r.body["user"]["email"], "anna@example.com"); assert_eq!(r.body["user"]["roles"], json!(["user"])); - assert_eq!(r.body["user"]["email_verified"], false); + assert_eq!(r.body["user"]["email_verified"], true); let token = r.body["session"]["token"].as_str().unwrap().to_string(); - - // duplicate, short password - let r = app - .post("/v1/auth/register", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"})) - .await; - assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("email_taken"))); - let r = app.post("/v1/auth/register", None, json!({"email": "b@example.com", "password": "rovid"})).await; - assert_eq!(r.status, StatusCode::BAD_REQUEST); + assert_eq!(set("masik-jelszo-123").await.body["error"]["code"], "invalid_token"); let r = app.get("/v1/me", Some(&token)).await; assert_eq!(r.status, StatusCode::OK); assert_eq!(r.body["providers"], json!(["password"])); assert_eq!(r.body["analyses_left"], json!({"natal": 0, "synastry": 0, "forecast": 0, "question": 0, "tarot": 0})); - // e-mail verification through the queued e-mail's link - let url = app.outbox_url("anna@example.com", "verify_email").await; - assert!(url.starts_with("https://sorsfonalak.test/verify-email?token=")); - let r = app.post("/v1/auth/verify-email", None, json!({"token": token_param(&url)})).await; - assert_eq!(r.status, StatusCode::OK, "{}", r.body); - let r = app.post("/v1/auth/verify-email", None, json!({"token": token_param(&url)})).await; - assert_eq!(r.body["error"]["code"], "invalid_token"); - assert_eq!(app.get("/v1/me", Some(&token)).await.body["user"]["email_verified"], true); + // signing up again with the address: the same answer, and the owner gets + // a link instead (once a minute at most) + for _ in 0..2 { + let r = app.post("/v1/auth/register", None, json!({"email": "anna@example.com"})).await; + assert_eq!(r.status, StatusCode::ACCEPTED); + } + assert_eq!(app.outbox_count("anna@example.com", "account_exists").await, 1); // login let r = @@ -400,15 +433,25 @@ async fn password_reset_ends_sessions(pool: PgPool) { StatusCode::ACCEPTED ); let url = app.outbox_url("anna@example.com", "reset_password").await; + assert!(url.starts_with("https://sorsfonalak.test/jelszo?token=")); let r = app - .post( - "/v1/auth/password-reset/confirm", - None, - json!({"token": token_param(&url), "password": "uj-titkos-jelszo-456"}), - ) + .post("/v1/auth/set-password", None, json!({"token": token_param(&url), "password": "uj-titkos-jelszo-456"})) .await; - assert_eq!(r.status, StatusCode::NO_CONTENT, "{}", r.body); + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + let fresh = r.body["session"]["token"].as_str().unwrap().to_string(); assert_eq!(app.get("/v1/me", Some(&token)).await.status, StatusCode::UNAUTHORIZED); + assert_eq!(app.get("/v1/me", Some(&fresh)).await.status, StatusCode::OK); + // the sign-up link cannot be used for it any more either + let signup = app.outbox_url("anna@example.com", "verify_email").await; + let r = app + .post("/v1/auth/set-password", None, json!({"token": token_param(&signup), "password": "harmadik-jelszo-789"})) + .await; + assert_eq!(r.body["error"]["code"], "invalid_token"); + // a flood of requests sends one more link a minute at most + for _ in 0..3 { + app.post("/v1/auth/password-reset", None, json!({"email": "anna@example.com"})).await; + } + assert_eq!(app.outbox_count("anna@example.com", "reset_password").await, 1); let r = app .post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "uj-titkos-jelszo-456"})) .await; @@ -430,31 +473,49 @@ async fn google_login_creates_links_and_rejects(pool: PgPool) { .await; assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false))); - // an existing, confirmed password account with the same address gets Google linked + // an existing password account with the same address gets Google linked + // (its address was confirmed when the password was set) let token = app.register("anna@example.com", "Anna").await; - sqlx::query("UPDATE users SET email_verified_at = now() WHERE email = 'anna@example.com'") - .execute(&app.pool) - .await - .unwrap(); let r = app .post("/v1/auth/google", None, json!({"id_token": google_token("g-2", "anna@example.com", GOOGLE_CLIENT)})) .await; assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false))); assert_eq!(app.get("/v1/me", Some(&token)).await.body["providers"], json!(["password", "google"])); - // an unconfirmed one may be someone else's: its password and sessions go - let squatter = app.register("victim@example.com", "Valaki").await; + // Someone signs up with another person's address: no password, no session. + // When the owner comes with Google, the account is theirs, and the link + // in their mailbox would only let them set their own password. + let r = app.post("/v1/auth/register", None, json!({"email": "victim@example.com", "display_name": "Valaki"})).await; + assert_eq!(r.status, StatusCode::ACCEPTED); let r = app .post("/v1/auth/google", None, json!({"id_token": google_token("g-4", "victim@example.com", GOOGLE_CLIENT)})) .await; assert_eq!(r.status, StatusCode::OK, "{}", r.body); let owner = r.body["session"]["token"].as_str().unwrap().to_string(); - assert_eq!(app.get("/v1/me", Some(&squatter)).await.status, StatusCode::UNAUTHORIZED); - assert_eq!(app.get("/v1/me", Some(&owner)).await.body["providers"], json!(["google"])); + let me = app.get("/v1/me", Some(&owner)).await.body; + assert_eq!((&me["providers"], &me["user"]["email_verified"]), (&json!(["google"]), &json!(true))); let r = app.post("/v1/auth/login", None, json!({"email": "victim@example.com", "password": "titkos-jelszo-123"})).await; assert_eq!(r.status, StatusCode::UNAUTHORIZED); + // An unconfirmed password account from before the links (legacy) cannot + // log in, and Google login removes its password and sessions. + let legacy = app.register("old@example.com", "Régi").await; + sqlx::query("UPDATE users SET email_verified_at = NULL WHERE email = 'old@example.com'") + .execute(&app.pool) + .await + .unwrap(); + let r = + app.post("/v1/auth/login", None, json!({"email": "old@example.com", "password": "titkos-jelszo-123"})).await; + assert_eq!(r.status, StatusCode::UNAUTHORIZED); + let r = app + .post("/v1/auth/google", None, json!({"id_token": google_token("g-5", "old@example.com", GOOGLE_CLIENT)})) + .await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!(app.get("/v1/me", Some(&legacy)).await.status, StatusCode::UNAUTHORIZED); + let owner = r.body["session"]["token"].as_str().unwrap().to_string(); + assert_eq!(app.get("/v1/me", Some(&owner)).await.body["providers"], json!(["google"])); + let r = app .post("/v1/auth/google", None, json!({"id_token": google_token("g-3", "x@gmail.com", "other-client")})) .await; @@ -769,15 +830,15 @@ async fn analyses_spend_units_and_reuse_results(pool: PgPool) { async fn password_login_can_be_disabled(pool: PgPool) { let app = TestApp::with_config(pool, |c| c.password_login = false).await; assert_eq!(app.get("/v1/config", None).await.body["password_login"], false); - let r = app - .post("/v1/auth/register", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"})) - .await; + let r = app.post("/v1/auth/register", None, json!({"email": "anna@example.com"})).await; assert_eq!(r.status, StatusCode::FORBIDDEN); let r = app.post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"})).await; assert_eq!(r.status, StatusCode::FORBIDDEN); let r = app.post("/v1/auth/password-reset", None, json!({"email": "anna@example.com"})).await; assert_eq!(r.status, StatusCode::FORBIDDEN); + let r = app.post("/v1/auth/set-password", None, json!({"token": "x", "password": "titkos-jelszo-123"})).await; + assert_eq!(r.status, StatusCode::FORBIDDEN); } #[sqlx::test(migrator = "db::MIGRATOR")] @@ -880,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; 17] = [ +const PUBLIC_ROUTES: [&str; 19] = [ "/healthz", // Stripe calls it; the signature proves it. "/v1/payments/stripe/webhook", @@ -890,17 +951,65 @@ const PUBLIC_ROUTES: [&str; 17] = [ "/v1/auth/login", "/v1/auth/google", "/v1/auth/apple", - "/v1/auth/verify-email", "/v1/auth/password-reset", - "/v1/auth/password-reset/confirm", + "/v1/auth/set-password", "/v1/public/shares/{slug}", "/v1/public/shares/{slug}/visit", "/v1/public/invites/{token}", "/v1/public/invitations/unsubscribe", "/v1/public/invitations/{token}", "/v1/public/waitlist", + // The public birth chart (limited per visitor address). + "/v1/public/chart", + "/v1/public/geo/countries", + "/v1/public/geo/places", ]; +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn the_public_birth_chart(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/chart", None, Some(birth.clone()), &[visitor]).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!( + r.body["highlights"], + json!({"sun": "cancer", "moon": "pisces", "ascendant": "aries", "time_known": true}) + ); + assert_eq!(r.body["chart"]["points"][0]["id"], "sun", "the whole chart comes back"); + // Without a birth time there is no Ascendant. + let r = app + .call_with( + "POST", + "/v1/public/chart", + None, + Some(json!({"date": "1990-06-21", "country": "HU", "geonames_id": 715429})), + &[visitor], + ) + .await; + assert_eq!((r.status, &r.body["highlights"]["time_known"]), (StatusCode::OK, &json!(false))); + let r = app.call_with("POST", "/v1/public/chart", 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/chart", None, Some(birth.clone()), &[visitor]).await; + assert_eq!(r.status, StatusCode::OK); + } + let r = app.call_with("POST", "/v1/public/chart", None, Some(birth.clone()), &[visitor]).await; + assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS); + let r = app.call_with("POST", "/v1/public/chart", 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; @@ -937,10 +1046,13 @@ async fn a_visit_by_someone_else_earns_one_question_once(pool: PgPool) { app.get(&visit.replace("/visit", ""), None).await; // someone else: counted, and the reward comes once - for _ in 0..2 { - let r = app.call_with("POST", &visit, None, None, &[browser, elsewhere]).await; - assert_eq!(r.body["counted"], true); - } + let r = app.call_with("POST", &visit, None, None, &[browser, elsewhere]).await; + assert_eq!(r.body["counted"], true); + // the same visitor again soon (a reload) is not a new visit + let r = app.call_with("POST", &visit, None, None, &[browser, elsewhere]).await; + assert_eq!(r.body["counted"], false); + let r = app.call_with("POST", &visit, None, None, &[browser, ("x-real-ip", "198.51.100.3")]).await; + assert_eq!(r.body["counted"], true); let body = me().await; assert_eq!( (body["analyses_left"]["question"].as_i64(), &body["share_reward_granted"]), @@ -2296,20 +2408,7 @@ async fn a_new_user_from_a_shared_link_earns_an_analysis(pool: PgPool) { let before = natal(anna.clone()).await; let join = |email: String| { let (app, slug) = (&app, slug.clone()); - async move { - let r = app - .post( - "/v1/auth/register", - None, - json!({"email": email, "password": "titkos-jelszo-123", "referral": slug}), - ) - .await; - assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); - r.body["token"].as_str().map(str::to_string).unwrap_or_else(|| { - let cookie = r.headers.get("set-cookie").unwrap().to_str().unwrap(); - cookie.split(';').next().unwrap().split('=').nth(1).unwrap().to_string() - }) - } + async move { app.register_with(json!({"email": email, "referral": slug})).await } }; // signing up is not enough: the reward comes with their own chart @@ -2332,14 +2431,7 @@ async fn a_new_user_from_a_shared_link_earns_an_analysis(pool: PgPool) { // nothing while the rewards are off let off = TestApp::with_config(pool, |c| c.referral_rewards = false).await; - let r = off - .post( - "/v1/auth/register", - None, - json!({"email": "late@example.com", "password": "titkos-jelszo-123", "referral": slug}), - ) - .await; - assert_eq!(r.status, StatusCode::CREATED); + off.register_with(json!({"email": "late@example.com", "referral": slug})).await; let count: i64 = sqlx::query_scalar( "SELECT count(*) FROM referrals r JOIN users u ON u.id = r.user_id WHERE u.email = 'late@example.com'", ) diff --git a/services/frontend/src/app/Landing.tsx b/services/frontend/src/app/Landing.tsx index 6fbba09..ea2f624 100644 --- a/services/frontend/src/app/Landing.tsx +++ b/services/frontend/src/app/Landing.tsx @@ -12,21 +12,6 @@ import type { AnalysisContent, ChartResult } from "@/lib/types"; /** The cards fanned out next to the tarot line (after a card back). */ const TAROT_CARDS = ["major-2", "major-17"].map((id) => tarotCard(id)).filter((c) => c !== undefined); -// A quiet starfield, the same on every render. -const STARS = (() => { - let seed = 7; - const rnd = () => { - seed = (seed * 9301 + 49297) % 233280; - return seed / 233280; - }; - return Array.from({ length: 70 }, (_, i) => ({ - x: (rnd() * 1000).toFixed(1), - y: (rnd() * 600).toFixed(1), - r: (0.6 + rnd() * 1.4).toFixed(1), - t: i % 5, - })); -})(); - const MONTHS = ["márc", "ápr", "máj", "jún", "júl", "aug", "szept", "okt", "nov", "dec", "jan", "febr"]; /** Points of a ring of the comparison picture. */ @@ -68,11 +53,6 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {
-
Születési képlet · Éves előrejelzés · Kapcsolat @@ -97,6 +77,10 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) { Példaelemzés
+

+ Ingyenes + Nézd meg a születési horoszkópodat belépés nélkül → +

{inviteOnly ? ( <> @@ -137,6 +121,34 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {

+
+
+
+ Ingyenes +

+ Belépés nélkül is kipróbálhatod +

+
+
+ + Születési horoszkóp + + A teljes képleted percre pontosan: képletrajz, aszcendens, holdjegy, bolygók a jegyekben és a házakban, + fényszögek. + + Elkészítem → + + + A 12 csillagjegy + + Milyen a jegyed napjegyként, holdjegyként és aszcendensként? Párkapcsolat, munka, és ami nem igaz róla. + + Megnézem → + +
+
+
+
@@ -480,6 +492,8 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {
-

1. A szolgáltató

+

1. A szolgáltatás

- {operatorDetails() ? ( - <> - A sorsfonalak.hu weboldalt és szolgáltatást (a továbbiakban: Sorsfonalak) a(z){" "} - {operatorDetails()} nyújtja. - - ) : ( - "A sorsfonalak.hu weboldalt és szolgáltatást (a továbbiakban: Sorsfonalak) üzemeltető szolgáltató adatai a vállalkozás bejegyzése után itt szerepelnek." - )}{" "} - Elérhetőség: {email}. A szolgáltatás nyelve magyar. -

-

- Tárhelyszolgáltató: DigitalOcean, LLC (digitalocean.com); az adatok az Európai Unióban (Amszterdam) - vannak tárolva. -

-
- -
-

2. A szolgáltatás

-

- A Sorsfonalak online tartalomszolgáltatás. A megadott születési adatokból kiszámítja és megrajzolja a - születési képletet, és ingyenes rövid összefoglalót ad. Csomagok vásárlásával a felhasználó szoftveresen - (mesterséges intelligenciával) előállított, személyre szabott szöveges tartalmakat kérhet: részletes - képletelemzést, kapcsolati elemzést, éves előrejelzést és kérdésekre adott válaszokat, valamint további - személyeket vehet fel. + A sorsfonalak.hu weboldal és szolgáltatás (a továbbiakban: Sorsfonalak) online tartalomszolgáltatás. A + megadott születési adatokból kiszámítja és megrajzolja a születési képletet, és ingyenes rövid összefoglalót + ad. Csomagok vásárlásával a felhasználó szoftveresen (mesterséges intelligenciával) előállított, személyre + szabott szöveges tartalmakat kérhet: részletes képletelemzést, kapcsolati elemzést, éves előrejelzést, + kártyajóslást és kérdésekre adott válaszokat, valamint további személyeket vehet fel.

A tartalmak szórakoztató és önismereti célúak. Nem minősülnek orvosi, pszichológiai, pénzügyi, jogi vagy @@ -63,17 +45,18 @@ export default async function TermsPage() {

-

3. Regisztráció

+

2. Regisztráció

- A szolgáltatás Google-fiókkal vehető igénybe, 16 éven felülieknek. Amíg az oldal meghívásos, új fiók csak - meghívóval jön létre. A felhasználó felel azért, hogy a megadott adatok (köztük mások születési adatai) az - érintettek hozzájárulásával kerüljenek a rendszerbe. Az adatkezelésről az{" "} + A szolgáltatás regisztrációval vehető igénybe (Google- vagy Apple-fiókkal, vagy e-mail-címmel és jelszóval), + 16 éven felülieknek. Amíg az oldal meghívásos, új fiók csak meghívóval jön létre. A felhasználó felel azért, + hogy a megadott adatok (köztük mások születési adatai) az érintettek hozzájárulásával kerüljenek a + rendszerbe. Az adatkezelésről az{" "} adatvédelmi tájékoztató szól.

-

4. A vásárlás menete

+

3. A vásárlás menete

  1. A felhasználó a Csomagok oldalon (vagy egy elemzésnél) kiválasztja a csomagot, és a „Megveszem” gombra kattint.
  2. @@ -82,7 +65,7 @@ export default async function TermsPage() {
  3. A fizetés előtt elfogadja ezt az ÁSZF-et, kéri a szolgáltatás azonnali megkezdését, és tudomásul veszi, - hogy ezzel elveszíti az elállási jogát (7. pont). + hogy ezzel elveszíti az elállási jogát (6. pont).
  4. A fizetéssel a szerződés létrejön. A csomagot azonnal jóváírjuk, és e-mailben visszaigazoljuk.
@@ -94,7 +77,7 @@ export default async function TermsPage() {
-

5. Árak, fizetés, számla

+

4. Árak, fizetés, számla

Az árak forintban értendő végső árak. Alanyi adómentesek vagyunk, áfát nem számítunk fel. Az árak változhatnak; a vásárláskor látott ár érvényes. @@ -107,7 +90,7 @@ export default async function TermsPage() {

-

6. Teljesítés

+

5. Teljesítés

A csomag egységei (elemzések, előrejelzések, kérdések, személyhelyek) a fizetés igazolása után azonnal a fiókban vannak. Nem járnak le, nem ruházhatók át, és pénzre nem válthatók vissza. Egy elemzés elkészítése @@ -116,7 +99,7 @@ export default async function TermsPage() {

-

7. Elállási jog

+

6. Elállási jog

Online vásárlásnál a fogyasztót alapesetben 14 napos, indoklás nélküli elállási jog illeti meg. Nem tárgyi adathordozón nyújtott digitális tartalomnál és szolgáltatásnál ez megszűnik, ha a teljesítés a fogyasztó @@ -128,7 +111,7 @@ export default async function TermsPage() {

-

8. Hibás teljesítés

+

7. Hibás teljesítés

Ha a szolgáltatás nem működik megfelelően, a jogszabályok szerinti jogok megilletnek (Ptk.; 373/2021. (VI. 30.) Korm. rendelet). Ha egy kért elemzés többszöri próbálkozás után sem készül el, a felhasznált egységet @@ -138,7 +121,7 @@ export default async function TermsPage() {

-

9. A fiók megszüntetése

+

8. A fiók megszüntetése

A fiók a Profil oldalon bármikor törölhető. A fel nem használt egységek ezzel megszűnnek; ezekért visszatérítés nem jár, kivéve, ha a törlést a szolgáltatás hibája tette szükségessé. A jogszabálysértő @@ -147,21 +130,28 @@ export default async function TermsPage() {

-

10. Panaszkezelés, jogorvoslat

+

9. Panaszkezelés, jogorvoslat

Panaszt a {email} címen tehetsz; 30 napon belül írásban válaszolunk. Ha a panaszt nem rendezzük, a - szolgáltató székhelye szerint illetékes békéltető testülethez fordulhatsz, panaszt tehetsz a + szolgáltató székhelye szerint illetékes békéltető testülethez fordulhatsz ({ARBITRATION_BOARD.name},{" "} + {ARBITRATION_BOARD.address}, {ARBITRATION_BOARD.email},{" "} + {ARBITRATION_BOARD.web.replace("https://", "")}), panaszt tehetsz a fogyasztóvédelmi hatóságnál (a lakóhelyed szerinti kormányhivatal), vagy bírósághoz fordulhatsz.

-

11. Egyéb

+

10. Egyéb

Az ÁSZF módosítása a módosítás után kötött vásárlásokra vonatkozik; a lényeges változásokat az oldalon - jelezzük. A szerződésre a magyar jog irányadó. + jelezzük. A szerződés és a szolgáltatás nyelve magyar, a szerződésre a magyar jog irányadó.

+ +
+

11. A szolgáltató adatai

+ +
); diff --git a/services/frontend/src/app/belepes/AppleLogin.tsx b/services/frontend/src/app/belepes/AppleLogin.tsx index 0e5b66f..8eef023 100644 --- a/services/frontend/src/app/belepes/AppleLogin.tsx +++ b/services/frontend/src/app/belepes/AppleLogin.tsx @@ -55,10 +55,13 @@ export function AppleLogin({ clientId, target, inviteToken = null, + referral = null, }: { clientId: string; target: string; inviteToken?: string | null; + /** The shared link the visitor came from (in the login link: `?ref=`), for the sharer's reward. */ + referral?: string | null; }) { const router = useRouter(); const [ready, setReady] = useState(false); @@ -95,20 +98,9 @@ export function AppleLogin({ setBusy(true); const name = [response.user?.name?.lastName, response.user?.name?.firstName].filter(Boolean).join(" ") || null; try { - let referral: string | null = null; - try { - referral = localStorage.getItem("sf_ref"); - } catch { - // storage blocked - } await api("/auth/apple", { body: { id_token: response.authorization.id_token, name, invite_token: inviteToken, referral }, }); - try { - localStorage.removeItem("sf_ref"); - } catch { - // storage blocked - } router.replace(target); router.refresh(); } catch (e) { diff --git a/services/frontend/src/app/belepes/GoogleLogin.tsx b/services/frontend/src/app/belepes/GoogleLogin.tsx index 11a317f..4b3117d 100644 --- a/services/frontend/src/app/belepes/GoogleLogin.tsx +++ b/services/frontend/src/app/belepes/GoogleLogin.tsx @@ -52,11 +52,14 @@ export function GoogleLogin({ clientId, target, inviteToken = null, + referral = null, }: { clientId: string; target: string; /** From an invitation link: lets in any Google account. */ inviteToken?: string | null; + /** The shared link the visitor came from (in the login link: `?ref=`), for the sharer's reward. */ + referral?: string | null; }) { const router = useRouter(); const slot = useRef(null); @@ -72,18 +75,7 @@ export function GoogleLogin({ setError(null); setUninvited(null); try { - let referral: string | null = null; - try { - referral = localStorage.getItem("sf_ref"); - } catch { - // storage blocked - } await api("/auth/google", { body: { id_token: response.credential, invite_token: inviteToken, referral } }); - try { - localStorage.removeItem("sf_ref"); - } catch { - // storage blocked - } router.replace(target); router.refresh(); } catch (e) { @@ -92,7 +84,7 @@ export function GoogleLogin({ setBusy(false); } }, - [router, target, inviteToken], + [router, target, inviteToken, referral], ); useEffect(() => { diff --git a/services/frontend/src/app/belepes/PasswordLogin.tsx b/services/frontend/src/app/belepes/PasswordLogin.tsx new file mode 100644 index 0000000..14e6cbf --- /dev/null +++ b/services/frontend/src/app/belepes/PasswordLogin.tsx @@ -0,0 +1,200 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useState } from "react"; + +import { Waitlist } from "@/components/Waitlist"; +import { ApiError, api, errorText } from "@/lib/api"; + +type Mode = "login" | "register" | "forgot"; + +function loginError(e: unknown): string { + if (e instanceof ApiError) { + if (e.code === "invalid_credentials") return "Hibás e-mail-cím vagy jelszó."; + if (e.code === "too_many_requests") return "Túl sok sikertelen próbálkozás. Próbáld újra negyedóra múlva."; + } + return errorText(e); +} + +/** + * E-mail and password: login, sign-up and forgotten password. Sign-up asks + * no password: it is set through the link sent to the address, so nobody can + * set a password for someone else's address. + */ +export function PasswordLogin({ + target, + inviteToken = null, + referral = null, + initialMode = "login", +}: { + target: string; + inviteToken?: string | null; + /** The shared link the visitor came from (in the login link: `?ref=`), for the sharer's reward. */ + referral?: string | null; + initialMode?: Mode; +}) { + const router = useRouter(); + const [mode, setMode] = useState(initialMode); + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [name, setName] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [sent, setSent] = useState(null); + const [uninvited, setUninvited] = useState(false); + + function switchTo(next: Mode) { + setMode(next); + setError(null); + setSent(null); + setUninvited(false); + } + + async function submit(e: React.FormEvent) { + e.preventDefault(); + setBusy(true); + setError(null); + setUninvited(false); + try { + if (mode === "login") { + await api("/auth/login", { body: { email, password } }); + router.replace(target); + router.refresh(); + return; + } + if (mode === "register") { + await api("/auth/register", { + body: { email, display_name: name.trim() || null, locale: "hu", invite_token: inviteToken, referral }, + }); + } else { + await api("/auth/password-reset", { body: { email } }); + } + setSent(mode); + } catch (err) { + if (err instanceof ApiError && err.code === "not_invited") setUninvited(true); + else setError(mode === "login" ? loginError(err) : errorText(err)); + } finally { + setBusy(false); + } + } + + if (sent) { + return ( +
+

+ {sent === "register" + ? "Küldtünk egy levelet a(z) " + : "Ha ehhez a címhez tartozik fiók, küldtünk egy levelet a(z) "} + {email} címre. A benne lévő linkkel adhatod meg a jelszavad + {sent === "register" ? ", és utána már be is vagy lépve." : "."} +

+

+ Nem jött meg pár percen belül? Nézd meg a spam mappát is, vagy{" "} + + . +

+
+ ); + } + + return ( +
+ {mode === "register" && ( +
+ + setName(e.target.value)} + /> +
+ )} +
+ + setEmail(e.target.value)} + placeholder="nev@pelda.hu" + /> +
+ {mode === "login" && ( +
+
+ + +
+ setPassword(e.target.value)} + /> +
+ )} + {mode === "register" && ( +

+ A jelszavadat a levélben kapott linken adod meg. Így biztos, hogy a cím a tiéd. +

+ )} + {mode === "forgot" && ( +

+ Küldünk egy linket, amellyel új jelszót adhatsz meg. Ha eddig Google- vagy Apple-fiókkal léptél be, így + jelszót is beállíthatsz. +

+ )} + + {error && ( +

+ {error} +

+ )} + {uninvited && ( + <> +

+ {inviteToken + ? "Ez a meghívó már nem érvényes, és ehhez a címhez sem tartozik másik." + : "A Sorsfonalak jelenleg meghívásos, és ehhez az e-mail-címhez nem tartozik meghívó. Ha kaptál meghívót, nyisd meg a levélben kapott linket."} +

+ + + )} +

+ {mode === "login" ? ( + <> + Még nincs fiókod?{" "} + + + ) : ( + + )} +

+ + ); +} diff --git a/services/frontend/src/app/belepes/page.tsx b/services/frontend/src/app/belepes/page.tsx index 2108d0f..93650e2 100644 --- a/services/frontend/src/app/belepes/page.tsx +++ b/services/frontend/src/app/belepes/page.tsx @@ -10,6 +10,7 @@ import type { InvitationLanding, PublicConfig } from "@/lib/types"; import { AppleLogin } from "./AppleLogin"; import { GoogleLogin } from "./GoogleLogin"; +import { PasswordLogin } from "./PasswordLogin"; export const metadata: Metadata = { title: "Belépés" }; @@ -48,7 +49,15 @@ const CLOSED: Record = { }; /** The invitation the visitor came with: who sent it and what they wrote. */ -function InvitationCard({ invitation, apple }: { invitation: InvitationLanding | null; apple: boolean }) { +function InvitationCard({ + invitation, + apple, + password, +}: { + invitation: InvitationLanding | null; + apple: boolean; + password: boolean; +}) { if (!invitation) { return (

@@ -71,7 +80,9 @@ function InvitationCard({ invitation, apple }: { invitation: InvitationLanding |

{invitation.message &&
{invitation.message}
}

- Bármelyik {apple ? "Google- vagy Apple-fiókoddal" : "Google-fiókoddal"} elfogadhatod. Érvényes: {formatDate(invitation.expires_at).replace(/\.$/, "")}-ig. + Bármelyik {apple ? "Google- vagy Apple-fiókoddal" : "Google-fiókoddal"} + {password ? ", vagy e-mail-címmel regisztrálva" : ""} elfogadhatod. Érvényes:{" "} + {formatDate(invitation.expires_at).replace(/\.$/, "")}-ig.

); @@ -90,7 +101,13 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis const clientId = config?.google_login.enabled ? config.google_login.client_id : null; const appleId = config?.apple_login?.enabled ? config.apple_login.client_id : null; const pendingInvite = invitation?.status === "pending" ? inviteToken : null; + // The shared link that brought the visitor (from its login button), for the sharer's reward. + const rawRef = Array.isArray(params.ref) ? params.ref[0] : params.ref; + const referral = rawRef && /^[A-Za-z0-9_-]{4,64}$/.test(rawRef) ? rawRef : null; const inviteOnly = config?.signup_mode === "invite"; + const password = config?.password_login === true; + const mod = Array.isArray(params.mod) ? params.mod[0] : params.mod; + const initialMode = mod === "elfelejtett" ? "forgot" : mod === "regisztracio" || rawToken ? "register" : "login"; return (
@@ -114,16 +131,32 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis

{rawToken ? "Meghívó" : "Belépés"}

{rawToken ? "Lépj be, és már kezdheted is." : "Üdv újra! Lépj be a fiókodba."}

- {rawToken && } + {rawToken && ( + + )} {config === null ? (

A szerver most nem érhető el. Próbáld újra egy kicsit később.

- ) : clientId ? ( -
- - {appleId && } -
+ ) : clientId || password ? ( + <> + {clientId && ( +
+ + {appleId && ( + + )} +
+ )} + {clientId && password && ( +
+ vagy +
+ )} + {password && ( + + )} + ) : (

A Google-belépés még nincs beállítva (a backend GOOGLE_CLIENT_IDS változója üres). @@ -134,7 +167,9 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis ? "A fiókod az első belépéskor jön létre." : inviteOnly ? "Az oldal jelenleg meghívásos: új fiók csak meghívóval jön létre." - : "Még nincs fiókod? Az első belépéskor létrejön."} + : password + ? "Google- vagy Apple-fiókkal az első belépéskor létrejön a fiókod." + : "Még nincs fiókod? Az első belépéskor létrejön."}

A belépéssel elfogadod az általános szerződési feltételeket, és hogy a születési diff --git a/services/frontend/src/app/csillagjegyek/[jegy]/page.tsx b/services/frontend/src/app/csillagjegyek/[jegy]/page.tsx new file mode 100644 index 0000000..9de7e2a --- /dev/null +++ b/services/frontend/src/app/csillagjegyek/[jegy]/page.tsx @@ -0,0 +1,159 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; + +import { JsonLd, PublicFooter } from "@/components/PublicFooter"; +import { PublicHeader } from "@/components/SiteHeader"; +import { ZODIAC, ZODIAC_BY_SLUG } from "@/content/zodiac"; +import { SIGNS } from "@/lib/astro"; +import { getMe } from "@/lib/server"; +import { siteUrl } from "@/lib/share"; + +export const dynamicParams = false; + +export function generateStaticParams() { + return ZODIAC.map((z) => ({ jegy: z.slug })); +} + +export async function generateMetadata({ params }: { params: Promise<{ jegy: string }> }): Promise { + const z = ZODIAC_BY_SLUG.get((await params).jegy); + if (!z) return {}; + return { + title: `${z.name} csillagjegy: ${z.name} Nap, Hold és aszcendens`, + description: `${z.name} (${z.dates}): milyen ${z.article} napjegyként, holdjegyként és aszcendensként, párkapcsolatban és munkában, és mi nem igaz róla.`, + alternates: { canonical: `/csillagjegyek/${z.slug}` }, + }; +} + +/** One sign: its facts, and what it means as Sun, Moon and Ascendant. */ +export default async function SignPage({ params }: { params: Promise<{ jegy: string }> }) { + const z = ZODIAC_BY_SLUG.get((await params).jegy); + if (!z) notFound(); + const me = await getMe(); + const base = await siteUrl(); + const index = ZODIAC.indexOf(z); + const prev = ZODIAC[(index + 11) % 12]; + const next = ZODIAC[(index + 1) % 12]; + const opposite = ZODIAC_BY_SLUG.get(z.opposite)!; + const glyph = SIGNS[z.id]?.glyph; + + return ( + <> + {!me && } +

+ +
+ +
+

{z.name}

+

{z.dates}

+
+
+ + + + + + + + + + + + + + + + +
Elem{z.element}Minőség{z.modality}
Uralkodó bolygó{z.ruler}Ellentétes jegy + {opposite.name} +
+ +

{z.intro}

+

+ A dátumok évről évre egy napot csúszhatnak. Ha a határ közelében születtél, az{" "} + ingyenes születési horoszkóp pontosan megmondja, melyik jegy a tiéd. +

+ +
+

{z.name} napjegy

+

{z.sun}

+
+
+

Hold {z.inSign}

+

{z.moon}

+
+
+

{z.name} aszcendens

+

{z.ascendant}

+
+
+

Párkapcsolatban

+

{z.love}

+
+
+

Munkában

+

{z.work}

+
+
+

Amit rosszul tudnak róla

+

{z.myth}

+
+ +
+
+

Erősségek

+

{z.strengths}

+
+
+

Árnyoldalak

+

{z.challenges}

+
+
+ + + + +
+ + + + ); +} diff --git a/services/frontend/src/app/csillagjegyek/page.tsx b/services/frontend/src/app/csillagjegyek/page.tsx new file mode 100644 index 0000000..18cbaf6 --- /dev/null +++ b/services/frontend/src/app/csillagjegyek/page.tsx @@ -0,0 +1,63 @@ +import type { Metadata } from "next"; +import Link from "next/link"; + +import { PublicFooter } from "@/components/PublicFooter"; +import { PublicHeader } from "@/components/SiteHeader"; +import { ZODIAC } from "@/content/zodiac"; +import { SIGNS } from "@/lib/astro"; +import { getMe } from "@/lib/server"; + +export const metadata: Metadata = { + title: "Csillagjegyek: mind a 12 jegy napjegyként, holdjegyként és aszcendensként", + description: + "A tizenkét csillagjegy dátumokkal, elemekkel és uralkodó bolygókkal: milyen egy jegy napjegyként, holdjegyként és aszcendensként.", + alternates: { canonical: "/csillagjegyek" }, +}; + +/** The twelve signs. */ +export default async function SignsPage() { + const me = await getMe(); + return ( + <> + {!me && } +
+
+ Csillagjegyek +

A tizenkét csillagjegy

+

+ A „milyen jegy vagy?” kérdésre a legtöbben a napjegyükkel felelnek. Pedig a Hold és az aszcendens jegye + legalább ennyit elárul. Minden jegynél leírjuk, milyen napjegyként, holdjegyként és aszcendensként. +

+
+
    + {ZODIAC.map((z) => ( +
  • + + + {z.name} + {z.dates} + + {z.element} · {z.modality} + + +
  • + ))} +
+
+

+ Nem tudod, melyik jegyben áll a Holdad, vagy mi az aszcendensed? Az ingyenes születési horoszkóp a születési + adataidból kiszámolja, belépés nélkül. +

+
+ + Ingyenes születési horoszkóp + +
+
+
+ + + ); +} diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css index 966cb57..e93726b 100644 --- a/services/frontend/src/app/globals.css +++ b/services/frontend/src/app/globals.css @@ -26,6 +26,10 @@ * { box-sizing: border-box; } html, body { margin: 0; } +/* The night sky behind everything (components/NightSky.tsx): drawn over the + page background, under all content, so anything with its own background + covers it. */ +.night-sky { position: fixed; inset: 0; width: 100%; height: 100%; z-index: -1; pointer-events: none; } body { min-height: 100vh; overflow-x: clip; /* nothing may push the page sideways on a phone */ @@ -198,6 +202,18 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; } .tagline { font-family: var(--font-display); font-size: 38px; font-weight: 600; line-height: 1.1; } .auth-foot { font-size: 15px; color: var(--muted); text-align: center; } +/* E-mail and password next to the social buttons */ +.auth-or { display: flex; align-items: center; gap: 14px; color: var(--muted); font-size: 13px; margin: -6px 0; } +.auth-or::before, .auth-or::after { content: ""; flex: 1; border-top: 1px solid var(--line); } +.pw-label-row { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; } +.pw-switch { text-align: center; } +.link-btn { + background: none; border: 0; padding: 0; font: inherit; color: var(--gold); cursor: pointer; + text-decoration: underline; text-underline-offset: 2px; +} +.link-btn:hover { color: var(--gold-hover); } +.pw-label-row .link-btn { font-size: 13px; text-decoration: none; } + /* Social login buttons; Google's own button lies invisibly on top (.gsi-overlay). */ .social-login { position: relative; } .btn-social { @@ -808,6 +824,17 @@ a.pair-row:hover strong { color: var(--gold); } .lp-wrap { max-width: 1180px; margin: 0 auto; padding: 0 24px; } .lp-header { gap: 16px; } .lp-nav { flex: 1; } +/* The free tools in the visitors' header, set apart from the paid sections. */ +.lp-free { display: flex; align-items: center; gap: 2px; padding-left: 14px; border-left: 1px solid var(--line-2); } +.lp-free-label { + font-size: 11px; font-weight: 600; letter-spacing: 1px; text-transform: uppercase; color: var(--gold); + border: 1px solid rgba(217, 180, 106, 0.45); border-radius: 999px; padding: 2px 8px; margin-right: 6px; white-space: nowrap; +} +.lp-free a { + color: var(--ink); text-decoration: none; padding: 10px 10px; border-radius: 8px; min-height: 44px; + display: inline-flex; align-items: center; white-space: nowrap; +} +.lp-free a:hover, .lp-free a[aria-current="page"] { color: var(--gold); background: rgba(217, 180, 106, 0.08); } .lp-hero { position: relative; overflow: hidden; } .lp-stars { position: absolute; inset: 0; width: 100%; height: 100%; } .lp-star { fill: var(--ink); opacity: 0.25; animation: lp-twinkle 6s ease-in-out infinite; } @@ -945,6 +972,10 @@ a.pair-row:hover strong { color: var(--gold); } .lp-pair { grid-template-columns: minmax(0, 1fr); justify-items: center; } .lp-rings { max-width: 200px; } .lp-nav { display: none; } + /* On phones the free tools get their own row under the logo. */ + .lp-header { flex-wrap: wrap; row-gap: 4px; } + .lp-free { order: 3; flex-basis: 100%; padding-left: 0; border-left: 0; overflow-x: auto; scrollbar-width: none; } + .lp-header > .btn { margin-left: auto; } } @media (prefers-reduced-motion: reduce) { .lp *, .lp-orbit { animation: none !important; } @@ -1114,3 +1145,66 @@ span.tarot-fan-card { cursor: default; } .birth-day { width: 5.2em; flex: none; } .birth-time { width: 4.4em; flex: none; text-align: center; } .birth-colon { color: var(--muted); font-weight: 600; } + +/* Public sign calculator (/aszcendens-kalkulator) */ +.calc-form { margin-bottom: 8px; } +.calc-result { display: flex; flex-direction: column; gap: 16px; margin: 24px 0 8px; scroll-margin-top: 84px; } +.calc-signs { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(220px, 100%), 1fr)); gap: 16px; } +.calc-sign { display: flex; flex-direction: column; gap: 10px; } +.calc-sign-main { display: flex; align-items: baseline; gap: 10px; } +.calc-sign-main strong { font-family: var(--font-display); font-size: 30px; font-weight: 600; } +.calc-glyph { font-size: 30px; color: var(--gold); line-height: 1; } +.calc-sign-link { font-size: 14px; margin-top: auto; } +.calc-cta { display: flex; flex-direction: row; gap: 20px; align-items: center; justify-content: space-between; flex-wrap: wrap; } +.calc-cta > div { flex: 1 1 320px; } +.calc-explain, .calc-faq { margin-top: 48px; display: flex; flex-direction: column; gap: 14px; } +.calc-explain-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(220px, 100%), 1fr)); gap: 20px; } +.calc-explain h3 { font-size: 18px; margin: 0 0 6px; } +.calc-explain p { margin: 0; color: var(--ink-2); line-height: 1.6; } +.calc-faq-item { padding: 16px 20px; } +.calc-faq-item summary { cursor: pointer; font-weight: 600; } +.calc-faq-item p { margin: 10px 0 0; color: var(--ink-2); line-height: 1.6; } + +/* Sign pages (/csillagjegyek) */ +.sign-grid { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(min(220px, 100%), 1fr)); gap: 16px; } +.sign-tile { display: flex; flex-direction: column; gap: 6px; text-decoration: none; color: var(--ink); height: 100%; } +.sign-tile:hover { border-color: #5a6790; color: var(--ink); } +.sign-tile strong { font-family: var(--font-display); font-size: 26px; font-weight: 600; } +.sign-tile-glyph { font-size: 28px; color: var(--gold); line-height: 1; } +.sign-crumbs { margin-bottom: 8px; } +.sign-crumbs a { color: var(--muted); } +.sign-head { flex-direction: row; align-items: center; gap: 20px; } +.sign-glyph { font-size: 64px; color: var(--gold); line-height: 1; } +.sign-facts { width: 100%; border-collapse: collapse; margin: 8px 0 24px; font-size: 15px; } +.sign-facts th, .sign-facts td { padding: 10px 12px; border-bottom: 1px solid var(--line); text-align: left; } +.sign-facts th { color: var(--muted); font-weight: 500; white-space: nowrap; } +.sign-intro { font-size: 18px; line-height: 1.65; } +.sign-section { margin-top: 32px; scroll-margin-top: 16px; } +.sign-section h2, .sign-traits h2 { font-size: 26px; margin: 0 0 10px; } +.sign-section p, .sign-traits p { line-height: 1.7; color: var(--ink-2); margin: 0; } +.sign-myth { border-left: 3px solid var(--gold); padding-left: 18px; } +.sign-traits { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(260px, 100%), 1fr)); gap: 24px; margin-top: 32px; } +.sign-cta { margin-top: 36px; display: flex; flex-direction: column; gap: 14px; } +.sign-pager { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-top: 32px; font-size: 15px; } +@media (max-width: 640px) { + .sign-facts th, .sign-facts td { display: block; padding: 4px 0; border: 0; } + .sign-facts td { padding-bottom: 10px; border-bottom: 1px solid var(--line); } + .sign-glyph { font-size: 48px; } +} + +/* The free tools on the home page, set apart from the paid sections */ +.lp-free-line { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin: 0; font-size: 15px; } +.lp-free-line .lp-free-label { margin-right: 0; } +.lp-free-band { border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); background: var(--panel); padding: 36px 0; } +.lp-free-head { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 18px; } +.lp-free-title { margin: 0; font-family: var(--font-display); font-size: 30px; font-weight: 600; } +.lp-free-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(300px, 100%), 1fr)); gap: 16px; } +.lp-free-card { display: flex; flex-direction: column; gap: 8px; text-decoration: none; color: var(--ink); border-color: rgba(217, 180, 106, 0.35); } +.lp-free-card:hover { border-color: var(--gold); color: var(--ink); } +.lp-free-card strong { font-family: var(--font-display); font-size: 24px; font-weight: 600; } +.lp-free-go { color: var(--gold); font-weight: 500; margin-top: auto; } +.calc-result-head { margin-top: 32px; } +.calc-links ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; } +.calc-links li { font-size: 15px; } +.calc-save { display: flex; flex-direction: column; gap: 10px; } +.calc-save .btn { align-self: flex-start; } diff --git a/services/frontend/src/app/jelszo/SetPasswordForm.tsx b/services/frontend/src/app/jelszo/SetPasswordForm.tsx new file mode 100644 index 0000000..7679492 --- /dev/null +++ b/services/frontend/src/app/jelszo/SetPasswordForm.tsx @@ -0,0 +1,92 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; + +import { ApiError, api, errorText } from "@/lib/api"; + +/** Sets the password with the e-mailed link's token; logs in on success. */ +export function SetPasswordForm({ token, minLength }: { token: string; minLength: number }) { + const router = useRouter(); + const [password, setPassword] = useState(""); + const [again, setAgain] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [expired, setExpired] = useState(false); + + async function submit(e: React.FormEvent) { + e.preventDefault(); + setError(null); + if (password.length < minLength) { + setError(`A jelszó legalább ${minLength} karakter legyen.`); + return; + } + if (password !== again) { + setError("A két jelszó nem egyezik."); + return; + } + setBusy(true); + try { + await api("/auth/set-password", { body: { token, password } }); + router.replace("/"); + router.refresh(); + } catch (err) { + if (err instanceof ApiError && err.code === "invalid_token") setExpired(true); + else setError(errorText(err)); + setBusy(false); + } + } + + if (expired) { + return ( +
+

+ Ez a link lejárt, vagy már felhasználták. +

+

+ A belépésnél az „Elfelejtett jelszó?” linkkel kérhetsz újat. +

+
+ ); + } + + return ( +
+
+ + setPassword(e.target.value)} + /> + Legalább {minLength} karakter. +
+
+ + setAgain(e.target.value)} + /> +
+ + {error && ( +

+ {error} +

+ )} +
+ ); +} diff --git a/services/frontend/src/app/jelszo/page.tsx b/services/frontend/src/app/jelszo/page.tsx new file mode 100644 index 0000000..89d737e --- /dev/null +++ b/services/frontend/src/app/jelszo/page.tsx @@ -0,0 +1,53 @@ +import type { Metadata } from "next"; +import Link from "next/link"; + +import { Logo } from "@/components/SiteHeader"; +import { BACKEND_URL } from "@/lib/server"; +import type { PublicConfig } from "@/lib/types"; + +import { SetPasswordForm } from "./SetPasswordForm"; + +export const metadata: Metadata = { title: "Jelszó megadása", robots: { index: false } }; + +async function minLength(): Promise { + try { + const res = await fetch(`${BACKEND_URL}/v1/config`, { cache: "no-store" }); + if (res.ok) return ((await res.json()) as PublicConfig).password_min_length; + } catch { + // backend down: the form still works, the backend checks the length + } + return 10; +} + +/** The page of the e-mailed password link (sign-up and forgotten password). */ +export default async function SetPasswordPage({ + searchParams, +}: { + searchParams: Promise>; +}) { + const params = await searchParams; + const raw = Array.isArray(params.token) ? params.token[0] : params.token; + const token = raw && /^[A-Za-z0-9_-]{8,200}$/.test(raw) ? raw : null; + + return ( +
+
+
+ +
+

Jelszó megadása

+

Add meg a jelszavad, amellyel ezentúl belépsz.

+
+ {token ? ( + + ) : ( +

+ Hiányos a link. Nyisd meg a teljes linket a levélből, vagy kérj újat a{" "} + belépésnél. +

+ )} +
+
+
+ ); +} diff --git a/services/frontend/src/app/layout.tsx b/services/frontend/src/app/layout.tsx index c452c83..6e15466 100644 --- a/services/frontend/src/app/layout.tsx +++ b/services/frontend/src/app/layout.tsx @@ -2,9 +2,11 @@ import type { Metadata } from "next"; import { Cormorant_Garamond, Inter } from "next/font/google"; import { Suspense } from "react"; +import { NightSky } from "@/components/NightSky"; import { PaymentReturn } from "@/components/PaymentReturn"; import { SiteHeader } from "@/components/SiteHeader"; import { getMe } from "@/lib/server"; +import { siteUrl } from "@/lib/share"; import "./globals.css"; @@ -15,16 +17,21 @@ const cormorant = Cormorant_Garamond({ }); const inter = Inter({ subsets: ["latin", "latin-ext"], variable: "--font-inter" }); -export const metadata: Metadata = { - title: { default: "Sorsfonalak", template: "%s · Sorsfonalak" }, - description: "Születési képlet, szinasztria és közösség – egy helyen.", -}; +export async function generateMetadata(): Promise { + return { + // Relative canonical and alternate addresses resolve against the site's address. + metadataBase: new URL(await siteUrl()), + title: { default: "Sorsfonalak", template: "%s · Sorsfonalak" }, + description: "Születési képlet, szinasztria és közösség – egy helyen.", + }; +} export default async function RootLayout({ children }: { children: React.ReactNode }) { const me = await getMe(); return ( + {me && } {children} {me && ( diff --git a/services/frontend/src/app/page.tsx b/services/frontend/src/app/page.tsx index 5b1e5fe..62c77b3 100644 --- a/services/frontend/src/app/page.tsx +++ b/services/frontend/src/app/page.tsx @@ -1,6 +1,8 @@ import type { Metadata } from "next"; import { redirect } from "next/navigation"; +import { JsonLd } from "@/components/PublicFooter"; +import { OPERATOR } from "@/lib/legal"; import { BACKEND_URL, getMe } from "@/lib/server"; import { siteUrl } from "@/lib/share"; import type { PublicConfig } from "@/lib/types"; @@ -44,5 +46,33 @@ async function signupMode(): Promise { export default async function Home() { const me = await getMe(); if (me) redirect(me.primary_chart_id ? "/keplet" : "/profil"); - return ; + const base = await siteUrl(); + return ( + <> + + + + ); } diff --git a/services/frontend/src/app/privacy/page.tsx b/services/frontend/src/app/privacy/page.tsx index 3f1a415..91ed8e5 100644 --- a/services/frontend/src/app/privacy/page.tsx +++ b/services/frontend/src/app/privacy/page.tsx @@ -1,13 +1,15 @@ import type { Metadata } from "next"; import Link from "next/link"; +import { OperatorDetails } from "@/components/OperatorDetails"; import { PublicHeader } from "@/components/SiteHeader"; -import { OPERATOR, PRIVACY_UPDATED_EN, operatorDetails } from "@/lib/legal"; +import { OPERATOR, PRIVACY_UPDATED_EN } from "@/lib/legal"; import { getMe } from "@/lib/server"; export const metadata: Metadata = { title: "Privacy Policy", description: "How Sorsfonalak handles your personal data, including the data received from your Google account.", + alternates: { canonical: "/privacy", languages: { hu: "/adatvedelem", en: "/privacy" } }, }; const DATA: [string, string, string][] = [ @@ -16,6 +18,11 @@ const DATA: [string, string, string][] = [ "Creating your account, signing you in, contacting you", "Performance of a contract (GDPR Art. 6(1)(b))", ], + [ + "Your e-mail address and password, if you sign up with your e-mail address (we never store the password, only a salted one-way hash of it)", + "Signing in; the link sent to the address confirms that it is yours and lets you set a new password", + "Performance of a contract", + ], ["Display name, the language of your readings", "Personalising the service", "Performance of a contract"], [ "Your birth data: date, time and place", @@ -27,7 +34,11 @@ const DATA: [string, string, string][] = [ "Their charts and readings, at your request", "Performance of a contract; adding someone requires their consent (see section 5)", ], - ["Your charts and finished readings", "So you can look at them again at any time", "Performance of a contract"], + [ + "Your charts, finished readings and tarot readings, the questions you asked and their answers", + "So you can look at them again at any time", + "Performance of a contract", + ], [ "Your purchases and used allowances (readings, persons)", "Providing the purchased service, accounting", @@ -38,6 +49,11 @@ const DATA: [string, string, string][] = [ "Proof of payment, issuing the invoice", "Performance of a contract; legal obligation (Art. 6(1)(c))", ], + [ + "Your shared links: the link's code, its view count and a salted hash of the IP address you created it from; if someone signs up from your link, who brought them", + "Making sharing work and the reward for sharing; not counting your own views", + "Performance of a contract; legitimate interest (Art. 6(1)(f))", + ], [ "An invitee's e-mail address, the inviter's name and personal message", "Sending the invitation; while the site is invitation-only, only invitees can sign up", @@ -80,14 +96,8 @@ export default async function PrivacyPolicyPage() {

1. Who is responsible for your data?

- {operatorDetails() ? ( - <> - The controller of the Sorsfonalak service (sorsfonalak.hu) is {operatorDetails()}.{" "} - - ) : ( - "The controller of the Sorsfonalak service (sorsfonalak.hu) can be reached by e-mail. " - )} - For any privacy or other question, contact us at{" "} + The details of the controller of the Sorsfonalak service (sorsfonalak.hu) are at the end of this policy, in + section 12. For any privacy or other question, contact us at{" "} {OPERATOR.email} @@ -123,6 +133,11 @@ export default async function PrivacyPolicyPage() { the payment's ID, the amount and your billing details, which we keep for the period required by accounting law (8 years), even after your account is deleted.

+

+ Shared links: if you share a chart, anyone you send the link to sees the chart drawing and + the latest short summary. It shows no name or birth data, search engines do not list it, and you can revoke + the link at any time. +

@@ -180,10 +195,13 @@ export default async function PrivacyPolicyPage() {

4. Readings and artificial intelligence

- The short summary and the detailed reading are written by a large language model (artificial intelligence). - Only the astronomical data of the chart reach the model (the signs, degrees, houses and - aspects of the planets). We never send your name, e-mail address, birth date, time or place. The readings are - for entertainment and self-reflection and are not medical, financial, legal or other professional advice. + The short summary, the detailed readings, tarot readings and the answers to your questions are written by a + large language model (artificial intelligence). The model receives the{" "} + astronomical data of the chart (the signs, degrees, houses and aspects of the planets), for + a tarot reading the cards drawn, and when you ask a question, its text. We never send your name, e-mail + address, birth date, time or place. Please do not write names or sensitive data (such as health data) into + your questions either. The readings are for entertainment and self-reflection and are not medical, + financial, legal or other professional advice.

@@ -224,7 +242,7 @@ export default async function PrivacyPolicyPage() {
  • OpenRouter, Inc. and the artificial intelligence providers it reaches: writing the readings, - only from the astronomical data described in section 4 (no personal data reaches them). + only from the data described in section 4 (they receive no name, e-mail address or birth data).
  • @@ -254,6 +272,14 @@ export default async function PrivacyPolicyPage() { We use a single cookie that is strictly necessary for the service (sf_session), which keeps you signed in. We use no advertising or tracking cookies and no analytics.

    +

    + On the public birth chart page (no account needed), the birth data you enter are sent only for the + calculation and are not stored on our server. So that they are not lost when you move between pages, they + stay in the browser tab's own storage (not in a cookie) and are removed when you close the tab; the + page's “Adatok törlése” (delete data) button removes them earlier. If you sign up in the same tab, they + fill in the birth data on your profile. This storage only keeps what you typed, so it needs no separate + consent. +

    @@ -296,6 +322,11 @@ export default async function PrivacyPolicyPage() { always on this page.

    + +
    +

    12. Controller details

    + +
    ); diff --git a/services/frontend/src/app/profil/BirthForm.tsx b/services/frontend/src/app/profil/BirthForm.tsx index 775e668..d70f936 100644 --- a/services/frontend/src/app/profil/BirthForm.tsx +++ b/services/frontend/src/app/profil/BirthForm.tsx @@ -4,6 +4,7 @@ import { useEffect, useId, useMemo, useRef, useState } from "react"; import { ApiError, api, errorText } from "@/lib/api"; import { countryName } from "@/lib/astro"; +import { BIRTH_DRAFT_KEY, type BirthDraft, MONTHS, composeDate, composeTime, daysIn } from "@/lib/birth"; import type { BirthData, Country, Place } from "@/lib/types"; type Initial = (BirthData & { placeName: string | null; region: string | null }) | null; @@ -16,41 +17,6 @@ const ERRORS: Record = { invalid_date: "Érvénytelen dátum.", }; -const MONTHS = [ - "január", - "február", - "március", - "április", - "május", - "június", - "július", - "augusztus", - "szeptember", - "október", - "november", - "december", -]; - -const pad = (n: number) => String(n).padStart(2, "0"); -const daysIn = (year: number, month: number) => new Date(Date.UTC(year || 2000, month, 0)).getUTCDate(); - -/** "YYYY-MM-DD" from the three fields, or null while it is not a real date. */ -function composeDate(year: string, month: string, day: string): string | null { - const y = Number(year); - const m = Number(month); - const d = Number(day); - if (!/^\d{4}$/.test(year) || y < 1000 || !m || !d || d > daysIn(y, m)) return null; - return `${year}-${pad(m)}-${pad(d)}`; -} - -/** "HH:MM" from the two fields, or null while it is not a real time. */ -function composeTime(hour: string, minute: string): string | null { - if (!/^\d{1,2}$/.test(hour) || !/^\d{1,2}$/.test(minute)) return null; - const h = Number(hour); - const m = Number(minute); - return h <= 23 && m <= 59 ? `${pad(h)}:${pad(m)}` : null; -} - /** Someone else's chart: added with a name, or (with `chartId`) corrected. */ export type PersonTarget = { chartId?: string; name?: string }; @@ -95,6 +61,37 @@ export function BirthForm({ const [error, setError] = useState(null); const [busy, setBusy] = useState(false); const today = useMemo(() => new Date().toISOString().slice(0, 10), []); + const [fromDraft, setFromDraft] = useState(false); + + // The own birth data, not given yet: offer what the visitor typed into the + // public birth chart page before signing up. + useEffect(() => { + if (initial || person) return; + let draft: BirthDraft | null = null; + try { + draft = JSON.parse(sessionStorage.getItem(BIRTH_DRAFT_KEY) ?? "null"); + } catch { + return; + } + if (!draft || !/^\d{4}-\d{2}-\d{2}$/.test(draft.date) || !draft.geonames_id) return; + setYear(draft.date.slice(0, 4)); + setMonth(String(Number(draft.date.slice(5, 7)))); + setDay(String(Number(draft.date.slice(8, 10)))); + if (draft.time) { + setHour(draft.time.slice(0, 2)); + setMinute(draft.time.slice(3, 5)); + } + setTimeUnknown(!draft.time); + setCountry(draft.country); + setPlace({ + geonames_id: draft.geonames_id, + name: draft.placeName, + region: draft.region, + population: null, + country_code: draft.country, + }); + setFromDraft(true); + }, [initial, person]); async function submit(e: React.FormEvent) { e.preventDefault(); @@ -134,6 +131,11 @@ export function BirthForm({ ? { label: name.trim(), is_primary: false, birth } : { label: "Saját képlet", is_primary: true, birth }, }); + try { + sessionStorage.removeItem(BIRTH_DRAFT_KEY); + } catch { + // storage blocked + } onSaved(saved.id); } catch (err) { if (err instanceof ApiError && err.code === "ambiguous_local_time") { @@ -151,6 +153,11 @@ export function BirthForm({ return (
    + {fromDraft && ( +

    + Áthoztuk az adatokat, amelyeket a születési horoszkópnál megadtál. Ellenőrizd, és mentsd el. +

    + )} {person && (
    @@ -314,10 +321,21 @@ export function BirthForm({ ); } -export function CountrySelect({ value, onChange }: { value: string; onChange: (iso2: string) => void }) { +/** Where the country list and the place search come from: logged-in users, or the public calculator. */ +export type GeoBase = "/api/geo" | "/api/v1/public/geo"; + +export function CountrySelect({ + value, + onChange, + geoBase = "/api/geo", +}: { + value: string; + onChange: (iso2: string) => void; + geoBase?: GeoBase; +}) { const [countries, setCountries] = useState([]); useEffect(() => { - fetch("/api/geo/countries") + fetch(`${geoBase}/countries`) .then((r) => (r.ok ? r.json() : { countries: [] })) .then((d: { countries: Country[] }) => { const named = d.countries.map((c) => ({ iso2: c.iso2, name: countryName(c.iso2, c.name) })); @@ -325,7 +343,7 @@ export function CountrySelect({ value, onChange }: { value: string; onChange: (i setCountries(named); }) .catch(() => setCountries([])); - }, []); + }, [geoBase]); return (
    @@ -345,10 +363,12 @@ export function PlaceSearch({ country, value, onChange, + geoBase = "/api/geo", }: { country: string; value: Place | null; onChange: (p: Place | null) => void; + geoBase?: GeoBase; }) { const listId = useId(); const [query, setQuery] = useState(value?.name ?? ""); @@ -367,6 +387,11 @@ export function PlaceSearch({ setResults([]); }, [country]); + // A place set from outside (e.g. brought over from the public chart page) shows its name. + useEffect(() => { + if (value) setQuery((q) => (q === value.name ? q : value.name)); + }, [value]); + useEffect(() => { const q = query.trim(); if (q.length < 2 || (value && value.name === query)) { @@ -377,7 +402,7 @@ export function PlaceSearch({ setLoading(true); const timer = setTimeout(async () => { try { - const res = await fetch(`/api/geo/places?country=${country}&q=${encodeURIComponent(q)}&limit=8`); + const res = await fetch(`${geoBase}/places?country=${country}&q=${encodeURIComponent(q)}&limit=8`); const data = res.ok ? ((await res.json()) as { places: Place[] }) : { places: [] }; if (id === seq.current) { setResults(data.places); @@ -391,7 +416,7 @@ export function PlaceSearch({ } }, 250); return () => clearTimeout(timer); - }, [query, country, value]); + }, [query, country, value, geoBase]); function choose(p: Place) { onChange(p); diff --git a/services/frontend/src/app/robots.ts b/services/frontend/src/app/robots.ts index c8348ac..17be8cc 100644 --- a/services/frontend/src/app/robots.ts +++ b/services/frontend/src/app/robots.ts @@ -2,27 +2,21 @@ import type { MetadataRoute } from "next"; import { siteUrl } from "@/lib/share"; -// AI crawlers that train models or answer from the site: they load pages -// far more often than visitors do. Link preview robots (Facebook, Messenger, -// Slack, WhatsApp, X, LinkedIn) stay allowed, they make the shared links work. -const AI_CRAWLERS = [ +// Crawlers that collect content to train AI models, or to sell it as +// training data. They bring no visitors back, so they are shut out. +// Google-Extended and Applebot-Extended only opt out of training: Google +// Search (AI Overviews included) and Siri keep reading the site. +const TRAINING_CRAWLERS = [ "GPTBot", - "ChatGPT-User", - "OAI-SearchBot", "ClaudeBot", - "Claude-User", - "Claude-SearchBot", "anthropic-ai", "CCBot", "Google-Extended", "GoogleOther", "Applebot-Extended", - "PerplexityBot", - "Perplexity-User", "Bytespider", "Amazonbot", "meta-externalagent", - "meta-externalfetcher", "FacebookBot", "cohere-ai", "cohere-training-data-crawler", @@ -30,23 +24,46 @@ const AI_CRAWLERS = [ "ImagesiftBot", "Omgilibot", "Omgili", - "YouBot", + "Webzio-Extended", "Timpibot", "AI2Bot", "Ai2Bot-Dolma", - "DuckAssistBot", - "MistralAI-User", + "PanguBot", + "Kangaroo Bot", + "img2dataset", + // Not training, but heavy and of no use here: Huawei's Petal search and + // Scrapy's default user agent. "PetalBot", "Scrapy", ]; +// AI search engines and the fetchers that read a page when someone asks a +// chatbot about it. These can cite the site and send visitors, so they may +// come, but at most one page every few seconds (for those that honour it). +const AI_SEARCH = [ + "OAI-SearchBot", + "ChatGPT-User", + "Claude-SearchBot", + "Claude-User", + "PerplexityBot", + "Perplexity-User", + "DuckAssistBot", + "MistralAI-User", + "meta-externalfetcher", + "YouBot", +]; + +// Logged-in pages redirect anyway; shared links carry noindex. +const PRIVATE = ["/api/", "/admin", "/profil", "/kepletek", "/osszevetesek", "/szemelyek", "/szamlak"]; + export default async function robots(): Promise { return { sitemap: `${await siteUrl()}/sitemap.xml`, rules: [ - { userAgent: AI_CRAWLERS, disallow: "/" }, - // Logged-in pages redirect anyway; shared links carry noindex. - { userAgent: "*", allow: "/", disallow: ["/api/", "/admin", "/profil", "/kepletek", "/osszevetesek", "/szemelyek", "/szamlak"] }, + { userAgent: TRAINING_CRAWLERS, disallow: "/" }, + // A crawler reads only its own group, so the private paths are repeated. + { userAgent: AI_SEARCH, allow: "/", disallow: PRIVATE, crawlDelay: 10 }, + { userAgent: "*", allow: "/", disallow: PRIVATE }, ], }; } diff --git a/services/frontend/src/app/s/[slug]/page.tsx b/services/frontend/src/app/s/[slug]/page.tsx index bb96947..3f6e626 100644 --- a/services/frontend/src/app/s/[slug]/page.tsx +++ b/services/frontend/src/app/s/[slug]/page.tsx @@ -92,7 +92,7 @@ export default async function SharedChartPage({ params }: Props) {

    Add meg a születési adataidat, és megkapod a saját képletedet a rövid összefoglalóval együtt, ingyen.

    - + {me ? "A saját képletem" : "Elkészítem a sajátomat"}
    diff --git a/services/frontend/src/app/sitemap.ts b/services/frontend/src/app/sitemap.ts index 352ef60..53a6aa0 100644 --- a/services/frontend/src/app/sitemap.ts +++ b/services/frontend/src/app/sitemap.ts @@ -1,5 +1,6 @@ import type { MetadataRoute } from "next"; +import { ZODIAC } from "@/content/zodiac"; import { siteUrl } from "@/lib/share"; /** The public pages for search engines; everything else needs a login. */ @@ -10,6 +11,9 @@ export default async function sitemap(): Promise { { url: `${base}/`, changeFrequency: "weekly", priority: 1 }, { url: `${base}/pelda`, changeFrequency: "monthly", priority: 0.8 }, { url: `${base}/kartyajoslas/pelda`, changeFrequency: "monthly", priority: 0.7 }, + { url: `${base}/szuletesi-horoszkop`, changeFrequency: "monthly", priority: 0.9 }, + { url: `${base}/csillagjegyek`, changeFrequency: "monthly", priority: 0.8 }, + ...ZODIAC.map((z) => ({ url: `${base}/csillagjegyek/${z.slug}`, changeFrequency: "monthly" as const, priority: 0.7 })), { url: `${base}/aszf`, changeFrequency: "yearly", priority: 0.2 }, { url: `${base}/adatvedelem`, changeFrequency: "yearly", priority: 0.2, alternates: privacy }, { url: `${base}/privacy`, changeFrequency: "yearly", priority: 0.2, alternates: privacy }, diff --git a/services/frontend/src/app/szuletesi-horoszkop/PublicChart.tsx b/services/frontend/src/app/szuletesi-horoszkop/PublicChart.tsx new file mode 100644 index 0000000..a612aa9 --- /dev/null +++ b/services/frontend/src/app/szuletesi-horoszkop/PublicChart.tsx @@ -0,0 +1,452 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useMemo, useRef, useState } from "react"; + +import { CountrySelect, PlaceSearch } from "@/app/profil/BirthForm"; +import { AspectGrid, AspectList, BigThree, PositionTables } from "@/components/ChartTables"; +import { ChartWheel, WheelLegend } from "@/components/ChartWheel"; +import { Tabs } from "@/components/Tabs"; +import { ZODIAC_BY_ID } from "@/content/zodiac"; +import { ApiError, api, errorText } from "@/lib/api"; +import { ASPECTS, countryName, formatBirthDate } from "@/lib/astro"; +import { BIRTH_DRAFT_KEY, MONTHS, type BirthDraft, composeDate, composeTime, daysIn } from "@/lib/birth"; +import type { BirthData, Chart, ChartResult, Place } from "@/lib/types"; + +interface Result { + highlights: Chart["highlights"]; + /** Without a birth time: the sign may have been the neighbouring one at the start or end of the day. */ + uncertain: { sun: boolean; moon: boolean }; + chart: ChartResult; +} + +const ERRORS: Record = { + place_not_found: "Nem találjuk ezt a települést. Válassz a listából.", + nonexistent_local_time: + "Ez az időpont az óraátállítás miatt nem létezett ezen a napon (az órát előreállították). Ellenőrizd a születési időt.", + invalid_date: "Érvénytelen dátum.", + too_many_requests: "Erről a címről most túl sok számítás érkezett. Próbáld újra egy óra múlva.", +}; + +const GRID_LEGEND = ["conjunction", "sextile", "square", "trine", "opposition"]; + +/** + * The calculated chart and the typed birth data, kept for this browser tab + * only (sessionStorage: not a cookie, gone when the tab is closed), so they + * are there again after visiting another page, and the profile can offer the + * birth data after signing up in the same tab. Storage that only keeps what + * the visitor typed, for the session, needs no consent. Nothing of this is + * stored on the server. + */ +const CHART_KEY = "sf_public_chart"; + +type Saved = { result: Result; birth: BirthData }; + +/** Links to the sign pages of the Sun, Moon and Ascendant. */ +function SignLinks({ result }: { result: Result }) { + const links: [string, string | null, string, boolean][] = [ + ["Napjegy", result.highlights.sun, "nap", result.uncertain.sun], + ["Holdjegy", result.highlights.moon, "hold", result.uncertain.moon], + ["Aszcendens", result.highlights.time_known ? result.highlights.ascendant : null, "aszcendens", false], + ]; + return ( +
    + Mit jelentenek? +
      + {links.map(([label, sign, anchor, uncertain]) => { + const z = sign ? ZODIAC_BY_ID.get(sign) : undefined; + return ( +
    • + {z ? ( + + {label}: {z.name} → + + ) : ( + {label}: pontos születési idő kell hozzá + )} + {uncertain && (a születési idő nélkül a szomszédos jegy is lehet)} +
    • + ); + })} +
    +
    + ); +} + +/** The calculated chart: the wheel and the tables of the chart pages, without the AI parts. */ +function ChartView({ result, birth }: { result: Result; birth: BirthData }) { + const r = result.chart; + const timeKnown = result.highlights.time_known; + const chart: Chart = { + id: "", + label: "Születési horoszkóp", + is_primary: false, + kind: "person", + editable_until: null, + birth_data: birth, + highlights: result.highlights, + chart: r, + created_at: "", + }; + const place = r.location.place; + const country = place?.country_code ?? birth.country; + return ( + <> +
    +

    A születési horoszkópod

    +

    + {formatBirthDate(birth.date)} + {timeKnown + ? `, ${r.time.local.slice(11, 16)} (UTC${r.time.utc_offset}${r.time.dst ? ", nyári idő" : ""})` + : ", ismeretlen időpont"} + {" · "} + {place?.name ?? "–"} + {country ? `, ${countryName(country)}` : ""} +

    +
    +
    +
    + + +
    +
    + + +
    + A rövid összefoglalóhoz lépj be +

    + A képletedhez ingyen írunk egy rövid, személyre szabott összefoglalót, ehhez azonban be kell jelentkezned. + Belépés után a képleted is megmarad: a most megadott születési adataidat áthozzuk. +

    + + Belépés és ingyenes összefoglaló + +
    +
    +
    +
    + }, + { + id: "matrix", + label: "Mátrix", + content: ( +
    + +
      + {GRID_LEGEND.map((k) => ( +
    • + {" "} + {ASPECTS[k]?.hu} +
    • + ))} +
    +
    + ), + }, + { id: "reszletek", label: "Fényszögek", content: }, + ]} + /> +
    + + ); +} + +/** The public birth chart: a calculation only, nothing is saved and no AI is used. */ +export function PublicChart() { + const [year, setYear] = useState(""); + const [month, setMonth] = useState(""); + const [day, setDay] = useState(""); + const [hour, setHour] = useState(""); + const [minute, setMinute] = useState(""); + const [timeUnknown, setTimeUnknown] = useState(false); + const [country, setCountry] = useState("HU"); + const [place, setPlace] = useState(null); + const [ambiguous, setAmbiguous] = useState(false); + const [ambiguity, setAmbiguity] = useState<"earlier" | "later">("earlier"); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [result, setResult] = useState(null); + const [stored, setStored] = useState(false); + /** After a calculation (smooth) or on coming back (at once): show the drawn chart. */ + const [reveal, setReveal] = useState(null); + const minuteRef = useRef(null); + const resultRef = useRef(null); + const today = useMemo(() => new Date().toISOString().slice(0, 10), []); + + // Back on the page: the birth data typed earlier and, in this tab, the chart. + useEffect(() => { + let draft: BirthDraft | null = null; + let saved: Saved | null = null; + try { + draft = JSON.parse(sessionStorage.getItem(BIRTH_DRAFT_KEY) ?? "null"); + saved = JSON.parse(sessionStorage.getItem(CHART_KEY) ?? "null"); + } catch { + return; + } + if (draft && /^\d{4}-\d{2}-\d{2}$/.test(draft.date) && draft.geonames_id) { + setYear(draft.date.slice(0, 4)); + setMonth(String(Number(draft.date.slice(5, 7)))); + setDay(String(Number(draft.date.slice(8, 10)))); + setHour(draft.time ? draft.time.slice(0, 2) : ""); + setMinute(draft.time ? draft.time.slice(3, 5) : ""); + setTimeUnknown(!draft.time); + setCountry(draft.country); + setPlace({ + geonames_id: draft.geonames_id, + name: draft.placeName, + region: draft.region, + population: null, + country_code: draft.country, + }); + setStored(true); + } + if (saved?.result?.chart && saved.birth?.date) { + setResult(saved); + setStored(true); + setReveal("instant"); + } + }, []); + + // Scrolls to the drawn chart, once it is on the page. An old tab in the + // address (#bolygok) would pull the page down to the tables instead. + useEffect(() => { + if (!reveal || !result) return; + if (window.location.hash) history.replaceState(null, "", window.location.pathname + window.location.search); + resultRef.current?.scrollIntoView({ behavior: reveal, block: "start" }); + setReveal(null); + }, [reveal, result]); + + /** Forgets the birth data and the chart in this browser. */ + function clear() { + try { + sessionStorage.removeItem(BIRTH_DRAFT_KEY); + sessionStorage.removeItem(CHART_KEY); + } catch { + // storage blocked + } + setYear(""); + setMonth(""); + setDay(""); + setHour(""); + setMinute(""); + setTimeUnknown(false); + setCountry("HU"); + setPlace(null); + setAmbiguous(false); + setResult(null); + setError(null); + setStored(false); + } + + async function submit(e: React.FormEvent) { + e.preventDefault(); + setError(null); + const date = composeDate(year, month, day); + const time = composeTime(hour, minute); + if (!date) return setError("Ellenőrizd a dátumot: az év négy számjegy, és a nap legyen az adott hónapban."); + if (date > today) return setError("A születési dátum nem lehet a jövőben."); + if (!timeUnknown && !time) + return setError("Add meg a születési időt (óra 0–23, perc 0–59), vagy jelöld, hogy nem tudod."); + if (!place) return setError("Válaszd ki a születési helyet a listából."); + setBusy(true); + try { + const birth = { + date, + ...(timeUnknown ? {} : { time }), + country, + geonames_id: place.geonames_id, + }; + const r = await api("/public/chart", { + body: { ...birth, ...(ambiguous ? { ambiguous_time: ambiguity } : {}) }, + }); + setResult({ result: r, birth }); + // Kept in this browser only: for coming back to the page, and for the profile after sign-up. + const draft: BirthDraft = { ...birth, time: birth.time ?? null, placeName: place.name, region: place.region }; + try { + sessionStorage.setItem(BIRTH_DRAFT_KEY, JSON.stringify(draft)); + sessionStorage.setItem(CHART_KEY, JSON.stringify({ result: r, birth })); + setStored(true); + } catch { + // storage blocked or full: the chart is still shown + } + setReveal("smooth"); + } catch (err) { + if (err instanceof ApiError && err.code === "ambiguous_local_time") { + setAmbiguous(true); + setError( + "Ez az időpont az óraátállítás miatt kétszer is előfordult ezen a napon. Válaszd ki, melyikben születtél.", + ); + } else { + setError(err instanceof ApiError ? (ERRORS[err.code] ?? errorText(err)) : errorText(err)); + } + } finally { + setBusy(false); + } + } + + return ( + <> + +
    +
    + Születési dátum +
    + + setYear(e.target.value.replace(/\D/g, ""))} + /> + + + + +
    +
    +
    + Születési idő (helyi idő) +
    + + { + const v = e.target.value.replace(/\D/g, ""); + setHour(v); + setAmbiguous(false); + if (v.length === 2 || (v.length === 1 && Number(v) > 2)) minuteRef.current?.focus(); + }} + /> + + + { + setMinute(e.target.value.replace(/\D/g, "")); + setAmbiguous(false); + }} + /> +
    + +
    +
    +
    + { + setCountry(c); + setPlace(null); + }} + /> + +
    + {ambiguous && ( +
    + + Melyik időpontban születtél? + + + +
    + )} + {error && ( +

    + {error} +

    + )} +
    + + {stored && ( + + )} +
    +

    + Ingyenes, belépés nélkül. Az adataidat a szerveren nem tároljuk: csak ebben a böngészőlapban maradnak meg, + hogy oldalváltáskor ne vesszenek el, és a lap bezárásakor törlődnek. +

    + + + {result && ( +
    + +
    + )} + + ); +} diff --git a/services/frontend/src/app/szuletesi-horoszkop/page.tsx b/services/frontend/src/app/szuletesi-horoszkop/page.tsx new file mode 100644 index 0000000..44ba459 --- /dev/null +++ b/services/frontend/src/app/szuletesi-horoszkop/page.tsx @@ -0,0 +1,110 @@ +import type { Metadata } from "next"; +import Link from "next/link"; + +import { JsonLd, PublicFooter } from "@/components/PublicFooter"; +import { PublicHeader } from "@/components/SiteHeader"; +import { getMe } from "@/lib/server"; +import { siteUrl } from "@/lib/share"; + +import { PublicChart } from "./PublicChart"; + +export const metadata: Metadata = { + title: "Ingyenes születési horoszkóp: képletrajz, aszcendens, holdjegy", + description: + "Készítsd el ingyen, belépés nélkül a születési horoszkópodat: képletrajz, aszcendens, holdjegy, a bolygók jegyekben és házakban, fényszögek.", + alternates: { canonical: "/szuletesi-horoszkop" }, +}; + +const FAQ: [string, string][] = [ + [ + "Mit mutat a születési horoszkóp?", + "A születési horoszkóp (más néven születési képlet vagy radix) az égbolt térképe a születésed pillanatában: hol állt a Nap, a Hold és a nyolc bolygó az állatövben, melyik házban, és milyen szöget zártak be egymással. A képletrajz és a táblázatok ezt mutatják.", + ], + [ + "Mi az aszcendens?", + "Az aszcendens az az állatövi jegy, amely a születésed pillanatában a keleti horizonton emelkedett. Azt mutatja, hogyan lépsz be egy új helyzetbe, milyen első benyomást keltesz, és milyen szemüvegen át nézed a világot. A házak rendszere is innen indul.", + ], + [ + "Miért kell hozzá a pontos születési idő?", + "A horizonton nagyjából két óránként vált a jegy, ezért az aszcendens és a házak pár perc alatt is eltolódhatnak. Születési idő nélkül a bolygók jegyei kiderülnek, de aszcendens és házak nincsenek. A pontos időt a születési anyakönyvi kivonaton vagy a kórházi zárójelentésen gyakran megtalálod.", + ], + [ + "Mi a holdjegy?", + "A holdjegy az a jegy, amelyben a Hold a születésedkor állt. Az érzelmi reakcióidról, a biztonságigényedről és arról szól, mi nyugtat meg. A Hold körülbelül két és fél naponta lép új jegybe, ezért a holdjegy sokszor születési idő nélkül is kiderül.", + ], + [ + "Miben más ez, mint a napilapok horoszkópja?", + "A napilapok csak a napjegyet nézik, ami egy hónapnyi születésnapra ugyanaz. A születési képlet ezzel szemben percre és helyre pontos: két ember, aki ugyanazon a napon született, más órában vagy más városban, egészen más képletet kap.", + ], +]; + +/** The public birth chart: no login, no AI, nothing saved. */ +export default async function BirthChartPage() { + const me = await getMe(); + const base = await siteUrl(); + return ( + <> + {!me && } +
    +
    + Ingyenes, belépés nélkül +

    Születési horoszkóp

    +

    + Add meg, mikor és hol születtél, és percre pontosan kiszámoljuk a képletedet: a képletrajzot, az aszcendenst + és a holdjegyet, a bolygókat a jegyekben és a házakban, és a köztük lévő fényszögeket. +

    +
    + + + +
    +

    Nap, Hold, aszcendens: a három legfontosabb pont

    +
    +
    +

    Napjegy

    +

    + Az alapvető jellemed, az, ami felé tartasz. Ezt kérdezik, amikor azt mondják: „Te milyen jegy vagy?” +

    +
    +
    +

    Holdjegy

    +

    Az érzelmeid és a megszokásaid. Az, ahogyan otthon, fáradtan, a szeretteid között vagy.

    +
    +
    +

    Aszcendens

    +

    Az első benyomás és a reflexeid. Sokan erre ismernek rá először, mert kívülről ez látszik.

    +
    +
    +

    + Ha a három különböző jegyben áll, az teljesen természetes: ezért érzed úgy, hogy a napilapok horoszkópja + csak részben illik rád. A jegyek részletes leírását a csillagjegyek{" "} + oldalán találod. +

    +
    + +
    +

    Gyakori kérdések

    + {FAQ.map(([q, a]) => ( +
    + {q} +

    {a}

    +
    + ))} +
    +
    + + ({ + "@type": "Question", + name: q, + acceptedAnswer: { "@type": "Answer", text: a }, + })), + }} + /> + + ); +} diff --git a/services/frontend/src/components/NightSky.tsx b/services/frontend/src/components/NightSky.tsx new file mode 100644 index 0000000..5b01019 --- /dev/null +++ b/services/frontend/src/components/NightSky.tsx @@ -0,0 +1,143 @@ +"use client"; + +import { useEffect, useRef } from "react"; + +/** The meteor's colour (warm gold, like the site's accent) and its head. */ +const TINT = [236, 205, 140]; +/** On average one meteor this often (seconds); each gap is 50–150% of it. */ +const EVERY = 6; + +/** + * The site's background: faint twinkling stars and, every few seconds, a + * shooting star. A fixed canvas behind all content, so anything with its own + * background (bands, cards, the header) covers it and the meteor passes + * under them. With "reduce motion" set, only still stars are drawn. + */ +export function NightSky() { + const ref = useRef(null); + + useEffect(() => { + const canvas = ref.current; + const ctx = canvas?.getContext("2d"); + if (!canvas || !ctx) return; + const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches; + + type Star = { x: number; y: number; r: number; base: number; phase: number; rate: number }; + type Meteor = { x: number; y: number; dx: number; dy: number; len: number; life: number; span: number; width: number }; + let w = 0; + let h = 0; + let stars: Star[] = []; + const meteors: Meteor[] = []; + + function resize() { + const dpr = Math.min(window.devicePixelRatio || 1, 2); + w = canvas!.clientWidth; + h = canvas!.clientHeight; + canvas!.width = Math.round(w * dpr); + canvas!.height = Math.round(h * dpr); + ctx!.setTransform(dpr, 0, 0, dpr, 0, 0); + // About one star per 9000 px². + stars = Array.from({ length: Math.round((w * h) / 9000) }, () => ({ + x: Math.random() * w, + y: Math.random() * h, + r: Math.random() < 0.85 ? 0.5 + Math.random() * 0.7 : 1.1 + Math.random() * 0.6, + base: 0.12 + Math.random() * 0.3, + phase: Math.random() * Math.PI * 2, + rate: 0.4 + Math.random() * 0.9, + })); + if (reduced) drawStars(0); + } + + /** Enters in the upper part of the screen and falls down and to the left at a shallow angle. */ + function spawn() { + const angle = ((200 + Math.random() * 18) * Math.PI) / 180; + const speed = (w > 700 ? 900 : 620) * (0.85 + Math.random() * 0.3); + meteors.push({ + x: w * (0.35 + Math.random() * 0.75), + y: -20 + Math.random() * h * 0.35, + dx: Math.cos(angle) * speed, + dy: -Math.sin(angle) * speed, + len: (w > 700 ? 190 : 130) * (0.8 + Math.random() * 0.5), + life: 0, + span: 0.75 + Math.random() * 0.45, + width: 1.2 + Math.random() * 0.8, + }); + } + + function drawStars(t: number) { + ctx!.clearRect(0, 0, w, h); + ctx!.fillStyle = "#ece6d8"; + for (const s of stars) { + ctx!.globalAlpha = Math.max(0.04, reduced ? s.base : s.base + Math.sin(t * s.rate + s.phase) * 0.12); + ctx!.beginPath(); + ctx!.arc(s.x, s.y, s.r, 0, Math.PI * 2); + ctx!.fill(); + } + ctx!.globalAlpha = 1; + } + + function drawMeteor(m: Meteor) { + const p = m.life / m.span; + // Fades in fast, burns, then fades out. + const fade = p < 0.15 ? p / 0.15 : p > 0.7 ? Math.max(0, (1 - p) / 0.3) : 1; + const [r, g, b] = TINT; + const norm = Math.hypot(m.dx, m.dy); + const tx = m.x - (m.dx / norm) * m.len; + const ty = m.y - (m.dy / norm) * m.len; + const tail = ctx!.createLinearGradient(m.x, m.y, tx, ty); + tail.addColorStop(0, `rgba(255, 250, 235, ${0.95 * fade})`); + tail.addColorStop(0.12, `rgba(${r}, ${g}, ${b}, ${0.75 * fade})`); + tail.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`); + ctx!.strokeStyle = tail; + ctx!.lineWidth = m.width; + ctx!.lineCap = "round"; + ctx!.beginPath(); + ctx!.moveTo(m.x, m.y); + ctx!.lineTo(tx, ty); + ctx!.stroke(); + const glow = ctx!.createRadialGradient(m.x, m.y, 0, m.x, m.y, 9); + glow.addColorStop(0, `rgba(255, 252, 240, ${0.9 * fade})`); + glow.addColorStop(0.4, `rgba(${r}, ${g}, ${b}, ${0.35 * fade})`); + glow.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`); + ctx!.fillStyle = glow; + ctx!.beginPath(); + ctx!.arc(m.x, m.y, 9, 0, Math.PI * 2); + ctx!.fill(); + } + + window.addEventListener("resize", resize); + resize(); + if (reduced) return () => window.removeEventListener("resize", resize); + + let next = 1.5; + let last = performance.now(); + let raf = 0; + const frame = (now: number) => { + // A hidden tab gets no frames; a long gap is not a burst of meteors. + const dt = Math.min((now - last) / 1000, 0.05); + last = now; + drawStars(now / 1000); + next -= dt; + if (next <= 0) { + spawn(); + next = EVERY * (0.5 + Math.random()); + } + for (let i = meteors.length - 1; i >= 0; i--) { + const m = meteors[i]; + m.life += dt; + m.x += m.dx * dt; + m.y += m.dy * dt; + if (m.life >= m.span) meteors.splice(i, 1); + else drawMeteor(m); + } + raf = requestAnimationFrame(frame); + }; + raf = requestAnimationFrame(frame); + return () => { + cancelAnimationFrame(raf); + window.removeEventListener("resize", resize); + }; + }, []); + + return