From 286ad140168f4b6184049722504c05e833c1a471 Mon Sep 17 00:00:00 2001 From: feco Date: Sat, 21 Nov 2026 18:04:01 +0000 Subject: [PATCH 01/14] legal: operator details, tarot in the terms, arbitration board MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sági Ferenc sole proprietor with address and tax number on the terms and privacy pages; the terms list tarot readings and name the Pest county arbitration board. Terms and privacy dated 2026-11-21. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- services/backend/src/routes/payments.rs | 2 +- services/frontend/src/app/aszf/page.tsx | 14 ++++--- services/frontend/src/app/privacy/page.tsx | 4 +- services/frontend/src/lib/legal.ts | 47 ++++++++++++++++------ 4 files changed, 45 insertions(+), 22 deletions(-) diff --git a/services/backend/src/routes/payments.rs b/services/backend/src/routes/payments.rs index 65ed79d..6292ad6 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-21"; /// 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 diff --git a/services/frontend/src/app/aszf/page.tsx b/services/frontend/src/app/aszf/page.tsx index a684bb0..d2cab6e 100644 --- a/services/frontend/src/app/aszf/page.tsx +++ b/services/frontend/src/app/aszf/page.tsx @@ -2,7 +2,7 @@ import type { Metadata } from "next"; import Link from "next/link"; import { PublicHeader } from "@/components/SiteHeader"; -import { OPERATOR, TERMS_UPDATED, operatorDetails } from "@/lib/legal"; +import { ARBITRATION_BOARD, OPERATOR, TERMS_UPDATED, operatorDetails } from "@/lib/legal"; import { getMe } from "@/lib/server"; export const metadata: Metadata = { @@ -32,8 +32,8 @@ export default async function TermsPage() {

{operatorDetails() ? ( <> - A sorsfonalak.hu weboldalt és szolgáltatást (a továbbiakban: Sorsfonalak) a(z){" "} - {operatorDetails()} nyújtja. + A sorsfonalak.hu weboldal és szolgáltatás (a továbbiakban: Sorsfonalak) szolgáltatója:{" "} + {operatorDetails()}. ) : ( "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." @@ -52,8 +52,8 @@ export default async function TermsPage() { 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. + 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 @@ -150,7 +150,9 @@ export default async function TermsPage() {

10. 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.

diff --git a/services/frontend/src/app/privacy/page.tsx b/services/frontend/src/app/privacy/page.tsx index 3f1a415..6f5274b 100644 --- a/services/frontend/src/app/privacy/page.tsx +++ b/services/frontend/src/app/privacy/page.tsx @@ -80,9 +80,9 @@ export default async function PrivacyPolicyPage() {

1. Who is responsible for your data?

- {operatorDetails() ? ( + {operatorDetails("en") ? ( <> - The controller of the Sorsfonalak service (sorsfonalak.hu) is {operatorDetails()}.{" "} + The controller of the Sorsfonalak service (sorsfonalak.hu) is {operatorDetails("en")}.{" "} ) : ( "The controller of the Sorsfonalak service (sorsfonalak.hu) can be reached by e-mail. " diff --git a/services/frontend/src/lib/legal.ts b/services/frontend/src/lib/legal.ts index 3e6979c..877bb4e 100644 --- a/services/frontend/src/lib/legal.ts +++ b/services/frontend/src/lib/legal.ts @@ -1,22 +1,43 @@ -// Operator details shown on the legal pages. The name, address and -// registration come with the company (at the opening); until then the pages -// leave them out and give the contact address only. +// Operator details shown on the legal pages. export const OPERATOR = { - name: null as string | null, - address: null as string | null, + name: "Sági Ferenc" as string | null, + /** Sole proprietor (egyéni vállalkozó). */ + soleTrader: true, + address: "2314 Halásztelek, Bólyai János u. 10/A" as string | null, email: "info@sorsfonalak.hu", - /** Company registration and tax number, if the operator is a company. */ - registration: null as string | null, + /** Sole proprietor registration number (nyilvántartási szám). */ + registrationNumber: null as string | null, + taxNumber: "92586503-1-33" as string | null, }; -/** Name, address and registration as one phrase ("Kft., 1234 Budapest, …"), or null. */ -export function operatorDetails(): string | null { - const parts = [OPERATOR.name, OPERATOR.address, OPERATOR.registration].filter(Boolean); +/** Name, address, registration and tax number as one phrase, or null. */ +export function operatorDetails(lang: "hu" | "en" = "hu"): string | null { + const en = lang === "en"; + const name = + OPERATOR.name && + (OPERATOR.soleTrader + ? `${OPERATOR.name} ${en ? "(sole proprietor)" : "egyéni vállalkozó"}` + : OPERATOR.name); + const reg = + OPERATOR.registrationNumber && + `${en ? "registration number" : "nyilvántartási szám"}: ${OPERATOR.registrationNumber}`; + const tax = + OPERATOR.taxNumber && + `${en ? "tax number" : "adószám"}: ${OPERATOR.taxNumber}`; + const parts = [name, OPERATOR.address, reg, tax].filter(Boolean); return parts.length > 0 ? parts.join(", ") : null; } -export const PRIVACY_UPDATED = "2026. november 20."; -export const PRIVACY_UPDATED_EN = "20 November 2026"; +/** The consumer arbitration board of the operator's seat (Pest county). */ +export const ARBITRATION_BOARD = { + name: "Pest Vármegyei Békéltető Testület", + address: "1055 Budapest, Balassi Bálint u. 25. IV/2.", + email: "pmbekelteto@pmkik.hu", + web: "https://panaszrendezes.hu", +}; + +export const PRIVACY_UPDATED = "2026. november 21."; +export const PRIVACY_UPDATED_EN = "21 November 2026"; /** The terms (ÁSZF) in force; the backend records this version with every purchase (TERMS_VERSION). */ -export const TERMS_UPDATED = "2026. november 20."; +export const TERMS_UPDATED = "2026. november 21."; From a63f8f9928e84d59c7fdb5431683a04ca0e335ff Mon Sep 17 00:00:00 2001 From: feco Date: Sat, 21 Nov 2026 18:07:25 +0000 Subject: [PATCH 02/14] legal: sole proprietor registration number, street name Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- services/frontend/src/lib/legal.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/frontend/src/lib/legal.ts b/services/frontend/src/lib/legal.ts index 877bb4e..c8087db 100644 --- a/services/frontend/src/lib/legal.ts +++ b/services/frontend/src/lib/legal.ts @@ -3,10 +3,10 @@ export const OPERATOR = { name: "Sági Ferenc" as string | null, /** Sole proprietor (egyéni vállalkozó). */ soleTrader: true, - address: "2314 Halásztelek, Bólyai János u. 10/A" as string | null, + address: "2314 Halásztelek, Bolyai János u. 10/A" as string | null, email: "info@sorsfonalak.hu", /** Sole proprietor registration number (nyilvántartási szám). */ - registrationNumber: null as string | null, + registrationNumber: "A167552407" as string | null, taxNumber: "92586503-1-33" as string | null, }; From 7d6a6c3d92dff54b55daf84718085484a27c974f Mon Sep 17 00:00:00 2001 From: feco Date: Sat, 21 Nov 2026 18:24:48 +0000 Subject: [PATCH 03/14] auth: e-mail + password login with e-mailed password links Sign-up asks no password: a link goes to the address and the password is set there (also for forgotten passwords), by whoever opens the mailbox. So nobody can register a password for someone else's address, and linking Google or Apple to an account with the same address stays safe. Opening the link confirms the address, ends other sessions and logs in. Sign-up answers alike for registered addresses (the owner gets an 'account exists' link), links are limited to one per kind a minute and five an hour, and unconfirmed password accounts cannot log in. Frontend: login form with sign-up and forgotten password next to the social buttons, and the /jelszo page for the link. Still behind PASSWORD_LOGIN (off on prod). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- crates/email-templates/src/lib.rs | 32 ++- services/backend/README.md | 11 +- services/backend/src/routes/auth.rs | 209 ++++++++++-------- services/backend/src/routes/mod.rs | 4 +- services/backend/src/tests.rs | 172 ++++++++------ .../src/app/belepes/PasswordLogin.tsx | 203 +++++++++++++++++ services/frontend/src/app/belepes/page.tsx | 46 +++- services/frontend/src/app/globals.css | 12 + .../src/app/jelszo/SetPasswordForm.tsx | 92 ++++++++ services/frontend/src/app/jelszo/page.tsx | 53 +++++ services/worker/src/tests.rs | 9 +- 11 files changed, 651 insertions(+), 192 deletions(-) create mode 100644 services/frontend/src/app/belepes/PasswordLogin.tsx create mode 100644 services/frontend/src/app/jelszo/SetPasswordForm.tsx create mode 100644 services/frontend/src/app/jelszo/page.tsx 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/services/backend/README.md b/services/backend/README.md index 4f2536d..e7b2c11 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,12 @@ 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 | | `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/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/mod.rs b/services/backend/src/routes/mod.rs index 7ba868d..ab9cda1 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -78,10 +78,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)) diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 743474a..4f8c9fe 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -278,17 +278,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 +348,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 +425,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 +465,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 +822,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 +933,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; 16] = [ "/healthz", // Stripe calls it; the signature proves it. "/v1/payments/stripe/webhook", @@ -890,9 +943,8 @@ 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}", @@ -2296,20 +2348,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 +2371,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/belepes/PasswordLogin.tsx b/services/frontend/src/app/belepes/PasswordLogin.tsx new file mode 100644 index 0000000..7e5346e --- /dev/null +++ b/services/frontend/src/app/belepes/PasswordLogin.tsx @@ -0,0 +1,203 @@ +"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, + initialMode = "login", +}: { + target: string; + inviteToken?: 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") { + let referral: string | null = null; + try { + referral = localStorage.getItem("sf_ref"); + } catch { + // storage blocked + } + 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..981fdd7 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.

); @@ -91,6 +102,9 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis const appleId = config?.apple_login?.enabled ? config.apple_login.client_id : null; const pendingInvite = invitation?.status === "pending" ? inviteToken : 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 +128,28 @@ 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 +160,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/globals.css b/services/frontend/src/app/globals.css index 966cb57..f0d36de 100644 --- a/services/frontend/src/app/globals.css +++ b/services/frontend/src/app/globals.css @@ -198,6 +198,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 { 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/worker/src/tests.rs b/services/worker/src/tests.rs index 3bdc450..4f74b3d 100644 --- a/services/worker/src/tests.rs +++ b/services/worker/src/tests.rs @@ -7,18 +7,19 @@ use crate::templates::{TemplateError, render}; #[test] fn templates_in_both_languages() { - let payload = json!({"url": "https://example.com/verify-email?token=abc", "display_name": "Anna"}); + let payload = json!({"url": "https://example.com/jelszo?token=abc", "display_name": "Anna"}); let hu = render("verify_email", "hu", &payload).unwrap(); - assert_eq!(hu.subject, "Erősítsd meg az e-mail-címed"); + assert_eq!(hu.subject, "Add meg a jelszavad"); assert!(hu.text.starts_with("Szia Anna!") && hu.text.contains("token=abc")); assert!( - hu.html.contains(r#""#) - && hu.html.contains(r#"href="https://example.com/verify-email?token=abc""#) + hu.html.contains(r#""#) && hu.html.contains(r#"href="https://example.com/jelszo?token=abc""#) ); let en = render("reset_password", "en", &payload).unwrap(); assert_eq!(en.subject, "Set a new password"); assert!(en.text.starts_with("Hi Anna,")); + let exists = render("account_exists", "hu", &payload).unwrap(); + assert_eq!(exists.subject, "Már van fiókod a Sorsfonalakon"); // Unknown locales fall back to English. assert_eq!(render("reset_password", "de", &payload).unwrap(), en); From 55048ed828d3a1fbb5b5c1354b4dc409a7ee4044 Mon Sep 17 00:00:00 2001 From: feco Date: Sat, 21 Nov 2026 18:41:13 +0000 Subject: [PATCH 04/14] docs: outgoing mail on prod goes through Amazon SES Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- docs/levelkuldes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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. From a571abdb653799e32fc89a22db4970486ae1ed46 Mon Sep 17 00:00:00 2001 From: feco Date: Sat, 21 Nov 2026 19:04:20 +0000 Subject: [PATCH 05/14] worker: Telegram notice about every purchase (notify task) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A separate worker task, apart from invoicing: each paid checkout is announced once to the operator's Telegram chat ('Páros csomag, 6 000 Ft', marked when it was a test payment), without the buyer's data. Outages and rate limits are retried; a wrong token or chat is logged, not retried. Needs TELEGRAM_BOT_TOKEN (.env.secrets) and TELEGRAM_CHAT_ID. Also fixes the worker test that still expected the old sign-up e-mail subject (CI failed on it since 7d6a6c3). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- .../db/migrations/0033_checkout_notified.sql | 4 + deploy/.env.example | 4 + deploy/README.md | 1 + deploy/docker-compose.yml | 4 +- docker-compose.yml | 2 + services/worker/src/config.rs | 20 +- services/worker/src/main.rs | 11 ++ services/worker/src/notify.rs | 176 ++++++++++++++++++ services/worker/src/telegram.rs | 72 +++++++ services/worker/src/tests.rs | 7 +- 10 files changed, 294 insertions(+), 7 deletions(-) create mode 100644 crates/db/migrations/0033_checkout_notified.sql create mode 100644 services/worker/src/notify.rs create mode 100644 services/worker/src/telegram.rs 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/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..ba0a4f5 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -88,5 +88,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/services/worker/src/config.rs b/services/worker/src/config.rs index 72fd724..2dacdb1 100644 --- a/services/worker/src/config.rs +++ b/services/worker/src/config.rs @@ -16,11 +16,13 @@ pub struct Tasks { pub analyses: bool, /// Issuing the invoices of the payments in Billingo. pub invoices: bool, + /// Telegram notices about purchases. + pub notify: bool, } impl Tasks { - pub const ALL: Tasks = Tasks { email: true, cleanup: true, analyses: true, invoices: true }; - const NONE: Tasks = Tasks { email: false, cleanup: false, analyses: false, invoices: false }; + pub const ALL: Tasks = Tasks { email: true, cleanup: true, analyses: true, invoices: true, notify: true }; + const NONE: Tasks = Tasks { email: false, cleanup: false, analyses: false, invoices: false, notify: false }; pub fn parse(raw: &str) -> anyhow::Result { let mut tasks = Self::NONE; @@ -30,7 +32,10 @@ impl Tasks { "cleanup" => tasks.cleanup = true, "analyses" => tasks.analyses = true, "invoices" => tasks.invoices = true, - other => anyhow::bail!("unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses, invoices)"), + "notify" => tasks.notify = true, + other => { + anyhow::bail!("unknown task '{other}' in WORKER_TASKS (email, cleanup, analyses, invoices, notify)") + } } } anyhow::ensure!(tasks != Self::NONE, "WORKER_TASKS names no task"); @@ -79,6 +84,12 @@ pub struct Config { /// `MAX_INVOICE_ATTEMPTS` (default 10, about a day with the backoff): /// then the invoice is marked failed for an admin. pub max_invoice_attempts: i32, + /// `TELEGRAM_BOT_TOKEN` (secret) and `TELEGRAM_CHAT_ID`: purchase notices + /// to this chat; unset: none. + pub telegram_bot_token: Option, + pub telegram_chat_id: Option, + /// `TELEGRAM_API_URL` (default `https://api.telegram.org`). + pub telegram_api_url: String, } fn var(name: &str) -> Option { @@ -129,6 +140,9 @@ impl Config { .transpose() .context("invalid BILLINGO_BLOCK_ID")?, max_invoice_attempts: parsed("MAX_INVOICE_ATTEMPTS", 10)?, + telegram_bot_token: var("TELEGRAM_BOT_TOKEN"), + telegram_chat_id: var("TELEGRAM_CHAT_ID"), + telegram_api_url: var("TELEGRAM_API_URL").unwrap_or_else(|| crate::telegram::DEFAULT_API_URL.into()), }) } } diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 54956bc..0482c68 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -20,7 +20,9 @@ mod compare; mod config; mod email; mod invoices; +mod notify; mod ses; +mod telegram; mod templates { pub use email_templates::*; } @@ -153,6 +155,15 @@ async fn main() -> anyhow::Result<()> { } None => tracing::warn!("BILLINGO_API_KEY is not set: invoices stay pending"), } + match (&config.telegram_bot_token, &config.telegram_chat_id) { + _ if !tasks.notify => {} + (Some(token), Some(chat)) => { + tracing::info!("purchase notices enabled (Telegram)"); + let telegram = telegram::Telegram::new(&config.telegram_api_url, token, chat); + jobs.spawn(notify::run(pool.clone(), telegram, config.poll_interval, stop.clone())); + } + _ => tracing::info!("TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID is not set: no purchase notices"), + } let app = Router::new().route("/healthz", get(healthz)).with_state(pool); let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?; diff --git a/services/worker/src/notify.rs b/services/worker/src/notify.rs new file mode 100644 index 0000000..5d826f4 --- /dev/null +++ b/services/worker/src/notify.rs @@ -0,0 +1,176 @@ +//! The `notify` task: a Telegram notice to the operator about every paid +//! checkout ("Páros csomag, 6 000 Ft"), once. It runs on its own, apart from +//! invoicing, and carries no personal data of the buyer. +//! +//! A purchase counts as notified when Telegram took the message, or refused +//! it for good (a wrong token or chat: logged as an error); after an outage +//! or a rate limit it is tried again on the next round. + +use std::time::Duration; + +use sqlx::PgPool; +use tokio::sync::watch; + +use crate::telegram::{Telegram, huf}; + +/// At most this many notices a round. +const BATCH: i64 = 20; + +/// The notice of one purchase. +fn text(item: &str, price_huf: i32, live: bool) -> String { + // The invoice item without its service prefix ("Online tartalomszolgáltatás – "). + let item = item.rsplit(" – ").next().unwrap_or(item); + format!("🛒 Vásárlás: {item}, {}{}", huf(price_huf), if live { "" } else { " (teszt fizetés)" }) +} + +/// Sends the notices of the purchases not notified yet; returns how many went out. +pub async fn run_once(db: &PgPool, telegram: &Telegram) -> Result { + let mut tx = db.begin().await?; + let due: Vec<(String, String, i32, bool)> = sqlx::query_as( + "SELECT c.id, coalesce(i.item_name, c.package), coalesce(c.amount_huf, c.price_huf), c.live \ + FROM stripe_checkouts c LEFT JOIN invoices i ON i.checkout_id = c.id \ + WHERE c.completed_at IS NOT NULL AND c.notified_at IS NULL \ + ORDER BY c.completed_at LIMIT $1 FOR UPDATE OF c SKIP LOCKED", + ) + .bind(BATCH) + .fetch_all(&mut *tx) + .await?; + let mut sent = 0; + for (id, item, price, live) in due { + match telegram.send(&text(&item, price, live)).await { + Ok(()) => sent += 1, + Err(e) if e.permanent => { + tracing::error!(checkout = %id, error = %e.message, "telegram refused the purchase notice; check TELEGRAM_*"); + } + Err(e) => { + tracing::warn!(checkout = %id, error = %e.message, "purchase notice not sent yet"); + break; + } + } + sqlx::query("UPDATE stripe_checkouts SET notified_at = now() WHERE id = $1") + .bind(&id) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + Ok(sent) +} + +pub async fn run(db: PgPool, telegram: Telegram, interval: Duration, stop: watch::Receiver) { + loop { + if let Err(e) = run_once(&db, &telegram).await { + tracing::error!(error = %e, "purchase notices"); + } + tokio::select! { + () = tokio::time::sleep(interval) => {} + () = crate::stopped(stop.clone()) => break, + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + + use axum::extract::State; + use axum::http::StatusCode; + use axum::routing::post; + use axum::{Json, Router}; + use serde_json::Value; + + use super::*; + + #[derive(Default)] + struct Fake { + messages: Mutex>, + /// The answer to give; `None`: 200. + status: Mutex>, + } + + async fn fake_telegram(fake: Arc) -> String { + async fn send(State(f): State>, Json(body): Json) -> StatusCode { + let status = *f.status.lock().unwrap(); + if status.is_none() { + f.messages.lock().unwrap().push(body); + } + status.unwrap_or(StatusCode::OK) + } + let app = Router::new().route("/botTOKEN/sendMessage", post(send)).with_state(fake); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}") + } + + async fn checkout(db: &PgPool, package: &str, price: i32, live: bool, paid: bool) -> String { + let id = format!("cs_{}", uuid::Uuid::now_v7()); + sqlx::query( + "INSERT INTO stripe_checkouts (id, package, price_huf, live, completed_at) \ + VALUES ($1, $2, $3, $4, CASE WHEN $5 THEN now() END)", + ) + .bind(&id) + .bind(package) + .bind(price) + .bind(live) + .bind(paid) + .execute(db) + .await + .unwrap(); + id + } + + #[test] + fn notice_texts() { + assert_eq!( + text("Online tartalomszolgáltatás – Páros csomag", 6000, true), + "🛒 Vásárlás: Páros csomag, 6\u{a0}000\u{a0}Ft" + ); + assert_eq!( + text("addon_questions", 1000, false), + "🛒 Vásárlás: addon_questions, 1\u{a0}000\u{a0}Ft (teszt fizetés)" + ); + } + + #[sqlx::test(migrator = "db::MIGRATOR")] + async fn each_purchase_is_announced_once(db: PgPool) { + let fake = Arc::new(Fake::default()); + let telegram = Telegram::new(&fake_telegram(fake.clone()).await, "TOKEN", "42"); + let paid = checkout(&db, "couple", 6000, false, true).await; + sqlx::query( + "INSERT INTO invoices (id, checkout_id, buyer_name, buyer_country, buyer_post_code, buyer_city, \ + buyer_address, buyer_tax_type, item_name, gross_huf, net_huf, vat_huf) \ + VALUES ($1, $2, 'Anna', 'HU', '6720', 'Szeged', 'Fő utca 1.', 'NO_TAX_NUMBER', \ + 'Online tartalomszolgáltatás – Páros csomag', 6000, 6000, 0)", + ) + .bind(uuid::Uuid::now_v7()) + .bind(&paid) + .execute(&db) + .await + .unwrap(); + checkout(&db, "single", 2000, true, false).await; // not paid (yet) + + // An outage: nothing is lost, it comes on the next round. + *fake.status.lock().unwrap() = Some(StatusCode::BAD_GATEWAY); + assert_eq!(run_once(&db, &telegram).await.unwrap(), 0); + *fake.status.lock().unwrap() = None; + assert_eq!(run_once(&db, &telegram).await.unwrap(), 1); + assert_eq!(run_once(&db, &telegram).await.unwrap(), 0); + let messages = fake.messages.lock().unwrap().clone(); + assert_eq!(messages.len(), 1); + assert_eq!(messages[0]["chat_id"], "42"); + assert_eq!(messages[0]["text"], "🛒 Vásárlás: Páros csomag, 6\u{a0}000\u{a0}Ft (teszt fizetés)"); + assert!(!messages[0]["text"].as_str().unwrap().contains("Anna"), "no personal data"); + + // A wrong chat is not retried for ever. + checkout(&db, "addon_questions", 1000, true, true).await; + *fake.status.lock().unwrap() = Some(StatusCode::BAD_REQUEST); + assert_eq!(run_once(&db, &telegram).await.unwrap(), 0); + let left: i64 = sqlx::query_scalar( + "SELECT count(*) FROM stripe_checkouts WHERE completed_at IS NOT NULL AND notified_at IS NULL", + ) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(left, 0); + } +} diff --git a/services/worker/src/telegram.rs b/services/worker/src/telegram.rs new file mode 100644 index 0000000..17fab61 --- /dev/null +++ b/services/worker/src/telegram.rs @@ -0,0 +1,72 @@ +//! Short notices to the operator's Telegram chat through a bot (Bot API +//! `sendMessage`). + +use std::time::Duration; + +use serde_json::json; + +pub const DEFAULT_API_URL: &str = "https://api.telegram.org"; + +pub struct Telegram { + http: reqwest::Client, + api: String, + token: String, + chat_id: String, +} + +impl Telegram { + pub fn new(api: &str, token: &str, chat_id: &str) -> Self { + let http = reqwest::Client::builder().timeout(Duration::from_secs(10)).build().expect("http client"); + Self { http, api: api.trim_end_matches('/').to_owned(), token: token.to_owned(), chat_id: chat_id.to_owned() } + } + + /// Sends `text` as a plain message. + pub async fn send(&self, text: &str) -> Result<(), SendError> { + let url = format!("{}/bot{}/sendMessage", self.api, self.token); + let body = json!({ "chat_id": self.chat_id, "text": text, "disable_web_page_preview": true }); + match self.http.post(&url).json(&body).send().await { + Ok(res) if res.status().is_success() => Ok(()), + Ok(res) => { + let status = res.status(); + let detail: String = res.text().await.unwrap_or_default().chars().take(200).collect(); + // A wrong token or chat stays wrong; rate limits and outages pass. + let permanent = status.is_client_error() && status != reqwest::StatusCode::TOO_MANY_REQUESTS; + Err(SendError { permanent, message: format!("{status}: {detail}") }) + } + // The URL holds the bot token: keep it out of the message. + Err(e) => Err(SendError { permanent: false, message: e.without_url().to_string() }), + } + } +} + +#[derive(Debug)] +pub struct SendError { + /// Retrying will not help (e.g. a wrong token or chat ID). + pub permanent: bool, + pub message: String, +} + +/// "6 000 Ft" +pub fn huf(amount: i32) -> String { + let digits = amount.unsigned_abs().to_string(); + let mut out = String::new(); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i).is_multiple_of(3) { + out.push('\u{a0}'); + } + out.push(c); + } + format!("{}{out}\u{a0}Ft", if amount < 0 { "-" } else { "" }) +} + +#[cfg(test)] +mod tests { + use super::huf; + + #[test] + fn forints() { + assert_eq!(huf(990), "990\u{a0}Ft"); + assert_eq!(huf(6000), "6\u{a0}000\u{a0}Ft"); + assert_eq!(huf(1234567), "1\u{a0}234\u{a0}567\u{a0}Ft"); + } +} diff --git a/services/worker/src/tests.rs b/services/worker/src/tests.rs index 4f74b3d..75501ee 100644 --- a/services/worker/src/tests.rs +++ b/services/worker/src/tests.rs @@ -99,7 +99,7 @@ async fn delivers_retries_and_gives_up(db: PgPool) { let d = delivery(db.clone(), vec![("flaky@example.com", false), ("rejected@example.com", true)]); assert_eq!(d.deliver_due().await.unwrap(), 4); - assert_eq!(sent(&d), vec![("anna@example.com".into(), "Erősítsd meg az e-mail-címed".into())]); + assert_eq!(sent(&d), vec![("anna@example.com".into(), "Add meg a jelszavad".into())]); assert_eq!(state(&db, ok).await, (1, true, false, None, false)); // Temporary failure: retried later, not at once. assert_eq!(state(&db, flaky).await, (1, false, false, Some("test failure".into()), true)); @@ -228,12 +228,13 @@ async fn cleanup_removes_only_expired_data(db: PgPool) { fn worker_tasks_are_chosen_by_name() { use crate::config::Tasks; let mail = Tasks::parse("email, cleanup").unwrap(); - assert_eq!(mail, Tasks { email: true, cleanup: true, analyses: false, invoices: false }); + assert_eq!(mail, Tasks { email: true, cleanup: true, analyses: false, invoices: false, notify: false }); assert_eq!( Tasks::parse("analyses").unwrap(), - Tasks { email: false, cleanup: false, analyses: true, invoices: false } + Tasks { email: false, cleanup: false, analyses: true, invoices: false, notify: false } ); assert!(Tasks::parse("email,invoices").unwrap().invoices); + assert!(Tasks::parse("email,cleanup,invoices,notify").unwrap().notify); assert!(Tasks::parse("emails").is_err()); assert!(Tasks::parse(" , ").is_err()); } From 0cd880b4181dc4237290be79012208ba9813a443 Mon Sep 17 00:00:00 2001 From: feco Date: Sat, 21 Nov 2026 19:11:06 +0000 Subject: [PATCH 06/14] worker: log whether the notify task runs Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- services/worker/src/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 0482c68..ae81d67 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -104,6 +104,7 @@ async fn main() -> anyhow::Result<()> { cleanup = tasks.cleanup, analyses = tasks.analyses, invoices = tasks.invoices, + notify = tasks.notify, "worker tasks" ); match &config.smtp_url { From 2eea1042a5cb63d31e7b1b1dae212f4c9aaa153b Mon Sep 17 00:00:00 2001 From: feco Date: Sat, 21 Nov 2026 20:31:45 +0000 Subject: [PATCH 07/14] Public sign calculator and the twelve sign pages, SEO basics /aszcendens-kalkulator: Sun, Moon and Ascendant signs from birth data without an account. A calculation only (no AI, nothing saved), limited to 30 calculations and 300 place searches an hour per visitor address (POST /v1/public/signs, GET /v1/public/geo/*). Without a birth time there is no Ascendant, and signs near a border are marked uncertain. /csillagjegyek and /csillagjegyek/{jegy}: the twelve signs with facts, Sun, Moon and Ascendant, love, work, a common misbelief and an offer, each written on its own. Links to the calculator and sign-up. SEO: metadataBase and canonical addresses, hreflang between the Hungarian and English privacy pages, Organization and WebSite JSON-LD on the home page, FAQPage on the calculator, BreadcrumbList on the sign pages; the sitemap lists the new pages, the footers link them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- crates/horoscope-client/src/lib.rs | 25 ++ services/backend/README.md | 2 + services/backend/src/auth.rs | 11 +- services/backend/src/main.rs | 6 + services/backend/src/routes/calculator.rs | 124 +++++++ services/backend/src/routes/mod.rs | 4 + services/backend/src/tests.rs | 58 ++- services/frontend/src/app/Landing.tsx | 2 + .../frontend/src/app/adatvedelem/page.tsx | 1 + .../aszcendens-kalkulator/SignCalculator.tsx | 310 ++++++++++++++++ .../src/app/aszcendens-kalkulator/page.tsx | 106 ++++++ .../src/app/csillagjegyek/[jegy]/page.tsx | 159 ++++++++ .../frontend/src/app/csillagjegyek/page.tsx | 63 ++++ services/frontend/src/app/globals.css | 46 +++ services/frontend/src/app/layout.tsx | 13 +- services/frontend/src/app/page.tsx | 32 +- services/frontend/src/app/privacy/page.tsx | 1 + .../frontend/src/app/profil/BirthForm.tsx | 59 +-- services/frontend/src/app/sitemap.ts | 4 + .../frontend/src/components/PublicFooter.tsx | 30 ++ services/frontend/src/content/zodiac.ts | 347 ++++++++++++++++++ services/frontend/src/lib/birth.ts | 39 ++ 22 files changed, 1395 insertions(+), 47 deletions(-) create mode 100644 services/backend/src/routes/calculator.rs create mode 100644 services/frontend/src/app/aszcendens-kalkulator/SignCalculator.tsx create mode 100644 services/frontend/src/app/aszcendens-kalkulator/page.tsx create mode 100644 services/frontend/src/app/csillagjegyek/[jegy]/page.tsx create mode 100644 services/frontend/src/app/csillagjegyek/page.tsx create mode 100644 services/frontend/src/components/PublicFooter.tsx create mode 100644 services/frontend/src/content/zodiac.ts create mode 100644 services/frontend/src/lib/birth.ts diff --git a/crates/horoscope-client/src/lib.rs b/crates/horoscope-client/src/lib.rs index f7df0d1..66a097c 100644 --- a/crates/horoscope-client/src/lib.rs +++ b/crates/horoscope-client/src/lib.rs @@ -48,6 +48,27 @@ impl HoroscopeClient { self.post("/v1/forecast", request).await } + /// `GET /v1/countries` + pub async fn countries(&self) -> Result { + self.get("/v1/countries", &[]).await + } + + /// `GET /v1/places?country=&q=&limit=` + pub async fn places(&self, country: &str, query: &str, limit: u32) -> Result { + self.get("/v1/places", &[("country", country), ("q", query), ("limit", &limit.to_string())]).await + } + + async fn get(&self, path: &str, query: &[(&str, &str)]) -> Result { + let response = self + .http + .get(format!("{}{path}", self.base_url)) + .query(query) + .send() + .await + .map_err(|e| HoroscopeError::Unavailable(e.to_string()))?; + Self::answer(response).await + } + async fn post(&self, path: &str, body: &Value) -> Result { let response = self .http @@ -56,6 +77,10 @@ impl HoroscopeClient { .send() .await .map_err(|e| HoroscopeError::Unavailable(e.to_string()))?; + Self::answer(response).await + } + + async fn answer(response: reqwest::Response) -> Result { let status = response.status(); let body: Value = response.json().await.map_err(|e| HoroscopeError::Unavailable(e.to_string()))?; if status.is_success() { diff --git a/services/backend/README.md b/services/backend/README.md index e7b2c11..1129aa2 100644 --- a/services/backend/README.md +++ b/services/backend/README.md @@ -68,6 +68,8 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh | `POST /v1/auth/logout`, `/logout-all` | user | kijelentkezés erről, illetve minden eszközről | | `POST /v1/auth/password-reset` | – | `{email}`; mindig 202 | | `POST /v1/auth/set-password` | – | `{token, password}` a levélben kapott linkből (regisztráció vagy elfelejtett jelszó); a cím megerősítetté válik, minden más munkamenet megszűnik, és belép | +| `POST /v1/public/signs` | – | a nyilvános kalkulátor: `{date, time?, country, geonames_id, ambiguous_time?}` → Nap-, Hold- és aszcendensjegy (idő nélkül aszcendens nélkül, a határ közeli jegyek `uncertain` jelöléssel); csak számítás, AI nélkül, nem ment semmit; IP-címenként óránként 30 | +| `GET /v1/public/geo/countries`, `/v1/public/geo/places?country=&q=` | – | országlista és helykereső a kalkulátorhoz (a helykereső IP-címenként óránként 300 kérés) | | `GET`/`PATCH`/`DELETE /v1/me` | user | profil (`display_name`, `locale`); törlés: `{confirm: "DELETE"}` | | `POST /v1/me/password` | user | `{current_password?, new_password}`; Google-fiókhoz jelszót is ad | | `GET /v1/me/export` | user | GDPR: minden adat egy JSON-ban | diff --git a/services/backend/src/auth.rs b/services/backend/src/auth.rs index 8305e7d..024f59a 100644 --- a/services/backend/src/auth.rs +++ b/services/backend/src/auth.rs @@ -186,7 +186,8 @@ pub static DUMMY_HASH: std::sync::LazyLock = std::sync::LazyLock::new(|| // --- brute-force protection ---------------------------------------------------------- /// Counts failed logins per e-mail address in a sliding window (in memory, -/// per backend instance). +/// per backend instance). Also counts the calls of public endpoints per +/// address ([`LoginLimiter::hit`]). pub struct LoginLimiter { max_failures: u32, window: Duration, @@ -222,6 +223,14 @@ impl LoginLimiter { entry.0 += 1; } + /// Counts one use of a public endpoint (every call, not just failures): + /// 429 once `max_failures` calls were made in the window. + pub fn hit(&self, key: &str) -> Result<(), ApiError> { + self.check(key)?; + self.failed(key); + Ok(()) + } + pub fn succeeded(&self, key: &str) { self.failures.lock().expect("limiter lock").remove(key); } diff --git a/services/backend/src/main.rs b/services/backend/src/main.rs index fe7d6b8..8e552c8 100644 --- a/services/backend/src/main.rs +++ b/services/backend/src/main.rs @@ -43,6 +43,10 @@ pub struct AppState { pub google: IdTokenVerifier, pub apple: IdTokenVerifier, pub login_limiter: LoginLimiter, + /// The public sign calculator, per visitor address. + pub calculator_limiter: LoginLimiter, + /// The public place search (typing makes several calls), per visitor address. + pub places_limiter: LoginLimiter, pub models: models::Catalog, pub stripe: stripe::Client, } @@ -54,6 +58,8 @@ impl AppState { google: IdTokenVerifier::google(config.google_client_ids.clone(), config.google_jwks_url.clone()), apple: IdTokenVerifier::apple(config.apple_client_ids.clone(), config.apple_jwks_url.clone()), login_limiter: LoginLimiter::new(10, Duration::from_secs(15 * 60)), + calculator_limiter: LoginLimiter::new(30, Duration::from_secs(60 * 60)), + places_limiter: LoginLimiter::new(300, Duration::from_secs(60 * 60)), models: models::Catalog::new(&config.openrouter_models_url), stripe: stripe::Client::default(), db, diff --git a/services/backend/src/routes/calculator.rs b/services/backend/src/routes/calculator.rs new file mode 100644 index 0000000..d95c444 --- /dev/null +++ b/services/backend/src/routes/calculator.rs @@ -0,0 +1,124 @@ +//! The public sign calculator (`/aszcendens-kalkulator`): the Sun, Moon and +//! Ascendant signs from birth data, without an account, plus the country list +//! and place search it needs. Nothing is stored. Each visitor address may +//! make a limited number of calculations and place searches an hour, so the +//! endpoints cannot serve as a free calculation service for other apps. + +use axum::Json; +use axum::extract::{Query, State}; +use axum::http::HeaderMap; +use axum_extra::extract::WithRejection; +use serde::Deserialize; +use serde_json::{Value, json}; + +use super::{Body, St, client_ip}; +use crate::error::{ApiError, ApiResult}; + +/// The limiter key of the visitor (all unknown addresses share one). +fn visitor(headers: &HeaderMap) -> String { + client_ip(headers).map_or_else(|| "unknown".to_string(), |ip| format!("ip:{ip}")) +} + +fn valid_country(country: &str) -> bool { + country.len() == 2 && country.chars().all(|c| c.is_ascii_uppercase()) +} + +pub async fn countries(State(state): St) -> ApiResult> { + Ok(Json(state.horoscope.countries().await?)) +} + +#[derive(Deserialize)] +pub struct PlacesQuery { + country: String, + q: String, + limit: Option, +} + +pub async fn places( + State(state): St, + headers: HeaderMap, + WithRejection(Query(query), _): WithRejection, ApiError>, +) -> ApiResult> { + let q = query.q.trim(); + if !valid_country(&query.country) || q.chars().count() < 2 || q.chars().count() > 80 { + return Err(ApiError::BadRequest("a country code and 2 to 80 characters of a place name are needed".into())); + } + state.places_limiter.hit(&visitor(&headers))?; + Ok(Json(state.horoscope.places(&query.country, q, query.limit.unwrap_or(8).min(10)).await?)) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SignsRequest { + date: String, + /// "HH:MM"; without it there is no Ascendant. + time: Option, + country: String, + geonames_id: i64, + /// "earlier" or "later", for a time that occurred twice (clocks set back). + ambiguous_time: Option, +} + +/// One sign of the answer. `uncertain`: without a birth time the point may +/// have been in the neighbouring sign at the start or the end of the day. +fn sign(point: &Value, time_known: bool, default_speed: f64) -> Value { + let degree = point["degree_in_sign"].as_f64(); + let speed = point["speed"].as_f64().unwrap_or(default_speed).abs(); + let uncertain = !time_known && degree.is_some_and(|d| d < speed / 2.0 || 30.0 - d < speed / 2.0); + json!({ "sign": point["sign"], "degree": degree.map(|d| d.floor()), "uncertain": uncertain }) +} + +/// The Sun, Moon and Ascendant signs of the birth data. +pub async fn signs( + State(state): St, + headers: HeaderMap, + WithRejection(Json(req), _): Body, +) -> ApiResult> { + if !valid_country(&req.country) { + return Err(ApiError::BadRequest("invalid country code".into())); + } + if req.ambiguous_time.as_deref().is_some_and(|a| a != "earlier" && a != "later") { + return Err(ApiError::BadRequest("ambiguous_time is 'earlier' or 'later'".into())); + } + state.calculator_limiter.hit(&visitor(&headers))?; + let mut birth = json!({ "date": req.date, "country": req.country, "geonames_id": req.geonames_id }); + if let Some(time) = &req.time { + birth["time"] = json!(time); + } + if let Some(ambiguous) = &req.ambiguous_time { + birth["ambiguous_time"] = json!(ambiguous); + } + let chart = state.horoscope.natal(&birth).await?; + let time_known = req.time.is_some(); + let point = |id: &str| { + chart["points"] + .as_array() + .and_then(|points| points.iter().find(|p| p["id"] == id)) + .cloned() + .unwrap_or(Value::Null) + }; + let ascendant = &chart["angles"]["ascendant"]; + Ok(Json(json!({ + "sun": sign(&point("sun"), time_known, 1.0), + "moon": sign(&point("moon"), time_known, 13.2), + "ascendant": (time_known && ascendant["sign"].is_string()).then(|| sign(ascendant, true, 0.0)), + "time_known": time_known, + "place": chart["location"]["place"]["name"], + }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn signs_near_a_border_are_uncertain_without_a_time() { + let moon = json!({"sign": "pisces", "degree_in_sign": 3.2, "speed": 12.6}); + assert_eq!(sign(&moon, false, 13.2)["uncertain"], true); + assert_eq!(sign(&moon, true, 13.2)["uncertain"], false); + let middle = json!({"sign": "pisces", "degree_in_sign": 15.0, "speed": 12.6}); + assert_eq!(sign(&middle, false, 13.2), json!({"sign": "pisces", "degree": 15.0, "uncertain": false})); + let sun = json!({"sign": "cancer", "degree_in_sign": 29.8}); + assert_eq!(sign(&sun, false, 1.0)["uncertain"], true); + } +} diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index ab9cda1..3a23ac7 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -9,6 +9,7 @@ mod account; mod admin; mod analyses; mod auth; +mod calculator; mod charts; mod errors; mod forecasts; @@ -125,6 +126,9 @@ pub fn router(state: Arc) -> Router { .route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe)) .route("/v1/public/invitations/{token}", get(invitations::public_view)) .route("/v1/public/waitlist", post(invitations::join_waitlist)) + .route("/v1/public/signs", post(calculator::signs)) + .route("/v1/public/geo/countries", get(calculator::countries)) + .route("/v1/public/geo/places", get(calculator::places)) // administration .route("/v1/admin/users", get(admin::list_users)) .route("/v1/admin/users/{id}", patch(admin::update_user)) diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 4f8c9fe..cdd39b2 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -175,6 +175,14 @@ async fn fake_services() -> String { .route("/v1/checkout/sessions", post(fake_stripe_create)) .route("/v1/checkout/sessions/{id}", get(fake_stripe_get)) .route("/v1/natal", post(fake_natal)) + .route("/v1/countries", get(|| async { Json(json!({"countries": [{"iso2": "HU", "name": "Hungary"}]})) })) + .route( + "/v1/places", + get(|axum::extract::Query(q): axum::extract::Query>| async move { + Json(json!({"places": [{"geonames_id": 715429, "name": format!("{}ed", q["q"]), "country_code": q["country"], + "region": null, "population": 160000}], "limit": q["limit"]})) + }), + ) .route("/v1/synastry", post(fake_synastry)) .route("/v1/forecast", post(fake_forecast)) .route("/jwks", get(fake_jwks)); @@ -933,7 +941,7 @@ async fn export_and_delete_account(pool: PgPool) { /// config and catalog, shared links, invitation pages, the waitlist and /// unsubscribing. Every other route (charts, calculations, analyses) needs a /// logged-in user, so other apps cannot use them. -const PUBLIC_ROUTES: [&str; 16] = [ +const PUBLIC_ROUTES: [&str; 19] = [ "/healthz", // Stripe calls it; the signature proves it. "/v1/payments/stripe/webhook", @@ -951,8 +959,56 @@ const PUBLIC_ROUTES: [&str; 16] = [ "/v1/public/invitations/unsubscribe", "/v1/public/invitations/{token}", "/v1/public/waitlist", + // The sign calculator (limited per visitor address). + "/v1/public/signs", + "/v1/public/geo/countries", + "/v1/public/geo/places", ]; +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn the_public_sign_calculator(pool: PgPool) { + let app = TestApp::new(pool).await; + let visitor = ("x-real-ip", "203.0.113.9"); + let birth = json!({"date": "1990-06-21", "time": "14:30", "country": "HU", "geonames_id": 715429}); + let r = app.call_with("POST", "/v1/public/signs", None, Some(birth.clone()), &[visitor]).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!( + (&r.body["sun"]["sign"], &r.body["moon"]["sign"], &r.body["ascendant"]["sign"]), + (&json!("cancer"), &json!("pisces"), &json!("aries")) + ); + // Without a birth time there is no Ascendant. + let r = app + .call_with( + "POST", + "/v1/public/signs", + None, + Some(json!({"date": "1990-06-21", "country": "HU", "geonames_id": 715429})), + &[visitor], + ) + .await; + assert_eq!((r.status, &r.body["ascendant"], &r.body["time_known"]), (StatusCode::OK, &Value::Null, &json!(false))); + let r = app.call_with("POST", "/v1/public/signs", None, Some(json!({"date": "1990-06-21"})), &[visitor]).await; + assert_eq!(r.status, StatusCode::BAD_REQUEST); + + // The place search passes the query on, with a capped limit. + let r = app.call_with("GET", "/v1/public/geo/places?country=HU&q=Szeg&limit=50", None, None, &[visitor]).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_eq!((&r.body["places"][0]["name"], &r.body["limit"]), (&json!("Szeged"), &json!("10"))); + let r = app.call_with("GET", "/v1/public/geo/places?country=hu&q=S", None, None, &[visitor]).await; + assert_eq!(r.status, StatusCode::BAD_REQUEST); + assert_eq!(app.get("/v1/public/geo/countries", None).await.body["countries"][0]["iso2"], "HU"); + + // 30 calculations an hour per address (the malformed request did not count). + for _ in 0..28 { + let r = app.call_with("POST", "/v1/public/signs", None, Some(birth.clone()), &[visitor]).await; + assert_eq!(r.status, StatusCode::OK); + } + let r = app.call_with("POST", "/v1/public/signs", None, Some(birth.clone()), &[visitor]).await; + assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS); + let r = app.call_with("POST", "/v1/public/signs", None, Some(birth), &[("x-real-ip", "198.51.100.2")]).await; + assert_eq!(r.status, StatusCode::OK); +} + #[sqlx::test(migrator = "db::MIGRATOR")] async fn a_visit_by_someone_else_earns_one_question_once(pool: PgPool) { let app = TestApp::new(pool).await; diff --git a/services/frontend/src/app/Landing.tsx b/services/frontend/src/app/Landing.tsx index 6fbba09..0c144d0 100644 --- a/services/frontend/src/app/Landing.tsx +++ b/services/frontend/src/app/Landing.tsx @@ -480,6 +480,8 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {
+
+
+
+ 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,7 +512,7 @@ export function Landing({ inviteOnly }: { inviteOnly: boolean }) {
-

1. A szolgáltató

+

1. A szolgáltatás

- {operatorDetails() ? ( - <> - A sorsfonalak.hu weboldal és szolgáltatás (a továbbiakban: Sorsfonalak) szolgáltatója:{" "} - {operatorDetails()}. - - ) : ( - "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, kártyajóslá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,7 +130,7 @@ 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 ({ARBITRATION_BOARD.name},{" "} @@ -158,12 +141,17 @@ export default async function TermsPage() {

-

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/privacy/page.tsx b/services/frontend/src/app/privacy/page.tsx index 3d186a9..91ed8e5 100644 --- a/services/frontend/src/app/privacy/page.tsx +++ b/services/frontend/src/app/privacy/page.tsx @@ -1,8 +1,9 @@ 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 = { @@ -17,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", @@ -28,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", @@ -39,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", @@ -81,14 +96,8 @@ export default async function PrivacyPolicyPage() {

1. Who is responsible for your data?

- {operatorDetails("en") ? ( - <> - The controller of the Sorsfonalak service (sorsfonalak.hu) is {operatorDetails("en")}.{" "} - - ) : ( - "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} @@ -124,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. +

@@ -181,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.

@@ -225,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).
  • @@ -305,6 +322,11 @@ export default async function PrivacyPolicyPage() { always on this page.

    + +
    +

    12. Controller details

    + +
    ); diff --git a/services/frontend/src/components/OperatorDetails.tsx b/services/frontend/src/components/OperatorDetails.tsx new file mode 100644 index 0000000..cbe2550 --- /dev/null +++ b/services/frontend/src/components/OperatorDetails.tsx @@ -0,0 +1,35 @@ +import { OPERATOR } from "@/lib/legal"; + +/** The operator's identifying details: a plain list in the last section of the legal pages. */ +export function OperatorDetails({ lang = "hu", hosting = false }: { lang?: "hu" | "en"; hosting?: boolean }) { + const en = lang === "en"; + const name = + OPERATOR.name && + (OPERATOR.soleTrader ? `${OPERATOR.name} ${en ? "(sole proprietor)" : "egyéni vállalkozó"}` : OPERATOR.name); + const rows: [string, React.ReactNode][] = [ + [en ? "Name" : "Név", name], + [en ? "Registered address" : "Székhely", OPERATOR.address], + [en ? "Registration number" : "Nyilvántartási szám", OPERATOR.registrationNumber], + [en ? "Tax number" : "Adószám", OPERATOR.taxNumber], + ["E-mail", {OPERATOR.email}], + ]; + if (hosting) { + rows.push([ + en ? "Hosting provider" : "Tárhelyszolgáltató", + en + ? "DigitalOcean, LLC (digitalocean.com); the data is stored in the European Union (Amsterdam)" + : "DigitalOcean, LLC (digitalocean.com); az adatok az Európai Unióban (Amszterdam) vannak tárolva", + ]); + } + return ( +
      + {rows + .filter(([, value]) => value) + .map(([label, value]) => ( +
    • + {label}: {value} +
    • + ))} +
    + ); +} diff --git a/services/frontend/src/lib/legal.ts b/services/frontend/src/lib/legal.ts index c8087db..5cf774a 100644 --- a/services/frontend/src/lib/legal.ts +++ b/services/frontend/src/lib/legal.ts @@ -10,24 +10,6 @@ export const OPERATOR = { taxNumber: "92586503-1-33" as string | null, }; -/** Name, address, registration and tax number as one phrase, or null. */ -export function operatorDetails(lang: "hu" | "en" = "hu"): string | null { - const en = lang === "en"; - const name = - OPERATOR.name && - (OPERATOR.soleTrader - ? `${OPERATOR.name} ${en ? "(sole proprietor)" : "egyéni vállalkozó"}` - : OPERATOR.name); - const reg = - OPERATOR.registrationNumber && - `${en ? "registration number" : "nyilvántartási szám"}: ${OPERATOR.registrationNumber}`; - const tax = - OPERATOR.taxNumber && - `${en ? "tax number" : "adószám"}: ${OPERATOR.taxNumber}`; - const parts = [name, OPERATOR.address, reg, tax].filter(Boolean); - return parts.length > 0 ? parts.join(", ") : null; -} - /** The consumer arbitration board of the operator's seat (Pest county). */ export const ARBITRATION_BOARD = { name: "Pest Vármegyei Békéltető Testület", @@ -36,8 +18,8 @@ export const ARBITRATION_BOARD = { web: "https://panaszrendezes.hu", }; -export const PRIVACY_UPDATED = "2026. november 21."; -export const PRIVACY_UPDATED_EN = "21 November 2026"; +export const PRIVACY_UPDATED = "2026. november 22."; +export const PRIVACY_UPDATED_EN = "22 November 2026"; /** The terms (ÁSZF) in force; the backend records this version with every purchase (TERMS_VERSION). */ -export const TERMS_UPDATED = "2026. november 21."; +export const TERMS_UPDATED = "2026. november 22."; From 4b93dc42e86cf46be2ff30667d848c52db239280 Mon Sep 17 00:00:00 2001 From: feco Date: Sun, 22 Nov 2026 06:36:16 +0000 Subject: [PATCH 14/14] =?UTF-8?q?Neutral=20invoice=20items;=20"k=C3=A1rtya?= =?UTF-8?q?"=20instead=20of=20"k=C3=A1rtyaj=C3=B3sl=C3=A1s"=20on=20Stripe?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Invoices: the add-ons share the item "Online tartalomszolgáltatás – kiegészítő csomag" and tarot readings are listed as "egyedi szöveges tartalom"; a test keeps "jóslás" and "kártya" off every invoice. Stripe's payment page and receipt call the tarot add-on "+5 kártya". The Telegram notice adds the package id to an add-on, so it still says which one was bought. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- docs/fizetes.md | 2 +- docs/kartyajoslas.md | 2 +- services/backend/src/packages.rs | 35 ++++++++++++++++++++----- services/backend/src/routes/payments.rs | 7 ++--- services/worker/src/notify.rs | 25 ++++++++++++------ 5 files changed, 51 insertions(+), 20 deletions(-) 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/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/payments.rs b/services/backend/src/routes/payments.rs index f7845ca..8cddc3e 100644 --- a/services/backend/src/routes/payments.rs +++ b/services/backend/src/routes/payments.rs @@ -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/worker/src/notify.rs b/services/worker/src/notify.rs index 5d826f4..20a2643 100644 --- a/services/worker/src/notify.rs +++ b/services/worker/src/notify.rs @@ -17,17 +17,20 @@ use crate::telegram::{Telegram, huf}; const BATCH: i64 = 20; /// The notice of one purchase. -fn text(item: &str, price_huf: i32, live: bool) -> String { +fn text(item: &str, package: &str, price_huf: i32, live: bool) -> String { // The invoice item without its service prefix ("Online tartalomszolgáltatás – "). let item = item.rsplit(" – ").next().unwrap_or(item); - format!("🛒 Vásárlás: {item}, {}{}", huf(price_huf), if live { "" } else { " (teszt fizetés)" }) + // The add-ons share one neutral invoice name; their id tells them apart. + let what = + if package.starts_with("addon_") && item != package { format!("{item} ({package})") } else { item.into() }; + format!("🛒 Vásárlás: {what}, {}{}", huf(price_huf), if live { "" } else { " (teszt fizetés)" }) } /// Sends the notices of the purchases not notified yet; returns how many went out. pub async fn run_once(db: &PgPool, telegram: &Telegram) -> Result { let mut tx = db.begin().await?; - let due: Vec<(String, String, i32, bool)> = sqlx::query_as( - "SELECT c.id, coalesce(i.item_name, c.package), coalesce(c.amount_huf, c.price_huf), c.live \ + let due: Vec<(String, String, String, i32, bool)> = sqlx::query_as( + "SELECT c.id, coalesce(i.item_name, c.package), c.package, coalesce(c.amount_huf, c.price_huf), c.live \ FROM stripe_checkouts c LEFT JOIN invoices i ON i.checkout_id = c.id \ WHERE c.completed_at IS NOT NULL AND c.notified_at IS NULL \ ORDER BY c.completed_at LIMIT $1 FOR UPDATE OF c SKIP LOCKED", @@ -36,8 +39,8 @@ pub async fn run_once(db: &PgPool, telegram: &Telegram) -> Result sent += 1, Err(e) if e.permanent => { tracing::error!(checkout = %id, error = %e.message, "telegram refused the purchase notice; check TELEGRAM_*"); @@ -122,11 +125,17 @@ mod tests { #[test] fn notice_texts() { assert_eq!( - text("Online tartalomszolgáltatás – Páros csomag", 6000, true), + text("Online tartalomszolgáltatás – Páros csomag", "couple", 6000, true), "🛒 Vásárlás: Páros csomag, 6\u{a0}000\u{a0}Ft" ); + // The add-ons share one invoice name: the id says which one it was. assert_eq!( - text("addon_questions", 1000, false), + text("Online tartalomszolgáltatás – kiegészítő csomag", "addon_tarot", 1000, true), + "🛒 Vásárlás: kiegészítő csomag (addon_tarot), 1\u{a0}000\u{a0}Ft" + ); + // No invoice yet: the id alone. + assert_eq!( + text("addon_questions", "addon_questions", 1000, false), "🛒 Vásárlás: addon_questions, 1\u{a0}000\u{a0}Ft (teszt fizetés)" ); }