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
+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);
}
}