From 08366ca895393c4e84cb7d351a2466fc7c4b30f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 16:26:35 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(settings):=20send=20a=20test?= =?UTF-8?q?=20mail=20to=20yourself=20and=20keep=20the=20result?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sender panel could be filled in and saved, but nothing told an admin whether what they saved actually works. The artboard answers that with a row under the fields — `delivered in 1.2 s — Aug 25 10:41` — so the result has to survive a reload, not live in a signal that a refresh throws away. - `send_test_mail` is admin-only in the handler, refuses when no sender is saved rather than burning a send, and mails only the caller's own address: a test pointable at a typed address would be a way to make Dizey mail a stranger on demand. - The outcome is stored on the workspace (migration 0009) and cleared by `set_sender`, so a green line never sits under settings nobody has tried. - Forms cannot nest, so the test form sits beside the settings form in a split foot and Save reaches back with `form="sender-settings"` — which works with and without script. - `.panel-foot` now sets `flex-direction: row`: a foot inside a `.panel-body` was inheriting that column and stacking the sign-out row centred. Verified in a headless browser: pressing the button with no sender saved says so; with a sender pointed at a closed port the row reads `not delivered, Aug 26 13:25 — Connection error: Connection refused (os error 111)` and is still there after a reload. The `delivered in 1.2 s` formatting is gated by a unit test, not by a live send. --- .../migrations/0009_sender_test.sql | 14 ++ crates/dizey-core/src/mail.rs | 23 +++ crates/dizey-core/src/store/mod.rs | 20 ++ crates/dizey-core/src/store/turso_store.rs | 38 +++- crates/dizey-core/tests/store.rs | 4 +- crates/dizey-web/src/server.rs | 8 + crates/dizey-web/src/settings.rs | 176 +++++++++++++++++- crates/dizey-web/tests/http.rs | 79 +++++++- style/main.scss | 11 ++ 9 files changed, 363 insertions(+), 10 deletions(-) create mode 100644 crates/dizey-core/migrations/0009_sender_test.sql diff --git a/crates/dizey-core/migrations/0009_sender_test.sql b/crates/dizey-core/migrations/0009_sender_test.sql new file mode 100644 index 0000000..e5d2c92 --- /dev/null +++ b/crates/dizey-core/migrations/0009_sender_test.sql @@ -0,0 +1,14 @@ +-- The result of the last "send test mail to myself", kept on the workspace. +-- +-- It is kept rather than shown once because of what the panel is for: an admin +-- fills the sender in, presses the button, and comes back tomorrow wondering +-- whether it ever worked. A result that vanished on reload would answer that +-- question with silence, and silence is what the whole mail ledger exists to +-- avoid. +-- +-- `smtp_test_error` is the mail server's own words, kept so the admin can act +-- on them. Nothing writes the password into it: the mailer builds its errors +-- from what the server said, never from the credentials it sent. +ALTER TABLE workspace ADD COLUMN smtp_test_at INTEGER; +ALTER TABLE workspace ADD COLUMN smtp_test_ms INTEGER; +ALTER TABLE workspace ADD COLUMN smtp_test_error TEXT; diff --git a/crates/dizey-core/src/mail.rs b/crates/dizey-core/src/mail.rs index 0a3e714..46f3fa9 100644 --- a/crates/dizey-core/src/mail.rs +++ b/crates/dizey-core/src/mail.rs @@ -137,6 +137,29 @@ impl Engine { } } + /// Sends one mail to the address given, right now, and says how long the + /// mail server took to accept it. + /// + /// This is the only send that does not go through the ledger, and that is + /// deliberate: a test mail is owed to nobody. If it fails there is nothing + /// to retry and nothing to abandon — the person who pressed the button is + /// watching, and the answer is for them. + pub async fn send_test(&self, to: &str) -> std::result::Result { + let mail = Outgoing { + to: to.to_string(), + subject: "Dizey test mail".to_string(), + body: "Somebody pressed the test button in Dizey's settings, and this \ + is what came out. Nothing else was sent, and nobody else was \ + written to.\n" + .to_string(), + }; + let started = std::time::Instant::now(); + self.mailer.send(&mail).await?; + Ok(Duration::milliseconds( + started.elapsed().as_millis().min(i64::MAX as u128) as i64, + )) + } + /// Everything one crossing owes. Called after the move has committed, never /// inside it. pub async fn on_transition(&self, transition: &Transition) -> crate::store::Result { diff --git a/crates/dizey-core/src/store/mod.rs b/crates/dizey-core/src/store/mod.rs index d7dc785..c4bc8f4 100644 --- a/crates/dizey-core/src/store/mod.rs +++ b/crates/dizey-core/src/store/mod.rs @@ -56,6 +56,9 @@ pub struct Workspace { /// Whether a password is stored, never the password. Derived in the query /// so that the value itself does not travel even this far. pub smtp_password_set: bool, + /// How the last "send test mail to myself" went, if one has been pressed + /// since the sender was last edited. + pub sender_test: Option, pub attachment_limit_bytes: u64, pub photo_limit_bytes: u64, pub allowed_file_types: Vec, @@ -67,6 +70,19 @@ pub struct Workspace { /// the screen sends when a password is already stored: the field is write-only, /// so an edit to the port must not blank the password just because the form had /// nothing to put in it. +/// What came of pressing the test button: when, how long the mail server took, +/// and what it said if it refused. +/// +/// `error` is `None` for a mail that was accepted. It holds the mail server's +/// own words otherwise, because "it did not work" is not something an admin can +/// act on and "535 authentication failed" is. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SenderTest { + pub at: OffsetDateTime, + pub took_ms: u64, + pub error: Option, +} + #[derive(Debug, Clone, PartialEq)] pub struct NewSender { pub host: String, @@ -322,6 +338,10 @@ pub trait Store: BoardReads + DetailReads + 'static { /// screen was never allowed to show them. async fn set_sender(&self, workspace_id: &str, sender: NewSender) -> Result<()>; + /// Writes down how the last test send went. Editing the sender clears it, + /// so what is stored is always about the settings that are stored. + async fn record_sender_test(&self, workspace_id: &str, test: SenderTest) -> Result<()>; + /// Reads the sender's password. Only the mailer calls this, and nothing it /// returns reaches a response body. async fn smtp_password(&self, workspace_id: &str) -> Result>; diff --git a/crates/dizey-core/src/store/turso_store.rs b/crates/dizey-core/src/store/turso_store.rs index 28b65d6..95b099e 100644 --- a/crates/dizey-core/src/store/turso_store.rs +++ b/crates/dizey-core/src/store/turso_store.rs @@ -15,7 +15,7 @@ use uuid::Uuid; use super::{ Audience, Deletion, Event, Freeing, MailRule, MailSend, NewSender, NewTask, NewUser, Recipient, Result, - SendState, Session, SigninLink, Store, StoreError, Trigger, User, Workspace, + SendState, SenderTest, Session, SigninLink, Store, StoreError, Trigger, User, Workspace, }; use crate::Role; use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition}; @@ -36,6 +36,7 @@ const MIGRATIONS: &[(i64, &str)] = &[ (6, include_str!("../../migrations/0006_sender_is_config.sql")), (7, include_str!("../../migrations/0007_who_invited.sql")), (8, include_str!("../../migrations/0008_sender_is_settings.sql")), + (9, include_str!("../../migrations/0009_sender_test.sql")), ]; /// The board a fresh workspace gets, and its columns. `Done` is the column @@ -351,6 +352,14 @@ fn workspace_from(row: &Row) -> Result { smtp_from_name: opt_text(row, 9)?, smtp_from_address: opt_text(row, 10)?, smtp_password_set: row.get::(11).map_err(backend)? != 0, + sender_test: match opt_stamp(row, 12)? { + Some(at) => Some(SenderTest { + at, + took_ms: row.get::(13).map_err(backend)?.max(0) as u64, + error: opt_text(row, 14)?, + }), + None => None, + }, }) } @@ -360,7 +369,8 @@ fn workspace_from(row: &Row) -> Result { const WORKSPACE_COLUMNS: &str = "id, name, created_at, attachment_limit_bytes, \ allowed_file_types, photo_limit_bytes, smtp_host, smtp_port, smtp_username, \ smtp_from_name, smtp_from_address, \ - (smtp_password IS NOT NULL AND smtp_password <> '')"; + (smtp_password IS NOT NULL AND smtp_password <> ''), \ + smtp_test_at, smtp_test_ms, smtp_test_error"; fn user_from(row: &Row) -> Result { Ok(User { @@ -535,11 +545,16 @@ impl Store for TursoStore { // screen sends no password when the admin did not type one, and the // stored secret survives an edit to the port. Passing an empty string // is not a way to blank it either — the form sends `None` for empty. + // + // The last test result is cleared by the same statement. It was about + // the settings that have just been replaced, and a green "delivered" + // line under a host nobody has tried yet is worse than no line at all. self.conn .execute( "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \ smtp_password = COALESCE(?4, smtp_password), smtp_from_name = ?5, \ - smtp_from_address = ?6 WHERE id = ?7", + smtp_from_address = ?6, smtp_test_at = NULL, smtp_test_ms = NULL, \ + smtp_test_error = NULL WHERE id = ?7", params![ sender.host, sender.port as i64, @@ -555,6 +570,23 @@ impl Store for TursoStore { Ok(()) } + async fn record_sender_test(&self, workspace_id: &str, test: SenderTest) -> Result<()> { + self.conn + .execute( + "UPDATE workspace SET smtp_test_at = ?1, smtp_test_ms = ?2, \ + smtp_test_error = ?3 WHERE id = ?4", + params![ + stamp(test.at)?, + test.took_ms as i64, + test.error, + workspace_id + ], + ) + .await + .map_err(backend)?; + Ok(()) + } + async fn smtp_password(&self, workspace_id: &str) -> Result> { match self .one_row( diff --git a/crates/dizey-core/tests/store.rs b/crates/dizey-core/tests/store.rs index 048f358..580e3e4 100644 --- a/crates/dizey-core/tests/store.rs +++ b/crates/dizey-core/tests/store.rs @@ -89,14 +89,14 @@ async fn migrations_apply_once_and_survive_reopen() { let path = dir.join("dizey.db").to_string_lossy().into_owned(); let first = TursoStore::open(&path).await.unwrap(); - assert_eq!(first.schema_version().await.unwrap(), 8); + assert_eq!(first.schema_version().await.unwrap(), 9); claim(&first).await; drop(first); // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and // must not lose what the first open wrote. let second = TursoStore::open(&path).await.unwrap(); - assert_eq!(second.schema_version().await.unwrap(), 8); + assert_eq!(second.schema_version().await.unwrap(), 9); assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey"); drop(second); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/dizey-web/src/server.rs b/crates/dizey-web/src/server.rs index 0de95e8..734c3ae 100644 --- a/crates/dizey-web/src/server.rs +++ b/crates/dizey-web/src/server.rs @@ -73,6 +73,14 @@ impl Mail { }); } + /// Sends one test mail and waits for the answer, because the answer is the + /// whole point of pressing the button. `None` means this process has no + /// engine at all, which happens only in tests. + pub async fn test(&self, to: &str) -> Option> { + let engine = self.0.clone()?; + Some(engine.send_test(to).await) + } + fn log(report: dizey_core::store::Result) { match report { Ok(report) if report.sent + report.failed + report.abandoned > 0 => { diff --git a/crates/dizey-web/src/settings.rs b/crates/dizey-web/src/settings.rs index fc3a653..7691d9f 100644 --- a/crates/dizey-web/src/settings.rs +++ b/crates/dizey-web/src/settings.rs @@ -26,6 +26,20 @@ pub struct Sender { pub from_name: String, pub from_address: String, pub password_set: bool, + /// The last test result, as the panel prints it, or nothing when the button + /// has not been pressed since the sender was last edited. + pub test: Option, +} + +/// What the row under the test button says. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TestResult { + /// `Aug 25 10:41`, in UTC, the same stamp the activity strip uses. + pub moment: String, + /// `1.2 s`, or nothing when the send never got as far as being timed. + pub took: Option, + /// What the mail server said, if it refused. + pub error: Option, } impl Sender { @@ -52,10 +66,27 @@ impl Sender { from_name: workspace.smtp_from_name.clone().unwrap_or_default(), from_address: workspace.smtp_from_address.clone().unwrap_or_default(), password_set: workspace.smtp_password_set, + test: workspace.sender_test.as_ref().map(|test| TestResult { + moment: dizey_core::detail::moment_label(test.at), + took: test.error.is_none().then(|| took_label(test.took_ms)), + error: test.error.clone(), + }), } } } +/// `1.2 s` for anything over a second, `840 ms` below it. A mail server that +/// answered in under a second is worth saying so precisely; one that took eight +/// is worth a number somebody can compare to the last one. +#[cfg(feature = "ssr")] +fn took_label(ms: u64) -> String { + if ms >= 1000 { + format!("{:.1} s", ms as f64 / 1000.0) + } else { + format!("{ms} ms") + } +} + /// The workspace's limits, as the panel edits them. Megabytes here and bytes /// in the store: the field says "25 MB per file" and a person typing 25 into /// it should not have to know what that is in bytes. @@ -352,6 +383,62 @@ pub async fn save_sender( } } +/// Sends one mail to the admin who pressed the button, and writes down how it +/// went so the answer survives a reload. +/// +/// It goes to their own address and nowhere else. A test that could be pointed +/// at an address somebody typed would be a way to make Dizey mail a stranger +/// on demand, which is a thing worth not building. +#[server] +pub async fn send_test_mail() -> Result, ServerFnError> { + use crate::server::{accounts, mail, require_admin}; + use dizey_core::store::SenderTest; + + let admin = match require_admin().await { + Ok(admin) => admin, + Err(refusal) => return Ok(Some(refusal)), + }; + + let store = accounts().store().clone(); + let configured = store + .workspace() + .await + .map_err(|e| ServerFnError::new(e.to_string()))? + .is_some_and(|ws| ws.smtp_password_set && ws.smtp_host.is_some()); + if !configured { + return Ok(Some(Refusal::BadSender( + "Fill the sender in and save it first — there is nothing to test yet.".to_string(), + ))); + } + + let Some(outcome) = mail().test(&admin.email).await else { + // No engine in this process at all. Nothing sends here, and saying so + // beats writing down a failure the settings did not cause. + return Ok(Some(Refusal::Unavailable)); + }; + + let at = time::OffsetDateTime::now_utc(); + let test = match outcome { + Ok(took) => SenderTest { + at, + took_ms: took.whole_milliseconds().max(0) as u64, + error: None, + }, + Err(problem) => SenderTest { + at, + took_ms: 0, + // The mailer builds this from what the server said, never from the + // credentials it sent, so it is safe to store and to show. + error: Some(problem.message.clone()), + }, + }; + if let Err(problem) = store.record_sender_test(&admin.workspace_id, test).await { + eprintln!("store error: {problem}"); + return Ok(Some(Refusal::Unavailable)); + } + Ok(None) +} + /// The shallowest check that catches a typo without rejecting a real address. /// Nothing here is trying to decide what RFC 5322 permits — the mail server /// settles that, and a refusal from it lands in the ledger with its own words. @@ -632,8 +719,53 @@ fn SenderPanel(sender: Sender, on_change: Callback<()>) -> impl IntoView { } }); + // The test writes down what happened, so the panel is refetched after it + // for the same reason it is after a save: what is on screen should be the + // stored answer, not this browser's memory of one. + let test = ServerAction::::new(); + let tested = test.value(); + Effect::new(move |_| { + if matches!(tested.get(), Some(Ok(None))) { + on_change.run(()); + } + }); + let test_refusal = move || match tested.get() { + Some(Ok(Some(refusal))) => Some(refusal.message()), + Some(Err(_)) => Some(Refusal::Unavailable.message()), + _ => None, + }; + let connected = sender.is_connected(); let password_set = sender.password_set; + // What the row says: a refusal from the call itself if there was one, and + // otherwise the stored result of the last test — which outlives the reload, + // because "did this ever work" is a question asked the next morning. + let last = sender.test.clone(); + let test_line = move || match (test_refusal(), last.clone()) { + (Some(message), _) => { + view! { {message} }.into_any() + } + (None, Some(result)) => match (result.error, result.took) { + (Some(problem), _) => { + view! { + + {format!("not delivered, {} — {problem}", result.moment)} + + } + .into_any() + } + (None, Some(took)) => { + view! { + + {format!("delivered in {took} — {}", result.moment)} + + } + .into_any() + } + (None, None) => ().into_any(), + }, + (None, None) => ().into_any(), + }; view! {
@@ -657,7 +789,7 @@ fn SenderPanel(sender: Sender, on_change: Callback<()>) -> impl IntoView {

} })} - +
-
+ + // The test lives outside the settings form because it is its + // own call, and a form cannot hold another. Save reaches back + // into that form by name, which is what the `form` attribute is + // for, and works in a browser with no script as well as one + // with. +
+
+ + + + {test_line} +
+
{move || refusal()} "Saved." - +
- +
} @@ -1032,3 +1185,18 @@ fn MembersPanel( } } + +#[cfg(all(test, feature = "ssr"))] +mod tests { + use super::took_label; + + #[test] + fn a_send_is_timed_the_way_the_artboard_writes_it() { + // The artboard's own line reads `delivered in 1.2 s`. + assert_eq!(took_label(1234), "1.2 s"); + assert_eq!(took_label(1000), "1.0 s"); + // Under a second the seconds reading would be all zeroes, so say milliseconds. + assert_eq!(took_label(999), "999 ms"); + assert_eq!(took_label(0), "0 ms"); + } +} diff --git a/crates/dizey-web/tests/http.rs b/crates/dizey-web/tests/http.rs index 7c1bd3e..d0d85a7 100644 --- a/crates/dizey-web/tests/http.rs +++ b/crates/dizey-web/tests/http.rs @@ -901,7 +901,8 @@ async fn an_admin_sees_the_sender_and_never_a_password() { answer.body.contains( "\"sender\":{\"host\":\"smtp.fastmail.com\",\"port\":465,\ \"username\":\"dizey\",\"from_name\":\"Dizey\",\ - \"from_address\":\"dizey@dizey.sh\",\"password_set\":true}" + \"from_address\":\"dizey@dizey.sh\",\"password_set\":true,\ + \"test\":null}" ), "{}", answer.body @@ -1566,3 +1567,79 @@ async fn signing_out_leaves_every_other_session_alone() { .await; assert!(still.body.contains("administers"), "{}", still.body); } + +#[tokio::test] +async fn a_member_may_not_press_the_test_button() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let member = invited(&app, &admin_cookie, "emre@dizey.sh", "Emre", Role::Member).await; + + let answer = app + .post( + path::(), + Some(&member), + &[], + ) + .await; + + assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); + assert!(answer.body.contains("Forbidden"), "{}", answer.body); +} + +#[tokio::test] +async fn a_viewer_may_not_press_the_test_button() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let viewer = invited(&app, &admin_cookie, "pinar@dizey.sh", "Pinar", Role::Viewer).await; + + let answer = app + .post( + path::(), + Some(&viewer), + &[], + ) + .await; + + assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); + assert!(answer.body.contains("Forbidden"), "{}", answer.body); +} + +#[tokio::test] +async fn a_signed_out_browser_may_not_press_the_test_button() { + let app = App::open().await; + + let answer = app + .post(path::(), None, &[]) + .await; + + assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); + assert!(answer.body.contains("SignInFirst"), "{}", answer.body); +} + +#[tokio::test] +async fn testing_a_sender_that_was_never_filled_in_says_so_rather_than_sending() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + + let answer = app + .post( + path::(), + Some(&admin_cookie), + &[], + ) + .await; + + assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); + assert!(answer.body.contains("BadSender"), "{}", answer.body); + assert!(answer.body.contains("save it first"), "{}", answer.body); + + // Nothing was recorded either: the panel still has no test line to show. + let seen = app + .post( + path::(), + Some(&admin_cookie), + &[], + ) + .await; + assert!(!seen.body.contains("\"test\":{"), "{}", seen.body); +} diff --git a/style/main.scss b/style/main.scss index 8b30011..d54b88b 100644 --- a/style/main.scss +++ b/style/main.scss @@ -1572,12 +1572,23 @@ a { .panel-foot { display: flex; + // A foot inside a `.panel-body` would inherit that column, and a foot is a row. + flex-direction: row; align-items: center; gap: 12px; justify-content: flex-end; // A foot with something to say on the left and the button on the right. &-split { justify-content: space-between; } + +} + +// One end of a split foot: its own controls, kept together. +.foot-side { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; } // The quiet counterpart of `.primary`, for an action that is real but is not