Invitation-only sign-up, invitation e-mails and waitlist

- SIGNUP_MODE=invite (default): a new account needs an open invitation for
  its address, or the invitation link (then any Google account will do)
- admin page "Meghívók": invite many addresses at once, personal message,
  resend (max 3, 24 h apart), revoke, copy link, mail preview and test copy,
  waitlist
- invitation e-mail in HTML and plain text; Message-ID on the sender's
  domain, List-Unsubscribe with one-click POST, opt-out list (hashes only)
- e-mail texts moved to a shared crate (crates/email-templates)
- login page shows the invitation; waitlist for uninvited visitors;
  unsubscribe page; privacy policy updated
- docs/levelkuldes.md: Brevo, DNS (SPF, DKIM, DMARC) and the SMTP setup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-17 18:37:15 +00:00
co-authored by Claude Opus 5.5
parent b53cadcd8c
commit 7272d0f1f3
37 changed files with 2333 additions and 231 deletions
+1 -1
View File
@@ -59,7 +59,7 @@ jobs:
# astro-engine and horoscope-api need the Swiss Ephemeris sources and # astro-engine and horoscope-api need the Swiss Ephemeris sources and
# data (scripts/fetch-deps.sh); their tests run locally. # data (scripts/fetch-deps.sh); their tests run locally.
- name: Test - 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: build:
needs: test needs: test
Generated
+9
View File
@@ -169,6 +169,7 @@ dependencies = [
"axum", "axum",
"axum-extra", "axum-extra",
"db", "db",
"email-templates",
"horoscope-client", "horoscope-client",
"http-body-util", "http-body-util",
"jsonwebtoken", "jsonwebtoken",
@@ -446,6 +447,13 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "email-templates"
version = "0.1.0"
dependencies = [
"serde_json",
]
[[package]] [[package]]
name = "email_address" name = "email_address"
version = "0.2.9" version = "0.2.9"
@@ -2868,6 +2876,7 @@ dependencies = [
"anyhow", "anyhow",
"axum", "axum",
"db", "db",
"email-templates",
"lettre", "lettre",
"rand 0.9.5", "rand 0.9.5",
"reqwest", "reqwest",
+2
View File
@@ -8,6 +8,7 @@ members = [
"crates/db", "crates/db",
"crates/horoscope-client", "crates/horoscope-client",
"crates/analysis-prompt", "crates/analysis-prompt",
"crates/email-templates",
"services/horoscope-api", "services/horoscope-api",
"services/backend", "services/backend",
"services/worker", "services/worker",
@@ -27,6 +28,7 @@ service-kit = { path = "crates/service-kit" }
db = { path = "crates/db" } db = { path = "crates/db" }
horoscope-client = { path = "crates/horoscope-client" } horoscope-client = { path = "crates/horoscope-client" }
analysis-prompt = { path = "crates/analysis-prompt" } analysis-prompt = { path = "crates/analysis-prompt" }
email-templates = { path = "crates/email-templates" }
anyhow = "1" anyhow = "1"
argon2 = { version = "0.5", features = ["std"] } argon2 = { version = "0.5", features = ["std"] }
+43
View File
@@ -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()
);
+10
View File
@@ -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
+482
View File
@@ -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<String>,
}
#[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<String>,
greeting: String,
intro: String,
/// A personal message, shown as a quote.
quote: Option<String>,
/// 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<String>,
/// Label and page of the unsubscribe link in the footer.
unsubscribe: Option<(&'static str, String)>,
unsubscribe_post_url: Option<String>,
}
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<Rendered, TemplateError> {
let lang = if locale.eq_ignore_ascii_case("hu") { Lang::Hu } else { Lang::En };
let url = field(payload, "url")?;
let greeting = |name: Option<String>| 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<Content, TemplateError> {
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<String, TemplateError> {
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<String> {
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<String> {
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<String> {
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("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
_ => 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#"<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent">{}</div>"#,
escape(p)
)
});
let quote = self.quote.as_deref().map_or(String::new(), |q| {
format!(
r#"<tr><td style="padding-bottom:24px"><div style="border-left:3px solid {GOLD};padding:4px 0 4px 16px;font-size:16px;line-height:1.6;font-style:italic;color:{TEXT}">{}</div></td></tr>
"#,
escape(q).replace('\n', "<br>")
)
});
let points = self.points.as_ref().map_or(String::new(), |(heading, items)| {
let items: String = items
.iter()
.map(|i| format!(r#"<li style="margin:0 0 6px">{}</li>"#, escape(i)))
.collect();
format!(
r#"<tr><td style="font-size:16px;line-height:1.6;padding-bottom:24px">{}<ul style="margin:8px 0 0;padding-left:20px">{items}</ul></td></tr>
"#,
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#"<a href="{}" style="color:{FAINT}">{}</a>"#, escape(url), escape(label)));
}
small.push(escape(footer));
let small = small.join("<br>");
let html = format!(
r#"<!doctype html>
<html lang="{lang}">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{subject}</title></head>
<body style="margin:0;padding:0;background:#f4f1ea;font-family:Georgia,'Times New Roman',serif;color:{TEXT}">
{preheader}<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f1ea;padding:32px 16px">
<tr><td align="center">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:520px;background:#ffffff;border-radius:8px;padding:32px">
<tr><td style="font-size:20px;letter-spacing:2px;color:{GOLD};padding-bottom:24px">SORSFONALAK</td></tr>
<tr><td style="font-size:16px;line-height:1.6;padding-bottom:12px">{greeting}</td></tr>
<tr><td style="font-size:16px;line-height:1.6;padding-bottom:24px">{intro}</td></tr>
{quote}{points}<tr><td style="padding-bottom:24px"><a href="{url}" style="display:inline-block;background:{GOLD};color:#ffffff;text-decoration:none;padding:12px 24px;border-radius:6px;font-size:16px">{button}</a></td></tr>
<tr><td style="font-size:14px;line-height:1.6;color:{MUTED};padding-bottom:16px">{note}</td></tr>
<tr><td style="font-size:12px;line-height:1.5;color:{FAINT};word-break:break-all">{url_text}</td></tr>
</table>
<p style="font-size:12px;line-height:1.5;color:{FAINT};max-width:520px">{small}</p>
</td></tr>
</table>
</body>
</html>
"#,
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!\n<b>Szia</b>",
"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> <b>Szia</b>"));
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!<br>&lt;b&gt;Szia&lt;/b&gt;"));
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);
}
}
+6 -2
View File
@@ -10,9 +10,13 @@ GOOGLE_CLIENT_IDS=
# These accounts become admins at their first login # These accounts become admins at their first login
BOOTSTRAP_ADMIN_EMAILS= BOOTSTRAP_ADMIN_EMAILS=
# Outgoing mail, e.g. smtps://user:password@smtp.example.com:465 # Outgoing mail (see docs/levelkuldes.md). DigitalOcean blocks ports 25/465/587: use 2525.
# e.g. smtp://login%40smtp-brevo.com:KEY@smtp-relay.brevo.com:2525?tls=required
SMTP_URL= SMTP_URL=
MAIL_FROM=Sorsfonalak <noreply@sorsfonalak.hu> MAIL_FROM=Sorsfonalak <hello@sorsfonalak.hu>
# invite: new accounts need an invitation (default); open: anyone can sign up
SIGNUP_MODE=invite
# Image version; every deployment rewrites it # Image version; every deployment rewrites it
TAG=latest TAG=latest
+2
View File
@@ -89,6 +89,8 @@ services:
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true} MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0} FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
UNLIMITED_DAILY_LIMIT: ${UNLIMITED_DAILY_LIMIT:-5} 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: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy
+2
View File
@@ -57,6 +57,8 @@ services:
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true} MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0} FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
UNLIMITED_DAILY_LIMIT: ${UNLIMITED_DAILY_LIMIT:-5} 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: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy
+58
View File
@@ -0,0 +1,58 @@
# Levélküldés élesben (meghívók, értesítések)
É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 kell a lenti négy lépés.
## 1. Levélküldő szolgáltatás
Javaslat: **Brevo** (EU-s, napi 300 levélig ingyenes; egy induló, meghívásos oldalnak bőven elég). Ha később fontosabb lesz a kézbesítési arány, a Postmark (fizetős) a legjobb; a beállítás ugyanígy megy.
A **DigitalOcean** a dropleteken alapból tiltja a kimenő SMTP-portokat (25, 465, 587), ezért a **2525-ös portot** kell használni; ezt a Brevo és a Postmark is tudja.
1. Brevo-fiók létrehozása.
2. *Senders, Domains & Dedicated IPs → Domains → Add a domain*: `sorsfonalak.hu`. A Brevo kiírja a szükséges DNS-rekordokat (lásd 2. pont).
3. *Senders*: feladó felvétele, javaslat: `hello@sorsfonalak.hu`. A `noreply` cím a szűrőknél rosszabb, és válaszolni sem lehet rá.
4. *SMTP & API → SMTP*: itt van az SMTP-login (`…@smtp-brevo.com` alakú) és egy új **SMTP-kulcs** (ez a jelszó).
## 2. DNS a Cloudflare-en
A rekordokat a Brevo pontosan megadja; ezek szoktak lenni:
| Típus | Név | Tartalom |
|---|---|---|
| TXT | `sorsfonalak.hu` | `brevo-code:…` (a domain igazolása) |
| CNAME | `brevo1._domainkey` | a Brevo által megadott cél (DKIM) |
| CNAME | `brevo2._domainkey` | a Brevo által megadott cél (DKIM) |
| TXT | `_dmarc` | `v=DMARC1; p=none; rua=mailto:<a te címed>` |
- A CNAME-ek legyenek **DNS only** (szürke felhő), különben a DKIM nem működik.
- SPF: ha a Brevo kér SPF-et, egy domainnek csak **egy** `v=spf1` rekordja lehet, a szolgáltatókat abba kell összevonni (például `v=spf1 include:spf.brevo.com ~all`).
- DMARC: induláskor `p=none` (csak jelentés). Ha pár hétig minden levél átmegy a DKIM-en, 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 MX- és SPF-rekordot is ad; az SPF-et ilyenkor a Brevóéval egy rekordba kell összevonni.
## 3. A szerver `.env` fájlja
`/opt/sorsfonalak/.env`:
```
SMTP_URL=smtp://<login>:<smtp-kulcs>@smtp-relay.brevo.com:2525?tls=required
MAIL_FROM=Sorsfonalak <hello@sorsfonalak.hu>
```
- A loginban lévő `@` jelet `%40`-re kell írni (például `abc123%40smtp-brevo.com`), mert az URL-ben az `@` választja el a jelszót a géptől.
- Utána: `docker compose up -d worker`. A naplóban ennek kell megjelennie: `e-mail delivery enabled`.
- 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;`.
## 4. 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ó.
## 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.
- `Message-ID` a feladó domainjén.
- `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).
- 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.
+1
View File
@@ -9,6 +9,7 @@ publish.workspace = true
[dependencies] [dependencies]
db.workspace = true db.workspace = true
analysis-prompt.workspace = true analysis-prompt.workspace = true
email-templates.workspace = true
horoscope-client.workspace = true horoscope-client.workspace = true
service-kit.workspace = true service-kit.workspace = true
anyhow.workspace = true anyhow.workspace = true
+17 -3
View File
@@ -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": "<id>"}` 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` | | `MOCK_PAYMENTS` | `false` | próbafizetés a Stripe bekötéséig: a `POST /v1/payments/mock` `{"package": "<id>"}` 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ó | | `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`) | | `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 | | `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) | | `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 | | `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. - **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. - 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á. - 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`. - **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:** - **Guardok:**
- `AuthUser`: belépés kell (401); - `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 | | 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`) | | `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/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/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/verify-email` | – | `{token}` az e-mailben kapott linkből |
| `POST /v1/auth/resend-verification` | user | | | `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 | | `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}/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 | | `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 | | `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<id>` | | `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<id>` |
| `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 | | `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 |
+27
View File
@@ -2,6 +2,24 @@
use anyhow::{Context, bail}; 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)] #[derive(Debug, Clone)]
pub struct Config { pub struct Config {
/// `DATABASE_URL` (required). /// `DATABASE_URL` (required).
@@ -51,6 +69,9 @@ pub struct Config {
pub free_person_slots: i64, pub free_person_slots: i64,
/// `UNLIMITED_DAILY_LIMIT` (default 5): new detailed analyses a day with the unlimited package. /// `UNLIMITED_DAILY_LIMIT` (default 5): new detailed analyses a day with the unlimited package.
pub unlimited_daily_limit: i64, 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<String> { fn var(name: &str) -> Option<String> {
@@ -106,6 +127,11 @@ impl Config {
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?, max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?,
free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?, free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?,
unlimited_daily_limit: parsed("UNLIMITED_DAILY_LIMIT", 5)?, 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 { if config.session_ttl_days < 1 {
bail!("SESSION_TTL_DAYS must be at least 1"); bail!("SESSION_TTL_DAYS must be at least 1");
@@ -136,6 +162,7 @@ impl Config {
max_charts_per_user: 50, max_charts_per_user: 50,
free_person_slots: 5, free_person_slots: 5,
unlimited_daily_limit: 3, unlimited_daily_limit: 3,
signup_mode: SignupMode::Open,
} }
} }
} }
+4
View File
@@ -16,6 +16,9 @@ pub enum ApiError {
InvalidCredentials(String), InvalidCredentials(String),
#[error("{0}")] #[error("{0}")]
Forbidden(String), 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")] #[error("{0} not found")]
NotFound(&'static str), NotFound(&'static str),
#[error("{message}")] #[error("{message}")]
@@ -51,6 +54,7 @@ impl ApiError {
ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"), ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
ApiError::InvalidCredentials(_) => (StatusCode::UNAUTHORIZED, "invalid_credentials"), ApiError::InvalidCredentials(_) => (StatusCode::UNAUTHORIZED, "invalid_credentials"),
ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"), ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"),
ApiError::Refused { code, .. } => (StatusCode::FORBIDDEN, code),
ApiError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"), ApiError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"),
ApiError::Conflict { code, .. } => (StatusCode::CONFLICT, code), ApiError::Conflict { code, .. } => (StatusCode::CONFLICT, code),
ApiError::Gone(_) => (StatusCode::GONE, "gone"), ApiError::Gone(_) => (StatusCode::GONE, "gone"),
+24 -4
View File
@@ -113,16 +113,28 @@ async fn consume_token(conn: &mut PgConnection, token: &str, purpose: &str) -> R
row.map(|(id,)| id).ok_or(ApiError::InvalidToken) 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> { 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<Uuid>,
to: &str,
template: &str,
locale: &str,
payload: Value,
) -> Result<(), ApiError> {
sqlx::query( sqlx::query(
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)", "INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)",
) )
.bind(Uuid::now_v7()) .bind(Uuid::now_v7())
.bind(user.id) .bind(user_id)
.bind(&user.email) .bind(to)
.bind(template) .bind(template)
.bind(&user.locale) .bind(locale)
.bind(payload) .bind(payload)
.execute(conn) .execute(conn)
.await?; .await?;
@@ -156,6 +168,8 @@ pub struct RegisterRequest {
password: String, password: String,
display_name: Option<String>, display_name: Option<String>,
locale: Option<String>, locale: Option<String>,
/// The invitation link's token, while sign-up needs an invitation.
invite_token: Option<String>,
} }
/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off. /// Password endpoints answer 403 while `PASSWORD_LOGIN` is off.
@@ -185,6 +199,7 @@ pub async fn register(
if exists.is_some() { if exists.is_some() {
return Err(ApiError::conflict("email_taken", "an account with this e-mail address already exists")); 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(); let user_id = Uuid::now_v7();
sqlx::query("INSERT INTO users (id, email, display_name, locale) VALUES ($1, $2, $3, $4)") sqlx::query("INSERT INTO users (id, email, display_name, locale) VALUES ($1, $2, $3, $4)")
.bind(user_id) .bind(user_id)
@@ -201,6 +216,7 @@ pub async fn register(
.bind(&email) .bind(&email)
.execute(&mut *tx) .execute(&mut *tx)
.await?; .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?; let mut user = load_user(&mut tx, user_id).await?;
apply_bootstrap_admin(&state, &mut tx, &mut user).await?; apply_bootstrap_admin(&state, &mut tx, &mut user).await?;
queue_verification(&state, &mut tx, &user).await?; queue_verification(&state, &mut tx, &user).await?;
@@ -266,6 +282,8 @@ pub async fn login(
pub struct GoogleRequest { pub struct GoogleRequest {
/// ID token (JWT) from Google Identity Services. /// ID token (JWT) from Google Identity Services.
id_token: String, id_token: String,
/// The invitation link's token, while sign-up needs an invitation.
invite_token: Option<String>,
} }
/// Logs in with Google. An unknown Google account is linked to the existing /// Logs in with Google. An unknown Google account is linked to the existing
@@ -311,6 +329,7 @@ pub async fn google(
(id, false) (id, false)
} }
None => { None => {
super::invitations::admit(&state, &mut tx, &email, req.invite_token.as_deref()).await?;
let id = Uuid::now_v7(); let id = Uuid::now_v7();
let locale = claims let locale = claims
.locale .locale
@@ -328,6 +347,7 @@ pub async fn google(
.bind(locale) .bind(locale)
.execute(&mut *tx) .execute(&mut *tx)
.await?; .await?;
super::invitations::mark_accepted(&mut tx, id, &email, req.invite_token.as_deref()).await?;
(id, true) (id, true)
} }
}; };
+547
View File
@@ -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<String>) -> Result<Option<String>, 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<String, ApiError> {
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<bool, ApiError> {
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<String>,
message: Option<String>,
locale: Option<String>,
}
/// 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<CreateInvitations>,
) -> ApiResult<(StatusCode, Json<Value>)> {
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<String>,
locale: String,
created_at: OffsetDateTime,
expires_at: OffsetDateTime,
sent_count: i32,
last_sent_at: OffsetDateTime,
accepted_at: Option<OffsetDateTime>,
revoked_at: Option<OffsetDateTime>,
invited_by_name: Option<String>,
accepted_by_name: Option<String>,
mail_created_at: Option<OffsetDateTime>,
mail_sent_at: Option<OffsetDateTime>,
mail_failed_at: Option<OffsetDateTime>,
mail_error: Option<String>,
}
fn status(accepted: Option<OffsetDateTime>, revoked: Option<OffsetDateTime>, 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<Json<Value>> {
let rows: Vec<Row> = 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<Value> = 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<String>)> = 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<Value> = 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<Json<Value>> {
let mut tx = state.db.begin().await?;
#[derive(sqlx::FromRow)]
struct Open {
email: String,
message: Option<String>,
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<StatusCode> {
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<Path<String>, ApiError>,
) -> ApiResult<StatusCode> {
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<String>,
locale: Option<String>,
/// 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<PreviewRequest>,
) -> ApiResult<Json<Value>> {
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<String>) -> ApiResult<Json<Value>> {
#[derive(sqlx::FromRow)]
struct Landing {
inviter: Option<String>,
message: Option<String>,
expires_at: OffsetDateTime,
accepted_at: Option<OffsetDateTime>,
revoked_at: Option<OffsetDateTime>,
}
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<Query<TokenQuery>, ApiError>,
) -> ApiResult<Json<Value>> {
let mut tx = state.db.begin().await?;
let email: Option<String> = 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<String>,
}
/// 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<WaitlistRequest>,
) -> ApiResult<(StatusCode, Json<Value>)> {
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 }))))
}
+10
View File
@@ -10,6 +10,7 @@ mod admin;
mod analyses; mod analyses;
mod auth; mod auth;
mod charts; mod charts;
mod invitations;
mod payments; mod payments;
mod prompts; mod prompts;
mod shares; mod shares;
@@ -87,11 +88,19 @@ pub fn router(state: Arc<AppState>) -> Router {
// public, no login // public, no login
.route("/v1/public/shares/{slug}", get(shares::public_view)) .route("/v1/public/shares/{slug}", get(shares::public_view))
.route("/v1/public/invites/{token}", get(synastries::public_invite)) .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 // administration
.route("/v1/admin/users", get(admin::list_users)) .route("/v1/admin/users", get(admin::list_users))
.route("/v1/admin/users/{id}", patch(admin::update_user)) .route("/v1/admin/users/{id}", patch(admin::update_user))
.route("/v1/admin/users/{id}/credits", post(admin::adjust_credits)) .route("/v1/admin/users/{id}/credits", post(admin::adjust_credits))
.route("/v1/admin/users/{id}/packages", post(admin::grant_package)) .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", get(prompts::list))
.route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save)) .route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save))
.route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview)) .route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview))
@@ -130,6 +139,7 @@ async fn public_config(State(state): St) -> Json<Value> {
"password_login": c.password_login, "password_login": c.password_login,
"mock_payments": c.mock_payments, "mock_payments": c.mock_payments,
"unlimited_daily_limit": c.unlimited_daily_limit, "unlimited_daily_limit": c.unlimited_daily_limit,
"signup_mode": c.signup_mode.as_str(),
"password_min_length": crate::auth::MIN_PASSWORD_LEN, "password_min_length": crate::auth::MIN_PASSWORD_LEN,
})) }))
} }
+134
View File
@@ -1112,3 +1112,137 @@ async fn renaming_a_person_keeps_chart_and_analyses(pool: PgPool) {
let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(same)).await; let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(same)).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body); 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");
}
@@ -76,6 +76,21 @@ export default async function PrivacyPage() {
<td>A megvásárolt szolgáltatás nyújtása, elszámolás</td> <td>A megvásárolt szolgáltatás nyújtása, elszámolás</td>
<td>Szerződés teljesítése; számviteli kötelezettség (6. cikk (1) c)</td> <td>Szerződés teljesítése; számviteli kötelezettség (6. cikk (1) c)</td>
</tr> </tr>
<tr>
<td>Meghívott e-mail-címe, a meghívó neve és személyes üzenete</td>
<td>A meghívó elküldése; amíg az oldal zártkörű, csak meghívottak regisztrálhatnak</td>
<td>Jogos érdek (6. cikk (1) f)</td>
</tr>
<tr>
<td>A várólistán megadott e-mail-cím</td>
<td>Értesítés, ha megnyílik az oldal, vagy meghívót küldünk</td>
<td>Hozzájárulás (6. cikk (1) a)</td>
</tr>
<tr>
<td>Azok a címek, amelyek leiratkoztak a meghívókról (csak a cím egyirányú lenyomata, hash-e)</td>
<td>Hogy ezekre a címekre ne küldjünk több meghívót</td>
<td>Jogos érdek (6. cikk (1) f)</td>
</tr>
<tr> <tr>
<td>IP-cím, böngésző adatai, a kérések ideje (szervernaplók)</td> <td>IP-cím, böngésző adatai, a kérések ideje (szervernaplók)</td>
<td>Biztonság, hibakeresés, visszaélések kiszűrése</td> <td>Biztonság, hibakeresés, visszaélések kiszűrése</td>
@@ -123,6 +138,10 @@ export default async function PrivacyPage() {
<li> <li>
<strong>Google LLC</strong> – bejelentkezés Google-fiókkal. <strong>Google LLC</strong> – bejelentkezés Google-fiókkal.
</li> </li>
<li>
<strong>Levélküldő szolgáltató</strong> – a rendszerlevelek és a meghívók kézbesítése; a neve az indításkor
itt lesz feltüntetve.
</li>
<li> <li>
<strong>OpenRouter, Inc.</strong> és az általa elért modellszolgáltató (jelenleg{" "} <strong>OpenRouter, Inc.</strong> és az általa elért modellszolgáltató (jelenleg{" "}
<strong>Anthropic PBC</strong>) – az elemzések megírása, kizárólag a 3. pontban leírt csillagászati <strong>Anthropic PBC</strong>) – 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() {
<li>Fiókod adatait, képleteidet és elemzéseidet a fiókod törléséig.</li> <li>Fiókod adatait, képleteidet és elemzéseidet a fiókod törléséig.</li>
<li>A biztonsági mentésekből a törölt adatok legkésőbb 14 nap után tűnnek el.</li> <li>A biztonsági mentésekből a törölt adatok legkésőbb 14 nap után tűnnek el.</li>
<li>A szervernaplókat legfeljebb 30 napig őrizzük.</li> <li>A szervernaplókat legfeljebb 30 napig őrizzük.</li>
<li>
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.
</li>
<li>A várólistán megadott címet a regisztrációdig, vagy amíg nem kéred a törlését.</li>
<li>A számlázáshoz szükséges adatokat a számviteli törvény szerinti ideig (8 évig) őrizzük.</li> <li>A számlázáshoz szükséges adatokat a számviteli törvény szerinti ideig (8 évig) őrizzük.</li>
</ul> </ul>
</section> </section>
@@ -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<AdminInvitation["status"], string> = {
pending: "Függőben",
accepted: "Elfogadva",
expired: "Lejárt",
revoked: "Visszavonva",
};
const MAIL: Record<AdminInvitation["mail"], string> = {
sent: "Elküldve",
queued: "Sorban vár",
failed: "Sikertelen",
archived: "Elküldve (archív)",
};
const RESULT: Record<InvitationResult["status"], string> = {
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 (
<button
type="button"
className="btn btn-sm btn-ghost"
onClick={async () => {
try {
await navigator.clipboard.writeText(url);
setCopied(true);
} catch {
window.prompt("A meghívólink:", url);
}
}}
>
{copied ? "Kimásolva" : "Link másolása"}
</button>
);
}
/** 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<ListData | null>(null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
try {
setData(await api<ListData>("/admin/invitations"));
setError(null);
} catch (e) {
setError(errorText(e));
}
}, []);
useEffect(() => {
load();
}, [load]);
return (
<div className="field" style={{ gap: 24 }}>
{data?.signup_mode === "open" && (
<p className="msg" role="status">
A regisztráció most nyitott (<code>SIGNUP_MODE=open</code>): bárki beléphet, a meghívó csak értesítés.
</p>
)}
<InviteForm onSent={load} />
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{data && <InvitationList invitations={data.invitations} onChange={load} />}
{data && <WaitlistTable waitlist={data.waitlist} onChange={load} />}
</div>
);
}
function InviteForm({ onSent }: { onSent: () => Promise<void> }) {
const [emails, setEmails] = useState("");
const [message, setMessage] = useState("");
const [locale, setLocale] = useState("hu");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [results, setResults] = useState<InvitationResult[] | null>(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 (
<section className="card field" style={{ gap: 16 }} aria-labelledby="invite-title">
<h2 id="invite-title" style={{ margin: 0 }}>
Új meghívó
</h2>
<form onSubmit={submit} className="field" style={{ gap: 14 }}>
<div className="field">
<label htmlFor="invite-emails">E-mail-címek</label>
<textarea
id="invite-emails"
className="inp"
rows={3}
required
value={emails}
onChange={(e) => setEmails(e.target.value)}
placeholder={"kata@pelda.hu\nbela@pelda.hu"}
/>
<span className="hint">Soronként egy, vagy vesszővel elválasztva; egyszerre legfeljebb 50.</span>
</div>
<div className="field">
<label htmlFor="invite-message">Személyes üzenet (nem kötelező)</label>
<textarea
id="invite-message"
className="inp"
rows={3}
maxLength={MAX_MESSAGE}
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Szia! Ezt nézd meg, szerintem tetszeni fog."
/>
<span className="hint">
{message.length}/{MAX_MESSAGE} karakter. Link nem lehet benne (spamszűrők miatt).
</span>
</div>
<div className="row" style={{ gap: 12, alignItems: "flex-end", flexWrap: "wrap" }}>
<div className="field" style={{ width: 160 }}>
<label htmlFor="invite-locale">A levél nyelve</label>
<select id="invite-locale" className="inp" value={locale} onChange={(e) => setLocale(e.target.value)}>
<option value="hu">magyar</option>
<option value="en">angol</option>
</select>
</div>
<button type="submit" className="btn btn-primary" disabled={busy || count === 0}>
{busy ? "Küldés…" : count > 1 ? `${count} meghívó küldése` : "Meghívó küldése"}
</button>
</div>
</form>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{results && (
<ul className="invite-results" aria-label="Eredmény">
{results.map((r) => (
<li key={r.email}>
<span className={r.status === "invited" ? "msg-ok" : "muted"}>
{r.email}: {RESULT[r.status]}
</span>
{r.url && <CopyLink url={r.url} />}
</li>
))}
</ul>
)}
<MailPreview message={message} locale={locale} />
</section>
);
}
/** The invitation e-mail as the recipient sees it, and a test copy to the admin. */
function MailPreview({ message, locale }: { message: string; locale: string }) {
const [mail, setMail] = useState<{ subject: string; html: string; text: string } | null>(null);
const [view, setView] = useState<"html" | "text">("html");
const [busy, setBusy] = useState(false);
const [note, setNote] = useState<{ ok: boolean; text: string } | null>(null);
async function show(sendToMe: boolean) {
setBusy(true);
setNote(null);
try {
const res = await api<{ subject: string; html: string; text: string; sent_to: string | null }>(
"/admin/invitations/preview",
{ body: { message: message.trim() || null, locale, send_to_me: sendToMe } },
);
setMail(res);
if (res.sent_to) setNote({ ok: true, text: `Tesztlevél a sorban: ${res.sent_to}. A linkjei nem működnek.` });
} catch (e) {
setNote({ ok: false, text: errorText(e) });
} finally {
setBusy(false);
}
}
return (
<div className="field mail-preview" style={{ gap: 10 }}>
<div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
<button type="button" className="btn btn-sm" onClick={() => show(false)} disabled={busy}>
{mail ? "Előnézet frissítése" : "Levél előnézete"}
</button>
<button type="button" className="btn btn-sm btn-ghost" onClick={() => show(true)} disabled={busy}>
Teszt küldése magamnak
</button>
</div>
{note && (
<p className={note.ok ? "msg msg-ok" : "msg msg-error"} role={note.ok ? "status" : "alert"}>
{note.text}
</p>
)}
{mail && (
<>
<p style={{ margin: 0 }}>
<span className="muted">Tárgy:</span> <strong>{mail.subject}</strong>
</p>
<div className="row" role="group" aria-label="Változat" style={{ gap: 4 }}>
{(["html", "text"] as const).map((v) => (
<button
key={v}
type="button"
className={view === v ? "btn btn-sm" : "btn btn-sm btn-ghost"}
aria-pressed={view === v}
onClick={() => setView(v)}
>
{v === "html" ? "HTML" : "Szöveges"}
</button>
))}
</div>
{view === "html" ? (
<iframe title="A levél HTML-változata" className="mail-frame" srcDoc={mail.html} sandbox="" />
) : (
<pre className="mail-text">{mail.text}</pre>
)}
</>
)}
</div>
);
}
function InvitationList({ invitations, onChange }: { invitations: AdminInvitation[]; onChange: () => Promise<void> }) {
return (
<section className="card" aria-labelledby="invitations-title">
<h2 id="invitations-title" style={{ marginTop: 0 }}>
Meghívók
</h2>
{invitations.length === 0 ? (
<p className="muted">Még nincs meghívó.</p>
) : (
<div className="table-wrap">
<table>
<thead>
<tr>
<th scope="col">Cím</th>
<th scope="col">Állapot</th>
<th scope="col">Levél</th>
<th scope="col">Küldve</th>
<th scope="col">Lejár</th>
<th scope="col">
<span className="sr-only">Műveletek</span>
</th>
</tr>
</thead>
<tbody>
{invitations.map((i) => (
<InvitationRow key={i.id} invitation={i} onChange={onChange} />
))}
</tbody>
</table>
</div>
)}
</section>
);
}
function InvitationRow({ invitation: i, onChange }: { invitation: AdminInvitation; onChange: () => Promise<void> }) {
const [busy, setBusy] = useState(false);
const [note, setNote] = useState<string | null>(null);
const [url, setUrl] = useState<string | null>(null);
async function act(kind: "resend" | "revoke") {
if (kind === "revoke" && !window.confirm(`Visszavonod a meghívót (${i.email})?`)) return;
setBusy(true);
setNote(null);
try {
if (kind === "resend") {
const res = await api<{ url: string }>(`/admin/invitations/${i.id}/resend`, { body: {} });
setUrl(res.url);
} else {
await api(`/admin/invitations/${i.id}`, { method: "DELETE" });
}
await onChange();
} catch (e) {
setNote(errorText(e));
} finally {
setBusy(false);
}
}
return (
<tr>
<td>
<div>{i.email}</div>
{i.message && (
<div className="hint invite-msg" title={i.message}>
„{i.message}”
</div>
)}
</td>
<td>
<span className={`badge invite-${i.status}`}>{STATUS[i.status]}</span>
{i.accepted_by && <div className="hint">{i.accepted_by}</div>}
</td>
<td>
<span className={i.mail === "failed" ? "msg-error" : i.mail === "queued" ? "muted" : undefined}>
{MAIL[i.mail]}
</span>
{i.mail_error && <div className="hint">{i.mail_error.slice(0, 120)}</div>}
</td>
<td className="num">
{formatDate(i.last_sent_at)}
{i.sent_count > 1 && <div className="hint">{i.sent_count}× küldve</div>}
</td>
<td className="num">{i.status === "pending" || i.status === "expired" ? formatDate(i.expires_at) : "–"}</td>
<td>
<div className="row" style={{ gap: 4, flexWrap: "nowrap", justifyContent: "flex-end" }}>
{url && <CopyLink url={url} />}
{i.can_resend && (
<button type="button" className="btn btn-sm" onClick={() => act("resend")} disabled={busy}>
Újraküldés
</button>
)}
{(i.status === "pending" || i.status === "expired") && (
<button type="button" className="btn btn-sm btn-ghost" onClick={() => act("revoke")} disabled={busy}>
Visszavonás
</button>
)}
</div>
{note && (
<div className="msg-error" role="alert" style={{ fontSize: 13 }}>
{note}
</div>
)}
</td>
</tr>
);
}
function WaitlistTable({ waitlist, onChange }: { waitlist: WaitlistEntry[]; onChange: () => Promise<void> }) {
const [busy, setBusy] = useState<string | null>(null);
const [note, setNote] = useState<string | null>(null);
async function invite(w: WaitlistEntry) {
setBusy(w.email);
setNote(null);
try {
const res = await api<{ results: InvitationResult[] }>("/admin/invitations", {
body: { emails: [w.email], locale: w.locale },
});
const r = res.results[0];
if (r && r.status !== "invited") setNote(`${r.email}: ${RESULT[r.status]}`);
await onChange();
} catch (e) {
setNote(errorText(e));
} finally {
setBusy(null);
}
}
async function remove(w: WaitlistEntry) {
setBusy(w.email);
setNote(null);
try {
await api(`/admin/waitlist/${encodeURIComponent(w.email)}`, { method: "DELETE" });
await onChange();
} catch (e) {
setNote(errorText(e));
} finally {
setBusy(null);
}
}
return (
<section className="card" aria-labelledby="waitlist-title">
<h2 id="waitlist-title" style={{ marginTop: 0 }}>
Várólista
</h2>
<p className="hint">Akik meghívó nélkül próbáltak belépni, és kérték, hogy szóljunk nekik.</p>
{note && (
<p className="msg msg-error" role="alert">
{note}
</p>
)}
{waitlist.length === 0 ? (
<p className="muted">Üres.</p>
) : (
<div className="table-wrap">
<table>
<thead>
<tr>
<th scope="col">Cím</th>
<th scope="col">Feliratkozott</th>
<th scope="col">Meghívó</th>
<th scope="col">
<span className="sr-only">Műveletek</span>
</th>
</tr>
</thead>
<tbody>
{waitlist.map((w) => (
<tr key={w.email}>
<td>{w.email}</td>
<td className="num">{formatDate(w.created_at)}</td>
<td>{w.invitation === "pending" ? "elküldve" : w.invitation === "accepted" ? "elfogadva" : "–"}</td>
<td>
<div className="row" style={{ gap: 4, flexWrap: "nowrap", justifyContent: "flex-end" }}>
{w.invitation === null && (
<button
type="button"
className="btn btn-sm"
onClick={() => invite(w)}
disabled={busy !== null}
>
Meghívás
</button>
)}
<button
type="button"
className="btn btn-sm btn-ghost"
onClick={() => remove(w)}
disabled={busy !== null}
>
Törlés
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
);
}
@@ -0,0 +1,27 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { AdminNav } from "@/components/AdminNav";
import { requireMe } from "@/lib/server";
import { AdminInvitations } from "./AdminInvitations";
export const metadata: Metadata = { title: "Meghívók" };
export default async function AdminInvitationsPage() {
const me = await requireMe("/admin/meghivok");
if (!me.user.roles.includes("admin")) notFound();
return (
<main className="page" style={{ maxWidth: 1180 }}>
<AdminNav current="/admin/meghivok" />
<div className="page-head">
<h1>Meghívók</h1>
<p className="muted">
Az oldalra csak meglévő felhasználó vagy meghívott léphet be. A meghívó 30 napig érvényes, és a linkkel bármelyik
Google-fiókkal elfogadható.
</p>
</div>
<AdminInvitations />
</main>
);
}
@@ -4,7 +4,8 @@ import Script from "next/script";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { api, errorText } from "@/lib/api"; import { Waitlist } from "@/components/Waitlist";
import { ApiError, api, errorText } from "@/lib/api";
/** Google's "G" mark (branding guidelines: unmodified, on the left of the label). */ /** Google's "G" mark (branding guidelines: unmodified, on the left of the label). */
function GoogleMark() { function GoogleMark() {
@@ -30,32 +31,57 @@ function GoogleMark() {
); );
} }
/** The e-mail address inside Google's ID token (only for prefilling a form; the backend verifies the token). */
function tokenEmail(credential: string): string {
try {
const part = credential.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
const bytes = Uint8Array.from(atob(part), (c) => c.charCodeAt(0));
const email = JSON.parse(new TextDecoder().decode(bytes)).email;
return typeof email === "string" ? email : "";
} catch {
return "";
}
}
/** /**
* "Continue with Google" in the site's own button style. Google's real * "Continue with Google" in the site's own button style. Google's real
* (rendered, invisible) button lies on top of it and receives the click, so * (rendered, invisible) button lies on top of it and receives the click, so
* the sign-in still returns an ID token. * the sign-in still returns an ID token.
*/ */
export function GoogleLogin({ clientId, target }: { clientId: string; target: string }) { export function GoogleLogin({
clientId,
target,
inviteToken = null,
}: {
clientId: string;
target: string;
/** From an invitation link: lets in any Google account. */
inviteToken?: string | null;
}) {
const router = useRouter(); const router = useRouter();
const slot = useRef<HTMLDivElement>(null); const slot = useRef<HTMLDivElement>(null);
const [ready, setReady] = useState(false); const [ready, setReady] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
/** Set when the address has no invitation: offer the waitlist for it. */
const [uninvited, setUninvited] = useState<string | null>(null);
const onCredential = useCallback( const onCredential = useCallback(
async (response: GoogleCredentialResponse) => { async (response: GoogleCredentialResponse) => {
setBusy(true); setBusy(true);
setError(null); setError(null);
setUninvited(null);
try { try {
await api("/auth/google", { body: { id_token: response.credential } }); await api("/auth/google", { body: { id_token: response.credential, invite_token: inviteToken } });
router.replace(target); router.replace(target);
router.refresh(); router.refresh();
} catch (e) { } catch (e) {
setError(errorText(e)); if (e instanceof ApiError && e.code === "not_invited") setUninvited(tokenEmail(response.credential));
else setError(errorText(e));
setBusy(false); setBusy(false);
} }
}, },
[router, target], [router, target, inviteToken],
); );
useEffect(() => { useEffect(() => {
@@ -94,6 +120,16 @@ export function GoogleLogin({ clientId, target }: { clientId: string; target: st
{error} {error}
</p> </p>
)} )}
{uninvited !== null && (
<>
<p className="msg msg-error" role="alert">
{inviteToken
? "Ez a meghívó már nem érvényes, és ehhez a Google-fiókhoz sem tartozik másik."
: `A Sorsfonalak jelenleg meghívásos, és ${uninvited ? `a(z) ${uninvited} címhez` : "ehhez a fiókhoz"} nem tartozik meghívó. Ha kaptál meghívót egy másik címre, lépj be azzal a Google-fiókkal, vagy nyisd meg a levélben kapott linket.`}
</p>
<Waitlist email={uninvited} />
</>
)}
</div> </div>
); );
} }
+71 -7
View File
@@ -5,7 +5,8 @@ import { redirect } from "next/navigation";
import { Logo } from "@/components/SiteHeader"; import { Logo } from "@/components/SiteHeader";
import { ZodiacWheel } from "@/components/ZodiacWheel"; import { ZodiacWheel } from "@/components/ZodiacWheel";
import { BACKEND_URL, getMe } from "@/lib/server"; import { BACKEND_URL, getMe } from "@/lib/server";
import type { PublicConfig } from "@/lib/types"; import { formatDate } from "@/lib/astro";
import type { InvitationLanding, PublicConfig } from "@/lib/types";
import { GoogleLogin } from "./GoogleLogin"; import { GoogleLogin } from "./GoogleLogin";
@@ -26,11 +27,63 @@ async function loadConfig(): Promise<PublicConfig | null> {
} }
} }
async function loadInvitation(token: string): Promise<InvitationLanding | null> {
try {
const res = await fetch(`${BACKEND_URL}/v1/public/invitations/${encodeURIComponent(token)}`, { cache: "no-store" });
return res.ok ? ((await res.json()) as InvitationLanding) : null;
} catch {
return null;
}
}
const CLOSED: Record<string, string> = {
accepted: "Ezt a meghívót már felhasználták. Ha a tiéd volt, egyszerűen lépj be ugyanazzal a Google-fiókkal.",
expired: "Ez a meghívó lejárt. Kérj újat attól, aki meghívott.",
revoked: "Ezt a meghívót visszavonták.",
};
/** The invitation the visitor came with: who sent it and what they wrote. */
function InvitationCard({ invitation }: { invitation: InvitationLanding | null }) {
if (!invitation) {
return (
<p className="msg msg-error" role="alert">
Ez a meghívólink érvénytelen. Ellenőrizd, hogy a teljes linket nyitottad-e meg a levélből.
</p>
);
}
if (invitation.status !== "pending") {
return (
<p className="msg msg-error" role="alert">
{CLOSED[invitation.status]}
</p>
);
}
return (
<div className="card invite-card">
<span className="eyebrow">Meghívó</span>
<p style={{ margin: 0 }}>
{invitation.inviter_name ? <strong>{invitation.inviter_name}</strong> : "Valaki"} meghívott a Sorsfonalakra.
</p>
{invitation.message && <blockquote className="invite-quote">{invitation.message}</blockquote>}
<p className="hint" style={{ margin: 0 }}>
Bármelyik Google-fiókoddal elfogadhatod. Érvényes: {formatDate(invitation.expires_at).replace(/\.$/, "")}-ig.
</p>
</div>
);
}
export default async function LoginPage({ searchParams }: { searchParams: Promise<Record<string, string | string[]>> }) { export default async function LoginPage({ searchParams }: { searchParams: Promise<Record<string, string | string[]>> }) {
const target = safeTarget((await searchParams).vissza); const params = await searchParams;
const target = safeTarget(params.vissza);
if (await getMe()) redirect(target); if (await getMe()) redirect(target);
const config = await loadConfig(); const rawToken = Array.isArray(params.meghivo) ? params.meghivo[0] : params.meghivo;
const inviteToken = rawToken && /^[A-Za-z0-9_-]{8,200}$/.test(rawToken) ? rawToken : null;
const [config, invitation] = await Promise.all([
loadConfig(),
inviteToken ? loadInvitation(inviteToken) : Promise.resolve(null),
]);
const clientId = config?.google_login.enabled ? config.google_login.client_id : null; const clientId = config?.google_login.enabled ? config.google_login.client_id : null;
const inviteOnly = config?.signup_mode === "invite";
return ( return (
<div className="auth"> <div className="auth">
@@ -47,21 +100,32 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis
<main className="auth-main"> <main className="auth-main">
<div className="auth-box"> <div className="auth-box">
<div className="page-head"> <div className="page-head">
<h1 style={{ fontSize: 44 }}>Belépés</h1> <h1 style={{ fontSize: 44 }}>{rawToken ? "Meghívó" : "Belépés"}</h1>
<p className="muted">Üdv újra! Lépj be a fiókodba.</p> <p className="muted">{rawToken ? "Lépj be, és már kezdheted is." : "Üdv újra! Lépj be a fiókodba."}</p>
</div> </div>
{rawToken && <InvitationCard invitation={inviteToken ? invitation : null} />}
{config === null ? ( {config === null ? (
<p className="msg msg-error" role="alert"> <p className="msg msg-error" role="alert">
A szerver most nem érhető el. Próbáld újra egy kicsit később. A szerver most nem érhető el. Próbáld újra egy kicsit később.
</p> </p>
) : clientId ? ( ) : clientId ? (
<GoogleLogin clientId={clientId} target={target} /> <GoogleLogin
clientId={clientId}
target={target}
inviteToken={invitation?.status === "pending" ? inviteToken : null}
/>
) : ( ) : (
<p className="msg msg-error" role="alert"> <p className="msg msg-error" role="alert">
A Google-belépés még nincs beállítva (a backend <code>GOOGLE_CLIENT_IDS</code> változója üres). A Google-belépés még nincs beállítva (a backend <code>GOOGLE_CLIENT_IDS</code> változója üres).
</p> </p>
)} )}
<p className="auth-foot">Még nincs fiókod? Az első belépéskor létrejön.</p> <p className="auth-foot">
{rawToken
? "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."}
</p>
<p className="hint"> <p className="hint">
A belépéssel elfogadod, hogy a születési adataidat a képleted kiszámításához tároljuk. Bármikor törölheted A belépéssel elfogadod, hogy a születési adataidat a képleted kiszámításához tároljuk. Bármikor törölheted
őket a profilodban. Részletek: <Link href="/adatvedelem">adatvédelmi tájékoztató</Link>. őket a profilodban. Részletek: <Link href="/adatvedelem">adatvédelmi tájékoztató</Link>.
+19
View File
@@ -549,3 +549,22 @@ a.pair-row:hover strong { color: var(--gold); }
.pkg-grid, .pkg-grid-compact { grid-template-columns: 1fr; } .pkg-grid, .pkg-grid-compact { grid-template-columns: 1fr; }
.pkg-tagline { min-height: 0; } .pkg-tagline { min-height: 0; }
} }
/* Invitations */
.invite-card { display: flex; flex-direction: column; gap: 8px; }
.invite-quote {
margin: 0; padding: 2px 0 2px 14px; border-left: 3px solid var(--gold);
font-style: italic; white-space: pre-line; color: var(--ink);
}
.waitlist { display: flex; flex-direction: column; gap: 10px; }
.invite-results { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 4px; }
.invite-results li { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.invite-msg { max-width: 280px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.invite-accepted { border-color: color-mix(in srgb, var(--ok) 50%, transparent); color: var(--ok); }
.invite-pending { border-color: rgba(217, 180, 106, 0.5); color: var(--gold); }
.invite-expired, .invite-revoked { color: var(--muted); }
.mail-frame { width: 100%; height: 640px; border: 1px solid var(--line); border-radius: 8px; background: #f4f1ea; }
.mail-text {
margin: 0; padding: 16px; border: 1px solid var(--line); border-radius: 8px; max-height: 640px; overflow: auto;
white-space: pre-wrap; font-size: 13px; line-height: 1.5;
}
@@ -0,0 +1,57 @@
"use client";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
// A button, not an automatic request: link scanners of mail providers open
// every link, and they must not unsubscribe anyone.
export function Unsubscribe({ token }: { token: string | null }) {
const [state, setState] = useState<"idle" | "busy" | "done">("idle");
const [error, setError] = useState<string | null>(null);
if (!token) {
return (
<p className="msg msg-error" role="alert">
Hiányzik a link vége. Nyisd meg a teljes linket a levélből.
</p>
);
}
if (state === "done") {
return (
<p className="msg msg-ok" role="status">
Leiratkoztál: erre a címre nem küldünk több meghívót.
</p>
);
}
async function confirm() {
setState("busy");
setError(null);
try {
await api(`/public/invitations/unsubscribe?token=${encodeURIComponent(token!)}`, { method: "POST" });
setState("done");
} catch (e) {
setError(errorText(e));
setState("idle");
}
}
return (
<div className="card field" style={{ gap: 12 }}>
<p style={{ margin: 0 }}>
Ha leiratkozol, erre az e-mail-címre többé nem küldünk meghívót, és a mostani meghívód is érvényét veszti.
</p>
<div>
<button type="button" className="btn btn-primary" onClick={confirm} disabled={state === "busy"}>
{state === "busy" ? "Leiratkozás…" : "Leiratkozom"}
</button>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
</div>
);
}
@@ -0,0 +1,20 @@
import type { Metadata } from "next";
import { Unsubscribe } from "./Unsubscribe";
export const metadata: Metadata = { title: "Leiratkozás", robots: { index: false } };
/** "No more invitations", from the link in the footer of an invitation e-mail. */
export default async function UnsubscribePage({ searchParams }: { searchParams: Promise<Record<string, string | string[]>> }) {
const raw = (await searchParams).token;
const token = Array.isArray(raw) ? raw[0] : raw;
return (
<main className="page" style={{ maxWidth: 560 }}>
<div className="page-head">
<h1>Leiratkozás</h1>
<p className="muted">Nem kérsz több meghívót a Sorsfonalakra.</p>
</div>
<Unsubscribe token={token ?? null} />
</main>
);
}
@@ -0,0 +1,7 @@
import { redirect } from "next/navigation";
/** The link in the invitation e-mail: the login page shows the invitation. */
export default async function InvitationLink({ params }: { params: Promise<{ token: string }> }) {
const { token } = await params;
redirect(`/belepes?meghivo=${encodeURIComponent(token)}`);
}
@@ -2,6 +2,7 @@ import Link from "next/link";
const PAGES = [ const PAGES = [
{ href: "/admin", label: "Felhasználók" }, { href: "/admin", label: "Felhasználók" },
{ href: "/admin/meghivok", label: "Meghívók" },
{ href: "/admin/promptok", label: "Promptok" }, { href: "/admin/promptok", label: "Promptok" },
]; ];
@@ -0,0 +1,67 @@
"use client";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
/** "Tell me when it opens": for visitors without an invitation. */
export function Waitlist({ email: initial = "" }: { email?: string }) {
const [email, setEmail] = useState(initial);
const [busy, setBusy] = useState(false);
const [done, setDone] = useState(false);
const [error, setError] = useState<string | null>(null);
async function submit(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
await api("/public/waitlist", { body: { email, locale: "hu" } });
setDone(true);
} catch (err) {
setError(errorText(err));
} finally {
setBusy(false);
}
}
if (done) {
return (
<p className="msg msg-ok" role="status">
Felírtunk. Ha megnyílik az oldal, vagy meghívót küldünk, ide írunk: <strong>{email}</strong>
</p>
);
}
return (
<form onSubmit={submit} className="card waitlist">
<p style={{ margin: 0 }}>
<strong>Szólunk, ha megnyílik.</strong>{" "}
<span className="muted">Add meg az e-mail-címed, és felírunk a várólistára.</span>
</p>
<div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
<label htmlFor="waitlist-email" className="sr-only">
E-mail-cím
</label>
<input
id="waitlist-email"
className="inp"
type="email"
required
autoComplete="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="nev@pelda.hu"
style={{ flex: "1 1 220px" }}
/>
<button type="submit" className="btn" disabled={busy}>
{busy ? "Küldés…" : "Feliratkozom"}
</button>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
</form>
);
}
+46
View File
@@ -71,6 +71,8 @@ export interface PublicConfig {
mock_payments: boolean; mock_payments: boolean;
/** New detailed analyses a day with the unlimited package. */ /** New detailed analyses a day with the unlimited package. */
unlimited_daily_limit: number; unlimited_daily_limit: number;
/** "invite": new accounts need an invitation. */
signup_mode: "invite" | "open";
} }
export interface Position { export interface Position {
@@ -298,3 +300,47 @@ export interface Country {
iso2: string; iso2: string;
name: string; name: string;
} }
export type InvitationStatus = "pending" | "accepted" | "expired" | "revoked";
/** What an invitation link shows before login. */
export interface InvitationLanding {
inviter_name: string | null;
message: string | null;
status: InvitationStatus;
expires_at: string;
}
export interface AdminInvitation {
id: string;
email: string;
message: string | null;
locale: string;
status: InvitationStatus;
created_at: string;
expires_at: string;
sent_count: number;
last_sent_at: string;
accepted_at: string | null;
accepted_by: string | null;
invited_by: string | null;
/** The last e-mail: sent, waiting, failed, or already removed from the outbox. */
mail: "sent" | "queued" | "failed" | "archived";
mail_error: string | null;
can_resend: boolean;
}
export interface WaitlistEntry {
email: string;
locale: string;
created_at: string;
/** The address's latest invitation, if any. */
invitation: "pending" | "accepted" | null;
}
export interface InvitationResult {
email: string;
status: "invited" | "invalid" | "already_user" | "already_invited" | "opted_out";
id?: string;
url?: string;
}
+1
View File
@@ -9,6 +9,7 @@ publish.workspace = true
[dependencies] [dependencies]
db.workspace = true db.workspace = true
analysis-prompt.workspace = true analysis-prompt.workspace = true
email-templates.workspace = true
service-kit.workspace = true service-kit.workspace = true
anyhow.workspace = true anyhow.workspace = true
axum.workspace = true axum.workspace = true
+4 -2
View File
@@ -9,13 +9,15 @@ Háttérmunkák a közös PostgreSQL-adatbázis fölött: e-mail-küldés, szöv
- A sorokat `FOR UPDATE SKIP LOCKED` zárolással veszi fel, ezért több worker is futhat egyszerre, és nem küldik el kétszer ugyanazt. A kézbesítés „legalább egyszer” elvű: ha a worker éppen küldés közben áll le, a levél újra kimehet. - A sorokat `FOR UPDATE SKIP LOCKED` zárolással veszi fel, ezért több worker is futhat egyszerre, és nem küldik el kétszer ugyanazt. A kézbesítés „legalább egyszer” elvű: ha a worker éppen küldés közben áll le, a levél újra kimehet.
- Átmeneti hibánál (hálózat, SMTP 4xx) újrapróbálja 1, 2, 4, … percenként, legfeljebb 6 óránként. `MAX_EMAIL_ATTEMPTS` próbálkozás után a levelet sikertelennek jelöli (`failed_at`, `last_error`). - Átmeneti hibánál (hálózat, SMTP 4xx) újrapróbálja 1, 2, 4, … percenként, legfeljebb 6 óránként. `MAX_EMAIL_ATTEMPTS` próbálkozás után a levelet sikertelennek jelöli (`failed_at`, `last_error`).
- Végleges hibánál nem próbálja újra: ilyen a hibás cím, az SMTP 5xx és az ismeretlen sablon. - Végleges hibánál nem próbálja újra: ilyen a hibás cím, az SMTP 5xx és az ismeretlen sablon.
- Sablonok magyarul és angolul, a felhasználó nyelve szerint (`src/templates.rs`): `verify_email`, `reset_password`, `invite_accepted`. Mindegyik szöveges és HTML-változatban megy ki; a felhasználó nevét HTML-ben escape-eli, és a vezérlőkaraktereket eltávolítja belőle. - Sablonok magyarul és angolul, a címzett nyelve szerint (`crates/email-templates`, a backend admin-előnézete is ezt használja): `verify_email`, `reset_password`, `invite_accepted`, `invitation`. Mindegyik szöveges és HTML-változatban megy ki; a felhasználói szöveget HTML-ben escape-eli, és a vezérlőkaraktereket eltávolítja belőle.
- A spamszűrők miatt a `Message-ID` a feladó domainjén van (`<outbox-id@domain>`), a meghívóknál pedig `List-Unsubscribe` és `List-Unsubscribe-Post` fejléc is megy (egykattintásos leiratkozás). Élesítés: `docs/levelkuldes.md`.
- Ha nincs `SMTP_URL`, a worker nem küld semmit, a levelek az outboxban várnak. - Ha nincs `SMTP_URL`, a worker nem küld semmit, a levelek az outboxban várnak.
**Takarítás** (induláskor, majd óránként) **Takarítás** (induláskor, majd óránként)
- lejárt munkamenetek és e-mail-tokenek; - lejárt munkamenetek és e-mail-tokenek;
- elküldött e-mailek 7 nap után (tokenes linkek vannak bennük), sikertelenek 30 nap után; - elküldött e-mailek 7 nap után (tokenes linkek vannak bennük), sikertelenek 30 nap után;
- el nem fogadott meghívók 30 nappal a lejáratuk után. - el nem fogadott „Mennyire illünk össze?” meghívók 30 nappal a lejáratuk után;
- el nem fogadott oldalmeghívók 30 nappal a lezárásuk (lejárat vagy visszavonás) után, az elfogadottak pedig, ha a fiókot törölték.
**Szöveges elemzések** (`analyses`, `pending` → `running` → `done`/`failed`) **Szöveges elemzések** (`analyses`, `pending` → `running` → `done`/`failed`)
- A backend létrehozza a `pending` sort, és levon egy elemzési egységet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül. - A backend létrehozza a `pending` sort, és levon egy elemzési egységet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül.
+8 -1
View File
@@ -8,7 +8,7 @@ use tokio::sync::watch;
const INTERVAL: Duration = Duration::from_secs(3600); const INTERVAL: Duration = Duration::from_secs(3600);
/// (what, statement) pairs; each returns the number of deleted rows. /// (what, statement) pairs; each returns the number of deleted rows.
const STATEMENTS: [(&str, &str); 5] = [ const STATEMENTS: [(&str, &str); 6] = [
("sessions", "DELETE FROM sessions WHERE expires_at < now()"), ("sessions", "DELETE FROM sessions WHERE expires_at < now()"),
("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"), ("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"),
// Sent e-mails contain links with tokens; keep them a week for support. // Sent e-mails contain links with tokens; keep them a week for support.
@@ -18,6 +18,13 @@ const STATEMENTS: [(&str, &str); 5] = [
OR failed_at < now() - interval '30 days'", OR failed_at < now() - interval '30 days'",
), ),
("invites", "DELETE FROM synastry_invites WHERE accepted_at IS NULL AND expires_at < now() - interval '30 days'"), ("invites", "DELETE FROM synastry_invites WHERE accepted_at IS NULL AND expires_at < now() - interval '30 days'"),
// Unused invitations 30 days after they closed; accepted ones once the account is deleted.
(
"invitations",
"DELETE FROM invitations WHERE (accepted_at IS NULL \
AND least(coalesce(revoked_at, expires_at), expires_at) < now() - interval '30 days') \
OR (accepted_at IS NOT NULL AND accepted_by IS NULL)",
),
("prompt_previews", "DELETE FROM prompt_previews WHERE created_at < now() - interval '30 days'"), ("prompt_previews", "DELETE FROM prompt_previews WHERE created_at < now() - interval '30 days'"),
]; ];
+48 -6
View File
@@ -6,6 +6,7 @@
use std::time::Duration; use std::time::Duration;
use lettre::message::header::{Header, HeaderName, HeaderValue};
use lettre::message::{Mailbox, MultiPart}; use lettre::message::{Mailbox, MultiPart};
use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor}; use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
use serde_json::Value; use serde_json::Value;
@@ -24,7 +25,8 @@ pub enum Mailer {
/// Collects messages instead of sending; fails for addresses listed in `fail`. /// Collects messages instead of sending; fails for addresses listed in `fail`.
#[cfg(test)] #[cfg(test)]
Memory { Memory {
sent: std::sync::Mutex<Vec<(String, Rendered)>>, /// Recipient, rendered mail and the whole message as sent.
sent: std::sync::Mutex<Vec<(String, Rendered, String)>>,
fail: Vec<(String, bool)>, fail: Vec<(String, bool)>,
}, },
} }
@@ -58,12 +60,19 @@ impl Mailer {
Ok(Mailer::Smtp(transport)) Ok(Mailer::Smtp(transport))
} }
async fn send(&self, from: &Mailbox, to: &str, mail: &Rendered) -> Result<(), SendError> { async fn send(&self, id: Uuid, from: &Mailbox, to: &str, mail: &Rendered) -> Result<(), SendError> {
let to_mailbox: Mailbox = to.parse().map_err(SendError::permanent)?; let to_mailbox: Mailbox = to.parse().map_err(SendError::permanent)?;
let message = Message::builder() // A Message-ID on our own domain (lettre would use the container's
// host name, which spam filters dislike); the same on every retry.
let mut builder = Message::builder()
.message_id(Some(format!("<{id}@{}>", from.email.domain())))
.from(from.clone()) .from(from.clone())
.to(to_mailbox) .to(to_mailbox)
.subject(&mail.subject) .subject(&mail.subject);
if let Some(url) = &mail.unsubscribe_post_url {
builder = builder.header(ListUnsubscribe(url.clone())).header(ListUnsubscribePost);
}
let message = builder
.multipart(MultiPart::alternative_plain_html(mail.text.clone(), mail.html.clone())) .multipart(MultiPart::alternative_plain_html(mail.text.clone(), mail.html.clone()))
.map_err(SendError::permanent)?; .map_err(SendError::permanent)?;
match self { match self {
@@ -77,13 +86,46 @@ impl Mailer {
if let Some((_, permanent)) = fail.iter().find(|(addr, _)| addr == to) { if let Some((_, permanent)) = fail.iter().find(|(addr, _)| addr == to) {
return Err(SendError { permanent: *permanent, message: "test failure".into() }); return Err(SendError { permanent: *permanent, message: "test failure".into() });
} }
sent.lock().unwrap().push((to.to_owned(), mail.clone())); let raw = String::from_utf8_lossy(&message.formatted()).into_owned();
sent.lock().unwrap().push((to.to_owned(), mail.clone(), raw));
Ok(()) Ok(())
} }
} }
} }
} }
/// `List-Unsubscribe: <url>`: mail clients show an unsubscribe button.
#[derive(Clone)]
struct ListUnsubscribe(String);
impl Header for ListUnsubscribe {
fn name() -> HeaderName {
HeaderName::new_from_ascii_str("List-Unsubscribe")
}
fn parse(s: &str) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
Ok(Self(s.trim().trim_start_matches('<').trim_end_matches('>').to_owned()))
}
fn display(&self) -> HeaderValue {
HeaderValue::new(Self::name(), format!("<{}>", self.0))
}
}
/// `List-Unsubscribe-Post`: the button unsubscribes with one POST (RFC 8058).
#[derive(Clone)]
struct ListUnsubscribePost;
impl Header for ListUnsubscribePost {
fn name() -> HeaderName {
HeaderName::new_from_ascii_str("List-Unsubscribe-Post")
}
fn parse(_: &str) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
Ok(Self)
}
fn display(&self) -> HeaderValue {
HeaderValue::new(Self::name(), "List-Unsubscribe=One-Click".into())
}
}
pub struct Delivery { pub struct Delivery {
pub db: PgPool, pub db: PgPool,
pub mailer: Mailer, pub mailer: Mailer,
@@ -127,7 +169,7 @@ impl Delivery {
for row in &rows { for row in &rows {
let attempts = row.attempts + 1; let attempts = row.attempts + 1;
let result = match templates::render(&row.template, &row.locale, &row.payload) { let result = match templates::render(&row.template, &row.locale, &row.payload) {
Ok(mail) => self.mailer.send(&self.from, &row.to_email, &mail).await, Ok(mail) => self.mailer.send(row.id, &self.from, &row.to_email, &mail).await,
Err(e) => Err(SendError::permanent(e)), Err(e) => Err(SendError::permanent(e)),
}; };
match result { match result {
+3 -1
View File
@@ -15,7 +15,9 @@ mod cleanup;
mod compare; mod compare;
mod config; mod config;
mod email; mod email;
mod templates; mod templates {
pub use email_templates::*;
}
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
-197
View File
@@ -1,197 +0,0 @@
//! E-mail texts (Hungarian and English), as plain text and HTML.
//!
//! The payloads are written by the backend (`queue_email`); the validity
//! periods in the texts match the token lifetimes there.
use serde_json::Value;
#[derive(Debug, Clone, PartialEq)]
pub struct Rendered {
pub subject: String,
pub text: String,
pub html: String,
}
#[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,
greeting: String,
intro: String,
button: &'static str,
url: String,
note: &'static str,
}
pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered, TemplateError> {
let lang = if locale.eq_ignore_ascii_case("hu") { Lang::Hu } else { Lang::En };
let url = payload["url"].as_str().filter(|u| !u.is_empty()).ok_or(TemplateError::MissingField("url"))?.to_owned();
let greeting = |name: Option<String>| 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 {
subject: "Erősítsd meg az e-mail-címed".into(),
greeting: greeting(name(payload, "display_name")),
intro: "Köszönjük, hogy regisztráltál a Sorsfonalakon! Az alábbi gombbal erősítsd meg az e-mail-címed."
.into(),
button: "E-mail-cím megerősítése",
url,
note: "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 {
subject: "Confirm your e-mail address".into(),
greeting: greeting(name(payload, "display_name")),
intro: "Thanks for signing up for Sorsfonalak! Please confirm your e-mail address with the button below."
.into(),
button: "Confirm e-mail address",
url,
note: "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 {
subject: "Új jelszó megadása".into(),
greeting: greeting(name(payload, "display_name")),
intro: "Jelszó-visszaállítást kértél a Sorsfonalak-fiókodhoz. Az alábbi gombbal adhatsz meg új jelszót."
.into(),
button: "Új jelszó megadása",
url,
note: "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 {
subject: "Set a new password".into(),
greeting: greeting(name(payload, "display_name")),
intro:
"You asked to reset the password of your Sorsfonalak account. Use the button below to set a new one."
.into(),
button: "Set a new password",
url,
note: "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 {
subject: match &who {
Some(n) => format!("{n} elfogadta a meghívásod"),
None => "Elfogadták a meghívásod".into(),
},
greeting: greeting(None),
intro: 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")
),
button: "Szinasztria megnyitása",
url,
note: "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 {
subject: match &who {
Some(n) => format!("{n} accepted your invitation"),
None => "Your invitation was accepted".into(),
},
greeting: greeting(None),
intro: format!(
"{} accepted your “How compatible are we?” invitation, and your synastry is ready.",
who.as_deref().unwrap_or("Your invitee")
),
button: "Open synastry",
url,
note: "You both see the synastry, but not each other's birth data.",
}
}
_ => return Err(TemplateError::UnknownTemplate(template.to_owned())),
};
Ok(content.render(lang))
}
/// A user-supplied name, safe for a subject line.
fn name(payload: &Value, field: &str) -> Option<String> {
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())
}
fn escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
_ => out.push(c),
}
}
out
}
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 text = format!(
"{}\n\n{}\n\n{}:\n{}\n\n{}\n\n-- \nSorsfonalak\n",
self.greeting, self.intro, self.button, self.url, self.note
);
let html = format!(
r#"<!doctype html>
<html lang="{lang}">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{subject}</title></head>
<body style="margin:0;padding:0;background:#f4f1ea;font-family:Georgia,'Times New Roman',serif;color:#2a2620">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f1ea;padding:32px 16px">
<tr><td align="center">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:520px;background:#ffffff;border-radius:8px;padding:32px">
<tr><td style="font-size:20px;letter-spacing:2px;color:#9a7b3c;padding-bottom:24px">SORSFONALAK</td></tr>
<tr><td style="font-size:16px;line-height:1.6;padding-bottom:12px">{greeting}</td></tr>
<tr><td style="font-size:16px;line-height:1.6;padding-bottom:24px">{intro}</td></tr>
<tr><td style="padding-bottom:24px"><a href="{url}" style="display:inline-block;background:#9a7b3c;color:#ffffff;text-decoration:none;padding:12px 24px;border-radius:6px;font-size:16px">{button}</a></td></tr>
<tr><td style="font-size:14px;line-height:1.6;color:#6b645a;padding-bottom:16px">{note}</td></tr>
<tr><td style="font-size:12px;line-height:1.5;color:#9b948a;word-break:break-all">{url_text}</td></tr>
</table>
<p style="font-size:12px;color:#9b948a;max-width:520px">{footer}</p>
</td></tr>
</table>
</body>
</html>
"#,
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),
footer = escape(footer),
);
Rendered { subject: self.subject, text, html }
}
}
+38 -2
View File
@@ -60,7 +60,7 @@ fn delivery(db: PgPool, fail: Vec<(&str, bool)>) -> Delivery {
fn sent(d: &Delivery) -> Vec<(String, String)> { fn sent(d: &Delivery) -> Vec<(String, String)> {
let Mailer::Memory { sent, .. } = &d.mailer else { unreachable!() }; let Mailer::Memory { sent, .. } = &d.mailer else { unreachable!() };
sent.lock().unwrap().iter().map(|(to, m)| (to.clone(), m.subject.clone())).collect() sent.lock().unwrap().iter().map(|(to, m, _)| (to.clone(), m.subject.clone())).collect()
} }
async fn queue(db: &PgPool, to: &str, template: &str) -> Uuid { async fn queue(db: &PgPool, to: &str, template: &str) -> Uuid {
@@ -123,6 +123,35 @@ async fn delivers_retries_and_gives_up(db: PgPool) {
assert_eq!(sent(&d).len(), 1); assert_eq!(sent(&d).len(), 1);
} }
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn invitation_headers_for_spam_filters(db: PgPool) {
let id = Uuid::now_v7();
sqlx::query(
"INSERT INTO email_outbox (id, to_email, template, locale, payload) VALUES ($1, $2, 'invitation', 'hu', $3)",
)
.bind(id)
.bind("guest@example.com")
.bind(json!({
"url": "https://example.com/meghivo/t",
"inviter_name": "Kata",
"message": null,
"expires_on": "2026-12-17",
"unsubscribe_url": "https://example.com/leiratkozas?token=t",
"unsubscribe_post_url": "https://example.com/api/v1/public/invitations/unsubscribe?token=t",
}))
.execute(&db)
.await
.unwrap();
let d = delivery(db.clone(), vec![]);
assert_eq!(d.deliver_due().await.unwrap(), 1);
let Mailer::Memory { sent, .. } = &d.mailer else { unreachable!() };
let raw = sent.lock().unwrap()[0].2.clone();
assert!(raw.contains(&format!("Message-ID: <{id}@example.com>")), "{raw}");
assert!(raw.contains("List-Unsubscribe: <https://example.com/api/v1/public/invitations/unsubscribe?token=t>"));
assert!(raw.contains("List-Unsubscribe-Post: List-Unsubscribe=One-Click"));
assert!(raw.contains("multipart/alternative") && raw.contains("text/plain") && raw.contains("text/html"));
}
#[sqlx::test(migrator = "db::MIGRATOR")] #[sqlx::test(migrator = "db::MIGRATOR")]
async fn concurrent_workers_do_not_send_twice(db: PgPool) { async fn concurrent_workers_do_not_send_twice(db: PgPool) {
for i in 0..15 { for i in 0..15 {
@@ -177,7 +206,14 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
let deleted = crate::cleanup::run_once(&db).await.unwrap(); let deleted = crate::cleanup::run_once(&db).await.unwrap();
assert_eq!( assert_eq!(
deleted, deleted,
vec![("sessions", 1), ("auth_tokens", 0), ("emails", 1), ("invites", 0), ("prompt_previews", 0)] vec![
("sessions", 1),
("auth_tokens", 0),
("emails", 1),
("invites", 0),
("invitations", 0),
("prompt_previews", 0)
]
); );
let (left,): (Vec<Uuid>,) = let (left,): (Vec<Uuid>,) =
sqlx::query_as("SELECT array_agg(id ORDER BY id) FROM email_outbox").fetch_one(&db).await.unwrap(); sqlx::query_as("SELECT array_agg(id ORDER BY id) FROM email_outbox").fetch_one(&db).await.unwrap();