diff --git a/crates/izlek-topcoat/src/settings.rs b/crates/izlek-topcoat/src/settings.rs index 1938635..e2137c0 100644 --- a/crates/izlek-topcoat/src/settings.rs +++ b/crates/izlek-topcoat/src/settings.rs @@ -1 +1,936 @@ -//! Lands in the page-port fan-out. +//! Settings, from the Settings and MemberSettings artboards. +//! +//! Which panels a person gets is decided on the server: the sender and the +//! limits belong to an admin, and a Member's answer simply does not carry +//! them — the page cannot hide what it was never sent. Every mutation here +//! checks the role again in its own handler, because a panel that is not +//! drawn is a courtesy and not a guard. +//! +//! Ported from `izlek-web/src/settings.rs`. That version reads through a +//! Leptos server fn behind a `Resource` and writes through `ServerAction`s +//! whose return value a hydrated page reads straight off; here the page is +//! rendered server-side on every request and a save is a plain form post, so +//! the answer — success or refusal — travels home the way `files.rs`'s +//! upload already does: appended to the redirect's query, in the same +//! `?refusal=&on=` shape `Refusal::code` was built for. +//! +//! `resend_link` differs from `izlek-web`'s in one respect: there it answered +//! a hydrated `ActionForm` with the mailed address directly. There is no +//! hydration here, so it redirects instead, carrying the address on the +//! query the same way a refusal does. + +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::content::Form; +use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, page, route}; +use topcoat::view::view; + +use izlek_core::store::{NewSender, SenderTest, User}; + +use crate::server::{Refusal, accounts, mail, require_admin, require_user}; + +/// The widest either limit may be set to. A ceiling of any size is a promise +/// the disk has to keep, and a limit typed with one extra zero is a mistake +/// nobody notices until the disk is full. +/// +/// `izlek-topcoat::files` carries its own copy until that lane imports this +/// one (per the settings lane's note there). +pub const WIDEST_ATTACHMENT_MB: u64 = 500; +pub const WIDEST_PHOTO_MB: u64 = 20; + +const MB: u64 = 1024 * 1024; + +/// `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. +fn took_label(ms: u64) -> String { + if ms >= 1000 { + format!("{:.1} s", ms as f64 / 1000.0) + } else { + format!("{ms} ms") + } +} + +/// 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. +fn is_address(raw: &str) -> bool { + let mut halves = raw.split('@'); + let (Some(local), Some(domain), None) = (halves.next(), halves.next(), halves.next()) else { + return false; + }; + !local.is_empty() + && domain.contains('.') + && !domain.starts_with('.') + && !domain.ends_with('.') + && !raw.contains(char::is_whitespace) +} + +/// The typed list as extensions, or `None` if one of them is not an +/// extension. +/// +/// Lowercased, dots dropped, duplicates dropped, and nothing but letters and +/// digits kept — a "type" with a slash or a dot in it would be a path or a +/// pattern wearing an extension's clothes, and this list is checked against a +/// filename later. +fn parse_types(raw: &str) -> Option> { + let mut types: Vec = Vec::new(); + for piece in raw.split([',', ' ', '\n']) { + let piece = piece.trim().trim_start_matches('.').to_lowercase(); + if piece.is_empty() { + continue; + } + if piece.len() > 12 || !piece.chars().all(|c| c.is_ascii_alphanumeric()) { + return None; + } + if !types.contains(&piece) { + types.push(piece); + } + } + Some(types) +} + +/// A query value survives the round trip to a `Location` header only if it +/// cannot be mistaken for another pair or break the header outright — a +/// mailed address may hold `+`, `&`, `=`, none of which a hand-built query +/// string may pass through raw. +fn encode_q(raw: &str) -> String { + let mut out = String::with_capacity(raw.len()); + for byte in raw.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(byte as char) + } + _ => out.push_str(&format!("%{byte:02X}")), + } + } + out +} + +fn decode_q(raw: &str) -> String { + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() { + if let Ok(value) = u8::from_str_radix(&raw[i + 1..i + 3], 16) { + out.push(value); + i += 3; + continue; + } + } + out.push(bytes[i]); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +#[cfg(test)] +mod codec_tests { + use super::{decode_q, encode_q, parse_types, took_label}; + + #[test] + fn an_address_survives_the_round_trip() { + for address in ["a@b.com", "a+tag@b.com", "a&b=c@b.com", "weird%chars@b.com"] { + assert_eq!(decode_q(&encode_q(address)), address); + } + } + + #[test] + fn a_list_is_lowercased_undotted_and_deduplicated() { + assert_eq!( + parse_types(".PNG, png, jpg").unwrap(), + vec!["png".to_string(), "jpg".to_string()] + ); + } + + #[test] + fn an_empty_list_means_every_type() { + assert_eq!(parse_types(" ").unwrap(), Vec::::new()); + } + + #[test] + fn nothing_that_is_not_an_extension_is_stored_as_one() { + assert!(parse_types("image/png").is_none()); + assert!(parse_types("../etc").is_none()); + assert!(parse_types("*").is_none()); + assert!(parse_types("tar.gz").is_none()); + } + + #[test] + fn a_send_is_timed_the_way_the_artboard_writes_it() { + assert_eq!(took_label(1234), "1.2 s"); + assert_eq!(took_label(1000), "1.0 s"); + assert_eq!(took_label(999), "999 ms"); + assert_eq!(took_label(0), "0 ms"); + } +} + +/// A 303 to `/settings`, with `query` appended. +fn redirect_to(query: &str) -> (StatusCode, HeaderMap, Vec) { + let mut headers = HeaderMap::new(); + let location = if query.is_empty() { "/settings".to_string() } else { format!("/settings?{query}") }; + if let Ok(value) = HeaderValue::from_str(&location) { + headers.insert(header::LOCATION, value); + } + (StatusCode::SEE_OTHER, headers, Vec::new()) +} + +/// Where a save lands: back on Settings, with the refusal (if any) on the +/// query the same way `files.rs`'s upload carries one, or `saved=` +/// when there was nothing to refuse. +fn saved_or_refused(call: &str, refusal: Option) -> (StatusCode, HeaderMap, Vec) { + match refusal { + Some(refusal) => redirect_to(&format!("refusal={}&on={call}", refusal.code())), + None => redirect_to(&format!("saved={call}")), + } +} + +// --------------------------------------------------------------------------- +// Routes +// --------------------------------------------------------------------------- + +#[derive(serde::Deserialize)] +struct SaveLimitsForm { + attachment_limit_mb: u64, + photo_limit_mb: u64, + allowed_file_types: String, +} + +/// Changes the workspace's limits. Admin-only, checked here. +/// +/// The list is parsed rather than trusted: it is what a later upload is +/// checked against, so a type that is not a plain extension has no business +/// being stored as one. +#[route(POST "/api/save_limits")] +async fn save_limits(cx: &Cx, Form(input): Form) -> Result<(StatusCode, HeaderMap, Vec)> { + let admin = match require_admin(cx).await { + Ok(admin) => admin, + Err(refusal) => return Ok(saved_or_refused("save_limits", Some(refusal))), + }; + if input.attachment_limit_mb == 0 + || input.photo_limit_mb == 0 + || input.attachment_limit_mb > WIDEST_ATTACHMENT_MB + || input.photo_limit_mb > WIDEST_PHOTO_MB + { + return Ok(saved_or_refused("save_limits", Some(Refusal::BadLimit))); + } + let Some(types) = parse_types(&input.allowed_file_types) else { + return Ok(saved_or_refused("save_limits", Some(Refusal::BadFileType))); + }; + let outcome = accounts(cx) + .store() + .set_limits( + &admin.workspace_id, + input.attachment_limit_mb * MB, + input.photo_limit_mb * MB, + &types, + ) + .await; + let refusal = match outcome { + Ok(()) => None, + Err(problem) => { + eprintln!("store error: {problem}"); + Some(Refusal::Unavailable) + } + }; + Ok(saved_or_refused("save_limits", refusal)) +} + +#[derive(serde::Deserialize)] +struct SaveSenderForm { + host: String, + port: u32, + username: String, + #[serde(default)] + password: String, + from_name: String, + from_address: String, +} + +/// Writes the workspace's sender. Admin-only, checked here. +/// +/// `password` is empty when the admin did not type one, and empty means +/// "leave the stored one alone" rather than "delete it": the field is +/// write-only, so the form has nothing to send back for a password that +/// already exists, and a save that took the blank literally would stop the +/// workspace sending mail as a side effect of fixing a typo in the port. +/// +/// A sender with no password at all is refused rather than stored, because a +/// half-filled sender is not a configuration — it is a mail nobody receives +/// and a ledger nobody reads. +#[route(POST "/api/save_sender")] +async fn save_sender(cx: &Cx, Form(input): Form) -> Result<(StatusCode, HeaderMap, Vec)> { + let admin = match require_admin(cx).await { + Ok(admin) => admin, + Err(refusal) => return Ok(saved_or_refused("save_sender", Some(refusal))), + }; + + let host = input.host.trim().to_string(); + let username = input.username.trim().to_string(); + let from_name = input.from_name.trim().to_string(); + let from_address = input.from_address.trim().to_string(); + // Not typed is not the same as blanked. Nothing here can clear a stored + // password; replacing it means typing a new one. + let password = (!input.password.is_empty()).then_some(input.password); + + let store = accounts(cx).store().clone(); + let known = store + .workspace() + .await? + .map(|ws| ws.smtp_password_set) + .unwrap_or(false); + + let complaint = if host.is_empty() { + Some("Give the SMTP host.") + } else if host.contains(char::is_whitespace) || host.contains('@') || host.contains('/') { + Some("The SMTP host is a host name, not an address or a URL.") + } else if !(1..=65535).contains(&input.port) { + Some("A port is a number between 1 and 65535.") + } else if username.is_empty() { + Some("Give the SMTP username.") + } else if password.is_none() && !known { + Some("A password is needed the first time.") + } else if !is_address(&from_address) { + Some("That is not a from-address.") + } else { + None + }; + if let Some(problem) = complaint { + return Ok(saved_or_refused( + "save_sender", + Some(Refusal::BadSender(problem.to_string())), + )); + } + + let outcome = store + .set_sender( + &admin.workspace_id, + NewSender { + host, + port: input.port, + username, + password, + from_name, + from_address, + }, + ) + .await; + let refusal = match outcome { + Ok(()) => None, + Err(problem) => { + eprintln!("store error: {problem}"); + Some(Refusal::Unavailable) + } + }; + Ok(saved_or_refused("save_sender", refusal)) +} + +/// 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 Izlek mail a +/// stranger on demand, which is a thing worth not building. +#[route(POST "/api/send_test_mail")] +async fn send_test_mail(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec)> { + let admin = match require_admin(cx).await { + Ok(admin) => admin, + Err(refusal) => return Ok(saved_or_refused("send_test_mail", Some(refusal))), + }; + + let store = accounts(cx).store().clone(); + let configured = store + .workspace() + .await? + .is_some_and(|ws| ws.smtp_password_set && ws.smtp_host.is_some()); + if !configured { + return Ok(saved_or_refused( + "send_test_mail", + Some(Refusal::BadSender( + "Fill the sender in and save it first — there is nothing to test yet.".to_string(), + )), + )); + } + + let Some(outcome) = mail(cx).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(saved_or_refused("send_test_mail", 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(saved_or_refused("send_test_mail", Some(Refusal::Unavailable))); + } + Ok(saved_or_refused("send_test_mail", None)) +} + +#[derive(serde::Deserialize)] +struct SaveProfileForm { + display_name: String, +} + +/// Renames the person asking. Nobody renames anybody else here: the id comes +/// from the session, never from the form. +#[route(POST "/api/save_profile")] +async fn save_profile(cx: &Cx, Form(input): Form) -> Result<(StatusCode, HeaderMap, Vec)> { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return Ok(saved_or_refused("save_profile", Some(refusal))), + }; + let display_name = input.display_name.trim().to_string(); + if display_name.is_empty() { + return Ok(saved_or_refused("save_profile", Some(Refusal::EmptyName))); + } + let outcome = accounts(cx) + .store() + .set_profile(&user.id, &display_name, user.photo_path.as_deref()) + .await; + let refusal = match outcome { + Ok(()) => None, + Err(problem) => { + eprintln!("store error: {problem}"); + Some(Refusal::Unavailable) + } + }; + Ok(saved_or_refused("save_profile", refusal)) +} + +#[derive(serde::Deserialize)] +struct ResendLinkForm { + user_id: String, +} + +/// Sends the same person another first-sign-in link by mail. Admin-only, +/// checked here. +/// +/// There is no hydrated action here to read a return value off of, so the +/// mailed address travels home on the redirect's query, the same way a +/// refusal does. +#[route(POST "/api/resend_link")] +async fn resend_link(cx: &Cx, Form(input): Form) -> Result<(StatusCode, HeaderMap, Vec)> { + let admin = match require_admin(cx).await { + Ok(admin) => admin, + Err(refusal) => return Ok(saved_or_refused("resend_link", Some(refusal))), + }; + match accounts(cx).resend_invitation(&admin, &input.user_id).await { + Ok(invitation) => { + mail(cx).after_invite(); + Ok(redirect_to(&format!("mailed={}", encode_q(&invitation.user.email)))) + } + Err(error) => Ok(saved_or_refused("resend_link", Some(error.into()))), + } +} + +// --------------------------------------------------------------------------- +// Page +// --------------------------------------------------------------------------- + +/// One row of the member list, as an admin may see it. There is no password +/// and no token here: whether a password exists is a fact about the account, +/// and the token of a live link is shown once at the moment it is minted and +/// is never readable afterwards — the store keeps only its hash. +struct Member { + id: String, + display_name: String, + email: String, + role: izlek_core::Role, + has_password: bool, + /// The day they last signed in, as the list writes it, or nothing. + last_signed_in: Option, + is_you: bool, + /// The first account. It administers the workspace and cannot be + /// removed. + is_owner: bool, +} + +async fn members_now(cx: &Cx, asking: &User) -> Result> { + let store = accounts(cx).store().clone(); + let owner = store.owner().await?.map(|owner| owner.id); + let users = store.users(&asking.workspace_id).await?; + Ok(users + .into_iter() + .map(|user| Member { + has_password: user.password_hash.is_some(), + last_signed_in: user.last_signed_in_at.map(|at| izlek_core::board::day_label(at.date())), + is_you: user.id == asking.id, + is_owner: owner.as_deref() == Some(user.id.as_str()), + id: user.id, + display_name: user.display_name, + email: user.email, + role: user.role, + }) + .collect()) +} + +async fn limits_now(cx: &Cx, workspace_id: &str) -> Result<(u64, u64, Vec)> { + let workspace = accounts(cx) + .store() + .workspace() + .await? + .filter(|workspace| workspace.id == workspace_id) + .ok_or_else(|| topcoat::Error::from(std::io::Error::other("no workspace")))?; + Ok(( + workspace.attachment_limit_bytes / MB, + workspace.photo_limit_bytes / MB, + workspace.allowed_file_types, + )) +} + +/// What the row under the test button says, once the workspace holds a +/// `sender_test` to read. +struct TestResult { + moment: String, + took: Option, + error: Option, +} + +/// The sender as the admin's screen may see it, plus the last test's +/// outcome — persisted, so it survives the reload the redirect gives it +/// rather than living only in this request's memory. +struct Sender { + host: String, + port: u16, + username: String, + from_name: String, + from_address: String, + password_set: bool, + test: Option, +} + +impl Sender { + fn is_connected(&self) -> bool { + !self.host.trim().is_empty() + && !self.username.trim().is_empty() + && !self.from_address.trim().is_empty() + && self.password_set + } +} + +async fn sender_now(cx: &Cx) -> Result { + let workspace = accounts(cx).store().workspace().await?; + Ok(match workspace { + None => Sender { + host: String::new(), + port: 587, + username: String::new(), + from_name: String::new(), + from_address: String::new(), + password_set: false, + test: None, + }, + Some(workspace) => Sender { + host: workspace.smtp_host.unwrap_or_default(), + port: workspace.smtp_port.and_then(|p| u16::try_from(p).ok()).unwrap_or(587), + username: workspace.smtp_username.unwrap_or_default(), + from_name: workspace.smtp_from_name.unwrap_or_default(), + from_address: workspace.smtp_from_address.unwrap_or_default(), + password_set: workspace.smtp_password_set, + test: workspace.sender_test.map(|test| TestResult { + moment: izlek_core::detail::moment_label(test.at), + took: test.error.is_none().then(|| took_label(test.took_ms)), + error: test.error, + }), + }, + }) +} + +/// The refusal that landed on this call's redirect, if any, and this call's +/// own `saved=` flag. +fn call_state<'q>(query: &'q str, call: &str) -> (Option, bool) { + let mut refusal_code = None; + let mut on = None; + let mut saved = false; + for pair in query.split('&') { + let Some((key, value)) = pair.split_once('=') else { continue }; + match key { + "refusal" => refusal_code = Some(value), + "on" => on = Some(value), + "saved" if value == call => saved = true, + _ => {} + } + } + let refusal = if on == Some(call) { refusal_code.and_then(Refusal::from_code) } else { None }; + (refusal, saved) +} + +fn query_value<'q>(query: &'q str, key: &str) -> Option<&'q str> { + query.split('&').find_map(|pair| pair.split_once('=').filter(|(k, _)| *k == key).map(|(_, v)| v)) +} + +/// The settings screen. +#[page("/settings")] +async fn settings_page(cx: &Cx) -> Result { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => { + return view! { + cx => +
+

(refusal.message())

+

"Back to the board"

+
+ }; + } + }; + let administers = user.role.can_administer(); + let query = topcoat::router::request::uri(cx).query().unwrap_or(""); + + let sender = if administers { Some(sender_now(cx).await?) } else { None }; + let (limits, allowed_types) = if administers { + let (attachment, photo, types) = limits_now(cx, &user.workspace_id).await?; + (Some((attachment, photo)), types) + } else { + (None, Vec::new()) + }; + let members = if administers { Some(members_now(cx, &user).await?) } else { None }; + + let (profile_refusal, profile_saved) = call_state(query, "save_profile"); + let (sender_refusal, sender_saved) = call_state(query, "save_sender"); + let (test_refusal, _) = call_state(query, "send_test_mail"); + let (limits_refusal, limits_saved) = call_state(query, "save_limits"); + let (member_refusal, _) = call_state(query, "resend_link"); + let mailed = query_value(query, "mailed").map(decode_q); + + view! { + cx => +
+
+ "izlek" + +
+
+ "Settings" +
+ (user.display_name.clone()) +
+ +
+ + +
+
+

"Settings"

+ (user.role.as_str().to_string()) +
+ +
+
+

"Your profile"

+
+
+ + +
+ if let Some(refusal) = &profile_refusal { + (refusal.message()) + } + if profile_saved { + "Saved." + } + +
+
+
+
+ +
+
+
+ + if let Some(sender) = &sender { + let connected = sender.is_connected(); + let password_set = sender.password_set; +
+
+

"Outgoing mail"

+ "Admin only" + if connected { + "Connected" + } else { + "Not configured" + } +
+
+ if !connected { +

"Not connected — mail queues until you save."

+ } +
+
+ + +
+ + +
+ + +
+
+
+
+
+ +
+ match (&test_refusal, &sender.test) { + (Some(refusal), _) => (refusal.message()), + (None, Some(result)) => match (&result.error, &result.took) { + (Some(problem), _) => (format!("not delivered, {} — {problem}", result.moment)), + (None, Some(took)) => (format!("delivered in {took} — {}", result.moment)), + (None, None) => "", + }, + (None, None) => "", + } +
+
+ if let Some(refusal) = &sender_refusal { + (refusal.message()) + } + if sender_saved { + "Saved." + } + +
+
+
+
+ } + + if let Some((attachment_limit_mb, photo_limit_mb)) = limits { +
+
+

"Workspace limits"

+ "Admin only" +
+
+
+ + +
+ +

"A lower limit never touches files already uploaded."

+
+ if let Some(refusal) = &limits_refusal { + (refusal.message()) + } + if limits_saved { + "Saved." + } + +
+
+
+ } + + if let Some(members) = members { +
+
+

"Members"

+ "Admin only" +
+
+ + + + + + + + + + + for member in members { + let account = if member.is_owner { + "owner".to_string() + } else if !member.has_password { + "invited".to_string() + } else if let Some(day) = member.last_signed_in.clone() { + format!("last seen {day}") + } else { + "active".to_string() + }; + + + + + + + } + +
"NAME""ADDRESS""ROLE""ACCOUNT"
+ (member.display_name.clone()) + if member.is_you { + "you" + } + (member.email.clone())(member.role.as_str().to_string())
+ + // `/api/invite_member` (auth.rs) answers a caller + // with script, not this post, so a submit here + // lands on its bare JSON rather than back on this + // page. + // corner-cut: no "Mailed to {address}" after + // Add member, ceiling = give invite_member the + // same redirect-carried answer `resend_link` + // above uses, in a slice that may touch auth.rs. +
+ + + + +
+ + if let Some(refusal) = &member_refusal { +

(refusal.message())

+ } + if let Some(address) = &mailed { +

(format!("Mailed to {address}"))

+ } + +
+

"Admin"" — sender, limits, members."

+

"Member"" — board and rule mail."

+

"Viewer"" — read and export only."

+
+
+
+ } +
+
+ } +}