From c5b40ed38d4beb843e69b96f977fdad73264b4dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 8 Sep 2026 20:24:20 +0300 Subject: [PATCH] =?UTF-8?q?an=20address=20is=20fixable=20at=20last,=20from?= =?UTF-8?q?=20either=20side=20of=20the=20door:=20the=20admin=20panel's=20u?= =?UTF-8?q?sers=20section=20grows=20a=20direct=20email=20edit=20on=20every?= =?UTF-8?q?=20row=20=E2=80=94=20applied=20outright,=20because=20an=20unrea?= =?UTF-8?q?chable=20mailbox=20is=20exactly=20what=20the=20rescue=20is=20fo?= =?UTF-8?q?r,=20and=20email=20is=20contact=20metadata,=20not=20a=20key,=20?= =?UTF-8?q?so=20the=20id=20stays=20and=20sessions,=20app=20tokens=20and=20?= =?UTF-8?q?OIDC=20claims=20read=20the=20new=20address=20on=20their=20next?= =?UTF-8?q?=20read=20=E2=80=94=20while=20a=20person=20asking=20on=20their?= =?UTF-8?q?=20own=20account,=20from=20the=20landing's=20profile=20card,=20?= =?UTF-8?q?must=20be=20vouched=20for=20at=20both=20ends:=20one=20confirmat?= =?UTF-8?q?ion=20mail=20to=20the=20address=20being=20left=20and=20one=20to?= =?UTF-8?q?=20the=20address=20being=20gained,=20the=20change=20applying=20?= =?UTF-8?q?only=20when=20both=20mailboxes=20click,=20either=20order,=20eac?= =?UTF-8?q?h=20link=20single-use=20on=20a=20reset-length=20clock,=20the=20?= =?UTF-8?q?gained=20address=20re-checked=20for=20another=20owner=20at=20th?= =?UTF-8?q?e=20moment=20it=20applies;=20the=20pair=20lives=20in=20a=20new?= =?UTF-8?q?=20email=5Fchanges=20table=20mirrored=20into=20im-migrate,=20a?= =?UTF-8?q?=20fresh=20ask=20retires=20the=20pair=20before=20it,=20and=20th?= =?UTF-8?q?e=20confirm=20card=20is=20a=20POST=20=E2=80=94=20never=20a=20li?= =?UTF-8?q?nk=20a=20mail=20scanner=20could=20pre-fetch=20=E2=80=94=20that?= =?UTF-8?q?=20any=20mailbox=20holder=20can=20press,=20signed=20in=20or=20n?= =?UTF-8?q?ot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/im-core/src/accounts.rs | 458 +++++++++++++++++++++++++++++++++ crates/im-core/src/store.rs | 13 + crates/im-migrate/src/main.rs | 12 + crates/im-web/src/admin.rs | 55 +++- crates/im-web/src/auth.rs | 111 ++++++++ crates/im-web/src/directory.rs | 218 ++++++++++++++++ crates/im-web/src/i18n.rs | 92 +++++++ crates/im-web/src/mailer.rs | 19 ++ crates/im-web/src/pages.rs | 75 ++++++ 9 files changed, 1048 insertions(+), 5 deletions(-) diff --git a/crates/im-core/src/accounts.rs b/crates/im-core/src/accounts.rs index ceb4082..4f3b64c 100644 --- a/crates/im-core/src/accounts.rs +++ b/crates/im-core/src/accounts.rs @@ -77,6 +77,12 @@ pub enum AccountError { InviteExpired, #[error("an account with this address already exists")] EmailTaken, + #[error("that address doesn't look valid")] + InvalidEmail, + #[error("that's already your address")] + SameEmail, + #[error("this email-change link is not valid")] + EmailChangeInvalid, #[error("password: {0}")] Password(#[from] PasswordProblem), #[error("password hashing failed: {0}")] @@ -864,6 +870,251 @@ pub async fn set_preferences( Ok(()) } +/// Normalizes an address the way the login path reads it — trimmed and +/// lowercased — and refuses what no mail could ever reach. +fn normalize_email(email: &str) -> std::result::Result { + let email = email.trim().to_lowercase(); + let Some((local, domain)) = email.split_once('@') else { + return Err(AccountError::InvalidEmail); + }; + if local.is_empty() || domain.is_empty() || !domain.contains('.') { + return Err(AccountError::InvalidEmail); + } + Ok(email) +} + +/// Rewrites a user's address in place — the admin panel's direct rescue +/// for a typo'd or unreachable mailbox. Email is contact metadata, not a +/// key: the id stays, and sessions, app tokens and OIDC claims read the +/// new address live. The address is normalized the way the login path +/// reads it, an address another account owns is refused, and setting the +/// address the account already carries quietly succeeds. +pub async fn set_email(store: &Store, user: &UserId, email: &str) -> std::result::Result<(), AccountError> { + let email = normalize_email(email)?; + if let Some(other) = user_by_email(store, &email).await? { + if other.id != *user { + return Err(AccountError::EmailTaken); + } + } + let conn = store.conn.lock().await; + conn.execute( + "UPDATE users SET email = ?1 WHERE id = ?2", + turso::params![email, user.to_string()], + ) + .await + .map_err(backend)?; + Ok(()) +} + +/// What a confirmed pair of mailboxes means: one side agreed and the +/// change waits, or both agreed and the address is rewritten. +#[derive(Debug)] +pub enum EmailChangeConfirmed { + /// One mailbox confirmed; the other address still owes its click. + AwaitOther, + /// Both confirmed; the carried `User` reads the new address. + Applied(User), +} + +/// Asks for an address change on one's own account: one pending row +/// carrying two independent tokens, one mailed to the address being left +/// and one to the address being gained. The change applies only when both +/// mailboxes confirm, in either order. Asking again retires the previous +/// pair — the newest mails are the only doors — and an address another +/// account owns is refused at the ask. +pub async fn request_email_change( + store: &Store, + user: &UserId, + new_email: &str, +) -> std::result::Result<(Token, Token), AccountError> { + let me = user_by_id(store, user) + .await? + .ok_or_else(|| AccountError::Backend("email change: user vanished".into()))?; + let old_email = normalize_email(&me.email)?; + let new_email = normalize_email(new_email)?; + if new_email == old_email { + return Err(AccountError::SameEmail); + } + if let Some(other) = user_by_email(store, &new_email).await? { + if other.id != *user { + return Err(AccountError::EmailTaken); + } + } + let old_token = Token::mint(); + let new_token = Token::mint(); + let now = store::now(); + // The reset link's clock: the same policy knob, the same urgency. + let expires = now + time::Duration::minutes(crate::settings::reset_minutes(store).await?); + let conn = store.conn.lock().await; + conn.execute( + "DELETE FROM email_changes WHERE user_id = ?1 AND used_at IS NULL", + turso::params![user.to_string()], + ) + .await + .map_err(backend)?; + conn.execute( + "INSERT INTO email_changes (old_token_hash, new_token_hash, user_id, old_email, \ + new_email, created_at, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + turso::params![ + old_token.hash(), + new_token.hash(), + user.to_string(), + old_email, + new_email, + store::stamp(now)?, + store::stamp(expires)?, + ], + ) + .await + .map_err(backend)?; + Ok((old_token, new_token)) +} + +/// Confirms one end of a pending address change. The first mailbox to +/// agree only marks its side; the second completes the pair, and the +/// gained address is re-checked at that moment — someone may have +/// registered it while the mails travelled. That refusal leaves the old +/// address in place and tears the dead pair down. Every link is +/// single-use and dies at expiry. +pub async fn confirm_email_change( + store: &Store, + token: &str, +) -> std::result::Result { + let hash = hash_token(token); + // Short-held read first: the row says which side clicked and whether + // the pair may still complete. + let row = { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT old_token_hash, new_token_hash, user_id, old_email, new_email, \ + expires_at, used_at, confirmed_old_at, confirmed_new_at \ + FROM email_changes WHERE old_token_hash = ?1 OR new_token_hash = ?1", + turso::params![hash.clone()], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Err(AccountError::EmailChangeInvalid); + }; + ( + store::text(&row, 0)?, + store::text(&row, 1)?, + UserId::from(store::text(&row, 2)?), + store::text(&row, 3)?, + store::text(&row, 4)?, + store::parse_stamp(&store::text(&row, 5)?)?, + store::opt_text(&row, 6)?.is_some(), + store::opt_text(&row, 7)?.is_some(), + store::opt_text(&row, 8)?.is_some(), + ) + }; + let (old_hash, _new_hash, user_id, _old_email, new_email, expires_at, used, old_done, new_done) = + row; + if used || expires_at < store::now() { + return Err(AccountError::EmailChangeInvalid); + } + let clicked_old = old_hash == hash; + if (clicked_old && old_done) || (!clicked_old && new_done) { + // This mailbox already agreed; a second click adds nothing but + // still says what the pair waits on. + return Ok(EmailChangeConfirmed::AwaitOther); + } + let completes = (clicked_old && new_done) || (!clicked_old && old_done); + if completes { + if let Some(other) = user_by_email(store, &new_email).await? { + if other.id != user_id { + let conn = store.conn.lock().await; + conn.execute( + "DELETE FROM email_changes WHERE old_token_hash = ?1 OR new_token_hash = ?1", + turso::params![hash], + ) + .await + .map_err(backend)?; + return Err(AccountError::EmailTaken); + } + } + set_email(store, &user_id, &new_email).await?; + let stamp = store::stamp(store::now())?; + let conn = store.conn.lock().await; + conn.execute( + "UPDATE email_changes SET confirmed_old_at = COALESCE(confirmed_old_at, ?1), \ + confirmed_new_at = COALESCE(confirmed_new_at, ?1), used_at = ?1 \ + WHERE old_token_hash = ?2 OR new_token_hash = ?2", + turso::params![stamp, hash], + ) + .await + .map_err(backend)?; + drop(conn); + let user = user_by_id(store, &user_id) + .await? + .ok_or_else(|| AccountError::Backend("email change: user vanished".into()))?; + return Ok(EmailChangeConfirmed::Applied(user)); + } + let sql = if clicked_old { + "UPDATE email_changes SET confirmed_old_at = ?1 \ + WHERE old_token_hash = ?2 OR new_token_hash = ?2" + } else { + "UPDATE email_changes SET confirmed_new_at = ?1 \ + WHERE old_token_hash = ?2 OR new_token_hash = ?2" + }; + let stamp = store::stamp(store::now())?; + let conn = store.conn.lock().await; + conn.execute(sql, turso::params![stamp, hash]) + .await + .map_err(backend)?; + Ok(EmailChangeConfirmed::AwaitOther) +} + +/// The change a confirmation link still offers — the address being gained +/// when the pair is live and unspent, `None` for a dead one. The confirm +/// card reads this to name what approval means. +pub async fn email_change_link( + store: &Store, + token: &str, +) -> std::result::Result, AccountError> { + let hash = hash_token(token); + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT new_email, expires_at, used_at FROM email_changes \ + WHERE old_token_hash = ?1 OR new_token_hash = ?1", + turso::params![hash], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(None); + }; + let new_email = store::text(&row, 0)?; + let expires_at = store::parse_stamp(&store::text(&row, 1)?)?; + let spent = store::opt_text(&row, 2)?.is_some(); + Ok((!spent && expires_at >= store::now()).then_some(new_email)) +} + +/// The address a user's pending change is waiting on, for the landing's +/// one-line state. `None` when nothing is asked for or the ask expired. +pub async fn pending_email_change( + store: &Store, + user: &UserId, +) -> std::result::Result, AccountError> { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT new_email, expires_at FROM email_changes \ + WHERE user_id = ?1 AND used_at IS NULL", + turso::params![user.to_string()], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(None); + }; + let new_email = store::text(&row, 0)?; + let expires_at = store::parse_stamp(&store::text(&row, 1)?)?; + Ok((expires_at >= store::now()).then_some(new_email)) +} + #[cfg(test)] mod tests { use super::*; @@ -1175,4 +1426,211 @@ mod tests { .unwrap(); assert!(!login_blocked(&store, "ann@example.com").await.unwrap()); } + async fn seeded_user(store: &Store, email: &str, name: &str) -> User { + let invite = create_invite(store, email, None, false).await.unwrap(); + create_user_from_invite(store, invite.expose(), name, "tDLr9!mZQ2xv") + .await + .unwrap() + } + + #[tokio::test] + async fn set_email_rewrites_the_address_and_refuses_another_accounts() { + let store = fixture().await; + let ann = seeded_user(&store, "ann@example.com", "Ann").await; + let bob = seeded_user(&store, "bob@example.com", "Bob").await; + + // The rewrite is normalized the way the login path reads it, and + // every reader of the address follows. + set_email(&store, &ann.id, " Ann.New@Example.COM ") + .await + .unwrap(); + let found = user_by_email(&store, "ann.new@example.com") + .await + .unwrap() + .expect("the new address must resolve"); + assert_eq!(found.id, ann.id); + assert_eq!(found.email, "ann.new@example.com"); + assert!( + user_by_email(&store, "ann@example.com") + .await + .unwrap() + .is_none() + ); + + // An address another account owns is refused, the account untouched. + assert!(matches!( + set_email(&store, &ann.id, "bob@example.com").await, + Err(AccountError::EmailTaken) + )); + assert_eq!( + user_by_id(&store, &ann.id).await.unwrap().unwrap().email, + "ann.new@example.com" + ); + + // The address the account already carries: quiet success. + set_email(&store, &bob.id, "BOB@example.com").await.unwrap(); + + // And what no mail could reach is named at the door. + assert!(matches!( + set_email(&store, &ann.id, "not-an-address").await, + Err(AccountError::InvalidEmail) + )); + } + + #[tokio::test] + async fn email_change_applies_only_after_both_addresses_confirm() { + let store = fixture().await; + let ann = seeded_user(&store, "ann@example.com", "Ann").await; + + let (old_token, new_token) = + request_email_change(&store, &ann.id, "ann2@example.com") + .await + .unwrap(); + assert_eq!( + pending_email_change(&store, &ann.id).await.unwrap().as_deref(), + Some("ann2@example.com") + ); + + // The new mailbox agrees first: a mark, not the change. + assert!(matches!( + confirm_email_change(&store, new_token.expose()).await, + Ok(EmailChangeConfirmed::AwaitOther) + )); + assert_eq!( + user_by_email(&store, "ann@example.com") + .await + .unwrap() + .unwrap() + .id, + ann.id, + "one click must not move the address" + ); + + // Clicking the same link again adds nothing and spends nothing. + assert!(matches!( + confirm_email_change(&store, new_token.expose()).await, + Ok(EmailChangeConfirmed::AwaitOther) + )); + + // The old mailbox's agreement completes the pair: the address moves. + let user = match confirm_email_change(&store, old_token.expose()).await { + Ok(EmailChangeConfirmed::Applied(user)) => user, + outcome => panic!("expected Applied, got {outcome:?}"), + }; + assert_eq!(user.id, ann.id); + assert_eq!(user.email, "ann2@example.com"); + assert!( + user_by_email(&store, "ann2@example.com") + .await + .unwrap() + .is_some() + ); + assert!( + user_by_email(&store, "ann@example.com") + .await + .unwrap() + .is_none() + ); + assert_eq!(pending_email_change(&store, &ann.id).await.unwrap(), None); + + // The pair is spent whole: either link answers dead from now on. + assert!(matches!( + confirm_email_change(&store, old_token.expose()).await, + Err(AccountError::EmailChangeInvalid) + )); + assert!(matches!( + confirm_email_change(&store, new_token.expose()).await, + Err(AccountError::EmailChangeInvalid) + )); + } + + #[tokio::test] + async fn email_change_refuses_a_taken_address_at_ask_and_at_apply() { + let store = fixture().await; + let ann = seeded_user(&store, "ann@example.com", "Ann").await; + let _bob = seeded_user(&store, "bob@example.com", "Bob").await; + + // An owned address is refused at the ask. + assert!(matches!( + request_email_change(&store, &ann.id, "bob@example.com").await, + Err(AccountError::EmailTaken) + )); + // And so is the address the account already carries. + assert!(matches!( + request_email_change(&store, &ann.id, "ann@example.com").await, + Err(AccountError::SameEmail) + )); + + // The race: the gained address is asked for, then taken by someone + // else before both clicks land. The apply-time refusal keeps the + // old address and tears the dead pair down. + let (old_token, new_token) = + request_email_change(&store, &ann.id, "free@example.com") + .await + .unwrap(); + let carol = seeded_user(&store, "free@example.com", "Carol").await; + assert!(matches!( + confirm_email_change(&store, new_token.expose()).await, + Ok(EmailChangeConfirmed::AwaitOther) + )); + assert!(matches!( + confirm_email_change(&store, old_token.expose()).await, + Err(AccountError::EmailTaken) + )); + assert_eq!( + user_by_email(&store, "ann@example.com") + .await + .unwrap() + .unwrap() + .id, + ann.id, + "the refusal must leave the old address in place" + ); + assert_eq!(carol.email, "free@example.com"); + assert_eq!(pending_email_change(&store, &ann.id).await.unwrap(), None); + } + + #[tokio::test] + async fn email_change_links_die_at_expiry_and_a_new_ask_supersedes() { + let store = fixture().await; + let ann = seeded_user(&store, "ann@example.com", "Ann").await; + + let (first_old, first_new) = + request_email_change(&store, &ann.id, "ann2@example.com") + .await + .unwrap(); + + // Asking again is the reset idiom: the newest pair is the only door. + request_email_change(&store, &ann.id, "ann3@example.com") + .await + .unwrap(); + assert!(matches!( + confirm_email_change(&store, first_old.expose()).await, + Err(AccountError::EmailChangeInvalid) + )); + assert!(matches!( + confirm_email_change(&store, first_new.expose()).await, + Err(AccountError::EmailChangeInvalid) + )); + + // And the clock kills a pair on its own: past expiry, dead. + let (expired_old, _expired_new) = + request_email_change(&store, &ann.id, "ann4@example.com") + .await + .unwrap(); + { + let conn = store.conn.lock().await; + conn.execute( + "UPDATE email_changes SET expires_at = ?1", + turso::params![store::stamp(store::now() - time::Duration::seconds(1)).unwrap()], + ) + .await + .unwrap(); + } + assert!(matches!( + confirm_email_change(&store, expired_old.expose()).await, + Err(AccountError::EmailChangeInvalid) + )); + assert_eq!(pending_email_change(&store, &ann.id).await.unwrap(), None); + } } diff --git a/crates/im-core/src/store.rs b/crates/im-core/src/store.rs index 98ab139..d7e8062 100644 --- a/crates/im-core/src/store.rs +++ b/crates/im-core/src/store.rs @@ -126,6 +126,18 @@ CREATE TABLE IF NOT EXISTS reset_links ( expires_at TEXT NOT NULL, used_at TEXT ); +CREATE TABLE IF NOT EXISTS email_changes ( + old_token_hash TEXT PRIMARY KEY, + new_token_hash TEXT NOT NULL UNIQUE, + user_id TEXT NOT NULL REFERENCES users(id), + old_email TEXT NOT NULL, + new_email TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + confirmed_old_at TEXT, + confirmed_new_at TEXT, + used_at TEXT +); CREATE TABLE IF NOT EXISTS login_attempts ( key TEXT NOT NULL, at TEXT NOT NULL @@ -393,6 +405,7 @@ mod tests { "refresh_tokens", "signing_keys", "reset_links", + "email_changes", "login_attempts", ] { assert!(tables.contains(&expected.to_string()), "missing {expected}"); diff --git a/crates/im-migrate/src/main.rs b/crates/im-migrate/src/main.rs index 63e5fee..68731b4 100644 --- a/crates/im-migrate/src/main.rs +++ b/crates/im-migrate/src/main.rs @@ -115,6 +115,18 @@ CREATE TABLE IF NOT EXISTS reset_links ( expires_at TEXT NOT NULL, used_at TEXT ); +CREATE TABLE IF NOT EXISTS email_changes ( + old_token_hash TEXT PRIMARY KEY, + new_token_hash TEXT NOT NULL UNIQUE, + user_id TEXT NOT NULL REFERENCES users(id), + old_email TEXT NOT NULL, + new_email TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + confirmed_old_at TEXT, + confirmed_new_at TEXT, + used_at TEXT +); CREATE TABLE IF NOT EXISTS login_attempts ( key TEXT NOT NULL, at TEXT NOT NULL diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index 80e2e50..1723f33 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -157,6 +157,7 @@ async fn admin_page(cx: &Cx) -> Result { "deleted" => t(lang, Key::OkDeleted), "settings" => t(lang, Key::OkSettingsSaved), "services" => t(lang, Key::OkServicesSaved), + "email_changed" => t(lang, Key::OkEmailChanged), _ => t(lang, Key::OkDone), } )), @@ -289,12 +290,28 @@ async fn users_section( .flatten() .collect::>() .join(" · "); + let id = escape(&user.id.to_string()); + let email = escape(&user.email); + // The address edit sits on every row — the admin's own included: + // the rescue exists precisely for a mailbox the mail cannot reach. + // Same two-step disclosure as the row's other actions. + let email_edit = format!( + r#"
{edit_word}
{edit_title}
"#, + edit_word = t(lang, Key::EditWord), + edit_title = i18n::email_edit_title(lang, &email), + id = id, + email_label = t(lang, Key::EmailCol), + email = email, + save = t(lang, Key::SaveButton), + ); let actions = if user.id == me.id { - // Never let the only admin lock themselves out by reflex. - format!(r#"{}"#, t(lang, Key::YouWord)) + // Never let the only admin lock themselves out by reflex. The + // address edit stays: fixing one's own address is the point. + format!( + r#"{}{email_edit}"#, + t(lang, Key::YouWord) + ) } else { - let id = escape(&user.id.to_string()); - let email = escape(&user.email); // Every row action is a two-step disclosure — iz's // confirm-details idiom: the summary is the word, the panel holds // the button that actually does it. No script required; the live @@ -333,7 +350,7 @@ async fn users_section( t(lang, Key::ConfirmDelete), ); format!( - r#"{toggle}
{remove}"#, + r#"{email_edit}{toggle}
{remove}"#, sign_out = t(lang, Key::SignOutEverywhere), ) }; @@ -1206,6 +1223,34 @@ async fn invite(cx: &Cx, Form(input): Form) -> Result { } } +#[derive(Deserialize)] +struct UserEmailForm { + user: String, + email: String, +} + +/// The users section's direct address edit — the admin's rescue for a +/// typo'd or unreachable mailbox, applied outright: email is contact +/// metadata, not a key, so the id stays and every reader of the address +/// follows on its next read. +#[route(POST "/admin/user_email")] +async fn user_email(cx: &Cx, Form(input): Form) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + let store = &app(cx).store; + match accounts::set_email(store, &UserId::from(input.user), &input.email).await { + Ok(()) => {} + Err(accounts::AccountError::EmailTaken) => return back(cx, "users", "&error=email_taken"), + Err(accounts::AccountError::InvalidEmail) => return back(cx, "users", "&error=bad_email"), + Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), + } + let email = input.email.trim().to_lowercase(); + server::log_event(cx, "email_changed", Some(&me.email), Some(&email)).await; + back(cx, "users", "&ok=email_changed") +} + #[derive(Deserialize)] struct InviteAction { invite: String, diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index 0064fdb..101eb60 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -388,6 +388,117 @@ async fn reset(cx: &Cx, Form(input): Form) -> Redirect { } } +#[derive(Deserialize)] +struct EmailChangeForm { + email: String, +} + +/// The landing's address change: one ask, two mails — the old address must +/// agree to let the account go and the new one to take it on. Without a +/// sender configured the two links come back on the redirect once — the +/// crate's unmailed idiom, and the requester is the only person who needs +/// them. +#[route(POST "/email_change")] +async fn email_change(cx: &Cx, Form(input): Form) -> Redirect { + let Some(me) = server::current_user(cx).await else { + return see("/".to_string()); + }; + let store = &server::app(cx).store; + let (old_token, new_token) = + match accounts::request_email_change(store, &me.id, &input.email).await { + Ok(pair) => pair, + Err(AccountError::InvalidEmail) => { + return see("/?section=profile&error=bad_email".to_string()); + } + Err(AccountError::SameEmail) => { + return see("/?section=profile&error=same_email".to_string()); + } + Err(AccountError::EmailTaken) => { + return see("/?section=profile&error=email_taken".to_string()); + } + Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), + }; + let issuer = server::app(cx).config.issuer.clone(); + // Both mails follow the account's own language. + let lang = crate::i18n::Lang::from_code(&me.language); + let old_mailed = crate::mailer::send_email_change( + store, + &issuer, + &me.email, + old_token.expose(), + lang, + false, + ) + .await + .is_ok(); + let new_mailed = crate::mailer::send_email_change( + store, + &issuer, + input.email.trim(), + new_token.expose(), + lang, + true, + ) + .await + .is_ok(); + server::log_event( + cx, + "email_change_asked", + Some(&me.email), + Some(input.email.trim().to_lowercase()).as_deref(), + ) + .await; + if old_mailed && new_mailed { + see("/?section=profile&ok=email_change_asked".to_string()) + } else { + let links = format!( + "{issuer}/email/{} {issuer}/email/{}", + old_token.expose(), + new_token.expose() + ); + see(format!( + "/?section=profile&ok=email_change_asked&links={}", + crate::oidc::urlencode(&links) + )) + } +} + +#[derive(Deserialize)] +struct EmailConfirmForm { + token: String, +} + +/// A confirmation link's POST — the click that counts. The first mailbox +/// to agree only marks its side; the second applies the change. Signed-out +/// viewers may confirm, because holding the mailbox is the proof; each +/// lands where their state says, a session on the landing and everyone +/// else at the front door. +#[route(POST "/email")] +async fn email_confirm(cx: &Cx, Form(input): Form) -> Redirect { + let store = &server::app(cx).store; + match accounts::confirm_email_change(store, &input.token).await { + Ok(accounts::EmailChangeConfirmed::Applied(user)) => { + server::log_event(cx, "email_changed", Some(&user.email), None).await; + if server::current_user(cx).await.is_some() { + see("/?section=profile&ok=email_changed".to_string()) + } else { + see("/login?ok=email_changed".to_string()) + } + } + Ok(accounts::EmailChangeConfirmed::AwaitOther) => { + if server::current_user(cx).await.is_some() { + see("/?section=profile&ok=email_half_confirmed".to_string()) + } else { + see("/login?ok=email_half_confirmed".to_string()) + } + } + Err(AccountError::EmailTaken) => see("/login?error=email_taken".to_string()), + Err(AccountError::EmailChangeInvalid) => { + see("/login?error=email_change_invalid".to_string()) + } + Err(e) => Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), + } +} #[derive(Deserialize)] struct SessionRevokeForm { session: String, diff --git a/crates/im-web/src/directory.rs b/crates/im-web/src/directory.rs index f8f89da..68e68a8 100644 --- a/crates/im-web/src/directory.rs +++ b/crates/im-web/src/directory.rs @@ -993,4 +993,222 @@ mod tests { ); } + /// Percent-decodes a query value back into text — the tests read the + /// once-shown confirmation links out of the redirect's Location. + fn pct_decode(raw: &str) -> String { + let bytes = raw.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + out.push( + u8::from_str_radix(std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap(), 16) + .unwrap(), + ); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8(out).unwrap() + } + + #[tokio::test] + async fn admin_email_edit_applies_directly_and_refuses_taken_address() { + let Setup { + router, store, .. + } = setup().await; + let ada = im_core::accounts::user_by_email(&store, "ada@example.com") + .await + .unwrap() + .unwrap(); + let ben = im_core::accounts::user_by_email(&store, "ben@example.com") + .await + .unwrap() + .unwrap(); + let session = im_core::sessions::create_session(&store, &ada.id, &Default::default()) + .await + .unwrap(); + let cookie = format!("{SESSION_COOKIE}={}", session.expose()); + + // A non-admin's edit is sent to the front door and writes nothing. + let ben_session = im_core::sessions::create_session(&store, &ben.id, &Default::default()) + .await + .unwrap(); + let (status, location, _) = post_form( + &router, + "/admin/user_email", + &format!("user={}&email=changed%40example.com", ben.id), + Some(&format!("{SESSION_COOKIE}={}", ben_session.expose())), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("/")); + assert!( + im_core::accounts::user_by_email(&store, "changed@example.com") + .await + .unwrap() + .is_none() + ); + + // The admin's edit lands back on the section with its ok code, the + // address normalized the way the login path reads it. + let (status, location, _) = post_form( + &router, + "/admin/user_email", + &format!("user={}&email=%20Ben.New%40Example.COM%20", ben.id), + Some(&cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!( + location.as_deref(), + Some("/admin?section=users&ok=email_changed") + ); + let moved = im_core::accounts::user_by_email(&store, "ben.new@example.com") + .await + .unwrap() + .unwrap(); + assert_eq!(moved.id, ben.id); + assert_eq!(moved.email, "ben.new@example.com"); + assert!( + im_core::accounts::user_by_email(&store, "ben@example.com") + .await + .unwrap() + .is_none() + ); + let panel = get_page(&router, "/admin?section=users", &cookie).await; + assert!(panel.contains("ben.new@example.com"), "{panel}"); + + // Another account's address is refused by name; the account's + // address stays. + let (status, location, _) = post_form( + &router, + "/admin/user_email", + &format!("user={}&email=ada%40example.com", ben.id), + Some(&cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!( + location.as_deref(), + Some("/admin?section=users&error=email_taken") + ); + assert_eq!( + im_core::accounts::user_by_email(&store, "ben.new@example.com") + .await + .unwrap() + .unwrap() + .id, + ben.id + ); + } + + #[tokio::test] + async fn self_served_email_change_applies_after_both_addresses_confirm() { + let Setup { + router, store, .. + } = setup().await; + let ben = im_core::accounts::user_by_email(&store, "ben@example.com") + .await + .unwrap() + .unwrap(); + let session = im_core::sessions::create_session(&store, &ben.id, &Default::default()) + .await + .unwrap(); + let cookie = format!("{SESSION_COOKIE}={}", session.expose()); + + // The ask: with no sender configured, the two confirmation links + // come back on the redirect once — the crate's unmailed idiom. + let (status, location, _) = post_form( + &router, + "/email_change", + "email=ben2%40example.com", + Some(&cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + let location = location.expect("a redirect carrying the once-shown links"); + assert!(location.contains("ok=email_change_asked"), "{location}"); + let encoded = location + .split("links=") + .nth(1) + .expect("the unmailed pair shows once"); + let tokens: Vec = pct_decode(encoded) + .split(' ') + .map(|link| { + link.rsplit('/') + .next() + .expect("each link ends in its token") + .to_string() + }) + .collect(); + assert_eq!(tokens.len(), 2); + + // The card names the address being gained, and the POST under it is + // the only door. + let card = get_page(&router, &format!("/email/{}", tokens[1]), "").await; + assert!(card.contains("ben2@example.com"), "{card}"); + assert!(card.contains(r#"action="/email""#), "{card}"); + + // The first click marks its side; the address does not move. + let (status, location, _) = post_form( + &router, + "/email", + &format!("token={}", tokens[1]), + Some(&cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!( + location.as_deref(), + Some("/?section=profile&ok=email_half_confirmed") + ); + assert!( + im_core::accounts::user_by_email(&store, "ben@example.com") + .await + .unwrap() + .is_some() + ); + + // The second mailbox's agreement applies the change. + let (status, location, _) = post_form( + &router, + "/email", + &format!("token={}", tokens[0]), + Some(&cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!( + location.as_deref(), + Some("/?section=profile&ok=email_changed") + ); + let moved = im_core::accounts::user_by_email(&store, "ben2@example.com") + .await + .unwrap() + .unwrap(); + assert_eq!(moved.id, ben.id); + assert!( + im_core::accounts::user_by_email(&store, "ben@example.com") + .await + .unwrap() + .is_none() + ); + + // Spent whole: either link answers dead now. + let (status, location, _) = post_form( + &router, + "/email", + &format!("token={}", tokens[0]), + Some(&cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!( + location.as_deref(), + Some("/login?error=email_change_invalid") + ); + } } diff --git a/crates/im-web/src/i18n.rs b/crates/im-web/src/i18n.rs index 60ef350..22acae0 100644 --- a/crates/im-web/src/i18n.rs +++ b/crates/im-web/src/i18n.rs @@ -50,6 +50,9 @@ pub enum Key { ErrInviteExpired, ErrInviteSpent, ErrEmailTaken, + ErrInvalidEmail, + ErrSameEmail, + ErrEmailChangeInvalid, ErrPasswordTooShort, ErrPasswordPersonal, ErrPasswordsDiffer, @@ -75,6 +78,15 @@ pub enum Key { OkPhotoRemoved, OkSessionRevoked, OkDone, + OkEmailChanged, + OkEmailChangeAsked, + OkEmailHalfConfirmed, + EmailCardTitle, + NewEmailLabel, + EmailChangeButton, + EmailChangeNote, + EmailConfirmTitle, + ConfirmEmailButton, // Sign-in card and auth pages. SignInTitle, @@ -315,6 +327,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (ErrInviteSpent, Tr) => "Bu davet zaten kullanıldı.", (ErrEmailTaken, En) => "An account with this address already exists.", (ErrEmailTaken, Tr) => "Bu adresle zaten bir hesap var.", + (ErrInvalidEmail, En) => "That doesn't look like an email address.", + (ErrInvalidEmail, Tr) => "Bu bir e-posta adresine benzemiyor.", + (ErrSameEmail, En) => "That's already your address.", + (ErrSameEmail, Tr) => "Bu adres zaten senin adresin.", + (ErrEmailChangeInvalid, En) => "This email-change link is not valid.", + (ErrEmailChangeInvalid, Tr) => "Bu e-posta değişikliği bağlantısı geçerli değil.", (ErrPasswordTooShort, En) => "The password needs at least 10 characters.", (ErrPasswordTooShort, Tr) => "Parola en az 10 karakter olmalı.", (ErrPasswordPersonal, En) => "The password can't contain your address or your name.", @@ -529,6 +547,24 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (NavServices, Tr) => "Hizmetler", (OkInvited, En) => "Invite created.", (OkInvited, Tr) => "Davet oluşturuldu.", + (OkEmailChanged, En) => "Email changed.", + (OkEmailChanged, Tr) => "E-posta değişti.", + (OkEmailChangeAsked, En) => "Confirmation mails sent — check both inboxes.", + (OkEmailChangeAsked, Tr) => "Onay postaları gönderildi — iki kutuyu da kontrol et.", + (OkEmailHalfConfirmed, En) => "One address confirmed — the change waits on the other.", + (OkEmailHalfConfirmed, Tr) => "Bir adres onaylandı — değişiklik diğer adresi bekliyor.", + (EmailCardTitle, En) => "Email address", + (EmailCardTitle, Tr) => "E-posta adresi", + (NewEmailLabel, En) => "New address", + (NewEmailLabel, Tr) => "Yeni adres", + (EmailChangeButton, En) => "Change address", + (EmailChangeButton, Tr) => "Adresi değiştir", + (EmailChangeNote, En) => "Both addresses confirm: one mail to the old one, one to the new.", + (EmailChangeNote, Tr) => "İki adres de onaylar: eskiye bir, yeniye bir posta.", + (EmailConfirmTitle, En) => "Confirm email change", + (EmailConfirmTitle, Tr) => "E-posta değişikliğini onayla", + (ConfirmEmailButton, En) => "Confirm", + (ConfirmEmailButton, Tr) => "Onayla", (OkRevoked, En) => "Sessions revoked — every device is signed out.", (OkRevoked, Tr) => "Oturumlar kapatıldı — her cihazın oturumu kapatıldı.", (OkDisabled, En) => "Account disabled.", @@ -945,3 +981,59 @@ pub fn reset_mail(lang: Lang, link: &str, minutes: i64) -> (String, String) { ), } } + +/// The email-change card's sentence: what approval does to the address. +pub fn email_confirm_sub(lang: Lang, new_email_html: &str) -> String { + match lang { + Lang::En => format!("Confirm to make {new_email_html} this account's address."), + Lang::Tr => format!("Onaylayınca hesabın adresi {new_email_html} olacak."), + } +} + +/// The landing's pending line: the change asked for but not yet doubly +/// confirmed. +pub fn email_pending_line(lang: Lang, new_email_html: &str) -> String { + match lang { + Lang::En => format!("A change to {new_email_html} awaits confirmation."), + Lang::Tr => format!("{new_email_html} değişikliği onay bekliyor."), + } +} + +/// The admin row's edit-disclosure title. +pub fn email_edit_title(lang: Lang, email_html: &str) -> String { + match lang { + Lang::En => format!("Change {email_html}'s address."), + Lang::Tr => format!("{email_html} adresini değiştir."), + } +} +/// The address-change confirmation mail. Two travel per request — to the +/// address being left and the one being gained — and each says which kind +/// it is, so the holder knows which door they're opening. +pub fn email_change_mail(lang: Lang, link: &str, minutes: i64, gaining: bool) -> (String, String) { + match (lang, gaining) { + (Lang::En, true) => ( + "Confirm your new im address".to_string(), + format!( + "A change of this im account's address was asked for. Confirm to make it this account's address. The link is yours for {minutes} minutes:\n\n{link}\n\nIf that wasn't you, this mail changes nothing.\n" + ), + ), + (Lang::En, false) => ( + "Your im address is being changed".to_string(), + format!( + "A change of this im account's address was asked for. Confirm to let the account go. The link is yours for {minutes} minutes:\n\n{link}\n\nIf that wasn't you, this mail changes nothing.\n" + ), + ), + (Lang::Tr, true) => ( + "Yeni im adresini onayla".to_string(), + format!( + "Bu im hesabı için bir adres değişikliği istendi. Onaylayınca adres hesabın olacak. Bağlantı {minutes} dakika boyunca senin:\n\n{link}\n\nBu sen değilsen, bu posta hiçbir şeyi değiştirmez.\n" + ), + ), + (Lang::Tr, false) => ( + "im adresin değiştiriliyor".to_string(), + format!( + "Bu im hesabının adres değişikliği istendi. Onaylayınca hesabı bırakmış olacaksın. Bağlantı {minutes} dakika boyunca senin:\n\n{link}\n\nBu sen değilsen, bu posta hiçbir şeyi değiştirmez.\n" + ), + ), + } +} diff --git a/crates/im-web/src/mailer.rs b/crates/im-web/src/mailer.rs index e85335b..8a7cd42 100644 --- a/crates/im-web/src/mailer.rs +++ b/crates/im-web/src/mailer.rs @@ -99,6 +99,25 @@ pub async fn send_reset( Ok(link) } +/// The address-change confirmation mail: the link is the whole payload, in +/// the account's language. Two travel per request — `gaining` marks the +/// one bound for the address being gained; its twin goes to the address +/// being left, and each says which door it opens. +pub async fn send_email_change( + store: &Store, + issuer: &str, + email: &str, + token: &str, + lang: Lang, + gaining: bool, +) -> Result { + let link = format!("{issuer}/email/{token}"); + let minutes = settings::reset_minutes(store).await?; + let (subject, body) = i18n::email_change_mail(lang, &link, minutes, gaining); + send(store, email, &subject, body).await?; + Ok(link) +} + /// Dials the mail server without sending anything: connect, TLS, hello, /// authenticate, NOOP, hang up. A pass proves the host, the port, the /// encryption and the password; it says nothing about whether the diff --git a/crates/im-web/src/pages.rs b/crates/im-web/src/pages.rs index a14a0dc..aef2586 100644 --- a/crates/im-web/src/pages.rs +++ b/crates/im-web/src/pages.rs @@ -27,6 +27,9 @@ pub fn error_text(code: &str, lang: Lang) -> &'static str { "invite_expired" => t(lang, Key::ErrInviteExpired), "invite_spent" => t(lang, Key::ErrInviteSpent), "email_taken" => t(lang, Key::ErrEmailTaken), + "bad_email" => t(lang, Key::ErrInvalidEmail), + "same_email" => t(lang, Key::ErrSameEmail), + "email_change_invalid" => t(lang, Key::ErrEmailChangeInvalid), "password_too_short" => t(lang, Key::ErrPasswordTooShort), "password_personal" => t(lang, Key::ErrPasswordPersonal), "passwords_differ" => t(lang, Key::ErrPasswordsDiffer), @@ -59,6 +62,9 @@ pub fn ok_text(code: &str, lang: Lang) -> &'static str { "photo_saved" => t(lang, Key::OkPhotoSaved), "photo_removed" => t(lang, Key::OkPhotoRemoved), "session_revoked" => t(lang, Key::OkSessionRevoked), + "email_changed" => t(lang, Key::OkEmailChanged), + "email_change_asked" => t(lang, Key::OkEmailChangeAsked), + "email_half_confirmed" => t(lang, Key::OkEmailHalfConfirmed), "preferences" => t(lang, Key::Saved), "password" => t(lang, Key::PasswordSaved), _ => t(lang, Key::OkDone), @@ -621,6 +627,8 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { let stats = im_core::stats::profile_stats(&server::app(cx).store, &user.id).await?; let joined = user.created_at.date().to_string(); let sessions = im_core::sessions::list_sessions(&server::app(cx).store, &user.id).await?; + let pending_email = + im_core::accounts::pending_email_change(&server::app(cx).store, &user.id).await?; let current = server::presented_session(cx).map(|token| im_core::accounts::hash_token(&token)); let sessions_html = sessions_html(&sessions, current.as_deref(), lang); let apps = im_core::oidc::list_connected_apps(&server::app(cx).store, &user.id).await?; @@ -861,6 +869,34 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { +
+
(t(lang, Key::EmailCardTitle))
+ if let Some(pending) = pending_email.as_deref() { +
+ (crate::i18n::email_pending_line(lang, &escape(pending))) +
+ } + if let Some(links) = query_value(&query, "links") { +
(links)
+ } +
+ + +
+
(t(lang, Key::EmailChangeNote))
+
} @@ -979,3 +1015,42 @@ async fn reset_page(cx: &Cx) -> Result { .await? .into_response(cx) } + +/// The address-change link's destination: a card naming the address being +/// gained, and the one button that agrees to it. A GET never mutates — +/// mail scanners prefetch links — so agreeing is this card's one POST. +#[route(GET "/email/{token}")] +async fn email_change_page(cx: &Cx) -> Result { + let lang = Lang::En; + let token: &str = path_param::(cx); + let Some(new_email) = im_core::accounts::email_change_link(&server::app(cx).store, token).await? + else { + return see_other("/login?error=email_change_invalid").into_response(cx); + }; + let stage = view! { + cx => +
+
+ (wordmark(cx).await?) +
+
+
(t(lang, Key::EmailConfirmTitle))
+
+ (crate::i18n::email_confirm_sub(lang, &escape(&new_email))) +
+
+
+ + +
+
+ +
+
+ }; + shell(cx, t(lang, Key::EmailConfirmTitle), None, stage) + .await? + .into_response(cx) +}