diff --git a/crates/im-core/src/accounts.rs b/crates/im-core/src/accounts.rs index 83bc5cf..1855648 100644 --- a/crates/im-core/src/accounts.rs +++ b/crates/im-core/src/accounts.rs @@ -49,6 +49,9 @@ pub enum PasswordProblem { TooShort, #[error("not your address or your name")] LooksLikeYou, + /// The current password given at change time is not the one in force. + #[error("that's not your current password")] + WrongCurrent, /// 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")] @@ -403,6 +406,47 @@ pub async fn verify_login( Ok(user) } +/// The panel's "change password": proves the current one, enforces the same +/// rules the invite screen does, refuses the walk-away "new = old", then +/// hashes and stores. Sessions are the caller's business — the web layer +/// revokes every session but the one holding the form, so a stolen device +/// loses its access the moment the password moves. +pub async fn change_password( + store: &Store, + user: &User, + current: &str, + new: &str, +) -> std::result::Result<(), AccountError> { + let mut rows = store + .conn + .query( + "SELECT password_hash FROM users WHERE id = ?1", + turso::params![user.id.to_string()], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Err(AccountError::InvalidCredentials); + }; + let phc = store::text(&row, 0)?; + if !verify_password(current, &phc) { + return Err(PasswordProblem::WrongCurrent.into()); + } + check_password(new, &user.email, &user.name)?; + if verify_password(new, &phc) { + return Err(PasswordProblem::IsCurrent.into()); + } + store + .conn + .execute( + "UPDATE users SET password_hash = ?1 WHERE id = ?2", + turso::params![hash_password(new)?, user.id.to_string()], + ) + .await + .map_err(backend)?; + Ok(()) +} + /// Looks a user up by email — the CLI's revoke path resolves names this way. pub async fn user_by_email(store: &Store, email: &str) -> Result> { let mut rows = store @@ -598,6 +642,47 @@ mod tests { )); } + #[tokio::test] + async fn change_password_proves_current_and_applies_rules() { + let store = fixture().await; + let invite = create_invite(&store, "ann@example.com", None, false) + .await + .unwrap(); + let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") + .await + .unwrap(); + + // Wrong current password is refused by name. + assert!(matches!( + change_password(&store, &user, "not-the-password", "Xk9#mQ2vLpR7").await, + Err(AccountError::Password(PasswordProblem::WrongCurrent)) + )); + // The rules the invite screen enforces apply here too. + assert!(matches!( + change_password(&store, &user, "tDLr9!mZQ2xv", "short").await, + Err(AccountError::Password(PasswordProblem::TooShort)) + )); + // New = old is the walk-away mistake, refused. + assert!(matches!( + change_password(&store, &user, "tDLr9!mZQ2xv", "tDLr9!mZQ2xv").await, + Err(AccountError::Password(PasswordProblem::IsCurrent)) + )); + + change_password(&store, &user, "tDLr9!mZQ2xv", "Xk9#mQ2vLpR7") + .await + .unwrap(); + assert!( + verify_login(&store, "ann@example.com", "Xk9#mQ2vLpR7") + .await + .is_ok() + ); + assert!( + verify_login(&store, "ann@example.com", "tDLr9!mZQ2xv") + .await + .is_err() + ); + } + #[tokio::test] async fn duplicate_email_is_refused() { let store = fixture().await; diff --git a/crates/im-core/src/sessions.rs b/crates/im-core/src/sessions.rs index 18eedea..8bf69e1 100644 --- a/crates/im-core/src/sessions.rs +++ b/crates/im-core/src/sessions.rs @@ -142,6 +142,56 @@ pub async fn revoke_user_sessions(store: &Store, user: &UserId) -> Result { Ok(count) } +/// A password change's revoke: every session dies except the one holding the +/// form — the browser that just proved the old password stays signed in, and +/// every other device (and every app token born of them) is out. +pub async fn revoke_user_sessions_except( + store: &Store, + user: &UserId, + keep_token: &str, +) -> Result { + let keep = hash_token(keep_token); + let mut rows = store + .conn + .query( + "SELECT token_hash FROM sessions \ + WHERE user_id = ?1 AND revoked_at IS NULL AND token_hash != ?2", + turso::params![user.to_string(), keep.clone()], + ) + .await + .map_err(backend)?; + let mut hashes = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + hashes.push(store::text(&row, 0)?); + } + let count = hashes.len() as u64; + for hash in &hashes { + revoke_session_hash(store, hash).await?; + } + // The kept session is the only one allowed to keep its app sessions and + // refresh tokens; everything else of this user's is swept. + let now = store::stamp(store::now())?; + store + .conn + .execute( + "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \ + AND session_hash != ?3", + turso::params![now.clone(), user.to_string(), keep.clone()], + ) + .await + .map_err(backend)?; + store + .conn + .execute( + "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \ + AND session_hash != ?3", + turso::params![now, user.to_string(), keep], + ) + .await + .map_err(backend)?; + Ok(count) +} + #[cfg(test)] mod tests { use super::*; @@ -183,4 +233,28 @@ mod tests { .is_none() ); } + + #[tokio::test] + async fn revoke_except_keeps_the_asking_session() { + let (store, user_id) = fixture().await; + let mine = create_session(&store, &user_id).await.unwrap(); + let other = create_session(&store, &user_id).await.unwrap(); + + let count = revoke_user_sessions_except(&store, &user_id, mine.expose()) + .await + .unwrap(); + assert_eq!(count, 1); + assert!( + resolve_session(&store, mine.expose()) + .await + .unwrap() + .is_some() + ); + assert!( + resolve_session(&store, other.expose()) + .await + .unwrap() + .is_none() + ); + } } diff --git a/crates/im-web/assets/main.css b/crates/im-web/assets/main.css index 7a716c2..30a463b 100644 --- a/crates/im-web/assets/main.css +++ b/crates/im-web/assets/main.css @@ -463,23 +463,29 @@ body:has(.admin-shell) { .admin-invite { display: flex; gap: 8px; - align-items: center; + align-items: stretch; + --control-h: 36px; } .admin-invite .auth-input { flex: 1; + height: var(--control-h); + box-sizing: border-box; } -.admin-invite .admin-action-wide { +.admin-invite .admin-role { + flex: 0 0 auto; width: auto; - padding: 0 20px; + padding: 0 28px 0 12px; + appearance: none; + background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%); + background-position: calc(100% - 16px) 50%, calc(100% - 11px) 50%; + background-size: 5px 5px, 5px 5px; + background-repeat: no-repeat; + cursor: pointer; } - -.admin-check { - display: flex; - align-items: center; - gap: 6px; - font-size: 12px; - color: var(--muted); - white-space: nowrap; +.admin-invite .admin-invite-go { + width: auto; + height: var(--control-h); + padding: 0 20px; } .admin-form { diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index e282ed0..31154c0 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -67,28 +67,34 @@ async fn admin_page(cx: &Cx) -> Result { .query() .unwrap_or("") .to_string(); - let section = query_value(&query, "section").unwrap_or_else(|| "users".to_string()); + let section = query_value(&query, "section").unwrap_or_else(|| "account".to_string()); let error = query_value(&query, "error"); let ok = query_value(&query, "ok"); let why = query_value(&query, "why"); let invited = query_value(&query, "invited"); let nav = |current: &str| { - [("users", "Users"), ("mail", "Mail"), ("logs", "Logs")] - .into_iter() - .map(|(id, label)| { - format!( - r#"{label}"#, - if id == current { " admin-nav-on" } else { "" } - ) - }) - .collect::() + [ + ("account", "Account"), + ("users", "Users"), + ("mail", "Mail"), + ("logs", "Logs"), + ] + .into_iter() + .map(|(id, label)| { + format!( + r#"{label}"#, + if id == current { " admin-nav-on" } else { "" } + ) + }) + .collect::() }; let section_html = match section.as_str() { "mail" => mail_section(cx).await?, "logs" => logs_section(cx).await?, - _ => users_section(cx, &me, invited.as_deref()).await?, + "users" => users_section(cx, &me, invited.as_deref()).await?, + _ => account_section(&me), }; let banner = match (ok.as_deref(), error.as_deref()) { @@ -101,6 +107,7 @@ async fn admin_page(cx: &Cx) -> Result { "enabled" => "Account enabled.", "smtp" => "Mail settings saved.", "smtp_test" => "Test mail sent.", + "password" => "Password changed — every other device is signed out.", _ => "Done.", } )), @@ -132,6 +139,32 @@ async fn admin_page(cx: &Cx) -> Result { }; shell(cx, "Admin · im", stage).await?.into_response(cx) } +/// The self-service half of the panel: the account the panel is signed in +/// as. Izlek keeps this on the settings rail's first tab; so do we. +fn account_section(me: &User) -> String { + let two_factor = if me.totp_confirmed { + "two-factor is on" + } else { + "two-factor is NOT on — sign out and back in to set it up" + }; + format!( + r#"
+
Account
+
Signed in as {} · {two_factor}.
+
+ + + + +
+
Changing it signs every other device out — this one stays.
+
"#, + escape(&me.email) + ) +} async fn users_section( cx: &Cx, @@ -194,8 +227,11 @@ async fn users_section(
- - + +
"# )) @@ -267,7 +303,7 @@ async fn logs_section(cx: &Cx) -> Result { #[derive(Deserialize)] struct InviteForm { email: String, - admin: Option, + role: Option, } #[route(POST "/admin/invite")] @@ -278,7 +314,7 @@ async fn invite(cx: &Cx, Form(input): Form) -> Result { }; let store = &app(cx).store; let email = input.email.trim().to_string(); - let admin = input.admin.as_deref() == Some("yes"); + let admin = input.role.as_deref() == Some("admin"); let token = match accounts::create_invite(store, &email, Some(me.id.clone()), admin).await { Ok(token) => token, Err(accounts::AccountError::EmailTaken) => { @@ -312,6 +348,45 @@ async fn invite(cx: &Cx, Form(input): Form) -> Result { } } +#[derive(Deserialize)] +struct PasswordForm { + current: String, + password: String, + password_confirm: String, +} + +#[route(POST "/admin/password")] +async fn password(cx: &Cx, Form(input): Form) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + if input.password != input.password_confirm { + return back(cx, "account", "&error=passwords_differ"); + } + let store = &app(cx).store; + match accounts::change_password(store, &me, &input.current, &input.password).await { + Ok(()) => {} + Err(accounts::AccountError::Password(problem)) => { + use im_core::accounts::PasswordProblem::*; + let code = match problem { + TooShort => "password_too_short", + LooksLikeYou => "password_personal", + WrongCurrent => "password_wrong", + IsCurrent => "password_same", + }; + return back(cx, "account", &format!("&error={code}")); + } + Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), + } + // Every other device is out; the browser holding this form proved the + // old password and keeps its session. + if let Some(token) = server::presented_session(cx) { + im_core::sessions::revoke_user_sessions_except(store, &me.id, &token).await?; + } + events::log(store, "password_changed", Some(&me.email), None).await; + back(cx, "account", "&ok=password") +} #[derive(Deserialize)] struct UserAction { user: String, diff --git a/crates/im-web/src/pages.rs b/crates/im-web/src/pages.rs index d34f948..de7753f 100644 --- a/crates/im-web/src/pages.rs +++ b/crates/im-web/src/pages.rs @@ -31,6 +31,8 @@ pub fn error_text(code: &str) -> &'static str { "passwords_differ" => "The two passwords don't match.", "enroll_first" => "Set up your second factor first.", "smtp_test" => "The test mail could not be sent.", + "password_wrong" => "That's not your current password.", + "password_same" => "That's already your password.", _ => "Something went wrong. Try again.", } } diff --git a/style/main.scss b/style/main.scss index 27a1aaf..eabb115 100644 --- a/style/main.scss +++ b/style/main.scss @@ -491,19 +491,37 @@ body:has(.admin-shell) { .admin-invite { display: flex; gap: 8px; - align-items: center; + align-items: stretch; + // One control height for the whole row — email, role and Invite all stand + // on the same line, the way izlek's member-invite row does. + --control-h: 36px; - .auth-input { flex: 1; } - .admin-action-wide { width: auto; padding: 0 20px; } -} + .auth-input { + flex: 1; + height: var(--control-h); + box-sizing: border-box; + } -.admin-check { - display: flex; - align-items: center; - gap: 6px; - font-size: 12px; - color: var(--muted); - white-space: nowrap; + // The role picker: same field skin as the inputs, just narrower — izlek's + // invite row uses a select here too, not a checkbox. + .admin-role { + flex: 0 0 auto; + width: auto; + padding: 0 28px 0 12px; + appearance: none; + background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), + linear-gradient(135deg, var(--muted) 50%, transparent 50%); + background-position: calc(100% - 16px) 50%, calc(100% - 11px) 50%; + background-size: 5px 5px, 5px 5px; + background-repeat: no-repeat; + cursor: pointer; + } + + .admin-invite-go { + width: auto; + height: var(--control-h); + padding: 0 20px; + } } .admin-form {