From c829fac796770720df62ca0f36397b4ae6d2a4f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 09:51:46 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20account=20profile,=20photo?= =?UTF-8?q?=20with=20re-encode,=20preferences,=20people=20cards,=20idle-ex?= =?UTF-8?q?tended=20sessions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 276 +++++++++++++++- Cargo.toml | 2 + config/im.example.toml | 2 + crates/im-core/Cargo.toml | 2 + .../0002_sessions_cap_and_language.sql | 9 + crates/im-core/src/config.rs | 13 +- crates/im-core/src/lib.rs | 1 + crates/im-core/src/model.rs | 20 +- crates/im-core/src/names.rs | 63 +++- crates/im-core/src/photo.rs | 226 +++++++++++++ crates/im-core/src/store/directory.rs | 42 +++ crates/im-core/src/store/migrate.rs | 8 +- crates/im-core/src/store/mod.rs | 3 +- crates/im-core/src/store/sessions.rs | 129 +++++++- crates/im-core/src/store/users.rs | 174 +++++++--- crates/im-core/src/time.rs | 35 ++ crates/im-core/src/totp.rs | 3 +- crates/im-web/src/auth.rs | 19 +- crates/im-web/src/boot.rs | 11 +- crates/im-web/src/i18n/account.rs | 174 +++++++++- crates/im-web/src/pages/home.rs | 2 + crates/im-web/src/pages/mod.rs | 4 + crates/im-web/src/pages/people.rs | 72 ++++ crates/im-web/src/pages/photo.rs | 198 +++++++++++ crates/im-web/src/pages/preferences.rs | 193 +++++++++++ crates/im-web/src/pages/profile.rs | 312 ++++++++++++++++++ crates/im-web/src/pages/setup.rs | 41 ++- crates/im-web/src/pages/tests.rs | 5 +- crates/im-web/src/security.rs | 68 +++- crates/im-web/src/views/mod.rs | 24 +- style/_components.scss | 23 ++ style/_tokens.scss | 6 +- 32 files changed, 2047 insertions(+), 113 deletions(-) create mode 100644 crates/im-core/migrations/0002_sessions_cap_and_language.sql create mode 100644 crates/im-core/src/photo.rs create mode 100644 crates/im-core/src/store/directory.rs create mode 100644 crates/im-web/src/pages/people.rs create mode 100644 crates/im-web/src/pages/photo.rs create mode 100644 crates/im-web/src/pages/preferences.rs create mode 100644 crates/im-web/src/pages/profile.rs diff --git a/Cargo.lock b/Cargo.lock index ab2ccc5..aede45d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aead" version = "0.5.2" @@ -284,7 +290,7 @@ version = "0.69.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088" dependencies = [ - "bitflags", + "bitflags 2.13.2", "cexpr", "clang-sys", "itertools 0.12.1", @@ -301,6 +307,12 @@ dependencies = [ "which", ] +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.2" @@ -419,6 +431,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.1" @@ -578,6 +596,12 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e769b5c8c8283982a987c6e948e540254f1058d5a74b8794914d4ef5fc2a24" +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + [[package]] name = "colorchoice" version = "1.0.5" @@ -819,6 +843,37 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745" +[[package]] +name = "defmt" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "defmt-parser" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" +dependencies = [ + "thiserror", +] + [[package]] name = "deranged" version = "0.5.9" @@ -1013,6 +1068,15 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + [[package]] name = "fiat-crypto" version = "0.3.0" @@ -1025,6 +1089,17 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + [[package]] name = "fnv" version = "1.0.7" @@ -1205,6 +1280,16 @@ dependencies = [ "polyval", ] +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + [[package]] name = "glob" version = "0.3.4" @@ -1658,7 +1743,9 @@ dependencies = [ "ed25519-dalek", "hex", "hmac 0.13.0", + "image", "ipnet", + "jiff", "rand 0.10.3", "serde", "serde_json", @@ -1696,6 +1783,34 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -1748,7 +1863,7 @@ version = "0.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb" dependencies = [ - "bitflags", + "bitflags 2.13.2", "cfg-if", "libc", ] @@ -1789,6 +1904,50 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + [[package]] name = "jobserver" version = "0.1.35" @@ -2057,6 +2216,26 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.4" @@ -2068,6 +2247,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "multer" version = "3.1.0" @@ -2326,6 +2515,19 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "polling" version = "3.11.0" @@ -2362,6 +2564,21 @@ dependencies = [ "universal-hash 0.5.1", ] +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -2449,12 +2666,24 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + [[package]] name = "qrcode" version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quote" version = "1.0.47" @@ -2608,7 +2837,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", + "bitflags 2.13.2", ] [[package]] @@ -2717,7 +2946,7 @@ version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys 0.4.15", @@ -2730,7 +2959,7 @@ version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys 0.12.1", @@ -2952,6 +3181,12 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "simdutf8" version = "0.1.5" @@ -3885,7 +4120,7 @@ dependencies = [ "arc-swap", "aristo", "bigdecimal", - "bitflags", + "bitflags 2.13.2", "branches", "bumpalo", "bytemuck", @@ -3974,7 +4209,7 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a69bb856ec8306ad7ed1c13fc61de6a79452bf646ca53d99bb4cc646d5bfc4ff" dependencies = [ - "bitflags", + "bitflags 2.13.2", "memchr", "miette", "strum", @@ -4268,6 +4503,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + [[package]] name = "which" version = "4.4.2" @@ -4584,6 +4825,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" @@ -4617,3 +4864,18 @@ dependencies = [ "cc", "pkg-config", ] + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/Cargo.toml b/Cargo.toml index ae234ee..39379a1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,8 @@ futures-util = "0.3.34" grass = "0.13.4" hex = "0.4.3" hmac = "0.13.0" +image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp", "gif"] } +jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] } http = "1.5.0" ipnet = "2.12.2" qrcode = { version = "0.14.1", default-features = false, features = ["svg"] } diff --git a/config/im.example.toml b/config/im.example.toml index 7d7521c..30c0459 100644 --- a/config/im.example.toml +++ b/config/im.example.toml @@ -37,3 +37,5 @@ healthcheck_url = "" require_2fa_for_admins = true # Sessions one person may hold at once. The oldest is ended when a new sign-in would exceed it. max_sessions = 10 +# Hard cap of a browser session, in days from sign-in. Sessions are extended while they are used, up to this. +session_max_days = 30 diff --git a/crates/im-core/Cargo.toml b/crates/im-core/Cargo.toml index ca4fdc0..38acfb2 100644 --- a/crates/im-core/Cargo.toml +++ b/crates/im-core/Cargo.toml @@ -15,6 +15,8 @@ chacha20poly1305.workspace = true ed25519-dalek.workspace = true hex.workspace = true hmac.workspace = true +image.workspace = true +jiff.workspace = true ipnet.workspace = true rand.workspace = true serde.workspace = true diff --git a/crates/im-core/migrations/0002_sessions_cap_and_language.sql b/crates/im-core/migrations/0002_sessions_cap_and_language.sql new file mode 100644 index 0000000..7e59b3b --- /dev/null +++ b/crates/im-core/migrations/0002_sessions_cap_and_language.sql @@ -0,0 +1,9 @@ +-- 0002: the hard lifetime cap of a session, and the "automatic language" flag of an account. +-- hard_expires_at is created + session_max_days; expires_at is never later than it. The default is +-- the epoch, so a row from before this migration is already expired (fails closed). +-- locale_auto = 1 means the UI language follows Accept-Language and users.locale is ignored. The +-- 0001 CHECK on locale only allows 'en' and 'tr', so "automatic" needs its own column. + +ALTER TABLE sessions ADD COLUMN hard_expires_at TEXT NOT NULL DEFAULT '1970-01-01T00:00:00.000000000Z'; + +ALTER TABLE users ADD COLUMN locale_auto INTEGER NOT NULL DEFAULT 1 CHECK (locale_auto IN (0, 1)); diff --git a/crates/im-core/src/config.rs b/crates/im-core/src/config.rs index 72a7393..b4f0d00 100644 --- a/crates/im-core/src/config.rs +++ b/crates/im-core/src/config.rs @@ -84,6 +84,9 @@ pub struct PolicyConfig { /// Sessions one person may hold at once. The oldest is ended when a new sign-in would exceed it. /// At least 1. pub max_sessions: u32, + /// Hard cap of a browser session, in days from sign-in. A session is idle-extended on use (30 days + /// since its last use) but never lives longer than this. Between 1 and 365. + pub session_max_days: u32, } impl Default for PolicyConfig { @@ -91,6 +94,7 @@ impl Default for PolicyConfig { Self { require_2fa_for_admins: true, max_sessions: 10, + session_max_days: 30, } } } @@ -170,7 +174,14 @@ impl Config { } } if self.policy.max_sessions == 0 { - return Err(Error::Config("[policy] max_sessions must be at least 1".into())); + return Err(Error::Config( + "[policy] max_sessions must be at least 1".into(), + )); + } + if !(1..=365).contains(&self.policy.session_max_days) { + return Err(Error::Config( + "[policy] session_max_days must be between 1 and 365".into(), + )); } let hc = &self.backup.healthcheck_url; if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) { diff --git a/crates/im-core/src/lib.rs b/crates/im-core/src/lib.rs index 7c0adc3..1a4e49a 100644 --- a/crates/im-core/src/lib.rs +++ b/crates/im-core/src/lib.rs @@ -8,6 +8,7 @@ pub mod error; pub mod model; pub mod names; pub mod password; +pub mod photo; pub mod secret; pub mod store; pub mod time; diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index a6bf9f5..d4ef908 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -25,8 +25,10 @@ pub struct User { pub totp_enabled_at: Option, /// The last TOTP step that was accepted. A code of this step or an earlier one is refused. pub totp_last_step: Option, - /// `en` or `tr`. + /// `en` or `tr`. Used only when `locale_auto` is false. pub locale: String, + /// True when the interface language follows the browser (`Accept-Language`) instead of `locale`. + pub locale_auto: bool, /// IANA time zone name. pub zoneinfo: String, /// `system`, `light` or `dark`. @@ -77,8 +79,10 @@ pub struct Session { pub csrf_token: String, /// Creation time (the sign-in time). pub created_at: String, - /// Absolute expiry. + /// Expiry, moved forward on use (idle extension). Never later than `hard_expires_at`. pub expires_at: String, + /// The hard cap: creation plus `session_max_days`. Idle extension stops here. + pub hard_expires_at: String, /// Last time the session was used. Written at most once every five minutes. pub last_seen_at: String, /// Address the session was created from. @@ -110,6 +114,14 @@ pub enum AuditAction { TotpEnabled, /// Two-factor sign-in was turned off. TotpDisabled, + /// The display name was changed. + NameChanged, + /// A profile photo was uploaded. + PhotoChanged, + /// The profile photo was removed. + PhotoRemoved, + /// Language, time zone or theme was changed. + PreferencesChanged, /// A new set of recovery codes was issued. RecoveryCodesIssued, /// One session was ended by its owner. @@ -130,6 +142,10 @@ impl AuditAction { AuditAction::PasswordChanged => "password.changed", AuditAction::TotpEnabled => "totp.enabled", AuditAction::TotpDisabled => "totp.disabled", + AuditAction::NameChanged => "profile.name", + AuditAction::PhotoChanged => "profile.photo", + AuditAction::PhotoRemoved => "profile.photo_removed", + AuditAction::PreferencesChanged => "preferences.changed", AuditAction::RecoveryCodesIssued => "recovery.issued", AuditAction::SessionRevoked => "session.revoked", AuditAction::SessionsRevoked => "sessions.revoked", diff --git a/crates/im-core/src/names.rs b/crates/im-core/src/names.rs index 901bfa2..b68a06d 100644 --- a/crates/im-core/src/names.rs +++ b/crates/im-core/src/names.rs @@ -6,9 +6,16 @@ //! account look exactly like the first one. //! //! The check is a sanity check on the text, not proof that the address exists or receives mail. +//! +//! This module also checks display names ([`parse_display_name`]). A name is shown in the topbar, +//! in mail and in other apps, so control characters and bidirectional overrides are refused: they +//! can make one name read as another. use crate::error::{Error, Result}; +/// Longest display name, in characters. The schema has the same limit. +pub const MAX_NAME_CHARS: usize = 100; + /// Longest address accepted, in bytes (RFC 5321 path limit). pub const MAX_EMAIL_LEN: usize = 254; @@ -35,6 +42,32 @@ pub fn parse_email(input: &str) -> Result { Ok(email) } +/// Checks a display name and returns its stored form. +/// +/// Rules: surrounding whitespace is removed; what is left has 1 to [`MAX_NAME_CHARS`] characters; +/// no character is a control character (this includes NUL, tab and line breaks); and no character +/// is a bidirectional override or isolate (U+202A to U+202E, U+2066 to U+2069). Those last ones +/// let a name display differently from the order its characters are stored in. +pub fn parse_display_name(input: &str) -> Result { + let name = input.trim(); + let invalid = |why: &str| Error::Invalid(format!("the name {why}")); + if name.is_empty() { + return Err(invalid("must not be empty")); + } + if name.chars().count() > MAX_NAME_CHARS { + return Err(invalid("must be at most 100 characters")); + } + if name.chars().any(|c| c.is_control() || is_bidi_control(c)) { + return Err(invalid("must not contain control or direction characters")); + } + Ok(name.to_owned()) +} + +/// The bidirectional embedding, override and isolate controls that [`parse_display_name`] refuses. +fn is_bidi_control(c: char) -> bool { + matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') +} + /// The shape rules of [`parse_email`], for text that is already normalised. fn check_shape(email: &str) -> Result<()> { let invalid = || Error::Invalid("email address is not valid".into()); @@ -59,7 +92,9 @@ fn check_shape(email: &str) -> Result<()> { && label.len() <= MAX_LABEL_LEN && !label.starts_with('-') && !label.ends_with('-') - && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'); + && label + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-'); if !well_formed { return Err(invalid()); } @@ -84,6 +119,32 @@ mod tests { ); } + #[test] + fn display_names_are_trimmed_and_checked() { + assert_eq!( + parse_display_name(" Ada Lovelace ").unwrap(), + "Ada Lovelace" + ); + assert_eq!(parse_display_name("Ayşe Çelik").unwrap(), "Ayşe Çelik"); + let hundred = "a".repeat(MAX_NAME_CHARS); + assert!(parse_display_name(&hundred).is_ok()); + for bad in [ + "", + " ", + "a\u{0}b", + "ada\nlovelace", + "ada\tlovelace", + "\u{7}bell", + "evil\u{202E}name", + "\u{202A}ltr", + "isolate\u{2066}x", + "\u{2069}", + &"a".repeat(MAX_NAME_CHARS + 1), + ] { + assert!(parse_display_name(bad).is_err(), "accepted {bad:?}"); + } + } + #[test] fn attack_strings_are_refused() { let long_local = format!("{}@example.com", "a".repeat(MAX_LOCAL_LEN + 1)); diff --git a/crates/im-core/src/photo.rs b/crates/im-core/src/photo.rs new file mode 100644 index 0000000..448185b --- /dev/null +++ b/crates/im-core/src/photo.rs @@ -0,0 +1,226 @@ +//! Profile photos: the decoding of an upload, the picture that is stored, and the files they live in. +//! +//! An upload is never stored as it was sent. [`normalize_photo`] decodes it with a fixed list of +//! formats and decoder limits, applies its EXIF orientation, crops the centre square, scales it to at +//! most [`MAX_SIDE`] pixels a side, and encodes the pixels again as lossless WebP. Everything else +//! the file carried (metadata, trailing bytes, a second format hidden inside a valid image) is gone. +//! The file name and the browser's content type are never looked at: the bytes decide. +//! +//! Files live at `data_dir/photos/` with mode 0600. A write goes to a temporary file that +//! is fsynced and then renamed over the old one, so a reader sees the old photo or the new one, +//! never half of either. + +use std::fs::{self, DirBuilder, File, OpenOptions}; +use std::io::{Cursor, Write}; +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; +use std::path::{Path, PathBuf}; + +use image::metadata::Orientation; +use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits}; + +use crate::error::{Error, Result}; + +/// Largest upload accepted, in bytes. The web layer streams the request and stops at this limit. +pub const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024; + +/// Longest side of the stored picture, in pixels. The picture is a square of this size at most. +pub const MAX_SIDE: u32 = 512; + +/// Longest side an input may have, in pixels. Larger inputs are refused before any pixel is decoded. +const MAX_INPUT_SIDE: u32 = 8000; + +/// Most memory the decoder may allocate for one input, in bytes (256 MiB). +const MAX_DECODE_ALLOC: u64 = 256 * 1024 * 1024; + +/// MIME type of every stored photo. Lossless WebP keeps transparency and needs no quality choice. +pub const STORED_MIME: &str = "image/webp"; + +/// Directory name inside `data_dir` that holds the photos. +const PHOTO_DIR: &str = "photos"; + +/// The message for an input that is not one of the accepted images. +fn refused() -> Error { + Error::Invalid("the file is not a PNG, JPEG, WebP or GIF image".into()) +} + +/// Turns an upload into the stored picture: a square WebP of at most [`MAX_SIDE`] pixels. +/// +/// Refuses anything whose bytes are not PNG, JPEG, WebP or GIF, whatever its name says, and any +/// image that is larger than the input limits or cannot be decoded. Only the first frame of an +/// animated GIF is kept. +pub fn normalize_photo(input: &[u8]) -> Result> { + let format = image::guess_format(input).map_err(|_| refused())?; + let accepted = matches!( + format, + ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::WebP | ImageFormat::Gif + ); + if !accepted { + return Err(refused()); + } + + let mut limits = Limits::default(); + limits.max_image_width = Some(MAX_INPUT_SIDE); + limits.max_image_height = Some(MAX_INPUT_SIDE); + limits.max_alloc = Some(MAX_DECODE_ALLOC); + let mut reader = ImageReader::with_format(Cursor::new(input), format); + reader.limits(limits); + let mut decoder = reader.into_decoder().map_err(decode_error)?; + // Phones store the rotation in EXIF and leave the pixels sideways; apply it before cropping. + let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms); + let mut image = DynamicImage::from_decoder(decoder).map_err(decode_error)?; + image.apply_orientation(orientation); + + let (width, height) = (image.width(), image.height()); + let side = width.min(height); + if side == 0 { + return Err(refused()); + } + let square = image.crop_imm((width - side) / 2, (height - side) / 2, side, side); + let scaled = if side > MAX_SIDE { + square.resize_exact(MAX_SIDE, MAX_SIDE, image::imageops::FilterType::Lanczos3) + } else { + square + }; + + let mut out = Cursor::new(Vec::new()); + DynamicImage::ImageRgba8(scaled.to_rgba8()) + .write_to(&mut out, ImageFormat::WebP) + .map_err(|_| refused())?; + Ok(out.into_inner()) +} + +/// Every decode failure is the uploader's problem: the bytes are not an image this build reads. +fn decode_error(_: image::ImageError) -> Error { + refused() +} + +/// The file that holds the photo of `user_id`. The id must be a plain identifier, so no id can +/// name a path outside the photo directory. +pub fn photo_path(data_dir: &Path, user_id: &str) -> Result { + let plain = !user_id.is_empty() + && user_id.len() <= 64 + && user_id.bytes().all(|b| b.is_ascii_alphanumeric()); + if !plain { + return Err(Error::Invalid("photo id is not valid".into())); + } + Ok(data_dir.join(PHOTO_DIR).join(user_id)) +} + +/// Replaces the stored photo of `user_id` with `bytes`, which must already be normalised. +/// +/// The bytes go to a temporary file in the same directory, which is fsynced and renamed over the +/// old file. The directory is fsynced too, so the rename survives a crash. +pub fn write_photo(data_dir: &Path, user_id: &str, bytes: &[u8]) -> Result<()> { + let path = photo_path(data_dir, user_id)?; + let dir = data_dir.join(PHOTO_DIR); + DirBuilder::new().recursive(true).mode(0o700).create(&dir)?; + let temp = dir.join(format!(".{user_id}.{}.tmp", ulid::Ulid::generate())); + let written = (|| -> Result<()> { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&temp)?; + file.write_all(bytes)?; + file.sync_all()?; + fs::rename(&temp, &path)?; + File::open(&dir)?.sync_all()?; + Ok(()) + })(); + if written.is_err() { + // Best effort: a leftover temporary file is harmless and never served. + let _ = fs::remove_file(&temp); + } + written +} + +/// The stored photo of `user_id`, or `None` when there is none. +pub fn read_photo(data_dir: &Path, user_id: &str) -> Result>> { + match fs::read(photo_path(data_dir, user_id)?) { + Ok(bytes) => Ok(Some(bytes)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.into()), + } +} + +/// Deletes the stored photo of `user_id`. Nothing to delete is not an error. +pub fn remove_photo(data_dir: &Path, user_id: &str) -> Result<()> { + match fs::remove_file(photo_path(data_dir, user_id)?) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A PNG of the given size, made with the same crate that reads uploads. + fn png(width: u32, height: u32) -> Vec { + let mut out = Cursor::new(Vec::new()); + DynamicImage::new_rgb8(width, height) + .write_to(&mut out, ImageFormat::Png) + .expect("encode test png"); + out.into_inner() + } + + #[test] + fn a_picture_is_stored_as_a_centred_square_of_at_most_512_pixels() { + let stored = normalize_photo(&png(1000, 600)).expect("normalised"); + assert_eq!( + image::guess_format(&stored).expect("format"), + ImageFormat::WebP + ); + let decoded = + image::load_from_memory_with_format(&stored, ImageFormat::WebP).expect("decodes"); + assert_eq!((decoded.width(), decoded.height()), (512, 512)); + + let small = normalize_photo(&png(40, 30)).expect("normalised"); + let decoded = + image::load_from_memory_with_format(&small, ImageFormat::WebP).expect("decodes"); + assert_eq!((decoded.width(), decoded.height()), (30, 30)); + } + + #[test] + fn an_html_file_renamed_to_png_is_refused() { + let html = b""; + assert!(normalize_photo(html).is_err()); + let mut polyglot = png(16, 16); + polyglot.extend_from_slice(b""); + // The trailing bytes are dropped by the re-encode, so the stored file has no script. + let stored = normalize_photo(&polyglot).expect("normalised"); + assert!(!stored.windows(8).any(|w| w == b"", "01HZ0000000000000000000000"); + assert!(!svg.contains("AL"), "{svg}"); + assert!(initials_svg(" ", "seed").contains(">?")); + } +} diff --git a/crates/im-web/src/pages/preferences.rs b/crates/im-web/src/pages/preferences.rs new file mode 100644 index 0000000..a6a35b3 --- /dev/null +++ b/crates/im-web/src/pages/preferences.rs @@ -0,0 +1,193 @@ +//! The preferences of the signed-in person: the interface language, the time zone and the theme. +//! +//! Every choice is checked against its list before it is stored: the language against `auto`, `en` +//! and `tr`; the time zone against the IANA names compiled into the build; the theme against +//! `system`, `light` and `dark`. The schema repeats the language and theme rules. The theme is +//! applied as a class on `` (see `views::shell`), never as an inline style. + +use im_core::model::AuditAction; +use im_core::time::{is_zone, zone_names}; +use serde::Deserialize; +use serde_json::json; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::see_other; +use topcoat::router::page; +use topcoat::view::{View, view}; + +use crate::audit::{Actor, record}; +use crate::auth::{Viewer, require_csrf, require_user}; +use crate::i18n::Lang; +use crate::i18n::account::{Txt, text}; +use crate::live::Topic; +use crate::state::AppState; +use crate::views::{ViewerInfo, alert, notice, page_lang, shell}; + +/// The language choices. `auto` follows the browser; the others are stored as they are. +const LANGUAGES: [&str; 3] = ["auto", "en", "tr"]; + +/// The theme choices, as stored in `users.theme`. +const THEMES: [&str; 3] = ["system", "light", "dark"]; + +/// The query of `GET /account/preferences`. +#[derive(Deserialize, Default)] +struct PreferencesQuery { + #[serde(default)] + notice: String, +} + +/// The preferences form. Every field defaults to empty, so a missing one is refused, not a 400. +#[derive(Deserialize, Default)] +struct PreferencesForm { + #[serde(default)] + csrf: String, + #[serde(default)] + language: String, + #[serde(default)] + zoneinfo: String, + #[serde(default)] + theme: String, +} + +/// What the preferences page shows. +struct PreferencesData { + csrf: String, + language: String, + zoneinfo: String, + theme: String, + flash_notice: Option, + flash_alert: Option, +} + +impl PreferencesData { + /// The stored preferences of `viewer`, with no notice and no alert. + fn of(viewer: &Viewer) -> Self { + Self { + csrf: viewer.session.csrf_token.clone(), + language: if viewer.user.locale_auto { + "auto".to_owned() + } else { + viewer.user.locale.clone() + }, + zoneinfo: viewer.user.zoneinfo.clone(), + theme: viewer.user.theme.clone(), + flash_notice: None, + flash_alert: None, + } + } +} + +/// `GET /account/preferences`. +#[page("/account/preferences")] +async fn preferences_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_user(cx).await?; + let lang = page_lang(cx, Some(&viewer)); + let mut data = PreferencesData::of(&viewer); + if query.notice == "saved" { + data.flash_notice = Some(text(lang, Txt::SavedPreferences).to_owned()); + } + Ok(preferences_view(cx, lang, ViewerInfo::of(&viewer), data)) +} + +/// `POST /account/preferences`. +#[page(POST "/account/preferences")] +async fn save_preferences(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let lang = page_lang(cx, Some(&viewer)); + + let valid = LANGUAGES.contains(&form.language.as_str()) + && THEMES.contains(&form.theme.as_str()) + && is_zone(&form.zoneinfo); + if !valid { + let mut data = PreferencesData::of(&viewer); + data.flash_alert = Some(text(lang, Txt::ErrPreferenceInvalid).to_owned()); + return Ok(preferences_view(cx, lang, ViewerInfo::of(&viewer), data)); + } + + // "Automatic" keeps the stored language value, which the schema requires to be a real one. + let automatic = form.language == "auto"; + let locale = if automatic { + viewer.user.locale.as_str() + } else { + form.language.as_str() + }; + state + .store + .update_preferences( + &viewer.user.id, + locale, + automatic, + &form.zoneinfo, + &form.theme, + ) + .await?; + state.live.bump(&Topic::Account(viewer.user.id.clone())); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::PreferencesChanged, + Some(("user", &viewer.user.id)), + json!({ "language": form.language, "theme": form.theme }), + ) + .await; + Err(see_other("/account/preferences?notice=saved").into()) +} + +/// The preferences page markup. +fn preferences_view(cx: &Cx, lang: Lang, info: ViewerInfo, data: PreferencesData) -> impl View { + let PreferencesData { + csrf, + language, + zoneinfo, + theme, + flash_notice, + flash_alert, + } = data; + let zones = zone_names(); + view! { cx => + shell(title: text(lang, Txt::PreferencesTitle), lang: lang, viewer: Some(info), +
+

(text(lang, Txt::PreferencesTitle))

+

(text(lang, Txt::PreferencesIntro))

+ if let Some(message) = flash_notice { + notice(message: message) + } + if let Some(message) = flash_alert { + alert(message: message) + } +
+
+ + + + + +
+
+
+ ) + } +} diff --git a/crates/im-web/src/pages/profile.rs b/crates/im-web/src/pages/profile.rs new file mode 100644 index 0000000..3bbc960 --- /dev/null +++ b/crates/im-web/src/pages/profile.rs @@ -0,0 +1,312 @@ +//! The profile of the signed-in person: the display name, the profile photo, and the email address. +//! +//! The email address is shown read-only until the mail step exists; changing it needs the +//! confirmation links that mail carries. The photo is the only upload in `im` so far. Its bytes are +//! read as a stream with a hard limit, and the CSRF field has to arrive before the first byte of the +//! picture, so an upload from another site is refused before it is read at all. What is read is +//! decoded and re-encoded by `im_core::photo` before anything is written. + +use im_core::model::AuditAction; +use im_core::names::parse_display_name; +use im_core::photo::{self, MAX_UPLOAD_BYTES, STORED_MIME}; +use serde::Deserialize; +use serde_json::json; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::content::multipart::Multipart; +use topcoat::router::error::{SeeOther, see_other}; +use topcoat::router::{page, route}; +use topcoat::view::{View, view}; + +use crate::audit::{Actor, record}; +use crate::auth::{Viewer, require_csrf, require_user}; +use crate::i18n::Lang; +use crate::i18n::account::{Txt, text}; +use crate::live::Topic; +use crate::pages::login::CsrfForm; +use crate::state::AppState; +use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; + +/// Path of the photo upload. The router raises the body limit for this path (see `boot.rs`). +pub const PHOTO_ROUTE: &str = "/account/profile/photo"; + +/// The query of `GET /account/profile`. +#[derive(Deserialize, Default)] +struct ProfileQuery { + #[serde(default)] + notice: String, +} + +/// The name form. +#[derive(Deserialize, Default)] +struct NameForm { + #[serde(default)] + csrf: String, + #[serde(default)] + name: String, +} + +/// What the profile page shows. +struct ProfileData { + csrf: String, + user_id: String, + name: String, + email: String, + has_photo: bool, + picture_version: i64, + flash_notice: Option, + flash_alert: Option, +} + +impl ProfileData { + /// The page data of `viewer`, with no notice and no alert. + fn of(viewer: &Viewer) -> Self { + Self { + csrf: viewer.session.csrf_token.clone(), + user_id: viewer.user.id.clone(), + name: viewer.user.name.clone(), + email: viewer.user.email.clone(), + has_photo: viewer.user.photo_mime.is_some(), + picture_version: viewer.user.picture_version, + flash_notice: None, + flash_alert: None, + } + } +} + +/// `GET /account/profile`. +#[page("/account/profile")] +async fn profile_page(cx: &Cx, Form(query): Form) -> Result { + let viewer = require_user(cx).await?; + let lang = page_lang(cx, Some(&viewer)); + let mut data = ProfileData::of(&viewer); + data.flash_notice = match query.notice.as_str() { + "saved-name" => Some(text(lang, Txt::SavedName).to_owned()), + "saved-photo" => Some(text(lang, Txt::SavedPhoto).to_owned()), + "removed-photo" => Some(text(lang, Txt::SavedPhotoRemoved).to_owned()), + _ => None, + }; + Ok(profile_view(cx, lang, ViewerInfo::of(&viewer), data)) +} + +/// `POST /account/profile/name`. +#[page(POST "/account/profile/name")] +async fn change_name(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let lang = page_lang(cx, Some(&viewer)); + let name = match parse_display_name(&form.name) { + Ok(name) => name, + Err(_) => { + // The field keeps the stored name: the typed one may hold control characters. + let mut data = ProfileData::of(&viewer); + data.flash_alert = Some(text(lang, Txt::ErrNameInvalid).to_owned()); + return Ok(profile_view(cx, lang, ViewerInfo::of(&viewer), data)); + } + }; + state.store.update_name(&viewer.user.id, &name).await?; + state.live.bump(&Topic::Account(viewer.user.id.clone())); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::NameChanged, + Some(("user", &viewer.user.id)), + json!({}), + ) + .await; + Err(see_other("/account/profile?notice=saved-name").into()) +} + +/// `POST /account/profile/photo`. A multipart form: the `csrf` field first, then the `photo` file. +#[page(POST "/account/profile/photo")] +async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result { + let state = app_context::(cx); + let mut token = String::new(); + let mut checked: Option = None; + let mut picture: Option> = None; + let mut too_large = false; + + while let Some(mut part) = multipart.next_field().await? { + let name = part.name().unwrap_or_default().to_owned(); + match name.as_str() { + "csrf" => token = part.text().await?, + "photo" => { + // Refused before any byte of the picture is read, unless the token is right. + if checked.is_none() { + checked = Some(require_csrf(cx, &token).await?); + } + let mut bytes = Vec::new(); + while let Some(chunk) = part.chunk().await? { + if bytes.len() + chunk.len() > MAX_UPLOAD_BYTES { + too_large = true; + break; + } + bytes.extend_from_slice(&chunk); + } + picture = Some(bytes); + if too_large { + break; + } + } + _ => { + part.bytes().await?; + } + } + } + + let viewer = match checked { + Some(viewer) => viewer, + None => require_csrf(cx, &token).await?, + }; + let lang = page_lang(cx, Some(&viewer)); + let problem = if too_large { + Some(text(lang, Txt::ErrPhotoTooLarge)) + } else { + None + }; + let Some(bytes) = picture.filter(|_| problem.is_none()) else { + let message = problem.unwrap_or(text(lang, Txt::ErrPhotoMissing)); + return Ok(upload_problem(cx, lang, viewer, message)); + }; + + // Decoding is CPU work and runs off the request threads. + let stored = tokio::task::spawn_blocking(move || photo::normalize_photo(&bytes)) + .await + .map_err(|error| topcoat::Error::msg(error.to_string()))?; + let stored = match stored { + Ok(stored) => stored, + Err(im_core::Error::Invalid(_)) => { + return Ok(upload_problem( + cx, + lang, + viewer, + text(lang, Txt::ErrPhotoType), + )); + } + Err(error) => return Err(error.into()), + }; + + // The file first, then the row: the row only ever names a file that is already in place. + let dir = state.config.data_dir.clone(); + let user_id = viewer.user.id.clone(); + let size = stored.len(); + tokio::task::spawn_blocking(move || photo::write_photo(&dir, &user_id, &stored)) + .await + .map_err(|error| topcoat::Error::msg(error.to_string()))??; + state.store.set_photo(&viewer.user.id, STORED_MIME).await?; + state.live.bump(&Topic::Account(viewer.user.id.clone())); + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::PhotoChanged, + Some(("user", &viewer.user.id)), + json!({ "stored_bytes": size }), + ) + .await; + Err(see_other("/account/profile?notice=saved-photo").into()) +} + +/// The profile page with an alert about the upload. Takes its values by value, so the page does not +/// borrow from the request's locals. +fn upload_problem(cx: &Cx, lang: Lang, viewer: Viewer, message: &str) -> impl View { + let mut data = ProfileData::of(&viewer); + data.flash_alert = Some(message.to_owned()); + profile_view(cx, lang, ViewerInfo::of(&viewer), data) +} + +/// `POST /account/profile/photo/remove`. The row changes first; the file goes after it. +#[route(POST "/account/profile/photo/remove")] +async fn remove_photo(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + if state.store.clear_photo(&viewer.user.id).await? { + state.live.bump(&Topic::Account(viewer.user.id.clone())); + let dir = state.config.data_dir.clone(); + let user_id = viewer.user.id.clone(); + let removed = tokio::task::spawn_blocking(move || photo::remove_photo(&dir, &user_id)) + .await + .map_err(|error| topcoat::Error::msg(error.to_string()))?; + if let Err(error) = removed { + // The row no longer names the file, so a leftover file is never served. + tracing::error!(error = %error, "removed photo file could not be deleted"); + } + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::PhotoRemoved, + Some(("user", &viewer.user.id)), + json!({}), + ) + .await; + } + Ok(see_other("/account/profile?notice=removed-photo")) +} + +/// The profile page markup. +fn profile_view(cx: &Cx, lang: Lang, info: ViewerInfo, data: ProfileData) -> impl View { + let ProfileData { + csrf, + user_id, + name, + email, + has_photo, + picture_version, + flash_notice, + flash_alert, + } = data; + let photo_src = format!("/photo/{user_id}?v={picture_version}"); + view! { cx => + shell(title: text(lang, Txt::ProfileTitle), lang: lang, viewer: Some(info), +
+

(text(lang, Txt::ProfileTitle))

+

(text(lang, Txt::ProfileIntro))

+ if let Some(message) = flash_notice { + notice(message: message) + } + if let Some(message) = flash_alert { + alert(message: message) + } + +
+

(text(lang, Txt::PhotoSection))

+
+ (text(lang, +
+

(text(lang, Txt::PhotoHelp))

+
+ + + +
+ if has_photo { +
+ +

(text(lang, Txt::PhotoRemoveHelp))

+ +
+ } +
+ +
+

(text(lang, Txt::Name))

+
+ + field(label: text(lang, Txt::Name), name: "name", kind: "text", autocomplete: "name", value: name) +

(text(lang, Txt::NameHelp))

+ +
+
+ +
+

(text(lang, Txt::Email))

+

(email)

+

(text(lang, Txt::EmailLaterNote))

+
+
+ ) + } +} diff --git a/crates/im-web/src/pages/setup.rs b/crates/im-web/src/pages/setup.rs index 86f11d3..958555e 100644 --- a/crates/im-web/src/pages/setup.rs +++ b/crates/im-web/src/pages/setup.rs @@ -3,7 +3,7 @@ //! reveal that the instance was set up. use im_core::model::{AuditAction, amr}; -use im_core::names::{normalize_email, parse_email}; +use im_core::names::{normalize_email, parse_display_name, parse_email}; use im_core::password::{check_policy, hash_password_async}; use serde::Deserialize; use serde_json::Value; @@ -67,24 +67,33 @@ async fn setup_submit(cx: &Cx, Form(form): Form) -> Result } let csrf = pre_csrf_token(cx); let lang = page_lang(cx, None); - let name = form.name.trim().to_owned(); let typed_email = form.email.clone(); - let problem = - if name.is_empty() || name.chars().count() > 200 || name.chars().any(char::is_control) { - Some(text(lang, Txt::ErrNameInvalid).to_owned()) - } else { - match parse_email(&normalize_email(&form.email)) { - Err(_) => Some(text(lang, Txt::ErrEmailInvalid).to_owned()), - Ok(email) => match check_policy(&form.password, &email, &name) { - Err(violation) => Some(policy_problem(lang, violation)), - Ok(()) if form.password != form.password_again => { - Some(text(lang, Txt::ErrPasswordsDiffer).to_owned()) - } - Ok(()) => None, - }, + // A refused name is not shown back: it may hold control characters, which must not reach HTML. + let name = match parse_display_name(&form.name) { + Ok(name) => name, + Err(_) => { + let problem = text(lang, Txt::ErrNameInvalid).to_owned(); + return Ok(setup_view( + cx, + lang, + csrf, + String::new(), + typed_email, + Some(problem), + )); + } + }; + let problem = match parse_email(&normalize_email(&form.email)) { + Err(_) => Some(text(lang, Txt::ErrEmailInvalid).to_owned()), + Ok(email) => match check_policy(&form.password, &email, &name) { + Err(violation) => Some(policy_problem(lang, violation)), + Ok(()) if form.password != form.password_again => { + Some(text(lang, Txt::ErrPasswordsDiffer).to_owned()) } - }; + Ok(()) => None, + }, + }; if let Some(problem) = problem { return Ok(setup_view(cx, lang, csrf, name, typed_email, Some(problem))); } diff --git a/crates/im-web/src/pages/tests.rs b/crates/im-web/src/pages/tests.rs index b313963..04eeef4 100644 --- a/crates/im-web/src/pages/tests.rs +++ b/crates/im-web/src/pages/tests.rs @@ -5,7 +5,7 @@ use std::time::Duration; use http::header::{CONTENT_TYPE, COOKIE}; use im_core::password::hash_password; -use im_core::store::sessions::NewSession; +use im_core::store::sessions::{NewSession, SESSION_IDLE}; use im_core::token::{generate_token, hash_token}; use topcoat::router::{Body, to_bytes}; @@ -50,7 +50,8 @@ async fn signed_in(state: &AppState) -> String { amr: "pwd", ip: None, user_agent: None, - ttl: Duration::from_secs(3600), + idle: SESSION_IDLE, + max_age: Duration::from_secs(3600), }, 10, ) diff --git a/crates/im-web/src/security.rs b/crates/im-web/src/security.rs index 8687abb..f31f8b9 100644 --- a/crates/im-web/src/security.rs +++ b/crates/im-web/src/security.rs @@ -1,11 +1,18 @@ -//! The security headers of every response, and the Content-Security-Policy they carry. +//! The security headers of every response, the cache policy that goes with them, and the +//! Content-Security-Policy they carry. //! //! The policy allows scripts and styles from the origin itself and nothing else. No page may use an //! inline script, an inline style or an inline event handler: all behaviour lives in //! `crates/im-web/assets/*.js`. Changing [`CSP`] is a security change, so keep it in step with //! `docs/conventions.md` section 5. +//! +//! Cache policy by path: pages (everything that is not a static asset or a photo) are `no-store`, +//! so a page with a secret (recovery codes, a TOTP secret) is never kept by a browser or a proxy. +//! Assets set their own long-lived policy. Photos set their own `private` policy and their own CSP +//! (see `pages/photo.rs`), so this layer leaves both alone. use topcoat::context::Cx; +use topcoat::router::request::uri; use topcoat::router::response::response_headers; use topcoat::router::{Body, HeaderMap, HeaderValue, Layer, LayerFuture, Next, Path, header}; @@ -16,6 +23,9 @@ pub const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self /// One year, in seconds. Sent only when the public origin is https. const HSTS: &str = "max-age=31536000"; +/// The cache policy of every page: nothing is stored, not even for going back in the history. +const NO_STORE: &str = "no-store"; + /// The headers that every response carries, for an instance at `base_url`. pub fn headers_for(base_url: &str) -> HeaderMap { let mut headers = HeaderMap::new(); @@ -41,18 +51,47 @@ pub fn headers_for(base_url: &str) -> HeaderMap { headers } -/// Adds a fixed set of headers to every response of the router. +/// What kind of answer a path gets, which decides its headers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Answer { + /// A static file under `/assets/`, with its own cache policy. + Asset, + /// A profile photo under `/photo/`, with its own cache policy and its own CSP. + Photo, + /// Everything else: pages, forms, streams. Never stored. + Page, +} + +/// The kind of answer for a request path. +pub fn answer_for(path: &str) -> Answer { + if path.starts_with("/assets/") { + Answer::Asset + } else if path.starts_with("/photo/") { + Answer::Photo + } else { + Answer::Page + } +} + +/// Adds the security headers to every response, and `Cache-Control: no-store` to every page. /// /// It uses the per-request response headers, which the router applies after the layers have run, -/// so error responses (404, 500) carry them as well. +/// so error responses (404, 500) carry them as well. A photo gets the same headers without the +/// page CSP, because the photo handler sends a stricter one of its own. pub struct SecurityHeaders { headers: HeaderMap, + photo_headers: HeaderMap, } impl SecurityHeaders { /// A layer that adds `headers` to every response. pub fn new(headers: HeaderMap) -> Self { - Self { headers } + let mut photo_headers = headers.clone(); + photo_headers.remove(header::CONTENT_SECURITY_POLICY); + Self { + headers, + photo_headers, + } } } @@ -63,7 +102,15 @@ impl Layer for SecurityHeaders { fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { Box::pin(async move { - response_headers(cx).extend(self.headers.clone()); + let answer = answer_for(uri(cx).path()); + let mut headers = match answer { + Answer::Photo => self.photo_headers.clone(), + Answer::Asset | Answer::Page => self.headers.clone(), + }; + if answer == Answer::Page { + headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE)); + } + response_headers(cx).extend(headers); next.run(cx, body).await }) } @@ -73,6 +120,17 @@ impl Layer for SecurityHeaders { mod tests { use super::*; + #[test] + fn only_pages_are_marked_no_store() { + assert_eq!(answer_for("/login"), Answer::Page); + assert_eq!(answer_for("/account/profile"), Answer::Page); + assert_eq!(answer_for("/setup"), Answer::Page); + assert_eq!(answer_for("/photo/01HZ"), Answer::Photo); + assert_eq!(answer_for("/assets/main.css"), Answer::Asset); + // A prefix match on the segment only: a page whose name starts the same is still a page. + assert_eq!(answer_for("/photographs"), Answer::Page); + } + #[test] fn hsts_only_for_https_origins() { assert!( diff --git a/crates/im-web/src/views/mod.rs b/crates/im-web/src/views/mod.rs index 5cc1fb2..9404174 100644 --- a/crates/im-web/src/views/mod.rs +++ b/crates/im-web/src/views/mod.rs @@ -21,6 +21,8 @@ pub struct ViewerInfo { pub is_admin: bool, /// The session's CSRF token, for the sign-out form in the menu. pub csrf: String, + /// `system`, `light` or `dark`. Becomes a class on ``. + pub theme: String, } impl ViewerInfo { @@ -30,14 +32,25 @@ impl ViewerInfo { name: viewer.user.name.clone(), is_admin: viewer.user.is_admin, csrf: viewer.session.csrf_token.clone(), + theme: viewer.user.theme.clone(), + } + } + + /// The class of `` for this theme. Anything unknown falls back to the device's choice. + pub fn theme_class(&self) -> &'static str { + match self.theme.as_str() { + "light" => "theme-light", + "dark" => "theme-dark", + _ => "theme-system", } } } -/// The language of a page: the signed-in person's stored choice when they have one, else the -/// request's `Accept-Language`. +/// The language of a page: the signed-in person's stored choice when they have one and have not +/// chosen "automatic", else the request's `Accept-Language`. pub fn page_lang(cx: &Cx, viewer: Option<&Viewer>) -> Lang { let stored = viewer + .filter(|viewer| !viewer.user.locale_auto) .map(|viewer| viewer.user.locale.as_str()) .filter(|locale| !locale.is_empty()); request_lang(cx, stored) @@ -56,9 +69,12 @@ pub async fn shell( #[default] child: Child<'_>, ) -> Result { let document_title = format!("{title} \u{b7} im"); + let theme_class = viewer + .as_ref() + .map_or("theme-system", ViewerInfo::theme_class); Ok(view! { - + @@ -99,6 +115,8 @@ pub async fn user_menu(lang: Lang, viewer: ViewerInfo) -> Result {