From 509d0e7b19104ad3ae2e1dc82c65e1f38dfe7d9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 9 Sep 2026 07:08:00 +0300 Subject: [PATCH] Timezone setting: im serves it, the directory carries it, iz will read it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit users gains timezone TEXT NOT NULL DEFAULT 'UTC+03:00' — migration- guarded ALTER, the DEFAULT backfilling every existing row to +3. The value format is iz's settings select ported verbatim: fixed offsets 'UTC-12:00' through 'UTC+14:00', zero-padded hours, 'UTC' for zero — both sides must speak identical strings over the directory, so im does not invent a spelling. User, its three queries (verify_login, user_by_id, list_users — timezone appended, no index shifts) and set_preferences expose it. The introspection answer and DirectoryMember — the web type and the im-client SDK type — carry timezone; the SDK field defaults to 'UTC+03:00' so rows mirrored before the field existed still read. The landing's preferences pane gains the TIME ZONE select under the three it had; the save validates against the option list (bad_zone otherwise) and — because the timezone rides the directory — announces the row as a profile frame, the way a name or photo change does. Tests: default + set-and-read-back at the store, the introspect field, and the route contract — /directory carries the stored zone, the live bus announces it, a value outside the select's list is refused whole. Browser-verified on the scratch server: 27 options (UTC-12:00 … UTC, UTC+14:00), the select saves and re-renders the stored zone, and /directory answers with it. Workspace check with zero warnings. --- crates/im-client/src/directory.rs | 14 +++++ crates/im-core/src/accounts.rs | 43 ++++++++++++-- crates/im-core/src/model.rs | 8 +++ crates/im-core/src/oidc.rs | 6 ++ crates/im-core/src/store.rs | 13 ++++- crates/im-web/src/auth.rs | 12 +++- crates/im-web/src/directory.rs | 93 ++++++++++++++++++++++++++++++- crates/im-web/src/i18n.rs | 6 ++ crates/im-web/src/pages.rs | 42 ++++++++++++++ 9 files changed, 228 insertions(+), 9 deletions(-) diff --git a/crates/im-client/src/directory.rs b/crates/im-client/src/directory.rs index 70bb31b..03c257a 100644 --- a/crates/im-client/src/directory.rs +++ b/crates/im-client/src/directory.rs @@ -46,6 +46,16 @@ pub struct DirectoryMember { /// `/photo/{sub}` be cached hard and still arrive fresh. #[serde(default)] pub photo_version: u64, + /// The member's display timezone (a fixed offset like "UTC+03:00"). + /// Defaulted: rows mirrored before im carried the field still read. + #[serde(default = "default_timezone")] + pub timezone: String, +} + +/// The timezone im starts every account on, and the one this SDK assumes +/// when a mirrored row predates the field. +fn default_timezone() -> String { + "UTC+03:00".to_string() } /// One event off the directory stream. The only thing `/directory/live` @@ -366,6 +376,7 @@ mod tests { assert_eq!( events, vec![DirectoryEvent::Profile(DirectoryMember { + timezone: default_timezone(), sub: "one".into(), email: "one@example.com".into(), name: "Ann".into(), @@ -387,6 +398,7 @@ mod tests { events.extend(parser.feed(&whole.as_bytes()[cut..])); assert_eq!(events.len(), 1, "cut at {cut}"); assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember { + timezone: default_timezone(), sub: "two".into(), email: "two@example.com".into(), name: "Ann".into(), @@ -403,6 +415,7 @@ mod tests { let events = parser.feed(frame("three", 1).replace('\n', "\r\n").as_bytes()); assert_eq!(events.len(), 1); assert_eq!(events[0], DirectoryEvent::Profile(DirectoryMember { + timezone: default_timezone(), sub: "three".into(), email: "three@example.com".into(), name: "Ann".into(), @@ -429,6 +442,7 @@ mod tests { assert_eq!( events[0], DirectoryEvent::Profile(DirectoryMember { + timezone: default_timezone(), sub: "four".into(), email: "four@example.com".into(), name: "Ann".into(), diff --git a/crates/im-core/src/accounts.rs b/crates/im-core/src/accounts.rs index ed10245..e3d03a1 100644 --- a/crates/im-core/src/accounts.rs +++ b/crates/im-core/src/accounts.rs @@ -20,7 +20,7 @@ use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq; use time::OffsetDateTime; -use crate::model::{Invite, User, UserId}; +use crate::model::{DEFAULT_TIMEZONE, Invite, User, UserId}; use crate::store::{self, Result, Store, StoreError, backend}; /// Argon2id at the OWASP Password Storage Cheat Sheet's recommended second @@ -392,6 +392,7 @@ pub async fn create_user_from_invite( theme: "light".to_string(), language: "en".to_string(), ui: "instrument".to_string(), + timezone: DEFAULT_TIMEZONE.to_string(), }; let password_hash = hash_password(password)?; // The lock is taken only now — the reads above (`invite_by_token`) lock @@ -656,7 +657,8 @@ pub async fn verify_login( let mut rows = conn .query( "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at, \ - photo_mime IS NOT NULL, photo_version, theme, language, ui FROM users WHERE email = ?1 COLLATE NOCASE", + photo_mime IS NOT NULL, photo_version, theme, language, ui, timezone \ + FROM users WHERE email = ?1 COLLATE NOCASE", turso::params![email], ) .await @@ -678,6 +680,7 @@ pub async fn verify_login( theme: store::text(&row, 10)?, language: store::text(&row, 11)?, ui: store::text(&row, 12)?, + timezone: store::text(&row, 13)?, }; let phc = store::text(&row, 3)?; if !verify_password(password, &phc) || user.disabled { @@ -750,7 +753,8 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result> { let mut rows = conn .query( "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \ - photo_mime IS NOT NULL, photo_version, theme, language, ui FROM users WHERE id = ?1", + photo_mime IS NOT NULL, photo_version, theme, language, ui, timezone \ + FROM users WHERE id = ?1", turso::params![id.to_string()], ) .await @@ -771,6 +775,7 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result> { theme: store::text(&row, 9)?, language: store::text(&row, 10)?, ui: store::text(&row, 11)?, + timezone: store::text(&row, 12)?, })) } @@ -801,7 +806,8 @@ pub async fn list_users(store: &Store) -> Result> { let mut rows = conn .query( "SELECT id, email, name, totp_confirmed, admin, disabled, created_at, \ - photo_mime IS NOT NULL, photo_version, theme, language, ui FROM users ORDER BY created_at", + photo_mime IS NOT NULL, photo_version, theme, language, ui, timezone \ + FROM users ORDER BY created_at", (), ) .await @@ -821,6 +827,7 @@ pub async fn list_users(store: &Store) -> Result> { theme: store::text(&row, 9)?, language: store::text(&row, 10)?, ui: store::text(&row, 11)?, + timezone: store::text(&row, 12)?, }); } Ok(users) @@ -863,11 +870,18 @@ pub async fn set_preferences( theme: &str, language: &str, ui: &str, + timezone: &str, ) -> Result<()> { let conn = store.conn.lock().await; conn.execute( - "UPDATE users SET theme = ?1, language = ?2, ui = ?3 WHERE id = ?4", - turso::params![theme.to_string(), language.to_string(), ui.to_string(), user.to_string()], + "UPDATE users SET theme = ?1, language = ?2, ui = ?3, timezone = ?4 WHERE id = ?5", + turso::params![ + theme.to_string(), + language.to_string(), + ui.to_string(), + timezone.to_string(), + user.to_string() + ], ) .await .map_err(backend)?; @@ -1430,6 +1444,23 @@ mod tests { .unwrap(); assert!(!login_blocked(&store, "ann@example.com").await.unwrap()); } + #[tokio::test] + async fn timezone_defaults_to_the_family_offset_and_follows_preferences() { + let store = fixture().await; + let ann = seeded_user(&store, "ann@example.com", "Ann").await; + assert_eq!( + user_by_id(&store, &ann.id).await.unwrap().unwrap().timezone, + DEFAULT_TIMEZONE, + "a fresh account — and a migrated row via the DEFAULT — starts on +3" + ); + set_preferences(&store, &ann.id, "dark", "tr", "ledger", "UTC-05:00") + .await + .unwrap(); + let reloaded = user_by_id(&store, &ann.id).await.unwrap().unwrap(); + assert_eq!(reloaded.timezone, "UTC-05:00"); + assert_eq!(reloaded.theme, "dark"); + } + async fn seeded_user(store: &Store, email: &str, name: &str) -> User { let invite = create_invite(store, email, None, false).await.unwrap(); create_user_from_invite(store, invite.expose(), name, "tDLr9!mZQ2xv") diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index 426619a..dc2d581 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -7,6 +7,11 @@ use serde::{Deserialize, Serialize}; use time::OffsetDateTime; +/// The timezone a fresh account — and every row the migration backfills — +/// starts on. The value is one of the fixed-offset strings the settings +/// select offers (iz's format, carried verbatim over the directory). +pub const DEFAULT_TIMEZONE: &str = "UTC+03:00"; + macro_rules! id_wrapper { ($name:ident, $doc:literal) => { #[doc = $doc] @@ -70,6 +75,9 @@ pub struct User { pub theme: String, pub language: String, pub ui: String, + /// Display-only fixed offset in iz's spelling ("UTC+03:00", or "UTC" + /// for zero). Apps read it over the directory to render times. + pub timezone: String, } /// An outstanding (or spent) invite, as stored. The raw token exists only in diff --git a/crates/im-core/src/oidc.rs b/crates/im-core/src/oidc.rs index 07df6e4..1051ac3 100644 --- a/crates/im-core/src/oidc.rs +++ b/crates/im-core/src/oidc.rs @@ -608,6 +608,7 @@ pub async fn introspect_app_session( "name": user.name, "admin": user.admin, "photo_version": user.photo_version, + "timezone": user.timezone, "exp": expires.unix_timestamp(), }))) } @@ -727,6 +728,11 @@ mod tests { assert_eq!(active["active"], true); assert_eq!(active["sub"], id.as_str()); assert_eq!(active["admin"], want); + assert_eq!( + active["timezone"], + crate::model::DEFAULT_TIMEZONE, + "introspection carries the display timezone" + ); } } diff --git a/crates/im-core/src/store.rs b/crates/im-core/src/store.rs index 6035ce3..3b6d1e1 100644 --- a/crates/im-core/src/store.rs +++ b/crates/im-core/src/store.rs @@ -50,7 +50,8 @@ CREATE TABLE IF NOT EXISTS users ( photo_version INTEGER NOT NULL DEFAULT 0, theme TEXT NOT NULL DEFAULT 'light', language TEXT NOT NULL DEFAULT 'en', - ui TEXT NOT NULL DEFAULT 'instrument' + ui TEXT NOT NULL DEFAULT 'instrument', + timezone TEXT NOT NULL DEFAULT 'UTC+03:00' ); CREATE TABLE IF NOT EXISTS invites ( token TEXT PRIMARY KEY, @@ -269,6 +270,16 @@ impl Store { // ALTER over the owner precedent: databases born before the // column get it here, and every existing row reads NULL until // its app re-registers. + // The display timezone (iz's fixed-offset spelling): the + // DEFAULT backfills every existing row to UTC+03:00. + if !has_column(&conn, "users", "timezone").await? { + conn.execute( + "ALTER TABLE users ADD COLUMN timezone TEXT NOT NULL DEFAULT 'UTC+03:00'", + (), + ) + .await + .map_err(backend)?; + } if !has_column(&conn, "services", "client_id").await? { conn.execute("ALTER TABLE services ADD COLUMN client_id TEXT", ()) .await diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index f7b7b9c..c90cdd7 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -545,6 +545,7 @@ struct PreferencesForm { theme: Option, ui: Option, language: Option, + timezone: Option, } /// The landing's preferences: three selects, validated against the option @@ -573,8 +574,17 @@ async fn preferences(cx: &Cx, Form(input): Form) -> Redirect { if language != "en" && language != "tr" { return see("/?section=preferences&error=bad_language".to_string()); } + let Some(timezone) = input.timezone.as_deref() else { + return see("/?section=preferences&error=bad_zone".to_string()); + }; + if !crate::pages::zone_options().contains(&timezone.to_string()) { + return see("/?section=preferences&error=bad_zone".to_string()); + } let store = &server::app(cx).store; - im_core::accounts::set_preferences(store, &user.id, theme, language, ui).await?; + im_core::accounts::set_preferences(store, &user.id, theme, language, ui, timezone).await?; + // The timezone rides the directory: registered siblings apply it live, + // the way a name or photo change announces itself. + server::notify_profile(cx, &user.id).await; server::log_event(cx, "preferences_saved", Some(&user.email), None).await; see("/?section=preferences&ok=preferences".to_string()) } diff --git a/crates/im-web/src/directory.rs b/crates/im-web/src/directory.rs index c873a26..ed30d68 100644 --- a/crates/im-web/src/directory.rs +++ b/crates/im-web/src/directory.rs @@ -30,6 +30,10 @@ pub struct DirectoryMember { pub name: String, pub admin: bool, pub photo_version: u64, + /// The member's display timezone, iz's fixed-offset spelling. This + /// side only serializes — the field is always written — so the serde + /// default lives on the SDK's reading half. + pub timezone: String, } impl DirectoryMember { @@ -41,6 +45,7 @@ impl DirectoryMember { name: user.name.clone(), admin: user.admin, photo_version: user.photo_version, + timezone: user.timezone.clone(), } } } @@ -249,6 +254,8 @@ mod tests { client_id: String, secret: String, store: Arc, + /// A handle on the live bus, for asserting what a change announces. + live: tokio::sync::broadcast::Sender, } async fn setup() -> Setup { @@ -310,7 +317,7 @@ mod tests { issuer: "http://127.0.0.1:7650".into(), services, }, - live, + live: live.clone(), }; let router = Router::builder() .discover() @@ -329,6 +336,7 @@ mod tests { client_id: client_id.to_string(), secret: secret.expose().to_string(), store, + live, } } @@ -558,6 +566,7 @@ mod tests { client_id, secret, store, + .. } = setup().await; let ada = im_core::accounts::user_by_email(&store, "ada@example.com") .await @@ -673,6 +682,7 @@ mod tests { client_id, secret, store, + .. } = setup().await; let ada = im_core::accounts::user_by_email(&store, "ada@example.com") .await @@ -854,6 +864,7 @@ mod tests { client_id, secret, store, + .. } = setup().await; // The setup already seeded; a re-boot's seed must be a no-op, even // though `in` is exactly the name the config carries. @@ -884,6 +895,7 @@ mod tests { client_id, secret, store, + .. } = setup().await; // No pair, no write. @@ -966,6 +978,7 @@ mod tests { client_id, secret, store, + .. } = setup().await; let ada = im_core::accounts::user_by_email(&store, "ada@example.com") .await @@ -1380,4 +1393,82 @@ mod tests { Some("/login?error=email_change_invalid") ); } + + #[tokio::test] + async fn timezone_rides_the_directory_and_the_live_frame() { + let Setup { + router, + client_id, + secret, + store, + live, + } = setup().await; + let ada = im_core::accounts::user_by_email(&store, "ada@example.com") + .await + .unwrap() + .unwrap(); + let session = im_core::sessions::create_session(&store, &ada.id, &Default::default()) + .await + .unwrap(); + let cookie = format!("{SESSION_COOKIE}={}", session.expose()); + + // The entry carries the family default before anyone touches it. + let (status, body) = get(&router, Some(basic(&client_id, &secret))).await; + assert_eq!(status, StatusCode::OK); + let roster = serde_json::from_str::(&body).unwrap(); + assert_eq!(roster[0]["timezone"], "UTC+03:00"); + + // Saving preferences with a new timezone refuses a value outside + // the select's list, and announces a real change as a profile + // frame — the same ride a name or photo change takes. + let mut rx = live.subscribe(); + let (status, location, _) = post_form( + &router, + "/preferences", + "theme=light&ui=instrument&language=en&timezone=UTC-05:00", + Some(&cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!( + location.as_deref(), + Some("/?section=preferences&ok=preferences") + ); + match rx.try_recv().unwrap() { + server::LiveEvent::Profile(member) => { + assert_eq!(member.timezone, "UTC-05:00"); + } + other => panic!("a profile change announces the row, got {other:?}"), + } + + // And the roster reads the stored zone back. + let (_, body) = get(&router, Some(basic(&client_id, &secret))).await; + let roster = serde_json::from_str::(&body).unwrap(); + let ada_entry = roster + .as_array() + .unwrap() + .iter() + .find(|member| member["email"] == "ada@example.com") + .unwrap(); + assert_eq!(ada_entry["timezone"], "UTC-05:00"); + + // A value the select never offers is refused whole. + let (status, location, _) = post_form( + &router, + "/preferences", + "theme=light&ui=instrument&language=en&timezone=Mars/Olympus", + Some(&cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!( + location.as_deref(), + Some("/?section=preferences&error=bad_zone") + ); + let reloaded = im_core::accounts::user_by_id(&store, &ada.id) + .await + .unwrap() + .unwrap(); + assert_eq!(reloaded.timezone, "UTC-05:00", "nothing half-written"); + } } diff --git a/crates/im-web/src/i18n.rs b/crates/im-web/src/i18n.rs index 157fa37..492c60c 100644 --- a/crates/im-web/src/i18n.rs +++ b/crates/im-web/src/i18n.rs @@ -304,6 +304,8 @@ pub enum Key { ThemeLabel, UiLabel, LanguageLabel, + TimeZoneLabel, + ErrBadZone, LightOption, DarkOption, InstrumentOption, @@ -380,6 +382,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (ErrBadUi, Tr) => "Bu bir arayüz değil.", (ErrBadLanguage, En) => "That is not a language.", (ErrBadLanguage, Tr) => "Bu bir dil değil.", + (ErrBadZone, En) => "That is not a time zone.", + (ErrBadZone, Tr) => "Bu bir saat dilimi değil.", (ErrBadService, En) => { "A service needs a key of lowercase letters, digits, or dashes, a name, and an http(s) address." } @@ -854,6 +858,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (UiLabel, Tr) => "ARAYÜZ", (LanguageLabel, En) => "LANGUAGE", (LanguageLabel, Tr) => "DİL", + (TimeZoneLabel, En) => "TIME ZONE", + (TimeZoneLabel, Tr) => "SAAT DİLİMİ", (LightOption, En) => "Light", (LightOption, Tr) => "Açık", (DarkOption, En) => "Dark", diff --git a/crates/im-web/src/pages.rs b/crates/im-web/src/pages.rs index 5280940..813bf8d 100644 --- a/crates/im-web/src/pages.rs +++ b/crates/im-web/src/pages.rs @@ -44,6 +44,7 @@ pub fn error_text(code: &str, lang: Lang) -> &'static str { "bad_theme" => t(lang, Key::ErrBadTheme), "bad_ui" => t(lang, Key::ErrBadUi), "bad_language" => t(lang, Key::ErrBadLanguage), + "bad_zone" => t(lang, Key::ErrBadZone), "bad_service" => t(lang, Key::ErrBadService), "bad_client" => t(lang, Key::ErrBadClient), "no_such_client" => t(lang, Key::ErrNoSuchClient), @@ -73,6 +74,41 @@ pub fn ok_text(code: &str, lang: Lang) -> &'static str { } } +/// The offsets the timezone field offers, `"UTC-12:00"` through +/// `"UTC+14:00"` — iz's settings select, ported verbatim so both sides +/// speak the same values over the directory. Fixed offsets: no tz database +/// rides along for what a display label needs, and `"UTC"` stands for +/// +00:00. +pub(crate) fn zone_options() -> Vec { + (-12..=14) + .map(|hour: i32| { + if hour == 0 { + "UTC".to_string() + } else { + format!( + "UTC{}{:02}:00", + if hour > 0 { "+" } else { "-" }, + hour.abs() + ) + } + }) + .collect() +} + +/// The timezone `"#, + z = zone, + sel = if zone == current { r#" selected="selected""# } else { "" }, + ) + }) + .collect::() +} + /// The refusal this request carries back, if any. Values come percent- /// decoded: `redirect_uri=http%3A%2F%2F…` must equal the registered URI. pub fn query_value(query: &str, key: &str) -> Option { @@ -715,6 +751,12 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { +