diff --git a/crates/im-core/src/accounts.rs b/crates/im-core/src/accounts.rs index 1855648..b2a8482 100644 --- a/crates/im-core/src/accounts.rs +++ b/crates/im-core/src/accounts.rs @@ -18,6 +18,7 @@ use rand::Rng; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq; +use time::OffsetDateTime; use crate::model::{Invite, User, UserId}; use crate::store::{self, Result, Store, StoreError, backend}; @@ -287,6 +288,69 @@ pub async fn invite_by_token(store: &Store, token: &str) -> Result Result> { + let mut rows = store + .conn + .query( + "SELECT token, email, admin, created_at, expires_at FROM invites \ + WHERE accepted_at IS NULL AND expires_at > ?1 ORDER BY created_at", + turso::params![store::stamp(store::now())?], + ) + .await + .map_err(backend)?; + let mut pending = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + pending.push(PendingInvite { + token_hash: store::text(&row, 0)?, + email: store::text(&row, 1)?, + admin: store::int(&row, 2)? != 0, + created_at: store::parse_stamp(&store::text(&row, 3)?)?, + expires_at: store::parse_stamp(&store::text(&row, 4)?)?, + }); + } + Ok(pending) +} + +/// Invalidates an invite: the row is gone, the link reads "not valid" from +/// that moment on. Returns the address it was made out to, for the log line. +pub async fn revoke_invite(store: &Store, token_hash: &str) -> Result> { + let mut rows = store + .conn + .query( + "SELECT email FROM invites WHERE token = ?1", + turso::params![token_hash], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(None); + }; + let email = store::text(&row, 0)?; + store + .conn + .execute( + "DELETE FROM invites WHERE token = ?1", + turso::params![token_hash], + ) + .await + .map_err(backend)?; + Ok(Some(email)) +} + /// Turns a valid invite into a user. The invite is marked accepted in the /// same transaction as the user insert, so a token can never mint two /// accounts. @@ -488,6 +552,28 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result> { })) } +/// Deletes an account outright: the user row, its sessions, and every app +/// token born of them. Disable is the reversible door; this is for "this +/// account should not exist" — the OIDC subject dies with it, and if the +/// person returns they get a fresh one. +pub async fn delete_user(store: &Store, user: &UserId) -> Result<()> { + let id = user.to_string(); + for sql in [ + "DELETE FROM app_sessions WHERE user_id = ?1", + "DELETE FROM refresh_tokens WHERE user_id = ?1", + "DELETE FROM sessions WHERE user_id = ?1", + "UPDATE invites SET invited_by = NULL WHERE invited_by = ?1", + "DELETE FROM users WHERE id = ?1", + ] { + store + .conn + .execute(sql, turso::params![id.clone()]) + .await + .map_err(backend)?; + } + Ok(()) +} + /// Every user, oldest first — the admin panel's roster. pub async fn list_users(store: &Store) -> Result> { let mut rows = store @@ -699,4 +785,64 @@ mod tests { Err(AccountError::EmailTaken) )); } + + #[tokio::test] + async fn pending_invites_list_and_revoke() { + let store = fixture().await; + let token = create_invite(&store, "bob@example.com", None, true) + .await + .unwrap(); + + let pending = list_pending_invites(&store).await.unwrap(); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].email, "bob@example.com"); + assert!(pending[0].admin); + + let email = revoke_invite(&store, &pending[0].token_hash).await.unwrap(); + assert_eq!(email.as_deref(), Some("bob@example.com")); + assert!(list_pending_invites(&store).await.unwrap().is_empty()); + // The link is dead: the token resolves to nothing. + assert!( + invite_by_token(&store, token.expose()) + .await + .unwrap() + .is_none() + ); + // Revoking the same invite twice is a quiet no-op. + assert!( + revoke_invite(&store, &pending[0].token_hash) + .await + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn delete_user_takes_sessions_with_it() { + let store = fixture().await; + let invite = create_invite(&store, "ann@example.com", None, false) + .await + .unwrap(); + let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") + .await + .unwrap(); + let session = crate::sessions::create_session(&store, &user.id) + .await + .unwrap(); + + delete_user(&store, &user.id).await.unwrap(); + assert!(user_by_id(&store, &user.id).await.unwrap().is_none()); + assert!( + crate::sessions::resolve_session(&store, session.expose()) + .await + .unwrap() + .is_none() + ); + // The address is free again: a fresh invite can be made for it. + assert!( + create_invite(&store, "ann@example.com", None, false) + .await + .is_ok() + ); + } } diff --git a/crates/im-web/assets/main.css b/crates/im-web/assets/main.css index 70045ba..cc8bc61 100644 --- a/crates/im-web/assets/main.css +++ b/crates/im-web/assets/main.css @@ -504,6 +504,48 @@ body:has(.admin-shell) { gap: 8px; } +.chip { + display: inline-flex; + align-items: center; + height: 24px; + padding: 0 10px; + border-radius: var(--radius); + font-size: 11px; + font-weight: 600; +} + +.chip-muted { + background: var(--panel-sunken); + border: 1px solid var(--border-strong); + color: var(--muted); +} + +.chip-connected { + background: var(--positive-tint); + border: 1px solid var(--positive-border); + color: var(--positive); +} + +.chip-refused { + background: var(--danger-tint-alt); + border: 1px solid var(--danger-border-soft); + color: var(--danger); +} + +.admin-card-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; +} + +.admin-danger { + color: var(--danger); +} +.admin-danger:hover { + background: var(--danger-tint-alt); +} + input[type=checkbox] { accent-color: var(--accent); } diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index db9f21a..9db20d5 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -108,6 +108,8 @@ async fn admin_page(cx: &Cx) -> Result { "smtp" => "Mail settings saved.", "smtp_test" => "Test mail sent.", "password" => "Password changed — every other device is signed out.", + "uninvited" => "Invite invalidated — the link is dead.", + "deleted" => "Account deleted.", _ => "Done.", } )), @@ -172,6 +174,7 @@ async fn users_section( invited: Option<&str>, ) -> Result { let users = accounts::list_users(&app(cx).store).await?; + let pending = accounts::list_pending_invites(&app(cx).store).await?; let mut rows = String::new(); for user in &users { let flags = [ @@ -198,7 +201,7 @@ async fn users_section( ) }; format!( - r#"{toggle}
"# + r#"{toggle}
"# ) }; rows.push_str(&format!( @@ -209,6 +212,26 @@ async fn users_section( actions )); } + // Invites still waiting on their person sit in the same table — "waiting" + // instead of a name, and the one action an outstanding link understands: + for row in &pending { + let flags = [Some("invited"), row.admin.then_some("admin")] + .into_iter() + .flatten() + .collect::>() + .join(" · "); + let expires = row + .expires_at + .format(&time::macros::format_description!("[year]-[month]-[day]")) + .unwrap_or_default(); + rows.push_str(&format!( + r#"{}waiting · until {}{}
"#, + escape(&row.email), + expires, + flags, + escape(&row.token_hash), + )); + } let invited_html = invited .map(|link| { format!( @@ -245,31 +268,50 @@ async fn mail_section(cx: &Cx) -> Result { } else { "no password set" }; - // The standing line, izlek's chip as a sentence: what the last probe - // proved, and when. Saving settings wipes the record, so this can never - // claim "connected" for settings that changed since. + // The standing chip, izlek's idiom: one colored chip that says what the + // last probe proved, with the server's own words under it on a refusal. + // Saving settings wipes the record, so the chip can never claim + // "connected" for settings that changed since. let stamp = |at: time::OffsetDateTime| { at.format(&time::macros::format_description!( "[year]-[month]-[day] [hour]:[minute] UTC" )) .unwrap_or_default() }; - let standing = match settings::standing(store).await? { - settings::Standing::NotConfigured => "No sender configured.".to_string(), - settings::Standing::Unchecked => { + let (chip_class, chip_text, lede) = match settings::standing(store).await? { + settings::Standing::NotConfigured => ( + "chip chip-muted", + "not configured".to_string(), + String::new(), + ), + settings::Standing::Unchecked => ( + "chip chip-muted", + "unchecked".to_string(), "Saved, but never checked — the check dials the server and stops before sending." - .to_string() - } - settings::Standing::Connected { at, took_ms } => { - format!("Connected · {took_ms} ms · {}", stamp(at)) - } - settings::Standing::Refused { at, said } => { - format!("Refused · {} — {}", stamp(at), escape(&said)) - } + .to_string(), + ), + settings::Standing::Connected { at, took_ms } => ( + "chip chip-connected", + format!("connected · {took_ms} ms"), + format!( + "Checked {} — TLS, hello, password: all accepted.", + stamp(at) + ), + ), + settings::Standing::Refused { at, said } => ( + "chip chip-refused", + "refused".to_string(), + format!("{} — {}", stamp(at), escape(&said)), + ), + }; + let lede_html = if lede.is_empty() { + String::new() + } else { + format!(r#"
{lede}
"#) }; Ok(format!( r#"
-
Mail
+
Mail
{chip_text}
Invites go out through this sender. The password is sealed under im.key; without a sender, invite links are shown here instead of mailed.
-
{standing}
+ {lede_html}
@@ -373,6 +415,43 @@ async fn invite(cx: &Cx, Form(input): Form) -> Result { } } +#[derive(Deserialize)] +struct InviteAction { + invite: String, +} + +/// Invalidates an outstanding invite: the link dies now, not at expiry. +#[route(POST "/admin/uninvite")] +async fn uninvite(cx: &Cx, Form(input): Form) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + let store = &app(cx).store; + let email = accounts::revoke_invite(store, &input.invite).await?; + events::log(store, "invite_revoked", Some(&me.email), email.as_deref()).await; + back(cx, "users", "&ok=uninvited") +} + +/// Deletes the account outright — user, sessions, app tokens. Disable is +/// the reversible door; this one is for "should not exist". The admin's own +/// row never carries the button, so there is no self-delete to guard here. +#[route(POST "/admin/delete")] +async fn delete(cx: &Cx, Form(input): Form) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + let store = &app(cx).store; + let user_id = UserId::from(input.user); + let email = accounts::user_by_id(store, &user_id) + .await? + .map(|u| u.email); + accounts::delete_user(store, &user_id).await?; + events::log(store, "user_deleted", Some(&me.email), email.as_deref()).await; + back(cx, "users", "&ok=deleted") +} + #[derive(Deserialize)] struct PasswordForm { current: String, diff --git a/style/main.scss b/style/main.scss index b9e82a1..58d1141 100644 --- a/style/main.scss +++ b/style/main.scss @@ -540,6 +540,52 @@ body:has(.admin-shell) { gap: 8px; } +// The standing chip, iz's idiom: one colored pill that says what the last +// probe proved — positive green on a pass, the danger tint on a refusal, +// quiet gray until there is anything to say. +.chip { + display: inline-flex; + align-items: center; + height: 24px; + padding: 0 10px; + border-radius: var(--radius); + font-size: 11px; + font-weight: 600; +} + +.chip-muted { + background: var(--panel-sunken); + border: 1px solid var(--border-strong); + color: var(--muted); +} + +.chip-connected { + background: var(--positive-tint); + border: 1px solid var(--positive-border); + color: var(--positive); +} + +.chip-refused { + background: var(--danger-tint-alt); + border: 1px solid var(--danger-border-soft); + color: var(--danger); +} + +.admin-card-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; +} + +// Delete is the one destructive row action; it wears the danger ink so it +// never reads as another quiet button. +.admin-danger { + color: var(--danger); + + &:hover { background: var(--danger-tint-alt); } +} + input[type="checkbox"] { accent-color: var(--accent); } @media (max-width: 720px) {