forge
Explore
Log in

Don't you dare go Hollow

Account tab with change-password

Browse files at this commit

0134def8e415e2a4b400e643d746d4a5af3e85a3Ahmet Kaan GümüşParent: 993ef22
  • feat
    • Account tab with change-password
    • invite row to izlek's idiom
Show full message
feat: Account tab with change-password; invite row to izlek's idiom

- New Account section (first tab, like izlek's Profile): change password
  with current-password proof, the invite screen's rules, and the walk-away
  new=old refusal. Every other session dies; the asking browser stays in.
- The invite row drops the bare checkbox for izlek's member-invite idiom:
  email input, member/admin role select in the same field skin, and an
  Invite button — all three at one control height on one baseline.

Verified: suite 36 green; driven in the browser — invite row measures
36px across input/select/button, wrong current password is refused by
name, a change keeps this session and logs password_changed.
crates/im-core/src/accounts.rsmodified+85 -0
@@ -49,6 +49,9 @@ pub enum PasswordProblem {
49 TooShort,49 TooShort,
50 #[error("not your address or your name")]50 #[error("not your address or your name")]
51 LooksLikeYou,51 LooksLikeYou,
52+ /// The current password given at change time is not the one in force.
53+ #[error("that's not your current password")]
54+ WrongCurrent,
52 /// The "new" password is the one already in force — the walk-away55 /// The "new" password is the one already in force — the walk-away
53 /// mistake, refused by name rather than silently succeeding.56 /// mistake, refused by name rather than silently succeeding.
54 #[error("that's your current password")]57 #[error("that's your current password")]
@@ -403,6 +406,47 @@ pub async fn verify_login(
403 Ok(user)406 Ok(user)
404 }407 }
405 408
409+/// The panel's "change password": proves the current one, enforces the same
410+/// rules the invite screen does, refuses the walk-away "new = old", then
411+/// hashes and stores. Sessions are the caller's business — the web layer
412+/// revokes every session but the one holding the form, so a stolen device
413+/// loses its access the moment the password moves.
414+pub async fn change_password(
415+ store: &Store,
416+ user: &User,
417+ current: &str,
418+ new: &str,
419+) -> std::result::Result<(), AccountError> {
420+ let mut rows = store
421+ .conn
422+ .query(
423+ "SELECT password_hash FROM users WHERE id = ?1",
424+ turso::params![user.id.to_string()],
425+ )
426+ .await
427+ .map_err(backend)?;
428+ let Some(row) = rows.next().await.map_err(backend)? else {
429+ return Err(AccountError::InvalidCredentials);
430+ };
431+ let phc = store::text(&row, 0)?;
432+ if !verify_password(current, &phc) {
433+ return Err(PasswordProblem::WrongCurrent.into());
434+ }
435+ check_password(new, &user.email, &user.name)?;
436+ if verify_password(new, &phc) {
437+ return Err(PasswordProblem::IsCurrent.into());
438+ }
439+ store
440+ .conn
441+ .execute(
442+ "UPDATE users SET password_hash = ?1 WHERE id = ?2",
443+ turso::params![hash_password(new)?, user.id.to_string()],
444+ )
445+ .await
446+ .map_err(backend)?;
447+ Ok(())
448+}
449+
406 /// Looks a user up by email — the CLI's revoke path resolves names this way.450 /// Looks a user up by email — the CLI's revoke path resolves names this way.
407 pub async fn user_by_email(store: &Store, email: &str) -> Result<Option<User>> {451 pub async fn user_by_email(store: &Store, email: &str) -> Result<Option<User>> {
408 let mut rows = store452 let mut rows = store
@@ -598,6 +642,47 @@ mod tests {
598 ));642 ));
599 }643 }
600 644
645+ #[tokio::test]
646+ async fn change_password_proves_current_and_applies_rules() {
647+ let store = fixture().await;
648+ let invite = create_invite(&store, "ann@example.com", None, false)
649+ .await
650+ .unwrap();
651+ let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv")
652+ .await
653+ .unwrap();
654+
655+ // Wrong current password is refused by name.
656+ assert!(matches!(
657+ change_password(&store, &user, "not-the-password", "Xk9#mQ2vLpR7").await,
658+ Err(AccountError::Password(PasswordProblem::WrongCurrent))
659+ ));
660+ // The rules the invite screen enforces apply here too.
661+ assert!(matches!(
662+ change_password(&store, &user, "tDLr9!mZQ2xv", "short").await,
663+ Err(AccountError::Password(PasswordProblem::TooShort))
664+ ));
665+ // New = old is the walk-away mistake, refused.
666+ assert!(matches!(
667+ change_password(&store, &user, "tDLr9!mZQ2xv", "tDLr9!mZQ2xv").await,
668+ Err(AccountError::Password(PasswordProblem::IsCurrent))
669+ ));
670+
671+ change_password(&store, &user, "tDLr9!mZQ2xv", "Xk9#mQ2vLpR7")
672+ .await
673+ .unwrap();
674+ assert!(
675+ verify_login(&store, "ann@example.com", "Xk9#mQ2vLpR7")
676+ .await
677+ .is_ok()
678+ );
679+ assert!(
680+ verify_login(&store, "ann@example.com", "tDLr9!mZQ2xv")
681+ .await
682+ .is_err()
683+ );
684+ }
685+
601 #[tokio::test]686 #[tokio::test]
602 async fn duplicate_email_is_refused() {687 async fn duplicate_email_is_refused() {
603 let store = fixture().await;688 let store = fixture().await;
crates/im-core/src/sessions.rsmodified+74 -0
@@ -142,6 +142,56 @@ pub async fn revoke_user_sessions(store: &Store, user: &UserId) -> Result<u64> {
142 Ok(count)142 Ok(count)
143 }143 }
144 144
145+/// A password change's revoke: every session dies except the one holding the
146+/// form — the browser that just proved the old password stays signed in, and
147+/// every other device (and every app token born of them) is out.
148+pub async fn revoke_user_sessions_except(
149+ store: &Store,
150+ user: &UserId,
151+ keep_token: &str,
152+) -> Result<u64> {
153+ let keep = hash_token(keep_token);
154+ let mut rows = store
155+ .conn
156+ .query(
157+ "SELECT token_hash FROM sessions \
158+ WHERE user_id = ?1 AND revoked_at IS NULL AND token_hash != ?2",
159+ turso::params![user.to_string(), keep.clone()],
160+ )
161+ .await
162+ .map_err(backend)?;
163+ let mut hashes = Vec::new();
164+ while let Some(row) = rows.next().await.map_err(backend)? {
165+ hashes.push(store::text(&row, 0)?);
166+ }
167+ let count = hashes.len() as u64;
168+ for hash in &hashes {
169+ revoke_session_hash(store, hash).await?;
170+ }
171+ // The kept session is the only one allowed to keep its app sessions and
172+ // refresh tokens; everything else of this user's is swept.
173+ let now = store::stamp(store::now())?;
174+ store
175+ .conn
176+ .execute(
177+ "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \
178+ AND session_hash != ?3",
179+ turso::params![now.clone(), user.to_string(), keep.clone()],
180+ )
181+ .await
182+ .map_err(backend)?;
183+ store
184+ .conn
185+ .execute(
186+ "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \
187+ AND session_hash != ?3",
188+ turso::params![now, user.to_string(), keep],
189+ )
190+ .await
191+ .map_err(backend)?;
192+ Ok(count)
193+}
194+
145 #[cfg(test)]195 #[cfg(test)]
146 mod tests {196 mod tests {
147 use super::*;197 use super::*;
@@ -183,4 +233,28 @@ mod tests {
183 .is_none()233 .is_none()
184 );234 );
185 }235 }
236+
237+ #[tokio::test]
238+ async fn revoke_except_keeps_the_asking_session() {
239+ let (store, user_id) = fixture().await;
240+ let mine = create_session(&store, &user_id).await.unwrap();
241+ let other = create_session(&store, &user_id).await.unwrap();
242+
243+ let count = revoke_user_sessions_except(&store, &user_id, mine.expose())
244+ .await
245+ .unwrap();
246+ assert_eq!(count, 1);
247+ assert!(
248+ resolve_session(&store, mine.expose())
249+ .await
250+ .unwrap()
251+ .is_some()
252+ );
253+ assert!(
254+ resolve_session(&store, other.expose())
255+ .await
256+ .unwrap()
257+ .is_none()
258+ );
259+ }
186 }260 }
crates/im-web/assets/main.cssmodified+17 -11
@@ -463,23 +463,29 @@ body:has(.admin-shell) {
463 .admin-invite {463 .admin-invite {
464 display: flex;464 display: flex;
465 gap: 8px;465 gap: 8px;
466- align-items: center;466+ align-items: stretch;
467+ --control-h: 36px;
467 }468 }
468 .admin-invite .auth-input {469 .admin-invite .auth-input {
469 flex: 1;470 flex: 1;
471+ height: var(--control-h);
472+ box-sizing: border-box;
470 }473 }
471-.admin-invite .admin-action-wide {474+.admin-invite .admin-role {
475+ flex: 0 0 auto;
472 width: auto;476 width: auto;
473- padding: 0 20px;477+ padding: 0 28px 0 12px;
478+ appearance: none;
479+ background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%);
480+ background-position: calc(100% - 16px) 50%, calc(100% - 11px) 50%;
481+ background-size: 5px 5px, 5px 5px;
482+ background-repeat: no-repeat;
483+ cursor: pointer;
474 }484 }
475-485+.admin-invite .admin-invite-go {
476-.admin-check {486+ width: auto;
477- display: flex;487+ height: var(--control-h);
478- align-items: center;488+ padding: 0 20px;
479- gap: 6px;
480- font-size: 12px;
481- color: var(--muted);
482- white-space: nowrap;
483 }489 }
484 490
485 .admin-form {491 .admin-form {
crates/im-web/src/admin.rsmodified+90 -15
@@ -67,28 +67,34 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
67 .query()67 .query()
68 .unwrap_or("")68 .unwrap_or("")
69 .to_string();69 .to_string();
70- let section = query_value(&query, "section").unwrap_or_else(|| "users".to_string());70+ let section = query_value(&query, "section").unwrap_or_else(|| "account".to_string());
71 let error = query_value(&query, "error");71 let error = query_value(&query, "error");
72 let ok = query_value(&query, "ok");72 let ok = query_value(&query, "ok");
73 let why = query_value(&query, "why");73 let why = query_value(&query, "why");
74 let invited = query_value(&query, "invited");74 let invited = query_value(&query, "invited");
75 75
76 let nav = |current: &str| {76 let nav = |current: &str| {
77- [("users", "Users"), ("mail", "Mail"), ("logs", "Logs")]77+ [
78- .into_iter()78+ ("account", "Account"),
79- .map(|(id, label)| {79+ ("users", "Users"),
80- format!(80+ ("mail", "Mail"),
81- r#"<a class="admin-nav{}" href="/admin?section={id}">{label}</a>"#,81+ ("logs", "Logs"),
82- if id == current { " admin-nav-on" } else { "" }82+ ]
83- )83+ .into_iter()
84- })84+ .map(|(id, label)| {
85- .collect::<String>()85+ format!(
86+ r#"<a class="admin-nav{}" href="/admin?section={id}">{label}</a>"#,
87+ if id == current { " admin-nav-on" } else { "" }
88+ )
89+ })
90+ .collect::<String>()
86 };91 };
87 92
88 let section_html = match section.as_str() {93 let section_html = match section.as_str() {
89 "mail" => mail_section(cx).await?,94 "mail" => mail_section(cx).await?,
90 "logs" => logs_section(cx).await?,95 "logs" => logs_section(cx).await?,
91- _ => users_section(cx, &me, invited.as_deref()).await?,96+ "users" => users_section(cx, &me, invited.as_deref()).await?,
97+ _ => account_section(&me),
92 };98 };
93 99
94 let banner = match (ok.as_deref(), error.as_deref()) {100 let banner = match (ok.as_deref(), error.as_deref()) {
@@ -101,6 +107,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
101 "enabled" => "Account enabled.",107 "enabled" => "Account enabled.",
102 "smtp" => "Mail settings saved.",108 "smtp" => "Mail settings saved.",
103 "smtp_test" => "Test mail sent.",109 "smtp_test" => "Test mail sent.",
110+ "password" => "Password changed — every other device is signed out.",
104 _ => "Done.",111 _ => "Done.",
105 }112 }
106 )),113 )),
@@ -132,6 +139,32 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
132 };139 };
133 shell(cx, "Admin · im", stage).await?.into_response(cx)140 shell(cx, "Admin · im", stage).await?.into_response(cx)
134 }141 }
142+/// The self-service half of the panel: the account the panel is signed in
143+/// as. Izlek keeps this on the settings rail's first tab; so do we.
144+fn account_section(me: &User) -> String {
145+ let two_factor = if me.totp_confirmed {
146+ "two-factor is on"
147+ } else {
148+ "two-factor is NOT on — sign out and back in to set it up"
149+ };
150+ format!(
151+ r#"<div class="admin-card">
152+ <div class="auth-title">Account</div>
153+ <div class="auth-sub">Signed in as <span class="mono">{}</span> · {two_factor}.</div>
154+ <form method="post" action="/admin/password" class="admin-form">
155+ <label class="auth-field"><span class="auth-label">Current password</span>
156+ <input class="auth-input auth-input-mono" type="password" name="current" autocomplete="current-password" required></label>
157+ <label class="auth-field"><span class="auth-label">New password</span>
158+ <input class="auth-input auth-input-mono" type="password" name="password" autocomplete="new-password" minlength="10" required></label>
159+ <label class="auth-field"><span class="auth-label">New password, again</span>
160+ <input class="auth-input auth-input-mono" type="password" name="password_confirm" autocomplete="new-password" minlength="10" required></label>
161+ <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">Change password</span></button>
162+ </form>
163+ <div class="auth-sub">Changing it signs every other device out — this one stays.</div>
164+</div>"#,
165+ escape(&me.email)
166+ )
167+}
135 168
136 async fn users_section(169 async fn users_section(
137 cx: &Cx,170 cx: &Cx,
@@ -194,8 +227,11 @@ async fn users_section(
194 </table>227 </table>
195 <form method="post" action="/admin/invite" class="admin-invite">228 <form method="post" action="/admin/invite" class="admin-invite">
196 <input class="auth-input auth-input-mono" type="email" name="email" placeholder="person@example.com" required>229 <input class="auth-input auth-input-mono" type="email" name="email" placeholder="person@example.com" required>
197- <label class="admin-check"><input type="checkbox" name="admin" value="yes"> admin</label>230+ <select class="auth-input admin-role" name="role">
198- <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">Invite</span></button>231+ <option value="member">member</option>
232+ <option value="admin">admin</option>
233+ </select>
234+ <button class="auth-submit admin-invite-go" type="submit"><span class="auth-submit-text">Invite</span></button>
199 </form>235 </form>
200 </div>"#236 </div>"#
201 ))237 ))
@@ -267,7 +303,7 @@ async fn logs_section(cx: &Cx) -> Result<String, topcoat::Error> {
267 #[derive(Deserialize)]303 #[derive(Deserialize)]
268 struct InviteForm {304 struct InviteForm {
269 email: String,305 email: String,
270- admin: Option<String>,306+ role: Option<String>,
271 }307 }
272 308
273 #[route(POST "/admin/invite")]309 #[route(POST "/admin/invite")]
@@ -278,7 +314,7 @@ async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Result<Response> {
278 };314 };
279 let store = &app(cx).store;315 let store = &app(cx).store;
280 let email = input.email.trim().to_string();316 let email = input.email.trim().to_string();
281- let admin = input.admin.as_deref() == Some("yes");317+ let admin = input.role.as_deref() == Some("admin");
282 let token = match accounts::create_invite(store, &email, Some(me.id.clone()), admin).await {318 let token = match accounts::create_invite(store, &email, Some(me.id.clone()), admin).await {
283 Ok(token) => token,319 Ok(token) => token,
284 Err(accounts::AccountError::EmailTaken) => {320 Err(accounts::AccountError::EmailTaken) => {
@@ -312,6 +348,45 @@ async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Result<Response> {
312 }348 }
313 }349 }
314 350
351+#[derive(Deserialize)]
352+struct PasswordForm {
353+ current: String,
354+ password: String,
355+ password_confirm: String,
356+}
357+
358+#[route(POST "/admin/password")]
359+async fn password(cx: &Cx, Form(input): Form<PasswordForm>) -> Result<Response> {
360+ let me = match require_admin(cx).await {
361+ Ok(me) => me,
362+ Err(redirect) => return Ok(redirect),
363+ };
364+ if input.password != input.password_confirm {
365+ return back(cx, "account", "&error=passwords_differ");
366+ }
367+ let store = &app(cx).store;
368+ match accounts::change_password(store, &me, &input.current, &input.password).await {
369+ Ok(()) => {}
370+ Err(accounts::AccountError::Password(problem)) => {
371+ use im_core::accounts::PasswordProblem::*;
372+ let code = match problem {
373+ TooShort => "password_too_short",
374+ LooksLikeYou => "password_personal",
375+ WrongCurrent => "password_wrong",
376+ IsCurrent => "password_same",
377+ };
378+ return back(cx, "account", &format!("&error={code}"));
379+ }
380+ Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))),
381+ }
382+ // Every other device is out; the browser holding this form proved the
383+ // old password and keeps its session.
384+ if let Some(token) = server::presented_session(cx) {
385+ im_core::sessions::revoke_user_sessions_except(store, &me.id, &token).await?;
386+ }
387+ events::log(store, "password_changed", Some(&me.email), None).await;
388+ back(cx, "account", "&ok=password")
389+}
315 #[derive(Deserialize)]390 #[derive(Deserialize)]
316 struct UserAction {391 struct UserAction {
317 user: String,392 user: String,
crates/im-web/src/pages.rsmodified+2 -0
@@ -31,6 +31,8 @@ pub fn error_text(code: &str) -> &'static str {
31 "passwords_differ" => "The two passwords don't match.",31 "passwords_differ" => "The two passwords don't match.",
32 "enroll_first" => "Set up your second factor first.",32 "enroll_first" => "Set up your second factor first.",
33 "smtp_test" => "The test mail could not be sent.",33 "smtp_test" => "The test mail could not be sent.",
34+ "password_wrong" => "That's not your current password.",
35+ "password_same" => "That's already your password.",
34 _ => "Something went wrong. Try again.",36 _ => "Something went wrong. Try again.",
35 }37 }
36 }38 }
style/main.scssmodified+29 -11
@@ -491,19 +491,37 @@ body:has(.admin-shell) {
491 .admin-invite {491 .admin-invite {
492 display: flex;492 display: flex;
493 gap: 8px;493 gap: 8px;
494- align-items: center;494+ align-items: stretch;
495+ // One control height for the whole row — email, role and Invite all stand
496+ // on the same line, the way izlek's member-invite row does.
497+ --control-h: 36px;
495 498
496- .auth-input { flex: 1; }499+ .auth-input {
497- .admin-action-wide { width: auto; padding: 0 20px; }500+ flex: 1;
498-}501+ height: var(--control-h);
502+ box-sizing: border-box;
503+ }
499 504
500-.admin-check {505+ // The role picker: same field skin as the inputs, just narrower — izlek's
501- display: flex;506+ // invite row uses a select here too, not a checkbox.
502- align-items: center;507+ .admin-role {
503- gap: 6px;508+ flex: 0 0 auto;
504- font-size: 12px;509+ width: auto;
505- color: var(--muted);510+ padding: 0 28px 0 12px;
506- white-space: nowrap;511+ appearance: none;
512+ background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%),
513+ linear-gradient(135deg, var(--muted) 50%, transparent 50%);
514+ background-position: calc(100% - 16px) 50%, calc(100% - 11px) 50%;
515+ background-size: 5px 5px, 5px 5px;
516+ background-repeat: no-repeat;
517+ cursor: pointer;
518+ }
519+
520+ .admin-invite-go {
521+ width: auto;
522+ height: var(--control-h);
523+ padding: 0 20px;
524+ }
507 }525 }
508 526
509 .admin-form {527 .admin-form {