forge
Explore
Log in

Don't you dare go Hollow

Password reset, rate limiting, policy settings

Browse files at this commit

6099ac7ed48f46e0c71af4b2431fe30deaef0883Ahmet Kaan GümüşParent: 794c3a4
  • feat
    • password reset, rate limiting, policy settings
  • fix
    • connection mutex, row alignment
Show full message
feat: password reset, rate limiting, policy settings; fix: connection mutex, row alignment

- Password reset: /forgot asks with one neutral answer for every address;
  the newest link is the only live one (minting retires the rest), redeeming
  spends the link, swaps the hash and revokes every session in one move.
  Reset links are never shown on screen — mail or nothing.
- Sign-in rate limiting: a rolling hour of failures per address (and per
  account for the second factor) against a panel-set ceiling; a success
  wipes the slate. Blocked doors answer 'too many tries' without saying
  which step refused.
- New Settings section: invite days, session days, second-factor window,
  reset-link minutes, failure ceiling — the constants the code shipped
  with, now the panel's.
- fix: every database access now holds the connection mutex (iz's
  pattern). Concurrent requests — an SSE refetch against a posting form —
  panicked turso's write lock; found by the browser drive, swept repo-wide.
- fix: the confirm disclosure's summary now renders at button height next
  to real buttons.

Verified: suite 41 green incl. single-active-link and limit-block/clear
contracts; browser-driven — Settings saves, 2 failures then 'too many
tries', dead reset link redirects to the ask with the refusal named,
concurrent write+3 reads answer 200 with no panic, and the action row
measures 32px across Disable/Sign-out/Delete.

16 changed files +1154 -435

crates/im-core/src/accounts.rsmodified+398 -113
@@ -67,10 +67,14 @@ pub enum AccountError {
6767 InvalidCredentials,
6868 #[error("this invite is not valid")]
6969 InviteInvalid,
70- #[error("this invite has expired")]
71- InviteExpired,
70+ /// Unknown, spent or expired — one refusal for all three, so the page
71+ /// never says which.
72+ #[error("this reset link is not valid")]
73+ ResetInvalid,
7274 #[error("this invite was already used")]
7375 InviteSpent,
76+ #[error("this invite has expired")]
77+ InviteExpired,
7478 #[error("an account with this address already exists")]
7579 EmailTaken,
7680 #[error("password: {0}")]
@@ -240,31 +244,32 @@ pub async fn create_invite(
240244 }
241245 let token = Token::mint();
242246 let now = store::now();
243- let expires = now + time::Duration::days(INVITE_DAYS);
244- store
245- .conn
246- .execute(
247- "INSERT INTO invites (token, email, invited_by, admin, created_at, expires_at) \
247+ // The panel's Settings section owns this number now; the constant is the
248+ // fresh-database default, not the value.
249+ let expires = now + time::Duration::days(crate::settings::invite_days(store).await?);
250+ let conn = store.conn.lock().await;
251+ conn.execute(
252+ "INSERT INTO invites (token, email, invited_by, admin, created_at, expires_at) \
248253 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
249- turso::params![
250- token.hash(),
251- email,
252- invited_by.map(|id| id.to_string()),
253- admin as i64,
254- store::stamp(now)?,
255- store::stamp(expires)?,
256- ],
257- )
258- .await
259- .map_err(backend)?;
254+ turso::params![
255+ token.hash(),
256+ email,
257+ invited_by.map(|id| id.to_string()),
258+ admin as i64,
259+ store::stamp(now)?,
260+ store::stamp(expires)?,
261+ ],
262+ )
263+ .await
264+ .map_err(backend)?;
260265 Ok(token)
261266 }
262267
263268 /// Looks an invite up by its raw token. Expiry and spent-ness are the
264269 /// caller's to rule on — this answers what the row says.
265270 pub async fn invite_by_token(store: &Store, token: &str) -> Result<Option<Invite>> {
266- let mut rows = store
267- .conn
271+ let conn = store.conn.lock().await;
272+ let mut rows = conn
268273 .query(
269274 "SELECT email, invited_by, admin, created_at, expires_at, accepted_at \
270275 FROM invites WHERE token = ?1",
@@ -303,8 +308,8 @@ pub struct PendingInvite {
303308
304309 /// Invites not yet accepted and not yet expired, oldest first.
305310 pub async fn list_pending_invites(store: &Store) -> Result<Vec<PendingInvite>> {
306- let mut rows = store
307- .conn
311+ let conn = store.conn.lock().await;
312+ let mut rows = conn
308313 .query(
309314 "SELECT token, email, admin, created_at, expires_at FROM invites \
310315 WHERE accepted_at IS NULL AND expires_at > ?1 ORDER BY created_at",
@@ -328,8 +333,8 @@ pub async fn list_pending_invites(store: &Store) -> Result<Vec<PendingInvite>> {
328333 /// Invalidates an invite: the row is gone, the link reads "not valid" from
329334 /// that moment on. Returns the address it was made out to, for the log line.
330335 pub async fn revoke_invite(store: &Store, token_hash: &str) -> Result<Option<String>> {
331- let mut rows = store
332- .conn
336+ let conn = store.conn.lock().await;
337+ let mut rows = conn
333338 .query(
334339 "SELECT email FROM invites WHERE token = ?1",
335340 turso::params![token_hash],
@@ -340,14 +345,12 @@ pub async fn revoke_invite(store: &Store, token_hash: &str) -> Result<Option<Str
340345 return Ok(None);
341346 };
342347 let email = store::text(&row, 0)?;
343- store
344- .conn
345- .execute(
346- "DELETE FROM invites WHERE token = ?1",
347- turso::params![token_hash],
348- )
349- .await
350- .map_err(backend)?;
348+ conn.execute(
349+ "DELETE FROM invites WHERE token = ?1",
350+ turso::params![token_hash],
351+ )
352+ .await
353+ .map_err(backend)?;
351354 Ok(Some(email))
352355 }
353356
@@ -380,59 +383,256 @@ pub async fn create_user_from_invite(
380383 created_at: store::now(),
381384 };
382385 let password_hash = hash_password(password)?;
386+ // The lock is taken only now — the reads above (`invite_by_token`) lock
387+ // for themselves, and the transaction holds it alone.
388+ let conn = store.conn.lock().await;
383389
384- store
385- .conn
386- .execute("BEGIN IMMEDIATE", ())
387- .await
388- .map_err(backend)?;
390+ conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
389391 let outcome = async {
390- store
391- .conn
392- .execute(
393- "INSERT INTO users (id, email, name, password_hash, admin, created_at) \
392+ conn.execute(
393+ "INSERT INTO users (id, email, name, password_hash, admin, created_at) \
394394 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
395- turso::params![
396- user.id.to_string(),
397- user.email.clone(),
398- user.name.clone(),
399- password_hash,
400- user.admin as i64,
401- store::stamp(user.created_at)?,
402- ],
403- )
404- .await
405- .map_err(|e| {
406- let text = e.to_string().to_lowercase();
407- if text.contains("constraint") || text.contains("unique") {
408- AccountError::EmailTaken
409- } else {
410- AccountError::Backend(e.to_string())
411- }
412- })?;
413- store
414- .conn
415- .execute(
416- "UPDATE invites SET accepted_at = ?1 WHERE token = ?2 AND accepted_at IS NULL",
417- turso::params![store::stamp(store::now())?, hash_token(token)],
395+ turso::params![
396+ user.id.to_string(),
397+ user.email.clone(),
398+ user.name.clone(),
399+ password_hash,
400+ user.admin as i64,
401+ store::stamp(user.created_at)?,
402+ ],
403+ )
404+ .await
405+ .map_err(|e| {
406+ let text = e.to_string().to_lowercase();
407+ if text.contains("constraint") || text.contains("unique") {
408+ AccountError::EmailTaken
409+ } else {
410+ AccountError::Backend(e.to_string())
411+ }
412+ })?;
413+ conn.execute(
414+ "UPDATE invites SET accepted_at = ?1 WHERE token = ?2 AND accepted_at IS NULL",
415+ turso::params![store::stamp(store::now())?, hash_token(token)],
416+ )
417+ .await
418+ .map_err(|e| AccountError::Backend(e.to_string()))?;
419+ Ok::<_, AccountError>(())
420+ }
421+ .await;
422+ match outcome {
423+ Ok(()) => {
424+ conn.execute("COMMIT", ()).await.map_err(backend)?;
425+ Ok(user)
426+ }
427+ Err(e) => {
428+ let _ = conn.execute("ROLLBACK", ()).await;
429+ Err(e)
430+ }
431+ }
432+}
433+
434+// ---------------------------------------------------------------------------
435+// Password reset
436+// ---------------------------------------------------------------------------
437+
438+/// Mints a reset link for the account at `email`, retiring every previous
439+/// live one first: two reset mails means the first is already dead — the
440+/// newest link is the only door. `None` for an address with no account, so
441+/// the web layer can answer every address identically.
442+pub async fn create_reset(
443+ store: &Store,
444+ email: &str,
445+) -> std::result::Result<Option<Token>, AccountError> {
446+ let Some(user) = user_by_email(store, email).await? else {
447+ return Ok(None);
448+ };
449+ let token = Token::mint();
450+ let now = store::now();
451+ let expires = now + time::Duration::minutes(crate::settings::reset_minutes(store).await?);
452+ let conn = store.conn.lock().await;
453+ conn.execute(
454+ "DELETE FROM reset_links WHERE user_id = ?1 AND used_at IS NULL",
455+ turso::params![user.id.to_string()],
456+ )
457+ .await
458+ .map_err(backend)?;
459+ conn.execute(
460+ "INSERT INTO reset_links (token, user_id, created_at, expires_at) \
461+ VALUES (?1, ?2, ?3, ?4)",
462+ turso::params![
463+ token.hash(),
464+ user.id.to_string(),
465+ store::stamp(now)?,
466+ store::stamp(expires)?,
467+ ],
468+ )
469+ .await
470+ .map_err(backend)?;
471+ Ok(Some(token))
472+}
473+
474+/// Turns a valid reset link into a new password. The link is spent, the hash
475+/// replaced, and every session revoked in one transaction — the old
476+/// password's doors close the moment the new one exists.
477+pub async fn redeem_reset(
478+ store: &Store,
479+ token: &str,
480+ password: &str,
481+) -> std::result::Result<User, AccountError> {
482+ let hash = hash_token(token);
483+ // Short-held read first: the row says whether the link may be redeemed.
484+ let (user_id, expires_at, used) = {
485+ let conn = store.conn.lock().await;
486+ let mut rows = conn
487+ .query(
488+ "SELECT user_id, expires_at, used_at FROM reset_links WHERE token = ?1",
489+ turso::params![hash.clone()],
418490 )
419491 .await
420- .map_err(|e| AccountError::Backend(e.to_string()))?;
492+ .map_err(backend)?;
493+ let Some(row) = rows.next().await.map_err(backend)? else {
494+ return Err(AccountError::ResetInvalid);
495+ };
496+ (
497+ UserId::from(store::text(&row, 0)?),
498+ store::parse_stamp(&store::text(&row, 1)?)?,
499+ store::opt_text(&row, 2)?.is_some(),
500+ )
501+ };
502+ if used || expires_at < store::now() {
503+ return Err(AccountError::ResetInvalid);
504+ }
505+ let user = user_by_id(store, &user_id)
506+ .await?
507+ .ok_or(AccountError::ResetInvalid)?;
508+ check_password(password, &user.email, &user.name)?;
509+ let password_hash = hash_password(password)?;
510+
511+ // The write half holds the lock across its transaction; revocation comes
512+ // after COMMIT because `revoke_user_sessions` locks for itself.
513+ let conn = store.conn.lock().await;
514+ conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
515+ let outcome = async {
516+ conn.execute(
517+ "UPDATE reset_links SET used_at = ?1 WHERE token = ?2 AND used_at IS NULL",
518+ turso::params![store::stamp(store::now())?, hash],
519+ )
520+ .await
521+ .map_err(|e| AccountError::Backend(e.to_string()))?;
522+ conn.execute(
523+ "UPDATE users SET password_hash = ?1 WHERE id = ?2",
524+ turso::params![password_hash, user.id.to_string()],
525+ )
526+ .await
527+ .map_err(|e| AccountError::Backend(e.to_string()))?;
421528 Ok::<_, AccountError>(())
422529 }
423530 .await;
424531 match outcome {
425532 Ok(()) => {
426- store.conn.execute("COMMIT", ()).await.map_err(backend)?;
533+ conn.execute("COMMIT", ()).await.map_err(backend)?;
534+ drop(conn);
535+ crate::sessions::revoke_user_sessions(store, &user.id)
536+ .await
537+ .map_err(|e| AccountError::Backend(e.to_string()))?;
538+ // Owning the mailbox is the proof; past failures stop counting.
539+ clear_login_failures(store, &user.email).await?;
427540 Ok(user)
428541 }
429542 Err(e) => {
430- let _ = store.conn.execute("ROLLBACK", ()).await;
543+ let _ = conn.execute("ROLLBACK", ()).await;
431544 Err(e)
432545 }
433546 }
434547 }
435548
549+// ---------------------------------------------------------------------------
550+// Sign-in rate limiting
551+// ---------------------------------------------------------------------------
552+
553+/// The counter is a rolling hour of failures per key — the address for
554+/// passwords, `totp:{user}` for second factors. Reads and writes both sweep
555+/// their own key's stale rows, so the table never grows without bound.
556+async fn sweep_attempts(store: &Store, key: &str) -> Result<()> {
557+ let conn = store.conn.lock().await;
558+ let cutoff = store::stamp(store::now() - time::Duration::hours(1))?;
559+ conn.execute(
560+ "DELETE FROM login_attempts WHERE key = ?1 AND at < ?2",
561+ turso::params![key, cutoff],
562+ )
563+ .await
564+ .map_err(backend)?;
565+ Ok(())
566+}
567+
568+/// True when the key has burned through the panel's per-hour allowance.
569+pub async fn login_blocked(store: &Store, key: &str) -> Result<bool> {
570+ sweep_attempts(store, key).await?;
571+ let cutoff = store::stamp(store::now() - time::Duration::hours(1))?;
572+ let count = {
573+ let conn = store.conn.lock().await;
574+ let mut rows = conn
575+ .query(
576+ "SELECT COUNT(*) FROM login_attempts WHERE key = ?1 AND at >= ?2",
577+ turso::params![key, cutoff],
578+ )
579+ .await
580+ .map_err(backend)?;
581+ match rows.next().await.map_err(backend)? {
582+ Some(row) => store::int(&row, 0)?,
583+ None => 0,
584+ }
585+ };
586+ // The limit reads settings, which locks for itself — the count's guard is
587+ // already gone.
588+ Ok(count >= crate::settings::login_attempts_per_hour(store).await?)
589+}
590+
591+/// Writes down a failure. Success is the caller's job to record too — by
592+/// clearing, with [`clear_login_failures`].
593+pub async fn record_login_failure(store: &Store, key: &str) -> Result<()> {
594+ sweep_attempts(store, key).await?;
595+ let conn = store.conn.lock().await;
596+ conn.execute(
597+ "INSERT INTO login_attempts (key, at) VALUES (?1, ?2)",
598+ turso::params![key, store::stamp(store::now())?],
599+ )
600+ .await
601+ .map_err(backend)?;
602+ Ok(())
603+}
604+
605+/// A success wipes the slate: the next failure starts from zero.
606+pub async fn clear_login_failures(store: &Store, key: &str) -> Result<()> {
607+ let conn = store.conn.lock().await;
608+ conn.execute(
609+ "DELETE FROM login_attempts WHERE key = ?1",
610+ turso::params![key],
611+ )
612+ .await
613+ .map_err(backend)?;
614+ Ok(())
615+}
616+
617+/// Whether the reset page may stand: the link exists, unspent, unexpired.
618+/// Redemption re-checks in its transaction — this is only the page's
619+/// early answer, so a dead link never shows a working form.
620+pub async fn reset_link_valid(store: &Store, token: &str) -> Result<bool> {
621+ let conn = store.conn.lock().await;
622+ let mut rows = conn
623+ .query(
624+ "SELECT expires_at, used_at FROM reset_links WHERE token = ?1",
625+ turso::params![hash_token(token)],
626+ )
627+ .await
628+ .map_err(backend)?;
629+ let Some(row) = rows.next().await.map_err(backend)? else {
630+ return Ok(false);
631+ };
632+ let expires_at = store::parse_stamp(&store::text(&row, 0)?)?;
633+ Ok(store::opt_text(&row, 1)?.is_none() && expires_at >= store::now())
634+}
635+
436636 /// Verifies an email+password pair, returning the user on success. Disabled
437637 /// accounts are refused with the same wording as a wrong password, and every
438638 /// miss path burns an Argon2 run so timing does not say which one it was.
@@ -441,8 +641,8 @@ pub async fn verify_login(
441641 email: &str,
442642 password: &str,
443643 ) -> std::result::Result<User, AccountError> {
444- let mut rows = store
445- .conn
644+ let conn = store.conn.lock().await;
645+ let mut rows = conn
446646 .query(
447647 "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at \
448648 FROM users WHERE email = ?1 COLLATE NOCASE",
@@ -481,8 +681,8 @@ pub async fn change_password(
481681 current: &str,
482682 new: &str,
483683 ) -> std::result::Result<(), AccountError> {
484- let mut rows = store
485- .conn
684+ let conn = store.conn.lock().await;
685+ let mut rows = conn
486686 .query(
487687 "SELECT password_hash FROM users WHERE id = ?1",
488688 turso::params![user.id.to_string()],
@@ -500,37 +700,38 @@ pub async fn change_password(
500700 if verify_password(new, &phc) {
501701 return Err(PasswordProblem::IsCurrent.into());
502702 }
503- store
504- .conn
505- .execute(
506- "UPDATE users SET password_hash = ?1 WHERE id = ?2",
507- turso::params![hash_password(new)?, user.id.to_string()],
508- )
509- .await
510- .map_err(backend)?;
703+ conn.execute(
704+ "UPDATE users SET password_hash = ?1 WHERE id = ?2",
705+ turso::params![hash_password(new)?, user.id.to_string()],
706+ )
707+ .await
708+ .map_err(backend)?;
511709 Ok(())
512710 }
513711
514712 /// Looks a user up by email — the CLI's revoke path resolves names this way.
515713 pub async fn user_by_email(store: &Store, email: &str) -> Result<Option<User>> {
516- let mut rows = store
517- .conn
518- .query(
519- "SELECT id FROM users WHERE email = ?1 COLLATE NOCASE",
520- turso::params![email],
521- )
522- .await
523- .map_err(backend)?;
524- let Some(row) = rows.next().await.map_err(backend)? else {
525- return Ok(None);
714+ let id = {
715+ let conn = store.conn.lock().await;
716+ let mut rows = conn
717+ .query(
718+ "SELECT id FROM users WHERE email = ?1 COLLATE NOCASE",
719+ turso::params![email],
720+ )
721+ .await
722+ .map_err(backend)?;
723+ match rows.next().await.map_err(backend)? {
724+ Some(row) => UserId::from(store::text(&row, 0)?),
725+ None => return Ok(None),
726+ }
526727 };
527- let id = UserId::from(store::text(&row, 0)?);
728+ // The id is in hand; the full row's lookup locks for itself.
528729 user_by_id(store, &id).await
529730 }
530731
531732 pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> {
532- let mut rows = store
533- .conn
733+ let conn = store.conn.lock().await;
734+ let mut rows = conn
534735 .query(
535736 "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \
536737 FROM users WHERE id = ?1",
@@ -557,6 +758,7 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> {
557758 /// account should not exist" — the OIDC subject dies with it, and if the
558759 /// person returns they get a fresh one.
559760 pub async fn delete_user(store: &Store, user: &UserId) -> Result<()> {
761+ let conn = store.conn.lock().await;
560762 let id = user.to_string();
561763 for sql in [
562764 "DELETE FROM app_sessions WHERE user_id = ?1",
@@ -565,9 +767,7 @@ pub async fn delete_user(store: &Store, user: &UserId) -> Result<()> {
565767 "UPDATE invites SET invited_by = NULL WHERE invited_by = ?1",
566768 "DELETE FROM users WHERE id = ?1",
567769 ] {
568- store
569- .conn
570- .execute(sql, turso::params![id.clone()])
770+ conn.execute(sql, turso::params![id.clone()])
571771 .await
572772 .map_err(backend)?;
573773 }
@@ -576,8 +776,8 @@ pub async fn delete_user(store: &Store, user: &UserId) -> Result<()> {
576776
577777 /// Every user, oldest first — the admin panel's roster.
578778 pub async fn list_users(store: &Store) -> Result<Vec<User>> {
579- let mut rows = store
580- .conn
779+ let conn = store.conn.lock().await;
780+ let mut rows = conn
581781 .query(
582782 "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \
583783 FROM users ORDER BY created_at",
@@ -604,28 +804,26 @@ pub async fn list_users(store: &Store) -> Result<Vec<User>> {
604804 /// sessions resolve to nobody, and introspection says inactive — every door
605805 /// closes on the same flag.
606806 pub async fn set_disabled(store: &Store, user: &UserId, disabled: bool) -> Result<()> {
607- store
608- .conn
609- .execute(
610- "UPDATE users SET disabled = ?1 WHERE id = ?2",
611- turso::params![disabled as i64, user.to_string()],
612- )
613- .await
614- .map_err(backend)?;
807+ let conn = store.conn.lock().await;
808+ conn.execute(
809+ "UPDATE users SET disabled = ?1 WHERE id = ?2",
810+ turso::params![disabled as i64, user.to_string()],
811+ )
812+ .await
813+ .map_err(backend)?;
615814 Ok(())
616815 }
617816
618817 /// Grants or revokes im's admin flag. Never crosses a token — this is im's
619818 /// own panel, not a claim apps ever see.
620819 pub async fn set_admin(store: &Store, user: &UserId, admin: bool) -> Result<()> {
621- store
622- .conn
623- .execute(
624- "UPDATE users SET admin = ?1 WHERE id = ?2",
625- turso::params![admin as i64, user.to_string()],
626- )
627- .await
628- .map_err(backend)?;
820+ let conn = store.conn.lock().await;
821+ conn.execute(
822+ "UPDATE users SET admin = ?1 WHERE id = ?2",
823+ turso::params![admin as i64, user.to_string()],
824+ )
825+ .await
826+ .map_err(backend)?;
629827 Ok(())
630828 }
631829
@@ -845,4 +1043,91 @@ mod tests {
8451043 .is_ok()
8461044 );
8471045 }
1046+
1047+ #[tokio::test]
1048+ async fn a_second_reset_link_kills_the_first() {
1049+ let store = fixture().await;
1050+ let invite = create_invite(&store, "ann@example.com", None, false)
1051+ .await
1052+ .unwrap();
1053+ let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv")
1054+ .await
1055+ .unwrap();
1056+ let session = crate::sessions::create_session(&store, &user.id)
1057+ .await
1058+ .unwrap();
1059+
1060+ // No account, no link — and nothing learned.
1061+ assert!(
1062+ create_reset(&store, "nobody@example.com")
1063+ .await
1064+ .unwrap()
1065+ .is_none()
1066+ );
1067+
1068+ let first = create_reset(&store, "ann@example.com")
1069+ .await
1070+ .unwrap()
1071+ .unwrap();
1072+ let second = create_reset(&store, "ann@example.com")
1073+ .await
1074+ .unwrap()
1075+ .unwrap();
1076+ // The first mail's link died the moment the second was minted.
1077+ assert!(matches!(
1078+ redeem_reset(&store, first.expose(), "Xk9#mQ2vLpR7").await,
1079+ Err(AccountError::ResetInvalid)
1080+ ));
1081+
1082+ let changed = redeem_reset(&store, second.expose(), "Xk9#mQ2vLpR7")
1083+ .await
1084+ .unwrap();
1085+ assert_eq!(changed.id, user.id);
1086+ // Spent links cannot be replayed, and the old password's sessions
1087+ // died with the change.
1088+ assert!(matches!(
1089+ redeem_reset(&store, second.expose(), "an0ther!Pass99").await,
1090+ Err(AccountError::ResetInvalid)
1091+ ));
1092+ assert!(
1093+ crate::sessions::resolve_session(&store, session.expose())
1094+ .await
1095+ .unwrap()
1096+ .is_none()
1097+ );
1098+ assert!(
1099+ verify_login(&store, "ann@example.com", "Xk9#mQ2vLpR7")
1100+ .await
1101+ .is_ok()
1102+ );
1103+ }
1104+
1105+ #[tokio::test]
1106+ async fn rate_limit_blocks_and_success_clears() {
1107+ let store = fixture().await;
1108+ crate::settings::set_policy(
1109+ &store,
1110+ &crate::settings::Policy {
1111+ login_attempts_per_hour: 3,
1112+ ..Default::default()
1113+ },
1114+ )
1115+ .await
1116+ .unwrap();
1117+
1118+ assert!(!login_blocked(&store, "ann@example.com").await.unwrap());
1119+ for _ in 0..3 {
1120+ record_login_failure(&store, "ann@example.com")
1121+ .await
1122+ .unwrap();
1123+ }
1124+ assert!(login_blocked(&store, "ann@example.com").await.unwrap());
1125+ // A different address is untouched.
1126+ assert!(!login_blocked(&store, "bob@example.com").await.unwrap());
1127+
1128+ clear_login_failures(&store, "ann@example.com")
1129+ .await
1130+ .unwrap();
1131+ assert!(!login_blocked(&store, "ann@example.com").await.unwrap());
1132+ }
8481133 }
crates/im-core/src/events.rsmodified+4 -4
@@ -17,8 +17,8 @@ pub struct Event {
1717 /// Appends an event. Never fails the caller's operation: a log that cannot
1818 /// be written is printed, not propagated.
1919 pub async fn log(store: &Store, kind: &str, actor: Option<&str>, detail: Option<&str>) {
20- let outcome = store
21- .conn
20+ let conn = store.conn.lock().await;
21+ let outcome = conn
2222 .execute(
2323 "INSERT INTO events (id, at, kind, actor, detail) VALUES (?1, ?2, ?3, ?4, ?5)",
2424 turso::params![
@@ -37,8 +37,8 @@ pub async fn log(store: &Store, kind: &str, actor: Option<&str>, detail: Option<
3737
3838 /// Newest-first page of the log for the admin panel.
3939 pub async fn list(store: &Store, limit: i64) -> Result<Vec<Event>> {
40- let mut rows = store
41- .conn
40+ let conn = store.conn.lock().await;
41+ let mut rows = conn
4242 .query(
4343 "SELECT id, at, kind, actor, detail FROM events ORDER BY at DESC, id DESC LIMIT ?1",
4444 turso::params![limit],
crates/im-core/src/keys.rsmodified+17 -19
@@ -19,8 +19,8 @@ use crate::store::{self, Result, Store, StoreError, backend};
1919 /// `kid` is a fingerprint of the public half, so a key's id is stable across
2020 /// restarts and a JWKS consumer can match header to key without guessing.
2121 pub async fn active_signing_key(store: &Store) -> Result<(String, RsaPrivateKey)> {
22- let mut rows = store
23- .conn
22+ let conn = store.conn.lock().await;
23+ let mut rows = conn
2424 .query(
2525 "SELECT kid, private_der_enc FROM signing_keys WHERE active = 1 \
2626 ORDER BY created_at DESC LIMIT 1",
@@ -53,20 +53,18 @@ pub async fn active_signing_key(store: &Store) -> Result<(String, RsaPrivateKey)
5353 .as_bytes()
5454 .to_vec();
5555 let kid = kid_of(&public_der);
56- store
57- .conn
58- .execute(
59- "INSERT INTO signing_keys (kid, private_der_enc, public_der, created_at) \
56+ conn.execute(
57+ "INSERT INTO signing_keys (kid, private_der_enc, public_der, created_at) \
6058 VALUES (?1, ?2, ?3, ?4)",
61- turso::params![
62- kid.clone(),
63- secret::seal(store.key(), &private_der),
64- public_der,
65- store::stamp(store::now())?,
66- ],
67- )
68- .await
69- .map_err(backend)?;
59+ turso::params![
60+ kid.clone(),
61+ secret::seal(store.key(), &private_der),
62+ public_der,
63+ store::stamp(store::now())?,
64+ ],
65+ )
66+ .await
67+ .map_err(backend)?;
7068 Ok((kid, key))
7169 }
7270
@@ -77,9 +75,9 @@ fn kid_of(public_der: &[u8]) -> String {
7775
7876 /// Every active public key as a JWKS document.
7977 pub async fn jwks(store: &Store) -> Result<serde_json::Value> {
78+ let conn = store.conn.lock().await;
8079 use base64::Engine;
81- let mut rows = store
82- .conn
80+ let mut rows = conn
8381 .query(
8482 "SELECT kid, public_der FROM signing_keys WHERE active = 1 ORDER BY created_at",
8583 (),
@@ -107,8 +105,8 @@ pub async fn jwks(store: &Store) -> Result<serde_json::Value> {
107105
108106 /// The public half of an active key, by id — what JWT verification looks up.
109107 pub async fn public_key_by_kid(store: &Store, kid: &str) -> Result<Option<RsaPublicKey>> {
110- let mut rows = store
111- .conn
108+ let conn = store.conn.lock().await;
109+ let mut rows = conn
112110 .query(
113111 "SELECT public_der FROM signing_keys WHERE kid = ?1 AND active = 1",
114112 turso::params![kid],
crates/im-core/src/oidc.rsmodified+129 -132
@@ -61,31 +61,30 @@ pub async fn create_client(
6161 name: &str,
6262 redirect_uris: Vec<String>,
6363 ) -> Result<(ClientId, Token)> {
64+ let conn = store.conn.lock().await;
6465 let id = ClientId::mint();
6566 let secret = Token::mint();
66- store
67- .conn
68- .execute(
69- "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \
67+ conn.execute(
68+ "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \
7069 VALUES (?1, ?2, ?3, ?4, ?5)",
71- turso::params![
72- id.to_string(),
73- name,
74- secret.hash(),
75- serde_json::to_string(&redirect_uris)
76- .map_err(|e| StoreError::Corrupt(format!("redirect_uris: {e}")))?,
77- store::stamp(store::now())?,
78- ],
79- )
80- .await
81- .map_err(backend)?;
70+ turso::params![
71+ id.to_string(),
72+ name,
73+ secret.hash(),
74+ serde_json::to_string(&redirect_uris)
75+ .map_err(|e| StoreError::Corrupt(format!("redirect_uris: {e}")))?,
76+ store::stamp(store::now())?,
77+ ],
78+ )
79+ .await
80+ .map_err(backend)?;
8281 Ok((id, secret))
8382 }
8483
8584 /// Looks a client up by its public id.
8685 pub async fn client_by_id(store: &Store, client_id: &str) -> Result<Option<OidcClient>> {
87- let mut rows = store
88- .conn
86+ let conn = store.conn.lock().await;
87+ let mut rows = conn
8988 .query(
9089 "SELECT client_id, name, secret_hash, redirect_uris, created_at \
9190 FROM oidc_clients WHERE client_id = ?1",
@@ -131,9 +130,9 @@ pub async fn create_auth_code(
131130 challenge: &str,
132131 session_hash: &str,
133132 ) -> Result<Token> {
133+ let conn = store.conn.lock().await;
134134 let code = Token::mint();
135- store
136- .conn
135+ conn
137136 .execute(
138137 "INSERT INTO auth_codes \
139138 (code_hash, client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, expires_at) \
@@ -158,15 +157,11 @@ pub async fn create_auth_code(
158157 /// `consumed_at` stamp run inside one immediate transaction, so two parallel
159158 /// exchanges of the same code cannot both succeed.
160159 pub async fn consume_auth_code(store: &Store, code: &str) -> Result<Option<AuthCode>> {
160+ let conn = store.conn.lock().await;
161161 let hash = hash_token(code);
162- store
163- .conn
164- .execute("BEGIN IMMEDIATE", ())
165- .await
166- .map_err(backend)?;
162+ conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
167163 let outcome = async {
168- let mut rows = store
169- .conn
164+ let mut rows = conn
170165 .query(
171166 "SELECT client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, \
172167 expires_at, consumed_at FROM auth_codes WHERE code_hash = ?1",
@@ -183,14 +178,12 @@ pub async fn consume_auth_code(store: &Store, code: &str) -> Result<Option<AuthC
183178 if store::parse_stamp(&store::text(&row, 6)?)? < store::now() {
184179 return Ok(None);
185180 }
186- store
187- .conn
188- .execute(
189- "UPDATE auth_codes SET consumed_at = ?1 WHERE code_hash = ?2",
190- turso::params![store::stamp(store::now())?, hash],
191- )
192- .await
193- .map_err(backend)?;
181+ conn.execute(
182+ "UPDATE auth_codes SET consumed_at = ?1 WHERE code_hash = ?2",
183+ turso::params![store::stamp(store::now())?, hash],
184+ )
185+ .await
186+ .map_err(backend)?;
194187 Ok(Some(AuthCode {
195188 client_id: ClientId::from(store::text(&row, 0)?),
196189 user_id: UserId::from(store::text(&row, 1)?),
@@ -204,11 +197,11 @@ pub async fn consume_auth_code(store: &Store, code: &str) -> Result<Option<AuthC
204197 .await;
205198 match outcome {
206199 Ok(found) => {
207- store.conn.execute("COMMIT", ()).await.map_err(backend)?;
200+ conn.execute("COMMIT", ()).await.map_err(backend)?;
208201 Ok(found)
209202 }
210203 Err(e) => {
211- let _ = store.conn.execute("ROLLBACK", ()).await;
204+ let _ = conn.execute("ROLLBACK", ()).await;
212205 Err(e)
213206 }
214207 }
@@ -226,23 +219,22 @@ pub async fn issue_refresh(
226219 client_id: &ClientId,
227220 session_hash: &str,
228221 ) -> Result<Token> {
222+ let conn = store.conn.lock().await;
229223 let token = Token::mint();
230- store
231- .conn
232- .execute(
233- "INSERT INTO refresh_tokens \
224+ conn.execute(
225+ "INSERT INTO refresh_tokens \
234226 (token_hash, user_id, client_id, session_hash, expires_at) \
235227 VALUES (?1, ?2, ?3, ?4, ?5)",
236- turso::params![
237- token.hash(),
238- user.to_string(),
239- client_id.to_string(),
240- session_hash,
241- store::stamp(store::now() + time::Duration::days(REFRESH_DAYS))?,
242- ],
243- )
244- .await
245- .map_err(backend)?;
228+ turso::params![
229+ token.hash(),
230+ user.to_string(),
231+ client_id.to_string(),
232+ session_hash,
233+ store::stamp(store::now() + time::Duration::days(REFRESH_DAYS))?,
234+ ],
235+ )
236+ .await
237+ .map_err(backend)?;
246238 Ok(token)
247239 }
248240
@@ -251,15 +243,11 @@ pub async fn issue_refresh(
251243 /// come back. `None` for unknown, expired, or revoked tokens — and for tokens
252244 /// whose central session is gone, which is what makes SSO logout global.
253245 pub async fn rotate_refresh(store: &Store, token: &str) -> Result<Option<(Token, RefreshToken)>> {
246+ let conn = store.conn.lock().await;
254247 let hash = hash_token(token);
255- store
256- .conn
257- .execute("BEGIN IMMEDIATE", ())
258- .await
259- .map_err(backend)?;
248+ conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
260249 let outcome = async {
261- let mut rows = store
262- .conn
250+ let mut rows = conn
263251 .query(
264252 "SELECT user_id, client_id, session_hash, expires_at, revoked_at \
265253 FROM refresh_tokens WHERE token_hash = ?1",
@@ -283,8 +271,7 @@ pub async fn rotate_refresh(store: &Store, token: &str) -> Result<Option<(Token,
283271 expires_at: store::parse_stamp(&store::text(&row, 3)?)?,
284272 };
285273 // The session that minted this token must still be alive.
286- let mut sessions = store
287- .conn
274+ let mut sessions = conn
288275 .query(
289276 "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1",
290277 turso::params![record.session_hash.clone()],
@@ -302,31 +289,39 @@ pub async fn rotate_refresh(store: &Store, token: &str) -> Result<Option<(Token,
302289 }
303290
304291 let now = store::stamp(store::now())?;
305- store
306- .conn
307- .execute(
308- "UPDATE refresh_tokens SET revoked_at = ?1 WHERE token_hash = ?2",
309- turso::params![now.clone(), hash.clone()],
310- )
311- .await
312- .map_err(backend)?;
313- let fresh = issue_refresh(
314- store,
315- &record.user_id,
316- &record.client_id,
317- &record.session_hash,
292+ conn.execute(
293+ "UPDATE refresh_tokens SET revoked_at = ?1 WHERE token_hash = ?2",
294+ turso::params![now.clone(), hash.clone()],
318295 )
319- .await?;
296+ .await
297+ .map_err(backend)?;
298+ // Inlined from `issue_refresh`: the transaction already holds the
299+ // connection, and the helper locks for itself.
300+ let fresh = Token::mint();
301+ conn.execute(
302+ "INSERT INTO refresh_tokens \
303+ (token_hash, user_id, client_id, session_hash, expires_at) \
304+ VALUES (?1, ?2, ?3, ?4, ?5)",
305+ turso::params![
306+ fresh.hash(),
307+ record.user_id.to_string(),
308+ record.client_id.to_string(),
309+ record.session_hash.clone(),
310+ store::stamp(store::now() + time::Duration::days(REFRESH_DAYS))?,
311+ ],
312+ )
313+ .await
314+ .map_err(backend)?;
320315 Ok(Some((fresh, record)))
321316 }
322317 .await;
323318 match outcome {
324319 Ok(found) => {
325- store.conn.execute("COMMIT", ()).await.map_err(backend)?;
320+ conn.execute("COMMIT", ()).await.map_err(backend)?;
326321 Ok(found)
327322 }
328323 Err(e) => {
329- let _ = store.conn.execute("ROLLBACK", ()).await;
324+ let _ = conn.execute("ROLLBACK", ()).await;
330325 Err(e)
331326 }
332327 }
@@ -428,25 +423,24 @@ pub async fn issue_app_session(
428423 client_id: &ClientId,
429424 session_hash: &str,
430425 ) -> Result<Token> {
426+ let conn = store.conn.lock().await;
431427 let token = Token::mint();
432428 let now = store::now();
433- store
434- .conn
435- .execute(
436- "INSERT INTO app_sessions \
429+ conn.execute(
430+ "INSERT INTO app_sessions \
437431 (token_hash, user_id, client_id, session_hash, created_at, expires_at) \
438432 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
439- turso::params![
440- token.hash(),
441- user.to_string(),
442- client_id.to_string(),
443- session_hash,
444- store::stamp(now)?,
445- store::stamp(now + time::Duration::days(APP_SESSION_DAYS))?,
446- ],
447- )
448- .await
449- .map_err(backend)?;
433+ turso::params![
434+ token.hash(),
435+ user.to_string(),
436+ client_id.to_string(),
437+ session_hash,
438+ store::stamp(now)?,
439+ store::stamp(now + time::Duration::days(APP_SESSION_DAYS))?,
440+ ],
441+ )
442+ .await
443+ .map_err(backend)?;
450444 Ok(token)
451445 }
452446
@@ -458,49 +452,52 @@ pub async fn introspect_app_session(
458452 token: &str,
459453 client_id: &str,
460454 ) -> Result<Option<serde_json::Value>> {
461- let mut rows = store
462- .conn
463- .query(
464- "SELECT user_id, client_id, session_hash, expires_at, revoked_at \
465- FROM app_sessions WHERE token_hash = ?1",
466- turso::params![hash_token(token)],
467- )
468- .await
469- .map_err(backend)?;
470- let Some(row) = rows.next().await.map_err(backend)? else {
471- return Ok(None);
472- };
473- if store::opt_text(&row, 4)?.is_some() {
474- return Ok(None);
475- }
476- let expires = store::parse_stamp(&store::text(&row, 3)?)?;
477- if expires < store::now() {
478- return Ok(None);
479- }
480- if store::text(&row, 1)? != client_id {
481- return Ok(None);
482- }
483- // The central session must still be alive — this is what makes admin
484- // revocation immediate.
485- let session_hash = store::text(&row, 2)?;
486- let mut sessions = store
487- .conn
488- .query(
489- "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1",
490- turso::params![session_hash],
491- )
492- .await
493- .map_err(backend)?;
494- let Some(session) = sessions.next().await.map_err(backend)? else {
495- return Ok(None);
455+ // Both rows are read under one short-held guard; the user lookup locks
456+ // for itself after it drops.
457+ let (user_id, expires) = {
458+ let conn = store.conn.lock().await;
459+ let mut rows = conn
460+ .query(
461+ "SELECT user_id, client_id, session_hash, expires_at, revoked_at \
462+ FROM app_sessions WHERE token_hash = ?1",
463+ turso::params![hash_token(token)],
464+ )
465+ .await
466+ .map_err(backend)?;
467+ let Some(row) = rows.next().await.map_err(backend)? else {
468+ return Ok(None);
469+ };
470+ if store::opt_text(&row, 4)?.is_some() {
471+ return Ok(None);
472+ }
473+ let expires = store::parse_stamp(&store::text(&row, 3)?)?;
474+ if expires < store::now() {
475+ return Ok(None);
476+ }
477+ if store::text(&row, 1)? != client_id {
478+ return Ok(None);
479+ }
480+ // The central session must still be alive — this is what makes admin
481+ // revocation immediate.
482+ let session_hash = store::text(&row, 2)?;
483+ let mut sessions = conn
484+ .query(
485+ "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1",
486+ turso::params![session_hash],
487+ )
488+ .await
489+ .map_err(backend)?;
490+ let Some(session) = sessions.next().await.map_err(backend)? else {
491+ return Ok(None);
492+ };
493+ if store::opt_text(&session, 1)?.is_some() {
494+ return Ok(None);
495+ }
496+ if store::parse_stamp(&store::text(&session, 0)?)? < store::now() {
497+ return Ok(None);
498+ }
499+ (UserId::from(store::text(&row, 0)?), expires)
496500 };
497- if store::opt_text(&session, 1)?.is_some() {
498- return Ok(None);
499- }
500- if store::parse_stamp(&store::text(&session, 0)?)? < store::now() {
501- return Ok(None);
502- }
503- let user_id = UserId::from(store::text(&row, 0)?);
504501 let Some(user) = crate::accounts::user_by_id(store, &user_id).await? else {
505502 return Ok(None);
506503 };
crates/im-core/src/sessions.rsmodified+116 -111
@@ -9,7 +9,9 @@ use crate::accounts::{Token, hash_token};
99 use crate::model::{User, UserId};
1010 use crate::store::{self, Result, Store, backend};
1111
12-/// How long a central session lives.
12+/// The default central-session lifetime. The panel's Settings section can
13+/// move it; the constant stays the fresh-database answer and the cookie's
14+/// Max-Age (which is set before the store is in hand).
1315 pub const SESSION_DAYS: i64 = 30;
1416
1517 /// Creates a session for `user`, returning the raw cookie token. The row
@@ -17,44 +19,50 @@ pub const SESSION_DAYS: i64 = 30;
1719 pub async fn create_session(store: &Store, user: &UserId) -> Result<Token> {
1820 let token = Token::mint();
1921 let now = store::now();
20- store
21- .conn
22- .execute(
23- "INSERT INTO sessions (token_hash, user_id, created_at, expires_at) \
22+ let days = crate::settings::policy(store).await?.session_days;
23+ let conn = store.conn.lock().await;
24+ conn.execute(
25+ "INSERT INTO sessions (token_hash, user_id, created_at, expires_at) \
2426 VALUES (?1, ?2, ?3, ?4)",
25- turso::params![
26- token.hash(),
27- user.to_string(),
28- store::stamp(now)?,
29- store::stamp(now + time::Duration::days(SESSION_DAYS))?,
30- ],
31- )
32- .await
33- .map_err(backend)?;
27+ turso::params![
28+ token.hash(),
29+ user.to_string(),
30+ store::stamp(now)?,
31+ store::stamp(now + time::Duration::days(days))?,
32+ ],
33+ )
34+ .await
35+ .map_err(backend)?;
3436 Ok(token)
3537 }
3638
3739 /// Resolves a raw cookie token to its user. `None` for unknown, expired,
3840 /// revoked, or disabled — every one of them is "please log in again".
3941 pub async fn resolve_session(store: &Store, token: &str) -> Result<Option<User>> {
40- let mut rows = store
41- .conn
42- .query(
43- "SELECT user_id, expires_at, revoked_at FROM sessions WHERE token_hash = ?1",
44- turso::params![hash_token(token)],
45- )
46- .await
47- .map_err(backend)?;
48- let Some(row) = rows.next().await.map_err(backend)? else {
49- return Ok(None);
42+ // The session row is read under a short-held guard; the user lookup locks
43+ // for itself once the guard is dropped.
44+ let found = {
45+ let conn = store.conn.lock().await;
46+ let mut rows = conn
47+ .query(
48+ "SELECT user_id, expires_at, revoked_at FROM sessions WHERE token_hash = ?1",
49+ turso::params![hash_token(token)],
50+ )
51+ .await
52+ .map_err(backend)?;
53+ match rows.next().await.map_err(backend)? {
54+ Some(row)
55+ if store::opt_text(&row, 2)?.is_none()
56+ && store::parse_stamp(&store::text(&row, 1)?)? >= store::now() =>
57+ {
58+ Some(UserId::from(store::text(&row, 0)?))
59+ }
60+ _ => None,
61+ }
5062 };
51- if store::opt_text(&row, 2)?.is_some() {
52- return Ok(None);
53- }
54- if store::parse_stamp(&store::text(&row, 1)?)? < store::now() {
63+ let Some(user_id) = found else {
5564 return Ok(None);
56- }
57- let user_id = UserId::from(store::text(&row, 0)?);
65+ };
5866 match crate::accounts::user_by_id(store, &user_id).await? {
5967 Some(user) if !user.disabled => Ok(Some(user)),
6068 _ => Ok(None),
@@ -71,31 +79,26 @@ pub async fn revoke_session(store: &Store, token: &str) -> Result<()> {
7179 /// The hash-level half of [`revoke_session`], shared with the admin's
7280 /// revoke-everything below.
7381 pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()> {
82+ let conn = store.conn.lock().await;
7483 let now = store::stamp(store::now())?;
75- store
76- .conn
77- .execute(
78- "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL",
79- turso::params![now.clone(), hash],
80- )
81- .await
82- .map_err(backend)?;
83- store
84- .conn
85- .execute(
86- "UPDATE refresh_tokens SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL",
87- turso::params![now.clone(), hash],
88- )
89- .await
90- .map_err(backend)?;
91- store
92- .conn
93- .execute(
94- "UPDATE app_sessions SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL",
95- turso::params![now, hash],
96- )
97- .await
98- .map_err(backend)?;
84+ conn.execute(
85+ "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL",
86+ turso::params![now.clone(), hash],
87+ )
88+ .await
89+ .map_err(backend)?;
90+ conn.execute(
91+ "UPDATE refresh_tokens SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL",
92+ turso::params![now.clone(), hash],
93+ )
94+ .await
95+ .map_err(backend)?;
96+ conn.execute(
97+ "UPDATE app_sessions SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL",
98+ turso::params![now, hash],
99+ )
100+ .await
101+ .map_err(backend)?;
99102 Ok(())
100103 }
101104
@@ -104,18 +107,23 @@ pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()>
104107 /// live app session down with them. Introspection is per-request, so the
105108 /// next call any app makes on their behalf comes back inactive — no ghost.
106109 pub async fn revoke_user_sessions(store: &Store, user: &UserId) -> Result<u64> {
107- let mut rows = store
108- .conn
109- .query(
110- "SELECT token_hash FROM sessions WHERE user_id = ?1 AND revoked_at IS NULL",
111- turso::params![user.to_string()],
112- )
113- .await
114- .map_err(backend)?;
115- let mut hashes = Vec::new();
116- while let Some(row) = rows.next().await.map_err(backend)? {
117- hashes.push(store::text(&row, 0)?);
118- }
110+ // Read under a short guard; the per-session revokes and the final sweep
111+ // lock for themselves.
112+ let hashes = {
113+ let conn = store.conn.lock().await;
114+ let mut rows = conn
115+ .query(
116+ "SELECT token_hash FROM sessions WHERE user_id = ?1 AND revoked_at IS NULL",
117+ turso::params![user.to_string()],
118+ )
119+ .await
120+ .map_err(backend)?;
121+ let mut hashes = Vec::new();
122+ while let Some(row) = rows.next().await.map_err(backend)? {
123+ hashes.push(store::text(&row, 0)?);
124+ }
125+ hashes
126+ };
119127 let count = hashes.len() as u64;
120128 for hash in hashes {
121129 revoke_session_hash(store, &hash).await?;
@@ -123,22 +131,19 @@ pub async fn revoke_user_sessions(store: &Store, user: &UserId) -> Result<u64> {
123131 // Sessions already revoked earlier still own live app sessions; sweep
124132 // those too so nothing outlives the person being signed out.
125133 let now = store::stamp(store::now())?;
126- store
127- .conn
128- .execute(
129- "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL",
130- turso::params![now.clone(), user.to_string()],
131- )
132- .await
133- .map_err(backend)?;
134- store
135- .conn
136- .execute(
137- "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL",
138- turso::params![now, user.to_string()],
139- )
140- .await
141- .map_err(backend)?;
134+ let conn = store.conn.lock().await;
135+ conn.execute(
136+ "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL",
137+ turso::params![now.clone(), user.to_string()],
138+ )
139+ .await
140+ .map_err(backend)?;
141+ conn.execute(
142+ "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL",
143+ turso::params![now, user.to_string()],
144+ )
145+ .await
146+ .map_err(backend)?;
142147 Ok(count)
143148 }
144149
@@ -151,19 +156,22 @@ pub async fn revoke_user_sessions_except(
151156 keep_token: &str,
152157 ) -> Result<u64> {
153158 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- }
159+ let hashes = {
160+ let conn = store.conn.lock().await;
161+ let mut rows = conn
162+ .query(
163+ "SELECT token_hash FROM sessions \
164+ WHERE user_id = ?1 AND revoked_at IS NULL AND token_hash != ?2",
165+ turso::params![user.to_string(), keep.clone()],
166+ )
167+ .await
168+ .map_err(backend)?;
169+ let mut hashes = Vec::new();
170+ while let Some(row) = rows.next().await.map_err(backend)? {
171+ hashes.push(store::text(&row, 0)?);
172+ }
173+ hashes
174+ };
167175 let count = hashes.len() as u64;
168176 for hash in &hashes {
169177 revoke_session_hash(store, hash).await?;
@@ -171,24 +179,21 @@ pub async fn revoke_user_sessions_except(
171179 // The kept session is the only one allowed to keep its app sessions and
172180 // refresh tokens; everything else of this user's is swept.
173181 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 \
182+ let conn = store.conn.lock().await;
183+ conn.execute(
184+ "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \
178185 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 \
186+ turso::params![now.clone(), user.to_string(), keep.clone()],
187+ )
188+ .await
189+ .map_err(backend)?;
190+ conn.execute(
191+ "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \
187192 AND session_hash != ?3",
188- turso::params![now, user.to_string(), keep],
189- )
190- .await
191- .map_err(backend)?;
193+ turso::params![now, user.to_string(), keep],
194+ )
195+ .await
196+ .map_err(backend)?;
192197 Ok(count)
193198 }
194199
crates/im-core/src/settings.rsmodified+134 -16
@@ -38,8 +38,8 @@ impl Smtp {
3838 }
3939
4040 async fn get(store: &Store, key: &str) -> Result<Option<String>> {
41- let mut rows = store
42- .conn
41+ let conn = store.conn.lock().await;
42+ let mut rows = conn
4343 .query(
4444 "SELECT value FROM settings WHERE key = ?1",
4545 turso::params![key],
@@ -53,13 +53,20 @@ async fn get(store: &Store, key: &str) -> Result<Option<String>> {
5353 }
5454
5555 async fn set(store: &Store, key: &str, value: &str) -> Result<()> {
56- store
57- .conn
58- .execute(
59- "INSERT INTO settings (key, value) VALUES (?1, ?2) \
56+ let conn = store.conn.lock().await;
57+ conn.execute(
58+ "INSERT INTO settings (key, value) VALUES (?1, ?2) \
6059 ON CONFLICT(key) DO UPDATE SET value = excluded.value",
61- turso::params![key, value],
62- )
60+ turso::params![key, value],
61+ )
62+ .await
63+ .map_err(backend)?;
64+ Ok(())
65+}
66+
67+async fn remove(store: &Store, key: &str) -> Result<()> {
68+ let conn = store.conn.lock().await;
69+ conn.execute("DELETE FROM settings WHERE key = ?1", turso::params![key])
6370 .await
6471 .map_err(backend)?;
6572 Ok(())
@@ -177,10 +184,9 @@ pub async fn last_check(store: &Store) -> Result<Option<SenderCheck>> {
177184 /// A saved sender cannot borrow the last probe's verdict: the check is
178185 /// cleared on every settings write, like izlek's.
179186 async fn clear_check(store: &Store) -> Result<()> {
187+ let conn = store.conn.lock().await;
180188 for key in ["smtp_check_at", "smtp_check_ms", "smtp_check_error"] {
181- store
182- .conn
183- .execute("DELETE FROM settings WHERE key = ?1", turso::params![key])
189+ conn.execute("DELETE FROM settings WHERE key = ?1", turso::params![key])
184190 .await
185191 .map_err(backend)?;
186192 }
@@ -201,11 +207,7 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res
201207 "smtp_check_ms",
202208 "smtp_check_error",
203209 ] {
204- store
205- .conn
206- .execute("DELETE FROM settings WHERE key = ?1", turso::params![key])
207- .await
208- .map_err(backend)?;
210+ remove(store, key).await?;
209211 }
210212 return Ok(());
211213 }
@@ -229,6 +231,122 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res
229231 Ok(())
230232 }
231233
234+/// The panel-tunable policy, with the defaults the code was born with. Every
235+/// reader falls back to the default when the key is absent, so a fresh
236+/// database behaves exactly like the pre-settings build.
237+#[derive(Debug, Clone, PartialEq, Eq)]
238+pub struct Policy {
239+ pub invite_days: i64,
240+ pub session_days: i64,
241+ pub pending_minutes: i64,
242+ pub reset_minutes: i64,
243+ pub login_attempts_per_hour: i64,
244+}
245+
246+impl Default for Policy {
247+ fn default() -> Self {
248+ Self {
249+ invite_days: 7,
250+ session_days: 30,
251+ pending_minutes: 10,
252+ reset_minutes: 60,
253+ login_attempts_per_hour: 10,
254+ }
255+ }
256+}
257+
258+async fn number(store: &Store, key: &str, default: i64) -> Result<i64> {
259+ Ok(get(store, key)
260+ .await?
261+ .and_then(|raw| raw.parse().ok())
262+ .unwrap_or(default))
263+}
264+
265+/// The policy as stored, defaults filled in.
266+pub async fn policy(store: &Store) -> Result<Policy> {
267+ let defaults = Policy::default();
268+ Ok(Policy {
269+ invite_days: number(store, "invite_days", defaults.invite_days).await?,
270+ session_days: number(store, "session_days", defaults.session_days).await?,
271+ pending_minutes: number(store, "pending_minutes", defaults.pending_minutes).await?,
272+ reset_minutes: number(store, "reset_minutes", defaults.reset_minutes).await?,
273+ login_attempts_per_hour: number(
274+ store,
275+ "login_attempts_per_hour",
276+ defaults.login_attempts_per_hour,
277+ )
278+ .await?,
279+ })
280+}
281+
282+/// Writes the policy. Values under one are refused by the panel before they
283+/// get here; zero or negative would be a door that never opens, so they are
284+/// clamped to the default rather than stored.
285+pub async fn set_policy(store: &Store, policy: &Policy) -> Result<()> {
286+ let defaults = Policy::default();
287+ let clamp = |value: i64, default: i64| if value >= 1 { value } else { default };
288+ set(
289+ store,
290+ "invite_days",
291+ &clamp(policy.invite_days, defaults.invite_days).to_string(),
292+ )
293+ .await?;
294+ set(
295+ store,
296+ "session_days",
297+ &clamp(policy.session_days, defaults.session_days).to_string(),
298+ )
299+ .await?;
300+ set(
301+ store,
302+ "pending_minutes",
303+ &clamp(policy.pending_minutes, defaults.pending_minutes).to_string(),
304+ )
305+ .await?;
306+ set(
307+ store,
308+ "reset_minutes",
309+ &clamp(policy.reset_minutes, defaults.reset_minutes).to_string(),
310+ )
311+ .await?;
312+ set(
313+ store,
314+ "login_attempts_per_hour",
315+ &clamp(
316+ policy.login_attempts_per_hour,
317+ defaults.login_attempts_per_hour,
318+ )
319+ .to_string(),
320+ )
321+ .await?;
322+ Ok(())
323+}
324+
325+/// Days an invite link stays valid.
326+pub async fn invite_days(store: &Store) -> Result<i64> {
327+ number(store, "invite_days", Policy::default().invite_days).await
328+}
329+
330+/// Minutes between password and second factor before the pending marker dies.
331+pub async fn pending_minutes(store: &Store) -> Result<i64> {
332+ number(store, "pending_minutes", Policy::default().pending_minutes).await
333+}
334+
335+/// Minutes a password-reset link stays valid.
336+pub async fn reset_minutes(store: &Store) -> Result<i64> {
337+ number(store, "reset_minutes", Policy::default().reset_minutes).await
338+}
339+
340+/// Failed sign-ins per address per hour before the door refuses to listen.
341+pub async fn login_attempts_per_hour(store: &Store) -> Result<i64> {
342+ number(
343+ store,
344+ "login_attempts_per_hour",
345+ Policy::default().login_attempts_per_hour,
346+ )
347+ .await
348+}
349+
232350 #[cfg(test)]
233351 mod tests {
234352 use super::*;
crates/im-core/src/store.rsmodified+25 -11
@@ -104,6 +104,18 @@ CREATE TABLE IF NOT EXISTS events (
104104 actor TEXT,
105105 detail TEXT
106106 );
107+CREATE TABLE IF NOT EXISTS reset_links (
108+ token TEXT PRIMARY KEY,
109+ user_id TEXT NOT NULL REFERENCES users(id),
110+ created_at TEXT NOT NULL,
111+ expires_at TEXT NOT NULL,
112+ used_at TEXT
113+);
114+CREATE TABLE IF NOT EXISTS login_attempts (
115+ key TEXT NOT NULL,
116+ at TEXT NOT NULL
117+);
118+CREATE INDEX IF NOT EXISTS login_attempts_key ON login_attempts(key, at);
107119 CREATE TABLE IF NOT EXISTS settings (
108120 key TEXT PRIMARY KEY,
109121 value TEXT NOT NULL
@@ -113,7 +125,7 @@ CREATE TABLE IF NOT EXISTS settings (
113125 /// One database handle with the at-rest key beside it. Turso is a
114126 /// single-writer engine; one connection per store, like izlek-core.
115127 pub struct Store {
116- pub(crate) conn: Connection,
128+ pub(crate) conn: tokio::sync::Mutex<Connection>,
117129 pub(crate) key: Key,
118130 }
119131
@@ -127,7 +139,7 @@ impl Store {
127139 let db = Builder::new_local(raw).build().await.map_err(backend)?;
128140 let conn = db.connect().map_err(backend)?;
129141 let store = Store {
130- conn,
142+ conn: tokio::sync::Mutex::new(conn),
131143 key: load_key(path)?,
132144 };
133145 store.migrate().await?;
@@ -136,15 +148,15 @@ impl Store {
136148
137149 /// Applies the schema inside one immediate transaction; safe to re-run.
138150 pub async fn migrate(&self) -> Result<()> {
139- self.conn
140- .execute("BEGIN IMMEDIATE", ())
141- .await
142- .map_err(backend)?;
143- if let Err(e) = self.conn.execute_batch(SCHEMA).await {
144- let _ = self.conn.execute("ROLLBACK", ()).await;
151+ // One guard for the whole transaction — nothing interleaves with a
152+ // schema write.
153+ let conn = self.conn.lock().await;
154+ conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
155+ if let Err(e) = conn.execute_batch(SCHEMA).await {
156+ let _ = conn.execute("ROLLBACK", ()).await;
145157 return Err(backend(e));
146158 }
147- self.conn.execute("COMMIT", ()).await.map_err(backend)?;
159+ conn.execute("COMMIT", ()).await.map_err(backend)?;
148160 Ok(())
149161 }
150162
@@ -217,8 +229,8 @@ mod tests {
217229 let store = Store::open(&path).await.unwrap();
218230 store.migrate().await.unwrap();
219231 store.migrate().await.unwrap();
220- let mut rows = store
221- .conn
232+ let conn = store.conn.lock().await;
233+ let mut rows = conn
222234 .query("SELECT name FROM sqlite_master WHERE type = 'table'", ())
223235 .await
224236 .unwrap();
@@ -234,6 +246,8 @@ mod tests {
234246 "auth_codes",
235247 "refresh_tokens",
236248 "signing_keys",
249+ "reset_links",
250+ "login_attempts",
237251 ] {
238252 assert!(tables.contains(&expected.to_string()), "missing {expected}");
239253 }
crates/im-core/src/totp.rsmodified+16 -18
@@ -84,28 +84,26 @@ pub fn verify_totp(secret: &[u8; 20], code: &str, at: OffsetDateTime) -> bool {
8484 /// Stores a freshly generated secret, sealed, unconfirmed until the user
8585 /// proves their app agrees (`confirm_totp`).
8686 pub async fn set_totp(store: &Store, user: &UserId, secret_bytes: &[u8; 20]) -> Result<()> {
87+ let conn = store.conn.lock().await;
8788 let sealed = secret::seal(store.key(), secret_bytes);
88- store
89- .conn
90- .execute(
91- "UPDATE users SET totp_secret = ?1, totp_confirmed = 0 WHERE id = ?2",
92- turso::params![sealed, user.to_string()],
93- )
94- .await
95- .map_err(backend)?;
89+ conn.execute(
90+ "UPDATE users SET totp_secret = ?1, totp_confirmed = 0 WHERE id = ?2",
91+ turso::params![sealed, user.to_string()],
92+ )
93+ .await
94+ .map_err(backend)?;
9695 Ok(())
9796 }
9897
9998 /// Marks the stored secret confirmed — called after one successful code.
10099 pub async fn confirm_totp(store: &Store, user: &UserId) -> Result<()> {
101- store
102- .conn
103- .execute(
104- "UPDATE users SET totp_confirmed = 1 WHERE id = ?1",
105- turso::params![user.to_string()],
106- )
107- .await
108- .map_err(backend)?;
100+ let conn = store.conn.lock().await;
101+ conn.execute(
102+ "UPDATE users SET totp_confirmed = 1 WHERE id = ?1",
103+ turso::params![user.to_string()],
104+ )
105+ .await
106+ .map_err(backend)?;
109107 Ok(())
110108 }
111109
@@ -113,8 +111,8 @@ pub async fn confirm_totp(store: &Store, user: &UserId) -> Result<()> {
113111 /// TOTP was never set up. A sealed value that no longer opens (wrong key,
114112 /// damaged ciphertext) reads as `None` — the user re-enrolls.
115113 pub async fn totp_secret(store: &Store, user: &UserId) -> Result<Option<([u8; 20], bool)>> {
116- let mut rows = store
117- .conn
114+ let conn = store.conn.lock().await;
115+ let mut rows = conn
118116 .query(
119117 "SELECT totp_secret, totp_confirmed FROM users WHERE id = ?1",
120118 turso::params![user.to_string()],
crates/im-web/assets/main.cssmodified+4 -0
@@ -548,9 +548,13 @@ body:has(.admin-shell) {
548548
549549 .admin-confirm {
550550 position: relative;
551+ display: inline-flex;
551552 }
552553 .admin-confirm summary {
553554 list-style: none;
555+ display: inline-flex;
556+ align-items: center;
557+ box-sizing: border-box;
554558 }
555559 .admin-confirm summary::-webkit-details-marker {
556560 display: none;
crates/im-web/src/admin.rsmodified+65 -0
@@ -135,6 +135,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
135135 ("account", "Account"),
136136 ("users", "Users"),
137137 ("mail", "Mail"),
138+ ("settings", "Settings"),
138139 ("logs", "Logs"),
139140 ]
140141 .into_iter()
@@ -149,6 +150,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
149150
150151 let section_html = match section.as_str() {
151152 "mail" => mail_section(cx).await?,
153+ "settings" => settings_section(cx).await?,
152154 "logs" => logs_section(cx).await?,
153155 "users" => users_section(cx, &me, invited.as_deref()).await?,
154156 _ => account_section(&me),
@@ -167,6 +169,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
167169 "password" => "Password changed — every other device is signed out.",
168170 "uninvited" => "Invite invalidated — the link is dead.",
169171 "deleted" => "Account deleted.",
172+ "settings" => "Settings saved.",
170173 _ => "Done.",
171174 }
172175 )),
@@ -344,6 +347,68 @@ async fn users_section(
344347 ))
345348 }
346349
350+/// The knobs the code shipped with, now the panel's: invite and reset link
351+/// lifetimes, the sign-in session's days, the pending marker's minutes, and
352+/// the sign-in failure ceiling. Same form skin as Mail.
353+async fn settings_section(cx: &Cx) -> Result<String, topcoat::Error> {
354+ let policy = settings::policy(&app(cx).store).await?;
355+ Ok(format!(
356+ r#"<div class="admin-card">
357+ <div class="auth-title">Settings</div>
358+ <div class="auth-sub">The rules identity lives by. They apply from the next invite, sign-in or link — nothing already minted is rewritten.</div>
359+ <form method="post" action="/admin/settings" class="admin-form">
360+ <label class="auth-field"><span class="auth-label">Invite link, days</span>
361+ <input class="auth-input auth-input-mono" type="number" name="invite_days" min="1" value="{}"></label>
362+ <label class="auth-field"><span class="auth-label">Sign-in session, days</span>
363+ <input class="auth-input auth-input-mono" type="number" name="session_days" min="1" value="{}"></label>
364+ <label class="auth-field"><span class="auth-label">Second-factor window, minutes</span>
365+ <input class="auth-input auth-input-mono" type="number" name="pending_minutes" min="1" value="{}"></label>
366+ <label class="auth-field"><span class="auth-label">Reset link, minutes</span>
367+ <input class="auth-input auth-input-mono" type="number" name="reset_minutes" min="1" value="{}"></label>
368+ <label class="auth-field"><span class="auth-label">Failed sign-ins per address per hour</span>
369+ <input class="auth-input auth-input-mono" type="number" name="login_attempts_per_hour" min="1" value="{}"></label>
370+ <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">Save</span></button>
371+ </form>
372+</div>"#,
373+ policy.invite_days,
374+ policy.session_days,
375+ policy.pending_minutes,
376+ policy.reset_minutes,
377+ policy.login_attempts_per_hour,
378+ ))
379+}
380+
381+#[derive(Deserialize)]
382+struct PolicyForm {
383+ invite_days: i64,
384+ session_days: i64,
385+ pending_minutes: i64,
386+ reset_minutes: i64,
387+ login_attempts_per_hour: i64,
388+}
389+
390+#[route(POST "/admin/settings")]
391+async fn settings_save(cx: &Cx, Form(input): Form<PolicyForm>) -> Result<Response> {
392+ let me = match require_admin(cx).await {
393+ Ok(me) => me,
394+ Err(redirect) => return Ok(redirect),
395+ };
396+ let store = &app(cx).store;
397+ settings::set_policy(
398+ store,
399+ &settings::Policy {
400+ invite_days: input.invite_days,
401+ session_days: input.session_days,
402+ pending_minutes: input.pending_minutes,
403+ reset_minutes: input.reset_minutes,
404+ login_attempts_per_hour: input.login_attempts_per_hour,
405+ },
406+ )
407+ .await?;
408+ server::log_event(cx, "settings_updated", Some(&me.email), None).await;
409+ back(cx, "settings", "&ok=settings")
410+}
411+
347412 async fn mail_section(cx: &Cx) -> Result<String, topcoat::Error> {
348413 let store = &app(cx).store;
349414 let smtp = settings::smtp(store).await?;
crates/im-web/src/auth.rsmodified+87 -6
@@ -55,10 +55,21 @@ pub struct LoginForm {
5555 async fn login(cx: &Cx, Form(input): Form<LoginForm>) -> Redirect {
5656 let back = safe_back(input.back.as_deref().unwrap_or("/")).to_string();
5757 let store = &server::app(cx).store;
58+ // The door stops listening after the panel's per-hour allowance of
59+ // failures. The refusal says nothing about which step refused, as always.
60+ let key = input.email.trim().to_lowercase();
61+ if accounts::login_blocked(store, &key).await? {
62+ server::log_event(cx, "login_limited", Some(&key), None).await;
63+ return see(format!(
64+ "/login?error=rate_limited&back={}",
65+ urlencode(&back)
66+ ));
67+ }
5868 match accounts::verify_login(store, &input.email, &input.password).await {
5969 Ok(user) if user.totp_confirmed => {
60- let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Login, back);
61- server::set_pending_cookie(cx, sealed);
70+ let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Login, back).await;
71+ server::set_pending_cookie(cx, sealed).await;
72+ let _ = accounts::clear_login_failures(store, &key).await;
6273 see("/login/totp".to_string())
6374 }
6475 Ok(user) => {
@@ -69,13 +80,15 @@ async fn login(cx: &Cx, Form(input): Form<LoginForm>) -> Redirect {
6980 let secret = im_core::totp::generate_secret();
7081 im_core::totp::set_totp(store, &user.id, &secret).await?;
7182 }
72- let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, back);
73- server::set_pending_cookie(cx, sealed);
83+ let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, back).await;
84+ server::set_pending_cookie(cx, sealed).await;
85+ let _ = accounts::clear_login_failures(store, &key).await;
7486 see("/enroll".to_string())
7587 }
7688 Err(_) => {
7789 // The failure is logged against the address tried, never the
7890 // password — and never whether the address exists.
91+ let _ = accounts::record_login_failure(store, &key).await;
7992 server::log_event(cx, "login_fail", Some(&input.email), None).await;
8093 see(format!("/login?error=bad_login&back={}", urlencode(&back)))
8194 }
@@ -111,10 +124,20 @@ async fn login_totp(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect {
111124 },
112125 None => false,
113126 };
127+ // The second factor gets the same ceiling as the first, keyed on the
128+ // account, so an attacker past the password cannot grind codes either.
129+ let totp_key = format!("totp:{}", pending.user);
130+ if accounts::login_blocked(store, &totp_key).await? {
131+ server::log_event(cx, "login_limited", None, Some("2fa")).await;
132+ server::clear_pending_cookie(cx);
133+ return see("/login?error=rate_limited".to_string());
134+ }
114135 if !ok {
136+ let _ = accounts::record_login_failure(store, &totp_key).await;
115137 server::log_event(cx, "totp_fail", None, Some("login")).await;
116138 return see("/login/totp?error=bad_code".to_string());
117139 }
140+ let _ = accounts::clear_login_failures(store, &totp_key).await;
118141 let token = im_core::sessions::create_session(store, &user_id).await?;
119142 let email = accounts::user_by_id(store, &user_id)
120143 .await?
@@ -173,8 +196,8 @@ async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Redirect {
173196 // enrolment page is the only way forward.
174197 let secret = im_core::totp::generate_secret();
175198 im_core::totp::set_totp(store, &user.id, &secret).await?;
176- let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string());
177- server::set_pending_cookie(cx, sealed);
199+ let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string()).await;
200+ server::set_pending_cookie(cx, sealed).await;
178201 server::log_event(cx, "invite_accepted", Some(&user.email), None).await;
179202 see("/enroll".to_string())
180203 }
@@ -226,3 +249,61 @@ async fn logout(cx: &Cx) -> Redirect {
226249 server::clear_session_cookie(cx);
227250 see("/".to_string())
228251 }
252+
253+#[derive(Deserialize)]
254+pub struct ForgotForm {
255+ email: String,
256+}
257+
258+/// The self-serve reset ask. It answers every address the same — the mail
259+/// either exists or it doesn't, and the page never says which. Each ask
260+/// retires the address's previous live link: the newest mail is the only
261+/// door.
262+#[route(POST "/forgot")]
263+async fn forgot(cx: &Cx, Form(input): Form<ForgotForm>) -> Redirect {
264+ let store = &server::app(cx).store;
265+ let email = input.email.trim().to_string();
266+ if let Some(token) = accounts::create_reset(store, &email).await? {
267+ let issuer = server::app(cx).config.issuer.clone();
268+ if crate::mailer::send_reset(store, &issuer, &email, token.expose())
269+ .await
270+ .is_ok()
271+ {
272+ server::log_event(cx, "reset_sent", Some(&email), None).await;
273+ }
274+ }
275+ see("/forgot?ok=sent".to_string())
276+}
277+
278+#[derive(Deserialize)]
279+pub struct ResetForm {
280+ token: String,
281+ password: String,
282+ password_confirm: String,
283+}
284+
285+/// Redeems a reset link: new password in, every session out. A dead link is
286+/// sent back to the ask — the form it came from is gone with it.
287+#[route(POST "/reset")]
288+async fn reset(cx: &Cx, Form(input): Form<ResetForm>) -> Redirect {
289+ if input.password != input.password_confirm {
290+ return see(format!("/reset/{}?error=passwords_differ", input.token));
291+ }
292+ let store = &server::app(cx).store;
293+ match accounts::redeem_reset(store, &input.token, &input.password).await {
294+ Ok(user) => {
295+ server::log_event(cx, "password_reset", Some(&user.email), None).await;
296+ see("/login?ok=reset".to_string())
297+ }
298+ Err(AccountError::Password(problem)) => {
299+ let code = match problem {
300+ im_core::accounts::PasswordProblem::TooShort => "password_too_short",
301+ im_core::accounts::PasswordProblem::LooksLikeYou => "password_personal",
302+ _ => "passwords_differ",
303+ };
304+ see(format!("/reset/{}?error={code}", input.token))
305+ }
306+ Err(AccountError::ResetInvalid) => see("/forgot?error=reset_invalid".to_string()),
307+ Err(e) => Err(topcoat::Error::from(std::io::Error::other(e.to_string()))),
308+ }
309+}
crates/im-web/src/mailer.rsmodified+17 -0
@@ -87,6 +87,23 @@ pub async fn send_invite(store: &Store, issuer: &str, email: &str, token: &str)
8787 Ok(link)
8888 }
8989
90+/// The reset mail: the link is the whole payload, and sending it retires
91+/// every previous link for the address (see `accounts::create_reset`).
92+pub async fn send_reset(store: &Store, issuer: &str, email: &str, token: &str) -> Result<String> {
93+ let link = format!("{issuer}/reset/{token}");
94+ let minutes = settings::reset_minutes(store).await?;
95+ send(
96+ store,
97+ email,
98+ "Reset your password",
99+ format!(
100+ "A password reset was asked for this address. The link is yours for {minutes} minutes:\n\n{link}\n\nIf that wasn't you, this mail changes nothing.\n"
101+ ),
102+ )
103+ .await?;
104+ Ok(link)
105+}
106+
90107 /// Dials the mail server without sending anything: connect, TLS, hello,
91108 /// authenticate, NOOP, hang up. A pass proves the host, the port, the
92109 /// encryption and the password; it says nothing about whether the
crates/im-web/src/oidc.rsmodified+2 -1
@@ -302,7 +302,8 @@ async fn exchange(cx: &Cx, Form(input): Form<TokenForm>) -> Result<Response> {
302302 &consumed.session_hash,
303303 )
304304 .await?;
305- server::log_event(cx,
305+ server::log_event(
306+ cx,
306307 "code_exchanged",
307308 Some(&user.email),
308309 Some(&format!("via {}", client.name)),
crates/im-web/src/pages.rsmodified+123 -0
@@ -33,10 +33,20 @@ pub fn error_text(code: &str) -> &'static str {
3333 "smtp_test" => "The test mail could not be sent.",
3434 "password_wrong" => "That's not your current password.",
3535 "password_same" => "That's already your password.",
36+ "rate_limited" => "Too many tries — wait a while and try again.",
37+ "reset_invalid" => "This reset link is not valid — ask for a fresh one.",
3638 _ => "Something went wrong. Try again.",
3739 }
3840 }
3941
42+/// The good news, where a page carries an `ok` code in its URL.
43+pub fn ok_text(code: &str) -> &'static str {
44+ match code {
45+ "reset" => "Password changed — sign in with the new one.",
46+ _ => "Done.",
47+ }
48+}
49+
4050 /// The refusal this request carries back, if any. Values come percent-
4151 /// decoded: `redirect_uri=http%3A%2F%2F…` must equal the registered URI.
4252 pub fn query_value(query: &str, key: &str) -> Option<String> {
@@ -107,6 +117,7 @@ async fn login_card(cx: &Cx) -> Result {
107117 let query = current_query(cx);
108118 let back = query_value(&query, "back").unwrap_or_else(|| "/".to_string());
109119 let error = query_value(&query, "error");
120+ let ok = query_value(&query, "ok");
110121 let stage = view! {
111122 cx =>
112123 <main class="auth-stage">
@@ -117,6 +128,9 @@ async fn login_card(cx: &Cx) -> Result {
117128 <div class="auth-title">"Sign in"</div>
118129 <div class="auth-sub">"One account for everything Dizey."</div>
119130 </div>
131+ if let Some(code) = ok {
132+ <div class="auth-ok">(ok_text(&code))</div>
133+ }
120134 if let Some(code) = error {
121135 <div class="auth-problem">(error_text(&code))</div>
122136 }
@@ -146,6 +160,7 @@ async fn login_card(cx: &Cx) -> Result {
146160 <span class="auth-submit-text">"Sign in"</span>
147161 </button>
148162 </form>
163+ <a class="auth-alt" href="/forgot">"Forgot it?"</a>
149164 </div>
150165 <div class="auth-footer">"im · Dizey SSO"</div>
151166 </div>
@@ -421,3 +436,111 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result {
421436 };
422437 shell(cx, "im", stage).await
423438 }
439+
440+/// "Forgot it?" — the self-serve reset ask. It answers the same whether the
441+/// address has an account: one quiet note, the same one for every address.
442+#[page("/forgot")]
443+async fn forgot(cx: &Cx) -> Result {
444+ let query = current_query(cx);
445+ let error = query_value(&query, "error");
446+ let sent = query_value(&query, "ok").as_deref() == Some("sent");
447+ let stage = view! {
448+ cx =>
449+ <main class="auth-stage">
450+ <div class="auth-column">
451+ (wordmark(cx).await?)
452+ <div class="auth-card">
453+ <div class="auth-head">
454+ <div class="auth-title">"Forgot it?"</div>
455+ <div class="auth-sub">"Your address gets a reset link, good for one password change. A fresh ask retires the last link."</div>
456+ </div>
457+ if sent {
458+ <div class="auth-ok">"If that address has an account, a link is on its way."</div>
459+ }
460+ if let Some(code) = error {
461+ <div class="auth-problem">(error_text(&code))</div>
462+ }
463+ <form method="post" action="/forgot">
464+ <label class="auth-field">
465+ <span class="auth-label">"Email"</span>
466+ <input
467+ class="auth-input auth-input-mono"
468+ type="email"
469+ name="email"
470+ autocomplete="email"
471+ required=""
472+ >
473+ </label>
474+ <button class="auth-submit" type="submit">
475+ <span class="auth-submit-text">"Send the link"</span>
476+ </button>
477+ </form>
478+ <a class="auth-alt" href="/">"Back to sign-in"</a>
479+ </div>
480+ <div class="auth-footer">"im · Dizey SSO"</div>
481+ </div>
482+ </main>
483+ };
484+ shell(cx, "Forgot it? · im", stage).await
485+}
486+
487+/// The reset link's destination: a new password, twice. A dead link never
488+/// shows a working form — it goes back to the ask with the refusal named.
489+#[route(GET "/reset/{token}")]
490+async fn reset_page(cx: &Cx) -> Result<Response> {
491+ let token: &str = path_param::<Token>(cx);
492+ if !im_core::accounts::reset_link_valid(&server::app(cx).store, token).await? {
493+ return see_other("/forgot?error=reset_invalid").into_response(cx);
494+ }
495+ let query = current_query(cx);
496+ let error = query_value(&query, "error");
497+ let stage = view! {
498+ cx =>
499+ <main class="auth-stage">
500+ <div class="auth-column">
501+ (wordmark(cx).await?)
502+ <div class="auth-card">
503+ <div class="auth-head">
504+ <div class="auth-title">"A fresh password"</div>
505+ <div class="auth-sub">"The change signs every device out, this one included."</div>
506+ </div>
507+ if let Some(code) = error {
508+ <div class="auth-problem">(error_text(&code))</div>
509+ }
510+ <form method="post" action="/reset">
511+ <input type="hidden" name="token" value=(token.to_string())>
512+ <label class="auth-field">
513+ <span class="auth-label">"New password"</span>
514+ <input
515+ class="auth-input auth-input-mono"
516+ type="password"
517+ name="password"
518+ autocomplete="new-password"
519+ minlength=(MIN_PASSWORD_CHARS.to_string())
520+ required=""
521+ >
522+ </label>
523+ <label class="auth-field">
524+ <span class="auth-label">"New password, again"</span>
525+ <input
526+ class="auth-input auth-input-mono"
527+ type="password"
528+ name="password_confirm"
529+ autocomplete="new-password"
530+ minlength=(MIN_PASSWORD_CHARS.to_string())
531+ required=""
532+ >
533+ </label>
534+ <button class="auth-submit" type="submit">
535+ <span class="auth-submit-text">"Change password"</span>
536+ </button>
537+ </form>
538+ </div>
539+ <div class="auth-footer">"im · Dizey SSO"</div>
540+ </div>
541+ </main>
542+ };
543+ shell(cx, "A fresh password · im", stage)
544+ .await?
545+ .into_response(cx)
546+}
crates/im-web/src/server.rsmodified+10 -4
@@ -85,13 +85,16 @@ pub fn set_session_cookie(cx: &Cx, token: &str) {
8585 });
8686 }
8787
88-pub fn set_pending_cookie(cx: &Cx, sealed: String) {
88+pub async fn set_pending_cookie(cx: &Cx, sealed: String) {
89+ let minutes = im_core::settings::pending_minutes(&app(cx).store)
90+ .await
91+ .unwrap_or(PENDING_MINUTES);
8992 app_cookies(cx).add(cookie! {
9093 PENDING_COOKIE = sealed;
9194 Path = "/";
9295 HttpOnly;
9396 SameSite = Lax;
94- MaxAge = time::Duration::minutes(PENDING_MINUTES)
97+ MaxAge = time::Duration::minutes(minutes)
9598 });
9699 }
97100
@@ -137,17 +140,20 @@ pub struct Pending {
137140 pub exp: i64,
138141 }
139142
140-pub fn mint_pending(
143+pub async fn mint_pending(
141144 cx: &Cx,
142145 user: &im_core::model::UserId,
143146 purpose: PendingPurpose,
144147 back: String,
145148 ) -> String {
149+ let minutes = im_core::settings::pending_minutes(&app(cx).store)
150+ .await
151+ .unwrap_or(PENDING_MINUTES);
146152 let pending = Pending {
147153 user: user.to_string(),
148154 purpose,
149155 back,
150- exp: time::OffsetDateTime::now_utc().unix_timestamp() + PENDING_MINUTES * 60,
156+ exp: time::OffsetDateTime::now_utc().unix_timestamp() + minutes * 60,
151157 };
152158 let json = serde_json::to_string(&pending).expect("Pending is plain data");
153159 app(cx).store.seal_value(json.as_bytes())
style/main.scssmodified+7 -0
@@ -590,9 +590,16 @@ body:has(.admin-shell) {
590590 // button skin; the popover names the cost and holds the real button.
591591 .admin-confirm {
592592 position: relative;
593+ display: inline-flex;
593594
595+ // The summary wears the button skin verbatim — a native summary is a
596+ // list-item, and without inline-flex it stands a few pixels off the real
597+ // buttons beside it.
594598 summary {
595599 list-style: none;
600+ display: inline-flex;
601+ align-items: center;
602+ box-sizing: border-box;
596603
597604 &::-webkit-details-marker { display: none; }
598605 }