diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 40da6f7..e66a999 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -59,7 +59,7 @@ jobs: # astro-engine and horoscope-api need the Swiss Ephemeris sources and # data (scripts/fetch-deps.sh); their tests run locally. - name: Test - run: cargo test --locked -p backend -p worker -p db -p horoscope-client -p service-kit -p analysis-prompt + run: cargo test --locked -p backend -p worker -p db -p horoscope-client -p service-kit -p analysis-prompt -p email-templates build: needs: test diff --git a/Cargo.lock b/Cargo.lock index b25cdf5..7b8ca1f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -169,6 +169,7 @@ dependencies = [ "axum", "axum-extra", "db", + "email-templates", "horoscope-client", "http-body-util", "jsonwebtoken", @@ -446,6 +447,13 @@ dependencies = [ "memchr", ] +[[package]] +name = "email-templates" +version = "0.1.0" +dependencies = [ + "serde_json", +] + [[package]] name = "email_address" version = "0.2.9" @@ -2867,13 +2875,17 @@ dependencies = [ "analysis-prompt", "anyhow", "axum", + "base64 0.22.1", "db", + "email-templates", + "hmac", "lettre", "rand 0.9.5", "reqwest", "serde", "serde_json", "service-kit", + "sha2", "sqlx", "time", "tokio", diff --git a/Cargo.toml b/Cargo.toml index 3d53720..aa52438 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ members = [ "crates/db", "crates/horoscope-client", "crates/analysis-prompt", + "crates/email-templates", "services/horoscope-api", "services/backend", "services/worker", @@ -27,12 +28,14 @@ service-kit = { path = "crates/service-kit" } db = { path = "crates/db" } horoscope-client = { path = "crates/horoscope-client" } analysis-prompt = { path = "crates/analysis-prompt" } +email-templates = { path = "crates/email-templates" } anyhow = "1" argon2 = { version = "0.5", features = ["std"] } axum = "0.8" axum-extra = { version = "0.10", features = ["cookie"] } base64 = "0.22" +hmac = "0.12" jsonwebtoken = { version = "9", default-features = false } lettre = { version = "0.11", default-features = false, features = ["builder", "hostname", "smtp-transport", "tokio1", "tokio1-rustls", "webpki-roots", "ring"] } rand = "0.9" diff --git a/crates/db/migrations/0013_invitations.sql b/crates/db/migrations/0013_invitations.sql new file mode 100644 index 0000000..11d9b84 --- /dev/null +++ b/crates/db/migrations/0013_invitations.sql @@ -0,0 +1,43 @@ +-- Invitations to the closed site. While SIGNUP_MODE=invite, a new account +-- (Google or password) needs an open invitation for its address, or the +-- invitation link itself (then any address will do). +CREATE TABLE invitations ( + id uuid PRIMARY KEY, + email text NOT NULL, + message text CHECK (char_length(message) <= 300), + locale text NOT NULL, + invited_by uuid REFERENCES users (id) ON DELETE SET NULL, + created_at timestamptz NOT NULL DEFAULT now(), + expires_at timestamptz NOT NULL, + sent_count integer NOT NULL DEFAULT 1, + last_sent_at timestamptz NOT NULL DEFAULT now(), + accepted_at timestamptz, + accepted_by uuid REFERENCES users (id) ON DELETE SET NULL, + revoked_at timestamptz +); +-- At most one open invitation per address. +CREATE UNIQUE INDEX invitations_open_email_idx ON invitations (email) + WHERE accepted_at IS NULL AND revoked_at IS NULL; +CREATE INDEX invitations_created_idx ON invitations (created_at DESC); + +-- Link tokens (only their hashes). Every sending issues a new one, and the +-- earlier links keep working while the invitation is open. +CREATE TABLE invitation_tokens ( + token_hash bytea PRIMARY KEY, + invitation_id uuid NOT NULL REFERENCES invitations (id) ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX invitation_tokens_invitation_idx ON invitation_tokens (invitation_id); + +-- Addresses that asked for no more invitations (only the SHA-256 of the address). +CREATE TABLE email_optouts ( + email_hash bytea PRIMARY KEY, + created_at timestamptz NOT NULL DEFAULT now() +); + +-- "Tell me when it opens": people without an invitation. +CREATE TABLE waitlist ( + email text PRIMARY KEY, + locale text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); diff --git a/crates/email-templates/Cargo.toml b/crates/email-templates/Cargo.toml new file mode 100644 index 0000000..f4e0418 --- /dev/null +++ b/crates/email-templates/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "email-templates" +description = "E-mail texts of Sorsfonalak as HTML and plain text (sent by the worker, previewed by the backend)" +edition.workspace = true +version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +serde_json.workspace = true diff --git a/crates/email-templates/src/lib.rs b/crates/email-templates/src/lib.rs new file mode 100644 index 0000000..a5305ea --- /dev/null +++ b/crates/email-templates/src/lib.rs @@ -0,0 +1,482 @@ +//! E-mail texts (Hungarian and English), as plain text and HTML. +//! +//! The payloads are written by the backend; the validity periods in the +//! texts match the token lifetimes there. The worker sends the result, the +//! backend renders it for the admin preview. +//! +//! The layout is deliberately plain for spam filters: one column, inline +//! styles, no images, no tracking, every link on the site's own domain, and +//! a plain-text part with the same content. + +use serde_json::Value; + +#[derive(Debug, Clone, PartialEq)] +pub struct Rendered { + pub subject: String, + pub text: String, + pub html: String, + /// One-click unsubscribe address for the `List-Unsubscribe` header (RFC 8058). + pub unsubscribe_post_url: Option, +} + +#[derive(Debug, PartialEq)] +pub enum TemplateError { + UnknownTemplate(String), + MissingField(&'static str), +} + +impl std::fmt::Display for TemplateError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + TemplateError::UnknownTemplate(t) => write!(f, "unknown e-mail template '{t}'"), + TemplateError::MissingField(field) => write!(f, "e-mail payload has no '{field}'"), + } + } +} + +#[derive(Clone, Copy, PartialEq)] +enum Lang { + Hu, + En, +} + +/// One e-mail: greeting, paragraphs, a button and a closing note. +struct Content { + subject: String, + /// The line mail clients show after the subject in the inbox. + preheader: Option, + greeting: String, + intro: String, + /// A personal message, shown as a quote. + quote: Option, + /// A short list after the intro, with its heading. + points: Option<(&'static str, Vec<&'static str>)>, + button: &'static str, + url: String, + note: String, + /// Why the recipient got this e-mail (for mails they did not ask for). + reason: Option, + /// Label and page of the unsubscribe link in the footer. + unsubscribe: Option<(&'static str, String)>, + unsubscribe_post_url: Option, +} + +impl Content { + fn simple(subject: String, greeting: String, intro: String, button: &'static str, url: String, note: &str) -> Self { + Self { + subject, + preheader: None, + greeting, + intro, + quote: None, + points: None, + button, + url, + note: note.to_owned(), + reason: None, + unsubscribe: None, + unsubscribe_post_url: None, + } + } +} + +pub fn render(template: &str, locale: &str, payload: &Value) -> Result { + let lang = if locale.eq_ignore_ascii_case("hu") { Lang::Hu } else { Lang::En }; + let url = field(payload, "url")?; + let greeting = |name: Option| match (lang, name) { + (Lang::Hu, Some(n)) => format!("Szia {n}!"), + (Lang::Hu, None) => "Szia!".to_owned(), + (Lang::En, Some(n)) => format!("Hi {n},"), + (Lang::En, None) => "Hi,".to_owned(), + }; + let content = match (template, lang) { + ("verify_email", Lang::Hu) => Content::simple( + "Erősítsd meg az e-mail-címed".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", + url, + "A link 3 napig érvényes. 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(), + 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", + url, + "The link is valid for 3 days. If you did not sign up, you can safely ignore this e-mail.", + ), + ("reset_password", Lang::Hu) => Content::simple( + "Új jelszó megadása".into(), + greeting(name(payload, "display_name")), + "Jelszó-visszaállítást kértél a Sorsfonalak-fiókodhoz. Az alábbi gombbal adhatsz meg új jelszót.".into(), + "Új jelszó megadása", + url, + "A link 1 óráig érvényes, és csak egyszer használható. Ha nem te kérted, hagyd figyelmen kívül ezt a levelet: a jelszavad nem változik.", + ), + ("reset_password", Lang::En) => Content::simple( + "Set a new password".into(), + greeting(name(payload, "display_name")), + "You asked to reset the password of your Sorsfonalak account. Use the button below to set a new one." + .into(), + "Set a new password", + url, + "The link is valid for 1 hour and can be used once. If you did not ask for this, ignore this e-mail: your password stays the same.", + ), + ("invite_accepted", Lang::Hu) => { + let who = name(payload, "invitee_name"); + Content::simple( + match &who { + Some(n) => format!("{n} elfogadta a meghívásod"), + None => "Elfogadták a meghívásod".into(), + }, + greeting(None), + format!( + "{} elfogadta a „Mennyire illünk össze?” meghívásod, és elkészült a szinasztriátok.", + who.as_deref().unwrap_or("A meghívott") + ), + "Szinasztria megnyitása", + url, + "A szinasztriát mindketten látjátok, de egymás születési adatait nem.", + ) + } + ("invite_accepted", Lang::En) => { + let who = name(payload, "invitee_name"); + Content::simple( + match &who { + Some(n) => format!("{n} accepted your invitation"), + None => "Your invitation was accepted".into(), + }, + greeting(None), + format!( + "{} accepted your “How compatible are we?” invitation, and your synastry is ready.", + who.as_deref().unwrap_or("Your invitee") + ), + "Open synastry", + url, + "You both see the synastry, but not each other's birth data.", + ) + } + ("invitation", _) => invitation(lang, payload, url)?, + _ => return Err(TemplateError::UnknownTemplate(template.to_owned())), + }; + Ok(content.render(lang)) +} + +/// An invitation to the closed site (sent by an administrator). +fn invitation(lang: Lang, payload: &Value, url: String) -> Result { + let inviter = name(payload, "inviter_name"); + let message = message(payload); + let until = + payload["expires_on"].as_str().and_then(|d| date(lang, d)).ok_or(TemplateError::MissingField("expires_on"))?; + // "2026. december 17." + "-ig" = "2026. december 17-ig" + let until_hu = until.trim_end_matches('.'); + let unsubscribe_url = field(payload, "unsubscribe_url")?; + let unsubscribe_post_url = field(payload, "unsubscribe_post_url")?; + Ok(match lang { + Lang::Hu => Content { + subject: match &inviter { + Some(n) => format!("{n} meghívott a Sorsfonalakra"), + None => "Meghívót kaptál a Sorsfonalakra".into(), + }, + preheader: Some(format!("Születési képlet és rövid elemzés ingyen. A meghívó {until_hu}-ig érvényes.")), + greeting: "Szia!".into(), + intro: match &inviter { + Some(n) => { + format!("{n} meghívott a Sorsfonalakra. Az oldal egyelőre zártkörű: csak meghívóval lehet belépni.") + } + None => { + "Meghívót kaptál a Sorsfonalakra. Az oldal egyelőre zártkörű: csak meghívóval lehet belépni.".into() + } + }, + quote: message, + points: Some(( + "Mit találsz ott?", + vec![ + "a születési képleted kiszámolva és megrajzolva, ingyen,", + "egy rövid, személyre szóló elemzést róla,", + "összevetést a szeretteiddel: mennyire illetek össze.", + ], + )), + button: "Meghívás elfogadása", + url, + note: format!( + "A meghívó {until_hu}-ig érvényes. Elfogadáskor Google-fiókkal lépsz be, és ezzel a linkkel bármelyik Google-fiókodat használhatod." + ), + reason: Some(match &inviter { + Some(n) => { + format!("Ezt a levelet azért kaptad, mert {n} megadta az e-mail-címed a Sorsfonalak meghívójában.") + } + None => { + "Ezt a levelet azért kaptad, mert valaki megadta az e-mail-címed a Sorsfonalak meghívójában.".into() + } + }), + unsubscribe: Some(("Nem kérek több meghívót", unsubscribe_url)), + unsubscribe_post_url: Some(unsubscribe_post_url), + }, + Lang::En => Content { + subject: match &inviter { + Some(n) => format!("{n} invited you to Sorsfonalak"), + None => "You are invited to Sorsfonalak".into(), + }, + preheader: Some(format!( + "Your birth chart and a short reading, free. The invitation is valid until {until}." + )), + greeting: "Hi,".into(), + intro: match &inviter { + Some(n) => format!("{n} invited you to Sorsfonalak. The site is invitation-only for now."), + None => "You are invited to Sorsfonalak. The site is invitation-only for now.".into(), + }, + quote: message, + points: Some(( + "What you will find there:", + vec![ + "your birth chart, calculated and drawn, for free,", + "a short, personal reading of it,", + "comparisons with your loved ones: how well you match.", + ], + )), + button: "Accept the invitation", + url, + note: format!( + "The invitation is valid until {until}. You sign in with Google, and with this link any of your Google accounts will do." + ), + reason: Some(match &inviter { + Some(n) => format!("You got this e-mail because {n} entered your address in a Sorsfonalak invitation."), + None => "You got this e-mail because someone entered your address in a Sorsfonalak invitation.".into(), + }), + unsubscribe: Some(("No more invitations, please", unsubscribe_url)), + unsubscribe_post_url: Some(unsubscribe_post_url), + }, + }) +} + +fn field(payload: &Value, name: &'static str) -> Result { + payload[name].as_str().filter(|u| !u.is_empty()).map(str::to_owned).ok_or(TemplateError::MissingField(name)) +} + +/// A user-supplied name, safe for a subject line. +fn name(payload: &Value, field: &str) -> Option { + let name: String = payload[field].as_str()?.chars().filter(|c| !c.is_control()).take(60).collect(); + let name = name.trim(); + (!name.is_empty()).then(|| name.to_owned()) +} + +/// The personal message of an invitation: line breaks kept, other control characters dropped. +fn message(payload: &Value) -> Option { + let text: String = + payload["message"].as_str()?.chars().filter(|c| *c == '\n' || !c.is_control()).take(500).collect(); + let text = text.trim(); + (!text.is_empty()).then(|| text.to_owned()) +} + +/// `2026-12-17` as "2026. december 17." or "17 December 2026". +fn date(lang: Lang, iso: &str) -> Option { + const HU: [&str; 12] = [ + "január", + "február", + "március", + "április", + "május", + "június", + "július", + "augusztus", + "szeptember", + "október", + "november", + "december", + ]; + const EN: [&str; 12] = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", + ]; + let mut parts = iso.splitn(3, '-'); + let (y, m, d) = (parts.next()?, parts.next()?, parts.next()?); + let (y, m, d): (u32, usize, u32) = (y.parse().ok()?, m.parse().ok()?, d.get(..2)?.parse().ok()?); + let month = m.checked_sub(1).filter(|&i| i < 12)?; + Some(match lang { + Lang::Hu => format!("{y}. {} {d}.", HU[month]), + Lang::En => format!("{d} {} {y}", EN[month]), + }) +} + +fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + _ => out.push(c), + } + } + out +} + +const TEXT: &str = "#2a2620"; +const MUTED: &str = "#6b645a"; +const FAINT: &str = "#9b948a"; +const GOLD: &str = "#9a7b3c"; + +impl Content { + fn render(self, lang: Lang) -> Rendered { + let footer = match lang { + Lang::Hu => "Ezt a levelet a Sorsfonalak küldte.", + Lang::En => "This e-mail was sent by Sorsfonalak.", + }; + + let mut text = format!("{}\n\n{}\n\n", self.greeting, self.intro); + if let Some(q) = &self.quote { + for line in q.lines() { + text.push_str(&format!("> {line}\n")); + } + text.push('\n'); + } + if let Some((heading, items)) = &self.points { + text.push_str(heading); + text.push('\n'); + for item in items { + text.push_str(&format!("- {item}\n")); + } + text.push('\n'); + } + text.push_str(&format!("{}:\n{}\n\n{}\n\n-- \nSorsfonalak\n", self.button, self.url, self.note)); + if let Some(reason) = &self.reason { + text.push_str(&format!("\n{reason}\n")); + } + if let Some((label, url)) = &self.unsubscribe { + text.push_str(&format!("{label}: {url}\n")); + } + + let preheader = self.preheader.as_deref().map_or(String::new(), |p| { + format!( + r#"
{}
"#, + escape(p) + ) + }); + let quote = self.quote.as_deref().map_or(String::new(), |q| { + format!( + r#"
{}
+"#, + escape(q).replace('\n', "
") + ) + }); + let points = self.points.as_ref().map_or(String::new(), |(heading, items)| { + let items: String = items + .iter() + .map(|i| format!(r#"
  • {}
  • "#, escape(i))) + .collect(); + format!( + r#"{}
      {items}
    +"#, + escape(heading) + ) + }); + let mut small = Vec::new(); + if let Some(reason) = &self.reason { + small.push(escape(reason)); + } + if let Some((label, url)) = &self.unsubscribe { + small.push(format!(r#"{}"#, escape(url), escape(label))); + } + small.push(escape(footer)); + let small = small.join("
    "); + + let html = format!( + r#" + +{subject} + +{preheader} + +
    + + + + +{quote}{points} + + +
    SORSFONALAK
    {greeting}
    {intro}
    {button}
    {note}
    {url_text}
    +

    {small}

    +
    + + +"#, + lang = if lang == Lang::Hu { "hu" } else { "en" }, + subject = escape(&self.subject), + greeting = escape(&self.greeting), + intro = escape(&self.intro), + url = escape(&self.url), + button = escape(self.button), + note = escape(&self.note), + url_text = escape(&self.url), + ); + Rendered { subject: self.subject, text, html, unsubscribe_post_url: self.unsubscribe_post_url } + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + fn invitation_payload() -> Value { + json!({ + "url": "https://sorsfonalak.test/meghivo/abc", + "inviter_name": "Kata", + "message": "Gyere, nézd meg!\nSzia", + "expires_on": "2026-12-17", + "unsubscribe_url": "https://sorsfonalak.test/leiratkozas?token=abc", + "unsubscribe_post_url": "https://sorsfonalak.test/api/v1/public/invitations/unsubscribe?token=abc", + }) + } + + #[test] + fn invitation_has_both_parts() { + let hu = render("invitation", "hu", &invitation_payload()).unwrap(); + assert_eq!(hu.subject, "Kata meghívott a Sorsfonalakra"); + assert!(hu.text.contains("> Gyere, nézd meg!\n> Szia")); + assert!(hu.text.contains("A meghívó 2026. december 17-ig érvényes.")); + assert!(hu.text.contains("Nem kérek több meghívót: https://sorsfonalak.test/leiratkozas?token=abc")); + assert!(hu.html.contains("Gyere, nézd meg!
    <b>Szia</b>")); + assert!(hu.html.contains(r#"href="https://sorsfonalak.test/meghivo/abc""#)); + assert!(hu.html.contains("display:none")); + assert_eq!( + hu.unsubscribe_post_url.as_deref(), + Some("https://sorsfonalak.test/api/v1/public/invitations/unsubscribe?token=abc") + ); + + let mut anonymous = invitation_payload(); + anonymous["inviter_name"] = Value::Null; + anonymous["message"] = Value::Null; + let en = render("invitation", "en", &anonymous).unwrap(); + assert_eq!(en.subject, "You are invited to Sorsfonalak"); + assert!(en.text.contains("valid until 17 December 2026") && !en.text.contains("> ")); + assert!(!en.html.contains("border-left")); + + let mut broken = invitation_payload(); + broken["unsubscribe_url"] = Value::Null; + assert_eq!(render("invitation", "hu", &broken), Err(TemplateError::MissingField("unsubscribe_url"))); + } + + #[test] + fn dates() { + assert_eq!(date(Lang::Hu, "2027-01-05").as_deref(), Some("2027. január 5.")); + assert_eq!(date(Lang::En, "2027-01-05T10:00:00Z").as_deref(), Some("5 January 2027")); + assert_eq!(date(Lang::Hu, "2027-13-05"), None); + } +} diff --git a/deploy/.env.example b/deploy/.env.example index be217e1..93915f8 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -10,9 +10,13 @@ GOOGLE_CLIENT_IDS= # These accounts become admins at their first login BOOTSTRAP_ADMIN_EMAILS= -# Outgoing mail, e.g. smtps://user:password@smtp.example.com:465 -SMTP_URL= -MAIL_FROM=Sorsfonalak +# Outgoing mail: Amazon SES (docs/levelkuldes.md). The credentials go to .env.secrets: +# SES_SMTP_USERNAME + SES_SMTP_PASSWORD, or AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY. +SES_REGION=eu-central-1 +MAIL_FROM=Sorsfonalak + +# invite: new accounts need an invitation (default); open: anyone can sign up +SIGNUP_MODE=invite # Image version; every deployment rewrites it TAG=latest diff --git a/deploy/Caddyfile b/deploy/Caddyfile index 2cc5dbe..031494c 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -11,12 +11,8 @@ } {$DOMAIN} { - # Temporary gate until launch (user sf, password sf). Remove this block to open the site. - # The privacy policy stays public (Google's OAuth consent screen links to it). - @gated not path /adatvedelem /_next/static/* /favicon.ico /icon* - basic_auth @gated { - sf $2a$14$oggzzuNO41uGS5M.TCMlB.bQ6fdXUHtNLx9XahWyKLHjRlpEP1XN6 - } + # No basic auth any more: the site is open, and new accounts need an + # invitation (SIGNUP_MODE=invite in the backend). encode zstd gzip reverse_proxy frontend:3000 } diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 040a095..094a427 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -89,6 +89,8 @@ services: MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true} FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0} UNLIMITED_DAILY_LIMIT: ${UNLIMITED_DAILY_LIMIT:-5} + # invite: new accounts need an invitation (admin page "Meghívók"); open: anyone. + SIGNUP_MODE: ${SIGNUP_MODE:-invite} depends_on: postgres: condition: service_healthy @@ -102,8 +104,10 @@ services: image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest} environment: DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak - SMTP_URL: ${SMTP_URL:-} - MAIL_FROM: ${MAIL_FROM:-} + # 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} + MAIL_FROM: ${MAIL_FROM:-Sorsfonalak } PUBLIC_BASE_URL: https://${DOMAIN} env_file: - path: .env.secrets diff --git a/docker-compose.yml b/docker-compose.yml index fb9d433..d9c04bc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -57,6 +57,8 @@ services: MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true} FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0} UNLIMITED_DAILY_LIMIT: ${UNLIMITED_DAILY_LIMIT:-5} + # invite: new accounts need an invitation (admin page "Meghívók"); open: anyone. + SIGNUP_MODE: ${SIGNUP_MODE:-invite} depends_on: postgres: condition: service_healthy diff --git a/docs/levelkuldes.md b/docs/levelkuldes.md new file mode 100644 index 0000000..d643cf0 --- /dev/null +++ b/docs/levelkuldes.md @@ -0,0 +1,95 @@ +# 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”). + +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. + +A SES ára 1000 levelenként 0,10 USD; a mi forgalmunknál ez havi néhány cent. + +## 1. Régió és domain (SES konzol) + +1. **Régió:** `eu-central-1` (Frankfurt), hogy az adatok az EU-ban maradjanak. Minden lépést ebben a régióban kell elvégezni, mert a SES-beállítások régiónként külön élnek. +2. *Configuration → Identities → Create identity → Domain*: `sorsfonalak.hu`. + - **Easy DKIM**, RSA 2048 bit. A SES három CNAME-rekordot ad (lásd 3. pont). + - **Custom MAIL FROM domain:** `mail.sorsfonalak.hu`, és *Behavior on MX failure*: *Use default MAIL FROM domain*. Ettől az SPF is a saját domainünkre szól, ami a DMARC-nál számít. Ehhez egy MX- és egy TXT-rekord kell. +3. A domain igazolása után bármelyik `@sorsfonalak.hu` cím lehet feladó. Javaslat: `hello@sorsfonalak.hu`. A `noreply` cím a szűrőknél rosszabb, és válaszolni sem lehet rá. + +## 2. Kilépés a homokozóból (sandbox) + +Új SES-fiók homokozóban indul. Ilyenkor: +- csak igazolt címekre lehet küldeni (*Identities → Create identity → Email address*; teszteléshez a saját címed elég); +- naponta legfeljebb 200 levél megy ki. + +Meghívót idegen címre csak éles hozzáféréssel lehet küldeni: *Account dashboard → Request production access*. Az AWS kézzel bírálja el, általában egy napon belül. A kérésben érdemes leírni: +- tranzakciós levelek (megerősítés, értesítés) és meghívók egy zártkörű oldalra; +- meghívót csak az admin küld, személyesen ismert embereknek, kis mennyiségben; +- minden meghívóban egykattintásos leiratkozás van, a leiratkozott címekre többé nem megy levél; +- a visszapattanó és panaszos címeket a SES fiókszintű tiltólistája kezeli (*Suppression list*: bounces és complaints). + +Fontos: ha a visszapattanási arány 5%, vagy a panaszarány 0,1% fölé megy, az AWS felfüggesztheti a küldést. Ezért csak olyan címre küldj meghívót, amelyről tudod, hogy él. + +## 3. DNS a Cloudflare-en + +| Típus | Név | Tartalom | +|---|---|---| +| CNAME ×3 | `._domainkey` | `.dkim.amazonses.com` (a SES konzol kiírja mindhármat) | +| MX | `mail` | `feedback-smtp.eu-central-1.amazonses.com`, prioritás 10 | +| TXT | `mail` | `v=spf1 include:amazonses.com ~all` | +| TXT | `_dmarc` | `v=DMARC1; p=none; rua=mailto:` | + +- Minden rekord **DNS only** (szürke felhő) legyen; a proxyzott CNAME-mel a DKIM nem működik. +- DMARC: induláskor `p=none` (csak jelentés). Ha pár hétig minden levél átmegy, szigorítható `p=quarantine`-ra. +- Ha a `hello@sorsfonalak.hu` címre érkező válaszokat is olvasni szeretnéd: a Cloudflare *Email Routing* ingyen továbbítja őket a Gmailedre. Ez a fő domainre (`sorsfonalak.hu`) tesz MX- és SPF-rekordot, ami nem ütközik a `mail.` aldomain rekordjaival. + +## 4. Hozzáférés + +Két út van, mindkettő a szerver `.env.secrets` fájljába kerül (kis- vagy nagybetűvel is jó): + +- **SMTP-hozzáférés** (*SMTP settings → Create SMTP credentials*): egy IAM-felhasználó, amely csak levelet küldhet. + ``` + SES_SMTP_USERNAME=AKIA... + SES_SMTP_PASSWORD=... + ``` +- **IAM-kulcspár**, amelynek van `ses:SendRawEmail` joga: + ``` + AWS_ACCESS_KEY_ID=AKIA... + AWS_SECRET_ACCESS_KEY=... + ``` + Más nevek is jók: a kulcsnál `SES_AUTH_KEY`, `SES_ACCESS_KEY`, `SES_KEY`, `AUTH_KEY`, a titoknál `SES_SECRET`, `SES_SECRET_KEY`, `AWS_SECRET`, `AUTH_SECRET` (a teljes lista: `services/worker/src/ses.rs`). + A worker ebből az AWS által leírt módon kiszámolja az SMTP-jelszót. Ha az `AWS_SECRET_ACCESS_KEY` helyére az SMTP-jelszót írtad, azt is felismeri, és változatlanul használja. + +A régió alapból `eu-central-1` (Frankfurt); felülírható a `SES_REGION` változóval. A port 2587, ezt a `SES_SMTP_PORT` írja felül. URL-kódolásra itt nincs szükség, mert a worker maga állítja össze a címet. + +## 5. Tűzfal + +A DigitalOcean a dropleteken tiltja a szokásos kimenő SMTP-portokat (25, 465, 587). A SES erre a **2587**-es portot (STARTTLS) is kínálja. + +A droplet saját tűzfala (`sorsfonalak-fw`, DigitalOcean → Networking → Firewalls) a kimenő forgalmat is szűri. Az **Outbound rules** közé fel kell venni a **TCP 2587**-et (cél: All IPv4, All IPv6), különben a worker nem éri el a SES-t. + +## 6. Indítás + +- A `.env` fájlban opcionális: `MAIL_FROM=Sorsfonalak ` (ez az alapérték is). +- Utána: `docker compose up -d worker`. A naplóban ennek kell megjelennie: `e-mail delivery enabled`, `via=Amazon SES eu-central-1:2587, credentials from …`. +- Az eddig várakozó levelek ekkor kimennek. Ha ezt nem szeretnéd, előtte töröld őket: `DELETE FROM email_outbox WHERE sent_at IS NULL;`. +- Hibaüzenetek a naplóban: + - `535 Authentication Credentials Invalid`: hibás kulcs, vagy az IAM-felhasználónak nincs `ses:SendRawEmail` joga; + - `554 Message rejected: Email address is not verified`: a fiók még homokozóban van, és a címzett nincs igazolva; + - időtúllépés: a tűzfalon nincs engedélyezve a kimenő 2587-es port. +- Ha mégis kész SMTP-címet adnál meg, az `SMTP_URL` mindig elsőbbséget élvez a SES-változókkal szemben. + +## 7. Próba + +1. Admin → Meghívók → **Teszt küldése magamnak**: megérkezik-e, és nem a spamben van-e. +2. A Gmailben a levélnél *⋮ → Eredeti megjelenítése*: az SPF, a DKIM és a DMARC mellett is `PASS` álljon. +3. A [mail-tester.com](https://www.mail-tester.com) ad egy egyszeri címet. Küldj rá meghívót az admin oldalról (utána vond vissza), és nézd meg a pontszámot; 9/10 fölött jó. Ehhez már éles hozzáférés kell. + +## Amit a kód már elintéz + +- HTML és szöveges változat ugyanazzal a tartalommal. Egyhasábos, képek és követés nélkül, minden link a saját domainre mutat. +- `List-Unsubscribe` és `List-Unsubscribe-Post` (RFC 8058): a Gmail és a többi levelező saját „Leiratkozás” gombot mutat. Aki leiratkozik, annak a címére soha többé nem megy meghívó (`email_optouts`, csak a cím hash-e). +- A worker saját domaines `Message-ID`-t tesz a levélre. A SES ezt a sajátjára cseréli, ami rendben van. +- Meghívót csak admin küldhet. Egy meghívó legfeljebb háromszor megy ki, 24 óránként egyszer. A személyes üzenet legfeljebb 300 karakter, és nem lehet benne link. + +## Később + +A visszapattanásokról és panaszokról a SES utólag, SNS-értesítésben szól; az SMTP-kapcsolat ezt nem jelzi. Ha lesz forgalom, érdemes bekötni egy SNS → backend webhookot. Ez a meghívólistán megjelölné a visszapattant címeket, és a panaszt tevőket a leiratkozottak közé tenné. diff --git a/services/backend/Cargo.toml b/services/backend/Cargo.toml index 4ba6e9f..28871b1 100644 --- a/services/backend/Cargo.toml +++ b/services/backend/Cargo.toml @@ -9,6 +9,7 @@ publish.workspace = true [dependencies] db.workspace = true analysis-prompt.workspace = true +email-templates.workspace = true horoscope-client.workspace = true service-kit.workspace = true anyhow.workspace = true diff --git a/services/backend/README.md b/services/backend/README.md index 5970d43..e304c95 100644 --- a/services/backend/README.md +++ b/services/backend/README.md @@ -17,6 +17,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh | `MOCK_PAYMENTS` | `false` | próbafizetés a Stripe bekötéséig: a `POST /v1/payments/mock` `{"package": ""}` azonnal jóváírja a katalógus egy csomagját (`{"unit": "natal"}` rövidítés: a legkisebb ilyen csomag); a compose-fájlokban egyelőre `true` | | `FREE_PERSON_SLOTS` | `0` | ennyi személyt vehet fel csomag nélkül egy felhasználó | | `UNLIMITED_DAILY_LIMIT` | `5` | a Korlátlan csomaggal naponta ennyi új részletes elemzés kérhető (méltányos használat; utána 429 `fair_use_limit`) | +| `SIGNUP_MODE` | `invite` | `invite`: új fiók csak meghívóval jön létre (403 `not_invited`); `open`: bárki regisztrálhat | | `GOOGLE_CLIENT_IDS` | – | Google OAuth kliens-azonosító(k); üresen a Google-belépés ki van kapcsolva | | `BOOTSTRAP_ADMIN_EMAILS` | – | ezek a címek regisztrációkor vagy belépéskor admin szerepet kapnak (így lesz meg az első admin) | | `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett | @@ -36,6 +37,12 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh - **Google:** a frontend a Google Identity Services gombbal vagy a One Tap felülettel szerez ID tokent, és elküldi a `POST /v1/auth/google` végpontra. A backend Google kulcsaival ellenőrzi az aláírást, a kiállítót és a kliens-azonosítót. - Ismeretlen Google-fióknál, ha a Google által igazolt e-mail-címmel már van felhasználó, ahhoz kapcsolja; ha nincs, újat hoz létre. - Ugyanaz a felhasználó több belépési móddal is rendelkezhet (`auth_identities`). A Facebook, az Apple és a passkey ugyanígy adható hozzá. +- **Meghívásos regisztráció** (`SIGNUP_MODE=invite`): új fiók (Google vagy jelszó) akkor jön létre, ha + - a címre szól élő meghívó (`invitations`), vagy + - a kérés a meghívólink tokenjét hozza (`invite_token`): ilyenkor bármelyik cím jó, mert sokan nem azzal a Google-fiókkal lépnek be, amelyiket az ismerősük tudja; a meghívó ezzel elfogy; + - vagy egy élő „Mennyire illünk össze?” link tokenjét hozza, illetve a cím a `BOOTSTRAP_ADMIN_EMAILS` listában van. + + Meglévő felhasználók belépése nem változik. Meghívót csak admin küld; a levelet a worker kézbesíti (`invitation` sablon). Minden küldés új linket ad, de a korábbi linkek is élnek, amíg a meghívó nyitott (`invitation_tokens`). A leiratkozott címekre nem megy több meghívó (`email_optouts`, csak hash). Lásd még `docs/levelkuldes.md`. - **Szerepek** (`users.roles`, tömb): `user` (alap), `creator` (cikkírás, 2. fázis), `premium` és `vip` (jelenleg nincs hozzájuk funkció; a fizetős elemzés egységekkel megy), `admin`. - **Guardok:** - `AuthUser`: belépés kell (401); @@ -47,11 +54,11 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh | Végpont | Guard | Leírás | |---|---|---| -| `GET /v1/config` | – | Google kliens-azonosító, `password_login`, nyelvek, elemző és összefoglaló modell | +| `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?}` → munkamenet; megerősítő e-mailt küld | +| `POST /v1/auth/register` | – | `{email, password, display_name?, locale?, invite_token?}` → munkamenet; megerősítő e-mailt küld | | `POST /v1/auth/login` | – | `{email, password}` | -| `POST /v1/auth/google` | – | `{id_token}`; `created: true`, ha most jött létre a fiók | +| `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 | | @@ -79,6 +86,13 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh | `PATCH /v1/admin/users/{id}` | admin | `{roles: [...]}`; a saját admin szerep nem vehető el | | `POST /v1/admin/users/{id}/packages` | admin | `{package, note?}`: csomag kiosztása ajándékként (`package_orders`, ár 0) | | `POST /v1/admin/users/{id}/credits` | admin | `{unit: natal\|synastry, delta, note?}`: elemzések jóváírása vagy levonása | +| `GET`/`POST /v1/admin/invitations` | admin | lista (állapot, az utolsó levél állapota, várólista); új: `{emails: [...], message?, locale?}`, címenként `invited` (linkkel), `invalid`, `already_user`, `already_invited` vagy `opted_out` | +| `POST /v1/admin/invitations/{id}/resend`, `DELETE …/{id}` | admin | újraküldés új linkkel és újabb 30 nappal (legfeljebb 3 küldés, 24 óránként); visszavonás | +| `POST /v1/admin/invitations/preview` | admin | `{message?, locale?, send_to_me?}`: a meghívólevél HTML- és szöveges változata mintalinkekkel; kérésre tesztpéldány az adminnak | +| `DELETE /v1/admin/waitlist/{email}` | admin | törlés a várólistáról | +| `GET /v1/public/invitations/{token}` | – | a meghívó adatai a belépőoldalnak (ki hívott, üzenet, állapot) | +| `POST /v1/public/invitations/unsubscribe?token=` | – | „Nem kérek több meghívót”: a lábléc linkjéről és a levelezők egykattintásos gombjáról (RFC 8058) | +| `POST /v1/public/waitlist` | – | `{email, locale?}`; mindig 202, nem árulja el, kinek van fiókja | | `GET /v1/admin/prompts` | admin | a tömör és a részletes elemzés system promptja nyelvenként: érvényes szöveg, alapértelmezett, változatok | | `PUT /v1/admin/prompts/{kind}/{language}` | admin | `{system}` új változatként menti (`null` vagy az alapértelmezett szöveg: vissza a beépítettre); az új elemzések `prompt_version`-je `v2-r` | | `POST /v1/admin/prompts/{kind}/{language}/preview` | admin | `{system, chart_id}`: próbafuttatás a (mentetlen) szöveggel egy saját képleten; nem kerül a képlethez, nem gyorsítótárazott, nem fogy egység; egyszerre legfeljebb 3 | @@ -124,5 +138,5 @@ A [worker](../worker/README.md) kiküldi az e-maileket, megírja az elemzéseket ## Korlátok - **Saját születési adatok módosítása:** az első mentés után egy órán belül még háromszor javíthatók, utána naponta egyszer (`birth_data_changes` tábla). A tiltott módosítás 429-et ad `birth_data_change_limit` kóddal, a felhasználónak szóló üzenettel („A rendszer csak napi egy módosítást engedélyez. …”). A `/v1/me` `birth_change` mezője mutatja, él-e a napi korlát. Más emberek képleteit ez nem érinti. -- **Személyek** (más emberek képletei, `charts.kind = 'person'`): minden új személy egy `person` egységet használ (`credit_ledger`, `reason = 'person'`); a törlés nem adja vissza. Helyet a csomagok adnak; korlátlan az `unlimited_persons` jogosultsággal és futó Korlátlan csomaggal. Ha elfogyott, 409 `person_limit_reached`. Egy személy születési adatai a felvétel után egy órán belül javíthatók (`PATCH /v1/charts/{id}` `birth` mezővel), utána 409 `person_locked`. Részletes elemzés (képlet vagy összevetés) után sem (409 `person_analysed`), és akkor sem, ha valaki más összevetésében szerepel (409 `person_in_synastry`); a saját, elemzés nélküli összevetései a javításkor törlődnek. A `/v1/me` `persons` mezője: `used`, `limit`, `left`, `unlimited`. +- **Személyek** (más emberek képletei, `charts.kind = 'person'`): minden új személy egy `person` egységet használ (`credit_ledger`, `reason = 'person'`); a törlés nem adja vissza. Helyet a csomagok adnak; korlátlan az `unlimited_persons` jogosultsággal és futó Korlátlan csomaggal. Ha elfogyott, 409 `person_limit_reached`. Egy személy születési adatai a felvétel után egy órán belül javíthatók (`PATCH /v1/charts/{id}` `birth` mezővel), utána 409 `person_locked`. A név (`label`) bármikor változhat; ha a `birth` ugyanaz, mint a tárolt (vagy ugyanazt a képletet adja), nincs újraszámolás, és az elemzések, összevetések maradnak. Részletes elemzés (képlet vagy összevetés) után sem (409 `person_analysed`), és akkor sem, ha valaki más összevetésében szerepel (409 `person_in_synastry`); a saját, elemzés nélküli összevetései a javításkor törlődnek. A `/v1/me` `persons` mezője: `used`, `limit`, `left`, `unlimited`. - **Admin:** nincs módosítási korlát, korlátlan személy, a személyek adatai bármikor javíthatók, és a részletes elemzés ingyenes (nem fogy egység). diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs index 12211c7..b3b280c 100644 --- a/services/backend/src/config.rs +++ b/services/backend/src/config.rs @@ -2,6 +2,24 @@ use anyhow::{Context, bail}; +/// Who may create an account. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SignupMode { + /// Anyone. + Open, + /// Only invited addresses (or the holder of an invitation link). + Invite, +} + +impl SignupMode { + pub fn as_str(self) -> &'static str { + match self { + SignupMode::Open => "open", + SignupMode::Invite => "invite", + } + } +} + #[derive(Debug, Clone)] pub struct Config { /// `DATABASE_URL` (required). @@ -51,6 +69,9 @@ pub struct Config { pub free_person_slots: i64, /// `UNLIMITED_DAILY_LIMIT` (default 5): new detailed analyses a day with the unlimited package. pub unlimited_daily_limit: i64, + /// `SIGNUP_MODE` (`invite` or `open`, default `invite`): whether new + /// accounts need an invitation. + pub signup_mode: SignupMode, } fn var(name: &str) -> Option { @@ -106,6 +127,11 @@ impl Config { max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?, free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?, unlimited_daily_limit: parsed("UNLIMITED_DAILY_LIMIT", 5)?, + signup_mode: match var("SIGNUP_MODE").as_deref() { + None | Some("invite") => SignupMode::Invite, + Some("open") => SignupMode::Open, + Some(other) => bail!("invalid SIGNUP_MODE '{other}': use 'invite' or 'open'"), + }, }; if config.session_ttl_days < 1 { bail!("SESSION_TTL_DAYS must be at least 1"); @@ -136,6 +162,7 @@ impl Config { max_charts_per_user: 50, free_person_slots: 5, unlimited_daily_limit: 3, + signup_mode: SignupMode::Open, } } } diff --git a/services/backend/src/error.rs b/services/backend/src/error.rs index b89e144..9137c14 100644 --- a/services/backend/src/error.rs +++ b/services/backend/src/error.rs @@ -16,6 +16,9 @@ pub enum ApiError { InvalidCredentials(String), #[error("{0}")] Forbidden(String), + /// Refused, with a code the frontend acts on (e.g. `not_invited`). + #[error("{message}")] + Refused { code: &'static str, message: String }, #[error("{0} not found")] NotFound(&'static str), #[error("{message}")] @@ -51,6 +54,7 @@ impl ApiError { ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"), ApiError::InvalidCredentials(_) => (StatusCode::UNAUTHORIZED, "invalid_credentials"), ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"), + ApiError::Refused { code, .. } => (StatusCode::FORBIDDEN, code), ApiError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"), ApiError::Conflict { code, .. } => (StatusCode::CONFLICT, code), ApiError::Gone(_) => (StatusCode::GONE, "gone"), diff --git a/services/backend/src/routes/auth.rs b/services/backend/src/routes/auth.rs index d5e2225..9ac9888 100644 --- a/services/backend/src/routes/auth.rs +++ b/services/backend/src/routes/auth.rs @@ -113,16 +113,28 @@ async fn consume_token(conn: &mut PgConnection, token: &str, purpose: &str) -> R row.map(|(id,)| id).ok_or(ApiError::InvalidToken) } -/// Queues an e-mail for the worker. +/// Queues an e-mail to a user for the worker. pub async fn queue_email(conn: &mut PgConnection, user: &User, template: &str, payload: Value) -> Result<(), ApiError> { + queue_email_to(conn, Some(user.id), &user.email, template, &user.locale, payload).await +} + +/// Queues an e-mail to any address (e.g. an invitation) for the worker. +pub async fn queue_email_to( + conn: &mut PgConnection, + user_id: Option, + to: &str, + template: &str, + locale: &str, + payload: Value, +) -> Result<(), ApiError> { sqlx::query( "INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)", ) .bind(Uuid::now_v7()) - .bind(user.id) - .bind(&user.email) + .bind(user_id) + .bind(to) .bind(template) - .bind(&user.locale) + .bind(locale) .bind(payload) .execute(conn) .await?; @@ -156,6 +168,8 @@ pub struct RegisterRequest { password: String, display_name: Option, locale: Option, + /// The invitation link's token, while sign-up needs an invitation. + invite_token: Option, } /// Password endpoints answer 403 while `PASSWORD_LOGIN` is off. @@ -185,6 +199,7 @@ pub async fn register( if exists.is_some() { return Err(ApiError::conflict("email_taken", "an account with this e-mail address already exists")); } + 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) @@ -201,6 +216,7 @@ pub async fn register( .bind(&email) .execute(&mut *tx) .await?; + super::invitations::mark_accepted(&mut tx, user_id, &email, req.invite_token.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?; @@ -266,6 +282,8 @@ pub async fn login( pub struct GoogleRequest { /// ID token (JWT) from Google Identity Services. id_token: String, + /// The invitation link's token, while sign-up needs an invitation. + invite_token: Option, } /// Logs in with Google. An unknown Google account is linked to the existing @@ -311,6 +329,7 @@ pub async fn google( (id, false) } None => { + super::invitations::admit(&state, &mut tx, &email, req.invite_token.as_deref()).await?; let id = Uuid::now_v7(); let locale = claims .locale @@ -328,6 +347,7 @@ pub async fn google( .bind(locale) .execute(&mut *tx) .await?; + super::invitations::mark_accepted(&mut tx, id, &email, req.invite_token.as_deref()).await?; (id, true) } }; diff --git a/services/backend/src/routes/charts.rs b/services/backend/src/routes/charts.rs index 649f076..67fefb4 100644 --- a/services/backend/src/routes/charts.rs +++ b/services/backend/src/routes/charts.rs @@ -267,15 +267,25 @@ pub async fn update( None => chart.label.clone(), }; let is_primary = req.is_primary.unwrap_or(chart.is_primary); - let recalculated = match req.birth { + // The same birth data again (e.g. only the name changed): no recalculation, + // and the analyses and comparisons stay. A new calculation that gives the + // same chart keeps them too. + let birth = req.birth.map(clean_birth).transpose()?.filter(|b| *b != chart.birth_data); + let recalculated = match birth { Some(birth) => Some(corrected_birth(&state, &auth, &chart, birth).await?), None => None, }; + let chart_changed = recalculated.as_ref().is_some_and(|(_, _, hash)| *hash != chart.chart_hash); let mut tx = state.db.begin().await?; if let Some((birth, result, hash)) = &recalculated { - // The old summary, the comparisons (and an admin's analyses) no longer match the chart. - sqlx::query("DELETE FROM analyses WHERE chart_id = $1").bind(id).execute(&mut *tx).await?; - sqlx::query("DELETE FROM synastries WHERE chart1_id = $1 OR chart2_id = $1").bind(id).execute(&mut *tx).await?; + if chart_changed { + // The old summary, the comparisons (and an admin's analyses) no longer match the chart. + sqlx::query("DELETE FROM analyses WHERE chart_id = $1").bind(id).execute(&mut *tx).await?; + sqlx::query("DELETE FROM synastries WHERE chart1_id = $1 OR chart2_id = $1") + .bind(id) + .execute(&mut *tx) + .await?; + } sqlx::query("UPDATE charts SET birth_data = $1, result = $2, chart_hash = $3 WHERE id = $4") .bind(birth) .bind(result) @@ -303,7 +313,7 @@ pub async fn update( birth_changes::record(&mut tx, &auth, id).await?; } tx.commit().await?; - if recalculated.is_some() { + if chart_changed { queue_summary(&state, &auth, &row).await; } Ok(Json(row.owner_view())) diff --git a/services/backend/src/routes/invitations.rs b/services/backend/src/routes/invitations.rs new file mode 100644 index 0000000..9440dd9 --- /dev/null +++ b/services/backend/src/routes/invitations.rs @@ -0,0 +1,547 @@ +//! Invitations to the closed site. +//! +//! While `SIGNUP_MODE=invite`, a new account needs an open invitation for its +//! e-mail address, or an invitation link (then any address will do, because +//! people often sign in with another Google account than the one their friend +//! knows). Only administrators invite; the worker sends the e-mails. +//! +//! People who asked for no more invitations are kept as the hash of their +//! address. People without an invitation can join the waitlist. + +use axum::Json; +use axum::extract::{Path, Query, State}; +use axum::http::StatusCode; +use axum_extra::extract::WithRejection; +use serde::Deserialize; +use serde_json::{Value, json}; +use sqlx::PgConnection; +use time::OffsetDateTime; +use uuid::Uuid; + +use super::auth::{normalize_email, queue_email_to, validate_locale}; +use super::{Body, IdPath, St}; +use crate::AppState; +use crate::auth::AdminUser; +use crate::config::SignupMode; +use crate::error::{ApiError, ApiResult}; +use crate::views::{rfc3339, rfc3339_opt}; + +pub const INVITATION_TTL: time::Duration = time::Duration::days(30); +/// A resend is possible this often, and at most this many sendings in all. +const RESEND_GAP: time::Duration = time::Duration::hours(24); +const MAX_SENDINGS: i32 = 3; +const MAX_MESSAGE_CHARS: usize = 300; +const MAX_BATCH: usize = 50; + +// --- the gate ------------------------------------------------------------------------------- + +/// Whether a new account may be created for `email` (with the invitation link +/// `token`, if the visitor came through one). +pub async fn admit( + state: &AppState, + conn: &mut PgConnection, + email: &str, + token: Option<&str>, +) -> Result<(), ApiError> { + if state.config.signup_mode == SignupMode::Open || state.config.bootstrap_admin_emails.iter().any(|e| e == email) { + return Ok(()); + } + let hash = token.map(|t| db::token_hash(t.trim())); + let invited: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM invitations i WHERE i.accepted_at IS NULL AND i.revoked_at IS NULL \ + AND i.expires_at > now() \ + AND (i.email = $1 OR i.id IN (SELECT invitation_id FROM invitation_tokens WHERE token_hash = $2))) \ + -- a \"how compatible are we?\" link also lets the invitee in + OR EXISTS (SELECT 1 FROM synastry_invites WHERE token_hash = $2 AND accepted_at IS NULL AND expires_at > now())", + ) + .bind(email) + .bind(hash) + .fetch_one(&mut *conn) + .await?; + if invited { + Ok(()) + } else { + Err(ApiError::Refused { + code: "not_invited", + message: "A Sorsfonalak jelenleg meghívásos: ehhez az e-mail-címhez nem tartozik meghívó.".into(), + }) + } +} + +/// After a new account is created: its invitations count as accepted, and it leaves the waitlist. +pub async fn mark_accepted( + conn: &mut PgConnection, + user_id: Uuid, + email: &str, + token: Option<&str>, +) -> Result<(), ApiError> { + let hash = token.map(|t| db::token_hash(t.trim())); + sqlx::query( + "UPDATE invitations SET accepted_at = now(), accepted_by = $1 \ + WHERE accepted_at IS NULL AND revoked_at IS NULL \ + AND (email = $2 OR (expires_at > now() AND id IN (SELECT invitation_id FROM invitation_tokens WHERE token_hash = $3)))", + ) + .bind(user_id) + .bind(email) + .bind(hash) + .execute(&mut *conn) + .await?; + sqlx::query("DELETE FROM waitlist WHERE email = $1").bind(email).execute(&mut *conn).await?; + Ok(()) +} + +// --- sending --------------------------------------------------------------------------------- + +fn clean_message(message: Option) -> Result, ApiError> { + let Some(message) = message.map(|m| m.replace("\r\n", "\n").trim().to_owned()).filter(|m| !m.is_empty()) else { + return Ok(None); + }; + if message.chars().count() > MAX_MESSAGE_CHARS { + return Err(ApiError::BadRequest(format!("A személyes üzenet legfeljebb {MAX_MESSAGE_CHARS} karakter lehet."))); + } + // Links in a mail from our domain are what spammers would use this field for. + let lower = message.to_lowercase(); + if lower.contains("://") || lower.contains("www.") { + return Err(ApiError::BadRequest("A személyes üzenetben nem lehet link.".into())); + } + Ok(Some(message)) +} + +fn links(state: &AppState, token: &str) -> (String, String, String) { + let base = &state.config.public_base_url; + ( + format!("{base}/meghivo/{token}"), + format!("{base}/leiratkozas?token={token}"), + format!("{base}/api/v1/public/invitations/unsubscribe?token={token}"), + ) +} + +fn payload( + state: &AppState, + token: &str, + inviter: Option<&str>, + message: Option<&str>, + expires: OffsetDateTime, +) -> Value { + let (url, unsubscribe_url, unsubscribe_post_url) = links(state, token); + json!({ + "url": url, + "unsubscribe_url": unsubscribe_url, + "unsubscribe_post_url": unsubscribe_post_url, + "inviter_name": inviter, + "message": message, + "expires_on": expires.date().to_string(), + }) +} + +/// Issues a new link token for an invitation and queues the e-mail; returns the link. +#[allow(clippy::too_many_arguments)] +async fn send( + state: &AppState, + conn: &mut PgConnection, + id: Uuid, + email: &str, + locale: &str, + inviter: Option<&str>, + message: Option<&str>, + expires: OffsetDateTime, +) -> Result { + let token = db::new_token(); + sqlx::query("INSERT INTO invitation_tokens (token_hash, invitation_id) VALUES ($1, $2)") + .bind(db::token_hash(&token)) + .bind(id) + .execute(&mut *conn) + .await?; + let payload = payload(state, &token, inviter, message, expires); + let url = payload["url"].as_str().unwrap_or_default().to_owned(); + queue_email_to(conn, None, email, "invitation", locale, payload).await?; + Ok(url) +} + +async fn opted_out(conn: &mut PgConnection, email: &str) -> Result { + Ok(sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM email_optouts WHERE email_hash = $1)") + .bind(db::token_hash(email)) + .fetch_one(conn) + .await?) +} + +// --- admin ------------------------------------------------------------------------------------ + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CreateInvitations { + emails: Vec, + message: Option, + locale: Option, +} + +/// Invites a list of addresses. Each gets a result: `invited` (with the +/// link, to pass on by hand if needed), `already_user`, `already_invited`, +/// `opted_out` or `invalid`. +pub async fn create( + State(state): St, + AdminUser(admin): AdminUser, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + if req.emails.is_empty() || req.emails.len() > MAX_BATCH { + return Err(ApiError::BadRequest(format!("1–{MAX_BATCH} e-mail-cím adható meg egyszerre."))); + } + let message = clean_message(req.message)?; + let locale = validate_locale(&state, req.locale.as_deref())?; + let inviter = admin.user.display_name.clone(); + let mut results = Vec::new(); + let mut seen = std::collections::HashSet::new(); + let mut tx = state.db.begin().await?; + for raw in &req.emails { + let raw = raw.trim(); + let Ok(email) = normalize_email(raw) else { + results.push(json!({ "email": raw, "status": "invalid" })); + continue; + }; + if !seen.insert(email.clone()) { + continue; + } + let user: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM users WHERE email = $1)") + .bind(&email) + .fetch_one(&mut *tx) + .await?; + if user { + results.push(json!({ "email": email, "status": "already_user" })); + continue; + } + if opted_out(&mut tx, &email).await? { + results.push(json!({ "email": email, "status": "opted_out" })); + continue; + } + // An expired open invitation gives way to the new one. + sqlx::query( + "UPDATE invitations SET revoked_at = now() \ + WHERE email = $1 AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at <= now()", + ) + .bind(&email) + .execute(&mut *tx) + .await?; + let id = Uuid::now_v7(); + let expires = OffsetDateTime::now_utc() + INVITATION_TTL; + let inserted = sqlx::query( + "INSERT INTO invitations (id, email, message, locale, invited_by, expires_at) \ + VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING", + ) + .bind(id) + .bind(&email) + .bind(&message) + .bind(&locale) + .bind(admin.id()) + .bind(expires) + .execute(&mut *tx) + .await? + .rows_affected(); + if inserted == 0 { + results.push(json!({ "email": email, "status": "already_invited" })); + continue; + } + let url = send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires).await?; + results.push(json!({ "email": email, "status": "invited", "id": id, "url": url })); + } + tx.commit().await?; + Ok((StatusCode::CREATED, Json(json!({ "results": results })))) +} + +#[derive(sqlx::FromRow)] +struct Row { + id: Uuid, + email: String, + message: Option, + locale: String, + created_at: OffsetDateTime, + expires_at: OffsetDateTime, + sent_count: i32, + last_sent_at: OffsetDateTime, + accepted_at: Option, + revoked_at: Option, + invited_by_name: Option, + accepted_by_name: Option, + mail_created_at: Option, + mail_sent_at: Option, + mail_failed_at: Option, + mail_error: Option, +} + +fn status(accepted: Option, revoked: Option, expires: OffsetDateTime) -> &'static str { + if accepted.is_some() { + "accepted" + } else if revoked.is_some() { + "revoked" + } else if expires <= OffsetDateTime::now_utc() { + "expired" + } else { + "pending" + } +} + +/// Every invitation (newest first) with the state of its last e-mail, and the waitlist. +pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult> { + let rows: Vec = sqlx::query_as( + "SELECT i.id, i.email, i.message, i.locale, i.created_at, i.expires_at, i.sent_count, i.last_sent_at, \ + i.accepted_at, i.revoked_at, inv.display_name AS invited_by_name, \ + coalesce(acc.display_name, acc.email) AS accepted_by_name, \ + m.created_at AS mail_created_at, m.sent_at AS mail_sent_at, m.failed_at AS mail_failed_at, m.last_error AS mail_error \ + FROM invitations i \ + LEFT JOIN users inv ON inv.id = i.invited_by \ + LEFT JOIN users acc ON acc.id = i.accepted_by \ + LEFT JOIN LATERAL (SELECT created_at, sent_at, failed_at, last_error FROM email_outbox \ + WHERE to_email = i.email AND template = 'invitation' \ + ORDER BY created_at DESC LIMIT 1) m ON true \ + ORDER BY i.created_at DESC LIMIT 500", + ) + .fetch_all(&state.db) + .await?; + let now = OffsetDateTime::now_utc(); + let invitations: Vec = rows + .into_iter() + .map(|r| { + let status = status(r.accepted_at, r.revoked_at, r.expires_at); + // Sent e-mails are removed from the outbox after a week. + let mail = match (r.mail_created_at, r.mail_sent_at, r.mail_failed_at) { + (None, _, _) => "archived", + (_, Some(_), _) => "sent", + (_, None, Some(_)) => "failed", + _ => "queued", + }; + let can_resend = matches!(status, "pending" | "expired") + && r.sent_count < MAX_SENDINGS + && r.last_sent_at + RESEND_GAP <= now; + json!({ + "id": r.id, "email": r.email, "message": r.message, "locale": r.locale, "status": status, + "created_at": rfc3339(r.created_at), "expires_at": rfc3339(r.expires_at), + "sent_count": r.sent_count, "last_sent_at": rfc3339(r.last_sent_at), + "accepted_at": rfc3339_opt(r.accepted_at), "accepted_by": r.accepted_by_name, + "invited_by": r.invited_by_name, + "mail": mail, "mail_error": r.mail_error, "can_resend": can_resend, + }) + }) + .collect(); + + let waitlist: Vec<(String, String, OffsetDateTime, Option)> = sqlx::query_as( + "SELECT w.email, w.locale, w.created_at, \ + (SELECT CASE WHEN accepted_at IS NOT NULL THEN 'accepted' WHEN expires_at > now() THEN 'pending' END \ + FROM invitations WHERE email = w.email AND revoked_at IS NULL ORDER BY created_at DESC LIMIT 1) \ + FROM waitlist w ORDER BY w.created_at", + ) + .fetch_all(&state.db) + .await?; + let waitlist: Vec = waitlist + .into_iter() + .map(|(email, locale, created, invitation)| { + json!({ "email": email, "locale": locale, "created_at": rfc3339(created), "invitation": invitation }) + }) + .collect(); + Ok(Json( + json!({ "invitations": invitations, "waitlist": waitlist, "signup_mode": state.config.signup_mode.as_str() }), + )) +} + +/// Sends the invitation again with a new link (the earlier links keep +/// working), and gives it another 30 days. +pub async fn resend( + State(state): St, + AdminUser(admin): AdminUser, + WithRejection(Path(id), _): IdPath, +) -> ApiResult> { + let mut tx = state.db.begin().await?; + #[derive(sqlx::FromRow)] + struct Open { + email: String, + message: Option, + locale: String, + sent_count: i32, + last_sent_at: OffsetDateTime, + closed: bool, + } + let Open { email, message, locale, sent_count, last_sent_at: last_sent, closed } = sqlx::query_as( + "SELECT email, message, locale, sent_count, last_sent_at, \ + accepted_at IS NOT NULL OR revoked_at IS NOT NULL AS closed \ + FROM invitations WHERE id = $1 FOR UPDATE", + ) + .bind(id) + .fetch_optional(&mut *tx) + .await? + .ok_or(ApiError::NotFound("invitation"))?; + if closed { + return Err(ApiError::conflict("invitation_closed", "Ezt a meghívót már elfogadták vagy visszavonták.")); + } + if sent_count >= MAX_SENDINGS { + return Err(ApiError::conflict( + "resend_limit", + format!("Egy meghívó legfeljebb {MAX_SENDINGS}-szor küldhető el (spamvédelem)."), + )); + } + if last_sent + RESEND_GAP > OffsetDateTime::now_utc() { + return Err(ApiError::conflict("resend_too_soon", "Újraküldés legkorábban 24 órával az előző küldés után.")); + } + if opted_out(&mut tx, &email).await? { + return Err(ApiError::conflict("opted_out", "Ez a cím leiratkozott a meghívókról.")); + } + let expires = OffsetDateTime::now_utc() + INVITATION_TTL; + sqlx::query( + "UPDATE invitations SET sent_count = sent_count + 1, last_sent_at = now(), expires_at = $2 WHERE id = $1", + ) + .bind(id) + .bind(expires) + .execute(&mut *tx) + .await?; + let inviter = admin.user.display_name.clone(); + let url = send(&state, &mut tx, id, &email, &locale, inviter.as_deref(), message.as_deref(), expires).await?; + tx.commit().await?; + Ok(Json(json!({ "id": id, "url": url, "expires_at": rfc3339(expires) }))) +} + +pub async fn revoke(State(state): St, _admin: AdminUser, WithRejection(Path(id), _): IdPath) -> ApiResult { + let done = sqlx::query( + "UPDATE invitations SET revoked_at = now() WHERE id = $1 AND accepted_at IS NULL AND revoked_at IS NULL", + ) + .bind(id) + .execute(&state.db) + .await? + .rows_affected(); + if done == 0 { + return Err(ApiError::NotFound("open invitation")); + } + Ok(StatusCode::NO_CONTENT) +} + +pub async fn remove_from_waitlist( + State(state): St, + _admin: AdminUser, + WithRejection(Path(email), _): WithRejection, ApiError>, +) -> ApiResult { + sqlx::query("DELETE FROM waitlist WHERE email = $1").bind(email.trim().to_lowercase()).execute(&state.db).await?; + Ok(StatusCode::NO_CONTENT) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PreviewRequest { + message: Option, + locale: Option, + /// Also send it to the admin's own address. + #[serde(default)] + send_to_me: bool, +} + +/// The invitation e-mail with sample links (they lead nowhere), and +/// optionally a test copy to the admin. +pub async fn preview( + State(state): St, + AdminUser(admin): AdminUser, + WithRejection(Json(req), _): Body, +) -> ApiResult> { + let message = clean_message(req.message)?; + let locale = validate_locale(&state, req.locale.as_deref())?; + let payload = payload( + &state, + "minta", + admin.user.display_name.as_deref(), + message.as_deref(), + OffsetDateTime::now_utc() + INVITATION_TTL, + ); + let mail = email_templates::render("invitation", &locale, &payload) + .map_err(|e| ApiError::Internal(format!("invitation template: {e}")))?; + if req.send_to_me { + let mut conn = state.db.acquire().await?; + queue_email_to(&mut conn, Some(admin.id()), &admin.user.email, "invitation", &locale, payload).await?; + } + Ok(Json(json!({ + "subject": mail.subject, "text": mail.text, "html": mail.html, + "sent_to": req.send_to_me.then_some(&admin.user.email), + }))) +} + +// --- public ------------------------------------------------------------------------------------- + +/// Landing data of an invitation link. +pub async fn public_view(State(state): St, Path(token): Path) -> ApiResult> { + #[derive(sqlx::FromRow)] + struct Landing { + inviter: Option, + message: Option, + expires_at: OffsetDateTime, + accepted_at: Option, + revoked_at: Option, + } + let l: Landing = sqlx::query_as( + "SELECT u.display_name AS inviter, i.message, i.expires_at, i.accepted_at, i.revoked_at \ + FROM invitation_tokens t JOIN invitations i ON i.id = t.invitation_id \ + LEFT JOIN users u ON u.id = i.invited_by WHERE t.token_hash = $1", + ) + .bind(db::token_hash(token.trim())) + .fetch_optional(&state.db) + .await? + .ok_or(ApiError::NotFound("invitation"))?; + Ok(Json(json!({ + "inviter_name": l.inviter, + "message": l.message, + "status": status(l.accepted_at, l.revoked_at, l.expires_at), + "expires_at": rfc3339(l.expires_at), + }))) +} + +#[derive(Deserialize)] +pub struct TokenQuery { + token: String, +} + +/// "No more invitations": from the page behind the footer link, or straight +/// from the mail client's unsubscribe button (RFC 8058 one-click POST). +pub async fn unsubscribe( + State(state): St, + WithRejection(Query(q), _): WithRejection, ApiError>, +) -> ApiResult> { + let mut tx = state.db.begin().await?; + let email: Option = sqlx::query_scalar( + "SELECT i.email FROM invitation_tokens t JOIN invitations i ON i.id = t.invitation_id WHERE t.token_hash = $1", + ) + .bind(db::token_hash(q.token.trim())) + .fetch_optional(&mut *tx) + .await?; + let email = email.ok_or(ApiError::NotFound("invitation"))?; + sqlx::query("INSERT INTO email_optouts (email_hash) VALUES ($1) ON CONFLICT DO NOTHING") + .bind(db::token_hash(&email)) + .execute(&mut *tx) + .await?; + sqlx::query( + "UPDATE invitations SET revoked_at = now() WHERE email = $1 AND accepted_at IS NULL AND revoked_at IS NULL", + ) + .bind(&email) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(Json(json!({ "unsubscribed": true }))) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WaitlistRequest { + email: String, + locale: Option, +} + +/// Joins the waitlist. Always answers the same, so it does not reveal who has an account. +pub async fn join_waitlist( + State(state): St, + WithRejection(Json(req), _): Body, +) -> ApiResult<(StatusCode, Json)> { + let email = normalize_email(&req.email)?; + let locale = validate_locale(&state, req.locale.as_deref())?; + sqlx::query( + "INSERT INTO waitlist (email, locale) SELECT $1, $2 \ + WHERE NOT EXISTS (SELECT 1 FROM users WHERE email = $1) \ + AND (SELECT count(*) FROM waitlist) < 10000 \ + ON CONFLICT DO NOTHING", + ) + .bind(&email) + .bind(&locale) + .execute(&state.db) + .await?; + Ok((StatusCode::ACCEPTED, Json(json!({ "ok": true })))) +} diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index d01e11d..4d2bbc1 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -10,6 +10,7 @@ mod admin; mod analyses; mod auth; mod charts; +mod invitations; mod payments; mod prompts; mod shares; @@ -87,11 +88,19 @@ pub fn router(state: Arc) -> Router { // public, no login .route("/v1/public/shares/{slug}", get(shares::public_view)) .route("/v1/public/invites/{token}", get(synastries::public_invite)) + .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)) // administration .route("/v1/admin/users", get(admin::list_users)) .route("/v1/admin/users/{id}", patch(admin::update_user)) .route("/v1/admin/users/{id}/credits", post(admin::adjust_credits)) .route("/v1/admin/users/{id}/packages", post(admin::grant_package)) + .route("/v1/admin/invitations", get(invitations::list).post(invitations::create)) + .route("/v1/admin/invitations/preview", post(invitations::preview)) + .route("/v1/admin/invitations/{id}", delete(invitations::revoke)) + .route("/v1/admin/invitations/{id}/resend", post(invitations::resend)) + .route("/v1/admin/waitlist/{email}", delete(invitations::remove_from_waitlist)) .route("/v1/admin/prompts", get(prompts::list)) .route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save)) .route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview)) @@ -130,6 +139,7 @@ async fn public_config(State(state): St) -> Json { "password_login": c.password_login, "mock_payments": c.mock_payments, "unlimited_daily_limit": c.unlimited_daily_limit, + "signup_mode": c.signup_mode.as_str(), "password_min_length": crate::auth::MIN_PASSWORD_LEN, })) } diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index a6b6bf4..0371b35 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -802,7 +802,8 @@ async fn persons_use_package_slots(pool: PgPool) { .execute(&app.pool) .await .unwrap(); - let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(corrected.clone())).await; + let again = json!({"birth": {"date": "1986-01-03", "time": "10:00", "country": "HU", "place": "Szeged"}}); + let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(again)).await; assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("person_locked"))); let r = app.call("PATCH", &format!("/v1/charts/{}", own["id"].as_str().unwrap()), Some(&anna), Some(corrected)).await; @@ -1068,3 +1069,180 @@ async fn packages_grant_units_and_unlimited(pool: PgPool) { assert_eq!(r.status, StatusCode::PAYMENT_REQUIRED); assert_eq!(app.get("/v1/me", Some(&bela)).await.body["unlimited_until"], Value::Null); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn renaming_a_person_keeps_chart_and_analyses(pool: PgPool) { + let app = TestApp::new(pool.clone()).await; + let anna = app.register("anna@example.com", "Anna").await; + let own = app.chart(&anna, "Saját", true, "1990-03-15").await; + let bela = app.chart(&anna, "Béla", false, "1985-08-02").await; + let id = bela["id"].as_str().unwrap(); + let syn = app.post("/v1/synastries", Some(&anna), json!({"chart1_id": own["id"], "chart2_id": id})).await; + assert_eq!(syn.status, StatusCode::CREATED); + let summaries = || async { + let (n,): (i64,) = sqlx::query_as("SELECT count(*) FROM analyses WHERE chart_id = $1::uuid") + .bind(id) + .fetch_one(&pool) + .await + .unwrap(); + n + }; + assert_eq!(summaries().await, 1); + + // the edit form sends the unchanged birth data with the new name + let same = json!({"label": "Béla bácsi", + "birth": {"date": "1985-08-02", "time": "14:30", "country": "HU", "place": "Szeged"}}); + let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(same.clone())).await; + assert_eq!( + (r.status, &r.body["label"], &r.body["chart_hash"]), + (StatusCode::OK, &json!("Béla bácsi"), &bela["chart_hash"]) + ); + assert_eq!(summaries().await, 1); + let r = app.get(&format!("/v1/synastries/{}", syn.body["id"].as_str().unwrap()), Some(&anna)).await; + assert_eq!(r.status, StatusCode::OK); + + // after the correction window the name can still change + sqlx::query("UPDATE charts SET created_at = now() - interval '2 hours' WHERE id = $1::uuid") + .bind(id) + .execute(&pool) + .await + .unwrap(); + let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(json!({"label": "Béla"}))).await; + assert_eq!((r.status, &r.body["label"]), (StatusCode::OK, &json!("Béla"))); + let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(same)).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); +} + +async fn google_signup(app: &TestApp, sub: &str, email: &str, invite: Option<&str>) -> Response { + app.post( + "/v1/auth/google", + None, + json!({"id_token": google_token(sub, email, GOOGLE_CLIENT), "invite_token": invite}), + ) + .await +} + +fn invite_token(url: &str) -> String { + url.rsplit('/').next().unwrap().to_string() +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn invitation_only_signup(pool: PgPool) { + let app = TestApp::with_config(pool.clone(), |c| c.signup_mode = crate::config::SignupMode::Invite).await; + assert_eq!(app.get("/v1/config", None).await.body["signup_mode"], "invite"); + + // nobody gets in uninvited, except the bootstrap admin + let r = google_signup(&app, "g-x", "stranger@gmail.com", None).await; + assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::FORBIDDEN, Some("not_invited"))); + let admin = app.register("admin@example.com", "Admin").await; + // an existing user (from before the invitation-only times) is not an admin + let user = { + let open = TestApp::new(pool.clone()).await; + open.register("anna@example.com", "Anna").await + }; + + // inviting: duplicates, invalid addresses and existing users are sorted out + let r = app + .post( + "/v1/admin/invitations", + Some(&admin), + json!({"emails": ["Guest@Example.com", "guest@example.com", "nope", "anna@example.com", "kata@example.com"], + "message": "Gyere, nézd meg!"}), + ) + .await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + let statuses: Vec<&str> = + r.body["results"].as_array().unwrap().iter().map(|x| x["status"].as_str().unwrap()).collect(); + assert_eq!(statuses, ["invited", "invalid", "already_user", "invited"]); + let guest_url = r.body["results"][0]["url"].as_str().unwrap().to_string(); + let guest_id = r.body["results"][0]["id"].as_str().unwrap().to_string(); + let guest_token = invite_token(&guest_url); + let r = app.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["guest@example.com"]})).await; + assert_eq!(r.body["results"][0]["status"], "already_invited"); + let r = app + .post( + "/v1/admin/invitations", + Some(&admin), + json!({"emails": ["x@example.com"], "message": "nézd: www.spam.hu"}), + ) + .await; + assert_eq!(r.status, StatusCode::BAD_REQUEST); + assert_eq!(app.get("/v1/admin/invitations", Some(&user)).await.status, StatusCode::FORBIDDEN); + + // the e-mail and the landing page + let (payload,): (Value,) = sqlx::query_as( + "SELECT payload FROM email_outbox WHERE to_email = 'guest@example.com' AND template = 'invitation'", + ) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(payload["url"], guest_url.as_str()); + assert_eq!(payload["inviter_name"], "Admin"); + assert!( + payload["unsubscribe_post_url"].as_str().unwrap().contains("/api/v1/public/invitations/unsubscribe?token=") + ); + let r = app.get(&format!("/v1/public/invitations/{guest_token}"), None).await; + assert_eq!((r.body["inviter_name"].as_str(), r.body["status"].as_str()), (Some("Admin"), Some("pending"))); + + // a resend: not too soon, then with a new link; the old one keeps working + let r = app.post(&format!("/v1/admin/invitations/{guest_id}/resend"), Some(&admin), json!({})).await; + assert_eq!(r.body["error"]["code"], "resend_too_soon"); + sqlx::query("UPDATE invitations SET last_sent_at = now() - interval '25 hours'").execute(&pool).await.unwrap(); + let r = app.post(&format!("/v1/admin/invitations/{guest_id}/resend"), Some(&admin), json!({})).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + assert_ne!(r.body["url"], guest_url.as_str()); + + // the link lets in any Google account, once + let r = google_signup(&app, "g-1", "guests.other.account@gmail.com", Some(&guest_token)).await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + let r = google_signup(&app, "g-2", "third@gmail.com", Some(&guest_token)).await; + assert_eq!(r.body["error"]["code"], "not_invited"); + // the invited address itself gets in without the link + assert_eq!(google_signup(&app, "g-3", "kata@example.com", None).await.status, StatusCode::CREATED); + + // revoked: no entry + let r = app + .post("/v1/admin/invitations", Some(&admin), json!({"emails": ["zoli@example.com", "mari@example.com"]})) + .await; + let zoli_id = r.body["results"][0]["id"].as_str().unwrap().to_string(); + let mari_token = invite_token(r.body["results"][1]["url"].as_str().unwrap()); + assert_eq!( + app.call("DELETE", &format!("/v1/admin/invitations/{zoli_id}"), Some(&admin), None).await.status, + StatusCode::NO_CONTENT + ); + assert_eq!(google_signup(&app, "g-4", "zoli@example.com", None).await.status, StatusCode::FORBIDDEN); + + // unsubscribing (one-click POST): the invitation closes and no new one can be sent + let r = app.call("POST", &format!("/v1/public/invitations/unsubscribe?token={mari_token}"), None, None).await; + assert_eq!(r.status, StatusCode::OK); + assert_eq!(google_signup(&app, "g-5", "mari@example.com", None).await.status, StatusCode::FORBIDDEN); + let r = app.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["MARI@example.com"]})).await; + assert_eq!(r.body["results"][0]["status"], "opted_out"); + + // the waitlist: joining reveals nothing, an invited and accepted address leaves it + for email in ["wait@example.com", "anna@example.com"] { + let r = app.post("/v1/public/waitlist", None, json!({"email": email})).await; + assert_eq!(r.status, StatusCode::ACCEPTED); + } + let list = app.get("/v1/admin/invitations", Some(&admin)).await.body; + assert_eq!(list["waitlist"].as_array().unwrap().len(), 1); + let statuses: Vec<(&str, &str)> = list["invitations"] + .as_array() + .unwrap() + .iter() + .map(|i| (i["email"].as_str().unwrap(), i["status"].as_str().unwrap())) + .collect(); + assert!( + statuses.contains(&("guest@example.com", "accepted")) && statuses.contains(&("zoli@example.com", "revoked")) + ); + app.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["wait@example.com"]})).await; + assert_eq!(google_signup(&app, "g-6", "wait@example.com", None).await.status, StatusCode::CREATED); + assert!(app.get("/v1/admin/invitations", Some(&admin)).await.body["waitlist"].as_array().unwrap().is_empty()); + + // preview and a test copy to the admin + let r = + app.post("/v1/admin/invitations/preview", Some(&admin), json!({"message": "Szia!", "send_to_me": true})).await; + assert_eq!(r.body["subject"], "Admin meghívott a Sorsfonalakra"); + assert!(r.body["html"].as_str().unwrap().contains("Szia!") && r.body["text"].as_str().unwrap().contains("> Szia!")); + assert_eq!(app.outbox_url("admin@example.com", "invitation").await, "https://sorsfonalak.test/meghivo/minta"); +} diff --git a/services/frontend/src/app/adatvedelem/page.tsx b/services/frontend/src/app/adatvedelem/page.tsx index 91e25b9..fa99bae 100644 --- a/services/frontend/src/app/adatvedelem/page.tsx +++ b/services/frontend/src/app/adatvedelem/page.tsx @@ -76,6 +76,21 @@ export default async function PrivacyPage() { A megvásárolt szolgáltatás nyújtása, elszámolás Szerződés teljesítése; számviteli kötelezettség (6. cikk (1) c) + + Meghívott e-mail-címe, a meghívó neve és személyes üzenete + A meghívó elküldése; amíg az oldal zártkörű, csak meghívottak regisztrálhatnak + Jogos érdek (6. cikk (1) f) + + + A várólistán megadott e-mail-cím + Értesítés, ha megnyílik az oldal, vagy meghívót küldünk + Hozzájárulás (6. cikk (1) a) + + + Azok a címek, amelyek leiratkoztak a meghívókról (csak a cím egyirányú lenyomata, hash-e) + Hogy ezekre a címekre ne küldjünk több meghívót + Jogos érdek (6. cikk (1) f) + IP-cím, böngésző adatai, a kérések ideje (szervernaplók) Biztonság, hibakeresés, visszaélések kiszűrése @@ -123,6 +138,10 @@ export default async function PrivacyPage() {
  • Google LLC – bejelentkezés Google-fiókkal.
  • +
  • + Amazon Web Services EMEA SARL (Amazon SES) – a rendszerlevelek és a meghívók kézbesítése; + az Európai Unióban (Frankfurt). +
  • OpenRouter, Inc. és az általa elért modellszolgáltató (jelenleg{" "} Anthropic PBC) – az elemzések megírása, kizárólag a 3. pontban leírt csillagászati @@ -142,6 +161,11 @@ export default async function PrivacyPage() {
  • Fiókod adatait, képleteidet és elemzéseidet a fiókod törléséig.
  • A biztonsági mentésekből a törölt adatok legkésőbb 14 nap után tűnnek el.
  • A szervernaplókat legfeljebb 30 napig őrizzük.
  • +
  • + Az el nem fogadott meghívókat a lejáratuk vagy visszavonásuk után 30 nappal töröljük. A meghívólevelekben + bármikor leiratkozhatsz. +
  • +
  • A várólistán megadott címet a regisztrációdig, vagy amíg nem kéred a törlését.
  • A számlázáshoz szükséges adatokat a számviteli törvény szerinti ideig (8 évig) őrizzük.
  • diff --git a/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx b/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx new file mode 100644 index 0000000..3bcba3a --- /dev/null +++ b/services/frontend/src/app/admin/meghivok/AdminInvitations.tsx @@ -0,0 +1,472 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; + +import { api, errorText } from "@/lib/api"; +import { formatDate } from "@/lib/astro"; +import type { AdminInvitation, InvitationResult, WaitlistEntry } from "@/lib/types"; + +const MAX_MESSAGE = 300; + +const STATUS: Record = { + pending: "Függőben", + accepted: "Elfogadva", + expired: "Lejárt", + revoked: "Visszavonva", +}; + +const MAIL: Record = { + sent: "Elküldve", + queued: "Sorban vár", + failed: "Sikertelen", + archived: "Elküldve (archív)", +}; + +const RESULT: Record = { + invited: "meghívva", + invalid: "érvénytelen cím", + already_user: "már felhasználó", + already_invited: "már van élő meghívója (újraküldés a listában)", + opted_out: "leiratkozott a meghívókról", +}; + +interface ListData { + invitations: AdminInvitation[]; + waitlist: WaitlistEntry[]; + signup_mode: "invite" | "open"; +} + +function CopyLink({ url }: { url: string }) { + const [copied, setCopied] = useState(false); + return ( + + ); +} + +/** Addresses from free text: one per line, or separated by commas, semicolons or spaces. */ +function parseEmails(text: string): string[] { + return text + .split(/[\s,;]+/) + .map((s) => s.trim()) + .filter(Boolean); +} + +export function AdminInvitations() { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + + const load = useCallback(async () => { + try { + setData(await api("/admin/invitations")); + setError(null); + } catch (e) { + setError(errorText(e)); + } + }, []); + + useEffect(() => { + load(); + }, [load]); + + return ( +
    + {data?.signup_mode === "open" && ( +

    + A regisztráció most nyitott (SIGNUP_MODE=open): bárki beléphet, a meghívó csak értesítés. +

    + )} + + {error && ( +

    + {error} +

    + )} + {data && } + {data && } +
    + ); +} + +function InviteForm({ onSent }: { onSent: () => Promise }) { + const [emails, setEmails] = useState(""); + const [message, setMessage] = useState(""); + const [locale, setLocale] = useState("hu"); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [results, setResults] = useState(null); + const count = parseEmails(emails).length; + + async function submit(e: React.FormEvent) { + e.preventDefault(); + setBusy(true); + setError(null); + setResults(null); + try { + const res = await api<{ results: InvitationResult[] }>("/admin/invitations", { + body: { emails: parseEmails(emails), message: message.trim() || null, locale }, + }); + setResults(res.results); + if (res.results.some((r) => r.status === "invited")) setEmails(""); + await onSent(); + } catch (err) { + setError(errorText(err)); + } finally { + setBusy(false); + } + } + + return ( +
    +

    + Új meghívó +

    +
    +
    + +