Merge pull request 'Main' (#7) from main into prod
CI / test (push) Successful in 57s
CI / build (push) Successful in 1m20s
CI / deploy (push) Successful in 42s

Reviewed-on: #7
This commit was merged in pull request #7.
This commit is contained in:
2026-11-17 19:58:35 +01:00
45 changed files with 2715 additions and 264 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
+12
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"
@@ -2867,13 +2875,17 @@ dependencies = [
"analysis-prompt", "analysis-prompt",
"anyhow", "anyhow",
"axum", "axum",
"base64 0.22.1",
"db", "db",
"email-templates",
"hmac",
"lettre", "lettre",
"rand 0.9.5", "rand 0.9.5",
"reqwest", "reqwest",
"serde", "serde",
"serde_json", "serde_json",
"service-kit", "service-kit",
"sha2",
"sqlx", "sqlx",
"time", "time",
"tokio", "tokio",
+3
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,12 +28,14 @@ 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"] }
axum = "0.8" axum = "0.8"
axum-extra = { version = "0.10", features = ["cookie"] } axum-extra = { version = "0.10", features = ["cookie"] }
base64 = "0.22" base64 = "0.22"
hmac = "0.12"
jsonwebtoken = { version = "9", default-features = false } jsonwebtoken = { version = "9", default-features = false }
lettre = { version = "0.11", default-features = false, features = ["builder", "hostname", "smtp-transport", "tokio1", "tokio1-rustls", "webpki-roots", "ring"] } lettre = { version = "0.11", default-features = false, features = ["builder", "hostname", "smtp-transport", "tokio1", "tokio1-rustls", "webpki-roots", "ring"] }
rand = "0.9" rand = "0.9"
+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);
}
}
+7 -3
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: Amazon SES (docs/levelkuldes.md). The credentials go to .env.secrets:
SMTP_URL= # SES_SMTP_USERNAME + SES_SMTP_PASSWORD, or AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY.
MAIL_FROM=Sorsfonalak <noreply@sorsfonalak.hu> SES_REGION=eu-central-1
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 -6
View File
@@ -11,12 +11,8 @@
} }
{$DOMAIN} { {$DOMAIN} {
# Temporary gate until launch (user sf, password sf). Remove this block to open the site. # No basic auth any more: the site is open, and new accounts need an
# The privacy policy stays public (Google's OAuth consent screen links to it). # invitation (SIGNUP_MODE=invite in the backend).
@gated not path /adatvedelem /_next/static/* /favicon.ico /icon*
basic_auth @gated {
sf $2a$14$oggzzuNO41uGS5M.TCMlB.bQ6fdXUHtNLx9XahWyKLHjRlpEP1XN6
}
encode zstd gzip encode zstd gzip
reverse_proxy frontend:3000 reverse_proxy frontend:3000
} }
+6 -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
@@ -102,8 +104,10 @@ services:
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest} image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest}
environment: environment:
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
SMTP_URL: ${SMTP_URL:-} # SMTP_URL or the SES credentials come from .env.secrets (docs/levelkuldes.md);
MAIL_FROM: ${MAIL_FROM:-} # listing them here with an empty default would override that file.
SES_REGION: ${SES_REGION:-eu-central-1}
MAIL_FROM: ${MAIL_FROM:-Sorsfonalak <hello@sorsfonalak.hu>}
PUBLIC_BASE_URL: https://${DOMAIN} PUBLIC_BASE_URL: https://${DOMAIN}
env_file: env_file:
- path: .env.secrets - path: .env.secrets
+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
+95
View File
@@ -0,0 +1,95 @@
# Levélküldés élesben: Amazon SES
Élesben most nincs levélküldő beállítva (`SMTP_URL` üres), így minden levél az `email_outbox` táblában vár. Amíg ez így van, a meghívót kézzel is továbbadhatod: az admin „Meghívók” oldala küldés után kiírja a linket („Link másolása”).
A meghívó a legkényesebb levéltípus, mert a címzett nem kérte. A spammappát elsősorban a feladó hírneve és a domain hitelesítése dönti el, a sablon csak ezután számít. Ezért kellenek a lenti lépések.
A SES ára 1000 levelenként 0,10 USD; a mi forgalmunknál ez havi néhány cent.
## 1. Régió és domain (SES konzol)
1. **Régió:** `eu-central-1` (Frankfurt), hogy az adatok az EU-ban maradjanak. Minden lépést ebben a régióban kell elvégezni, mert a SES-beállítások régiónként külön élnek.
2. *Configuration → Identities → Create identity → Domain*: `sorsfonalak.hu`.
- **Easy DKIM**, RSA 2048 bit. A SES három CNAME-rekordot ad (lásd 3. pont).
- **Custom MAIL FROM domain:** `mail.sorsfonalak.hu`, és *Behavior on MX failure*: *Use default MAIL FROM domain*. Ettől az SPF is a saját domainünkre szól, ami a DMARC-nál számít. Ehhez egy MX- és egy TXT-rekord kell.
3. A domain igazolása után bármelyik `@sorsfonalak.hu` cím lehet feladó. Javaslat: `hello@sorsfonalak.hu`. A `noreply` cím a szűrőknél rosszabb, és válaszolni sem lehet rá.
## 2. Kilépés a homokozóból (sandbox)
Új SES-fiók homokozóban indul. Ilyenkor:
- csak igazolt címekre lehet küldeni (*Identities → Create identity → Email address*; teszteléshez a saját címed elég);
- naponta legfeljebb 200 levél megy ki.
Meghívót idegen címre csak éles hozzáféréssel lehet küldeni: *Account dashboard → Request production access*. Az AWS kézzel bírálja el, általában egy napon belül. A kérésben érdemes leírni:
- tranzakciós levelek (megerősítés, értesítés) és meghívók egy zártkörű oldalra;
- meghívót csak az admin küld, személyesen ismert embereknek, kis mennyiségben;
- minden meghívóban egykattintásos leiratkozás van, a leiratkozott címekre többé nem megy levél;
- a visszapattanó és panaszos címeket a SES fiókszintű tiltólistája kezeli (*Suppression list*: bounces és complaints).
Fontos: ha a visszapattanási arány 5%, vagy a panaszarány 0,1% fölé megy, az AWS felfüggesztheti a küldést. Ezért csak olyan címre küldj meghívót, amelyről tudod, hogy él.
## 3. DNS a Cloudflare-en
| Típus | Név | Tartalom |
|---|---|---|
| CNAME ×3 | `<kód>._domainkey` | `<kód>.dkim.amazonses.com` (a SES konzol kiírja mindhármat) |
| MX | `mail` | `feedback-smtp.eu-central-1.amazonses.com`, prioritás 10 |
| TXT | `mail` | `v=spf1 include:amazonses.com ~all` |
| TXT | `_dmarc` | `v=DMARC1; p=none; rua=mailto:<a te címed>` |
- Minden rekord **DNS only** (szürke felhő) legyen; a proxyzott CNAME-mel a DKIM nem működik.
- DMARC: induláskor `p=none` (csak jelentés). Ha pár hétig minden levél átmegy, szigorítható `p=quarantine`-ra.
- Ha a `hello@sorsfonalak.hu` címre érkező válaszokat is olvasni szeretnéd: a Cloudflare *Email Routing* ingyen továbbítja őket a Gmailedre. Ez a fő domainre (`sorsfonalak.hu`) tesz MX- és SPF-rekordot, ami nem ütközik a `mail.` aldomain rekordjaival.
## 4. Hozzáférés
Két út van, mindkettő a szerver `.env.secrets` fájljába kerül (kis- vagy nagybetűvel is jó):
- **SMTP-hozzáférés** (*SMTP settings → Create SMTP credentials*): egy IAM-felhasználó, amely csak levelet küldhet.
```
SES_SMTP_USERNAME=AKIA...
SES_SMTP_PASSWORD=...
```
- **IAM-kulcspár**, amelynek van `ses:SendRawEmail` joga:
```
AWS_ACCESS_KEY_ID=AKIA...
AWS_SECRET_ACCESS_KEY=...
```
Más nevek is jók: a kulcsnál `SES_AUTH_KEY`, `SES_ACCESS_KEY`, `SES_KEY`, `AUTH_KEY`, a titoknál `SES_SECRET`, `SES_SECRET_KEY`, `AWS_SECRET`, `AUTH_SECRET` (a teljes lista: `services/worker/src/ses.rs`).
A worker ebből az AWS által leírt módon kiszámolja az SMTP-jelszót. Ha az `AWS_SECRET_ACCESS_KEY` helyére az SMTP-jelszót írtad, azt is felismeri, és változatlanul használja.
A régió alapból `eu-central-1` (Frankfurt); felülírható a `SES_REGION` változóval. A port 2587, ezt a `SES_SMTP_PORT` írja felül. URL-kódolásra itt nincs szükség, mert a worker maga állítja össze a címet.
## 5. Tűzfal
A DigitalOcean a dropleteken tiltja a szokásos kimenő SMTP-portokat (25, 465, 587). A SES erre a **2587**-es portot (STARTTLS) is kínálja.
A droplet saját tűzfala (`sorsfonalak-fw`, DigitalOcean → Networking → Firewalls) a kimenő forgalmat is szűri. Az **Outbound rules** közé fel kell venni a **TCP 2587**-et (cél: All IPv4, All IPv6), különben a worker nem éri el a SES-t.
## 6. Indítás
- A `.env` fájlban opcionális: `MAIL_FROM=Sorsfonalak <hello@sorsfonalak.hu>` (ez az alapérték is).
- Utána: `docker compose up -d worker`. A naplóban ennek kell megjelennie: `e-mail delivery enabled`, `via=Amazon SES eu-central-1:2587, credentials from …`.
- Az eddig várakozó levelek ekkor kimennek. Ha ezt nem szeretnéd, előtte töröld őket: `DELETE FROM email_outbox WHERE sent_at IS NULL;`.
- Hibaüzenetek a naplóban:
- `535 Authentication Credentials Invalid`: hibás kulcs, vagy az IAM-felhasználónak nincs `ses:SendRawEmail` joga;
- `554 Message rejected: Email address is not verified`: a fiók még homokozóban van, és a címzett nincs igazolva;
- időtúllépés: a tűzfalon nincs engedélyezve a kimenő 2587-es port.
- Ha mégis kész SMTP-címet adnál meg, az `SMTP_URL` mindig elsőbbséget élvez a SES-változókkal szemben.
## 7. Próba
1. Admin → Meghívók → **Teszt küldése magamnak**: megérkezik-e, és nem a spamben van-e.
2. A Gmailben a levélnél *⋮ → Eredeti megjelenítése*: az SPF, a DKIM és a DMARC mellett is `PASS` álljon.
3. A [mail-tester.com](https://www.mail-tester.com) ad egy egyszeri címet. Küldj rá meghívót az admin oldalról (utána vond vissza), és nézd meg a pontszámot; 9/10 fölött jó. Ehhez már éles hozzáférés kell.
## Amit a kód már elintéz
- HTML és szöveges változat ugyanazzal a tartalommal. Egyhasábos, képek és követés nélkül, minden link a saját domainre mutat.
- `List-Unsubscribe` és `List-Unsubscribe-Post` (RFC 8058): a Gmail és a többi levelező saját „Leiratkozás” gombot mutat. Aki leiratkozik, annak a címére soha többé nem megy meghívó (`email_optouts`, csak a cím hash-e).
- A worker saját domaines `Message-ID`-t tesz a levélre. A SES ezt a sajátjára cseréli, ami rendben van.
- Meghívót csak admin küldhet. Egy meghívó legfeljebb háromszor megy ki, 24 óránként egyszer. A személyes üzenet legfeljebb 300 karakter, és nem lehet benne link.
## Később
A visszapattanásokról és panaszokról a SES utólag, SNS-értesítésben szól; az SMTP-kapcsolat ezt nem jelzi. Ha lesz forgalom, érdemes bekötni egy SNS → backend webhookot. Ez a meghívólistán megjelölné a visszapattant címeket, és a panaszt tevőket a leiratkozottak közé tenné.
+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
+18 -4
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 |
@@ -124,5 +138,5 @@ A [worker](../worker/README.md) kiküldi az e-maileket, megírja az elemzéseket
## Korlátok ## Korlátok
- **Saját születési adatok módosítása:** az első mentés után egy órán belül még háromszor javíthatók, utána naponta egyszer (`birth_data_changes` tábla). A tiltott módosítás 429-et ad `birth_data_change_limit` kóddal, a felhasználónak szóló üzenettel („A rendszer csak napi egy módosítást engedélyez. …”). A `/v1/me` `birth_change` mezője mutatja, él-e a napi korlát. Más emberek képleteit ez nem érinti. - **Saját születési adatok módosítása:** az első mentés után egy órán belül még háromszor javíthatók, utána naponta egyszer (`birth_data_changes` tábla). A tiltott módosítás 429-et ad `birth_data_change_limit` kóddal, a felhasználónak szóló üzenettel („A rendszer csak napi egy módosítást engedélyez. …”). A `/v1/me` `birth_change` mezője mutatja, él-e a napi korlát. Más emberek képleteit ez nem érinti.
- **Személyek** (más emberek képletei, `charts.kind = 'person'`): minden új személy egy `person` egységet használ (`credit_ledger`, `reason = 'person'`); a törlés nem adja vissza. Helyet a csomagok adnak; korlátlan az `unlimited_persons` jogosultsággal és futó Korlátlan csomaggal. Ha elfogyott, 409 `person_limit_reached`. Egy személy születési adatai a felvétel után egy órán belül javíthatók (`PATCH /v1/charts/{id}` `birth` mezővel), utána 409 `person_locked`. Részletes elemzés (képlet vagy összevetés) után sem (409 `person_analysed`), és akkor sem, ha valaki más összevetésében szerepel (409 `person_in_synastry`); a saját, elemzés nélküli összevetései a javításkor törlődnek. A `/v1/me` `persons` mezője: `used`, `limit`, `left`, `unlimited`. - **Személyek** (más emberek képletei, `charts.kind = 'person'`): minden új személy egy `person` egységet használ (`credit_ledger`, `reason = 'person'`); a törlés nem adja vissza. Helyet a csomagok adnak; korlátlan az `unlimited_persons` jogosultsággal és futó Korlátlan csomaggal. Ha elfogyott, 409 `person_limit_reached`. Egy személy születési adatai a felvétel után egy órán belül javíthatók (`PATCH /v1/charts/{id}` `birth` mezővel), utána 409 `person_locked`. A név (`label`) bármikor változhat; ha a `birth` ugyanaz, mint a tárolt (vagy ugyanazt a képletet adja), nincs újraszámolás, és az elemzések, összevetések maradnak. Részletes elemzés (képlet vagy összevetés) után sem (409 `person_analysed`), és akkor sem, ha valaki más összevetésében szerepel (409 `person_in_synastry`); a saját, elemzés nélküli összevetései a javításkor törlődnek. A `/v1/me` `persons` mezője: `used`, `limit`, `left`, `unlimited`.
- **Admin:** nincs módosítási korlát, korlátlan személy, a személyek adatai bármikor javíthatók, és a részletes elemzés ingyenes (nem fogy egység). - **Admin:** nincs módosítási korlát, korlátlan személy, a személyek adatai bármikor javíthatók, és a részletes elemzés ingyenes (nem fogy egység).
+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)
} }
}; };
+15 -5
View File
@@ -267,15 +267,25 @@ pub async fn update(
None => chart.label.clone(), None => chart.label.clone(),
}; };
let is_primary = req.is_primary.unwrap_or(chart.is_primary); let is_primary = req.is_primary.unwrap_or(chart.is_primary);
let recalculated = match req.birth { // The same birth data again (e.g. only the name changed): no recalculation,
// and the analyses and comparisons stay. A new calculation that gives the
// same chart keeps them too.
let birth = req.birth.map(clean_birth).transpose()?.filter(|b| *b != chart.birth_data);
let recalculated = match birth {
Some(birth) => Some(corrected_birth(&state, &auth, &chart, birth).await?), Some(birth) => Some(corrected_birth(&state, &auth, &chart, birth).await?),
None => None, None => None,
}; };
let chart_changed = recalculated.as_ref().is_some_and(|(_, _, hash)| *hash != chart.chart_hash);
let mut tx = state.db.begin().await?; let mut tx = state.db.begin().await?;
if let Some((birth, result, hash)) = &recalculated { if let Some((birth, result, hash)) = &recalculated {
// The old summary, the comparisons (and an admin's analyses) no longer match the chart. if chart_changed {
sqlx::query("DELETE FROM analyses WHERE chart_id = $1").bind(id).execute(&mut *tx).await?; // The old summary, the comparisons (and an admin's analyses) no longer match the chart.
sqlx::query("DELETE FROM synastries WHERE chart1_id = $1 OR chart2_id = $1").bind(id).execute(&mut *tx).await?; sqlx::query("DELETE FROM analyses WHERE chart_id = $1").bind(id).execute(&mut *tx).await?;
sqlx::query("DELETE FROM synastries WHERE chart1_id = $1 OR chart2_id = $1")
.bind(id)
.execute(&mut *tx)
.await?;
}
sqlx::query("UPDATE charts SET birth_data = $1, result = $2, chart_hash = $3 WHERE id = $4") sqlx::query("UPDATE charts SET birth_data = $1, result = $2, chart_hash = $3 WHERE id = $4")
.bind(birth) .bind(birth)
.bind(result) .bind(result)
@@ -303,7 +313,7 @@ pub async fn update(
birth_changes::record(&mut tx, &auth, id).await?; birth_changes::record(&mut tx, &auth, id).await?;
} }
tx.commit().await?; tx.commit().await?;
if recalculated.is_some() { if chart_changed {
queue_summary(&state, &auth, &row).await; queue_summary(&state, &auth, &row).await;
} }
Ok(Json(row.owner_view())) Ok(Json(row.owner_view()))
+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,
})) }))
} }
+179 -1
View File
@@ -802,7 +802,8 @@ async fn persons_use_package_slots(pool: PgPool) {
.execute(&app.pool) .execute(&app.pool)
.await .await
.unwrap(); .unwrap();
let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(corrected.clone())).await; let again = json!({"birth": {"date": "1986-01-03", "time": "10:00", "country": "HU", "place": "Szeged"}});
let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(again)).await;
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("person_locked"))); assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("person_locked")));
let r = let r =
app.call("PATCH", &format!("/v1/charts/{}", own["id"].as_str().unwrap()), Some(&anna), Some(corrected)).await; app.call("PATCH", &format!("/v1/charts/{}", own["id"].as_str().unwrap()), Some(&anna), Some(corrected)).await;
@@ -1068,3 +1069,180 @@ async fn packages_grant_units_and_unlimited(pool: PgPool) {
assert_eq!(r.status, StatusCode::PAYMENT_REQUIRED); assert_eq!(r.status, StatusCode::PAYMENT_REQUIRED);
assert_eq!(app.get("/v1/me", Some(&bela)).await.body["unlimited_until"], Value::Null); assert_eq!(app.get("/v1/me", Some(&bela)).await.body["unlimited_until"], Value::Null);
} }
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn renaming_a_person_keeps_chart_and_analyses(pool: PgPool) {
let app = TestApp::new(pool.clone()).await;
let anna = app.register("anna@example.com", "Anna").await;
let own = app.chart(&anna, "Saját", true, "1990-03-15").await;
let bela = app.chart(&anna, "Béla", false, "1985-08-02").await;
let id = bela["id"].as_str().unwrap();
let syn = app.post("/v1/synastries", Some(&anna), json!({"chart1_id": own["id"], "chart2_id": id})).await;
assert_eq!(syn.status, StatusCode::CREATED);
let summaries = || async {
let (n,): (i64,) = sqlx::query_as("SELECT count(*) FROM analyses WHERE chart_id = $1::uuid")
.bind(id)
.fetch_one(&pool)
.await
.unwrap();
n
};
assert_eq!(summaries().await, 1);
// the edit form sends the unchanged birth data with the new name
let same = json!({"label": "Béla bácsi",
"birth": {"date": "1985-08-02", "time": "14:30", "country": "HU", "place": "Szeged"}});
let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(same.clone())).await;
assert_eq!(
(r.status, &r.body["label"], &r.body["chart_hash"]),
(StatusCode::OK, &json!("Béla bácsi"), &bela["chart_hash"])
);
assert_eq!(summaries().await, 1);
let r = app.get(&format!("/v1/synastries/{}", syn.body["id"].as_str().unwrap()), Some(&anna)).await;
assert_eq!(r.status, StatusCode::OK);
// after the correction window the name can still change
sqlx::query("UPDATE charts SET created_at = now() - interval '2 hours' WHERE id = $1::uuid")
.bind(id)
.execute(&pool)
.await
.unwrap();
let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(json!({"label": "Béla"}))).await;
assert_eq!((r.status, &r.body["label"]), (StatusCode::OK, &json!("Béla")));
let r = app.call("PATCH", &format!("/v1/charts/{id}"), Some(&anna), Some(same)).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
}
async fn google_signup(app: &TestApp, sub: &str, email: &str, invite: Option<&str>) -> Response {
app.post(
"/v1/auth/google",
None,
json!({"id_token": google_token(sub, email, GOOGLE_CLIENT), "invite_token": invite}),
)
.await
}
fn invite_token(url: &str) -> String {
url.rsplit('/').next().unwrap().to_string()
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn invitation_only_signup(pool: PgPool) {
let app = TestApp::with_config(pool.clone(), |c| c.signup_mode = crate::config::SignupMode::Invite).await;
assert_eq!(app.get("/v1/config", None).await.body["signup_mode"], "invite");
// nobody gets in uninvited, except the bootstrap admin
let r = google_signup(&app, "g-x", "stranger@gmail.com", None).await;
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::FORBIDDEN, Some("not_invited")));
let admin = app.register("admin@example.com", "Admin").await;
// an existing user (from before the invitation-only times) is not an admin
let user = {
let open = TestApp::new(pool.clone()).await;
open.register("anna@example.com", "Anna").await
};
// inviting: duplicates, invalid addresses and existing users are sorted out
let r = app
.post(
"/v1/admin/invitations",
Some(&admin),
json!({"emails": ["Guest@Example.com", "guest@example.com", "nope", "anna@example.com", "kata@example.com"],
"message": "Gyere, nézd meg!"}),
)
.await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
let statuses: Vec<&str> =
r.body["results"].as_array().unwrap().iter().map(|x| x["status"].as_str().unwrap()).collect();
assert_eq!(statuses, ["invited", "invalid", "already_user", "invited"]);
let guest_url = r.body["results"][0]["url"].as_str().unwrap().to_string();
let guest_id = r.body["results"][0]["id"].as_str().unwrap().to_string();
let guest_token = invite_token(&guest_url);
let r = app.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["guest@example.com"]})).await;
assert_eq!(r.body["results"][0]["status"], "already_invited");
let r = app
.post(
"/v1/admin/invitations",
Some(&admin),
json!({"emails": ["x@example.com"], "message": "nézd: www.spam.hu"}),
)
.await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
assert_eq!(app.get("/v1/admin/invitations", Some(&user)).await.status, StatusCode::FORBIDDEN);
// the e-mail and the landing page
let (payload,): (Value,) = sqlx::query_as(
"SELECT payload FROM email_outbox WHERE to_email = 'guest@example.com' AND template = 'invitation'",
)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(payload["url"], guest_url.as_str());
assert_eq!(payload["inviter_name"], "Admin");
assert!(
payload["unsubscribe_post_url"].as_str().unwrap().contains("/api/v1/public/invitations/unsubscribe?token=")
);
let r = app.get(&format!("/v1/public/invitations/{guest_token}"), None).await;
assert_eq!((r.body["inviter_name"].as_str(), r.body["status"].as_str()), (Some("Admin"), Some("pending")));
// a resend: not too soon, then with a new link; the old one keeps working
let r = app.post(&format!("/v1/admin/invitations/{guest_id}/resend"), Some(&admin), json!({})).await;
assert_eq!(r.body["error"]["code"], "resend_too_soon");
sqlx::query("UPDATE invitations SET last_sent_at = now() - interval '25 hours'").execute(&pool).await.unwrap();
let r = app.post(&format!("/v1/admin/invitations/{guest_id}/resend"), Some(&admin), json!({})).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_ne!(r.body["url"], guest_url.as_str());
// the link lets in any Google account, once
let r = google_signup(&app, "g-1", "guests.other.account@gmail.com", Some(&guest_token)).await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
let r = google_signup(&app, "g-2", "third@gmail.com", Some(&guest_token)).await;
assert_eq!(r.body["error"]["code"], "not_invited");
// the invited address itself gets in without the link
assert_eq!(google_signup(&app, "g-3", "kata@example.com", None).await.status, StatusCode::CREATED);
// revoked: no entry
let r = app
.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["zoli@example.com", "mari@example.com"]}))
.await;
let zoli_id = r.body["results"][0]["id"].as_str().unwrap().to_string();
let mari_token = invite_token(r.body["results"][1]["url"].as_str().unwrap());
assert_eq!(
app.call("DELETE", &format!("/v1/admin/invitations/{zoli_id}"), Some(&admin), None).await.status,
StatusCode::NO_CONTENT
);
assert_eq!(google_signup(&app, "g-4", "zoli@example.com", None).await.status, StatusCode::FORBIDDEN);
// unsubscribing (one-click POST): the invitation closes and no new one can be sent
let r = app.call("POST", &format!("/v1/public/invitations/unsubscribe?token={mari_token}"), None, None).await;
assert_eq!(r.status, StatusCode::OK);
assert_eq!(google_signup(&app, "g-5", "mari@example.com", None).await.status, StatusCode::FORBIDDEN);
let r = app.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["MARI@example.com"]})).await;
assert_eq!(r.body["results"][0]["status"], "opted_out");
// the waitlist: joining reveals nothing, an invited and accepted address leaves it
for email in ["wait@example.com", "anna@example.com"] {
let r = app.post("/v1/public/waitlist", None, json!({"email": email})).await;
assert_eq!(r.status, StatusCode::ACCEPTED);
}
let list = app.get("/v1/admin/invitations", Some(&admin)).await.body;
assert_eq!(list["waitlist"].as_array().unwrap().len(), 1);
let statuses: Vec<(&str, &str)> = list["invitations"]
.as_array()
.unwrap()
.iter()
.map(|i| (i["email"].as_str().unwrap(), i["status"].as_str().unwrap()))
.collect();
assert!(
statuses.contains(&("guest@example.com", "accepted")) && statuses.contains(&("zoli@example.com", "revoked"))
);
app.post("/v1/admin/invitations", Some(&admin), json!({"emails": ["wait@example.com"]})).await;
assert_eq!(google_signup(&app, "g-6", "wait@example.com", None).await.status, StatusCode::CREATED);
assert!(app.get("/v1/admin/invitations", Some(&admin)).await.body["waitlist"].as_array().unwrap().is_empty());
// preview and a test copy to the admin
let r =
app.post("/v1/admin/invitations/preview", Some(&admin), json!({"message": "Szia!", "send_to_me": true})).await;
assert_eq!(r.body["subject"], "Admin meghívott a Sorsfonalakra");
assert!(r.body["html"].as_str().unwrap().contains("Szia!") && r.body["text"].as_str().unwrap().contains("> Szia!"));
assert_eq!(app.outbox_url("admin@example.com", "invitation").await, "https://sorsfonalak.test/meghivo/minta");
}
@@ -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>Amazon Web Services EMEA SARL</strong> (Amazon SES) – a rendszerlevelek és a meghívók kézbesítése;
az Európai Unióban (Frankfurt).
</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,59 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
/** Changes only a person's name (any time; the chart and analyses stay). */
export function RenamePerson({ id, name }: { id: string; name: string }) {
const router = useRouter();
const [value, setValue] = useState(name);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function save(e: React.FormEvent) {
e.preventDefault();
if (!value.trim()) return setError("Add meg a nevét.");
setBusy(true);
setError(null);
try {
await api(`/charts/${id}`, { method: "PATCH", body: { label: value.trim() } });
router.push(`/kepletek/${id}`);
router.refresh();
} catch (err) {
setError(errorText(err));
setBusy(false);
}
}
return (
<form onSubmit={save} className="field" style={{ gap: 16 }} noValidate>
<div className="field" style={{ maxWidth: 420 }}>
<label htmlFor="rename">Név</label>
<input
id="rename"
className="inp"
value={value}
maxLength={100}
autoComplete="off"
onChange={(e) => setValue(e.target.value)}
required
/>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={busy || value.trim() === name}>
{busy ? "Mentés…" : "Név mentése"}
</button>
<button type="button" className="btn btn-ghost" onClick={() => router.push(`/kepletek/${id}`)} disabled={busy}>
Mégse
</button>
</div>
</form>
);
}
@@ -1,17 +1,17 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { backendGet, requireMe } from "@/lib/server"; import { backendGet, requireMe } from "@/lib/server";
import type { Chart } from "@/lib/types"; import type { Chart } from "@/lib/types";
import { EditPerson } from "./EditPerson"; import { EditPerson } from "./EditPerson";
import { RenamePerson } from "./RenamePerson";
export const metadata: Metadata = { title: "Adatok javítása" }; export const metadata: Metadata = { title: "Adatok javítása" };
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/** Correcting a person's birth data (within an hour of adding them; admins any time). */ /** Correcting a person: name any time, birth data within an hour of adding them (admins any time). */
export default async function EditPersonPage({ params }: { params: Promise<{ id: string }> }) { export default async function EditPersonPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params; const { id } = await params;
const me = await requireMe(`/kepletek/${id}/javitas`); const me = await requireMe(`/kepletek/${id}/javitas`);
@@ -26,7 +26,9 @@ export default async function EditPersonPage({ params }: { params: Promise<{ id:
<div className="page-head"> <div className="page-head">
<h1>{chart.label} adatai</h1> <h1>{chart.label} adatai</h1>
<p className="muted"> <p className="muted">
A javítás után újraszámoljuk a képletet és a rövid összefoglalót. {editable
? "Ha a születési adatokon változtatsz, újraszámoljuk a képletet és a rövid összefoglalót. A név módosítása a képletet és az elemzéseket nem érinti."
: "A név bármikor módosítható; a képlet és az elemzések maradnak."}
</p> </p>
</div> </div>
<section className="card" aria-label="Születési adatok"> <section className="card" aria-label="Születési adatok">
@@ -42,10 +44,8 @@ export default async function EditPersonPage({ params }: { params: Promise<{ id:
/> />
) : ( ) : (
<> <>
<p className="muted">A személy születési adatai csak a felvételt követő egy órán belül javíthatók.</p> <RenamePerson id={id} name={chart.label} />
<Link href={`/kepletek/${id}`} className="btn" style={{ alignSelf: "flex-start" }}> <p className="hint">A születési adatok csak a felvételt követő egy órán belül javíthatók.</p>
Vissza a képlethez
</Link>
</> </>
)} )}
</section> </section>
@@ -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)}`);
}
+10 -1
View File
@@ -69,10 +69,19 @@ export function BirthForm({
geonames_id: place.geonames_id, geonames_id: place.geonames_id,
...(ambiguous ? { ambiguous_time: ambiguity } : {}), ...(ambiguous ? { ambiguous_time: ambiguity } : {}),
}; };
// Correcting a person: the birth data only when it changed, so a new
// name alone does not recalculate the chart or drop its analyses.
const birthChanged =
!initial ||
ambiguous ||
date !== initial.date ||
(timeUnknown ? null : time) !== (initial.time?.slice(0, 5) ?? null) ||
country !== (initial.country ?? "HU") ||
place.geonames_id !== initial.geonames_id;
const saved = person?.chartId const saved = person?.chartId
? await api<{ id: string }>(`/charts/${person.chartId}`, { ? await api<{ id: string }>(`/charts/${person.chartId}`, {
method: "PATCH", method: "PATCH",
body: { label: name.trim(), birth }, body: birthChanged ? { label: name.trim(), birth } : { label: name.trim() },
}) })
: await api<{ id: string }>("/charts", { : await api<{ id: string }>("/charts", {
body: person body: person
@@ -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" },
]; ];
@@ -53,11 +53,9 @@ export function PersonActions({
) : ( ) : (
<> <>
{ownId && <CompareButton chart1={ownId} chart2={id} />} {ownId && <CompareButton chart1={ownId} chart2={id} />}
{editable && ( <Link href={`/kepletek/${id}/javitas`} className="btn btn-sm btn-ghost">
<Link href={`/kepletek/${id}/javitas`} className="btn btn-sm btn-ghost"> {editable ? "Adatok javítása" : "Átnevezés"}
Adatok javítása </Link>
</Link>
)}
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setConfirm(true)}> <button type="button" className="btn btn-sm btn-ghost" onClick={() => setConfirm(true)}>
Törlés Törlés
</button> </button>
@@ -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;
}
+4
View File
@@ -9,14 +9,18 @@ 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
base64.workspace = true
hmac.workspace = true
lettre.workspace = true lettre.workspace = true
rand.workspace = true rand.workspace = true
reqwest.workspace = true reqwest.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
sha2.workspace = true
sqlx.workspace = true sqlx.workspace = true
time.workspace = true time.workspace = true
tokio.workspace = true tokio.workspace = true
+6 -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.
@@ -61,6 +63,8 @@ Ugyanazt a radix-elemzést több modellel is megírja, véletlenszerű betűkkel
|---|---|---| |---|---|---|
| `DATABASE_URL` | – (kötelező) | PostgreSQL kapcsolat | | `DATABASE_URL` | – (kötelező) | PostgreSQL kapcsolat |
| `SMTP_URL` | – | `smtp://mailpit:1025` (fejlesztés), `smtp://user:pass@host:587?tls=required` (STARTTLS), `smtps://user:pass@host:465` (TLS) | | `SMTP_URL` | – | `smtp://mailpit:1025` (fejlesztés), `smtp://user:pass@host:587?tls=required` (STARTTLS), `smtps://user:pass@host:465` (TLS) |
| `AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` | – | Amazon SES, ha nincs `SMTP_URL` (a `.env.secrets` fájlból; más nevek is jók, lásd `src/ses.rs`). A titkos kulcsból a worker kiszámolja az SMTP-jelszót. Helyettük `SES_SMTP_USERNAME` + `SES_SMTP_PASSWORD` is megadható |
| `SES_REGION`, `SES_SMTP_PORT` | `eu-central-1`, `2587` | SES-régió és port (a DigitalOcean a 25-ös, 465-ös és 587-es portot tiltja) |
| `MAIL_FROM` | `Sorsfonalak <noreply@sorsfonalak.local>` | feladó | | `MAIL_FROM` | `Sorsfonalak <noreply@sorsfonalak.local>` | feladó |
| `POLL_INTERVAL_SECS` | `30` | tartalék lekérdezési időköz | | `POLL_INTERVAL_SECS` | `30` | tartalék lekérdezési időköz |
| `MAX_EMAIL_ATTEMPTS` | `8` | ennyi próbálkozás után sikertelen a levél | | `MAX_EMAIL_ATTEMPTS` | `8` | ennyi próbálkozás után sikertelen a levé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'"),
]; ];
+13 -2
View File
@@ -8,8 +8,11 @@ use lettre::message::Mailbox;
pub struct Config { pub struct Config {
pub database_url: String, pub database_url: String,
/// `smtp://host:port` (plain, e.g. Mailpit), `smtp://user:pass@host:587?tls=required` /// `smtp://host:port` (plain, e.g. Mailpit), `smtp://user:pass@host:587?tls=required`
/// (STARTTLS) or `smtps://...` (TLS). Unset: e-mails stay in the outbox. /// (STARTTLS) or `smtps://...` (TLS). Without it, Amazon SES from the AWS
/// variables (see `ses.rs`). Neither: e-mails stay in the outbox.
pub smtp_url: Option<String>, pub smtp_url: Option<String>,
/// For the log: where the SMTP address came from (no secrets).
pub smtp_about: Option<String>,
/// Sender, e.g. `Sorsfonalak <noreply@sorsfonalak.hu>`. /// Sender, e.g. `Sorsfonalak <noreply@sorsfonalak.hu>`.
pub mail_from: Mailbox, pub mail_from: Mailbox,
/// Fallback polling interval; new e-mails are picked up at once via LISTEN/NOTIFY. /// Fallback polling interval; new e-mails are picked up at once via LISTEN/NOTIFY.
@@ -44,9 +47,17 @@ where
impl Config { impl Config {
pub fn from_env() -> anyhow::Result<Self> { pub fn from_env() -> anyhow::Result<Self> {
let mail_from = var("MAIL_FROM").unwrap_or_else(|| "Sorsfonalak <noreply@sorsfonalak.local>".into()); let mail_from = var("MAIL_FROM").unwrap_or_else(|| "Sorsfonalak <noreply@sorsfonalak.local>".into());
let (smtp_url, smtp_about) = match var("SMTP_URL") {
Some(url) => (Some(url), None),
None => match crate::ses::smtp_url(|name| std::env::var(name).ok())? {
Some((url, about)) => (Some(url), Some(about)),
None => (None, None),
},
};
Ok(Self { Ok(Self {
database_url: var("DATABASE_URL").context("DATABASE_URL is required")?, database_url: var("DATABASE_URL").context("DATABASE_URL is required")?,
smtp_url: var("SMTP_URL"), smtp_url,
smtp_about,
mail_from: mail_from.parse().with_context(|| format!("invalid MAIL_FROM '{mail_from}'"))?, mail_from: mail_from.parse().with_context(|| format!("invalid MAIL_FROM '{mail_from}'"))?,
poll_interval: Duration::from_secs(parsed("POLL_INTERVAL_SECS", 30)?), poll_interval: Duration::from_secs(parsed("POLL_INTERVAL_SECS", 30)?),
max_email_attempts: parsed("MAX_EMAIL_ATTEMPTS", 8)?, max_email_attempts: parsed("MAX_EMAIL_ATTEMPTS", 8)?,
+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 {
+7 -3
View File
@@ -15,7 +15,10 @@ mod cleanup;
mod compare; mod compare;
mod config; mod config;
mod email; mod email;
mod templates; mod ses;
mod templates {
pub use email_templates::*;
}
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
@@ -91,10 +94,11 @@ async fn main() -> anyhow::Result<()> {
match &config.smtp_url { match &config.smtp_url {
Some(url) => { Some(url) => {
let delivery = email::Delivery::new(pool.clone(), email::Mailer::smtp(url)?, &config); let delivery = email::Delivery::new(pool.clone(), email::Mailer::smtp(url)?, &config);
tracing::info!(host = %email::smtp_host(url), "e-mail delivery enabled"); let via = config.smtp_about.clone().unwrap_or_else(|| "SMTP_URL".into());
tracing::info!(host = %email::smtp_host(url), via = %via, from = %config.mail_from, "e-mail delivery enabled");
jobs.spawn(email::run(delivery, config.poll_interval, stop.clone())); jobs.spawn(email::run(delivery, config.poll_interval, stop.clone()));
} }
None => tracing::warn!("SMTP_URL is not set: e-mails stay in the outbox"), None => tracing::warn!("neither SMTP_URL nor SES credentials are set: e-mails stay in the outbox"),
} }
match &config.openrouter_api_key { match &config.openrouter_api_key {
Some(key) => { Some(key) => {
+172
View File
@@ -0,0 +1,172 @@
//! Amazon SES over SMTP, configured from AWS-style variables when `SMTP_URL`
//! is not set (so the credentials can sit in `.env.secrets` as they are).
//!
//! Accepted (upper or lower case):
//! * `SES_SMTP_USERNAME` + `SES_SMTP_PASSWORD`: SMTP credentials from the SES console;
//! * or `AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` (or another name from
//! `KEY_NAMES` / `SECRET_NAMES`, e.g. `ses_auth_key` + `ses_secret`): an IAM
//! key allowed `ses:SendRawEmail`; the SMTP
//! password is derived from it as AWS documents. If the "secret" already is
//! an SMTP password, it is used as it is.
//! * `SES_REGION` / `AWS_REGION` / `AWS_DEFAULT_REGION` (default `eu-central-1`),
//! `SES_SMTP_PORT` (default 2587, STARTTLS: DigitalOcean blocks 25, 465 and 587).
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use hmac::{Hmac, Mac};
use sha2::Sha256;
pub const DEFAULT_REGION: &str = "eu-central-1";
/// Names the access key id may have in a secrets file.
const KEY_NAMES: &[&str] = &[
"SES_ACCESS_KEY_ID",
"AWS_ACCESS_KEY_ID",
"SES_AUTH_KEY",
"SES_ACCESS_KEY",
"SES_KEY",
"AWS_AUTH_KEY",
"AWS_ACCESS_KEY",
"AUTH_KEY",
];
/// Names the secret access key may have.
const SECRET_NAMES: &[&str] = &[
"SES_SECRET_ACCESS_KEY",
"AWS_SECRET_ACCESS_KEY",
"SES_SECRET",
"SES_SECRET_KEY",
"SES_AUTH_SECRET",
"AWS_SECRET",
"AWS_SECRET_KEY",
"AUTH_SECRET",
];
const DEFAULT_PORT: u16 = 2587;
/// The first set variable among `names`, each tried in upper and lower case.
fn var(lookup: &impl Fn(&str) -> Option<String>, names: &[&str]) -> Option<(String, String)> {
names.iter().find_map(|name| {
[name.to_string(), name.to_lowercase()]
.into_iter()
.find_map(|n| lookup(&n).map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()).map(|v| (n, v)))
})
}
/// The SES SMTP address and a description for the log (no secrets), if credentials are set.
pub fn smtp_url(lookup: impl Fn(&str) -> Option<String>) -> anyhow::Result<Option<(String, String)>> {
let region =
var(&lookup, &["SES_REGION", "AWS_REGION", "AWS_DEFAULT_REGION"]).map_or(DEFAULT_REGION.into(), |(_, v)| v);
if !region.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
anyhow::bail!("invalid SES region '{region}'");
}
let port: u16 = match var(&lookup, &["SES_SMTP_PORT"]) {
Some((_, p)) => p.parse().map_err(|e| anyhow::anyhow!("invalid SES_SMTP_PORT '{p}': {e}"))?,
None => DEFAULT_PORT,
};
let smtp = var(&lookup, &["SES_SMTP_USERNAME", "SES_SMTP_USER"]).zip(var(&lookup, &["SES_SMTP_PASSWORD"]));
let (user, password, source) = if let Some(((name, user), (_, password))) = smtp {
(user, password, name)
} else {
let key = var(&lookup, KEY_NAMES);
let secret = var(&lookup, SECRET_NAMES);
match (key, secret) {
(Some((name, key)), Some((_, secret))) => {
let password = if is_smtp_password(&secret) { secret } else { smtp_password(&secret, &region) };
(key, password, name)
}
(None, None) => return Ok(None),
_ => anyhow::bail!("SES: both the access key id and the secret access key are needed"),
}
};
let url =
format!("smtp://{}:{}@email-smtp.{region}.amazonaws.com:{port}?tls=required", encode(&user), encode(&password));
Ok(Some((url, format!("Amazon SES {region}:{port}, credentials from {source}"))))
}
/// The SES SMTP password of an IAM secret access key (AWS docs, "Obtaining
/// Amazon SES SMTP credentials": signature version 4, `SendRawEmail`).
pub fn smtp_password(secret: &str, region: &str) -> String {
fn sign(key: &[u8], msg: &str) -> Vec<u8> {
let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("HMAC takes any key length");
mac.update(msg.as_bytes());
mac.finalize().into_bytes().to_vec()
}
let mut signature = sign(format!("AWS4{secret}").as_bytes(), "11111111");
for part in [region, "ses", "aws4_request", "SendRawEmail"] {
signature = sign(&signature, part);
}
let mut bytes = vec![0x04];
bytes.extend(signature);
STANDARD.encode(bytes)
}
/// An SMTP password is a version byte (4) and a 32-byte signature, in base64;
/// an IAM secret key is 40 characters.
fn is_smtp_password(s: &str) -> bool {
s.len() == 44 && STANDARD.decode(s).is_ok_and(|b| b.len() == 33 && b[0] == 0x04)
}
/// Percent-encoding for the user and password part of a URL.
fn encode(s: &str) -> String {
s.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => (b as char).to_string(),
_ => format!("%{b:02X}"),
})
.collect()
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::*;
fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
let map: HashMap<String, String> = pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
move |k| map.get(k).cloned()
}
#[test]
fn derives_the_smtp_password() {
// The value of AWS's Python example (docs: "Obtaining Amazon SES SMTP credentials") for this made-up key.
let password = smtp_password("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "eu-central-1");
assert_eq!(password, "BF0/eIJm0ruTHsSjOkRuOGzGF+zeSyE3aiRzrzUQ8LwG");
assert!(is_smtp_password(&password));
assert!(!is_smtp_password("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"));
}
#[test]
fn url_from_variables() {
assert!(smtp_url(env(&[])).unwrap().is_none());
let (url, about) = smtp_url(env(&[
("aws_access_key_id", "AKIAEXAMPLE"),
("aws_secret_access_key", "BF0/eIJm0ruTHsSjOkRuOGzGF+zeSyE3aiRzrzUQ8LwG"),
]))
.unwrap()
.unwrap();
// already an SMTP password: kept, with + and / encoded
assert_eq!(
url,
"smtp://AKIAEXAMPLE:BF0%2FeIJm0ruTHsSjOkRuOGzGF%2BzeSyE3aiRzrzUQ8LwG@email-smtp.eu-central-1.amazonaws.com:2587?tls=required"
);
assert_eq!(about, "Amazon SES eu-central-1:2587, credentials from aws_access_key_id");
let (url, _) = smtp_url(env(&[
("SES_SMTP_USERNAME", "AKIA2"),
("SES_SMTP_PASSWORD", "a/b+c="),
("SES_REGION", "eu-west-1"),
]))
.unwrap()
.unwrap();
assert_eq!(url, "smtp://AKIA2:a%2Fb%2Bc%3D@email-smtp.eu-west-1.amazonaws.com:2587?tls=required");
assert!(smtp_url(env(&[("AWS_ACCESS_KEY_ID", "AKIA")])).is_err());
// other common names; a real secret key is turned into the SMTP password
let (url, about) =
smtp_url(env(&[("ses_auth_key", "AKIA3"), ("ses_secret", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")]))
.unwrap()
.unwrap();
assert!(
url.starts_with("smtp://AKIA3:BF0%2FeIJm0ruTHsSjOkRuOGzGF%2BzeSyE3aiRzrzUQ8LwG@email-smtp.eu-central-1.")
);
assert!(about.ends_with("from ses_auth_key"));
}
}
-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();