From 8092e0d49f26f242a72b5803fa47fa4f5556a718 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 4 Sep 2026 07:05:40 +0300 Subject: [PATCH] Profile section: photo, statistics, public page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The signed-in landing gains a profile section — photo, 2FA/admin chips, Email and Member-since fields, and a statistics card (sign-ins, active sessions, connected apps) — and /people/{user_id} gives every account a public profile any signed-in member can read, iz's people page ported to the auth-card idiom. Photos keep izlek's split: the row carries only the mime type, the bytes live as files under storage/photos/ — staged write, row commit, rename on set; row first, best-effort unlink on clear; a boot sweep collects staged leftovers and orphans. Upload caps at 5 MiB and sniffs the mime from magic bytes; serving is session-gated (404, never 403) with ETag/304 and immutable caching behind a per-upload URL stamp. --- .gitignore | 1 + Cargo.lock | 29 ++++ crates/im-core/src/accounts.rs | 16 +- crates/im-core/src/lib.rs | 4 + crates/im-core/src/model.rs | 3 + crates/im-core/src/photos.rs | 276 +++++++++++++++++++++++++++++++++ crates/im-core/src/stats.rs | 151 ++++++++++++++++++ crates/im-core/src/store.rs | 85 +++++++++- crates/im-web/Cargo.toml | 2 + crates/im-web/assets/main.css | 116 ++++++++++++++ crates/im-web/src/auth.rs | 4 +- crates/im-web/src/layout.rs | 29 ++++ crates/im-web/src/main.rs | 9 +- crates/im-web/src/pages.rs | 112 ++++++++++++- crates/im-web/src/people.rs | 93 +++++++++++ crates/im-web/src/photo.rs | 208 +++++++++++++++++++++++++ style/main.scss | 129 +++++++++++++++ 17 files changed, 1246 insertions(+), 21 deletions(-) create mode 100644 crates/im-core/src/photos.rs create mode 100644 crates/im-core/src/stats.rs create mode 100644 crates/im-web/src/people.rs create mode 100644 crates/im-web/src/photo.rs diff --git a/.gitignore b/.gitignore index fb2078c..a0becf7 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ /im-migrate-mapping.csv /public/* !/public/.gitkeep +/storage diff --git a/Cargo.lock b/Cargo.lock index 7edf8be..395029c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1002,6 +1002,15 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + [[package]] name = "env_filter" version = "2.0.0" @@ -1828,6 +1837,7 @@ dependencies = [ "http", "im-core", "lettre", + "parking_lot", "qrcode", "serde", "serde_json", @@ -2281,6 +2291,23 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + [[package]] name = "murmurhash32" version = "0.3.1" @@ -4172,6 +4199,7 @@ dependencies = [ "bytes", "form_urlencoded", "futures-core", + "futures-util", "heck", "http", "http-body", @@ -4180,6 +4208,7 @@ dependencies = [ "hyper-util", "inventory", "matchit", + "multer", "percent-encoding", "ref-cast", "serde", diff --git a/crates/im-core/src/accounts.rs b/crates/im-core/src/accounts.rs index 193e1ce..7e82ee0 100644 --- a/crates/im-core/src/accounts.rs +++ b/crates/im-core/src/accounts.rs @@ -378,6 +378,7 @@ pub async fn create_user_from_invite( email: invite.email.clone(), name: name.to_string(), totp_confirmed: false, + has_photo: false, admin: invite.admin, disabled: false, created_at: store::now(), @@ -644,8 +645,8 @@ pub async fn verify_login( let conn = store.conn.lock().await; let mut rows = conn .query( - "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at \ - FROM users WHERE email = ?1 COLLATE NOCASE", + "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at, \ + photo_mime IS NOT NULL FROM users WHERE email = ?1 COLLATE NOCASE", turso::params![email], ) .await @@ -659,6 +660,7 @@ pub async fn verify_login( email: store::text(&row, 1)?, name: store::text(&row, 2)?, totp_confirmed: store::int(&row, 4)? != 0, + has_photo: store::int(&row, 8)? != 0, admin: store::int(&row, 5)? != 0, disabled: store::int(&row, 6)? != 0, created_at: store::parse_stamp(&store::text(&row, 7)?)?, @@ -733,8 +735,8 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result> { let conn = store.conn.lock().await; let mut rows = conn .query( - "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \ - FROM users WHERE id = ?1", + "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \ + photo_mime IS NOT NULL FROM users WHERE id = ?1", turso::params![id.to_string()], ) .await @@ -747,6 +749,7 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result> { email: store::text(&row, 1)?, name: store::text(&row, 2)?, totp_confirmed: store::int(&row, 3)? != 0, + has_photo: store::int(&row, 7)? != 0, admin: store::int(&row, 4)? != 0, disabled: store::int(&row, 5)? != 0, created_at: store::parse_stamp(&store::text(&row, 6)?)?, @@ -779,8 +782,8 @@ pub async fn list_users(store: &Store) -> Result> { let conn = store.conn.lock().await; let mut rows = conn .query( - "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \ - FROM users ORDER BY created_at", + "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \ + photo_mime IS NOT NULL FROM users ORDER BY created_at", (), ) .await @@ -792,6 +795,7 @@ pub async fn list_users(store: &Store) -> Result> { email: store::text(&row, 1)?, name: store::text(&row, 2)?, totp_confirmed: store::int(&row, 3)? != 0, + has_photo: store::int(&row, 7)? != 0, admin: store::int(&row, 4)? != 0, disabled: store::int(&row, 5)? != 0, created_at: store::parse_stamp(&store::text(&row, 6)?)?, diff --git a/crates/im-core/src/lib.rs b/crates/im-core/src/lib.rs index 3ab86c1..50f6c53 100644 --- a/crates/im-core/src/lib.rs +++ b/crates/im-core/src/lib.rs @@ -14,12 +14,16 @@ pub mod keys; #[cfg(feature = "server")] pub mod oidc; #[cfg(feature = "server")] +pub mod photos; +#[cfg(feature = "server")] mod secret; #[cfg(feature = "server")] pub mod sessions; #[cfg(feature = "server")] pub mod settings; #[cfg(feature = "server")] +pub mod stats; +#[cfg(feature = "server")] pub mod store; #[cfg(feature = "server")] pub mod totp; diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index f8787d7..34d15a2 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -51,6 +51,9 @@ pub struct User { pub email: String, pub name: String, pub totp_confirmed: bool, + /// Whether this person has a profile photo: the row keeps the mime + /// type, the bytes live as a file under the storage tree (`photos.rs`). + pub has_photo: bool, /// im's own admin flag — never crosses a token; AuthN stays the only /// thing apps receive. pub admin: bool, diff --git a/crates/im-core/src/photos.rs b/crates/im-core/src/photos.rs new file mode 100644 index 0000000..55164a4 --- /dev/null +++ b/crates/im-core/src/photos.rs @@ -0,0 +1,276 @@ +//! Profile photos: the row keeps the mime type, the storage tree keeps the +//! bytes — one file per user at `/photos/`, the same +//! split izlek-core keeps. The web layer caps the upload (5 MiB) and sniffs +//! the mime before anything here runs; this module trusts both, the way +//! `accounts` trusts the password rules were checked. +//! +//! Writes order themselves so a crash leaves stale bytes, never destroyed +//! ones: `set_photo` stages the new file under a name no row wears, commits +//! the row, and only then renames over the old photo; `clear_photo` commits +//! the row first and unlinks best-effort. Whatever a crash strands — staged +//! files, files no row names — the boot sweep collects (see +//! [`sweep_orphan_files`], run from `Store::open`). + +use crate::model::UserId; +use crate::store::{Result, Store, StoreError, backend}; + +/// Where `user_id`'s photo lives inside the store's photos directory. Named +/// by the user id the store minted — never by anything an upload carried — +/// so a path here is always exactly one store-named file deep. +fn photo_file(store: &Store, user_id: &str) -> std::path::PathBuf { + store.photos_dir.join(user_id) +} + +/// Writes `bytes` to `path` through a temporary file in the same directory +/// and a rename: a crash or a full disk mid-write leaves whatever file was +/// there before intact, never a truncated one under the real name. +fn write_file_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write as _; + let tmp = path.with_extension(format!("{}.tmp", ulid::Ulid::new())); + let mut file = std::fs::File::create(&tmp)?; + file.write_all(bytes)?; + file.sync_all()?; + std::fs::rename(&tmp, path) +} + +/// Stores the photo's bytes and mime type, replacing any previous one. +pub async fn set_photo(store: &Store, user: &UserId, bytes: &[u8], mime: &str) -> Result<()> { + let id = user.to_string(); + let path = photo_file(store, &id); + // The new bytes stage under a name no row wears, the row commits, and + // only then does the rename put them over the old photo: a failed update + // leaves the committed photo exactly as it was, and a crash between + // commit and rename serves the old bytes next to a staged file the boot + // sweep collects — stale, never destroyed. + let staged = path.with_extension(format!("incoming-{}", ulid::Ulid::new())); + write_file_atomic(&staged, bytes).map_err(|e| StoreError::Backend(e.to_string()))?; + let written = { + let conn = store.conn.lock().await; + conn.execute( + "UPDATE users SET photo_mime = ?1 WHERE id = ?2", + turso::params![mime, id.clone()], + ) + .await + }; + if let Err(e) = written { + let _ = std::fs::remove_file(&staged); + return Err(backend(e)); + } + std::fs::rename(&staged, &path).map_err(|e| StoreError::Backend(e.to_string()))?; + Ok(()) +} + +/// Clears the photo. The row goes first: the file may only follow a delete +/// that committed, or a crash in between would leave a row whose photo is +/// gone. The unlink is best-effort — a file that survives it is orphaned +/// bytes the boot sweep collects. +pub async fn clear_photo(store: &Store, user: &UserId) -> Result<()> { + let id = user.to_string(); + { + let conn = store.conn.lock().await; + conn.execute( + "UPDATE users SET photo_mime = NULL WHERE id = ?1", + turso::params![id.clone()], + ) + .await + .map_err(backend)?; + } + let _ = std::fs::remove_file(photo_file(store, &id)); + Ok(()) +} + +/// The photo's bytes and mime type, or `None` when none is set. A row whose +/// file went missing is reported at boot; the read answers "nothing to +/// serve" rather than failing the page. +pub async fn photo(store: &Store, user: &UserId) -> Result, String)>> { + let id = user.to_string(); + let mime = { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT photo_mime FROM users WHERE id = ?1", + turso::params![id.clone()], + ) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => crate::store::opt_text(&row, 0)?, + None => return Ok(None), + } + }; + let Some(mime) = mime else { + return Ok(None); + }; + match std::fs::read(photo_file(store, &id)) { + Ok(bytes) => Ok(Some((bytes, mime))), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(StoreError::Backend(e.to_string())), + } +} + +/// Sets the photos tree against the database, once per boot. The two are +/// halves of one state, and a crash between a row write and its file write — +/// either order — leaves exactly one half behind: a file no row names goes +/// (staged `incoming-*` and `*.tmp` leftovers first), and a row whose file +/// is missing is reported. Never fails the boot — a sweep that cannot read +/// its own directory has nothing safe to delete anyway. +pub(crate) async fn sweep_orphan_files(store: &Store) { + let known: std::collections::HashSet = { + let conn = store.conn.lock().await; + let mut rows = match conn + .query("SELECT id FROM users WHERE photo_mime IS NOT NULL", ()) + .await + { + Ok(rows) => rows, + Err(e) => { + eprintln!( + "im photos: could not list photo rows for the sweep: {}", + backend(e) + ); + return; + } + }; + let mut ids = std::collections::HashSet::new(); + loop { + match rows.next().await { + Ok(Some(row)) => match crate::store::text(&row, 0) { + Ok(id) => { + ids.insert(id); + } + Err(e) => { + eprintln!("im photos: sweep could not read a user id: {e}"); + return; + } + }, + Ok(None) => break, + Err(e) => { + eprintln!("im photos: sweep could not read photo rows: {}", backend(e)); + return; + } + } + } + ids + }; + // Rows whose file went missing: reported, never failed — the photo read + // already answers "nothing to serve" for them. + for id in &known { + if !store.photos_dir.join(id).is_file() { + eprintln!("im photos: {id} has a photo row but no file"); + } + } + let entries = match std::fs::read_dir(&store.photos_dir) { + Ok(entries) => entries, + Err(e) => { + eprintln!( + "im photos: could not sweep {}: {e}", + store.photos_dir.display() + ); + return; + } + }; + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + let staged = name.contains(".incoming-") || name.contains(".tmp"); + if (staged || !known.contains(&name)) + && let Err(e) = std::fs::remove_file(entry.path()) + { + eprintln!("im photos: could not delete orphaned file {name}: {e}"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::accounts::{create_invite, create_user_from_invite, user_by_id}; + use std::path::Path; + + async fn fixture() -> (Store, UserId) { + let store = Store::open(Path::new(":memory:")).await.unwrap(); + 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(); + (store, user.id) + } + + #[tokio::test] + async fn photo_roundtrip() { + let (store, user_id) = fixture().await; + assert!(photo(&store, &user_id).await.unwrap().is_none()); + assert!( + !user_by_id(&store, &user_id) + .await + .unwrap() + .unwrap() + .has_photo + ); + + set_photo(&store, &user_id, b"\x89PNG-fake", "image/png") + .await + .unwrap(); + let (bytes, mime) = photo(&store, &user_id).await.unwrap().unwrap(); + assert_eq!(bytes, b"\x89PNG-fake"); + assert_eq!(mime, "image/png"); + assert!( + user_by_id(&store, &user_id) + .await + .unwrap() + .unwrap() + .has_photo + ); + // The bytes are a file named by the user id — never a column. + let file = photo_file(&store, &user_id.to_string()); + assert_eq!(std::fs::read(&file).unwrap(), b"\x89PNG-fake"); + + // A second upload replaces, it does not append. + set_photo(&store, &user_id, b"\xff\xd8\xff", "image/jpeg") + .await + .unwrap(); + let (bytes, mime) = photo(&store, &user_id).await.unwrap().unwrap(); + assert_eq!(bytes, b"\xff\xd8\xff"); + assert_eq!(mime, "image/jpeg"); + + clear_photo(&store, &user_id).await.unwrap(); + assert!(photo(&store, &user_id).await.unwrap().is_none()); + assert!( + !user_by_id(&store, &user_id) + .await + .unwrap() + .unwrap() + .has_photo + ); + assert!(!file.exists()); + } + + #[tokio::test] + async fn a_row_without_its_file_reads_as_no_photo() { + let (store, user_id) = fixture().await; + set_photo(&store, &user_id, b"\x89PNG-fake", "image/png") + .await + .unwrap(); + std::fs::remove_file(photo_file(&store, &user_id.to_string())).unwrap(); + assert!(photo(&store, &user_id).await.unwrap().is_none()); + } + + #[tokio::test] + async fn the_boot_sweep_collects_orphans_and_staged_files() { + let (store, user_id) = fixture().await; + set_photo(&store, &user_id, b"\x89PNG-fake", "image/png") + .await + .unwrap(); + let real = photo_file(&store, &user_id.to_string()); + let staged = real.with_extension("incoming-deadbeef"); + let stranger = store.photos_dir.join("01STRANGERXXXXXXXXXXXXXXXXX0"); + std::fs::write(&staged, b"half an upload").unwrap(); + std::fs::write(&stranger, b"no row names me").unwrap(); + + sweep_orphan_files(&store).await; + + assert!(real.is_file()); + assert!(!staged.exists()); + assert!(!stranger.exists()); + } +} diff --git a/crates/im-core/src/stats.rs b/crates/im-core/src/stats.rs new file mode 100644 index 0000000..851cd01 --- /dev/null +++ b/crates/im-core/src/stats.rs @@ -0,0 +1,151 @@ +//! The profile page's statistics: how often this identity has been used, +//! and what is holding it right now. +//! +//! Everything here derives from rows the system already keeps — a session +//! row per sign-in, an app-session row per app a sign-in was handed to. No +//! counters, nothing to drift: the page's numbers are the tables, read. + +use crate::model::UserId; +use crate::store::{self, Result, Store, backend}; + +/// One person's counts, for the profile section of the signed-in landing. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProfileStats { + /// Every sign-in ever: one central-session row is written per login. + pub sign_ins: u64, + /// Sessions neither revoked nor expired — the devices that could act + /// as this person right now. + pub active_sessions: u64, + /// Apps holding a live token for this person (distinct OIDC clients + /// with an unrevoked, unexpired app session). + pub connected_apps: u64, +} + +/// Reads the three counts. One round-trip: the tables are small, and the +/// landing is the only reader. +pub async fn profile_stats(store: &Store, user: &UserId) -> Result { + let conn = store.conn.lock().await; + let id = user.to_string(); + let now = store::stamp(store::now())?; + let mut rows = conn + .query( + "SELECT \ + (SELECT COUNT(*) FROM sessions WHERE user_id = ?1), \ + (SELECT COUNT(*) FROM sessions \ + WHERE user_id = ?1 AND revoked_at IS NULL AND expires_at > ?2), \ + (SELECT COUNT(DISTINCT client_id) FROM app_sessions \ + WHERE user_id = ?1 AND revoked_at IS NULL AND expires_at > ?2)", + turso::params![id, now], + ) + .await + .map_err(backend)?; + let row = rows + .next() + .await + .map_err(backend)? + .ok_or_else(|| backend("counts query returned no row"))?; + Ok(ProfileStats { + sign_ins: store::int(&row, 0)? as u64, + active_sessions: store::int(&row, 1)? as u64, + connected_apps: store::int(&row, 2)? as u64, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::accounts::{create_invite, create_user_from_invite}; + use std::path::Path; + + async fn fixture() -> (Store, UserId) { + let store = Store::open(Path::new(":memory:")).await.unwrap(); + 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(); + (store, user.id) + } + + /// Stamps relative to now, so "expired" and "live" rows stay on their + /// own sides of the comparison whatever the clock says at test time. + fn stamp_in(hours: i64) -> String { + store::stamp(store::now() + time::Duration::hours(hours)).unwrap() + } + + #[tokio::test] + async fn counts_reflect_the_tables() { + let (store, user_id) = fixture().await; + let id = user_id.to_string(); + { + let conn = store.conn.lock().await; + // Three sign-ins: one expired, one revoked, one live. + for (hash, expires, revoked) in [ + ("h-expired", stamp_in(-1), None), + ("h-revoked", stamp_in(24), Some(stamp_in(-1))), + ("h-live", stamp_in(24), None), + ] { + conn.execute( + "INSERT INTO sessions (token_hash, user_id, created_at, expires_at, revoked_at) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + turso::params![hash, id.clone(), stamp_in(-24), expires, revoked], + ) + .await + .unwrap(); + } + // A client the app sessions point at, then three app sessions: + // two live for one client (counts once), one revoked for another. + conn.execute( + "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \ + VALUES ('client-a', 'A', 'x', '[]', ?1)", + turso::params![stamp_in(-24)], + ) + .await + .unwrap(); + conn.execute( + "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \ + VALUES ('client-b', 'B', 'x', '[]', ?1)", + turso::params![stamp_in(-24)], + ) + .await + .unwrap(); + for (hash, client, expires, revoked) in [ + ("a1", "client-a", stamp_in(24), None), + ("a2", "client-a", stamp_in(24), None), + ("b1", "client-b", stamp_in(24), Some(stamp_in(-1))), + ] { + conn.execute( + "INSERT INTO app_sessions \ + (token_hash, user_id, client_id, session_hash, created_at, expires_at, revoked_at) \ + VALUES (?1, ?2, ?3, 'h-live', ?4, ?5, ?6)", + turso::params![hash, id.clone(), client, stamp_in(-24), expires, revoked], + ) + .await + .unwrap(); + } + } + let stats = profile_stats(&store, &user_id).await.unwrap(); + assert_eq!( + stats, + ProfileStats { + sign_ins: 3, + active_sessions: 1, + connected_apps: 1, + } + ); + } + + #[tokio::test] + async fn a_fresh_account_reads_zero() { + let (store, user_id) = fixture().await; + assert_eq!( + profile_stats(&store, &user_id).await.unwrap(), + ProfileStats { + sign_ins: 0, + active_sessions: 0, + connected_apps: 0, + } + ); + } +} diff --git a/crates/im-core/src/store.rs b/crates/im-core/src/store.rs index c331eef..b3d8d62 100644 --- a/crates/im-core/src/store.rs +++ b/crates/im-core/src/store.rs @@ -37,7 +37,8 @@ CREATE TABLE IF NOT EXISTS users ( totp_confirmed INTEGER NOT NULL DEFAULT 0, admin INTEGER NOT NULL DEFAULT 0, disabled INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL + created_at TEXT NOT NULL, + photo_mime TEXT ); CREATE TABLE IF NOT EXISTS invites ( token TEXT PRIMARY KEY, @@ -127,12 +128,33 @@ CREATE TABLE IF NOT EXISTS settings ( pub struct Store { pub(crate) conn: tokio::sync::Mutex, pub(crate) key: Key, + /// The directory profile photos live in, one file per user, named by the + /// user id — the same contract izlek-core's storage tree keeps: the + /// database keeps the facts, this tree keeps the bytes, back the two up + /// together. + pub(crate) photos_dir: std::path::PathBuf, } impl Store { /// Opens (creating if needed) the database at `path` and runs the schema /// migration. `:memory:` gives a test store with a fresh throwaway key. pub async fn open(path: &Path) -> Result { + // The tree goes in before anything else — every writer past this + // point assumes the directory is there to write into. + let photos_dir = photos_dir(path); + std::fs::create_dir_all(&photos_dir).map_err(|e| { + StoreError::Backend(format!( + "creating photos directory {}: {e}", + photos_dir.display() + )) + })?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&photos_dir, std::fs::Permissions::from_mode(0o700)).map_err( + |e| StoreError::Backend(format!("restricting {}: {e}", photos_dir.display())), + )?; + } let raw = path .to_str() .ok_or_else(|| StoreError::Corrupt("path is not utf-8".into()))?; @@ -141,8 +163,10 @@ impl Store { let store = Store { conn: tokio::sync::Mutex::new(conn), key: load_key(path)?, + photos_dir, }; store.migrate().await?; + crate::photos::sweep_orphan_files(&store).await; Ok(store) } @@ -152,11 +176,31 @@ impl Store { // schema write. let conn = self.conn.lock().await; conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; - if let Err(e) = conn.execute_batch(SCHEMA).await { - let _ = conn.execute("ROLLBACK", ()).await; - return Err(backend(e)); + let outcome = async { + conn.execute_batch(SCHEMA).await.map_err(backend)?; + // Columns born after databases already existed: the CREATE above + // is `IF NOT EXISTS`, so an old users table never sees them from + // it. Each goes in with its own guarded ALTER — a boot either + // adds the column or finds it there, and re-boot is a no-op. + // The photo's bytes are never a column: they live as files under + // the storage tree (see `photos.rs`). + if !has_column(&conn, "users", "photo_mime").await? { + conn.execute("ALTER TABLE users ADD COLUMN photo_mime TEXT", ()) + .await + .map_err(backend)?; + } + Ok(()) + } + .await; + match outcome { + Ok(()) => { + conn.execute("COMMIT", ()).await.map_err(backend)?; + } + Err(e) => { + let _ = conn.execute("ROLLBACK", ()).await; + return Err(e); + } } - conn.execute("COMMIT", ()).await.map_err(backend)?; Ok(()) } @@ -177,6 +221,37 @@ impl Store { } } +/// The directory a database's profile photos live in: a `storage/photos` +/// tree beside the database file, so a backup that takes the database takes +/// the photos with it. `:memory:` has no directory to anchor to — its tree +/// is a fresh tempdir, as throwaway as the database itself. +fn photos_dir(path: &Path) -> std::path::PathBuf { + if path.as_os_str() == ":memory:" { + return std::env::temp_dir().join(format!("im-storage-{}", ulid::Ulid::new())); + } + path.parent() + .filter(|d| !d.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")) + .join("storage") + .join("photos") +} + +/// Whether `table` carries `column` — the migration's guard for ALTERs that +/// must be no-ops on databases already carrying them. Both names are +/// literals from this module, never request data. +async fn has_column(conn: &Connection, table: &str, column: &str) -> Result { + let mut rows = conn + .query(format!("PRAGMA table_info({table})"), ()) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + if row.get::(1).map_err(backend)? == column { + return Ok(true); + } + } + Ok(false) +} + /// The key for `path`'s database. `:memory:` has no directory to anchor a /// sibling file to, so it gets a key generated fresh in memory — every /// in-memory store is its own, unrelated encryption domain. diff --git a/crates/im-web/Cargo.toml b/crates/im-web/Cargo.toml index 8a2dfb7..2b3b14a 100644 --- a/crates/im-web/Cargo.toml +++ b/crates/im-web/Cargo.toml @@ -17,9 +17,11 @@ topcoat = { version = "0.6.2", default-features = false, features = [ "discover", "serve", "compression", + "multipart", "sse", ] } futures-util = { version = "0.3", default-features = false } +parking_lot = "0.12" im-core = { workspace = true, features = ["server"] } serde.workspace = true serde_json.workspace = true diff --git a/crates/im-web/assets/main.css b/crates/im-web/assets/main.css index 78fc3a3..3bc5912 100644 --- a/crates/im-web/assets/main.css +++ b/crates/im-web/assets/main.css @@ -334,6 +334,122 @@ body:has(.auth-stage) > .auth-stage::-webkit-scrollbar { padding-top: 4px; } +.profile-head { + display: flex; + align-items: center; + gap: 14px; +} + +.profile-avatar { + flex: none; + width: 72px; + height: 72px; + border-radius: var(--radius); + border: 1px solid var(--border); + object-fit: cover; +} + +.profile-avatar-initial { + display: flex; + align-items: center; + justify-content: center; + background: var(--panel-sunken); + color: var(--muted); + font-family: var(--font-mono); + font-size: 26px; + font-weight: 500; + user-select: none; +} + +.profile-heading { + display: flex; + flex-direction: column; + gap: 6px; + min-width: 0; +} + +.profile-marks { + display: flex; + gap: 6px; + flex-wrap: wrap; +} + +.chip-accent { + background: var(--accent-tint); + border: 1px solid var(--border-strong); + color: var(--accent-ink); +} + +.profile-fields { + margin: 0; + display: flex; + flex-direction: column; + gap: 10px; +} + +.profile-field { + display: flex; + flex-direction: column; + gap: 4px; +} + +.profile-value { + margin: 0; + font-size: 13px; +} + +.profile-photo-actions { + display: flex; + gap: 8px; + align-items: center; +} +.profile-photo-actions .profile-upload { + flex: 1; + width: auto; +} + +#profile-photo-remove { + display: none; +} + +.profile-file { + height: auto; + padding: 7px 12px; + font-size: 12px; + color: var(--muted); +} +.profile-file::file-selector-button { + margin-right: 10px; + padding: 4px 10px; + background: var(--panel-sunken); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + color: var(--ink); + font-family: var(--font-sans); + font-size: 12px; + cursor: pointer; +} + +.profile-stats { + margin: 0; + display: flex; + justify-content: space-between; + gap: 12px; +} + +.profile-stat { + display: flex; + flex-direction: column; + gap: 2px; +} + +.profile-stat-value { + margin: 0; + font-size: 22px; + font-weight: 600; + letter-spacing: -0.01em; +} + @media (max-width: 720px) { .auth-stage { padding: 0 16px 24px; diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index 029f6d2..6fa9b5c 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -12,9 +12,9 @@ use topcoat::router::{HeaderName, StatusCode, header, route}; use crate::server::{self, PendingPurpose}; -type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>; +pub(crate) type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>; -fn see(location: String) -> Redirect { +pub(crate) fn see(location: String) -> Redirect { Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)])) } diff --git a/crates/im-web/src/layout.rs b/crates/im-web/src/layout.rs index a897e41..dfb916b 100644 --- a/crates/im-web/src/layout.rs +++ b/crates/im-web/src/layout.rs @@ -20,6 +20,35 @@ pub async fn wordmark(cx: &Cx) -> Result { } } +/// The profile card's face: the photo when the account has one, the name's +/// first letter on a quiet tile when it does not. The URL's stamp comes from +/// `photo::PhotoStamps`, so a changed photo is a changed URL. +pub async fn avatar(cx: &Cx, user: &im_core::model::User) -> Result { + if user.has_photo { + let src = format!( + "/photo/{}?v={}", + user.id, + crate::photo::photo_stamp(cx, &user.id.to_string()) + ); + view! { + cx => + (user.name.clone()) + } + } else { + let initial = user + .name + .chars() + .next() + .unwrap_or('?') + .to_uppercase() + .to_string(); + view! { + cx => + (initial) + } + } +} + /// A full document around an already-rendered stage — the same way /// izlek-web's `#[layout]` receives its slot. pub async fn shell(cx: &Cx, title: &str, stage: Result) -> Result { diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index c1e8706..326ec9f 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -8,7 +8,7 @@ use im_core::store::Store; use topcoat::Result; use topcoat::asset::RouterBuilderAssetExt; use topcoat::cookie::RouterBuilderCookieExt; -use topcoat::router::{Router, RouterBuilderDiscoverExt, route}; +use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, route}; mod admin; mod auth; @@ -18,6 +18,8 @@ mod live; mod mailer; mod oidc; mod pages; +mod people; +mod photo; mod server; use config::Config; @@ -228,9 +230,14 @@ async fn serve(config: Config) { let router = Router::builder() .discover() + // Headroom over the photo cap: the boundary and part headers ride + // inside the body limit, so the handler's byte cap — not this layer — + // stays the one that says "over 5 MB". + .layer(BodyLimit::max(photo::PHOTO_LIMIT_BYTES as usize + 4096).at("/api/profile_photo")) .cookies() .assets(bundle) .app_context(app) + .app_context(photo::PhotoStamps::default()) .app_context(live::Shutdown(stopping)) .build(); diff --git a/crates/im-web/src/pages.rs b/crates/im-web/src/pages.rs index 761dd6d..dd95e41 100644 --- a/crates/im-web/src/pages.rs +++ b/crates/im-web/src/pages.rs @@ -11,7 +11,7 @@ use topcoat::router::response::{IntoResponse, Response}; use topcoat::router::{page, path_param, route}; use topcoat::view::view; -use crate::layout::{shell, wordmark}; +use crate::layout::{avatar, shell, wordmark}; use crate::server::{self, PendingPurpose}; path_param!(token); @@ -34,6 +34,9 @@ pub fn error_text(code: &str) -> &'static str { "password_wrong" => "That's not your current password.", "password_same" => "That's already your password.", "rate_limited" => "Too many tries — wait a while and try again.", + "photo_too_big" => "That image is over 5 MB.", + "not_an_image" => "That file is not an image.", + "no_file" => "Choose an image first.", "reset_invalid" => "This reset link is not valid — ask for a fresh one.", _ => "Something went wrong. Try again.", } @@ -43,6 +46,9 @@ pub fn error_text(code: &str) -> &'static str { pub fn ok_text(code: &str) -> &'static str { match code { "reset" => "Password changed — sign in with the new one.", + "enrolled" => "Two-factor sign-in is on. You're all set.", + "photo_saved" => "Profile photo updated.", + "photo_removed" => "Profile photo removed.", _ => "Done.", } } @@ -404,23 +410,115 @@ async fn enroll(cx: &Cx) -> Result { } /// The signed-in landing. im is an auth service, not an app: this page is -/// the proof of session, the way out, and nothing more. +/// the proof of session, the person's profile — photo and the counts their +/// identity has earned — and the way out. izlek gives a profile its own +/// page under `/people`; im has exactly one signed-in screen, so the +/// profile is a section of it. async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { let query = current_query(cx); let ok = query_value(&query, "ok"); + let error = query_value(&query, "error"); + let stats = im_core::stats::profile_stats(&server::app(cx).store, &user.id).await?; + let joined = user.created_at.date().to_string(); let stage = view! { cx =>
(wordmark(cx).await?)
-
-
(format!("Signed in as {}", user.name))
-
(user.email.clone())
+
+ (avatar(cx, user).await?) +
+
(user.name.clone())
+
+ if user.totp_confirmed { + "2FA on" + } else { + "2FA off" + } + if user.admin { + "Admin" + } +
+
- if ok.as_deref() == Some("enrolled") { -
"Two-factor sign-in is on. You're all set."
+ if let Some(code) = ok { +
(ok_text(&code))
+ } + if let Some(code) = error { +
(error_text(&code))
+ } +
+
+
"Email"
+
(user.email.clone())
+
+
+
"Member since"
+
(joined)
+
+
+
+ +
+ + if user.has_photo { + + } +
+
+ "Public profile" + if user.has_photo { +
} +
+
+
+
+
(stats.sign_ins)
+
"Sign-ins"
+
+
+
(stats.active_sessions)
+
"Active sessions"
+
+
+
(stats.connected_apps)
+
"Connected apps"
+
+
+
+