From de8406267a4c2b3a822ac8c032d2504e2edd285f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 10:36:46 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20mail:=20SMTP=20sender=20set?= =?UTF-8?q?tings,=20outbox=20worker,=20rules=20engine=20with=20transaction?= =?UTF-8?q?al=20events,=20reminders,=20rules=20and=20logs=20pages,=20messa?= =?UTF-8?q?ge=20to=20members?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 22 + Cargo.toml | 1 + .../iz-core/migrations/0004_mail_events.sql | 22 + crates/iz-core/src/clock.rs | 12 +- crates/iz-core/src/lib.rs | 3 + crates/iz-core/src/limits.rs | 13 + crates/iz-core/src/mail_text.rs | 312 +++++++++ crates/iz-core/src/rules.rs | 375 +++++++++++ crates/iz-core/src/sender.rs | 260 ++++++++ crates/iz-core/src/store/comments.rs | 14 + crates/iz-core/src/store/events.rs | 54 ++ crates/iz-core/src/store/migrate.rs | 1 + crates/iz-core/src/store/mod.rs | 8 +- crates/iz-core/src/store/outbox.rs | 514 +++++++++++++++ crates/iz-core/src/store/reminders.rs | 180 ++++++ crates/iz-core/src/store/rules.rs | 295 +++++++++ crates/iz-core/src/store/rules_engine.rs | 559 ++++++++++++++++ crates/iz-core/src/store/sender.rs | 196 ++++++ crates/iz-core/src/store/tasks.rs | 105 +-- crates/iz-web/Cargo.toml | 1 + crates/iz-web/src/auth.rs | 11 +- crates/iz-web/src/boot.rs | 1 + crates/iz-web/src/i18n/admin.rs | 399 ++++++++++++ crates/iz-web/src/i18n/mod.rs | 1 + crates/iz-web/src/mail/compose.rs | 210 ++++++ crates/iz-web/src/mail/mod.rs | 245 +++++++ crates/iz-web/src/main.rs | 1 + crates/iz-web/src/pages/admin.rs | 69 ++ crates/iz-web/src/pages/logs.rs | 169 +++++ crates/iz-web/src/pages/mod.rs | 4 + crates/iz-web/src/pages/rules.rs | 332 ++++++++++ crates/iz-web/src/pages/settings.rs | 281 ++++++++ crates/iz-web/src/views/admin.rs | 601 ++++++++++++++++++ crates/iz-web/src/views/mod.rs | 1 + 34 files changed, 5219 insertions(+), 53 deletions(-) create mode 100644 crates/iz-core/migrations/0004_mail_events.sql create mode 100644 crates/iz-core/src/mail_text.rs create mode 100644 crates/iz-core/src/rules.rs create mode 100644 crates/iz-core/src/sender.rs create mode 100644 crates/iz-core/src/store/events.rs create mode 100644 crates/iz-core/src/store/outbox.rs create mode 100644 crates/iz-core/src/store/reminders.rs create mode 100644 crates/iz-core/src/store/rules.rs create mode 100644 crates/iz-core/src/store/rules_engine.rs create mode 100644 crates/iz-core/src/store/sender.rs create mode 100644 crates/iz-web/src/i18n/admin.rs create mode 100644 crates/iz-web/src/mail/compose.rs create mode 100644 crates/iz-web/src/mail/mod.rs create mode 100644 crates/iz-web/src/pages/admin.rs create mode 100644 crates/iz-web/src/pages/logs.rs create mode 100644 crates/iz-web/src/pages/rules.rs create mode 100644 crates/iz-web/src/pages/settings.rs create mode 100644 crates/iz-web/src/views/admin.rs diff --git a/Cargo.lock b/Cargo.lock index a3ad5ce..1f1e9c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1905,6 +1905,7 @@ dependencies = [ "iz-core", "jiff", "jsonwebtoken", + "lettre", "rand 0.10.3", "reqwest", "serde", @@ -2076,15 +2077,26 @@ version = "0.11.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae" dependencies = [ + "async-trait", + "base64 0.23.1", "email-encoding", "email_address", "fastrand", + "futures-io", + "futures-util", "hostname", "httpdate", "idna", "mime", "nom 8.0.0", + "percent-encoding", "quoted_printable", + "rustls", + "socket2", + "tokio", + "tokio-rustls", + "url", + "webpki-roots", ] [[package]] @@ -3126,6 +3138,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", + "log", "once_cell", "rustls-pki-types", "rustls-webpki", @@ -4939,6 +4952,15 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "which" version = "4.4.2" diff --git a/Cargo.toml b/Cargo.toml index 64b900e..772cdf4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,7 @@ http-body-util = "0.1.5" chacha20poly1305 = "0.11.0" hex = "0.4.3" ipnet = "2.12.2" +lettre = { version = "0.11.23", default-features = false, features = ["builder", "hostname", "smtp-transport", "tokio1", "tokio1-rustls", "aws-lc-rs", "webpki-roots"] } jsonwebtoken = { version = "11.1.0", default-features = false, features = ["aws_lc_rs"] } jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] } rand = "0.10.3" diff --git a/crates/iz-core/migrations/0004_mail_events.sql b/crates/iz-core/migrations/0004_mail_events.sql new file mode 100644 index 0000000..7b3e16c --- /dev/null +++ b/crates/iz-core/migrations/0004_mail_events.sql @@ -0,0 +1,22 @@ +-- 0004: the event queue of the mail rules engine. A task or comment write inserts one row per event in +-- the same transaction as the change (store/events.rs), so a crash can neither lose nor duplicate an +-- event. The rules engine (store/rules_engine.rs) reads unprocessed rows in order and writes the +-- decisions and outbox rows of each one. The mail system never inserts here, so mail cannot trigger rules. + +CREATE TABLE mail_events ( + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL REFERENCES boards(id) ON DELETE CASCADE, + -- No foreign key: the ledger of an event outlives its task (a deleted task is still named in mail). + task_id TEXT, + kind TEXT NOT NULL CHECK (kind IN ( + 'status', 'unblocked', 'created', 'assigned', 'unassigned', 'commented', + 'deadline_set', 'deadline_cleared', 'retitled', 'linked', 'unlinked', 'deleted' + )), + column_id TEXT, + actor TEXT, + subject TEXT, + detail TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(detail)), + at TEXT NOT NULL, + processed_at TEXT +); +CREATE INDEX mail_events_pending ON mail_events(at, id) WHERE processed_at IS NULL; diff --git a/crates/iz-core/src/clock.rs b/crates/iz-core/src/clock.rs index 81f6f31..efad2f1 100644 --- a/crates/iz-core/src/clock.rs +++ b/crates/iz-core/src/clock.rs @@ -15,8 +15,7 @@ use crate::error::{Error, Result}; use crate::time::format_stamp; use crate::zones::{local_to_utc, utc_to_local}; -/// How long before a meeting its reminder is due, in minutes. A default; the `reminder_minutes` -/// setting replaces it once the setting exists. +/// How long before a meeting its reminder is due, in minutes, when the setting was never saved. pub const REMINDER_LEAD_MINUTES: i64 = 15; /// What the user typed for a deadline and meeting time. Every part is optional. @@ -68,10 +67,11 @@ pub fn timestamp_of(stamp: &str) -> Result { .map_err(|e| Error::Database(format!("stored meeting time is not a stamp: {e}"))) } -/// The moment a reminder for a meeting at `meeting` is due: `REMINDER_LEAD_MINUTES` before it. -pub fn reminder_due(meeting: Timestamp) -> Result { +/// The moment a reminder for a meeting at `meeting` is due: `lead_minutes` before it. The lead comes from +/// the `reminder_minutes` setting (0 turns reminders off, so the caller never asks for a due time then). +pub fn reminder_due(meeting: Timestamp, lead_minutes: i64) -> Result { let due = meeting - .checked_sub(SignedDuration::from_mins(REMINDER_LEAD_MINUTES)) + .checked_sub(SignedDuration::from_mins(lead_minutes)) .map_err(|e| Error::Invalid(format!("reminder time out of range: {e}")))?; stamp_of(due) } @@ -153,7 +153,7 @@ mod tests { fn reminder_is_lead_time_before_meeting() { let meeting: Timestamp = "2026-01-15T08:30:00Z".parse().unwrap(); assert_eq!( - reminder_due(meeting).unwrap(), + reminder_due(meeting, REMINDER_LEAD_MINUTES).unwrap(), "2026-01-15T08:15:00.000000000Z" ); } diff --git a/crates/iz-core/src/lib.rs b/crates/iz-core/src/lib.rs index 1767b79..412eb33 100644 --- a/crates/iz-core/src/lib.rs +++ b/crates/iz-core/src/lib.rs @@ -10,8 +10,11 @@ pub mod clock; pub mod config; pub mod error; pub mod limits; +pub mod mail_text; pub mod preview; +pub mod rules; pub mod secret; +pub mod sender; pub mod sheet; pub mod slides; pub mod sniff; diff --git a/crates/iz-core/src/limits.rs b/crates/iz-core/src/limits.rs index ca292d7..59957d4 100644 --- a/crates/iz-core/src/limits.rs +++ b/crates/iz-core/src/limits.rs @@ -63,3 +63,16 @@ pub const SLIDES_MAX: usize = 200; pub const SLIDE_TEXT_MAX: usize = 4000; /// Largest XML part of a deck that is read, in bytes. Reason: a single slide is far below this. pub const DECK_PART_MAX_BYTES: u64 = 4 * 1024 * 1024; + +/// Longest mail subject after rendering, in characters. Reason: header lines stay short and readable. +pub const MAIL_SUBJECT_MAX: usize = 200; +/// Longest sender display name, in characters. Reason: a mail client shows only the start of it. +pub const SENDER_NAME_MAX: usize = 100; +/// Longest host name of the mail server, in characters (DNS limit). +pub const SENDER_HOST_MAX: usize = 253; +/// Longest SMTP user name, in characters. Reason: long enough for an address, short enough to store. +pub const SMTP_USERNAME_MAX: usize = 254; +/// Longest SMTP password, in characters. Reason: a generous bound for a stored secret. +pub const SMTP_PASSWORD_MAX: usize = 512; +/// Highest reminder cap a member can be given, in mails per hour. Reason: above this the cap is no guard. +pub const REMINDER_CAP_MAX: u32 = 500; diff --git a/crates/iz-core/src/mail_text.rs b/crates/iz-core/src/mail_text.rs new file mode 100644 index 0000000..90ba747 --- /dev/null +++ b/crates/iz-core/src/mail_text.rs @@ -0,0 +1,312 @@ +//! The words of every mail iz sends: rule mails, reminders, admin notices and the test mail, in English +//! and Turkish. Pure text: no I/O, no HTML (the web layer escapes the plain text when it builds the HTML part). +//! +//! The strings are keyed by [`K`] and matched exhaustively on `(key, language)`, so a missing translation +//! does not compile. Values (names, titles, times) are cleaned with [`clean_text`] before they are placed, +//! so no value can add a line to a subject. The brand in every text is the single word `iz`. + +use jiff::Timestamp; + +use crate::rules::clean_text; +use crate::zones::{parse_zone, utc_to_local}; + +/// The language a mail is written in: the recipient's own choice, else the directory's, else English. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MailLang { + /// English. + En, + /// Turkish. + Tr, +} + +impl MailLang { + /// The language for a member: `locale_override` first, then the directory `locale`, else English. + pub fn of(locale_override: Option<&str>, locale: Option<&str>) -> MailLang { + match locale_override.or(locale) { + Some("tr") => MailLang::Tr, + _ => MailLang::En, + } + } +} + +/// A subject and a plain-text body, ready to be stored in the outbox. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Mail { + /// The subject, plain text, already cleaned and short. + pub subject: String, + /// The body, plain text with `\n` line breaks. + pub body: String, +} + +/// Every fixed string of a mail. Matched exhaustively in [`text`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum K { + /// Heading label of the key and title line. + Key, + /// Label of the column. + Column, + /// Label of the deadline day. + Deadline, + /// Label of the assignees. + Assignees, + /// Label of the meeting time. + When, + /// Label of the link back to the board. + Link, + /// Sentence: the task moved to a column. + SentStatus, + /// Sentence: the task was created. + SentCreated, + /// Sentence: someone was assigned. + SentAssigned, + /// Sentence: someone was removed from the assignees. + SentUnassigned, + /// Sentence: a comment was posted. + SentCommented, + /// Sentence: a deadline or meeting time was set. + SentDeadlineSet, + /// Sentence: a deadline or meeting time was cleared. + SentDeadlineCleared, + /// Sentence: the title changed. + SentRetitled, + /// Sentence: a dependency was added. + SentLinked, + /// Sentence: a dependency was removed. + SentUnlinked, + /// Sentence: the task was deleted. + SentDeleted, + /// Sentence: the task stopped being blocked. + SentUnblocked, + /// Subject prefix of a reminder, before the title. + ReminderSubject, + /// The reminder body's first line, before the meeting time. + ReminderLead, + /// Subject of the test mail. + TestSubject, + /// Body of the test mail. + TestBody, +} + +/// The text of `key` in `lang`. Exhaustive over both languages. +pub fn text(lang: MailLang, key: K) -> &'static str { + use MailLang::{En, Tr}; + match (key, lang) { + (K::Key, En) => "Task", + (K::Key, Tr) => "Kart", + (K::Column, En) => "Column", + (K::Column, Tr) => "Sütun", + (K::Deadline, En) => "Deadline", + (K::Deadline, Tr) => "Son tarih", + (K::Assignees, En) => "Assignees", + (K::Assignees, Tr) => "Atananlar", + (K::When, En) => "Meeting time", + (K::When, Tr) => "Toplantı saati", + (K::Link, En) => "Open the task", + (K::Link, Tr) => "Kartı aç", + (K::SentStatus, En) => "moved the task to the column", + (K::SentStatus, Tr) => "kartı sütuna taşıdı", + (K::SentCreated, En) => "created the task", + (K::SentCreated, Tr) => "kartı oluşturdu", + (K::SentAssigned, En) => "assigned", + (K::SentAssigned, Tr) => "kişisini atadı", + (K::SentUnassigned, En) => "removed the assignment of", + (K::SentUnassigned, Tr) => "kişisinin atamasını kaldırdı", + (K::SentCommented, En) => "commented on the task", + (K::SentCommented, Tr) => "karta yorum yaptı", + (K::SentDeadlineSet, En) => "set the deadline or meeting time", + (K::SentDeadlineSet, Tr) => "son tarihi veya toplantı saatini belirledi", + (K::SentDeadlineCleared, En) => "cleared the deadline or meeting time", + (K::SentDeadlineCleared, Tr) => "son tarihi veya toplantı saatini kaldırdı", + (K::SentRetitled, En) => "changed the title", + (K::SentRetitled, Tr) => "kartın başlığını değiştirdi", + (K::SentLinked, En) => "added a dependency", + (K::SentLinked, Tr) => "bir bağımlılık ekledi", + (K::SentUnlinked, En) => "removed a dependency", + (K::SentUnlinked, Tr) => "bir bağımlılığı kaldırdı", + (K::SentDeleted, En) => "deleted the task", + (K::SentDeleted, Tr) => "kartı sildi", + (K::SentUnblocked, En) => "The task is no longer blocked.", + (K::SentUnblocked, Tr) => "Kart artık engelli değil.", + (K::ReminderSubject, En) => "Reminder:", + (K::ReminderSubject, Tr) => "Hatırlatma:", + (K::ReminderLead, En) => "A meeting for this task is coming up.", + (K::ReminderLead, Tr) => "Bu kart için bir toplantı yaklaşıyor.", + (K::TestSubject, En) => "iz test mail", + (K::TestSubject, Tr) => "iz deneme e-postası", + (K::TestBody, En) => "This is a test mail from iz. No other action follows from it.", + (K::TestBody, Tr) => { + "Bu, iz uygulamasından bir deneme e-postasıdır. Başka bir işlem yapmaz." + } + } +} + +/// The meeting time as text in a member's zone: `2026-10-28 14:30 Europe/Istanbul`. Unknown zones are +/// shown in UTC with the zone name `UTC`, so the text is never empty for a stored instant. +pub fn when_text(stamp: &str, zoneinfo: &str) -> Option { + let at: Timestamp = stamp.parse().ok()?; + let zone = parse_zone(zoneinfo).ok(); + let name = zone + .as_ref() + .and_then(|z| z.iana_name().map(str::to_owned)) + .unwrap_or_else(|| "UTC".to_owned()); + let zone = zone.unwrap_or(jiff::tz::TimeZone::UTC); + let local = utc_to_local(&zone, at); + Some(format!("{} {}", local.strftime("%Y-%m-%d %H:%M"), name)) +} + +/// Everything a rule mail says about one task and one event. +pub struct RuleMail<'a> { + /// The recipient's language. + pub lang: MailLang, + /// The trigger word of the event. + pub kind: &'a str, + /// Who did it, by name. + pub actor: &'a str, + /// The person the event names, by name (assigned and unassigned events). + pub subject_name: &'a str, + /// The task key, for example `IZ-42`. + pub key: &'a str, + /// The task title. + pub title: &'a str, + /// The column name. + pub column: &'a str, + /// The deadline day, if any. + pub deadline: Option<&'a str>, + /// The assignee names, sorted as the store lists them. + pub assignees: &'a [String], + /// The meeting time in the recipient's zone, if any. + pub when: Option<&'a str>, + /// The link back to the task. + pub link: &'a str, + /// Whether the details block is included (the rule's `include_details`). + pub details: bool, + /// The subject, already rendered from the rule's template. + pub subject: &'a str, +} + +/// The body of a rule mail: the event sentence, then the details the rule opts into, then the link. +pub fn rule_body(m: &RuleMail<'_>) -> String { + let lang = m.lang; + let actor = clean_text(m.actor); + let subject_name = clean_text(m.subject_name); + let sentence = match m.kind { + "status" => format!( + "{actor} {} {}.", + text(lang, K::SentStatus), + clean_text(m.column) + ), + "created" => format!("{actor} {}.", text(lang, K::SentCreated)), + "assigned" => format!("{actor} {} {subject_name}.", text(lang, K::SentAssigned)), + "unassigned" => format!("{actor} {} {subject_name}.", text(lang, K::SentUnassigned)), + "commented" => format!("{actor} {}.", text(lang, K::SentCommented)), + "deadline_set" => format!("{actor} {}.", text(lang, K::SentDeadlineSet)), + "deadline_cleared" => format!("{actor} {}.", text(lang, K::SentDeadlineCleared)), + "retitled" => format!("{actor} {}.", text(lang, K::SentRetitled)), + "linked" => format!("{actor} {}.", text(lang, K::SentLinked)), + "unlinked" => format!("{actor} {}.", text(lang, K::SentUnlinked)), + "deleted" => format!("{actor} {}.", text(lang, K::SentDeleted)), + _ => text(lang, K::SentUnblocked).to_owned(), + }; + let mut lines = vec![ + format!( + "{}: {} — {}", + text(lang, K::Key), + clean_text(m.key), + clean_text(m.title) + ), + sentence, + ]; + if m.details { + lines.push(format!( + "{}: {}", + text(lang, K::Column), + clean_text(m.column) + )); + if let Some(day) = m.deadline { + lines.push(format!("{}: {}", text(lang, K::Deadline), clean_text(day))); + } + let names: Vec = m.assignees.iter().map(|n| clean_text(n)).collect(); + if !names.is_empty() { + lines.push(format!( + "{}: {}", + text(lang, K::Assignees), + names.join(", ") + )); + } + if let Some(when) = m.when { + lines.push(format!("{}: {}", text(lang, K::When), clean_text(when))); + } + } + lines.push(format!("{}: {}", text(lang, K::Link), clean_text(m.link))); + lines.join("\n") +} + +/// A reminder for a meeting: subject with the title and key, body with the meeting time in the +/// recipient's zone and the link. +pub fn reminder(lang: MailLang, key: &str, title: &str, when: &str, link: &str) -> Mail { + Mail { + subject: clean_text(&format!( + "{} {} ({})", + text(lang, K::ReminderSubject), + title, + key + )) + .chars() + .take(crate::limits::MAIL_SUBJECT_MAX) + .collect(), + body: [ + text(lang, K::ReminderLead).to_owned(), + format!( + "{}: {} — {}", + text(lang, K::Key), + clean_text(key), + clean_text(title) + ), + format!("{}: {}", text(lang, K::When), clean_text(when)), + format!("{}: {}", text(lang, K::Link), clean_text(link)), + ] + .join("\n"), + } +} + +/// The test mail sent to the admin who asks for one. +pub fn test_mail(lang: MailLang) -> Mail { + Mail { + subject: text(lang, K::TestSubject).to_owned(), + body: text(lang, K::TestBody).to_owned(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_key_has_text_in_both_languages() { + for key in [ + K::Key, + K::Column, + K::Deadline, + K::Assignees, + K::When, + K::Link, + K::TestSubject, + ] { + assert!(!text(MailLang::En, key).is_empty()); + assert!(!text(MailLang::Tr, key).is_empty()); + } + } + + #[test] + fn the_locale_override_wins_over_the_directory() { + assert_eq!(MailLang::of(Some("en"), Some("tr")), MailLang::En); + assert_eq!(MailLang::of(None, Some("tr")), MailLang::Tr); + assert_eq!(MailLang::of(None, None), MailLang::En); + } + + #[test] + fn meeting_time_is_shown_in_the_members_zone() { + let text = when_text("2026-10-28T12:00:00.000000000Z", "Europe/Istanbul").unwrap(); + assert_eq!(text, "2026-10-28 15:00 Europe/Istanbul"); + } +} diff --git a/crates/iz-core/src/rules.rs b/crates/iz-core/src/rules.rs new file mode 100644 index 0000000..32d94de --- /dev/null +++ b/crates/iz-core/src/rules.rs @@ -0,0 +1,375 @@ +//! Mail rules, pure part: the closed set of triggers and audiences, the verdict of one rule on one +//! event, and the rendering of a rule's subject. No I/O. The store (`store/rules_engine.rs`) loads the +//! facts (task, members, eligible recipients) and writes the decisions and outbox rows this module decides. +//! +//! Invariants kept here: the actor of an event is never a recipient of it; a recipient is always one of +//! the eligible members handed in (enabled, role admin or member), so a viewer, a role `none` member and a +//! disabled member can never be owed mail; a subject is plain text with no control characters, at most +//! `MAIL_SUBJECT_MAX` characters, whatever the template or the values were. + +use crate::limits::MAIL_SUBJECT_MAX; + +/// Every trigger a rule can name. The schema CHECK lists the same twelve words. +pub const TRIGGERS: [&str; 12] = [ + "status", + "unblocked", + "created", + "assigned", + "unassigned", + "commented", + "deadline_set", + "deadline_cleared", + "retitled", + "linked", + "unlinked", + "deleted", +]; + +/// Who a rule mails. The schema CHECK lists the same four words. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Audience { + /// The task's assignees. For `assigned` and `unassigned`, only the person named by the event. + Assignees, + /// Every eligible member of the board. + Board, + /// The member who created the task. + Creator, + /// The members who opted in to watch this task. + Watchers, +} + +impl Audience { + /// The stored spelling. + pub fn as_str(self) -> &'static str { + match self { + Audience::Assignees => "assignees", + Audience::Board => "board", + Audience::Creator => "creator", + Audience::Watchers => "watchers", + } + } + + /// Parses the stored spelling. Unknown text is `None`. + pub fn parse(text: &str) -> Option { + match text { + "assignees" => Some(Audience::Assignees), + "board" => Some(Audience::Board), + "creator" => Some(Audience::Creator), + "watchers" => Some(Audience::Watchers), + _ => None, + } + } +} + +/// Whether `text` is one of the triggers. +pub fn is_trigger(text: &str) -> bool { + TRIGGERS.contains(&text) +} + +/// The rule fields a verdict depends on. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RuleFacts { + /// Whether the rule is switched on. + pub enabled: bool, + /// Only for `status`: the column that must be entered. `None` means any column. + pub column_id: Option, + /// The project the task must wear. `None` means any project. + pub tag_id: Option, + /// Who is mailed. + pub audience: Audience, +} + +/// The event fields a verdict depends on. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EventFacts { + /// The trigger word of the event. + pub kind: String, + /// The member the event names (the person assigned or removed), if any. + pub subject: Option, + /// The column the task entered, for `status` events. + pub column_id: Option, + /// Who did it. Never mailed about their own action. + pub actor: Option, +} + +/// The task fields a verdict depends on, as they are now. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TaskFacts { + /// The project the task wears. + pub tag_id: String, + /// Whether the task is soft-deleted. + pub deleted: bool, + /// Who created it. + pub creator: String, + /// Current assignees, sorted. + pub assignees: Vec, + /// Members who watch the task, sorted. + pub watchers: Vec, +} + +/// Why a rule does not apply to an event whose task is in the wrong state or place. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mismatch { + /// A status rule names another column. + Column, + /// The rule is limited to another project. + Project, +} + +impl Mismatch { + /// The text stored in the decision ledger. + pub fn as_str(self) -> &'static str { + match self { + Mismatch::Column => "column", + Mismatch::Project => "project", + } + } +} + +/// The outcome of one rule on one event, before any row is written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + /// The rule is off. + Disabled, + /// The task is gone (deleted before the event was handled), so the mail would be about nothing. + TaskGone, + /// The event does not match the rule's column or project. + NotMatched(Mismatch), + /// The rule applies, but nobody eligible is in the audience (after removing the actor). + NoRecipients, + /// These members are owed the mail, sorted. + Owed(Vec), +} + +/// Decides one rule on one event. `task` is `None` when the task row does not exist. `eligible` is every +/// member who may receive mail (enabled, role admin or member), sorted. +pub fn evaluate( + rule: &RuleFacts, + event: &EventFacts, + task: Option<&TaskFacts>, + eligible: &[String], +) -> Verdict { + if !rule.enabled { + return Verdict::Disabled; + } + let Some(task) = task else { + return Verdict::TaskGone; + }; + // A deleted task still announces its own deletion; any other event about it is gone. + if task.deleted && event.kind != "deleted" { + return Verdict::TaskGone; + } + if let Some(column) = &rule.column_id + && event.column_id.as_deref() != Some(column.as_str()) + { + return Verdict::NotMatched(Mismatch::Column); + } + if let Some(tag) = &rule.tag_id + && *tag != task.tag_id + { + return Verdict::NotMatched(Mismatch::Project); + } + let owed = audience(rule.audience, event, task, eligible); + if owed.is_empty() { + Verdict::NoRecipients + } else { + Verdict::Owed(owed) + } +} + +/// The recipients of an audience: the candidates, restricted to the eligible members and without the actor. +/// Sorted and without duplicates. `eligible` may be in any order. +pub fn audience( + audience: Audience, + event: &EventFacts, + task: &TaskFacts, + eligible: &[String], +) -> Vec { + let candidates: Vec<&String> = match audience { + Audience::Assignees if matches!(event.kind.as_str(), "assigned" | "unassigned") => { + event.subject.iter().collect() + } + Audience::Assignees => task.assignees.iter().collect(), + Audience::Board => eligible.iter().collect(), + Audience::Creator => vec![&task.creator], + Audience::Watchers => task.watchers.iter().collect(), + }; + let mut out: Vec = candidates + .into_iter() + .filter(|sub| eligible.contains(sub)) + .filter(|sub| event.actor.as_deref() != Some(sub.as_str())) + .cloned() + .collect(); + out.sort(); + out.dedup(); + out +} + +/// Removes every control character (CR, LF, tab, NUL and the rest of the C0 and C1 sets) and the Unicode +/// direction and zero-width format marks that let text pass for something else. Values that go into a +/// mail header or a subject are cleaned with this first. +pub fn clean_text(text: &str) -> String { + text.chars().filter(|c| !is_unsafe_char(*c)).collect() +} + +/// Whether a character must never reach a mail header or a subject. +fn is_unsafe_char(c: char) -> bool { + c.is_control() + || matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{FEFF}') +} + +/// Renders a subject from its template: `{name}` is replaced by the value of `name` in `vars`. A name +/// that is not in `vars` stays as written, so a typo shows in the mail instead of vanishing. The values +/// are inserted as they are and are never scanned again. The result is cleaned with [`clean_text`] and +/// cut to [`MAIL_SUBJECT_MAX`] characters. +pub fn render_subject(template: &str, vars: &[(&str, &str)]) -> String { + let mut out = String::with_capacity(template.len()); + let mut rest = template; + while let Some(open) = rest.find('{') { + out.push_str(&rest[..open]); + let after = &rest[open + 1..]; + let Some(close) = after.find('}') else { + out.push_str(&rest[open..]); + rest = ""; + break; + }; + let name = &after[..close]; + match vars.iter().find(|(key, _)| *key == name) { + Some((_, value)) => out.push_str(value), + None => { + out.push('{'); + out.push_str(name); + out.push('}'); + } + } + rest = &after[close + 1..]; + } + out.push_str(rest); + clean_text(&out) + .trim() + .chars() + .take(MAIL_SUBJECT_MAX) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn facts(assignees: &[&str], watchers: &[&str]) -> TaskFacts { + TaskFacts { + tag_id: "t1".into(), + deleted: false, + creator: "ada".into(), + assignees: assignees.iter().map(|s| s.to_string()).collect(), + watchers: watchers.iter().map(|s| s.to_string()).collect(), + } + } + + fn event(kind: &str, subject: Option<&str>) -> EventFacts { + EventFacts { + kind: kind.into(), + subject: subject.map(str::to_owned), + column_id: None, + actor: Some("ada".into()), + } + } + + fn rule(audience: Audience) -> RuleFacts { + RuleFacts { + enabled: true, + column_id: None, + tag_id: None, + audience, + } + } + + #[test] + fn the_actor_is_never_owed_and_ineligible_members_never_are() { + let eligible = vec!["bo".to_owned(), "ada".to_owned()]; + // "cy" is assigned but not eligible (a viewer, a disabled or a role-none member). + let task = facts(&["ada", "bo", "cy"], &[]); + let verdict = evaluate( + &rule(Audience::Assignees), + &event("commented", None), + Some(&task), + &eligible, + ); + assert_eq!(verdict, Verdict::Owed(vec!["bo".to_owned()])); + } + + #[test] + fn assignment_events_name_only_the_person_just_assigned() { + let eligible = vec!["bo".to_owned(), "cy".to_owned()]; + let task = facts(&["bo", "cy"], &[]); + let verdict = evaluate( + &rule(Audience::Assignees), + &event("assigned", Some("cy")), + Some(&task), + &eligible, + ); + assert_eq!(verdict, Verdict::Owed(vec!["cy".to_owned()])); + } + + #[test] + fn disabled_gone_and_mismatched_rules_owe_nothing() { + let eligible = vec!["bo".to_owned()]; + let task = facts(&["bo"], &[]); + let mut off = rule(Audience::Board); + off.enabled = false; + assert_eq!( + evaluate(&off, &event("created", None), Some(&task), &eligible), + Verdict::Disabled + ); + assert_eq!( + evaluate( + &rule(Audience::Board), + &event("created", None), + None, + &eligible + ), + Verdict::TaskGone + ); + let mut deleted = facts(&["bo"], &[]); + deleted.deleted = true; + assert_eq!( + evaluate( + &rule(Audience::Board), + &event("commented", None), + Some(&deleted), + &eligible + ), + Verdict::TaskGone + ); + let mut status = rule(Audience::Board); + status.column_id = Some("done".into()); + let mut moved = event("status", None); + moved.column_id = Some("todo".into()); + assert_eq!( + evaluate(&status, &moved, Some(&task), &eligible), + Verdict::NotMatched(Mismatch::Column) + ); + } + + #[test] + fn subject_is_plain_text_without_line_breaks_and_capped() { + let title = "x\r\nBcc: evil@example.com"; + let subject = render_subject( + "New: {title}\r\nBcc: {key}", + &[("title", title), ("key", "IZ-7")], + ); + assert!(!subject.contains('\r') && !subject.contains('\n')); + assert!(subject.starts_with("New: xBcc: evil@example.com")); + let long = "a".repeat(500); + assert_eq!( + render_subject("{title}", &[("title", &long)]) + .chars() + .count(), + MAIL_SUBJECT_MAX + ); + assert_eq!( + render_subject("{nope} {key}", &[("key", "IZ-1")]), + "{nope} IZ-1" + ); + } +} diff --git a/crates/iz-core/src/sender.rs b/crates/iz-core/src/sender.rs new file mode 100644 index 0000000..b90e109 --- /dev/null +++ b/crates/iz-core/src/sender.rs @@ -0,0 +1,260 @@ +//! The outgoing mail sender, pure part: what an admin may enter for the SMTP server and the From line, +//! and how each field is checked. The password is not handled here; the web layer seals it. +//! +//! Invariants: no control characters or line breaks in any field that becomes a header or a log line; the +//! TLS mode is implicit or STARTTLS, and plaintext only when the host is the loopback name `localhost`, +//! `127.0.0.1` or `::1`. + +use crate::error::{Error, Result}; +use crate::limits::{SENDER_HOST_MAX, SENDER_NAME_MAX, SMTP_PASSWORD_MAX, SMTP_USERNAME_MAX}; + +/// The name shown in From when the admin leaves it empty. +pub const DEFAULT_FROM_NAME: &str = "iz"; +/// The SMTP port when the admin leaves it empty (submission with STARTTLS). +pub const DEFAULT_PORT: u16 = 587; +/// Reminders per member per hour when the setting was never saved. Reason: a guard against a burst. +pub const DEFAULT_REMINDER_CAP: u32 = 20; + +/// How the connection to the mail server is protected. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TlsMode { + /// TLS from the first byte (usually port 465). + Implicit, + /// Plain connection upgraded with STARTTLS (usually port 587). + StartTls, + /// No encryption. Allowed only for a loopback host. + Plain, +} + +impl TlsMode { + /// The stored spelling. + pub fn as_str(self) -> &'static str { + match self { + TlsMode::Implicit => "implicit", + TlsMode::StartTls => "starttls", + TlsMode::Plain => "plain", + } + } + + /// Parses the stored or submitted spelling. + pub fn parse(text: &str) -> Option { + match text { + "implicit" => Some(TlsMode::Implicit), + "starttls" => Some(TlsMode::StartTls), + "plain" => Some(TlsMode::Plain), + _ => None, + } + } +} + +/// A checked sender configuration (everything but the password). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Sender { + /// Host name of the mail server. + pub host: String, + /// TCP port of the mail server. + pub port: u16, + /// Connection protection. + pub tls: TlsMode, + /// SMTP user name. + pub username: String, + /// The address mail is sent from. + pub from_address: String, + /// The name shown with the address; never empty (defaults to `iz`). + pub from_name: String, +} + +/// Whether `host` names this machine. Only then may a connection be unencrypted. +pub fn is_loopback(host: &str) -> bool { + matches!(host, "localhost" | "127.0.0.1" | "::1") +} + +/// Checks the host name: ASCII letters, digits, dots, hyphens, at most `SENDER_HOST_MAX` characters. +fn valid_host(host: &str) -> bool { + let labels_ok = host.split('.').all(|label| { + !label.is_empty() + && label.len() <= 63 + && !label.starts_with('-') + && !label.ends_with('-') + && label + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-') + }); + labels_ok && host.len() <= SENDER_HOST_MAX +} + +/// Checks an e-mail address: one `@`, a local part and a domain of ASCII labels, no spaces, no control +/// characters, at most 254 characters. Strict on purpose: the address becomes a header. +pub fn valid_address(address: &str) -> bool { + if address.len() > 254 || address.bytes().any(|b| b <= b' ' || b == 0x7f) { + return false; + } + let mut parts = address.split('@'); + let (Some(local), Some(domain), None) = (parts.next(), parts.next(), parts.next()) else { + return false; + }; + let local_ok = !local.is_empty() + && local.len() <= 64 + && !local.starts_with('.') + && !local.ends_with('.') + && local + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-/=?^_`{|}~.".contains(&b)); + let domain_ok = domain.contains('.') + && domain.split('.').all(|label| { + !label.is_empty() + && label.len() <= 63 + && !label.starts_with('-') + && !label.ends_with('-') + && label + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-') + }); + local_ok && domain_ok +} + +/// A display name with no control characters (and no Unicode direction or zero-width marks), at most +/// `max` characters. Trimmed. Empty is allowed and returned as empty. +pub fn checked_name(text: &str, max: usize) -> Result { + let trimmed = text.trim(); + if trimmed.chars().any(|c| c.is_control() || is_format_mark(c)) { + return Err(Error::Invalid( + "the name contains a control character or a line break".into(), + )); + } + if trimmed.chars().count() > max { + return Err(Error::Invalid(format!( + "the name is longer than {max} characters" + ))); + } + Ok(trimmed.to_owned()) +} + +/// Unicode marks that change how text is read (direction and zero width). Refused in names. +fn is_format_mark(c: char) -> bool { + matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{FEFF}') +} + +/// The raw values of the sender form, as typed. +#[derive(Debug, Clone, Default)] +pub struct SenderInput { + /// Host name. + pub host: String, + /// Port, as typed. + pub port: String, + /// `implicit`, `starttls` or `plain`. + pub tls: String, + /// SMTP user name. + pub username: String, + /// From address. + pub from_address: String, + /// From name, may be empty. + pub from_name: String, +} + +/// Checks a sender form and returns the checked configuration. Every error is safe to show to the admin. +pub fn validate_sender(input: &SenderInput) -> Result { + let host = input.host.trim().to_ascii_lowercase(); + if host.is_empty() || !valid_host(&host) { + return Err(Error::Invalid( + "the mail server name is not a valid host name".into(), + )); + } + let port_text = input.port.trim(); + let port = if port_text.is_empty() { + DEFAULT_PORT + } else { + port_text + .parse::() + .ok() + .filter(|p| *p >= 1) + .ok_or_else(|| Error::Invalid("the port must be a number from 1 to 65535".into()))? + }; + let tls = TlsMode::parse(input.tls.trim()) + .ok_or_else(|| Error::Invalid("choose implicit TLS or STARTTLS".into()))?; + if tls == TlsMode::Plain && !is_loopback(&host) { + return Err(Error::Invalid( + "an unencrypted connection is allowed only to localhost".into(), + )); + } + let username = input.username.trim().to_owned(); + if username.is_empty() + || username.chars().count() > SMTP_USERNAME_MAX + || username.chars().any(char::is_control) + { + return Err(Error::Invalid( + "the user name is required and must be printable".into(), + )); + } + let from_address = input.from_address.trim().to_owned(); + if !valid_address(&from_address) { + return Err(Error::Invalid( + "the from address is not a valid e-mail address".into(), + )); + } + let from_name = checked_name(&input.from_name, SENDER_NAME_MAX)?; + let from_name = if from_name.is_empty() { + DEFAULT_FROM_NAME.to_owned() + } else { + from_name + }; + Ok(Sender { + host, + port, + tls, + username, + from_address, + from_name, + }) +} + +/// Checks a password: required, at most `SMTP_PASSWORD_MAX` characters, no control characters. +pub fn validate_password(password: &str) -> Result<()> { + if password.is_empty() + || password.chars().count() > SMTP_PASSWORD_MAX + || password.chars().any(char::is_control) + { + return Err(Error::Invalid( + "the password is required and must be printable".into(), + )); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn input() -> SenderInput { + SenderInput { + host: "smtp.example.com".into(), + port: "587".into(), + tls: "starttls".into(), + username: "iz".into(), + from_address: "iz@example.com".into(), + from_name: String::new(), + } + } + + #[test] + fn a_valid_sender_gets_the_default_name() { + let sender = validate_sender(&input()).unwrap(); + assert_eq!(sender.from_name, "iz"); + assert_eq!(sender.tls, TlsMode::StartTls); + } + + #[test] + fn plaintext_only_to_loopback_and_no_line_breaks_in_names() { + let mut plain = input(); + plain.tls = "plain".into(); + assert!(validate_sender(&plain).is_err()); + plain.host = "localhost".into(); + assert!(validate_sender(&plain).is_ok()); + let mut breaking = input(); + breaking.from_name = "x\r\nBcc: evil@example.com".into(); + assert!(validate_sender(&breaking).is_err()); + breaking.from_name = "Aile".into(); + breaking.from_address = "a b@example.com".into(); + assert!(validate_sender(&breaking).is_err()); + } +} diff --git a/crates/iz-core/src/store/comments.rs b/crates/iz-core/src/store/comments.rs index 071fd15..5d0b4b2 100644 --- a/crates/iz-core/src/store/comments.rs +++ b/crates/iz-core/src/store/comments.rs @@ -6,6 +6,7 @@ use turso::Connection; use super::activity::{self, NewActivity}; +use super::events::{EventDraft, emit}; use super::{col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; use crate::authz::{Action, Actor, authorize}; use crate::error::{Error, Result}; @@ -109,6 +110,19 @@ impl Store { ) .await .map_err(db_err)?; + emit( + &tx, + EventDraft { + board_id, + task_id: Some(task_id), + kind: "commented", + column_id: None, + actor: Some(author), + subject: None, + detail: serde_json::json!({ "comment": id }), + }, + ) + .await?; activity::record( &tx, NewActivity { diff --git a/crates/iz-core/src/store/events.rs b/crates/iz-core/src/store/events.rs new file mode 100644 index 0000000..1c0bf25 --- /dev/null +++ b/crates/iz-core/src/store/events.rs @@ -0,0 +1,54 @@ +//! The mail event queue, write side. A task or comment write calls [`emit`] inside its own transaction, +//! so the event row exists if and only if the change committed: a crash cannot lose an event or make +//! two of them. The rules engine (`rules_engine.rs`) reads the rows later and marks them processed. +//! +//! Only the write paths of this crate call `emit`. The mail system never does, which is what keeps a +//! rule from ever firing on a mail. + +use turso::transaction::Transaction; + +use super::{db_err, new_id}; +use crate::error::Result; +use crate::time::now_stamp; + +/// One event to queue. `kind` is one of the twelve triggers; the schema refuses any other word. +pub struct EventDraft<'a> { + /// The board the task belongs to. + pub board_id: &'a str, + /// The task the event is about. + pub task_id: Option<&'a str>, + /// The trigger word. + pub kind: &'static str, + /// The column the task entered, for `status` events. + pub column_id: Option<&'a str>, + /// Who did it. + pub actor: Option<&'a str>, + /// The member the event names, if any. + pub subject: Option<&'a str>, + /// Details for the ledger. Never secrets, never mail text. + pub detail: serde_json::Value, +} + +/// Writes one event row inside `tx`. The caller commits or rolls back with the change it describes. +pub async fn emit(tx: &Transaction<'_>, draft: EventDraft<'_>) -> Result<()> { + let detail = serde_json::to_string(&draft.detail) + .map_err(|e| crate::error::Error::Database(format!("event detail is not JSON: {e}")))?; + tx.execute( + "INSERT INTO mail_events (id, board_id, task_id, kind, column_id, actor, subject, detail, at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", + ( + new_id(), + draft.board_id.to_owned(), + draft.task_id.map(str::to_owned), + draft.kind, + draft.column_id.map(str::to_owned), + draft.actor.map(str::to_owned), + draft.subject.map(str::to_owned), + detail, + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) +} diff --git a/crates/iz-core/src/store/migrate.rs b/crates/iz-core/src/store/migrate.rs index 06603f6..908c6ed 100644 --- a/crates/iz-core/src/store/migrate.rs +++ b/crates/iz-core/src/store/migrate.rs @@ -15,6 +15,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ include_str!("../../migrations/0002_session_id_token.sql"), ), (3, include_str!("../../migrations/0003_blob_deletions.sql")), + (4, include_str!("../../migrations/0004_mail_events.sql")), ]; fn migration_err(e: turso::Error) -> Error { diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index 413aff7..31bd8d3 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -11,8 +11,14 @@ pub mod activity; pub mod attachments; pub mod board; pub mod comments; +pub mod events; pub mod members; pub mod migrate; +pub mod outbox; +pub mod reminders; +pub mod rules; +pub mod rules_engine; +pub mod sender; pub mod sessions; pub mod snapshot; pub mod tasks; @@ -380,7 +386,7 @@ mod tests { }) .await .unwrap(); - assert_eq!(versions, vec![1, 2, 3]); + assert_eq!(versions, vec![1, 2, 3, 4]); } #[tokio::test] diff --git a/crates/iz-core/src/store/outbox.rs b/crates/iz-core/src/store/outbox.rs new file mode 100644 index 0000000..1e1943a --- /dev/null +++ b/crates/iz-core/src/store/outbox.rs @@ -0,0 +1,514 @@ +//! The outbox: every mail iz sends is a row here first, written in the transaction that decided it. The +//! worker in `iz-web` claims due rows under a lease, sends them and records the result. Nothing else sends. +//! +//! Retries: a failed attempt waits `BACKOFF_MINUTES` (1, 5, 15, then 60) before the next one; the fifth +//! failure, or a permanent refusal by the server, abandons the row. A row that cannot be sent for lack of a +//! sender is held for `HOLD_MINUTES` and spends no attempt. A claim is a lease of `LEASE_MINUTES`: a worker +//! that dies lets the row go again after that. Rows of a member who is no longer eligible are abandoned at +//! claim time, so a member demoted after the mail was queued never receives it. + +use jiff::{SignedDuration, Timestamp}; +use turso::Connection; +use turso::transaction::Transaction; + +use super::{col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; +use crate::clock::stamp_of; +use crate::error::{Error, Result}; +use crate::limits::{MESSAGE_BODY_MAX, MESSAGE_SUBJECT_MAX}; +use crate::rules::clean_text; +use crate::store::Store; +use crate::time::now_stamp; + +/// Failed attempts before a row is abandoned. +pub const MAX_ATTEMPTS: i64 = 5; +/// The wait after the first, second, third and fourth failure, in minutes. The fifth failure abandons. +pub const BACKOFF_MINUTES: [i64; 4] = [1, 5, 15, 60]; +/// The wait before trying again when no sender is configured. It spends no attempt. +pub const HOLD_MINUTES: i64 = 1; +/// How long a claim holds a row before another worker may take it, in minutes. +pub const LEASE_MINUTES: i64 = 5; +/// The minimum time between two messages to members from the same instance, in minutes. +pub const MESSAGE_INTERVAL_MINUTES: i64 = 10; +/// Rows of the logs page per page when the page asks for a size the code does not know. +pub const PAGE_DEFAULT: usize = 50; +/// Largest page of the logs lists. Reason: bounds one response. +pub const PAGE_MAX: usize = 200; + +/// The wait after the `attempts`-th failed attempt, or `None` when the row is abandoned. +pub fn backoff_after(attempts: i64) -> Option { + if !(1..MAX_ATTEMPTS).contains(&attempts) { + return None; + } + let index = usize::try_from(attempts - 1).ok()?; + BACKOFF_MINUTES + .get(index) + .map(|m| SignedDuration::from_mins(*m)) +} + +/// One outbox row with its recipient, as the worker and the logs page read it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OutboxRow { + /// Row id (ULID). + pub id: String, + /// The rule that owes it, if a rule did. + pub rule_id: Option, + /// The task the mail is about, if any. + pub task_id: Option, + /// `rule`, `notice` or `reminder`. + pub kind: String, + /// The recipient's member id. + pub recipient: String, + /// The recipient's name, for the logs. + pub recipient_name: String, + /// The recipient's address. + pub recipient_email: String, + /// The subject, plain text. + pub subject: String, + /// The body, plain text. + pub body: String, + /// `pending`, `sent`, `failed` or `abandoned`. + pub state: String, + /// Attempts made so far. + pub attempts: i64, + /// The last error the server or the worker reported, if any. + pub last_error: Option, + /// When the row is due next. + pub next_attempt_at: String, + /// When it was sent, if it was. + pub sent_at: Option, + /// When it was queued. + pub created_at: String, +} + +/// A row to queue. `rule_id` is `None` for notices and reminders. +pub struct OutboxDraft<'a> { + /// The rule that owes the mail. + pub rule_id: Option<&'a str>, + /// The event (or reminder or message) the mail belongs to. + pub event_id: &'a str, + /// The task the mail is about. + pub task_id: Option<&'a str>, + /// The recipient's member id. + pub recipient: &'a str, + /// `rule`, `notice` or `reminder`. + pub kind: &'a str, + /// The subject, already cleaned. + pub subject: &'a str, + /// The body, already cleaned. + pub body: &'a str, + /// When the row is due first. + pub next_attempt_at: &'a str, +} + +/// Queues one row inside `tx`. Returns `false` when the unique key (rule, event, task, recipient) already +/// holds a row, which is how a repeated pass avoids a second mail. +pub async fn insert_outbox(tx: &Transaction<'_>, draft: &OutboxDraft<'_>) -> Result { + let changed = tx + .execute( + "INSERT INTO mail_outbox (id, rule_id, event_id, task_id, recipient, kind, subject, body, state, \ + attempts, next_attempt_at, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'pending', 0, ?9, ?10) \ + ON CONFLICT(rule_id, event_id, task_id, recipient) DO NOTHING", + ( + new_id(), + draft.rule_id.map(str::to_owned), + draft.event_id.to_owned(), + draft.task_id.map(str::to_owned), + draft.recipient.to_owned(), + draft.kind.to_owned(), + draft.subject.to_owned(), + draft.body.to_owned(), + draft.next_attempt_at.to_owned(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + Ok(changed > 0) +} + +/// The columns of an outbox row joined with its recipient. The recipient join is inner: a row whose +/// recipient is gone cannot be sent and is never selected. +const OUTBOX_COLS: &str = "o.id, o.rule_id, o.task_id, o.kind, o.recipient, m.name, m.email, o.subject, o.body, \ + o.state, o.attempts, o.last_error, o.next_attempt_at, o.sent_at, o.created_at"; + +fn map_outbox(row: &turso::Row) -> Result { + Ok(OutboxRow { + id: col_text(row, 0)?, + rule_id: col_opt_text(row, 1)?, + task_id: col_opt_text(row, 2)?, + kind: col_text(row, 3)?, + recipient: col_text(row, 4)?, + recipient_name: col_text(row, 5)?, + recipient_email: col_text(row, 6)?, + subject: col_text(row, 7)?, + body: col_text(row, 8)?, + state: col_text(row, 9)?, + attempts: col_int(row, 10)?, + last_error: col_opt_text(row, 11)?, + next_attempt_at: col_text(row, 12)?, + sent_at: col_opt_text(row, 13)?, + created_at: col_text(row, 14)?, + }) +} + +/// One page of the outbox, newest first, with the cursor of the next page. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OutboxPage { + /// The rows, newest first. + pub items: Vec, + /// Pass back as the cursor of the next (older) page. `None` when this is the last page. + pub next_cursor: Option, +} + +/// Splits a `~` cursor. A missing or malformed cursor is `None` (the first page). +pub fn parse_cursor(cursor: Option<&str>) -> Result> { + match cursor.filter(|c| !c.is_empty()) { + None => Ok(None), + Some(text) => text + .split_once('~') + .map(|(at, id)| Some((at.to_owned(), id.to_owned()))) + .ok_or_else(|| Error::Invalid("malformed cursor".into())), + } +} + +/// The page size, clamped to `1..=PAGE_MAX`. +pub fn clamp_page(limit: usize) -> usize { + limit.clamp(1, PAGE_MAX) +} + +/// Decides whether a claimed recipient may still receive mail: enabled, role admin or member. +fn eligible_role(role: &str) -> bool { + matches!(role, "admin" | "member") +} + +impl Store { + /// Claims up to `batch` due rows for sending under a lease of `LEASE_MINUTES`. Rows of recipients who + /// are no longer eligible are abandoned here and not returned. The rows are due when `next_attempt_at` + /// has passed and no live lease holds them. + pub async fn claim_due(&self, now: Timestamp, batch: usize) -> Result> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result> = async { + let stamp = stamp_of(now)?; + let lease_cutoff = stamp_of(now - SignedDuration::from_mins(LEASE_MINUTES))?; + let candidates = fetch_all( + &tx, + &format!( + "SELECT {OUTBOX_COLS}, m.role FROM mail_outbox o JOIN members m ON m.sub = o.recipient \ + WHERE o.state IN ('pending', 'failed') AND o.next_attempt_at <= ?1 \ + AND (o.claimed_at IS NULL OR o.claimed_at <= ?2) \ + ORDER BY o.next_attempt_at, o.id LIMIT ?3" + ), + (stamp.clone(), lease_cutoff, i64::try_from(batch).unwrap_or(i64::MAX)), + |row| Ok((map_outbox(row)?, col_text(row, 15)?)), + ) + .await?; + let mut claimed = Vec::new(); + for (row, role) in candidates { + let member_ok = eligible_role(&role) && member_enabled(&tx, &row.recipient).await?; + if member_ok { + tx.execute( + "UPDATE mail_outbox SET claimed_at = ?2 WHERE id = ?1", + (row.id.clone(), stamp.clone()), + ) + .await + .map_err(db_err)?; + claimed.push(row); + } else { + tx.execute( + "UPDATE mail_outbox SET state = 'abandoned', claimed_at = NULL, last_error = ?2 WHERE id = ?1", + (row.id.clone(), "the recipient is no longer eligible for mail".to_owned()), + ) + .await + .map_err(db_err)?; + } + } + Ok(claimed) + } + .await; + finish(tx, outcome).await + } + + /// Records a successful send: the row is `sent` and counts the attempt. + pub async fn mark_sent(&self, row_id: &str, now: Timestamp) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE mail_outbox SET state = 'sent', attempts = attempts + 1, sent_at = ?2, claimed_at = NULL, \ + last_error = NULL WHERE id = ?1", + (row_id.to_owned(), stamp_of(now)?), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Records a failed attempt. A permanent refusal, or the last allowed attempt, abandons the row; any + /// other failure schedules the next attempt after the backoff. + pub async fn mark_failed( + &self, + row_id: &str, + now: Timestamp, + error: &str, + permanent: bool, + ) -> Result { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let attempts = fetch_opt( + &tx, + "SELECT attempts FROM mail_outbox WHERE id = ?1", + (row_id.to_owned(),), + |row| col_int(row, 0), + ) + .await? + .ok_or(Error::NotFound)? + + 1; + let error = clean_text(error).chars().take(300).collect::(); + let next = match backoff_after(attempts) { + Some(wait) if !permanent => { + let at = now + wait; + tx.execute( + "UPDATE mail_outbox SET state = 'failed', attempts = ?2, last_error = ?3, \ + next_attempt_at = ?4, claimed_at = NULL WHERE id = ?1", + (row_id.to_owned(), attempts, error, stamp_of(at)?), + ) + .await + .map_err(db_err)?; + "failed" + } + _ => { + tx.execute( + "UPDATE mail_outbox SET state = 'abandoned', attempts = ?2, last_error = ?3, claimed_at = NULL \ + WHERE id = ?1", + (row_id.to_owned(), attempts, error), + ) + .await + .map_err(db_err)?; + "abandoned" + } + }; + Ok(next.to_owned()) + } + .await; + finish(tx, outcome).await + } + + /// Puts a row back for a later attempt without spending one (no sender configured, for example). + pub async fn defer(&self, row_id: &str, until: Timestamp, reason: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE mail_outbox SET next_attempt_at = ?2, last_error = ?3, claimed_at = NULL WHERE id = ?1", + (row_id.to_owned(), stamp_of(until)?, reason.to_owned()), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Requeues a failed or abandoned row now, with a fresh attempt count. `NotFound` for any other row. + pub async fn retry_row(&self, row_id: &str, now: Timestamp) -> Result<()> { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE mail_outbox SET state = 'pending', attempts = 0, next_attempt_at = ?2, claimed_at = NULL \ + WHERE id = ?1 AND state IN ('failed', 'abandoned')", + (row_id.to_owned(), stamp_of(now)?), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + + /// One page of the outbox, newest first. `cursor` is the `next_cursor` of the previous page. + pub async fn outbox_page(&self, cursor: Option<&str>, limit: usize) -> Result { + let before = parse_cursor(cursor)?; + let limit = clamp_page(limit); + let conn = self.read_conn().await; + let items = fetch_all( + &conn, + &format!( + "SELECT {OUTBOX_COLS} FROM mail_outbox o JOIN members m ON m.sub = o.recipient \ + WHERE (?1 IS NULL OR o.created_at < ?1 OR (o.created_at = ?1 AND o.id < ?2)) \ + ORDER BY o.created_at DESC, o.id DESC LIMIT ?3" + ), + ( + before.as_ref().map(|b| b.0.clone()), + before.as_ref().map(|b| b.1.clone()), + i64::try_from(limit).unwrap_or(i64::MAX), + ), + map_outbox, + ) + .await?; + let next_cursor = match items.last() { + Some(last) if items.len() == limit => Some(format!("{}~{}", last.created_at, last.id)), + _ => None, + }; + Ok(OutboxPage { items, next_cursor }) + } + + /// Queues a notice to every eligible member except the sender, then records the time of the message + /// for the rate limit. `Conflict` when the previous message is too recent. Returns the number queued. + pub async fn queue_message( + &self, + actor: &str, + subject: &str, + body: &str, + now: Timestamp, + ) -> Result { + let subject = clean_text(subject).trim().to_owned(); + if subject.is_empty() || subject.chars().count() > MESSAGE_SUBJECT_MAX { + return Err(Error::Invalid(format!( + "the subject must be 1 to {MESSAGE_SUBJECT_MAX} characters" + ))); + } + let body = clean_message_body(body)?; + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + if let Some(last) = fetch_opt( + &tx, + "SELECT value FROM settings WHERE key = 'message_last_at'", + (), + |row| col_text(row, 0), + ) + .await? + { + let last: Timestamp = last.parse().map_err(|_| Error::Database("stored message time".into()))?; + if now < last + SignedDuration::from_mins(MESSAGE_INTERVAL_MINUTES) { + return Err(Error::Conflict(format!( + "a message was sent recently; wait {MESSAGE_INTERVAL_MINUTES} minutes between messages" + ))); + } + } + let recipients = fetch_all( + &tx, + "SELECT sub FROM members WHERE disabled = 0 AND role IN ('admin', 'member') AND sub <> ?1 ORDER BY sub", + (actor.to_owned(),), + |row| col_text(row, 0), + ) + .await?; + let stamp = stamp_of(now)?; + let event_id = new_id(); + let mut queued = 0; + for sub in &recipients { + let draft = OutboxDraft { + rule_id: None, + event_id: &event_id, + task_id: None, + recipient: sub, + kind: "notice", + subject: &subject, + body: &body, + next_attempt_at: &stamp, + }; + if insert_outbox(&tx, &draft).await? { + queued += 1; + } + } + tx.execute( + "INSERT INTO settings (key, value, updated_at) VALUES ('message_last_at', ?1, ?1) \ + ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", + (stamp,), + ) + .await + .map_err(db_err)?; + Ok(queued) + } + .await; + finish(tx, outcome).await + } + + /// One page of rule decisions, newest first: the rule's name, the task key, the outcome and its reason. + pub async fn decisions_page(&self, cursor: Option<&str>, limit: usize) -> Result { + let before = parse_cursor(cursor)?; + let limit = clamp_page(limit); + let conn = self.read_conn().await; + let items = fetch_all( + &conn, + "SELECT d.id, r.name, t.key, d.outcome, d.detail, d.created_at FROM mail_decisions d \ + LEFT JOIN mail_rules r ON r.id = d.rule_id LEFT JOIN tasks t ON t.id = d.task_id \ + WHERE (?1 IS NULL OR d.created_at < ?1 OR (d.created_at = ?1 AND d.id < ?2)) \ + ORDER BY d.created_at DESC, d.id DESC LIMIT ?3", + ( + before.as_ref().map(|b| b.0.clone()), + before.as_ref().map(|b| b.1.clone()), + i64::try_from(limit).unwrap_or(i64::MAX), + ), + |row| { + Ok(Decision { + id: col_text(row, 0)?, + rule_name: col_opt_text(row, 1)?.unwrap_or_default(), + task_key: col_opt_text(row, 2)?, + outcome: col_text(row, 3)?, + detail: col_text(row, 4)?, + at: col_text(row, 5)?, + }) + }, + ) + .await?; + let next_cursor = match items.last() { + Some(last) if items.len() == limit => Some(format!("{}~{}", last.at, last.id)), + _ => None, + }; + Ok(DecisionPage { items, next_cursor }) + } +} + +/// One rule decision as the logs page shows it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Decision { + /// Row id. + pub id: String, + /// The rule's name (empty when the rule was deleted). + pub rule_name: String, + /// The task key, if the task still exists. + pub task_key: Option, + /// `owed`, `already_owed`, `no_recipients`, `not_matched`, `disabled` or `task_gone`. + pub outcome: String, + /// The reason, for example the mismatch. + pub detail: String, + /// When it was decided. + pub at: String, +} + +/// One page of decisions, newest first. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DecisionPage { + /// The decisions, newest first. + pub items: Vec, + /// Cursor of the next page. + pub next_cursor: Option, +} + +/// Checks a message body: CRLF becomes LF, other control characters go (tab and newline stay), at least one +/// visible character, at most `MESSAGE_BODY_MAX` characters. +pub fn clean_message_body(body: &str) -> Result { + let normalized = body.replace("\r\n", "\n").replace('\r', "\n"); + let cleaned: String = normalized + .chars() + .filter(|c| *c == '\n' || *c == '\t' || !c.is_control()) + .collect(); + let cleaned = cleaned.trim().to_owned(); + if cleaned.is_empty() || cleaned.chars().count() > MESSAGE_BODY_MAX { + return Err(Error::Invalid(format!( + "the message must be 1 to {MESSAGE_BODY_MAX} characters" + ))); + } + Ok(cleaned) +} + +/// Whether the member's account is enabled. Read inside the claim transaction. +async fn member_enabled(conn: &Connection, sub: &str) -> Result { + Ok(fetch_opt( + conn, + "SELECT disabled FROM members WHERE sub = ?1", + (sub.to_owned(),), + |row| col_int(row, 0), + ) + .await? + .is_some_and(|disabled| disabled == 0)) +} diff --git a/crates/iz-core/src/store/reminders.rs b/crates/iz-core/src/store/reminders.rs new file mode 100644 index 0000000..f24f4f5 --- /dev/null +++ b/crates/iz-core/src/store/reminders.rs @@ -0,0 +1,180 @@ +//! Meeting reminders. One reminder per (task, member, meeting value): it is due `reminder_minutes` before the +//! meeting, and a reminder is sent at most once for each due value. +//! +//! `sync_reminders` runs inside every write that can change a reminder (the meeting time, the assignees, the +//! done state, the deletion). It drops the unsent rows and the rows of an old due value, then makes one row +//! per eligible assignee for the current one. So a changed meeting time re-arms the reminder, and a change +//! that does not move the due value (moving a card to done and back, say) keeps the sent mark. A task that +//! is done, deleted, has no meeting or has a past meeting gets no new rows. +//! +//! `run_reminders` sends the due rows as outbox rows, with a per-recipient cap per hour (the spam guard). +//! A reminder over the cap is marked sent without a mail and logged, so it is not retried forever. + +use jiff::Timestamp; +use turso::transaction::Transaction; + +use super::outbox::{OutboxDraft, insert_outbox}; +use super::{col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; +use crate::clock::{reminder_due, stamp_of, timestamp_of}; +use crate::error::Result; +use crate::mail_text::{MailLang, reminder, when_text}; +use crate::store::Store; +use crate::store::rules_engine::task_link; + +/// The lead time of reminders in minutes, from the setting (0 is off). +pub async fn lead_minutes(conn: &turso::Connection) -> Result { + let value = fetch_opt( + conn, + "SELECT value FROM settings WHERE key = 'reminder_minutes'", + (), + |row| col_text(row, 0), + ) + .await?; + Ok(value + .and_then(|v| v.parse::().ok()) + .unwrap_or(crate::clock::REMINDER_LEAD_MINUTES) + .clamp(0, 1440)) +} + +/// Rebuilds the reminders of one task inside `tx`. See the module comment for the rule. +pub(super) async fn sync_reminders(tx: &Transaction<'_>, task_id: &str) -> Result<()> { + tx.execute( + "DELETE FROM reminders WHERE task_id = ?1 AND sent_at IS NULL", + (task_id.to_owned(),), + ) + .await + .map_err(db_err)?; + let lead = lead_minutes(tx).await?; + let state = fetch_opt( + tx, + "SELECT meeting_at, done_at, deleted_at FROM tasks WHERE id = ?1", + (task_id.to_owned(),), + |row| { + Ok(( + col_opt_text(row, 0)?, + col_opt_text(row, 1)?, + col_opt_text(row, 2)?, + )) + }, + ) + .await?; + let due = match state { + Some((Some(meeting), None, None)) if lead > 0 => { + let at = timestamp_of(&meeting)?; + if at <= Timestamp::now() { + None + } else { + Some(reminder_due(at, lead)?) + } + } + _ => None, + }; + let Some(due) = due else { + // No active meeting: unsent rows are gone; sent rows stay, so a return to the same value is not re-sent. + return Ok(()); + }; + tx.execute( + "DELETE FROM reminders WHERE task_id = ?1 AND due_at <> ?2", + (task_id.to_owned(), due.clone()), + ) + .await + .map_err(db_err)?; + tx.execute( + "INSERT INTO reminders (task_id, sub, due_at, sent_at) \ + SELECT a.task_id, a.sub, ?2, NULL FROM task_assignees a \ + WHERE a.task_id = ?1 AND EXISTS ( \ + SELECT 1 FROM members m WHERE m.sub = a.sub AND m.disabled = 0 AND m.role IN ('admin', 'member')) \ + ON CONFLICT(task_id, sub) DO NOTHING", + (task_id.to_owned(), due), + ) + .await + .map_err(db_err)?; + Ok(()) +} + +impl Store { + /// Sends the reminders that are due at `now`, at most `batch` of them, as outbox rows. `cap` is the most + /// reminder mails one member may be queued in the hour before `now`. Returns the number queued. + pub async fn run_reminders( + &self, + now: Timestamp, + base_url: &str, + cap: u32, + batch: usize, + ) -> Result { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let stamp = stamp_of(now)?; + let window_start = stamp_of(now - jiff::SignedDuration::from_hours(1))?; + let due = fetch_all( + &tx, + "SELECT r.task_id, r.sub, t.key, t.title, t.meeting_at, m.zoneinfo, m.locale, m.locale_override \ + FROM reminders r JOIN tasks t ON t.id = r.task_id JOIN members m ON m.sub = r.sub \ + WHERE r.sent_at IS NULL AND r.due_at <= ?1 AND t.deleted_at IS NULL \ + AND m.disabled = 0 AND m.role IN ('admin', 'member') \ + ORDER BY r.due_at, r.task_id, r.sub LIMIT ?2", + (stamp.clone(), i64::try_from(batch).unwrap_or(i64::MAX)), + |row| { + Ok(( + col_text(row, 0)?, + col_text(row, 1)?, + col_text(row, 2)?, + col_text(row, 3)?, + col_opt_text(row, 4)?, + col_text(row, 5)?, + col_opt_text(row, 6)?, + col_opt_text(row, 7)?, + )) + }, + ) + .await?; + let mut queued = 0; + for (task_id, sub, key, title, meeting, zone, locale, locale_override) in due { + let sent_before = fetch_opt( + &tx, + "SELECT COUNT(*) FROM mail_outbox WHERE recipient = ?1 AND kind = 'reminder' AND created_at >= ?2", + (sub.clone(), window_start.clone()), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + let over_cap = sent_before >= i64::from(cap); + if !over_cap { + let lang = MailLang::of(locale_override.as_deref(), locale.as_deref()); + let when = meeting + .as_deref() + .and_then(|at| when_text(at, &zone)) + .unwrap_or_default(); + let link = task_link(base_url, &key); + let mail = reminder(lang, &key, &title, &when, &link); + let event_id = new_id(); + let draft = OutboxDraft { + rule_id: None, + event_id: &event_id, + task_id: Some(&task_id), + recipient: &sub, + kind: "reminder", + subject: &mail.subject, + body: &mail.body, + next_attempt_at: &stamp, + }; + if insert_outbox(&tx, &draft).await? { + queued += 1; + } + } else { + tracing::warn!(recipient = %sub, cap, "reminder suppressed by the hourly cap"); + } + tx.execute( + "UPDATE reminders SET sent_at = ?3 WHERE task_id = ?1 AND sub = ?2", + (task_id, sub, stamp.clone()), + ) + .await + .map_err(db_err)?; + } + Ok(queued) + } + .await; + finish(tx, outcome).await + } +} diff --git a/crates/iz-core/src/store/rules.rs b/crates/iz-core/src/store/rules.rs new file mode 100644 index 0000000..6685626 --- /dev/null +++ b/crates/iz-core/src/store/rules.rs @@ -0,0 +1,295 @@ +//! Mail rules as stored: the list, the create/edit/delete writes and the enable switch. The rules +//! themselves are evaluated in `rules_engine.rs`. Every write is checked here: the trigger and audience +//! words, the column only for `status`, and the column and project belonging to the board. + +use turso::Connection; + +use super::{col_bool, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; +use crate::error::{Error, Result}; +use crate::limits::RULE_SUBJECT_MAX; +use crate::rules::{Audience, is_trigger}; +use crate::store::Store; +use crate::time::now_stamp; + +/// The longest rule name, in characters. +pub const RULE_NAME_MAX: usize = 120; + +/// One rule as stored. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MailRule { + /// Rule id (ULID). + pub id: String, + /// The board it belongs to. + pub board_id: String, + /// The admin's name for it. + pub name: String, + /// The trigger word. + pub trigger: String, + /// Only for `status`: the column that must be entered; `None` is any column. + pub column_id: Option, + /// The project it is limited to; `None` is any project. + pub tag_id: Option, + /// Who is mailed. + pub audience: Audience, + /// Whether the mail carries the details block. + pub include_details: bool, + /// Whether the rule is on. + pub enabled: bool, + /// The subject template, with `{key}`, `{title}`, `{column}`, `{actor}`, `{tag}`, `{deadline}`. + pub subject_template: String, + /// UTC stamp of creation. + pub created_at: String, +} + +/// The fields of a rule as the admin enters them. The store checks them all. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RuleInput { + /// Name, 1 to 120 characters. + pub name: String, + /// The trigger word. + pub trigger: String, + /// Column, only with the `status` trigger. + pub column_id: Option, + /// Project, or `None` for any. + pub tag_id: Option, + /// Audience word. + pub audience: String, + /// Whether to include the details block. + pub include_details: bool, + /// Whether the rule is on. + pub enabled: bool, + /// Subject template, 1 to 120 characters. + pub subject_template: String, +} + +const RULE_COLS: &str = "id, board_id, name, trigger, column_id, tag_id, audience, include_details, enabled, \ + subject_template, created_at"; + +fn map_rule(row: &turso::Row) -> Result { + let audience_text = col_text(row, 6)?; + let audience = Audience::parse(&audience_text) + .ok_or_else(|| Error::Database(format!("unknown stored audience: {audience_text}")))?; + Ok(MailRule { + id: col_text(row, 0)?, + board_id: col_text(row, 1)?, + name: col_text(row, 2)?, + trigger: col_text(row, 3)?, + column_id: col_opt_text(row, 4)?, + tag_id: col_opt_text(row, 5)?, + audience, + include_details: col_bool(row, 7)?, + enabled: col_bool(row, 8)?, + subject_template: col_text(row, 9)?, + created_at: col_text(row, 10)?, + }) +} + +/// Checks the input and returns the cleaned copy. Every refusal is a message for the admin. +async fn checked(conn: &Connection, board_id: &str, input: &RuleInput) -> Result { + let name = input.name.trim().to_owned(); + if name.is_empty() || name.chars().count() > RULE_NAME_MAX { + return Err(Error::Invalid(format!( + "the name must be 1 to {RULE_NAME_MAX} characters" + ))); + } + let trigger = input.trigger.trim().to_owned(); + if !is_trigger(&trigger) { + return Err(Error::Invalid("that trigger does not exist".into())); + } + let column_id = match input + .column_id + .as_deref() + .map(str::trim) + .filter(|c| !c.is_empty()) + { + None => None, + Some(column) if trigger == "status" => { + let live = fetch_opt( + conn, + "SELECT id FROM columns WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", + (column.to_owned(), board_id.to_owned()), + |row| col_text(row, 0), + ) + .await?; + if live.is_none() { + return Err(Error::Invalid("that column does not exist".into())); + } + Some(column.to_owned()) + } + Some(_) => { + return Err(Error::Invalid( + "only a status rule can name a column".into(), + )); + } + }; + let tag_id = match input + .tag_id + .as_deref() + .map(str::trim) + .filter(|t| !t.is_empty()) + { + None => None, + Some(tag) => { + let known = fetch_opt( + conn, + "SELECT id FROM tags WHERE id = ?1 AND board_id = ?2", + (tag.to_owned(), board_id.to_owned()), + |row| col_text(row, 0), + ) + .await?; + if known.is_none() { + return Err(Error::Invalid("that project does not exist".into())); + } + Some(tag.to_owned()) + } + }; + let audience = input.audience.trim().to_owned(); + if Audience::parse(&audience).is_none() { + return Err(Error::Invalid("that audience does not exist".into())); + } + let subject_template = input.subject_template.trim().to_owned(); + if subject_template.is_empty() || subject_template.chars().count() > RULE_SUBJECT_MAX { + return Err(Error::Invalid(format!( + "the subject must be 1 to {RULE_SUBJECT_MAX} characters" + ))); + } + Ok(RuleInput { + name, + trigger, + column_id, + tag_id, + audience, + include_details: input.include_details, + enabled: input.enabled, + subject_template, + }) +} + +impl Store { + /// Every rule of the board, oldest first. + pub async fn list_rules(&self, board_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {RULE_COLS} FROM mail_rules WHERE board_id = ?1 ORDER BY created_at, id" + ), + (board_id.to_owned(),), + map_rule, + ) + .await + } + + /// One rule of the board, or `NotFound`. + pub async fn rule(&self, board_id: &str, rule_id: &str) -> Result { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {RULE_COLS} FROM mail_rules WHERE id = ?1 AND board_id = ?2"), + (rule_id.to_owned(), board_id.to_owned()), + map_rule, + ) + .await? + .ok_or(Error::NotFound) + } + + /// Creates a rule after checking it. Returns the stored rule. + pub async fn create_rule(&self, board_id: &str, input: &RuleInput) -> Result { + let conn = self.inner.conn.lock().await; + let input = checked(&conn, board_id, input).await?; + let id = new_id(); + conn.execute( + "INSERT INTO mail_rules (id, board_id, name, trigger, column_id, tag_id, audience, include_details, \ + enabled, subject_template, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", + ( + id.clone(), + board_id.to_owned(), + input.name, + input.trigger, + input.column_id, + input.tag_id, + input.audience, + i64::from(input.include_details), + i64::from(input.enabled), + input.subject_template, + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + drop(conn); + self.rule(board_id, &id).await + } + + /// Replaces the fields of a rule after checking them. The rule keeps its id and creation time. + pub async fn update_rule( + &self, + board_id: &str, + rule_id: &str, + input: &RuleInput, + ) -> Result { + let conn = self.inner.conn.lock().await; + let input = checked(&conn, board_id, input).await?; + let changed = conn + .execute( + "UPDATE mail_rules SET name = ?3, trigger = ?4, column_id = ?5, tag_id = ?6, audience = ?7, \ + include_details = ?8, enabled = ?9, subject_template = ?10 WHERE id = ?1 AND board_id = ?2", + ( + rule_id.to_owned(), + board_id.to_owned(), + input.name, + input.trigger, + input.column_id, + input.tag_id, + input.audience, + i64::from(input.include_details), + i64::from(input.enabled), + input.subject_template, + ), + ) + .await + .map_err(db_err)?; + drop(conn); + if changed == 0 { + return Err(Error::NotFound); + } + self.rule(board_id, rule_id).await + } + + /// Switches a rule on or off. + pub async fn set_rule_enabled( + &self, + board_id: &str, + rule_id: &str, + enabled: bool, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE mail_rules SET enabled = ?3 WHERE id = ?1 AND board_id = ?2", + (rule_id.to_owned(), board_id.to_owned(), i64::from(enabled)), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + + /// Deletes a rule. Its outbox rows stay (the link to the rule is cleared), and its decisions go with it. + pub async fn delete_rule(&self, board_id: &str, rule_id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "DELETE FROM mail_rules WHERE id = ?1 AND board_id = ?2", + (rule_id.to_owned(), board_id.to_owned()), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + Ok(()) + } +} diff --git a/crates/iz-core/src/store/rules_engine.rs b/crates/iz-core/src/store/rules_engine.rs new file mode 100644 index 0000000..c9d7845 --- /dev/null +++ b/crates/iz-core/src/store/rules_engine.rs @@ -0,0 +1,559 @@ +//! The rules engine: turns queued events into decisions and outbox rows. +//! +//! One pass reads up to `batch` unprocessed events in order and handles all of them in one transaction: +//! for each event, every rule with its trigger gets one decision row (outcome and reason) and, when it +//! owes mail, one outbox row per recipient. The unique keys (decision per rule, event and task; outbox per +//! rule, event, task and recipient) make a repeated pass a no-op. The pass either commits everything or +//! nothing, so a crash between the two leaves the events unprocessed and they are handled again. +//! +//! Recipients come from the eligible members only (enabled, role admin or member), and the actor is +//! removed by `rules::audience`. Mail text is built per recipient in the recipient's language and zone. + +use jiff::Timestamp; +use turso::Connection; +use turso::transaction::Transaction; + +use super::outbox::{OutboxDraft, insert_outbox}; +use super::{col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; +use crate::clock::stamp_of; +use crate::error::Result; +use crate::mail_text::{MailLang, RuleMail, rule_body, when_text}; +use crate::rules::{Audience, EventFacts, RuleFacts, TaskFacts, Verdict, evaluate, render_subject}; +use crate::store::Store; +use crate::time::now_stamp; + +/// One unprocessed event as read back. +struct QueuedEvent { + id: String, + board_id: String, + task_id: Option, + kind: String, + column_id: Option, + actor: Option, + subject: Option, +} + +/// An eligible member: enabled, role admin or member. The language and zone are the ones mail uses. +#[derive(Clone)] +struct Eligible { + sub: String, + lang: MailLang, + zone: String, +} + +/// The task row fields a mail body needs. +struct TaskRow { + key: String, + title: String, + column_id: String, + tag_id: String, + deadline: Option, + meeting_at: Option, + deleted: bool, + creator: String, +} + +/// What one pass did. Returned for logs and tests. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct PassReport { + /// Events handled in this pass. + pub events: usize, + /// Outbox rows queued in this pass. + pub mails: usize, +} + +/// The eligible members of the instance, sorted by id. +async fn eligible_members(tx: &Transaction<'_>) -> Result> { + fetch_all( + tx, + "SELECT sub, locale, locale_override, zoneinfo FROM members \ + WHERE disabled = 0 AND role IN ('admin', 'member') ORDER BY sub", + (), + |row| { + let locale = col_opt_text(row, 1)?; + let locale_override = col_opt_text(row, 2)?; + Ok(Eligible { + sub: col_text(row, 0)?, + lang: MailLang::of(locale_override.as_deref(), locale.as_deref()), + zone: col_text(row, 3)?, + }) + }, + ) + .await +} + +/// The task row of `task_id` on `board_id`, deleted or not. +async fn task_row(conn: &Connection, board_id: &str, task_id: &str) -> Result> { + fetch_opt( + conn, + "SELECT key, title, column_id, tag_id, deadline, meeting_at, deleted_at, created_by FROM tasks \ + WHERE id = ?1 AND board_id = ?2", + (task_id.to_owned(), board_id.to_owned()), + |row| { + Ok(TaskRow { + key: col_text(row, 0)?, + title: col_text(row, 1)?, + column_id: col_text(row, 2)?, + tag_id: col_text(row, 3)?, + deadline: col_opt_text(row, 4)?, + meeting_at: col_opt_text(row, 5)?, + deleted: col_opt_text(row, 6)?.is_some(), + creator: col_text(row, 7)?, + }) + }, + ) + .await +} + +/// Sorted ids of the people assigned to `task_id`, and the names in the same order. +async fn assignees_of(conn: &Connection, task_id: &str) -> Result> { + fetch_all( + conn, + "SELECT a.sub, m.name FROM task_assignees a JOIN members m ON m.sub = a.sub \ + WHERE a.task_id = ?1 ORDER BY a.sub", + (task_id.to_owned(),), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await +} + +/// Sorted ids of the members who watch `task_id`. +async fn watchers_of(conn: &Connection, task_id: &str) -> Result> { + fetch_all( + conn, + "SELECT sub FROM task_watchers WHERE task_id = ?1 ORDER BY sub", + (task_id.to_owned(),), + |row| col_text(row, 0), + ) + .await +} + +/// A name by id, or empty when the member is unknown. +async fn name_of(conn: &Connection, sub: &str) -> Result { + Ok(fetch_opt( + conn, + "SELECT name FROM members WHERE sub = ?1", + (sub.to_owned(),), + |row| col_text(row, 0), + ) + .await? + .unwrap_or_default()) +} + +/// A column or project name by id, or empty when it is gone. +async fn label_of(conn: &Connection, table: &'static str, id: &str) -> Result { + let sql = match table { + "columns" => "SELECT name FROM columns WHERE id = ?1", + _ => "SELECT name FROM tags WHERE id = ?1", + }; + Ok( + fetch_opt(conn, sql, (id.to_owned(),), |row| col_text(row, 0)) + .await? + .unwrap_or_default(), + ) +} + +/// The link back to a task. The base has no trailing slash (see `config.base_url`). +pub fn task_link(base_url: &str, key: &str) -> String { + format!("{}/?task={key}", base_url.trim_end_matches('/')) +} + +/// Handles one event: every rule of its trigger gets a decision, and mail rows for the owed recipients. +async fn handle(tx: &Transaction<'_>, event: &QueuedEvent, base_url: &str) -> Result { + let rules = fetch_all( + tx, + "SELECT id, column_id, tag_id, audience, enabled, subject_template, include_details FROM mail_rules \ + WHERE board_id = ?1 AND trigger = ?2 ORDER BY created_at, id", + (event.board_id.clone(), event.kind.clone()), + |row| { + let audience_text = col_text(row, 3)?; + let audience = Audience::parse(&audience_text).unwrap_or(Audience::Assignees); + Ok(( + col_text(row, 0)?, + RuleFacts { + enabled: col_int(row, 4)? == 1, + column_id: col_opt_text(row, 1)?, + tag_id: col_opt_text(row, 2)?, + audience, + }, + col_text(row, 5)?, + col_int(row, 6)? == 1, + )) + }, + ) + .await?; + if rules.is_empty() { + return Ok(0); + } + let eligible = eligible_members(tx).await?; + let subs: Vec = eligible.iter().map(|m| m.sub.clone()).collect(); + let task = match &event.task_id { + Some(task_id) => task_row(tx, &event.board_id, task_id).await?, + None => None, + }; + let facts = match (&event.task_id, &task) { + (Some(task_id), Some(row)) => Some(TaskFacts { + tag_id: row.tag_id.clone(), + deleted: row.deleted, + creator: row.creator.clone(), + assignees: assignees_of(tx, task_id) + .await? + .into_iter() + .map(|(sub, _)| sub) + .collect(), + watchers: watchers_of(tx, task_id).await?, + }), + _ => None, + }; + let event_facts = EventFacts { + kind: event.kind.clone(), + subject: event.subject.clone(), + column_id: event.column_id.clone(), + actor: event.actor.clone(), + }; + let actor_name = match &event.actor { + Some(actor) => name_of(tx, actor).await?, + None => String::new(), + }; + let subject_name = match &event.subject { + Some(sub) => name_of(tx, sub).await?, + None => String::new(), + }; + let queued_at = now_stamp(); + let mut mails = 0; + for (rule_id, rule, template, details) in &rules { + let verdict = evaluate(rule, &event_facts, facts.as_ref(), &subs); + let (outcome, detail, recipients) = match &verdict { + Verdict::Disabled => ("disabled", String::new(), Vec::new()), + Verdict::TaskGone => ("task_gone", String::new(), Vec::new()), + Verdict::NotMatched(reason) => ("not_matched", reason.as_str().to_owned(), Vec::new()), + Verdict::NoRecipients => ("no_recipients", "empty".to_owned(), Vec::new()), + Verdict::Owed(recipients) => ("owed", String::new(), recipients.clone()), + }; + let mut queued = 0; + if let (Some(row), Some(task_id)) = (&task, &event.task_id) { + let column_id = event + .column_id + .clone() + .unwrap_or_else(|| row.column_id.clone()); + let column = label_of(tx, "columns", &column_id).await?; + let tag = label_of(tx, "tags", &row.tag_id).await?; + let assignees: Vec = assignees_of(tx, task_id) + .await? + .into_iter() + .map(|(_, n)| n) + .collect(); + let link = task_link(base_url, &row.key); + for sub in &recipients { + let Some(member) = eligible.iter().find(|m| &m.sub == sub) else { + continue; + }; + let when = row + .meeting_at + .as_deref() + .and_then(|at| when_text(at, &member.zone)); + let subject = render_subject( + template, + &[ + ("key", &row.key), + ("title", &row.title), + ("column", &column), + ("actor", &actor_name), + ("tag", &tag), + ("deadline", row.deadline.as_deref().unwrap_or("")), + ], + ); + let body = rule_body(&RuleMail { + lang: member.lang, + kind: &event.kind, + actor: &actor_name, + subject_name: &subject_name, + key: &row.key, + title: &row.title, + column: &column, + deadline: row.deadline.as_deref(), + assignees: &assignees, + when: when.as_deref(), + link: &link, + details: *details, + subject: &subject, + }); + let draft = OutboxDraft { + rule_id: Some(rule_id), + event_id: &event.id, + task_id: Some(task_id), + recipient: sub, + kind: "rule", + subject: &subject, + body: &body, + next_attempt_at: &queued_at, + }; + if insert_outbox(tx, &draft).await? { + queued += 1; + } + } + } + mails += queued; + let outcome = if outcome == "owed" && queued == 0 { + "already_owed" + } else { + outcome + }; + tx.execute( + "INSERT INTO mail_decisions (id, rule_id, event_id, task_id, outcome, detail, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) ON CONFLICT(rule_id, event_id, task_id) DO NOTHING", + ( + new_id(), + rule_id.clone(), + event.id.clone(), + event.task_id.clone(), + outcome, + detail, + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + } + Ok(mails) +} + +impl Store { + /// One pass of the rules engine over up to `batch` queued events, in one transaction. `now` stamps the + /// outbox rows; `base_url` is the link base of the mails. + pub async fn run_rules( + &self, + now: Timestamp, + base_url: &str, + batch: usize, + ) -> Result { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let events = fetch_all( + &tx, + "SELECT id, board_id, task_id, kind, column_id, actor, subject FROM mail_events \ + WHERE processed_at IS NULL ORDER BY at, id LIMIT ?1", + (i64::try_from(batch).unwrap_or(i64::MAX),), + |row| { + Ok(QueuedEvent { + id: col_text(row, 0)?, + board_id: col_text(row, 1)?, + task_id: col_opt_text(row, 2)?, + kind: col_text(row, 3)?, + column_id: col_opt_text(row, 4)?, + actor: col_opt_text(row, 5)?, + subject: col_opt_text(row, 6)?, + }) + }, + ) + .await?; + let mut report = PassReport::default(); + let stamp = stamp_of(now)?; + for event in &events { + report.mails += handle(&tx, event, base_url).await?; + tx.execute( + "UPDATE mail_events SET processed_at = ?2 WHERE id = ?1", + (event.id.clone(), stamp.clone()), + ) + .await + .map_err(db_err)?; + report.events += 1; + } + Ok(report) + } + .await; + finish(tx, outcome).await + } +} + +#[cfg(test)] +mod tests { + use jiff::{SignedDuration, Timestamp}; + + use super::*; + use crate::clock::stamp_of; + use crate::store::rules::RuleInput; + use crate::store::tasks::{NewTask, TaskEdit}; + use crate::store::test_support::seeded; + use crate::time::stamp_after; + use std::time::Duration; + + const BASE: &str = "http://127.0.0.1:7654"; + + fn rule(trigger: &str, audience: &str) -> RuleInput { + RuleInput { + name: "Test rule".into(), + trigger: trigger.into(), + column_id: None, + tag_id: None, + audience: audience.into(), + include_details: true, + enabled: true, + subject_template: "{key} {title}".into(), + } + } + + fn new_task(column: &str, tag: &str, assignees: &[&str], meeting: Option) -> NewTask { + NewTask { + title: "Dentist".into(), + description: String::new(), + column_id: column.into(), + tag_id: tag.into(), + deadline: None, + meeting_at: meeting, + assignees: assignees.iter().map(|s| s.to_string()).collect(), + parent_id: None, + link: None, + } + } + + /// The first column and the default project of the board. + async fn column_and_tag(store: &Store, board_id: &str) -> (String, String) { + let column = store.columns(board_id).await.unwrap()[0].id.clone(); + let tag = store.tags(board_id).await.unwrap()[0].id.clone(); + (column, tag) + } + + #[tokio::test] + async fn a_mail_event_cannot_trigger_a_rule() { + let (_dir, store, board_id) = seeded().await; + store + .create_rule(&board_id, &rule("commented", "board")) + .await + .unwrap(); + // A notice is mail, not a board event: queuing and sending it writes no event. + let queued = store + .queue_message("ada", "Hello", "Bye", Timestamp::now()) + .await + .unwrap(); + assert_eq!(queued, 1); + let now = Timestamp::now(); + for row in store.claim_due(now, 10).await.unwrap() { + store.mark_sent(&row.id, now).await.unwrap(); + } + let report = store.run_rules(now, BASE, 100).await.unwrap(); + assert_eq!( + report, + PassReport { + events: 0, + mails: 0 + } + ); + let rule_mail = store + .outbox_page(None, 100) + .await + .unwrap() + .items + .iter() + .filter(|row| row.kind == "rule") + .count(); + assert_eq!(rule_mail, 0); + } + + #[tokio::test] + async fn a_ghost_member_and_the_actor_receive_nothing() { + let (_dir, store, board_id) = seeded().await; + let (column, tag) = column_and_tag(&store, &board_id).await; + let ghost = crate::store::members::DirectoryMember { + sub: "ghost".into(), + email: "ghost@example.com".into(), + name: "Ghost".into(), + im_admin: false, + disabled: false, + locale: None, + zoneinfo: "UTC".into(), + picture_version: 0, + }; + store + .apply_directory_member(&ghost, crate::authz::Role::Member) + .await + .unwrap(); + store + .create_rule(&board_id, &rule("created", "board")) + .await + .unwrap(); + store + .create_task( + &board_id, + new_task(&column, &tag, &["bo", "ghost"], None), + "ada", + ) + .await + .unwrap(); + // The member leaves the family after being assigned: the queued mail must not reach them. + let mut gone = ghost.clone(); + gone.disabled = true; + store + .apply_directory_member(&gone, crate::authz::Role::Member) + .await + .unwrap(); + store.run_rules(Timestamp::now(), BASE, 100).await.unwrap(); + let rows = store.outbox_page(None, 100).await.unwrap().items; + let recipients: Vec<&str> = rows.iter().map(|r| r.recipient.as_str()).collect(); + assert_eq!( + recipients, + vec!["bo"], + "only the eligible, non-acting member is mailed" + ); + // Anybody claiming the queued mail after the change is refused as well. + let claimed = store.claim_due(Timestamp::now(), 10).await.unwrap(); + assert!(claimed.iter().all(|r| r.recipient != "ghost")); + } + + #[tokio::test] + async fn a_reminder_fires_once_per_meeting_and_re_arms_after_a_change() { + let (_dir, store, board_id) = seeded().await; + let (column, tag) = column_and_tag(&store, &board_id).await; + let now = Timestamp::now(); + let meeting = stamp_after(Duration::from_secs(2 * 3600)); + let task = store + .create_task( + &board_id, + new_task(&column, &tag, &["bo"], Some(meeting)), + "ada", + ) + .await + .unwrap(); + let reminders_for_bo = |store: &Store| { + let store = store.clone(); + async move { + store + .outbox_page(None, 200) + .await + .unwrap() + .items + .iter() + .filter(|r| r.kind == "reminder" && r.recipient == "bo") + .count() + } + }; + // Past the due time (meeting minus 15 minutes) once: one reminder. + let after_due = now + SignedDuration::from_mins(110); + store.run_reminders(after_due, BASE, 20, 100).await.unwrap(); + store.run_reminders(after_due, BASE, 20, 100).await.unwrap(); + assert_eq!(reminders_for_bo(&store).await, 1); + // Moving the meeting re-arms the reminder for the new due value. + let moved = stamp_of(now + SignedDuration::from_hours(4)).unwrap(); + let edit = TaskEdit { + title: task.title.clone(), + description: task.description.clone(), + tag_id: task.tag_id.clone(), + deadline: None, + meeting_at: Some(moved), + }; + store + .edit_task(&board_id, &task.id, edit, "ada") + .await + .unwrap(); + store + .run_reminders(now + SignedDuration::from_hours(5), BASE, 20, 100) + .await + .unwrap(); + store + .run_reminders(now + SignedDuration::from_hours(5), BASE, 20, 100) + .await + .unwrap(); + assert_eq!(reminders_for_bo(&store).await, 2); + } +} diff --git a/crates/iz-core/src/store/sender.rs b/crates/iz-core/src/store/sender.rs new file mode 100644 index 0000000..1527481 --- /dev/null +++ b/crates/iz-core/src/store/sender.rs @@ -0,0 +1,196 @@ +//! Stored mail settings: the sender (SMTP host, port, TLS mode, user name, From address and name, and the +//! sealed password) and the reminder settings (lead time and hourly cap). They live in the `settings` table +//! as plain text, except the password, which the web layer seals before it gets here. +//! +//! The password is never read back into a page. `load_sender` says only whether it is set. + +use turso::transaction::Transaction; + +use super::{col_text, db_err, fetch_opt, finish}; +use crate::clock::REMINDER_LEAD_MINUTES; +use crate::error::{Error, Result}; +use crate::sender::{DEFAULT_REMINDER_CAP, Sender}; +use crate::store::Store; +use crate::time::now_stamp; + +/// Settings key of each sender field. The password key holds the sealed value. +const KEYS: [&str; 6] = [ + "mail_host", + "mail_port", + "mail_tls", + "mail_username", + "mail_from_address", + "mail_from_name", +]; +/// Settings key of the sealed SMTP password. +pub const KEY_PASSWORD: &str = "mail_password"; +/// Settings key of the reminder lead time in minutes. +pub const KEY_REMINDER_MINUTES: &str = "reminder_minutes"; +/// Settings key of the reminder cap per member per hour. +pub const KEY_REMINDER_CAP: &str = "reminder_hourly_cap"; + +/// What the store knows about the sender. The password is only represented by its sealed text. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SenderState { + /// The checked configuration, or `None` when a field is missing or was never saved. + pub sender: Option, + /// Whether a password is stored. + pub password_set: bool, + /// The sealed password, for the web layer to open when it connects. + pub sealed_password: Option, +} + +/// The settings of reminders: lead minutes (0 is off) and the cap per member per hour. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReminderSettings { + /// Minutes before a meeting that the reminder is due. + pub lead_minutes: u32, + /// Reminder mails one member may receive in an hour. + pub hourly_cap: u32, +} + +impl Default for ReminderSettings { + fn default() -> Self { + ReminderSettings { + lead_minutes: u32::try_from(REMINDER_LEAD_MINUTES).unwrap_or(15), + hourly_cap: DEFAULT_REMINDER_CAP, + } + } +} + +/// Writes settings in `tx`, one upsert each, with the same stamp. +async fn put_all(tx: &Transaction<'_>, pairs: &[(&str, String)]) -> Result<()> { + let stamp = now_stamp(); + for (key, value) in pairs { + tx.execute( + "INSERT INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3) \ + ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", + (key.to_string(), value.clone(), stamp.clone()), + ) + .await + .map_err(db_err)?; + } + Ok(()) +} + +impl Store { + /// The sender as stored. A configuration with a missing field reads as `sender: None`. + pub async fn load_sender(&self) -> Result { + let conn = self.read_conn().await; + let mut values = Vec::with_capacity(KEYS.len()); + for key in KEYS { + let value = fetch_opt( + &conn, + "SELECT value FROM settings WHERE key = ?1", + (key.to_owned(),), + |row| col_text(row, 0), + ) + .await?; + values.push(value); + } + let sealed_password = fetch_opt( + &conn, + "SELECT value FROM settings WHERE key = ?1", + (KEY_PASSWORD.to_owned(),), + |row| col_text(row, 0), + ) + .await?; + let sender = match values.as_slice() { + [ + Some(host), + Some(port), + Some(tls), + Some(username), + Some(address), + Some(name), + ] => { + let input = crate::sender::SenderInput { + host: host.clone(), + port: port.clone(), + tls: tls.clone(), + username: username.clone(), + from_address: address.clone(), + from_name: name.clone(), + }; + crate::sender::validate_sender(&input).ok() + } + _ => None, + }; + Ok(SenderState { + sender, + password_set: sealed_password.is_some(), + sealed_password, + }) + } + + /// Saves the sender. `sealed_password` replaces the stored password when it is `Some`; `None` keeps it. + pub async fn save_sender(&self, sender: &Sender, sealed_password: Option<&str>) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let mut pairs: Vec<(&str, String)> = vec![ + (KEYS[0], sender.host.clone()), + (KEYS[1], sender.port.to_string()), + (KEYS[2], sender.tls.as_str().to_owned()), + (KEYS[3], sender.username.clone()), + (KEYS[4], sender.from_address.clone()), + (KEYS[5], sender.from_name.clone()), + ]; + if let Some(sealed) = sealed_password { + pairs.push((KEY_PASSWORD, sealed.to_owned())); + } + put_all(&tx, &pairs).await + } + .await; + finish(tx, outcome).await + } + + /// The reminder settings as stored, or the defaults for a value never saved. + pub async fn reminder_settings(&self) -> Result { + let conn = self.read_conn().await; + let lead = super::reminders::lead_minutes(&conn).await?; + let cap = fetch_opt( + &conn, + "SELECT value FROM settings WHERE key = ?1", + (KEY_REMINDER_CAP.to_owned(),), + |row| col_text(row, 0), + ) + .await? + .and_then(|v| v.parse::().ok()) + .unwrap_or(DEFAULT_REMINDER_CAP); + Ok(ReminderSettings { + lead_minutes: u32::try_from(lead).unwrap_or(0), + hourly_cap: cap.min(crate::limits::REMINDER_CAP_MAX), + }) + } + + /// Saves the reminder settings. The lead is `0..=REMINDER_MINUTES_MAX`, the cap `1..=REMINDER_CAP_MAX`. + pub async fn save_reminder_settings(&self, settings: ReminderSettings) -> Result<()> { + if settings.lead_minutes > crate::limits::REMINDER_MINUTES_MAX { + return Err(Error::Invalid(format!( + "the reminder lead must be 0 to {} minutes", + crate::limits::REMINDER_MINUTES_MAX + ))); + } + if settings.hourly_cap == 0 || settings.hourly_cap > crate::limits::REMINDER_CAP_MAX { + return Err(Error::Invalid(format!( + "the reminder cap must be 1 to {} mails per hour", + crate::limits::REMINDER_CAP_MAX + ))); + } + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + put_all( + &tx, + &[ + (KEY_REMINDER_MINUTES, settings.lead_minutes.to_string()), + (KEY_REMINDER_CAP, settings.hourly_cap.to_string()), + ], + ) + .await + } + .await; + finish(tx, outcome).await + } +} diff --git a/crates/iz-core/src/store/tasks.rs b/crates/iz-core/src/store/tasks.rs index 46c38bc..7890b3c 100644 --- a/crates/iz-core/src/store/tasks.rs +++ b/crates/iz-core/src/store/tasks.rs @@ -16,11 +16,13 @@ use turso::transaction::Transaction; use super::activity::{self, NewActivity}; use super::board::{Column, Tag, column_in, live_columns}; +use super::events::{EventDraft, emit}; +use super::reminders::sync_reminders; use super::{ col_int, col_opt_text, col_real, col_text, db_err, fetch_all, fetch_opt, finish, new_id, }; use crate::board::{fold_for_search, format_key, is_overdue, position_between, would_cycle}; -use crate::clock::{reminder_due, timestamp_of}; +use crate::clock::timestamp_of; use crate::error::{Error, Result}; use crate::limits::{DESCRIPTION_MAX, TITLE_MAX}; use crate::store::Store; @@ -424,6 +426,31 @@ async fn record_transition( Ok(()) } +/// Queues one mail event for a task write, inside the write's transaction (see `events.rs`). +async fn queue_event( + tx: &Transaction<'_>, + board_id: &str, + task_id: &str, + kind: &'static str, + actor: &str, + subject: Option<&str>, + column: Option<&str>, +) -> Result<()> { + emit( + tx, + EventDraft { + board_id, + task_id: Some(task_id), + kind, + column_id: column, + actor: Some(actor), + subject, + detail: serde_json::json!({}), + }, + ) + .await +} + /// Writes one task-scoped activity row. async fn log( tx: &Transaction<'_>, @@ -446,50 +473,6 @@ async fn log( .await } -/// Rebuilds the pending reminders of one task (inventory 2.4): one per assignee, due a fixed lead time -/// before the meeting. Sent reminders are kept. None are made when the task is done, deleted, has no -/// meeting, or its meeting is in the past. -async fn sync_reminders(tx: &Transaction<'_>, task_id: &str) -> Result<()> { - tx.execute( - "DELETE FROM reminders WHERE task_id = ?1 AND sent_at IS NULL", - (task_id.to_owned(),), - ) - .await - .map_err(db_err)?; - let state = fetch_opt( - tx, - "SELECT meeting_at, done_at, deleted_at FROM tasks WHERE id = ?1", - (task_id.to_owned(),), - |row| { - Ok(( - col_opt_text(row, 0)?, - col_opt_text(row, 1)?, - col_opt_text(row, 2)?, - )) - }, - ) - .await?; - let Some((Some(meeting), None, None)) = state else { - return Ok(()); - }; - let at = timestamp_of(&meeting)?; - if at <= Timestamp::now() { - return Ok(()); - } - let due = reminder_due(at)?; - tx.execute( - "INSERT INTO reminders (task_id, sub, due_at, sent_at) \ - SELECT a.task_id, a.sub, ?2, NULL FROM task_assignees a \ - WHERE a.task_id = ?1 AND EXISTS ( \ - SELECT 1 FROM members m WHERE m.sub = a.sub AND m.disabled = 0 AND m.role IN ('admin', 'member')) \ - ON CONFLICT(task_id, sub) DO NOTHING", - (task_id.to_owned(), due), - ) - .await - .map_err(db_err)?; - Ok(()) -} - impl Store { /// Creates a task with everything it starts with, in one transaction: the key (from the board's /// counter, never reused), the placement, the assignees, the optional subtask parent and the optional @@ -585,6 +568,7 @@ impl Store { ) .await .map_err(db_err)?; + queue_event(&tx, board_id, &id, "linked", actor, None, None).await?; let direction_text = match direction { LinkDirection::BlockedBy => "blocked_by", LinkDirection::Blocks => "blocks", @@ -607,6 +591,7 @@ impl Store { .await .map_err(db_err)?; log(&tx, &id, actor, "assigned", Some(sub), serde_json::json!({})).await?; + queue_event(&tx, board_id, &id, "assigned", actor, Some(sub.as_str()), None).await?; } log( &tx, @@ -618,6 +603,7 @@ impl Store { ) .await?; record_transition(&tx, &id, None, &column.id, actor).await?; + queue_event(&tx, board_id, &id, "created", actor, None, None).await?; sync_reminders(&tx, &id).await?; live_task(&tx, board_id, &id).await } @@ -693,6 +679,19 @@ impl Store { } sync_reminders(&tx, task_id).await?; } + if before.title != title { + queue_event(&tx, board_id, task_id, "retitled", actor, None, None).await?; + } + let deadline_set = edit.deadline.is_some() && before.deadline != edit.deadline + || edit.meeting_at.is_some() && before.meeting_at != edit.meeting_at; + let deadline_cleared = before.deadline.is_some() && edit.deadline.is_none() + || before.meeting_at.is_some() && edit.meeting_at.is_none(); + if deadline_set { + queue_event(&tx, board_id, task_id, "deadline_set", actor, None, None).await?; + } + if deadline_cleared { + queue_event(&tx, board_id, task_id, "deadline_cleared", actor, None, None).await?; + } live_task(&tx, board_id, task_id).await } .await; @@ -774,6 +773,7 @@ impl Store { if task.done_at.is_some() != target.is_done { sync_reminders(&tx, task_id).await?; } + queue_event(&tx, board_id, task_id, "status", actor, None, Some(target.id.as_str())).await?; Ok(MoveOutcome::Moved) } .await; @@ -813,6 +813,7 @@ impl Store { .map_err(db_err)?; log(&tx, id, actor, "task_deleted", None, serde_json::json!({})).await?; } + queue_event(&tx, board_id, task_id, "deleted", actor, None, None).await?; let doomed_set: HashSet<&str> = doomed.iter().map(String::as_str).collect(); let mut edges: Vec<(String, String)> = Vec::new(); for id in &doomed { @@ -851,6 +852,7 @@ impl Store { serde_json::json!({ "blocker": blocking }), ) .await?; + queue_event(&tx, board_id, &blocked, "unblocked", actor, None, None).await?; freed.push(blocked); } } @@ -893,6 +895,7 @@ impl Store { .map_err(db_err)?; if added > 0 { log(&tx, task_id, actor, "assigned", Some(sub), serde_json::json!({})).await?; + queue_event(&tx, board_id, task_id, "assigned", actor, Some(sub.as_str()), None).await?; } } sync_reminders(&tx, task_id).await @@ -923,6 +926,16 @@ impl Store { .await .map_err(db_err)?; if removed > 0 { + queue_event( + &tx, + board_id, + task_id, + "unassigned", + actor, + Some(sub.as_str()), + None, + ) + .await?; log( &tx, task_id, @@ -1041,6 +1054,7 @@ impl Store { if would_cycle(&refs, (blocked_id, blocking_id)) { return Err(Error::Conflict("this link would make a dependency cycle".into())); } + queue_event(&tx, board_id, blocked_id, "linked", actor, None, None).await?; let now = now_stamp(); if existing.is_some() { tx.execute( @@ -1095,6 +1109,7 @@ impl Store { if changed == 0 { return Err(Error::NotFound); } + queue_event(&tx, board_id, blocked_id, "unlinked", actor, None, None).await?; log( &tx, blocked_id, diff --git a/crates/iz-web/Cargo.toml b/crates/iz-web/Cargo.toml index ac30ebe..6f89784 100644 --- a/crates/iz-web/Cargo.toml +++ b/crates/iz-web/Cargo.toml @@ -34,6 +34,7 @@ topcoat.workspace = true tracing.workspace = true thiserror.workspace = true tracing-subscriber = { workspace = true, features = ["env-filter"] } +lettre.workspace = true [dev-dependencies] # Makes Ed25519 keys for the token tests. Never used by the server. diff --git a/crates/iz-web/src/auth.rs b/crates/iz-web/src/auth.rs index d35d580..cf2d0d4 100644 --- a/crates/iz-web/src/auth.rs +++ b/crates/iz-web/src/auth.rs @@ -44,6 +44,8 @@ pub enum Need { Viewer, /// Creating and changing tasks, comments and files. Member, + /// The administrator pages: sender, mail rules, logs and messages to members. + Admin, } /// A signed-in member and the session that carries them. @@ -129,10 +131,17 @@ pub async fn require_role(cx: &Cx, need: Need) -> Result { let action = match need { Need::Viewer => Action::ReadBoard, Need::Member => Action::WriteTask, + Need::Admin => Action::Administer, }; match authorize(&me.actor(), &action) { Ok(()) => Ok(me), - Err(Denied::Forbidden) if need == Need::Member => Err(forbidden().into()), + // An active member who is refused an admin page is told so (403). A disabled member is not, + // so a disabled administrator sees the same 404 as anyone without access. + Err(Denied::Forbidden) + if need == Need::Member || (need == Need::Admin && !me.member.disabled) => + { + Err(forbidden().into()) + } Err(_) => Err(not_found().into()), } } diff --git a/crates/iz-web/src/boot.rs b/crates/iz-web/src/boot.rs index 200156a..63e6825 100644 --- a/crates/iz-web/src/boot.rs +++ b/crates/iz-web/src/boot.rs @@ -51,6 +51,7 @@ pub async fn serve(config_path: &Path) -> iz_core::Result<()> { let (stop_tx, stop_rx) = watch::channel(false); directory::spawn(state.clone(), stop_rx.clone()); attachments::spawn(state.clone(), stop_rx.clone()); + crate::mail::spawn(state.clone(), stop_rx.clone()); tokio::spawn(async move { shutdown_signal().await; tracing::info!("shutdown signal received"); diff --git a/crates/iz-web/src/i18n/admin.rs b/crates/iz-web/src/i18n/admin.rs new file mode 100644 index 0000000..f6525fe --- /dev/null +++ b/crates/iz-web/src/i18n/admin.rs @@ -0,0 +1,399 @@ +//! Strings of the admin pages: settings (sender, reminders, message to members), mail rules and logs. +//! One variant per phrase; `t` matches `(key, lang)` exhaustively, so a missing Turkish text does not compile. +//! Sentences with values use `{}` placeholders filled by `fill`, never by concatenation in views. + +use super::Lang; + +/// One phrase of the admin pages. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum K { + // Shared + NavSettings, + NavRules, + NavLogs, + Edit, + Delete, + Retry, + Enabled, + Apply, + Older, + NothingYet, + // Sender + SettingsTitle, + SenderHeading, + SenderHelp, + FieldHost, + FieldPort, + FieldTls, + TlsImplicit, + TlsStartTls, + TlsPlain, + FieldUsername, + FieldPassword, + PasswordHint, + PasswordSet, + PasswordNotSet, + FieldFromAddress, + FieldFromName, + FromNameHint, + SaveSender, + CheckConnection, + SendTestMail, + SenderNotConfigured, + // Reminders + RemindersHeading, + ReminderLead, + ReminderCap, + SaveReminders, + // Message to members + MessageHeading, + MessageHelp, + MessageSubject, + MessageBody, + SendMessage, + // Notices + NoticeSenderSaved, + NoticeCheckOk, + NoticeTestSent, + NoticeRemindersSaved, + NoticeMessageQueued, + NoticeRuleSaved, + NoticeRuleDeleted, + NoticeRuleSwitched, + NoticeRetried, + // Rules + RulesTitle, + RulesHelp, + NoRules, + RuleOn, + RuleOff, + NewRule, + EditRule, + FieldName, + FieldTrigger, + FieldColumn, + AnyColumn, + FieldProject, + AnyProject, + FieldAudience, + FieldSubject, + SubjectHint, + IncludeDetails, + SaveRule, + CancelEdit, + RuleSentence, + TrigStatus, + TrigStatusAny, + TrigUnblocked, + TrigCreated, + TrigAssigned, + TrigUnassigned, + TrigCommented, + TrigDeadlineSet, + TrigDeadlineCleared, + TrigRetitled, + TrigLinked, + TrigUnlinked, + TrigDeleted, + AudAssignees, + AudBoard, + AudCreator, + AudWatchers, + ProjectNote, + // Logs + LogsTitle, + SectionOutbox, + SectionDecisions, + SectionActivity, + ColRecipient, + ColSubject, + ColState, + ColAttempts, + ColLastError, + ColWhen, + ColRule, + ColTask, + ColOutcome, + ColDetail, + ColWho, + ColWhat, + StatePending, + StateSent, + StateFailed, + StateAbandoned, + OutOwed, + OutAlreadyOwed, + OutNoRecipients, + OutNotMatched, + OutDisabled, + OutTaskGone, + ReasonColumn, + ReasonProject, + FilterKind, + // Errors +} + +/// The text of `key` in `lang`. Placeholders are `{}` and are filled by [`fill`]. +pub fn t(lang: Lang, key: K) -> &'static str { + use Lang::{En, Tr}; + match (key, lang) { + (K::NavSettings, En) => "Settings", + (K::NavSettings, Tr) => "Ayarlar", + (K::NavRules, En) => "Mail rules", + (K::NavRules, Tr) => "Mail kuralları", + (K::NavLogs, En) => "Logs", + (K::NavLogs, Tr) => "Kayıtlar", + (K::Edit, En) => "Edit", + (K::Edit, Tr) => "Düzenle", + (K::Delete, En) => "Delete", + (K::Delete, Tr) => "Sil", + (K::Retry, En) => "Retry", + (K::Retry, Tr) => "Yeniden dene", + (K::Enabled, En) => "Enabled", + (K::Enabled, Tr) => "Etkin", + (K::Apply, En) => "Apply", + (K::Apply, Tr) => "Uygula", + (K::Older, En) => "Older", + (K::Older, Tr) => "Daha eski", + (K::NothingYet, En) => "Nothing here yet.", + (K::NothingYet, Tr) => "Henüz burada bir şey yok.", + (K::SettingsTitle, En) => "Settings", + (K::SettingsTitle, Tr) => "Ayarlar", + (K::SenderHeading, En) => "Outgoing mail", + (K::SenderHeading, Tr) => "Giden e-posta", + (K::SenderHelp, En) => { + "The server that sends iz mail. The password is stored sealed and is never shown again." + } + (K::SenderHelp, Tr) => { + "iz e-postalarını gönderen sunucu. Parola şifreli saklanır ve bir daha gösterilmez." + } + (K::FieldHost, En) => "Mail server", + (K::FieldHost, Tr) => "Posta sunucusu", + (K::FieldPort, En) => "Port", + (K::FieldPort, Tr) => "Port", + (K::FieldTls, En) => "Encryption", + (K::FieldTls, Tr) => "Şifreleme", + (K::TlsImplicit, En) => "Implicit TLS", + (K::TlsImplicit, Tr) => "Baştan TLS (implicit)", + (K::TlsStartTls, En) => "STARTTLS", + (K::TlsStartTls, Tr) => "STARTTLS", + (K::TlsPlain, En) => "None (localhost only)", + (K::TlsPlain, Tr) => "Yok (yalnızca localhost)", + (K::FieldUsername, En) => "User name", + (K::FieldUsername, Tr) => "Kullanıcı adı", + (K::FieldPassword, En) => "Password", + (K::FieldPassword, Tr) => "Parola", + (K::PasswordHint, En) => "Leave empty to keep the stored password.", + (K::PasswordHint, Tr) => "Kayıtlı parolayı korumak için boş bırakın.", + (K::PasswordSet, En) => "set", + (K::PasswordSet, Tr) => "ayarlı", + (K::PasswordNotSet, En) => "not set", + (K::PasswordNotSet, Tr) => "ayarlı değil", + (K::FieldFromAddress, En) => "From address", + (K::FieldFromAddress, Tr) => "Gönderen adresi", + (K::FieldFromName, En) => "From name", + (K::FieldFromName, Tr) => "Gönderen adı", + (K::FromNameHint, En) => "Empty means iz.", + (K::FromNameHint, Tr) => "Boş bırakılırsa iz kullanılır.", + (K::SaveSender, En) => "Save sender", + (K::SaveSender, Tr) => "Göndereni kaydet", + (K::CheckConnection, En) => "Check connection", + (K::CheckConnection, Tr) => "Bağlantıyı denetle", + (K::SendTestMail, En) => "Send test mail to me", + (K::SendTestMail, Tr) => "Bana deneme e-postası gönder", + (K::SenderNotConfigured, En) => "No sender is set up yet, so mail waits in the outbox.", + (K::SenderNotConfigured, Tr) => { + "Gönderen henüz ayarlanmadı; e-postalar giden kutusunda bekler." + } + (K::RemindersHeading, En) => "Meeting reminders", + (K::RemindersHeading, Tr) => "Toplantı hatırlatmaları", + (K::ReminderLead, En) => "Minutes before the meeting (0 turns reminders off)", + (K::ReminderLead, Tr) => "Toplantıdan kaç dakika önce (0 hatırlatmayı kapatır)", + (K::ReminderCap, En) => "Most reminder mails per member per hour", + (K::ReminderCap, Tr) => "Üye başına saatte en çok hatırlatma e-postası", + (K::SaveReminders, En) => "Save reminders", + (K::SaveReminders, Tr) => "Hatırlatmaları kaydet", + (K::MessageHeading, En) => "Message to members", + (K::MessageHeading, Tr) => "Üyelere ileti", + (K::MessageHelp, En) => { + "Sent as mail to every active member except you. One message every 10 minutes." + } + (K::MessageHelp, Tr) => { + "Siz hariç etkin her üyeye e-posta olarak gönderilir. 10 dakikada bir ileti gönderilebilir." + } + (K::MessageSubject, En) => "Subject", + (K::MessageSubject, Tr) => "Konu", + (K::MessageBody, En) => "Message", + (K::MessageBody, Tr) => "İleti", + (K::SendMessage, En) => "Send message", + (K::SendMessage, Tr) => "İletiyi gönder", + (K::NoticeSenderSaved, En) => "Sender saved.", + (K::NoticeSenderSaved, Tr) => "Gönderen kaydedildi.", + (K::NoticeCheckOk, En) => "The server accepted the connection.", + (K::NoticeCheckOk, Tr) => "Sunucu bağlantıyı kabul etti.", + (K::NoticeTestSent, En) => "Test mail sent to your address.", + (K::NoticeTestSent, Tr) => "Deneme e-postası adresinize gönderildi.", + (K::NoticeRemindersSaved, En) => "Reminder settings saved.", + (K::NoticeRemindersSaved, Tr) => "Hatırlatma ayarları kaydedildi.", + (K::NoticeMessageQueued, En) => "Message queued for {} members.", + (K::NoticeMessageQueued, Tr) => "İleti {} üye için kuyruğa alındı.", + (K::NoticeRuleSaved, En) => "Rule saved.", + (K::NoticeRuleSaved, Tr) => "Kural kaydedildi.", + (K::NoticeRuleDeleted, En) => "Rule deleted.", + (K::NoticeRuleDeleted, Tr) => "Kural silindi.", + (K::NoticeRuleSwitched, En) => "Rule switched.", + (K::NoticeRuleSwitched, Tr) => "Kural değiştirildi.", + (K::NoticeRetried, En) => "Queued again.", + (K::NoticeRetried, Tr) => "Yeniden kuyruğa alındı.", + (K::RulesTitle, En) => "Mail rules", + (K::RulesTitle, Tr) => "Mail kuralları", + (K::RulesHelp, En) => "A rule mails people when something happens on the board.", + (K::RulesHelp, Tr) => "Kural, panoda bir şey olduğunda kişilere e-posta gönderir.", + (K::NoRules, En) => "No rules yet.", + (K::NoRules, Tr) => "Henüz kural yok.", + (K::RuleOn, En) => "On", + (K::RuleOn, Tr) => "Açık", + (K::RuleOff, En) => "Off", + (K::RuleOff, Tr) => "Kapalı", + (K::NewRule, En) => "New rule", + (K::NewRule, Tr) => "Yeni kural", + (K::EditRule, En) => "Edit rule", + (K::EditRule, Tr) => "Kuralı düzenle", + (K::FieldName, En) => "Name", + (K::FieldName, Tr) => "Ad", + (K::FieldTrigger, En) => "When", + (K::FieldTrigger, Tr) => "Ne zaman", + (K::FieldColumn, En) => "Column (for the moves-to trigger)", + (K::FieldColumn, Tr) => "Sütun (taşınma tetikleyicisi için)", + (K::AnyColumn, En) => "Any column", + (K::AnyColumn, Tr) => "Herhangi bir sütun", + (K::FieldProject, En) => "Project", + (K::FieldProject, Tr) => "Proje", + (K::AnyProject, En) => "Any project", + (K::AnyProject, Tr) => "Herhangi bir proje", + (K::FieldAudience, En) => "Who gets the mail", + (K::FieldAudience, Tr) => "E-postayı kim alır", + (K::FieldSubject, En) => "Subject", + (K::FieldSubject, Tr) => "Konu", + (K::SubjectHint, En) => "Placeholders: {key} {title} {column} {actor} {tag} {deadline}", + (K::SubjectHint, Tr) => "Yer tutucular: {key} {title} {column} {actor} {tag} {deadline}", + (K::IncludeDetails, En) => { + "Include the details (column, deadline, assignees, meeting time)" + } + (K::IncludeDetails, Tr) => "Ayrıntıları ekle (sütun, son tarih, atananlar, toplantı saati)", + (K::SaveRule, En) => "Save rule", + (K::SaveRule, Tr) => "Kuralı kaydet", + (K::CancelEdit, En) => "Cancel", + (K::CancelEdit, Tr) => "Vazgeç", + (K::RuleSentence, En) => "When a task {}, mail {}. Subject: “{}”.", + (K::RuleSentence, Tr) => "Bir kart {}, {} e-posta alır. Konu: “{}”.", + (K::TrigStatus, En) => "moves to {}", + (K::TrigStatus, Tr) => "{} sütununa taşınırsa", + (K::TrigStatusAny, En) => "moves to any column", + (K::TrigStatusAny, Tr) => "herhangi bir sütuna taşınırsa", + (K::TrigUnblocked, En) => "stops being blocked", + (K::TrigUnblocked, Tr) => "engelli olmaktan çıkarsa", + (K::TrigCreated, En) => "is created", + (K::TrigCreated, Tr) => "oluşturulursa", + (K::TrigAssigned, En) => "is assigned to someone", + (K::TrigAssigned, Tr) => "birine atanırsa", + (K::TrigUnassigned, En) => "loses an assignee", + (K::TrigUnassigned, Tr) => "bir atanan çıkarılırsa", + (K::TrigCommented, En) => "gets a comment", + (K::TrigCommented, Tr) => "yorum alırsa", + (K::TrigDeadlineSet, En) => "gets a deadline or meeting time", + (K::TrigDeadlineSet, Tr) => "son tarih veya toplantı saati alırsa", + (K::TrigDeadlineCleared, En) => "loses its deadline or meeting time", + (K::TrigDeadlineCleared, Tr) => "son tarihi veya toplantı saati kalkarsa", + (K::TrigRetitled, En) => "is renamed", + (K::TrigRetitled, Tr) => "başlığı değişirse", + (K::TrigLinked, En) => "gets a dependency", + (K::TrigLinked, Tr) => "bir bağımlılık alırsa", + (K::TrigUnlinked, En) => "loses a dependency", + (K::TrigUnlinked, Tr) => "bir bağımlılığı kalkarsa", + (K::TrigDeleted, En) => "is deleted", + (K::TrigDeleted, Tr) => "silinirse", + (K::AudAssignees, En) => "the assignees", + (K::AudAssignees, Tr) => "atanan kişiler", + (K::AudBoard, En) => "every member", + (K::AudBoard, Tr) => "tüm üyeler", + (K::AudCreator, En) => "the creator", + (K::AudCreator, Tr) => "kartı oluşturan", + (K::AudWatchers, En) => "the watchers", + (K::AudWatchers, Tr) => "izleyenler", + (K::ProjectNote, En) => "(project {})", + (K::ProjectNote, Tr) => "({} projesi)", + (K::LogsTitle, En) => "Logs", + (K::LogsTitle, Tr) => "Kayıtlar", + (K::SectionOutbox, En) => "Outbox", + (K::SectionOutbox, Tr) => "Giden kutusu", + (K::SectionDecisions, En) => "Rule decisions", + (K::SectionDecisions, Tr) => "Kural kararları", + (K::SectionActivity, En) => "Activity", + (K::SectionActivity, Tr) => "Etkinlik", + (K::ColRecipient, En) => "Recipient", + (K::ColRecipient, Tr) => "Alıcı", + (K::ColSubject, En) => "Subject", + (K::ColSubject, Tr) => "Konu", + (K::ColState, En) => "State", + (K::ColState, Tr) => "Durum", + (K::ColAttempts, En) => "Attempts", + (K::ColAttempts, Tr) => "Deneme", + (K::ColLastError, En) => "Last error", + (K::ColLastError, Tr) => "Son hata", + (K::ColWhen, En) => "When", + (K::ColWhen, Tr) => "Zaman", + (K::ColRule, En) => "Rule", + (K::ColRule, Tr) => "Kural", + (K::ColTask, En) => "Task", + (K::ColTask, Tr) => "Kart", + (K::ColOutcome, En) => "Outcome", + (K::ColOutcome, Tr) => "Sonuç", + (K::ColDetail, En) => "Detail", + (K::ColDetail, Tr) => "Ayrıntı", + (K::ColWho, En) => "Who", + (K::ColWho, Tr) => "Kim", + (K::ColWhat, En) => "What", + (K::ColWhat, Tr) => "Ne", + (K::StatePending, En) => "pending", + (K::StatePending, Tr) => "bekliyor", + (K::StateSent, En) => "sent", + (K::StateSent, Tr) => "gönderildi", + (K::StateFailed, En) => "failed, will retry", + (K::StateFailed, Tr) => "başarısız, yeniden denenecek", + (K::StateAbandoned, En) => "abandoned", + (K::StateAbandoned, Tr) => "vazgeçildi", + (K::OutOwed, En) => "owed", + (K::OutOwed, Tr) => "gönderilecek", + (K::OutAlreadyOwed, En) => "already owed", + (K::OutAlreadyOwed, Tr) => "zaten kuyrukta", + (K::OutNoRecipients, En) => "no recipients", + (K::OutNoRecipients, Tr) => "alıcı yok", + (K::OutNotMatched, En) => "not matched", + (K::OutNotMatched, Tr) => "eşleşmedi", + (K::OutDisabled, En) => "rule off", + (K::OutDisabled, Tr) => "kural kapalı", + (K::OutTaskGone, En) => "task gone", + (K::OutTaskGone, Tr) => "kart yok", + (K::ReasonColumn, En) => "another column", + (K::ReasonColumn, Tr) => "başka sütun", + (K::ReasonProject, En) => "another project", + (K::ReasonProject, Tr) => "başka proje", + (K::FilterKind, En) => "Kind", + (K::FilterKind, Tr) => "Tür", + } +} + +/// Fills the `{}` placeholders of `template` in order. Extra placeholders stay empty. +pub fn fill(template: &str, values: &[&str]) -> String { + let mut out = String::with_capacity(template.len() + 16); + let mut rest = template; + let mut values = values.iter(); + while let Some(at) = rest.find("{}") { + out.push_str(&rest[..at]); + out.push_str(values.next().copied().unwrap_or("")); + rest = &rest[at + 2..]; + } + out.push_str(rest); + out +} diff --git a/crates/iz-web/src/i18n/mod.rs b/crates/iz-web/src/i18n/mod.rs index bfcb045..6dd121d 100644 --- a/crates/iz-web/src/i18n/mod.rs +++ b/crates/iz-web/src/i18n/mod.rs @@ -7,6 +7,7 @@ //! This module decides the language. It does not format sentences with values; those get small //! helper functions next to their keys. +pub mod admin; pub mod board; pub mod shell; pub mod task; diff --git a/crates/iz-web/src/mail/compose.rs b/crates/iz-web/src/mail/compose.rs new file mode 100644 index 0000000..03ccc38 --- /dev/null +++ b/crates/iz-web/src/mail/compose.rs @@ -0,0 +1,210 @@ +//! Builds the message of one outbox row with lettre's typed builders. It is the only place a mail +//! header is written, and it never takes a header from text: every name and the subject go through +//! `clean_text` first, so a CR or LF in a member's name or an actor's name cannot start a header line. +//! +//! The body is plain text, and an HTML alternative is made from it here with every character escaped. +//! It is not a rendering of a page, so it never contains a link or script the text did not have. + +use iz_core::rules::clean_text; +use iz_core::sender::Sender; +use lettre::Address; +use lettre::message::{Mailbox, Message, MultiPart}; + +/// Longest subject sent, in characters. Reason: the same cap as the subject field of a rule. +pub const SUBJECT_MAX: usize = iz_core::limits::MAIL_SUBJECT_MAX; +/// Longest display name of a mailbox, in characters. Reason: a name is a label, not a sentence. +const NAME_MAX: usize = 100; +/// Message-ID domain used when the base URL has no usable host. Reason: a fixed, valid fallback. +const FALLBACK_DOMAIN: &str = "localhost"; + +/// What the builder needs besides the row: the sender's configuration and the recipient. +pub struct Outgoing<'a> { + /// The checked sender configuration (host, port, and the From address and name). + pub sender: &'a Sender, + /// The recipient's display name. + pub to_name: &'a str, + /// The recipient's address, as the directory has it. + pub to_address: &'a str, + /// The subject, plain text. + pub subject: &'a str, + /// The body, plain text. + pub body: &'a str, + /// The outbox row id. It makes the Message-ID unique. + pub row_id: &'a str, + /// The domain part of the Message-ID, taken from the base URL. + pub domain: &'a str, +} + +/// Builds the message. `Err` holds the reason as text; the caller stores it as the last error. +pub fn build(m: &Outgoing<'_>) -> Result { + let from_name = bounded(&m.sender.from_name, NAME_MAX); + let from_address: Address = m + .sender + .from_address + .parse() + .map_err(|_| "the sender address is not valid".to_owned())?; + let to_address: Address = m + .to_address + .parse() + .map_err(|_| "the recipient address is not valid".to_owned())?; + let from = Mailbox::new(non_empty(from_name), from_address); + let to = Mailbox::new(non_empty(bounded(m.to_name, NAME_MAX)), to_address); + let subject = bounded(m.subject, SUBJECT_MAX); + let body = clean_body(m.body); + let html = html_alternative(&body); + Message::builder() + .from(from) + .to(to) + .subject(subject) + .message_id(Some(format!("<{}@{}>", m.row_id, safe_domain(m.domain)))) + .date_now() + .multipart(MultiPart::alternative_plain_html(body, html)) + .map_err(|e| format!("cannot build the message: {e}")) +} + +/// The text with control and invisible formatting characters removed, cut to `max` characters. +fn bounded(text: &str, max: usize) -> String { + clean_text(text).trim().chars().take(max).collect() +} + +/// `None` for an empty name, so the mailbox has only the address. +fn non_empty(name: String) -> Option { + (!name.is_empty()).then_some(name) +} + +/// The body with CRLF and CR turned into LF, and control characters other than tab and LF removed. +fn clean_body(body: &str) -> String { + let normalized = body.replace("\r\n", "\n").replace('\r', "\n"); + normalized + .chars() + .filter(|c| *c == '\n' || *c == '\t' || !c.is_control()) + .collect() +} + +/// The HTML alternative: each line is one paragraph, every character escaped. Nothing else is emitted. +fn html_alternative(text: &str) -> String { + let mut out = String::from("\n\n"); + for line in text.split('\n') { + if line.is_empty() { + out.push_str("
\n"); + } else { + out.push_str("

"); + out.push_str(&escape(line)); + out.push_str("

\n"); + } + } + out.push_str("\n"); + out +} + +/// Escapes the five characters that are special in HTML text and attribute values. +pub fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + other => out.push(other), + } + } + out +} + +/// The host of a base URL, reduced to letters, digits, dots and dashes. The fallback when it is empty. +pub fn domain_of(base_url: &str) -> String { + let host = reqwest::Url::parse(base_url) + .ok() + .and_then(|url| url.host_str().map(str::to_owned)) + .unwrap_or_default(); + safe_domain(&host).to_owned() +} + +/// `domain` if it is made of letters, digits, dots and dashes; the fallback otherwise. +fn safe_domain(domain: &str) -> &str { + let usable = !domain.is_empty() + && domain.len() <= 253 + && domain + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-'); + if usable { domain } else { FALLBACK_DOMAIN } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sender(from_name: &str) -> Sender { + Sender { + host: "mail.example.test".into(), + port: 587, + tls: iz_core::sender::TlsMode::StartTls, + username: "u".into(), + from_address: "iz@example.test".into(), + from_name: from_name.into(), + } + } + + /// A CRLF in the from name, the actor's name or the subject must not produce a header line. + #[test] + fn crlf_and_bcc_injection_makes_no_extra_header() { + let evil = sender("Board\r\nBcc: spy@evil.test"); + let message = build(&Outgoing { + sender: &evil, + to_name: "Ada\r\nBcc: spy@evil.test", + to_address: "ada@example.test", + subject: "Task moved\r\nBcc: spy@evil.test\r\nX-Injected: 1", + body: "Hello", + row_id: "01HZ", + domain: "iz.example.test", + }) + .expect("builds"); + let text = String::from_utf8_lossy(&message.formatted()).into_owned(); + let headers = text.split("\r\n\r\n").next().unwrap_or_default(); + assert!( + !headers.lines().any(|line| line.starts_with("Bcc:")), + "{headers}" + ); + assert!( + !headers.lines().any(|line| line.starts_with("X-Injected:")), + "{headers}" + ); + } + + #[test] + fn subject_is_cleaned_and_cut_to_the_limit() { + let long = format!("{}\r\n{}", "a".repeat(300), "b"); + let message = build(&Outgoing { + sender: &sender("iz"), + to_name: "", + to_address: "ada@example.test", + subject: &long, + body: "x", + row_id: "01HZ", + domain: "iz.example.test", + }) + .expect("builds"); + let text = String::from_utf8_lossy(&message.formatted()).into_owned(); + let subject_line = text + .lines() + .find(|line| line.starts_with("Subject:")) + .expect("has a subject"); + assert!(subject_line.len() <= "Subject: ".len() + SUBJECT_MAX); + } + + #[test] + fn html_alternative_escapes_every_value() { + let html = html_alternative(" & \"q\""); + assert!(!html.contains("