forge
Explore
Log in

Don't you dare go Hollow

Profile section: photo, statistics, public page

Browse files at this commit

8092e0d49f26f242a72b5803fa47fa4f5556a718Ahmet Kaan GümüşParent: 6099ac7
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/<user id> — 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.
.gitignoremodified+1 -0
@@ -6,3 +6,4 @@
66 /im-migrate-mapping.csv
77 /public/*
88 !/public/.gitkeep
9+/storage
Cargo.lockmodified+29 -0
@@ -1002,6 +1002,15 @@ version = "0.2.9"
10021002 source = "registry+https://github.com/rust-lang/crates.io-index"
10031003 checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
10041004
1005+[[package]]
1006+name = "encoding_rs"
1007+version = "0.8.35"
1008+source = "registry+https://github.com/rust-lang/crates.io-index"
1009+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
1010+dependencies = [
1011+ "cfg-if",
1012+]
1013+
10051014 [[package]]
10061015 name = "env_filter"
10071016 version = "2.0.0"
@@ -1828,6 +1837,7 @@ dependencies = [
18281837 "http",
18291838 "im-core",
18301839 "lettre",
1840+ "parking_lot",
18311841 "qrcode",
18321842 "serde",
18331843 "serde_json",
@@ -2281,6 +2291,23 @@ dependencies = [
22812291 "windows-sys 0.61.2",
22822292 ]
22832293
2294+[[package]]
2295+name = "multer"
2296+version = "3.1.0"
2297+source = "registry+https://github.com/rust-lang/crates.io-index"
2298+checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b"
2299+dependencies = [
2300+ "bytes",
2301+ "encoding_rs",
2302+ "futures-util",
2303+ "http",
2304+ "httparse",
2305+ "memchr",
2306+ "mime",
2307+ "spin",
2308+ "version_check",
2309+]
2310+
22842311 [[package]]
22852312 name = "murmurhash32"
22862313 version = "0.3.1"
@@ -4172,6 +4199,7 @@ dependencies = [
41724199 "bytes",
41734200 "form_urlencoded",
41744201 "futures-core",
4202+ "futures-util",
41754203 "heck",
41764204 "http",
41774205 "http-body",
@@ -4180,6 +4208,7 @@ dependencies = [
41804208 "hyper-util",
41814209 "inventory",
41824210 "matchit",
4211+ "multer",
41834212 "percent-encoding",
41844213 "ref-cast",
41854214 "serde",
crates/im-core/src/accounts.rsmodified+10 -6
@@ -378,6 +378,7 @@ pub async fn create_user_from_invite(
378378 email: invite.email.clone(),
379379 name: name.to_string(),
380380 totp_confirmed: false,
381+ has_photo: false,
381382 admin: invite.admin,
382383 disabled: false,
383384 created_at: store::now(),
@@ -644,8 +645,8 @@ pub async fn verify_login(
644645 let conn = store.conn.lock().await;
645646 let mut rows = conn
646647 .query(
647- "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at \
648- FROM users WHERE email = ?1 COLLATE NOCASE",
648+ "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at, \
649+ photo_mime IS NOT NULL FROM users WHERE email = ?1 COLLATE NOCASE",
649650 turso::params![email],
650651 )
651652 .await
@@ -659,6 +660,7 @@ pub async fn verify_login(
659660 email: store::text(&row, 1)?,
660661 name: store::text(&row, 2)?,
661662 totp_confirmed: store::int(&row, 4)? != 0,
663+ has_photo: store::int(&row, 8)? != 0,
662664 admin: store::int(&row, 5)? != 0,
663665 disabled: store::int(&row, 6)? != 0,
664666 created_at: store::parse_stamp(&store::text(&row, 7)?)?,
@@ -733,8 +735,8 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> {
733735 let conn = store.conn.lock().await;
734736 let mut rows = conn
735737 .query(
736- "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \
737- FROM users WHERE id = ?1",
738+ "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \
739+ photo_mime IS NOT NULL FROM users WHERE id = ?1",
738740 turso::params![id.to_string()],
739741 )
740742 .await
@@ -747,6 +749,7 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> {
747749 email: store::text(&row, 1)?,
748750 name: store::text(&row, 2)?,
749751 totp_confirmed: store::int(&row, 3)? != 0,
752+ has_photo: store::int(&row, 7)? != 0,
750753 admin: store::int(&row, 4)? != 0,
751754 disabled: store::int(&row, 5)? != 0,
752755 created_at: store::parse_stamp(&store::text(&row, 6)?)?,
@@ -779,8 +782,8 @@ pub async fn list_users(store: &Store) -> Result<Vec<User>> {
779782 let conn = store.conn.lock().await;
780783 let mut rows = conn
781784 .query(
782- "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \
783- FROM users ORDER BY created_at",
785+ "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \
786+ photo_mime IS NOT NULL FROM users ORDER BY created_at",
784787 (),
785788 )
786789 .await
@@ -792,6 +795,7 @@ pub async fn list_users(store: &Store) -> Result<Vec<User>> {
792795 email: store::text(&row, 1)?,
793796 name: store::text(&row, 2)?,
794797 totp_confirmed: store::int(&row, 3)? != 0,
798+ has_photo: store::int(&row, 7)? != 0,
795799 admin: store::int(&row, 4)? != 0,
796800 disabled: store::int(&row, 5)? != 0,
797801 created_at: store::parse_stamp(&store::text(&row, 6)?)?,
crates/im-core/src/lib.rsmodified+4 -0
@@ -14,12 +14,16 @@ pub mod keys;
1414 #[cfg(feature = "server")]
1515 pub mod oidc;
1616 #[cfg(feature = "server")]
17+pub mod photos;
18+#[cfg(feature = "server")]
1719 mod secret;
1820 #[cfg(feature = "server")]
1921 pub mod sessions;
2022 #[cfg(feature = "server")]
2123 pub mod settings;
2224 #[cfg(feature = "server")]
25+pub mod stats;
26+#[cfg(feature = "server")]
2327 pub mod store;
2428 #[cfg(feature = "server")]
2529 pub mod totp;
crates/im-core/src/model.rsmodified+3 -0
@@ -51,6 +51,9 @@ pub struct User {
5151 pub email: String,
5252 pub name: String,
5353 pub totp_confirmed: bool,
54+ /// Whether this person has a profile photo: the row keeps the mime
55+ /// type, the bytes live as a file under the storage tree (`photos.rs`).
56+ pub has_photo: bool,
5457 /// im's own admin flag — never crosses a token; AuthN stays the only
5558 /// thing apps receive.
5659 pub admin: bool,
crates/im-core/src/photos.rsadded+276 -0
@@ -0,0 +1,276 @@
1+//! Profile photos: the row keeps the mime type, the storage tree keeps the
2+//! bytes — one file per user at `<storage>/photos/<user id>`, the same
3+//! split izlek-core keeps. The web layer caps the upload (5 MiB) and sniffs
4+//! the mime before anything here runs; this module trusts both, the way
5+//! `accounts` trusts the password rules were checked.
6+//!
7+//! Writes order themselves so a crash leaves stale bytes, never destroyed
8+//! ones: `set_photo` stages the new file under a name no row wears, commits
9+//! the row, and only then renames over the old photo; `clear_photo` commits
10+//! the row first and unlinks best-effort. Whatever a crash strands — staged
11+//! files, files no row names — the boot sweep collects (see
12+//! [`sweep_orphan_files`], run from `Store::open`).
13+
14+use crate::model::UserId;
15+use crate::store::{Result, Store, StoreError, backend};
16+
17+/// Where `user_id`'s photo lives inside the store's photos directory. Named
18+/// by the user id the store minted — never by anything an upload carried —
19+/// so a path here is always exactly one store-named file deep.
20+fn photo_file(store: &Store, user_id: &str) -> std::path::PathBuf {
21+ store.photos_dir.join(user_id)
22+}
23+
24+/// Writes `bytes` to `path` through a temporary file in the same directory
25+/// and a rename: a crash or a full disk mid-write leaves whatever file was
26+/// there before intact, never a truncated one under the real name.
27+fn write_file_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
28+ use std::io::Write as _;
29+ let tmp = path.with_extension(format!("{}.tmp", ulid::Ulid::new()));
30+ let mut file = std::fs::File::create(&tmp)?;
31+ file.write_all(bytes)?;
32+ file.sync_all()?;
33+ std::fs::rename(&tmp, path)
34+}
35+
36+/// Stores the photo's bytes and mime type, replacing any previous one.
37+pub async fn set_photo(store: &Store, user: &UserId, bytes: &[u8], mime: &str) -> Result<()> {
38+ let id = user.to_string();
39+ let path = photo_file(store, &id);
40+ // The new bytes stage under a name no row wears, the row commits, and
41+ // only then does the rename put them over the old photo: a failed update
42+ // leaves the committed photo exactly as it was, and a crash between
43+ // commit and rename serves the old bytes next to a staged file the boot
44+ // sweep collects — stale, never destroyed.
45+ let staged = path.with_extension(format!("incoming-{}", ulid::Ulid::new()));
46+ write_file_atomic(&staged, bytes).map_err(|e| StoreError::Backend(e.to_string()))?;
47+ let written = {
48+ let conn = store.conn.lock().await;
49+ conn.execute(
50+ "UPDATE users SET photo_mime = ?1 WHERE id = ?2",
51+ turso::params![mime, id.clone()],
52+ )
53+ .await
54+ };
55+ if let Err(e) = written {
56+ let _ = std::fs::remove_file(&staged);
57+ return Err(backend(e));
58+ }
59+ std::fs::rename(&staged, &path).map_err(|e| StoreError::Backend(e.to_string()))?;
60+ Ok(())
61+}
62+
63+/// Clears the photo. The row goes first: the file may only follow a delete
64+/// that committed, or a crash in between would leave a row whose photo is
65+/// gone. The unlink is best-effort — a file that survives it is orphaned
66+/// bytes the boot sweep collects.
67+pub async fn clear_photo(store: &Store, user: &UserId) -> Result<()> {
68+ let id = user.to_string();
69+ {
70+ let conn = store.conn.lock().await;
71+ conn.execute(
72+ "UPDATE users SET photo_mime = NULL WHERE id = ?1",
73+ turso::params![id.clone()],
74+ )
75+ .await
76+ .map_err(backend)?;
77+ }
78+ let _ = std::fs::remove_file(photo_file(store, &id));
79+ Ok(())
80+}
81+
82+/// The photo's bytes and mime type, or `None` when none is set. A row whose
83+/// file went missing is reported at boot; the read answers "nothing to
84+/// serve" rather than failing the page.
85+pub async fn photo(store: &Store, user: &UserId) -> Result<Option<(Vec<u8>, String)>> {
86+ let id = user.to_string();
87+ let mime = {
88+ let conn = store.conn.lock().await;
89+ let mut rows = conn
90+ .query(
91+ "SELECT photo_mime FROM users WHERE id = ?1",
92+ turso::params![id.clone()],
93+ )
94+ .await
95+ .map_err(backend)?;
96+ match rows.next().await.map_err(backend)? {
97+ Some(row) => crate::store::opt_text(&row, 0)?,
98+ None => return Ok(None),
99+ }
100+ };
101+ let Some(mime) = mime else {
102+ return Ok(None);
103+ };
104+ match std::fs::read(photo_file(store, &id)) {
105+ Ok(bytes) => Ok(Some((bytes, mime))),
106+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
107+ Err(e) => Err(StoreError::Backend(e.to_string())),
108+ }
109+}
110+
111+/// Sets the photos tree against the database, once per boot. The two are
112+/// halves of one state, and a crash between a row write and its file write —
113+/// either order — leaves exactly one half behind: a file no row names goes
114+/// (staged `incoming-*` and `*.tmp` leftovers first), and a row whose file
115+/// is missing is reported. Never fails the boot — a sweep that cannot read
116+/// its own directory has nothing safe to delete anyway.
117+pub(crate) async fn sweep_orphan_files(store: &Store) {
118+ let known: std::collections::HashSet<String> = {
119+ let conn = store.conn.lock().await;
120+ let mut rows = match conn
121+ .query("SELECT id FROM users WHERE photo_mime IS NOT NULL", ())
122+ .await
123+ {
124+ Ok(rows) => rows,
125+ Err(e) => {
126+ eprintln!(
127+ "im photos: could not list photo rows for the sweep: {}",
128+ backend(e)
129+ );
130+ return;
131+ }
132+ };
133+ let mut ids = std::collections::HashSet::new();
134+ loop {
135+ match rows.next().await {
136+ Ok(Some(row)) => match crate::store::text(&row, 0) {
137+ Ok(id) => {
138+ ids.insert(id);
139+ }
140+ Err(e) => {
141+ eprintln!("im photos: sweep could not read a user id: {e}");
142+ return;
143+ }
144+ },
145+ Ok(None) => break,
146+ Err(e) => {
147+ eprintln!("im photos: sweep could not read photo rows: {}", backend(e));
148+ return;
149+ }
150+ }
151+ }
152+ ids
153+ };
154+ // Rows whose file went missing: reported, never failed — the photo read
155+ // already answers "nothing to serve" for them.
156+ for id in &known {
157+ if !store.photos_dir.join(id).is_file() {
158+ eprintln!("im photos: {id} has a photo row but no file");
159+ }
160+ }
161+ let entries = match std::fs::read_dir(&store.photos_dir) {
162+ Ok(entries) => entries,
163+ Err(e) => {
164+ eprintln!(
165+ "im photos: could not sweep {}: {e}",
166+ store.photos_dir.display()
167+ );
168+ return;
169+ }
170+ };
171+ for entry in entries.flatten() {
172+ let name = entry.file_name().to_string_lossy().to_string();
173+ let staged = name.contains(".incoming-") || name.contains(".tmp");
174+ if (staged || !known.contains(&name))
175+ && let Err(e) = std::fs::remove_file(entry.path())
176+ {
177+ eprintln!("im photos: could not delete orphaned file {name}: {e}");
178+ }
179+ }
180+}
181+
182+#[cfg(test)]
183+mod tests {
184+ use super::*;
185+ use crate::accounts::{create_invite, create_user_from_invite, user_by_id};
186+ use std::path::Path;
187+
188+ async fn fixture() -> (Store, UserId) {
189+ let store = Store::open(Path::new(":memory:")).await.unwrap();
190+ let invite = create_invite(&store, "ann@example.com", None, false)
191+ .await
192+ .unwrap();
193+ let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv")
194+ .await
195+ .unwrap();
196+ (store, user.id)
197+ }
198+
199+ #[tokio::test]
200+ async fn photo_roundtrip() {
201+ let (store, user_id) = fixture().await;
202+ assert!(photo(&store, &user_id).await.unwrap().is_none());
203+ assert!(
204+ !user_by_id(&store, &user_id)
205+ .await
206+ .unwrap()
207+ .unwrap()
208+ .has_photo
209+ );
210+
211+ set_photo(&store, &user_id, b"\x89PNG-fake", "image/png")
212+ .await
213+ .unwrap();
214+ let (bytes, mime) = photo(&store, &user_id).await.unwrap().unwrap();
215+ assert_eq!(bytes, b"\x89PNG-fake");
216+ assert_eq!(mime, "image/png");
217+ assert!(
218+ user_by_id(&store, &user_id)
219+ .await
220+ .unwrap()
221+ .unwrap()
222+ .has_photo
223+ );
224+ // The bytes are a file named by the user id — never a column.
225+ let file = photo_file(&store, &user_id.to_string());
226+ assert_eq!(std::fs::read(&file).unwrap(), b"\x89PNG-fake");
227+
228+ // A second upload replaces, it does not append.
229+ set_photo(&store, &user_id, b"\xff\xd8\xff", "image/jpeg")
230+ .await
231+ .unwrap();
232+ let (bytes, mime) = photo(&store, &user_id).await.unwrap().unwrap();
233+ assert_eq!(bytes, b"\xff\xd8\xff");
234+ assert_eq!(mime, "image/jpeg");
235+
236+ clear_photo(&store, &user_id).await.unwrap();
237+ assert!(photo(&store, &user_id).await.unwrap().is_none());
238+ assert!(
239+ !user_by_id(&store, &user_id)
240+ .await
241+ .unwrap()
242+ .unwrap()
243+ .has_photo
244+ );
245+ assert!(!file.exists());
246+ }
247+
248+ #[tokio::test]
249+ async fn a_row_without_its_file_reads_as_no_photo() {
250+ let (store, user_id) = fixture().await;
251+ set_photo(&store, &user_id, b"\x89PNG-fake", "image/png")
252+ .await
253+ .unwrap();
254+ std::fs::remove_file(photo_file(&store, &user_id.to_string())).unwrap();
255+ assert!(photo(&store, &user_id).await.unwrap().is_none());
256+ }
257+
258+ #[tokio::test]
259+ async fn the_boot_sweep_collects_orphans_and_staged_files() {
260+ let (store, user_id) = fixture().await;
261+ set_photo(&store, &user_id, b"\x89PNG-fake", "image/png")
262+ .await
263+ .unwrap();
264+ let real = photo_file(&store, &user_id.to_string());
265+ let staged = real.with_extension("incoming-deadbeef");
266+ let stranger = store.photos_dir.join("01STRANGERXXXXXXXXXXXXXXXXX0");
267+ std::fs::write(&staged, b"half an upload").unwrap();
268+ std::fs::write(&stranger, b"no row names me").unwrap();
269+
270+ sweep_orphan_files(&store).await;
271+
272+ assert!(real.is_file());
273+ assert!(!staged.exists());
274+ assert!(!stranger.exists());
275+ }
276+}
crates/im-core/src/stats.rsadded+151 -0
@@ -0,0 +1,151 @@
1+//! The profile page's statistics: how often this identity has been used,
2+//! and what is holding it right now.
3+//!
4+//! Everything here derives from rows the system already keeps — a session
5+//! row per sign-in, an app-session row per app a sign-in was handed to. No
6+//! counters, nothing to drift: the page's numbers are the tables, read.
7+
8+use crate::model::UserId;
9+use crate::store::{self, Result, Store, backend};
10+
11+/// One person's counts, for the profile section of the signed-in landing.
12+#[derive(Debug, Clone, PartialEq, Eq)]
13+pub struct ProfileStats {
14+ /// Every sign-in ever: one central-session row is written per login.
15+ pub sign_ins: u64,
16+ /// Sessions neither revoked nor expired — the devices that could act
17+ /// as this person right now.
18+ pub active_sessions: u64,
19+ /// Apps holding a live token for this person (distinct OIDC clients
20+ /// with an unrevoked, unexpired app session).
21+ pub connected_apps: u64,
22+}
23+
24+/// Reads the three counts. One round-trip: the tables are small, and the
25+/// landing is the only reader.
26+pub async fn profile_stats(store: &Store, user: &UserId) -> Result<ProfileStats> {
27+ let conn = store.conn.lock().await;
28+ let id = user.to_string();
29+ let now = store::stamp(store::now())?;
30+ let mut rows = conn
31+ .query(
32+ "SELECT \
33+ (SELECT COUNT(*) FROM sessions WHERE user_id = ?1), \
34+ (SELECT COUNT(*) FROM sessions \
35+ WHERE user_id = ?1 AND revoked_at IS NULL AND expires_at > ?2), \
36+ (SELECT COUNT(DISTINCT client_id) FROM app_sessions \
37+ WHERE user_id = ?1 AND revoked_at IS NULL AND expires_at > ?2)",
38+ turso::params![id, now],
39+ )
40+ .await
41+ .map_err(backend)?;
42+ let row = rows
43+ .next()
44+ .await
45+ .map_err(backend)?
46+ .ok_or_else(|| backend("counts query returned no row"))?;
47+ Ok(ProfileStats {
48+ sign_ins: store::int(&row, 0)? as u64,
49+ active_sessions: store::int(&row, 1)? as u64,
50+ connected_apps: store::int(&row, 2)? as u64,
51+ })
52+}
53+
54+#[cfg(test)]
55+mod tests {
56+ use super::*;
57+ use crate::accounts::{create_invite, create_user_from_invite};
58+ use std::path::Path;
59+
60+ async fn fixture() -> (Store, UserId) {
61+ let store = Store::open(Path::new(":memory:")).await.unwrap();
62+ let invite = create_invite(&store, "ann@example.com", None, false)
63+ .await
64+ .unwrap();
65+ let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv")
66+ .await
67+ .unwrap();
68+ (store, user.id)
69+ }
70+
71+ /// Stamps relative to now, so "expired" and "live" rows stay on their
72+ /// own sides of the comparison whatever the clock says at test time.
73+ fn stamp_in(hours: i64) -> String {
74+ store::stamp(store::now() + time::Duration::hours(hours)).unwrap()
75+ }
76+
77+ #[tokio::test]
78+ async fn counts_reflect_the_tables() {
79+ let (store, user_id) = fixture().await;
80+ let id = user_id.to_string();
81+ {
82+ let conn = store.conn.lock().await;
83+ // Three sign-ins: one expired, one revoked, one live.
84+ for (hash, expires, revoked) in [
85+ ("h-expired", stamp_in(-1), None),
86+ ("h-revoked", stamp_in(24), Some(stamp_in(-1))),
87+ ("h-live", stamp_in(24), None),
88+ ] {
89+ conn.execute(
90+ "INSERT INTO sessions (token_hash, user_id, created_at, expires_at, revoked_at) \
91+ VALUES (?1, ?2, ?3, ?4, ?5)",
92+ turso::params![hash, id.clone(), stamp_in(-24), expires, revoked],
93+ )
94+ .await
95+ .unwrap();
96+ }
97+ // A client the app sessions point at, then three app sessions:
98+ // two live for one client (counts once), one revoked for another.
99+ conn.execute(
100+ "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \
101+ VALUES ('client-a', 'A', 'x', '[]', ?1)",
102+ turso::params![stamp_in(-24)],
103+ )
104+ .await
105+ .unwrap();
106+ conn.execute(
107+ "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \
108+ VALUES ('client-b', 'B', 'x', '[]', ?1)",
109+ turso::params![stamp_in(-24)],
110+ )
111+ .await
112+ .unwrap();
113+ for (hash, client, expires, revoked) in [
114+ ("a1", "client-a", stamp_in(24), None),
115+ ("a2", "client-a", stamp_in(24), None),
116+ ("b1", "client-b", stamp_in(24), Some(stamp_in(-1))),
117+ ] {
118+ conn.execute(
119+ "INSERT INTO app_sessions \
120+ (token_hash, user_id, client_id, session_hash, created_at, expires_at, revoked_at) \
121+ VALUES (?1, ?2, ?3, 'h-live', ?4, ?5, ?6)",
122+ turso::params![hash, id.clone(), client, stamp_in(-24), expires, revoked],
123+ )
124+ .await
125+ .unwrap();
126+ }
127+ }
128+ let stats = profile_stats(&store, &user_id).await.unwrap();
129+ assert_eq!(
130+ stats,
131+ ProfileStats {
132+ sign_ins: 3,
133+ active_sessions: 1,
134+ connected_apps: 1,
135+ }
136+ );
137+ }
138+
139+ #[tokio::test]
140+ async fn a_fresh_account_reads_zero() {
141+ let (store, user_id) = fixture().await;
142+ assert_eq!(
143+ profile_stats(&store, &user_id).await.unwrap(),
144+ ProfileStats {
145+ sign_ins: 0,
146+ active_sessions: 0,
147+ connected_apps: 0,
148+ }
149+ );
150+ }
151+}
crates/im-core/src/store.rsmodified+80 -5
@@ -37,7 +37,8 @@ CREATE TABLE IF NOT EXISTS users (
3737 totp_confirmed INTEGER NOT NULL DEFAULT 0,
3838 admin INTEGER NOT NULL DEFAULT 0,
3939 disabled INTEGER NOT NULL DEFAULT 0,
40- created_at TEXT NOT NULL
40+ created_at TEXT NOT NULL,
41+ photo_mime TEXT
4142 );
4243 CREATE TABLE IF NOT EXISTS invites (
4344 token TEXT PRIMARY KEY,
@@ -127,12 +128,33 @@ CREATE TABLE IF NOT EXISTS settings (
127128 pub struct Store {
128129 pub(crate) conn: tokio::sync::Mutex<Connection>,
129130 pub(crate) key: Key,
131+ /// The directory profile photos live in, one file per user, named by the
132+ /// user id — the same contract izlek-core's storage tree keeps: the
133+ /// database keeps the facts, this tree keeps the bytes, back the two up
134+ /// together.
135+ pub(crate) photos_dir: std::path::PathBuf,
130136 }
131137
132138 impl Store {
133139 /// Opens (creating if needed) the database at `path` and runs the schema
134140 /// migration. `:memory:` gives a test store with a fresh throwaway key.
135141 pub async fn open(path: &Path) -> Result<Store> {
142+ // The tree goes in before anything else — every writer past this
143+ // point assumes the directory is there to write into.
144+ let photos_dir = photos_dir(path);
145+ std::fs::create_dir_all(&photos_dir).map_err(|e| {
146+ StoreError::Backend(format!(
147+ "creating photos directory {}: {e}",
148+ photos_dir.display()
149+ ))
150+ })?;
151+ #[cfg(unix)]
152+ {
153+ use std::os::unix::fs::PermissionsExt;
154+ std::fs::set_permissions(&photos_dir, std::fs::Permissions::from_mode(0o700)).map_err(
155+ |e| StoreError::Backend(format!("restricting {}: {e}", photos_dir.display())),
156+ )?;
157+ }
136158 let raw = path
137159 .to_str()
138160 .ok_or_else(|| StoreError::Corrupt("path is not utf-8".into()))?;
@@ -141,8 +163,10 @@ impl Store {
141163 let store = Store {
142164 conn: tokio::sync::Mutex::new(conn),
143165 key: load_key(path)?,
166+ photos_dir,
144167 };
145168 store.migrate().await?;
169+ crate::photos::sweep_orphan_files(&store).await;
146170 Ok(store)
147171 }
148172
@@ -152,11 +176,31 @@ impl Store {
152176 // schema write.
153177 let conn = self.conn.lock().await;
154178 conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
155- if let Err(e) = conn.execute_batch(SCHEMA).await {
156- let _ = conn.execute("ROLLBACK", ()).await;
157- return Err(backend(e));
179+ let outcome = async {
180+ conn.execute_batch(SCHEMA).await.map_err(backend)?;
181+ // Columns born after databases already existed: the CREATE above
182+ // is `IF NOT EXISTS`, so an old users table never sees them from
183+ // it. Each goes in with its own guarded ALTER — a boot either
184+ // adds the column or finds it there, and re-boot is a no-op.
185+ // The photo's bytes are never a column: they live as files under
186+ // the storage tree (see `photos.rs`).
187+ if !has_column(&conn, "users", "photo_mime").await? {
188+ conn.execute("ALTER TABLE users ADD COLUMN photo_mime TEXT", ())
189+ .await
190+ .map_err(backend)?;
191+ }
192+ Ok(())
193+ }
194+ .await;
195+ match outcome {
196+ Ok(()) => {
197+ conn.execute("COMMIT", ()).await.map_err(backend)?;
198+ }
199+ Err(e) => {
200+ let _ = conn.execute("ROLLBACK", ()).await;
201+ return Err(e);
202+ }
158203 }
159- conn.execute("COMMIT", ()).await.map_err(backend)?;
160204 Ok(())
161205 }
162206
@@ -177,6 +221,37 @@ impl Store {
177221 }
178222 }
179223
224+/// The directory a database's profile photos live in: a `storage/photos`
225+/// tree beside the database file, so a backup that takes the database takes
226+/// the photos with it. `:memory:` has no directory to anchor to — its tree
227+/// is a fresh tempdir, as throwaway as the database itself.
228+fn photos_dir(path: &Path) -> std::path::PathBuf {
229+ if path.as_os_str() == ":memory:" {
230+ return std::env::temp_dir().join(format!("im-storage-{}", ulid::Ulid::new()));
231+ }
232+ path.parent()
233+ .filter(|d| !d.as_os_str().is_empty())
234+ .unwrap_or_else(|| Path::new("."))
235+ .join("storage")
236+ .join("photos")
237+}
238+
239+/// Whether `table` carries `column` — the migration's guard for ALTERs that
240+/// must be no-ops on databases already carrying them. Both names are
241+/// literals from this module, never request data.
242+async fn has_column(conn: &Connection, table: &str, column: &str) -> Result<bool> {
243+ let mut rows = conn
244+ .query(format!("PRAGMA table_info({table})"), ())
245+ .await
246+ .map_err(backend)?;
247+ while let Some(row) = rows.next().await.map_err(backend)? {
248+ if row.get::<String>(1).map_err(backend)? == column {
249+ return Ok(true);
250+ }
251+ }
252+ Ok(false)
253+}
254+
180255 /// The key for `path`'s database. `:memory:` has no directory to anchor a
181256 /// sibling file to, so it gets a key generated fresh in memory — every
182257 /// in-memory store is its own, unrelated encryption domain.
crates/im-web/Cargo.tomlmodified+2 -0
@@ -17,9 +17,11 @@ topcoat = { version = "0.6.2", default-features = false, features = [
1717 "discover",
1818 "serve",
1919 "compression",
20+ "multipart",
2021 "sse",
2122 ] }
2223 futures-util = { version = "0.3", default-features = false }
24+parking_lot = "0.12"
2325 im-core = { workspace = true, features = ["server"] }
2426 serde.workspace = true
2527 serde_json.workspace = true
crates/im-web/assets/main.cssmodified+116 -0
@@ -334,6 +334,122 @@ body:has(.auth-stage) > .auth-stage::-webkit-scrollbar {
334334 padding-top: 4px;
335335 }
336336
337+.profile-head {
338+ display: flex;
339+ align-items: center;
340+ gap: 14px;
341+}
342+
343+.profile-avatar {
344+ flex: none;
345+ width: 72px;
346+ height: 72px;
347+ border-radius: var(--radius);
348+ border: 1px solid var(--border);
349+ object-fit: cover;
350+}
351+
352+.profile-avatar-initial {
353+ display: flex;
354+ align-items: center;
355+ justify-content: center;
356+ background: var(--panel-sunken);
357+ color: var(--muted);
358+ font-family: var(--font-mono);
359+ font-size: 26px;
360+ font-weight: 500;
361+ user-select: none;
362+}
363+
364+.profile-heading {
365+ display: flex;
366+ flex-direction: column;
367+ gap: 6px;
368+ min-width: 0;
369+}
370+
371+.profile-marks {
372+ display: flex;
373+ gap: 6px;
374+ flex-wrap: wrap;
375+}
376+
377+.chip-accent {
378+ background: var(--accent-tint);
379+ border: 1px solid var(--border-strong);
380+ color: var(--accent-ink);
381+}
382+
383+.profile-fields {
384+ margin: 0;
385+ display: flex;
386+ flex-direction: column;
387+ gap: 10px;
388+}
389+
390+.profile-field {
391+ display: flex;
392+ flex-direction: column;
393+ gap: 4px;
394+}
395+
396+.profile-value {
397+ margin: 0;
398+ font-size: 13px;
399+}
400+
401+.profile-photo-actions {
402+ display: flex;
403+ gap: 8px;
404+ align-items: center;
405+}
406+.profile-photo-actions .profile-upload {
407+ flex: 1;
408+ width: auto;
409+}
410+
411+#profile-photo-remove {
412+ display: none;
413+}
414+
415+.profile-file {
416+ height: auto;
417+ padding: 7px 12px;
418+ font-size: 12px;
419+ color: var(--muted);
420+}
421+.profile-file::file-selector-button {
422+ margin-right: 10px;
423+ padding: 4px 10px;
424+ background: var(--panel-sunken);
425+ border: 1px solid var(--border-strong);
426+ border-radius: var(--radius);
427+ color: var(--ink);
428+ font-family: var(--font-sans);
429+ font-size: 12px;
430+ cursor: pointer;
431+}
432+
433+.profile-stats {
434+ margin: 0;
435+ display: flex;
436+ justify-content: space-between;
437+ gap: 12px;
438+}
439+
440+.profile-stat {
441+ display: flex;
442+ flex-direction: column;
443+ gap: 2px;
444+}
445+
446+.profile-stat-value {
447+ margin: 0;
448+ font-size: 22px;
449+ font-weight: 600;
450+ letter-spacing: -0.01em;
451+}
452+
337453 @media (max-width: 720px) {
338454 .auth-stage {
339455 padding: 0 16px 24px;
crates/im-web/src/auth.rsmodified+2 -2
@@ -12,9 +12,9 @@ use topcoat::router::{HeaderName, StatusCode, header, route};
1212
1313 use crate::server::{self, PendingPurpose};
1414
15-type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>;
15+pub(crate) type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>;
1616
17-fn see(location: String) -> Redirect {
17+pub(crate) fn see(location: String) -> Redirect {
1818 Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)]))
1919 }
2020
crates/im-web/src/layout.rsmodified+29 -0
@@ -20,6 +20,35 @@ pub async fn wordmark(cx: &Cx) -> Result {
2020 }
2121 }
2222
23+/// The profile card's face: the photo when the account has one, the name's
24+/// first letter on a quiet tile when it does not. The URL's stamp comes from
25+/// `photo::PhotoStamps`, so a changed photo is a changed URL.
26+pub async fn avatar(cx: &Cx, user: &im_core::model::User) -> Result {
27+ if user.has_photo {
28+ let src = format!(
29+ "/photo/{}?v={}",
30+ user.id,
31+ crate::photo::photo_stamp(cx, &user.id.to_string())
32+ );
33+ view! {
34+ cx =>
35+ <img class="profile-avatar" src=(src) alt=(user.name.clone())>
36+ }
37+ } else {
38+ let initial = user
39+ .name
40+ .chars()
41+ .next()
42+ .unwrap_or('?')
43+ .to_uppercase()
44+ .to_string();
45+ view! {
46+ cx =>
47+ <span class="profile-avatar profile-avatar-initial">(initial)</span>
48+ }
49+ }
50+}
51+
2352 /// A full document around an already-rendered stage — the same way
2453 /// izlek-web's `#[layout]` receives its slot.
2554 pub async fn shell(cx: &Cx, title: &str, stage: Result) -> Result {
crates/im-web/src/main.rsmodified+8 -1
@@ -8,7 +8,7 @@ use im_core::store::Store;
88 use topcoat::Result;
99 use topcoat::asset::RouterBuilderAssetExt;
1010 use topcoat::cookie::RouterBuilderCookieExt;
11-use topcoat::router::{Router, RouterBuilderDiscoverExt, route};
11+use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, route};
1212
1313 mod admin;
1414 mod auth;
@@ -18,6 +18,8 @@ mod live;
1818 mod mailer;
1919 mod oidc;
2020 mod pages;
21+mod people;
22+mod photo;
2123 mod server;
2224
2325 use config::Config;
@@ -228,9 +230,14 @@ async fn serve(config: Config) {
228230
229231 let router = Router::builder()
230232 .discover()
233+ // Headroom over the photo cap: the boundary and part headers ride
234+ // inside the body limit, so the handler's byte cap — not this layer —
235+ // stays the one that says "over 5 MB".
236+ .layer(BodyLimit::max(photo::PHOTO_LIMIT_BYTES as usize + 4096).at("/api/profile_photo"))
231237 .cookies()
232238 .assets(bundle)
233239 .app_context(app)
240+ .app_context(photo::PhotoStamps::default())
234241 .app_context(live::Shutdown(stopping))
235242 .build();
236243
crates/im-web/src/pages.rsmodified+105 -7
@@ -11,7 +11,7 @@ use topcoat::router::response::{IntoResponse, Response};
1111 use topcoat::router::{page, path_param, route};
1212 use topcoat::view::view;
1313
14-use crate::layout::{shell, wordmark};
14+use crate::layout::{avatar, shell, wordmark};
1515 use crate::server::{self, PendingPurpose};
1616
1717 path_param!(token);
@@ -34,6 +34,9 @@ pub fn error_text(code: &str) -> &'static str {
3434 "password_wrong" => "That's not your current password.",
3535 "password_same" => "That's already your password.",
3636 "rate_limited" => "Too many tries — wait a while and try again.",
37+ "photo_too_big" => "That image is over 5 MB.",
38+ "not_an_image" => "That file is not an image.",
39+ "no_file" => "Choose an image first.",
3740 "reset_invalid" => "This reset link is not valid — ask for a fresh one.",
3841 _ => "Something went wrong. Try again.",
3942 }
@@ -43,6 +46,9 @@ pub fn error_text(code: &str) -> &'static str {
4346 pub fn ok_text(code: &str) -> &'static str {
4447 match code {
4548 "reset" => "Password changed — sign in with the new one.",
49+ "enrolled" => "Two-factor sign-in is on. You're all set.",
50+ "photo_saved" => "Profile photo updated.",
51+ "photo_removed" => "Profile photo removed.",
4652 _ => "Done.",
4753 }
4854 }
@@ -404,23 +410,115 @@ async fn enroll(cx: &Cx) -> Result<Response> {
404410 }
405411
406412 /// The signed-in landing. im is an auth service, not an app: this page is
407-/// the proof of session, the way out, and nothing more.
413+/// the proof of session, the person's profile — photo and the counts their
414+/// identity has earned — and the way out. izlek gives a profile its own
415+/// page under `/people`; im has exactly one signed-in screen, so the
416+/// profile is a section of it.
408417 async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result {
409418 let query = current_query(cx);
410419 let ok = query_value(&query, "ok");
420+ let error = query_value(&query, "error");
421+ let stats = im_core::stats::profile_stats(&server::app(cx).store, &user.id).await?;
422+ let joined = user.created_at.date().to_string();
411423 let stage = view! {
412424 cx =>
413425 <main class="auth-stage">
414426 <div class="auth-column">
415427 (wordmark(cx).await?)
416428 <div class="auth-card">
417- <div class="auth-head">
418- <div class="auth-title">(format!("Signed in as {}", user.name))</div>
419- <div class="auth-sub">(user.email.clone())</div>
429+ <div class="profile-head">
430+ (avatar(cx, user).await?)
431+ <div class="profile-heading">
432+ <div class="auth-title">(user.name.clone())</div>
433+ <div class="profile-marks">
434+ if user.totp_confirmed {
435+ <span class="chip chip-connected">"2FA on"</span>
436+ } else {
437+ <span class="chip chip-muted">"2FA off"</span>
438+ }
439+ if user.admin {
440+ <span class="chip chip-accent">"Admin"</span>
441+ }
442+ </div>
443+ </div>
420444 </div>
421- if ok.as_deref() == Some("enrolled") {
422- <div class="auth-ok">"Two-factor sign-in is on. You're all set."</div>
445+ if let Some(code) = ok {
446+ <div class="auth-ok">(ok_text(&code))</div>
447+ }
448+ if let Some(code) = error {
449+ <div class="auth-problem">(error_text(&code))</div>
450+ }
451+ <dl class="profile-fields">
452+ <div class="profile-field">
453+ <dt class="auth-label">"Email"</dt>
454+ <dd class="profile-value mono">(user.email.clone())</dd>
455+ </div>
456+ <div class="profile-field">
457+ <dt class="auth-label">"Member since"</dt>
458+ <dd class="profile-value">(joined)</dd>
459+ </div>
460+ </dl>
461+ <form
462+ class="profile-photo-form"
463+ method="post"
464+ action="/api/profile_photo"
465+ enctype="multipart/form-data"
466+ >
467+ <label class="auth-field">
468+ <span class="auth-label">"Profile photo"</span>
469+ <input
470+ class="auth-input profile-file"
471+ type="file"
472+ name="photo"
473+ accept="image/png,image/jpeg,image/gif,image/webp,image/avif"
474+ required=""
475+ >
476+ </label>
477+ <div class="profile-photo-actions">
478+ <button class="auth-submit profile-upload" type="submit">
479+ if user.has_photo {
480+ <span class="auth-submit-text">"Change"</span>
481+ } else {
482+ <span class="auth-submit-text">"Upload"</span>
483+ }
484+ </button>
485+ if user.has_photo {
486+ <button
487+ class="admin-action"
488+ type="submit"
489+ form="profile-photo-remove"
490+ >
491+ "Remove"
492+ </button>
493+ }
494+ </div>
495+ </form>
496+ <a class="auth-alt" href=(format!("/people/{}", user.id))>"Public profile"</a>
497+ if user.has_photo {
498+ <form
499+ id="profile-photo-remove"
500+ method="post"
501+ action="/api/delete_profile_photo"
502+ ></form>
423503 }
504+ </div>
505+ <div class="auth-card">
506+ <dl class="profile-stats">
507+ <div class="profile-stat">
508+ <dd class="profile-stat-value">(stats.sign_ins)</dd>
509+ <dt class="auth-label">"Sign-ins"</dt>
510+ </div>
511+ <div class="profile-stat">
512+ <dd class="profile-stat-value">(stats.active_sessions)</dd>
513+ <dt class="auth-label">"Active sessions"</dt>
514+ </div>
515+ <div class="profile-stat">
516+ <dd class="profile-stat-value">(stats.connected_apps)</dd>
517+ <dt class="auth-label">"Connected apps"</dt>
518+ </div>
519+ </dl>
520+ </div>
521+ <div class="auth-card">
424522 <form method="post" action="/logout">
425523 <button class="auth-submit" type="submit">
426524 <span class="auth-submit-text">"Sign out everywhere"</span>
crates/im-web/src/people.rsadded+93 -0
@@ -0,0 +1,93 @@
1+//! A member's public profile: who they are, and what their identity has
2+//! done here. Any signed-in member may read it, and nothing on the page
3+//! writes — the one editor a profile has is the landing, which the page
4+//! links to for its own person and nowhere else. A stranger and a missing
5+//! id read the same: the router's own not-found, never a `403` —
6+//! `photo.rs` keeps the same rule for bytes.
7+
8+use topcoat::Result;
9+use topcoat::context::Cx;
10+use topcoat::router::error::not_found;
11+use topcoat::router::{page, path_param};
12+use topcoat::view::view;
13+
14+use im_core::accounts;
15+
16+use crate::layout::{avatar, shell, wordmark};
17+use crate::server;
18+
19+path_param!(user_id);
20+
21+/// A person's page. `/people/{user_id}`.
22+#[page("/people/{user_id}")]
23+async fn people_page(cx: &Cx) -> Result {
24+ let Some(viewer) = server::current_user(cx).await else {
25+ return Err(not_found().into());
26+ };
27+ let target_id: &str = path_param::<UserId>(cx);
28+ let store = server::app(cx).store.clone();
29+ let target = im_core::model::UserId::from(target_id.to_string());
30+ let Some(person) = accounts::user_by_id(store.as_ref(), &target).await? else {
31+ return Err(not_found().into());
32+ };
33+ let mine = person.id == viewer.id;
34+ let stats = im_core::stats::profile_stats(&store, &person.id).await?;
35+ let joined = person.created_at.date().to_string();
36+ let stage = view! {
37+ cx =>
38+ <main class="auth-stage">
39+ <div class="auth-column">
40+ (wordmark(cx).await?)
41+ <div class="auth-card">
42+ <div class="profile-head">
43+ (avatar(cx, &person).await?)
44+ <div class="profile-heading">
45+ <div class="auth-title">(person.name.clone())</div>
46+ <div class="profile-marks">
47+ if person.totp_confirmed {
48+ <span class="chip chip-connected">"2FA on"</span>
49+ } else {
50+ <span class="chip chip-muted">"2FA off"</span>
51+ }
52+ if person.admin {
53+ <span class="chip chip-accent">"Admin"</span>
54+ }
55+ </div>
56+ </div>
57+ </div>
58+ <dl class="profile-fields">
59+ <div class="profile-field">
60+ <dt class="auth-label">"Email"</dt>
61+ <dd class="profile-value mono">(person.email.clone())</dd>
62+ </div>
63+ <div class="profile-field">
64+ <dt class="auth-label">"Member since"</dt>
65+ <dd class="profile-value">(joined)</dd>
66+ </div>
67+ </dl>
68+ if mine {
69+ <a class="auth-alt" href="/">"Edit profile"</a>
70+ }
71+ </div>
72+ <div class="auth-card">
73+ <dl class="profile-stats">
74+ <div class="profile-stat">
75+ <dd class="profile-stat-value">(stats.sign_ins)</dd>
76+ <dt class="auth-label">"Sign-ins"</dt>
77+ </div>
78+ <div class="profile-stat">
79+ <dd class="profile-stat-value">(stats.active_sessions)</dd>
80+ <dt class="auth-label">"Active sessions"</dt>
81+ </div>
82+ <div class="profile-stat">
83+ <dd class="profile-stat-value">(stats.connected_apps)</dd>
84+ <dt class="auth-label">"Connected apps"</dt>
85+ </div>
86+ </dl>
87+ </div>
88+ <div class="auth-footer">"im · Dizey SSO"</div>
89+ </div>
90+ </main>
91+ };
92+ shell(cx, &format!("{} · im", person.name), stage).await
93+}
crates/im-web/src/photo.rsadded+208 -0
@@ -0,0 +1,208 @@
1+//! Profile photo upload, removal and serving — the landing's profile card
2+//! is their only reader. Adapted from izlek-web's `photo.rs`; the refusal
3+//! answer is im's, though: a plain 303 whose query names the code, which the
4+//! landing reads back on render.
5+
6+use std::collections::HashMap;
7+use std::sync::{Arc, LazyLock};
8+
9+use im_core::photos;
10+use parking_lot::Mutex;
11+use time::OffsetDateTime;
12+use topcoat::context::{Cx, try_app_context};
13+use topcoat::router::content::multipart::Multipart;
14+use topcoat::router::request::headers as request_headers;
15+use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route};
16+
17+use crate::auth::{Redirect, see};
18+use crate::server;
19+
20+path_param!(user_id);
21+
22+/// The upload ceiling: big enough for any sane avatar, small enough that a
23+/// form post cannot park the connection. The router's body limit carries the
24+/// same number so an oversized body dies before it is even parsed.
25+pub const PHOTO_LIMIT_BYTES: u64 = 5 * 1024 * 1024;
26+
27+/// What the first bytes say the image is. The browser's claimed mime never
28+/// reaches the store — only this.
29+fn sniff(bytes: &[u8]) -> Option<&'static str> {
30+ if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
31+ Some("image/png")
32+ } else if bytes.starts_with(b"\xff\xd8\xff") {
33+ Some("image/jpeg")
34+ } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF98a") {
35+ Some("image/gif")
36+ } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
37+ Some("image/webp")
38+ } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"avif" {
39+ Some("image/avif")
40+ } else {
41+ None
42+ }
43+}
44+
45+/// Sets the signed-in person's own photo. Nobody else's — the id comes from
46+/// the session, never from the form.
47+#[route(POST "/api/profile_photo")]
48+async fn upload(cx: &Cx, mut multipart: Multipart) -> Redirect {
49+ let Some(user) = server::current_user(cx).await else {
50+ return see("/login".to_string());
51+ };
52+ let store = server::app(cx).store.clone();
53+ loop {
54+ let mut field = match multipart.next_field().await {
55+ Ok(Some(field)) => field,
56+ _ => return see("/?error=no_file".to_string()),
57+ };
58+ if field.file_name().is_none() {
59+ continue;
60+ }
61+ let mut collected = Vec::new();
62+ loop {
63+ match field.chunk().await {
64+ Ok(Some(chunk)) => {
65+ if (collected.len() + chunk.len()) as u64 > PHOTO_LIMIT_BYTES {
66+ return see("/?error=photo_too_big".to_string());
67+ }
68+ collected.extend_from_slice(&chunk);
69+ }
70+ Ok(None) => break,
71+ Err(_) => return see("/?error=photo_too_big".to_string()),
72+ }
73+ }
74+ let Some(mime) = sniff(&collected) else {
75+ return see("/?error=not_an_image".to_string());
76+ };
77+ return match photos::set_photo(&store, &user.id, &collected, mime).await {
78+ Ok(()) => {
79+ // The bytes changed, so the URL the avatar renders has to
80+ // change with them — bump before the answer goes out.
81+ if let Some(stamps) = try_app_context::<PhotoStamps>(cx) {
82+ stamps.bump(&user.id.to_string());
83+ }
84+ server::log_event(cx, "photo_saved", Some(&user.email), None).await;
85+ see("/?ok=photo_saved".to_string())
86+ }
87+ Err(_) => see("/?error=unavailable".to_string()),
88+ };
89+ }
90+}
91+
92+/// Clears the signed-in person's own photo.
93+#[route(POST "/api/delete_profile_photo")]
94+async fn delete(cx: &Cx) -> Redirect {
95+ let Some(user) = server::current_user(cx).await else {
96+ return see("/login".to_string());
97+ };
98+ let store = server::app(cx).store.clone();
99+ match photos::clear_photo(&store, &user.id).await {
100+ Ok(()) => {
101+ server::log_event(cx, "photo_removed", Some(&user.email), None).await;
102+ see("/?ok=photo_removed".to_string())
103+ }
104+ Err(_) => see("/?error=unavailable".to_string()),
105+ }
106+}
107+
108+/// Photo URL version stamps, in process memory. The `user` row carries no
109+/// photo-updated moment and a schema column for cache-busting is out of
110+/// proportion, so the stamp lives here: `upload` bumps it when the bytes
111+/// change, and the avatar render reads it back. A photo whose bytes this
112+/// process never saw change stamps at the process start, which is still a
113+/// URL no browser has fetched, so it is re-downloaded exactly once per
114+/// restart and cached from then on.
115+#[derive(Clone, Default)]
116+pub struct PhotoStamps(Arc<Mutex<HashMap<String, i64>>>);
117+
118+/// Unix microseconds at first use: the stamp for every photo whose bytes
119+/// this process never saw change. Stable for the process's lifetime, and
120+/// later than any stamp an earlier process emitted, so no pre-restart URL
121+/// survives a restart.
122+static PROCESS_START: LazyLock<i64> =
123+ LazyLock::new(|| (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000) as i64);
124+
125+impl PhotoStamps {
126+ fn stamp(&self, user_id: &str) -> i64 {
127+ self.0
128+ .lock()
129+ .get(user_id)
130+ .copied()
131+ .unwrap_or(*PROCESS_START)
132+ }
133+
134+ fn bump(&self, user_id: &str) {
135+ let now = (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000) as i64;
136+ let mut stamps = self.0.lock();
137+ // A write always moves the URL: never emit a stamp this user has
138+ // already rendered with, even when two writes land inside the same
139+ // microsecond.
140+ let stamp = stamps.get(user_id).copied().unwrap_or(*PROCESS_START);
141+ stamps.insert(user_id.to_string(), now.max(stamp + 1));
142+ }
143+}
144+
145+/// The stamp an avatar's photo URL carries. A router built without
146+/// `PhotoStamps` falls back to the process start, which is still a URL no
147+/// browser has fetched before.
148+pub fn photo_stamp(cx: &Cx, user_id: &str) -> i64 {
149+ match try_app_context::<PhotoStamps>(cx) {
150+ Some(stamps) => stamps.stamp(user_id),
151+ None => *PROCESS_START,
152+ }
153+}
154+
155+/// A cheap, non-cryptographic hash — good enough for an `ETag` on bytes only
156+/// this server ever writes.
157+fn fnv1a(bytes: &[u8]) -> u64 {
158+ let mut hash: u64 = 0xcbf29ce484222325;
159+ for &b in bytes {
160+ hash ^= b as u64;
161+ hash = hash.wrapping_mul(0x100000001b3);
162+ }
163+ hash
164+}
165+
166+fn not_found() -> (StatusCode, HeaderMap, Vec<u8>) {
167+ (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new())
168+}
169+
170+/// Serves one person's photo. Signed-in only, and a missing photo reads
171+/// exactly like a missing person: the not-found, never a `403`.
172+#[route(GET "/photo/{user_id}")]
173+async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
174+ if server::current_user(cx).await.is_none() {
175+ return Ok(not_found());
176+ }
177+ let target = im_core::model::UserId::from(path_param::<UserId>(cx).to_string());
178+ let store = server::app(cx).store.clone();
179+ let Ok(Some((bytes, mime))) = photos::photo(&store, &target).await else {
180+ return Ok(not_found());
181+ };
182+
183+ let etag = format!("\"{:x}\"", fnv1a(&bytes));
184+ let mut headers = HeaderMap::new();
185+ headers.insert(header::ETAG, HeaderValue::from_str(&etag).unwrap());
186+ // The stamp in the URL is the other half of this caching: `upload`
187+ // bumps it whenever the bytes change, so a year of `immutable` never
188+ // shows an old photo — a changed photo is a changed URL. `private`
189+ // because the route is session-gated.
190+ headers.insert(
191+ header::CACHE_CONTROL,
192+ HeaderValue::from_static("private, max-age=31536000, immutable"),
193+ );
194+
195+ let if_none_match = request_headers(cx)
196+ .get(header::IF_NONE_MATCH)
197+ .and_then(|v| v.to_str().ok());
198+ if if_none_match == Some(etag.as_str()) {
199+ return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new()));
200+ }
201+
202+ headers.insert(
203+ header::CONTENT_TYPE,
204+ HeaderValue::from_str(&mime)
205+ .unwrap_or(HeaderValue::from_static("application/octet-stream")),
206+ );
207+ Ok((StatusCode::OK, headers, bytes))
208+}
style/main.scssmodified+129 -0
@@ -369,6 +369,135 @@ body:has(.auth-stage) {
369369 padding-top: 4px;
370370 }
371371
372+// --- Profile section (the signed-in landing) -------------------------------
373+// izlek's people page, folded into the auth card: the face and name up top,
374+// the counts in their own card below.
375+
376+.profile-head {
377+ display: flex;
378+ align-items: center;
379+ gap: 14px;
380+}
381+
382+.profile-avatar {
383+ flex: none;
384+ width: 72px;
385+ height: 72px;
386+ border-radius: var(--radius);
387+ border: 1px solid var(--border);
388+ object-fit: cover;
389+}
390+
391+// The no-photo face: the name's first letter on a quiet tile.
392+.profile-avatar-initial {
393+ display: flex;
394+ align-items: center;
395+ justify-content: center;
396+ background: var(--panel-sunken);
397+ color: var(--muted);
398+ font-family: var(--font-mono);
399+ font-size: 26px;
400+ font-weight: 500;
401+ user-select: none;
402+}
403+
404+.profile-heading {
405+ display: flex;
406+ flex-direction: column;
407+ gap: 6px;
408+ min-width: 0;
409+}
410+
411+.profile-marks {
412+ display: flex;
413+ gap: 6px;
414+ flex-wrap: wrap;
415+}
416+
417+// The accent chip: not a probe result, a standing fact — membership of the
418+// admin set reads in the accent, not in a pass/fail colour.
419+.chip-accent {
420+ background: var(--accent-tint);
421+ border: 1px solid var(--border-strong);
422+ color: var(--accent-ink);
423+}
424+
425+.profile-fields {
426+ margin: 0;
427+ display: flex;
428+ flex-direction: column;
429+ gap: 10px;
430+}
431+
432+.profile-field {
433+ display: flex;
434+ flex-direction: column;
435+ gap: 4px;
436+}
437+
438+.profile-value {
439+ margin: 0;
440+ font-size: 13px;
441+}
442+
443+.profile-photo-actions {
444+ display: flex;
445+ gap: 8px;
446+ align-items: center;
447+
448+ .profile-upload {
449+ flex: 1;
450+ width: auto;
451+ }
452+}
453+
454+// The remove form carries no visible chrome of its own — its button lives in
455+// the upload row and reaches it by `form=`.
456+#profile-photo-remove {
457+ display: none;
458+}
459+
460+// A file input in the auth-input skin: the native button wears the quiet
461+// control look, the height follows the content instead of the 40px field.
462+.profile-file {
463+ height: auto;
464+ padding: 7px 12px;
465+ font-size: 12px;
466+ color: var(--muted);
467+
468+ &::file-selector-button {
469+ margin-right: 10px;
470+ padding: 4px 10px;
471+ background: var(--panel-sunken);
472+ border: 1px solid var(--border-strong);
473+ border-radius: var(--radius);
474+ color: var(--ink);
475+ font-family: var(--font-sans);
476+ font-size: 12px;
477+ cursor: pointer;
478+ }
479+}
480+
481+.profile-stats {
482+ margin: 0;
483+ display: flex;
484+ justify-content: space-between;
485+ gap: 12px;
486+}
487+
488+.profile-stat {
489+ display: flex;
490+ flex-direction: column;
491+ gap: 2px;
492+}
493+
494+.profile-stat-value {
495+ margin: 0;
496+ font-size: 22px;
497+ font-weight: 600;
498+ letter-spacing: -0.01em;
499+}
500+
372501 @media (max-width: 720px) {
373502 .auth-stage { padding: 0 16px 24px; }
374503 }