diff --git a/crates/izlek-core/src/accounts.rs b/crates/izlek-core/src/accounts.rs index a79e07f..5b54d27 100644 --- a/crates/izlek-core/src/accounts.rs +++ b/crates/izlek-core/src/accounts.rs @@ -405,6 +405,13 @@ impl Accounts { if !ok { return Err(AccountError::Rejected); } + // Setting the password back to itself is the walk-away mistake, not + // a change: refused by name, and nothing here signs anybody out. + if let Some(stored) = user.password_hash.as_deref() { + if verify_password(new, stored) { + return Err(AccountError::Password(auth::PasswordProblem::IsCurrent)); + } + } auth::check_password(new, &user.email, &user.display_name)?; let hash = hash_password(new)?; self.store.set_password_hash(&user.id, &hash).await?; diff --git a/crates/izlek-core/src/auth.rs b/crates/izlek-core/src/auth.rs index f18c7e7..ded5444 100644 --- a/crates/izlek-core/src/auth.rs +++ b/crates/izlek-core/src/auth.rs @@ -13,6 +13,7 @@ use argon2::password_hash::phc::PasswordHash; use argon2::password_hash::{PasswordHasher, PasswordVerifier}; use argon2::{Algorithm, Argon2, Params, Version}; use rand::Rng; +use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq; @@ -34,12 +35,16 @@ pub const MIN_PASSWORD_CHARS: usize = 10; /// A password rule the person's choice broke. The wording is the wording on the /// first-sign-in screen. -#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)] pub enum PasswordProblem { #[error("at least 10 characters")] TooShort, #[error("not your address or your name")] LooksLikeYou, + /// The "new" password is the one already in force — the walk-away + /// mistake, refused by name rather than silently succeeding. + #[error("that's your current password")] + IsCurrent, } #[derive(Debug, thiserror::Error)] diff --git a/crates/izlek-core/src/detail.rs b/crates/izlek-core/src/detail.rs index 5db45c4..4d7d21f 100644 --- a/crates/izlek-core/src/detail.rs +++ b/crates/izlek-core/src/detail.rs @@ -340,8 +340,13 @@ impl ActivityEntry { | ActivityKind::RuleEdited | ActivityKind::RuleToggled | ActivityKind::RuleDeleted - | ActivityKind::MessageSent - | ActivityKind::Other(_) => detail.to_string(), + | ActivityKind::MessageSent => detail.to_string(), + ActivityKind::Other(raw) => match raw.as_str() { + // A kind this version knows gets its words; anything a newer + // version wrote falls through as the raw detail it stored. + "tagged" => format!("tagged it {detail}"), + _ => detail.to_string(), + }, } } diff --git a/crates/izlek-core/src/mail.rs b/crates/izlek-core/src/mail.rs index d6d31d7..2df8214 100644 --- a/crates/izlek-core/src/mail.rs +++ b/crates/izlek-core/src/mail.rs @@ -1106,7 +1106,8 @@ mod backoff_tests { #[cfg(test)] mod trigger_fold_tests { use super::fires_on; - use crate::detail::{ActivityKind, Trigger}; + use crate::detail::ActivityKind; + use crate::store::Trigger; #[test] fn a_time_change_fires_the_deadline_triggers() { diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index 995611c..21fe3b9 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -332,7 +332,10 @@ impl TursoStore { /// wrong more often — a reminder row is a promise the queue is holding, /// and a promise whose grounds moved is re-made, not patched. Rows that /// already went out (or failed on their own retry clock) are history and - /// stay untouched. + /// stay untouched — and stay served: a recipient this task's reminders + /// have already been written for is never minted a second row, or every + /// later write about the card would quietly re-queue a mail they have + /// already had, one copy per write. /// /// Answers whether anything was written or abandoned, so the caller can /// announce the queue only when this did something — the task-write @@ -343,11 +346,36 @@ impl TursoStore { task_id: &str, now: OffsetDateTime, ) -> Result { + // Who this task's reminders have already served: a row that went + // out (`sent`), is riding its own retries (`failed`), or was given + // up on by that same retry ladder (`abandoned` with attempts on the + // clock) settles that recipient's reminder. A draft the re-derive + // itself abandoned has attempts 0 and serves nobody — the promise it + // stood for is unkept, and the mint below owes it fresh. Read before + // the abandon below, in the same transaction: a row still pending + // here is an unkept promise, and the moment it counts as served it + // would be silenced forever. + let mut rows = tx + .query( + "SELECT DISTINCT recipient FROM mail_send \ + WHERE task_id = ?1 AND kind = 'reminder' \ + AND (state IN ('sent', 'failed') \ + OR (state = 'abandoned' AND attempts > 0))", + params![task_id], + ) + .await + .map_err(backend)?; + let mut served = std::collections::HashSet::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + served.insert(text(&row, 0)?); + } + drop(rows); + // Nothing the re-derivation below can say changes a row that is no // longer pending. let abandoned = tx .execute( - "UPDATE mail_send SET state = 'abandoned' \ + "UPDATE mail_send SET state = 'abandoned', next_attempt_at = NULL \ WHERE task_id = ?1 AND kind = 'reminder' AND state = 'pending'", params![task_id], ) @@ -417,7 +445,13 @@ impl TursoStore { } drop(rows); + let mut minted = 0usize; for (email, timezone) in people { + // Already reminded of this meeting, or their reminder is on the + // queue's own retry clock: a second row here is a second mail. + if served.contains(&email) { + continue; + } // Each recipient reads the moment in their own stored timezone: // the meeting is one fact, and what it says on the clock where // they sit is not. @@ -452,9 +486,10 @@ impl TursoStore { ) .await .map_err(backend)?; + minted += 1; } - Ok(true) + Ok(abandoned > 0 || minted > 0) } } diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index 258d8cc..1faed1d 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -2309,6 +2309,30 @@ async fn changing_a_password_needs_the_current_one_and_obeys_the_rules() { .unwrap(); } +#[tokio::test] +async fn the_old_password_stops_working_after_a_change() { + let (_scratch, accounts, admin) = claimed().await; + accounts + .change_password( + &admin.id, + "tide-tables-1892", + "chronometer-1761", + "198.51.100.7", + ) + .await + .unwrap(); + assert!(matches!( + accounts + .sign_in("ada@izlek.sh", "tide-tables-1892", "198.51.100.7") + .await, + Err(AccountError::Rejected) + )); + accounts + .sign_in("ada@izlek.sh", "chronometer-1761", "198.51.100.7") + .await + .unwrap(); +} + #[tokio::test] async fn signing_out_ends_that_browser_only() { let (_scratch, accounts, _admin) = claimed().await; @@ -8348,3 +8372,174 @@ async fn reminder_rows_survive_a_reopen() { assert_eq!(after[0].next_attempt_at, before[0].next_attempt_at); let _ = std::fs::remove_dir_all(&dir); } +#[tokio::test] +async fn a_reminder_already_sent_is_never_queued_again() { + let (dir, store, workspace, admin) = shared().await; + let grace = member(&store, &workspace, "grace@izlek.sh", "Grace").await; + let emre = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let clock = OffsetDateTime::now_utc() + Duration::hours(2); + let task = clocked_task(&store, &workspace, &admin, Some(clock)).await; + store.assign_task(&task, &grace).await.unwrap(); + store.assign_task(&task, &emre).await.unwrap(); + + let mailer = Remembering::taking_everything(); + let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + // The meeting is 15 minutes out from due, so a pass anywhere after that + // delivers both reminders. + let later = clock - Duration::minutes(14); + assert_eq!(engine.deliver_owed(later, 10).await.unwrap().sent, 2); + + // Any later write about the card re-derives the reminders. The two who + // were reminded keep the rows that went out; nobody is minted a second. + let yusuf = member(&store, &workspace, "yusuf@izlek.sh", "Yusuf").await; + store.assign_task(&task, &yusuf).await.unwrap(); + let rows = reminders(&store, &task).await; + let yusuf_rows: Vec<_> = rows + .iter() + .filter(|r| r.recipient == "yusuf@izlek.sh") + .collect(); + assert_eq!(yusuf_rows.len(), 1, "the newcomer has one row: {rows:?}"); + let served: Vec<_> = rows + .iter() + .filter(|r| r.recipient != "yusuf@izlek.sh") + .collect(); + assert!( + served.iter().all(|r| r.state != SendState::Pending), + "nobody served is owed again: {served:?}" + ); + for person in ["grace@izlek.sh", "emre@izlek.sh"] { + assert_eq!( + served + .iter() + .filter(|r| r.recipient == person && r.state == SendState::Sent) + .count(), + 1, + "{person} was delivered exactly once: {served:?}" + ); + } + let pending = pending_reminders(&store, &task).await; + assert_eq!(pending.len(), 1, "only the newcomer is owed: {pending:?}"); + assert_eq!(pending[0].recipient, "yusuf@izlek.sh"); + + // And the queue itself repeats nothing: sweep after sweep re-delivers + // nobody, whatever the writes in between did. Taking Yusuf off the card + // and putting him back is a write pair every round — the sync his + // reminder rides abandons and re-derives each time. + for _ in 0..3 { + engine + .deliver_owed(later + Duration::minutes(1), 10) + .await + .unwrap(); + store.unassign_task(&task, &yusuf).await.unwrap(); + store.assign_task(&task, &yusuf).await.unwrap(); + } + assert_eq!(mailer.sent().len(), 3, "{:?}", mailer.sent()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn a_reminder_failing_on_retries_is_not_minted_twice() { + let (dir, store, workspace, admin) = shared().await; + let grace = member(&store, &workspace, "grace@izlek.sh", "Grace").await; + let clock = OffsetDateTime::now_utc() + Duration::hours(2); + let task = clocked_task(&store, &workspace, &admin, Some(clock)).await; + store.assign_task(&task, &grace).await.unwrap(); + + let mailer = Remembering::refusing(vec![MailError::retryable("host is down")]); + let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + let later = clock - Duration::minutes(14); + assert_eq!(engine.deliver_owed(later, 10).await.unwrap().failed, 1); + + // The write between the sweeps finds Grace's reminder riding its own + // retry clock, and leaves it exactly one row. + let emre = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + store.assign_task(&task, &emre).await.unwrap(); + let rows = reminders(&store, &task).await; + assert_eq!(rows.len(), 2, "one row per person: {rows:?}"); + let grace_row = rows.iter().find(|r| r.recipient == "grace@izlek.sh").unwrap(); + assert_eq!(grace_row.state, SendState::Failed); + assert_eq!(grace_row.attempts, 1); + + // When the host comes back the retry lands once — not once per row. + engine + .deliver_owed(later + backoff(1) + Duration::minutes(1), 10) + .await + .unwrap(); + let grace_mail = mailer + .sent() + .iter() + .filter(|m| m.to == "grace@izlek.sh") + .count(); + assert_eq!(grace_mail, 1, "{:?}", mailer.sent()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn the_reminder_never_lands_at_or_after_the_deadline() { + let (dir, store, workspace, admin) = shared().await; + // A meeting comfortably ahead: the lead decides the moment. + let clock = OffsetDateTime::now_utc() + Duration::hours(2); + let task = clocked_task(&store, &workspace, &admin, Some(clock)).await; + store + .assign_task(&task, &member(&store, &workspace, "grace@izlek.sh", "Grace").await) + .await + .unwrap(); + let rows = reminders(&store, &task).await; + assert_eq!(rows.len(), 1); + let due = rows[0].next_attempt_at.unwrap(); + assert!( + due < clock, + "the reminder fires {:#?} before the clock", + clock - due + ); + assert_eq!(due, clock - Duration::minutes(15)); + + // A meeting already inside the window: the warning commits now, which is + // still before the clock. + let soon = OffsetDateTime::now_utc() + Duration::minutes(10); + let task = clocked_task(&store, &workspace, &admin, Some(soon)).await; + store + .assign_task(&task, &member(&store, &workspace, "emre@izlek.sh", "Emre").await) + .await + .unwrap(); + let rows = reminders(&store, &task).await; + assert_eq!(rows.len(), 1); + let due = rows[0].next_attempt_at.unwrap(); + assert!(due < soon, "due {due} at or after the clock {soon}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Setting the password back to what it already is is refused by name, and a +/// refused change leaves every session — and the old password — standing. +#[tokio::test] +async fn a_change_back_to_the_same_password_is_refused_and_signs_nobody_out() { + let (_scratch, accounts, admin) = claimed().await; + // A second browser holds a session the refused change must not touch. + let other = accounts + .sign_in("ada@izlek.sh", "tide-tables-1892", "198.51.100.8") + .await + .unwrap(); + assert!(matches!( + accounts + .change_password( + &admin.id, + "tide-tables-1892", + "tide-tables-1892", + "198.51.100.7" + ) + .await, + Err(AccountError::Password(PasswordProblem::IsCurrent)) + )); + // The other browser is still signed in, and the old password still works. + assert!( + accounts + .authenticate(other.session_token.expose()) + .await + .unwrap() + .is_some() + ); + accounts + .sign_in("ada@izlek.sh", "tide-tables-1892", "198.51.100.7") + .await + .unwrap(); +} diff --git a/crates/izlek-web/src/auth.rs b/crates/izlek-web/src/auth.rs index 361b128..3a95d59 100644 --- a/crates/izlek-web/src/auth.rs +++ b/crates/izlek-web/src/auth.rs @@ -250,7 +250,15 @@ async fn change_password(cx: &Cx, Form(input): Form) -> Redi time::OffsetDateTime::now_utc(), ) .await; - redirect(cx, None) + // The pane says so itself: `saved=change_password` asks for the + // note, with the other-devices fact in it. + let back = back_to(cx, "/"); + let sep = if back.contains('?') { "&" } else { "?" }; + Ok(( + StatusCode::SEE_OTHER, + [(header::LOCATION, format!("{back}{sep}saved=change_password"))], + Json(None), + )) } Err(error) => redirect(cx, Some(error.into())), } diff --git a/crates/izlek-web/src/detail.rs b/crates/izlek-web/src/detail.rs index 8022353..2d82a48 100644 --- a/crates/izlek-web/src/detail.rs +++ b/crates/izlek-web/src/detail.rs @@ -620,9 +620,9 @@ struct SetTaskTagForm { } /// Files a task under a tag. A Viewer can read tags but not set them; the -/// tag has to be this workspace board's own. No activity is recorded and no -/// mail follows — re-labeling a card is not a thing anybody needs told -/// about. +/// tag has to be this workspace board's own. The relabeling lands on the +/// task's own trail and the workspace feed; no rule mails about it, since no +/// trigger matches a tag. #[route(POST "/api/set_task_tag")] async fn set_task_tag(cx: &Cx, Form(input): Form) -> Redirect { let (actor, _) = match writer_and_task(cx, &input.task_id).await { @@ -634,10 +634,20 @@ async fn set_task_tag(cx: &Cx, Form(input): Form) -> Redirect { return redirect(cx, Some(Refusal::Unavailable)); }; let tags = store.tags(&board.id).await?; - if !tags.iter().any(|tag| tag.id == input.tag_id) { + let Some(tag) = tags.iter().find(|tag| tag.id == input.tag_id) else { return redirect(cx, Some(Refusal::NotFound)); - } + }; store.set_task_tag(&input.task_id, &input.tag_id).await?; + let _ = store + .record_activity( + &input.task_id, + Some(&actor.id), + None, + &izlek_core::detail::ActivityKind::Other("tagged".to_string()), + &tag.name, + time::OffsetDateTime::now_utc(), + ) + .await; redirect(cx, None) } @@ -1270,7 +1280,12 @@ async fn description_control(cx: &Cx, task: &TaskDetail, may_write: bool, lang: /// The grid now autosubmits, the way the log filters already did, and /// closing is what Escape and a click outside are for. The time rides the /// same commit: a posted form carries whatever is typed, so `16:20` plus a -/// pressed day is one exact moment, and Clear empties both. +/// pressed day is one exact moment, and Clear empties both. A time the day +/// can already carry commits by itself — the two boxes submit when they +/// agree (both set or both emptied) and the input holds a day, because a +/// lone box is a half-written value, not a moment, and a time with no day +/// anywhere is not one either. On a dayless task the picks wait for the +/// pressed day and ride its commit. /// /// The box speaks the moment when there is one, the day when there is only /// a day — the clock's day is always the deadline's, and the label reads in @@ -1466,6 +1481,18 @@ pub(crate) async fn datepicker_script(cx: &Cx, lang: Lang) -> Result { var panel = toggle.closest('.datepick-pop').querySelector('.datepick-panel');\ if (panel) {{ render(panel); }}\ }});\ + document.addEventListener('change', function(e) {{\ + var box = e.target;\ + if (!box.matches || !box.matches('.datepick-time select')) {{ return; }}\ + var panel = box.closest('.datepick-panel');\ + var input = panel && panel.querySelector('.datepick-input');\ + if (!input || !input.hasAttribute('data-autosubmit') || !input.value) {{ return; }}\ + var hour = panel.querySelector('[name=clock_hour]');\ + var minute = panel.querySelector('[name=clock_minute]');\ + if (!hour || !minute) {{ return; }}\ + if (!!hour.value !== !!minute.value) {{ return; }}\ + if (input.form) {{ input.form.requestSubmit(); }}\ + }});\ document.addEventListener('izlek:wire', function () {{\ document.querySelectorAll('.datepick-pop').forEach(function (pop) {{\ var panel = pop.querySelector('.datepick-panel');\ diff --git a/crates/izlek-web/src/i18n.rs b/crates/izlek-web/src/i18n.rs index 9b80abd..cb818ad 100644 --- a/crates/izlek-web/src/i18n.rs +++ b/crates/izlek-web/src/i18n.rs @@ -299,6 +299,15 @@ pub enum Key { ActLimitsSaved, ActTestMailSent, ActMessageSent, + ActSendRetried, + ActPhotoSaved, + ActPhotoRemoved, + ActSenderChecked, + PWCurrentWrong, + PWIsCurrent, + PWTooShort, + PWLooksLikeYou, + PasswordSaved, UnblockedWord, AColumn, AudienceEmpty, @@ -900,6 +909,24 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (ActTestMailSent, Tr) => "test postası gönderdi", (ActMessageSent, En) => "sent a message", (ActMessageSent, Tr) => "mesaj gönderdi", + (ActSendRetried, En) => "retried a send", + (ActSendRetried, Tr) => "bir gönderimi yeniden denedi", + (ActPhotoSaved, En) => "saved the profile photo", + (ActPhotoSaved, Tr) => "profil fotoğrafını kaydetti", + (ActPhotoRemoved, En) => "removed the profile photo", + (ActPhotoRemoved, Tr) => "profil fotoğrafını kaldırdı", + (ActSenderChecked, En) => "checked the mail server", + (ActSenderChecked, Tr) => "posta sunucusunu denetledi", + (PWCurrentWrong, En) => "The current password is wrong.", + (PWCurrentWrong, Tr) => "Mevcut parola yanlış.", + (PWIsCurrent, En) => "That's your current password.", + (PWIsCurrent, Tr) => "Bu zaten mevcut parolan.", + (PWTooShort, En) => "At least 10 characters.", + (PWTooShort, Tr) => "En az 10 karakter.", + (PWLooksLikeYou, En) => "Not your address or your name.", + (PWLooksLikeYou, Tr) => "Adresin ya da adın değil.", + (PasswordSaved, En) => "Password changed. Your other devices were signed out.", + (PasswordSaved, Tr) => "Parola değişti. Diğer cihazlarının oturumu kapatıldı.", (UnblockedWord, En) => "unblocked", (UnblockedWord, Tr) => "engeli kaldırıldı", (AColumn, En) => "a column", @@ -1238,6 +1265,41 @@ pub fn rule_deleted_label(lang: Lang, detail: &str) -> String { } } +pub fn tagged_label(lang: Lang, detail: &str) -> String { + match lang { + Lang::En => format!("tagged it {detail}"), + Lang::Tr => format!("{detail} ile etiketledi"), + } +} + +pub fn tag_created_label(lang: Lang, detail: &str) -> String { + match lang { + Lang::En => format!("created the tag {detail}"), + Lang::Tr => format!("{detail} etiketini oluşturdu"), + } +} + +pub fn tag_renamed_label(lang: Lang, detail: &str) -> String { + match lang { + Lang::En => format!("renamed the tag {detail}"), + Lang::Tr => format!("{detail} etiketini yeniden adlandırdı"), + } +} + +pub fn tag_deleted_label(lang: Lang, detail: &str) -> String { + match lang { + Lang::En => format!("deleted the tag {detail}"), + Lang::Tr => format!("{detail} etiketini sildi"), + } +} + +pub fn tag_moved_label(lang: Lang, detail: &str) -> String { + match lang { + Lang::En => format!("moved the tag {detail}"), + Lang::Tr => format!("{detail} etiketini taşıdı"), + } +} + pub fn file_added_label(lang: Lang, detail: &str) -> String { match lang { Lang::En => format!("added {detail}"), @@ -1313,6 +1375,24 @@ pub fn activity_kind_word(lang: Lang, kind: &str) -> String { ("deleted", Lang::Tr) => "silindi".to_string(), ("commented", Lang::En) => "commented".to_string(), ("commented", Lang::Tr) => "yorum yapıldı".to_string(), + ("tagged", Lang::En) => "tagged".to_string(), + ("tagged", Lang::Tr) => "etiketlendi".to_string(), + ("tag_created", Lang::En) => "tag created".to_string(), + ("tag_created", Lang::Tr) => "etiket oluşturuldu".to_string(), + ("tag_renamed", Lang::En) => "tag renamed".to_string(), + ("tag_renamed", Lang::Tr) => "etiket yeniden adlandırıldı".to_string(), + ("tag_deleted", Lang::En) => "tag deleted".to_string(), + ("tag_deleted", Lang::Tr) => "etiket silindi".to_string(), + ("tag_moved", Lang::En) => "tag moved".to_string(), + ("tag_moved", Lang::Tr) => "etiket taşındı".to_string(), + ("send_retried", Lang::En) => "send retried".to_string(), + ("send_retried", Lang::Tr) => "gönderim yeniden denendi".to_string(), + ("photo_saved", Lang::En) => "photo saved".to_string(), + ("photo_saved", Lang::Tr) => "fotoğraf kaydedildi".to_string(), + ("photo_removed", Lang::En) => "photo removed".to_string(), + ("photo_removed", Lang::Tr) => "fotoğraf kaldırıldı".to_string(), + ("sender_checked", Lang::En) => "mail server checked".to_string(), + ("sender_checked", Lang::Tr) => "posta sunucusu denetlendi".to_string(), (other, _) => other.to_string(), } } diff --git a/crates/izlek-web/src/logs.rs b/crates/izlek-web/src/logs.rs index b10db64..a6222dc 100644 --- a/crates/izlek-web/src/logs.rs +++ b/crates/izlek-web/src/logs.rs @@ -124,6 +124,15 @@ const ACTIVITY_KINDS: &[&str] = &[ "rule_deleted", "file_added", "file_removed", + "tagged", + "tag_created", + "tag_renamed", + "tag_deleted", + "tag_moved", + "send_retried", + "photo_saved", + "photo_removed", + "sender_checked", ]; /// The word the decisions panel prints for an outcome. Terse: the panel is @@ -184,7 +193,18 @@ fn activity_sentence(kind: &izlek_core::detail::ActivityKind, detail: &str, lang ActivityKind::RuleEdited => crate::i18n::rule_edited_label(lang, detail), ActivityKind::RuleToggled => crate::i18n::rule_toggled_label(lang, detail), ActivityKind::RuleDeleted => crate::i18n::rule_deleted_label(lang, detail), - ActivityKind::Other(_) => detail.to_string(), + ActivityKind::Other(raw) => match raw.as_str() { + "tagged" => crate::i18n::tagged_label(lang, detail), + "tag_created" => crate::i18n::tag_created_label(lang, detail), + "tag_renamed" => crate::i18n::tag_renamed_label(lang, detail), + "tag_deleted" => crate::i18n::tag_deleted_label(lang, detail), + "tag_moved" => crate::i18n::tag_moved_label(lang, detail), + "send_retried" => t(lang, Key::ActSendRetried).to_string(), + "photo_saved" => t(lang, Key::ActPhotoSaved).to_string(), + "photo_removed" => t(lang, Key::ActPhotoRemoved).to_string(), + "sender_checked" => t(lang, Key::ActSenderChecked).to_string(), + _ => detail.to_string(), + }, } } @@ -764,18 +784,26 @@ struct RetrySendForm { send_id: String, } -/// Puts a failed or abandoned send back in play, admin only. No trail event: -/// no `ActivityKind` fits a retry, so none is written rather than one being -/// invented. +/// Puts a failed or abandoned send back in play, admin only. The retry lands +/// on the workspace trail, so the queue's history reads whole. #[route(POST "/api/retry_send")] async fn retry_send(cx: &Cx, Form(input): Form) -> Redirect { - if let Err(refusal) = require_admin(cx).await { - return redirect(cx, Some(refusal)); - } + let admin = match require_admin(cx).await { + Ok(admin) => admin, + Err(refusal) => return redirect(cx, Some(refusal)), + }; let store = accounts(cx).store().clone(); let _ = store .requeue_send(&input.send_id, OffsetDateTime::now_utc()) .await; + let _ = store + .record_event( + Some(&admin.id), + &izlek_core::detail::ActivityKind::Other("send_retried".to_string()), + "", + OffsetDateTime::now_utc(), + ) + .await; redirect(cx, None) } diff --git a/crates/izlek-web/src/photo.rs b/crates/izlek-web/src/photo.rs index 9993dde..1c4bbc7 100644 --- a/crates/izlek-web/src/photo.rs +++ b/crates/izlek-web/src/photo.rs @@ -77,6 +77,14 @@ async fn upload( if let Some(stamps) = try_app_context::(cx) { stamps.bump(&user.id); } + let _ = store + .record_event( + Some(&user.id), + &izlek_core::detail::ActivityKind::Other("photo_saved".to_string()), + "", + OffsetDateTime::now_utc(), + ) + .await; saved_or_refused("profile_photo", None) } Err(_) => saved_or_refused("profile_photo", Some(Refusal::Unavailable)), @@ -93,7 +101,17 @@ async fn delete(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { }; let store = accounts(cx).store().clone(); Ok(match store.clear_photo(&user.id).await { - Ok(()) => saved_or_refused("delete_profile_photo", None), + Ok(()) => { + let _ = store + .record_event( + Some(&user.id), + &izlek_core::detail::ActivityKind::Other("photo_removed".to_string()), + "", + OffsetDateTime::now_utc(), + ) + .await; + saved_or_refused("delete_profile_photo", None) + } Err(_) => saved_or_refused("delete_profile_photo", Some(Refusal::Unavailable)), }) } diff --git a/crates/izlek-web/src/server.rs b/crates/izlek-web/src/server.rs index b69dad3..9c0b1cc 100644 --- a/crates/izlek-web/src/server.rs +++ b/crates/izlek-web/src/server.rs @@ -8,6 +8,7 @@ //! `izlek-web/src/auth.rs`, onto topcoat's context/cookie/layer primitives. use izlek_core::accounts::{AccountError, Accounts}; +use izlek_core::auth::PasswordProblem; use izlek_core::board::Transition; use izlek_core::mail::Engine; use izlek_core::store::{Freeing, User}; @@ -282,7 +283,7 @@ fn refusal_for(error: &AccountError) -> Refusal { match error { AccountError::Rejected => Refusal::Rejected, AccountError::RateLimited => Refusal::RateLimited, - AccountError::Password(problem) => Refusal::Password(problem.to_string()), + AccountError::Password(problem) => Refusal::Password(*problem), AccountError::Forbidden => Refusal::Forbidden, AccountError::AlreadyClaimed => Refusal::AlreadyClaimed, AccountError::AddressTaken => Refusal::AddressTaken, @@ -315,8 +316,10 @@ pub enum Refusal { Rejected, RateLimited, /// A password broke a stated rule. Only reachable once we know who the - /// person is, so it gives nothing away. - Password(String), + /// person is, so it gives nothing away. The problem itself rides in the + /// variant — the wording is built at the edge, in the reader's language, + /// never reflected out of the address bar. + Password(PasswordProblem), Forbidden, SignInFirst, AlreadyClaimed, @@ -400,7 +403,7 @@ impl Refusal { Refusal::RateLimited => { "Too many attempts — wait a few minutes and try again.".to_string() } - Refusal::Password(problem) => problem.clone(), + Refusal::Password(problem) => problem.to_string(), Refusal::Forbidden => "Not permitted.".to_string(), Refusal::SignInFirst => "Sign in first.".to_string(), Refusal::AlreadyClaimed => "This workspace already has an owner.".to_string(), @@ -502,10 +505,12 @@ impl Refusal { Refusal::AddressTaken => "Bu adresin zaten bir hesabı var.".to_string(), Refusal::LinkNotUsable => "Bu bağlantı artık çalışmıyor.".to_string(), Refusal::EmptyName => "Kendine bir isim ver.".to_string(), - // Built by `izlek-core`'s password validator, out of this - // slice's reach — stays English until that crate carries `Lang` - // too. - Refusal::Password(_) => self.message(), + // The validator's own words, in the reader's language. + Refusal::Password(problem) => match problem { + PasswordProblem::TooShort => "En az 10 karakter.".to_string(), + PasswordProblem::LooksLikeYou => "Adresin ya da adın değil.".to_string(), + PasswordProblem::IsCurrent => "Bu zaten mevcut parolan.".to_string(), + }, } } @@ -516,8 +521,9 @@ impl Refusal { Some(match code { "rejected" => Refusal::Rejected, "rate-limited" => Refusal::RateLimited, - "password-short" => Refusal::Password("at least 10 characters".to_string()), - "password-you" => Refusal::Password("not your address or your name".to_string()), + "password-short" => Refusal::Password(PasswordProblem::TooShort), + "password-you" => Refusal::Password(PasswordProblem::LooksLikeYou), + "password-current" => Refusal::Password(PasswordProblem::IsCurrent), "forbidden" => Refusal::Forbidden, "sign-in-first" => Refusal::SignInFirst, "already-claimed" => Refusal::AlreadyClaimed, @@ -570,15 +576,11 @@ impl Refusal { Refusal::RateLimited => "rate-limited", // The problem itself, not the wording, so the sentence is built // here on the way back rather than reflected out of the address. - Refusal::Password(problem) => { - if problem == "at least 10 characters" { - "password-short" - } else if problem == "not your address or your name" { - "password-you" - } else { - "rejected" - } - } + Refusal::Password(problem) => match problem { + PasswordProblem::TooShort => "password-short", + PasswordProblem::LooksLikeYou => "password-you", + PasswordProblem::IsCurrent => "password-current", + }, Refusal::Forbidden => "forbidden", Refusal::SignInFirst => "sign-in-first", Refusal::AlreadyClaimed => "already-claimed", @@ -813,6 +815,37 @@ fn same_origin(location: &str) -> &str { } } +/// The cache directives a response cannot choose for itself. +/// +/// HTML is revalidated on every load: a page the browser kept from before a +/// deploy is the old app answering under the new one's address, which is how a +/// fixed bug once came back after shipping. So every response whose body is a +/// document gets `no-cache`. Responses that already carry a directive keep it — +/// topcoat stamps the fingerprinted assets under `/_topcoat/assets` with a year +/// of `immutable` and the live stream with `no-cache`, and the photo and +/// attachment handlers stamp their own — and everything else (redirects, JSON +/// answers) ships none, the idiom they already ride on: no directive, nothing +/// cached. One layer at `/`, because the decision is about what the bytes are, +/// not which route built them. +#[topcoat::router::layer("/")] +async fn cache_directives(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result { + let response = next.run(cx, body).await?; + let (mut parts, body) = response.into_parts(); + let is_html = parts + .headers + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value.starts_with("text/html")); + if !is_html || parts.headers.contains_key(header::CACHE_CONTROL) { + return Ok(Response::from_parts(parts, body)); + } + parts.headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static("no-cache"), + ); + Ok(Response::from_parts(parts, body)) +} + #[cfg(test)] mod refusal_redirect_tests { use super::carrying; @@ -895,14 +928,16 @@ mod refusal_redirect_tests { #[cfg(test)] mod refusal_message_tests { use super::Refusal; + use izlek_core::auth::PasswordProblem; #[test] fn every_refusal_survives_the_address_bar() { let all = [ Refusal::Rejected, Refusal::RateLimited, - Refusal::Password("at least 10 characters".to_string()), - Refusal::Password("not your address or your name".to_string()), + Refusal::Password(PasswordProblem::TooShort), + Refusal::Password(PasswordProblem::LooksLikeYou), + Refusal::Password(PasswordProblem::IsCurrent), Refusal::Forbidden, Refusal::SignInFirst, Refusal::AlreadyClaimed, diff --git a/crates/izlek-web/src/settings.rs b/crates/izlek-web/src/settings.rs index 2d3c340..0b7b05b 100644 --- a/crates/izlek-web/src/settings.rs +++ b/crates/izlek-web/src/settings.rs @@ -25,6 +25,7 @@ use topcoat::router::content::Form; use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, page, route}; use topcoat::view::view; +use izlek_core::auth::PasswordProblem; use izlek_core::detail::ActivityKind; use izlek_core::store::{NewSender, SenderCheck, SenderTest, Store, User}; @@ -564,11 +565,16 @@ async fn check_sender(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec)> { Ok(admin) => admin, Err(refusal) => return Ok(saved_or_refused("check_sender", Some(refusal))), }; - probe_sender( - mail(cx), - accounts(cx).store().clone(), - admin.workspace_id.clone(), - ); + let store = accounts(cx).store().clone(); + probe_sender(mail(cx), store.clone(), admin.workspace_id.clone()); + let _ = store + .record_event( + Some(&admin.id), + &ActivityKind::Other("sender_checked".to_string()), + "", + time::OffsetDateTime::now_utc(), + ) + .await; Ok(saved_or_refused("check_sender", None)) } @@ -1132,6 +1138,21 @@ fn call_state<'q>(query: &'q str, call: &str) -> (Option, bool) { (refusal, saved) } +/// The password pane words a refusal itself: on this surface `Rejected` can +/// only be the current password failing, so the pane says which half did +/// rather than the generic "that did not work". +fn password_pane_word(lang: Lang, refusal: &Refusal) -> String { + match refusal { + Refusal::Rejected => t(lang, Key::PWCurrentWrong).to_string(), + Refusal::Password(problem) => match problem { + PasswordProblem::TooShort => t(lang, Key::PWTooShort).to_string(), + PasswordProblem::LooksLikeYou => t(lang, Key::PWLooksLikeYou).to_string(), + PasswordProblem::IsCurrent => t(lang, Key::PWIsCurrent).to_string(), + }, + other => other.message_in(lang), + } +} + fn query_value<'q>(query: &'q str, key: &str) -> Option<&'q str> { query.split('&').find_map(|pair| { pair.split_once('=') @@ -1221,7 +1242,7 @@ async fn settings_page(cx: &Cx) -> Result { let (invite_refusal, _) = call_state(query, "invite_member"); let (role_refusal, _) = call_state(query, "set_role"); let member_refusal = resend_refusal.or(invite_refusal).or(role_refusal); - let (password_refusal, _) = call_state(query, "change_password"); + let (password_refusal, password_saved) = call_state(query, "change_password"); let (message_refusal, message_saved) = call_state(query, "send_message"); let mailed = query_value(query, "mailed").map(decode_q); @@ -1343,7 +1364,10 @@ async fn settings_page(cx: &Cx) -> Result {
if let Some(refusal) = &password_refusal { - (refusal.message_in(lang)) + (password_pane_word(lang, refusal)) + } + if password_saved { + (t(lang, Key::PasswordSaved)) }
diff --git a/crates/izlek-web/src/tags.rs b/crates/izlek-web/src/tags.rs index d296447..a409895 100644 --- a/crates/izlek-web/src/tags.rs +++ b/crates/izlek-web/src/tags.rs @@ -122,6 +122,20 @@ struct CreateTagForm { name: String, } +/// One line on the workspace trail: who did what to which tag. A trail +/// write that fails is swallowed, like every other trail write behind a +/// handler — a lost log line never fails the write that caused it. +async fn tag_event(store: &Arc, actor: &User, kind: &str, detail: &str) { + let _ = store + .record_event( + Some(&actor.id), + &izlek_core::detail::ActivityKind::Other(kind.to_string()), + detail, + time::OffsetDateTime::now_utc(), + ) + .await; +} + /// Writes one tag. A duplicate name is the store's `Conflict`, which lands /// here like every other store error: the admin sees "something went wrong" /// and the list still shows the tag they collide with. @@ -147,6 +161,7 @@ async fn create_tag(cx: &Cx, Form(input): Form) -> Redirect { { return redirect(cx, Some(Refusal::Unavailable)); } + tag_event(&store, &user, "tag_created", &name).await; redirect(cx, None) } @@ -161,7 +176,7 @@ struct RenameTagForm { /// renamed by an admin who never owned it. #[route(POST "/api/rename_tag")] async fn rename_tag(cx: &Cx, Form(input): Form) -> Redirect { - let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await { + let (store, user, tag) = match tag_of_this_workspace(cx, &input.tag_id).await { Ok(triple) => triple, Err(refusal) => return redirect(cx, Some(refusal)), }; @@ -172,6 +187,13 @@ async fn rename_tag(cx: &Cx, Form(input): Form) -> Redirect { if store.rename_tag(&input.tag_id, &name).await.is_err() { return redirect(cx, Some(Refusal::Unavailable)); } + tag_event( + &store, + &user, + "tag_renamed", + &format!("{} -> {name}", tag.name), + ) + .await; redirect(cx, None) } @@ -187,12 +209,15 @@ struct DeleteTagForm { /// the same rule where it is actually enforced. #[route(POST "/api/delete_tag")] async fn delete_tag(cx: &Cx, Form(input): Form) -> Redirect { - let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await { + let (store, user, tag) = match tag_of_this_workspace(cx, &input.tag_id).await { Ok(triple) => triple, Err(refusal) => return redirect(cx, Some(refusal)), }; match store.delete_tag(&input.tag_id).await { - Ok(()) => redirect(cx, None), + Ok(()) => { + tag_event(&store, &user, "tag_deleted", &tag.name).await; + redirect(cx, None) + } Err(izlek_core::store::StoreError::Conflict("tag_in_use")) => { redirect(cx, Some(Refusal::TagInUse)) } @@ -211,7 +236,7 @@ struct MoveTagForm { /// form gone wrong, and does nothing. #[route(POST "/api/move_tag")] async fn move_tag(cx: &Cx, Form(input): Form) -> Redirect { - let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await { + let (store, user, tag) = match tag_of_this_workspace(cx, &input.tag_id).await { Ok(triple) => triple, Err(refusal) => return redirect(cx, Some(refusal)), }; @@ -223,6 +248,7 @@ async fn move_tag(cx: &Cx, Form(input): Form) -> Redirect { if store.move_tag(&input.tag_id, up).await.is_err() { return redirect(cx, Some(Refusal::Unavailable)); } + tag_event(&store, &user, "tag_moved", &tag.name).await; redirect(cx, None) } diff --git a/crates/izlek-web/tests/http.rs b/crates/izlek-web/tests/http.rs index 4d1f4d8..da4a5e3 100644 --- a/crates/izlek-web/tests/http.rs +++ b/crates/izlek-web/tests/http.rs @@ -5010,11 +5010,10 @@ async fn the_topbar_nav_marks_the_active_page() { } /// A wrong current password lands back on the rail section it was posted -/// from with a refusal; a right one changes nothing about the query but the -/// refusal — `carry_refusal_on_redirect` never writes a `saved=` for a call -/// nobody asked to see a note about. +/// from with a refusal; a right one lands with the pane's own `saved=` note — +/// the user asked the pane to say what happened, other devices included. #[tokio::test] -async fn a_password_change_carries_its_own_refusal_and_never_a_saved_note() { +async fn a_password_change_carries_its_own_refusal_and_a_saved_note() { let app = App::open().await; let admin_cookie = admin(&app).await; @@ -5055,7 +5054,7 @@ async fn a_password_change_carries_its_own_refusal_and_never_a_saved_note() { right .location .as_deref() - .is_some_and(|location| !location.contains("saved=")), + .is_some_and(|location| location.contains("saved=change_password")), "{:?}", right.location ); @@ -9110,3 +9109,414 @@ async fn an_off_step_clock_renders_itself_not_a_rounded_step() { ); assert!(html.contains(">Sep 02 11:23<"), "{html}"); } + +#[tokio::test] +async fn a_page_revalidates_and_an_asset_caches_forever() { + let app = App::open().await; + + // A page the browser kept from before a deploy is the old app answering + // under the new one's address, so HTML is revalidated on every load. + let page = Request::builder() + .method("GET") + .uri("/") + .body(Body::empty()) + .unwrap(); + let page = app.router.handle(page).await; + assert_eq!(page.status(), StatusCode::OK); + let directive = page + .headers() + .get(header::CACHE_CONTROL) + .and_then(|value| value.to_str().ok()); + assert_eq!(directive, Some("no-cache")); + + // The asset's name carries its content hash, so the year of `immutable` + // topcoat stamps it with survives the layer untouched. + let stylesheet = std::fs::read_dir(asset_dir()) + .unwrap() + .filter_map(|entry| { + let path = entry.ok()?.path(); + (path.extension()?.to_str()? == "css").then_some(path) + }) + .next() + .expect("no compiled stylesheet in the asset bundle"); + let asset_path = format!( + "/_topcoat/assets/{}", + stylesheet.file_name().unwrap().to_str().unwrap() + ); + let asset = Request::builder() + .method("GET") + .uri(&asset_path) + .body(Body::empty()) + .unwrap(); + let asset = app.router.handle(asset).await; + assert_eq!(asset.status(), StatusCode::OK); + let directive = asset + .headers() + .get(header::CACHE_CONTROL) + .and_then(|value| value.to_str().ok()); + assert_eq!(directive, Some("public, max-age=31536000, immutable")); + + // A redirect carries no directive at all: nothing cached, nothing stale. + let redirected = Request::builder() + .method("POST") + .uri("/api/sign_out") + .header(header::ACCEPT, "application/json") + .body(Body::empty()) + .unwrap(); + let redirected = app.router.handle(redirected).await; + assert_eq!(redirected.status(), StatusCode::SEE_OTHER); + assert!(redirected.headers().get(header::CACHE_CONTROL).is_none()); +} + +/// Every tag write lands on the workspace trail with the acting admin as the +/// actor: created, moved, renamed (old -> new) and deleted each name the tag +/// itself in the detail. +#[tokio::test] +async fn tag_writes_record_their_events() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + + app + .post( + "/api/create_tag", + Some(&admin_cookie), + &[("name", "Urgent")], + ) + .await; + let workspace_id = app.workspace_id().await; + let tag = { + let board = izlek_core::board::load(app.store.as_ref(), &workspace_id) + .await + .unwrap() + .unwrap(); + app.store + .tags(&board.board.id) + .await + .unwrap() + .into_iter() + .find(|tag| tag.name == "Urgent") + .expect("the tag was created") + }; + app + .post( + "/api/move_tag", + Some(&admin_cookie), + &[("tag_id", &tag.id), ("direction", "up")], + ) + .await; + app + .post( + "/api/rename_tag", + Some(&admin_cookie), + &[("tag_id", &tag.id), ("name", "High")], + ) + .await; + app + .post( + "/api/delete_tag", + Some(&admin_cookie), + &[("tag_id", &tag.id)], + ) + .await; + + let lines = app + .store + .recent_activity( + 20, + izlek_core::store::FeedPage::Newest, + izlek_core::store::Dir::Newest, + &izlek_core::store::ActivityFilter::default(), + ) + .await + .unwrap(); + let line_of = |raw: &str| { + lines + .iter() + .find(|line| line.kind.as_str() == raw) + .unwrap_or_else(|| panic!("no {raw} line: {lines:?}")) + }; + assert_eq!(line_of("tag_created").detail, "Urgent"); + assert_eq!(line_of("tag_renamed").detail, "Urgent -> High"); + assert_eq!(line_of("tag_moved").detail, "Urgent"); + assert_eq!(line_of("tag_deleted").detail, "High"); + for raw in ["tag_created", "tag_renamed", "tag_moved", "tag_deleted"] { + assert_eq!( + line_of(raw).actor_name.as_deref(), + Some("Ada Lovelace"), + "{raw}" + ); + } +} + +/// Filing a task under a tag writes one line on the task's own trail, naming +/// the tag, with the person who filed it as the actor. +#[tokio::test] +async fn tagging_a_task_records_a_trail_line() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let workspace_id = app.workspace_id().await; + let board = izlek_core::board::load(app.store.as_ref(), &workspace_id) + .await + .unwrap() + .unwrap(); + let column = board.columns[0].column.id.clone(); + let task = a_task(&app, &admin_cookie, &column, "Audit me").await; + app + .post( + "/api/create_tag", + Some(&admin_cookie), + &[("name", "Shipped")], + ) + .await; + let tag = { + let board = izlek_core::board::load(app.store.as_ref(), &workspace_id) + .await + .unwrap() + .unwrap(); + app.store + .tags(&board.board.id) + .await + .unwrap() + .into_iter() + .find(|tag| tag.name == "Shipped") + .expect("the tag was created") + }; + + app + .post( + "/api/set_task_tag", + Some(&admin_cookie), + &[("task_id", &task), ("tag_id", &tag.id)], + ) + .await; + + let lines = app + .store + .recent_activity( + 20, + izlek_core::store::FeedPage::Newest, + izlek_core::store::Dir::Newest, + &izlek_core::store::ActivityFilter { + kind: Some("tagged".to_string()), + ..Default::default() + }, + ) + .await + .unwrap(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0].detail, "Shipped"); + assert_eq!(lines[0].actor_name.as_deref(), Some("Ada Lovelace")); +} + +/// A profile photo set and cleared both land on the workspace trail, and the +/// person whose photo it is is the actor on both lines. +#[tokio::test] +async fn profile_photo_changes_record_their_events() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + + app + .post_multipart( + "/api/profile_photo", + Some(&admin_cookie), + &[], + Some(("me.png", "image/png", &PNG)), + ) + .await; + app + .post("/api/delete_profile_photo", Some(&admin_cookie), &[]) + .await; + + let lines = app + .store + .recent_activity( + 20, + izlek_core::store::FeedPage::Newest, + izlek_core::store::Dir::Newest, + &izlek_core::store::ActivityFilter::default(), + ) + .await + .unwrap(); + let saved = lines + .iter() + .find(|line| line.kind.as_str() == "photo_saved") + .expect("no photo_saved line"); + assert_eq!(saved.actor_name.as_deref(), Some("Ada Lovelace")); + let removed = lines + .iter() + .find(|line| line.kind.as_str() == "photo_removed") + .expect("no photo_removed line"); + assert_eq!(removed.actor_name.as_deref(), Some("Ada Lovelace")); +} + +/// Asking for a mail-server check rides the trail too — it writes a check +/// row, so the trail says who asked. +#[tokio::test] +async fn checking_the_sender_records_an_event() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + + let answer = app + .post("/api/check_sender", Some(&admin_cookie), &[]) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + + let lines = app + .store + .recent_activity( + 20, + izlek_core::store::FeedPage::Newest, + izlek_core::store::Dir::Newest, + &izlek_core::store::ActivityFilter { + kind: Some("sender_checked".to_string()), + ..Default::default() + }, + ) + .await + .unwrap(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0].actor_name.as_deref(), Some("Ada Lovelace")); +} + +/// The settings pane for a given feedback query, as HTML — every assertion +/// below reads the words the pane itself would show. +async fn password_pane(app: &App, cookie: &str, query: &str) -> String { + let page = app + .get( + &format!("/settings?section=profile&{query}"), + Some(cookie), + ) + .await; + String::from_utf8_lossy(&page.bytes).into_owned() +} + +/// The password pane names each failure — wrong current, same as current, +/// too short, looks-like-you — each with its own refusal code and its own +/// one-line message in either language; a successful change lands with the +/// pane's saved note about the other devices. +#[tokio::test] +async fn the_password_pane_names_each_failure() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let referer = "http://izlek.test/settings?section=profile"; + + // The current password is wrong. + let wrong = app + .post_without_script( + "/api/change_password", + Some(&admin_cookie), + referer, + &[("current", "not the password"), ("new", "a whole new passphrase")], + ) + .await; + let location = wrong.location.expect("a redirect location"); + assert!( + location.contains("refusal=rejected") && location.contains("on=change_password"), + "{location}" + ); + assert!( + password_pane(&app, &admin_cookie, "refusal=rejected&on=change_password") + .await + .contains("The current password is wrong.") + ); + + // The new password is the one already in force. + let same = app + .post_without_script( + "/api/change_password", + Some(&admin_cookie), + referer, + &[ + ("current", "correct horse battery staple"), + ("new", "correct horse battery staple"), + ], + ) + .await; + let location = same.location.expect("a redirect location"); + assert!( + location.contains("refusal=password-current"), + "{location}" + ); + assert!( + password_pane(&app, &admin_cookie, "refusal=password-current&on=change_password") + .await + .contains("That's your current password.") + ); + + // Too short. + let short = app + .post_without_script( + "/api/change_password", + Some(&admin_cookie), + referer, + &[("current", "correct horse battery staple"), ("new", "short")], + ) + .await; + let location = short.location.expect("a redirect location"); + assert!(location.contains("refusal=password-short"), "{location}"); + assert!( + password_pane(&app, &admin_cookie, "refusal=password-short&on=change_password") + .await + .contains("At least 10 characters.") + ); + + // Looks like the address the account wears. + let you = app + .post_without_script( + "/api/change_password", + Some(&admin_cookie), + referer, + &[("current", "correct horse battery staple"), ("new", "ada@izlek.sh!!")], + ) + .await; + let location = you.location.expect("a redirect location"); + assert!(location.contains("refusal=password-you"), "{location}"); + assert!( + password_pane(&app, &admin_cookie, "refusal=password-you&on=change_password") + .await + .contains("Not your address or your name.") + ); + + // A change that works lands with the pane's own note, and the fresh + // cookie the answer carries is the session that reads it. (`post` + // keeps the answer's cookie; `post_without_script` models a browser + // that only follows the redirect and hands none back.) + let right = app + .post( + "/api/change_password", + Some(&admin_cookie), + &[ + ("current", "correct horse battery staple"), + ("new", "brand-new-pass-99"), + ], + ) + .await; + let location = right.location.clone().expect("a redirect location"); + assert!(location.contains("saved=change_password"), "{location}"); + let fresh = right.session.clone().expect("a fresh session cookie"); + let page = app + .get("/settings?section=profile&saved=change_password", Some(&fresh)) + .await; + let html = String::from_utf8_lossy(&page.bytes); + assert!( + html.contains("Password changed. Your other devices were signed out."), + "{html}" + ); + + // The same pane in Turkish names the same failures in Turkish. + app + .post( + "/api/save_profile", + Some(&fresh), + &[("display_name", "Ada Lovelace"), ("language", "tr")], + ) + .await; + let tr = app + .get( + "/settings?section=profile&refusal=password-current&on=change_password", + Some(&fresh), + ) + .await; + let tr_html = String::from_utf8_lossy(&tr.bytes); + assert!(tr_html.contains("Bu zaten mevcut parolan."), "{tr_html}"); +}