Account profile, photo with re-encode, preferences, people cards, idle-extended sessions
Browse files at this commitc829fac796770720df62ca0f36397b4ae6d2a4f3Parent: fb1f524- feat
- account profile, photo with re-encode, preferences, people cards, idle-extended sessions
32 changed files +2047 -113
- Cargo.lock +269 -7
- Cargo.toml +2 -0
- config/im.example.toml +2 -0
- crates/im-core/Cargo.toml +2 -0
- crates/im-core/migrations/0002_sessions_cap_and_language.sql +9 -0
- crates/im-core/src/config.rs +12 -1
- crates/im-core/src/lib.rs +1 -0
- crates/im-core/src/model.rs +18 -2
- crates/im-core/src/names.rs +62 -1
- crates/im-core/src/photo.rs +226 -0
- crates/im-core/src/store/directory.rs +42 -0
- crates/im-core/src/store/migrate.rs +7 -1
- crates/im-core/src/store/mod.rs +2 -1
- crates/im-core/src/store/sessions.rs +112 -17
- crates/im-core/src/store/users.rs +134 -40
- crates/im-core/src/time.rs +35 -0
- crates/im-core/src/totp.rs +1 -2
- crates/im-web/src/auth.rs +12 -7
- crates/im-web/src/boot.rs +9 -2
- crates/im-web/src/i18n/account.rs +171 -3
- crates/im-web/src/pages/home.rs +2 -0
- crates/im-web/src/pages/mod.rs +4 -0
- crates/im-web/src/pages/people.rs +72 -0
- crates/im-web/src/pages/photo.rs +198 -0
- crates/im-web/src/pages/preferences.rs +193 -0
- crates/im-web/src/pages/profile.rs +312 -0
- crates/im-web/src/pages/setup.rs +25 -16
- crates/im-web/src/pages/tests.rs +3 -2
- crates/im-web/src/security.rs +63 -5
- crates/im-web/src/views/mod.rs +21 -3
- style/_components.scss +23 -0
- style/_tokens.scss +3 -3
Cargo.lockmodified+269 -7
| @@ -2,6 +2,12 @@ | |||
| 2 | # It is not intended for manual editing. | 2 | # It is not intended for manual editing. |
| 3 | version = 4 | 3 | version = 4 |
| 4 | 4 | ||
| 5 | +[[package]] | ||
| 6 | +name = "adler2" | ||
| 7 | +version = "2.0.1" | ||
| 8 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 9 | +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" | ||
| 10 | + | ||
| 5 | [[package]] | 11 | [[package]] |
| 6 | name = "aead" | 12 | name = "aead" |
| 7 | version = "0.5.2" | 13 | version = "0.5.2" |
| @@ -284,7 +290,7 @@ version = "0.69.5" | |||
| 284 | source = "registry+https://github.com/rust-lang/crates.io-index" | 290 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 285 | checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088" | 291 | checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088" |
| 286 | dependencies = [ | 292 | dependencies = [ |
| 287 | - "bitflags", | 293 | + "bitflags 2.13.2", |
| 288 | "cexpr", | 294 | "cexpr", |
| 289 | "clang-sys", | 295 | "clang-sys", |
| 290 | "itertools 0.12.1", | 296 | "itertools 0.12.1", |
| @@ -301,6 +307,12 @@ dependencies = [ | |||
| 301 | "which", | 307 | "which", |
| 302 | ] | 308 | ] |
| 303 | 309 | ||
| 310 | +[[package]] | ||
| 311 | +name = "bitflags" | ||
| 312 | +version = "1.3.2" | ||
| 313 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 314 | +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" | ||
| 315 | + | ||
| 304 | [[package]] | 316 | [[package]] |
| 305 | name = "bitflags" | 317 | name = "bitflags" |
| 306 | version = "2.13.2" | 318 | version = "2.13.2" |
| @@ -419,6 +431,12 @@ version = "1.5.0" | |||
| 419 | source = "registry+https://github.com/rust-lang/crates.io-index" | 431 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 420 | checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" | 432 | checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" |
| 421 | 433 | ||
| 434 | +[[package]] | ||
| 435 | +name = "byteorder-lite" | ||
| 436 | +version = "0.1.0" | ||
| 437 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 438 | +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" | ||
| 439 | + | ||
| 422 | [[package]] | 440 | [[package]] |
| 423 | name = "bytes" | 441 | name = "bytes" |
| 424 | version = "1.12.1" | 442 | version = "1.12.1" |
| @@ -578,6 +596,12 @@ version = "0.1.3" | |||
| 578 | source = "registry+https://github.com/rust-lang/crates.io-index" | 596 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 579 | checksum = "b9e769b5c8c8283982a987c6e948e540254f1058d5a74b8794914d4ef5fc2a24" | 597 | checksum = "b9e769b5c8c8283982a987c6e948e540254f1058d5a74b8794914d4ef5fc2a24" |
| 580 | 598 | ||
| 599 | +[[package]] | ||
| 600 | +name = "color_quant" | ||
| 601 | +version = "1.1.0" | ||
| 602 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 603 | +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" | ||
| 604 | + | ||
| 581 | [[package]] | 605 | [[package]] |
| 582 | name = "colorchoice" | 606 | name = "colorchoice" |
| 583 | version = "1.0.5" | 607 | version = "1.0.5" |
| @@ -819,6 +843,37 @@ version = "0.2.0" | |||
| 819 | source = "registry+https://github.com/rust-lang/crates.io-index" | 843 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 820 | checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745" | 844 | checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745" |
| 821 | 845 | ||
| 846 | +[[package]] | ||
| 847 | +name = "defmt" | ||
| 848 | +version = "1.2.0" | ||
| 849 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 850 | +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" | ||
| 851 | +dependencies = [ | ||
| 852 | + "bitflags 1.3.2", | ||
| 853 | + "defmt-macros", | ||
| 854 | +] | ||
| 855 | + | ||
| 856 | +[[package]] | ||
| 857 | +name = "defmt-macros" | ||
| 858 | +version = "1.2.0" | ||
| 859 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 860 | +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" | ||
| 861 | +dependencies = [ | ||
| 862 | + "defmt-parser", | ||
| 863 | + "proc-macro2", | ||
| 864 | + "quote", | ||
| 865 | + "syn 3.0.9", | ||
| 866 | +] | ||
| 867 | + | ||
| 868 | +[[package]] | ||
| 869 | +name = "defmt-parser" | ||
| 870 | +version = "1.1.0" | ||
| 871 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 872 | +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" | ||
| 873 | +dependencies = [ | ||
| 874 | + "thiserror", | ||
| 875 | +] | ||
| 876 | + | ||
| 822 | [[package]] | 877 | [[package]] |
| 823 | name = "deranged" | 878 | name = "deranged" |
| 824 | version = "0.5.9" | 879 | version = "0.5.9" |
| @@ -1013,6 +1068,15 @@ version = "2.5.0" | |||
| 1013 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1068 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1014 | checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" | 1069 | checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" |
| 1015 | 1070 | ||
| 1071 | +[[package]] | ||
| 1072 | +name = "fdeflate" | ||
| 1073 | +version = "0.3.7" | ||
| 1074 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1075 | +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" | ||
| 1076 | +dependencies = [ | ||
| 1077 | + "simd-adler32", | ||
| 1078 | +] | ||
| 1079 | + | ||
| 1016 | [[package]] | 1080 | [[package]] |
| 1017 | name = "fiat-crypto" | 1081 | name = "fiat-crypto" |
| 1018 | version = "0.3.0" | 1082 | version = "0.3.0" |
| @@ -1025,6 +1089,17 @@ version = "0.1.15" | |||
| 1025 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1089 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1026 | checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" | 1090 | checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" |
| 1027 | 1091 | ||
| 1092 | +[[package]] | ||
| 1093 | +name = "flate2" | ||
| 1094 | +version = "1.1.10" | ||
| 1095 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1096 | +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" | ||
| 1097 | +dependencies = [ | ||
| 1098 | + "crc32fast", | ||
| 1099 | + "miniz_oxide 0.9.1", | ||
| 1100 | + "zlib-rs", | ||
| 1101 | +] | ||
| 1102 | + | ||
| 1028 | [[package]] | 1103 | [[package]] |
| 1029 | name = "fnv" | 1104 | name = "fnv" |
| 1030 | version = "1.0.7" | 1105 | version = "1.0.7" |
| @@ -1205,6 +1280,16 @@ dependencies = [ | |||
| 1205 | "polyval", | 1280 | "polyval", |
| 1206 | ] | 1281 | ] |
| 1207 | 1282 | ||
| 1283 | +[[package]] | ||
| 1284 | +name = "gif" | ||
| 1285 | +version = "0.14.2" | ||
| 1286 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1287 | +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" | ||
| 1288 | +dependencies = [ | ||
| 1289 | + "color_quant", | ||
| 1290 | + "weezl", | ||
| 1291 | +] | ||
| 1292 | + | ||
| 1208 | [[package]] | 1293 | [[package]] |
| 1209 | name = "glob" | 1294 | name = "glob" |
| 1210 | version = "0.3.4" | 1295 | version = "0.3.4" |
| @@ -1658,7 +1743,9 @@ dependencies = [ | |||
| 1658 | "ed25519-dalek", | 1743 | "ed25519-dalek", |
| 1659 | "hex", | 1744 | "hex", |
| 1660 | "hmac 0.13.0", | 1745 | "hmac 0.13.0", |
| 1746 | + "image", | ||
| 1661 | "ipnet", | 1747 | "ipnet", |
| 1748 | + "jiff", | ||
| 1662 | "rand 0.10.3", | 1749 | "rand 0.10.3", |
| 1663 | "serde", | 1750 | "serde", |
| 1664 | "serde_json", | 1751 | "serde_json", |
| @@ -1696,6 +1783,34 @@ dependencies = [ | |||
| 1696 | "tracing-subscriber", | 1783 | "tracing-subscriber", |
| 1697 | ] | 1784 | ] |
| 1698 | 1785 | ||
| 1786 | +[[package]] | ||
| 1787 | +name = "image" | ||
| 1788 | +version = "0.25.10" | ||
| 1789 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1790 | +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" | ||
| 1791 | +dependencies = [ | ||
| 1792 | + "bytemuck", | ||
| 1793 | + "byteorder-lite", | ||
| 1794 | + "color_quant", | ||
| 1795 | + "gif", | ||
| 1796 | + "image-webp", | ||
| 1797 | + "moxcms", | ||
| 1798 | + "num-traits", | ||
| 1799 | + "png", | ||
| 1800 | + "zune-core", | ||
| 1801 | + "zune-jpeg", | ||
| 1802 | +] | ||
| 1803 | + | ||
| 1804 | +[[package]] | ||
| 1805 | +name = "image-webp" | ||
| 1806 | +version = "0.2.4" | ||
| 1807 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1808 | +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" | ||
| 1809 | +dependencies = [ | ||
| 1810 | + "byteorder-lite", | ||
| 1811 | + "quick-error", | ||
| 1812 | +] | ||
| 1813 | + | ||
| 1699 | [[package]] | 1814 | [[package]] |
| 1700 | name = "indexmap" | 1815 | name = "indexmap" |
| 1701 | version = "2.14.2" | 1816 | version = "2.14.2" |
| @@ -1748,7 +1863,7 @@ version = "0.7.15" | |||
| 1748 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1863 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1749 | checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb" | 1864 | checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb" |
| 1750 | dependencies = [ | 1865 | dependencies = [ |
| 1751 | - "bitflags", | 1866 | + "bitflags 2.13.2", |
| 1752 | "cfg-if", | 1867 | "cfg-if", |
| 1753 | "libc", | 1868 | "libc", |
| 1754 | ] | 1869 | ] |
| @@ -1789,6 +1904,50 @@ version = "1.0.18" | |||
| 1789 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1904 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1790 | checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" | 1905 | checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" |
| 1791 | 1906 | ||
| 1907 | +[[package]] | ||
| 1908 | +name = "jiff" | ||
| 1909 | +version = "0.2.38" | ||
| 1910 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1911 | +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" | ||
| 1912 | +dependencies = [ | ||
| 1913 | + "defmt", | ||
| 1914 | + "jiff-core", | ||
| 1915 | + "jiff-static", | ||
| 1916 | + "jiff-tzdb", | ||
| 1917 | + "log", | ||
| 1918 | + "portable-atomic", | ||
| 1919 | + "portable-atomic-util", | ||
| 1920 | + "serde_core", | ||
| 1921 | +] | ||
| 1922 | + | ||
| 1923 | +[[package]] | ||
| 1924 | +name = "jiff-core" | ||
| 1925 | +version = "0.1.1" | ||
| 1926 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1927 | +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" | ||
| 1928 | +dependencies = [ | ||
| 1929 | + "defmt", | ||
| 1930 | + "log", | ||
| 1931 | +] | ||
| 1932 | + | ||
| 1933 | +[[package]] | ||
| 1934 | +name = "jiff-static" | ||
| 1935 | +version = "0.2.38" | ||
| 1936 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1937 | +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" | ||
| 1938 | +dependencies = [ | ||
| 1939 | + "jiff-core", | ||
| 1940 | + "proc-macro2", | ||
| 1941 | + "quote", | ||
| 1942 | + "syn 2.0.119", | ||
| 1943 | +] | ||
| 1944 | + | ||
| 1945 | +[[package]] | ||
| 1946 | +name = "jiff-tzdb" | ||
| 1947 | +version = "0.1.9" | ||
| 1948 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1949 | +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" | ||
| 1950 | + | ||
| 1792 | [[package]] | 1951 | [[package]] |
| 1793 | name = "jobserver" | 1952 | name = "jobserver" |
| 1794 | version = "0.1.35" | 1953 | version = "0.1.35" |
| @@ -2057,6 +2216,26 @@ version = "0.2.1" | |||
| 2057 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2216 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2058 | checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" | 2217 | checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" |
| 2059 | 2218 | ||
| 2219 | +[[package]] | ||
| 2220 | +name = "miniz_oxide" | ||
| 2221 | +version = "0.8.9" | ||
| 2222 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2223 | +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" | ||
| 2224 | +dependencies = [ | ||
| 2225 | + "adler2", | ||
| 2226 | + "simd-adler32", | ||
| 2227 | +] | ||
| 2228 | + | ||
| 2229 | +[[package]] | ||
| 2230 | +name = "miniz_oxide" | ||
| 2231 | +version = "0.9.1" | ||
| 2232 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2233 | +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" | ||
| 2234 | +dependencies = [ | ||
| 2235 | + "adler2", | ||
| 2236 | + "simd-adler32", | ||
| 2237 | +] | ||
| 2238 | + | ||
| 2060 | [[package]] | 2239 | [[package]] |
| 2061 | name = "mio" | 2240 | name = "mio" |
| 2062 | version = "1.2.4" | 2241 | version = "1.2.4" |
| @@ -2068,6 +2247,16 @@ dependencies = [ | |||
| 2068 | "windows-sys 0.61.2", | 2247 | "windows-sys 0.61.2", |
| 2069 | ] | 2248 | ] |
| 2070 | 2249 | ||
| 2250 | +[[package]] | ||
| 2251 | +name = "moxcms" | ||
| 2252 | +version = "0.8.1" | ||
| 2253 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2254 | +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" | ||
| 2255 | +dependencies = [ | ||
| 2256 | + "num-traits", | ||
| 2257 | + "pxfm", | ||
| 2258 | +] | ||
| 2259 | + | ||
| 2071 | [[package]] | 2260 | [[package]] |
| 2072 | name = "multer" | 2261 | name = "multer" |
| 2073 | version = "3.1.0" | 2262 | version = "3.1.0" |
| @@ -2326,6 +2515,19 @@ version = "0.3.34" | |||
| 2326 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2515 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2327 | checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" | 2516 | checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" |
| 2328 | 2517 | ||
| 2518 | +[[package]] | ||
| 2519 | +name = "png" | ||
| 2520 | +version = "0.18.1" | ||
| 2521 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2522 | +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" | ||
| 2523 | +dependencies = [ | ||
| 2524 | + "bitflags 2.13.2", | ||
| 2525 | + "crc32fast", | ||
| 2526 | + "fdeflate", | ||
| 2527 | + "flate2", | ||
| 2528 | + "miniz_oxide 0.8.9", | ||
| 2529 | +] | ||
| 2530 | + | ||
| 2329 | [[package]] | 2531 | [[package]] |
| 2330 | name = "polling" | 2532 | name = "polling" |
| 2331 | version = "3.11.0" | 2533 | version = "3.11.0" |
| @@ -2362,6 +2564,21 @@ dependencies = [ | |||
| 2362 | "universal-hash 0.5.1", | 2564 | "universal-hash 0.5.1", |
| 2363 | ] | 2565 | ] |
| 2364 | 2566 | ||
| 2567 | +[[package]] | ||
| 2568 | +name = "portable-atomic" | ||
| 2569 | +version = "1.15.0" | ||
| 2570 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2571 | +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" | ||
| 2572 | + | ||
| 2573 | +[[package]] | ||
| 2574 | +name = "portable-atomic-util" | ||
| 2575 | +version = "0.2.8" | ||
| 2576 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2577 | +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" | ||
| 2578 | +dependencies = [ | ||
| 2579 | + "portable-atomic", | ||
| 2580 | +] | ||
| 2581 | + | ||
| 2365 | [[package]] | 2582 | [[package]] |
| 2366 | name = "potential_utf" | 2583 | name = "potential_utf" |
| 2367 | version = "0.1.6" | 2584 | version = "0.1.6" |
| @@ -2449,12 +2666,24 @@ dependencies = [ | |||
| 2449 | "syn 2.0.119", | 2666 | "syn 2.0.119", |
| 2450 | ] | 2667 | ] |
| 2451 | 2668 | ||
| 2669 | +[[package]] | ||
| 2670 | +name = "pxfm" | ||
| 2671 | +version = "0.1.30" | ||
| 2672 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2673 | +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" | ||
| 2674 | + | ||
| 2452 | [[package]] | 2675 | [[package]] |
| 2453 | name = "qrcode" | 2676 | name = "qrcode" |
| 2454 | version = "0.14.1" | 2677 | version = "0.14.1" |
| 2455 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2678 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2456 | checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" | 2679 | checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" |
| 2457 | 2680 | ||
| 2681 | +[[package]] | ||
| 2682 | +name = "quick-error" | ||
| 2683 | +version = "2.0.1" | ||
| 2684 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2685 | +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" | ||
| 2686 | + | ||
| 2458 | [[package]] | 2687 | [[package]] |
| 2459 | name = "quote" | 2688 | name = "quote" |
| 2460 | version = "1.0.47" | 2689 | version = "1.0.47" |
| @@ -2608,7 +2837,7 @@ version = "0.5.18" | |||
| 2608 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2837 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2609 | checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" | 2838 | checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" |
| 2610 | dependencies = [ | 2839 | dependencies = [ |
| 2611 | - "bitflags", | 2840 | + "bitflags 2.13.2", |
| 2612 | ] | 2841 | ] |
| 2613 | 2842 | ||
| 2614 | [[package]] | 2843 | [[package]] |
| @@ -2717,7 +2946,7 @@ version = "0.38.44" | |||
| 2717 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2946 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2718 | checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" | 2947 | checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" |
| 2719 | dependencies = [ | 2948 | dependencies = [ |
| 2720 | - "bitflags", | 2949 | + "bitflags 2.13.2", |
| 2721 | "errno", | 2950 | "errno", |
| 2722 | "libc", | 2951 | "libc", |
| 2723 | "linux-raw-sys 0.4.15", | 2952 | "linux-raw-sys 0.4.15", |
| @@ -2730,7 +2959,7 @@ version = "1.1.6" | |||
| 2730 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2959 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2731 | checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" | 2960 | checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" |
| 2732 | dependencies = [ | 2961 | dependencies = [ |
| 2733 | - "bitflags", | 2962 | + "bitflags 2.13.2", |
| 2734 | "errno", | 2963 | "errno", |
| 2735 | "libc", | 2964 | "libc", |
| 2736 | "linux-raw-sys 0.12.1", | 2965 | "linux-raw-sys 0.12.1", |
| @@ -2952,6 +3181,12 @@ dependencies = [ | |||
| 2952 | "rand_core 0.10.1", | 3181 | "rand_core 0.10.1", |
| 2953 | ] | 3182 | ] |
| 2954 | 3183 | ||
| 3184 | +[[package]] | ||
| 3185 | +name = "simd-adler32" | ||
| 3186 | +version = "0.3.10" | ||
| 3187 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3188 | +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" | ||
| 3189 | + | ||
| 2955 | [[package]] | 3190 | [[package]] |
| 2956 | name = "simdutf8" | 3191 | name = "simdutf8" |
| 2957 | version = "0.1.5" | 3192 | version = "0.1.5" |
| @@ -3885,7 +4120,7 @@ dependencies = [ | |||
| 3885 | "arc-swap", | 4120 | "arc-swap", |
| 3886 | "aristo", | 4121 | "aristo", |
| 3887 | "bigdecimal", | 4122 | "bigdecimal", |
| 3888 | - "bitflags", | 4123 | + "bitflags 2.13.2", |
| 3889 | "branches", | 4124 | "branches", |
| 3890 | "bumpalo", | 4125 | "bumpalo", |
| 3891 | "bytemuck", | 4126 | "bytemuck", |
| @@ -3974,7 +4209,7 @@ version = "0.8.3" | |||
| 3974 | source = "registry+https://github.com/rust-lang/crates.io-index" | 4209 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3975 | checksum = "a69bb856ec8306ad7ed1c13fc61de6a79452bf646ca53d99bb4cc646d5bfc4ff" | 4210 | checksum = "a69bb856ec8306ad7ed1c13fc61de6a79452bf646ca53d99bb4cc646d5bfc4ff" |
| 3976 | dependencies = [ | 4211 | dependencies = [ |
| 3977 | - "bitflags", | 4212 | + "bitflags 2.13.2", |
| 3978 | "memchr", | 4213 | "memchr", |
| 3979 | "miette", | 4214 | "miette", |
| 3980 | "strum", | 4215 | "strum", |
| @@ -4268,6 +4503,12 @@ dependencies = [ | |||
| 4268 | "wasm-bindgen", | 4503 | "wasm-bindgen", |
| 4269 | ] | 4504 | ] |
| 4270 | 4505 | ||
| 4506 | +[[package]] | ||
| 4507 | +name = "weezl" | ||
| 4508 | +version = "0.1.12" | ||
| 4509 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4510 | +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" | ||
| 4511 | + | ||
| 4271 | [[package]] | 4512 | [[package]] |
| 4272 | name = "which" | 4513 | name = "which" |
| 4273 | version = "4.4.2" | 4514 | version = "4.4.2" |
| @@ -4584,6 +4825,12 @@ dependencies = [ | |||
| 4584 | "syn 3.0.9", | 4825 | "syn 3.0.9", |
| 4585 | ] | 4826 | ] |
| 4586 | 4827 | ||
| 4828 | +[[package]] | ||
| 4829 | +name = "zlib-rs" | ||
| 4830 | +version = "0.6.8" | ||
| 4831 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4832 | +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" | ||
| 4833 | + | ||
| 4587 | [[package]] | 4834 | [[package]] |
| 4588 | name = "zmij" | 4835 | name = "zmij" |
| 4589 | version = "1.0.23" | 4836 | version = "1.0.23" |
| @@ -4617,3 +4864,18 @@ dependencies = [ | |||
| 4617 | "cc", | 4864 | "cc", |
| 4618 | "pkg-config", | 4865 | "pkg-config", |
| 4619 | ] | 4866 | ] |
| 4867 | + | ||
| 4868 | +[[package]] | ||
| 4869 | +name = "zune-core" | ||
| 4870 | +version = "0.5.3" | ||
| 4871 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4872 | +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" | ||
| 4873 | + | ||
| 4874 | +[[package]] | ||
| 4875 | +name = "zune-jpeg" | ||
| 4876 | +version = "0.5.15" | ||
| 4877 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4878 | +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" | ||
| 4879 | +dependencies = [ | ||
| 4880 | + "zune-core", | ||
| 4881 | +] | ||
Cargo.tomlmodified+2 -0
| @@ -19,6 +19,8 @@ futures-util = "0.3.34" | |||
| 19 | grass = "0.13.4" | 19 | grass = "0.13.4" |
| 20 | hex = "0.4.3" | 20 | hex = "0.4.3" |
| 21 | hmac = "0.13.0" | 21 | hmac = "0.13.0" |
| 22 | +image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp", "gif"] } | ||
| 23 | +jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] } | ||
| 22 | http = "1.5.0" | 24 | http = "1.5.0" |
| 23 | ipnet = "2.12.2" | 25 | ipnet = "2.12.2" |
| 24 | qrcode = { version = "0.14.1", default-features = false, features = ["svg"] } | 26 | qrcode = { version = "0.14.1", default-features = false, features = ["svg"] } |
config/im.example.tomlmodified+2 -0
| @@ -37,3 +37,5 @@ healthcheck_url = "" | |||
| 37 | require_2fa_for_admins = true | 37 | require_2fa_for_admins = true |
| 38 | # Sessions one person may hold at once. The oldest is ended when a new sign-in would exceed it. | 38 | # Sessions one person may hold at once. The oldest is ended when a new sign-in would exceed it. |
| 39 | max_sessions = 10 | 39 | max_sessions = 10 |
| 40 | +# Hard cap of a browser session, in days from sign-in. Sessions are extended while they are used, up to this. | ||
| 41 | +session_max_days = 30 | ||
crates/im-core/Cargo.tomlmodified+2 -0
| @@ -15,6 +15,8 @@ chacha20poly1305.workspace = true | |||
| 15 | ed25519-dalek.workspace = true | 15 | ed25519-dalek.workspace = true |
| 16 | hex.workspace = true | 16 | hex.workspace = true |
| 17 | hmac.workspace = true | 17 | hmac.workspace = true |
| 18 | +image.workspace = true | ||
| 19 | +jiff.workspace = true | ||
| 18 | ipnet.workspace = true | 20 | ipnet.workspace = true |
| 19 | rand.workspace = true | 21 | rand.workspace = true |
| 20 | serde.workspace = true | 22 | serde.workspace = true |
crates/im-core/migrations/0002_sessions_cap_and_language.sqladded+9 -0
| @@ -0,0 +1,9 @@ | |||
| 1 | +-- 0002: the hard lifetime cap of a session, and the "automatic language" flag of an account. | ||
| 2 | +-- hard_expires_at is created + session_max_days; expires_at is never later than it. The default is | ||
| 3 | +-- the epoch, so a row from before this migration is already expired (fails closed). | ||
| 4 | +-- locale_auto = 1 means the UI language follows Accept-Language and users.locale is ignored. The | ||
| 5 | +-- 0001 CHECK on locale only allows 'en' and 'tr', so "automatic" needs its own column. | ||
| 6 | + | ||
| 7 | +ALTER TABLE sessions ADD COLUMN hard_expires_at TEXT NOT NULL DEFAULT '1970-01-01T00:00:00.000000000Z'; | ||
| 8 | + | ||
| 9 | +ALTER TABLE users ADD COLUMN locale_auto INTEGER NOT NULL DEFAULT 1 CHECK (locale_auto IN (0, 1)); | ||
crates/im-core/src/config.rsmodified+12 -1
| @@ -84,6 +84,9 @@ pub struct PolicyConfig { | |||
| 84 | /// Sessions one person may hold at once. The oldest is ended when a new sign-in would exceed it. | 84 | /// Sessions one person may hold at once. The oldest is ended when a new sign-in would exceed it. |
| 85 | /// At least 1. | 85 | /// At least 1. |
| 86 | pub max_sessions: u32, | 86 | pub max_sessions: u32, |
| 87 | + /// Hard cap of a browser session, in days from sign-in. A session is idle-extended on use (30 days | ||
| 88 | + /// since its last use) but never lives longer than this. Between 1 and 365. | ||
| 89 | + pub session_max_days: u32, | ||
| 87 | } | 90 | } |
| 88 | 91 | ||
| 89 | impl Default for PolicyConfig { | 92 | impl Default for PolicyConfig { |
| @@ -91,6 +94,7 @@ impl Default for PolicyConfig { | |||
| 91 | Self { | 94 | Self { |
| 92 | require_2fa_for_admins: true, | 95 | require_2fa_for_admins: true, |
| 93 | max_sessions: 10, | 96 | max_sessions: 10, |
| 97 | + session_max_days: 30, | ||
| 94 | } | 98 | } |
| 95 | } | 99 | } |
| 96 | } | 100 | } |
| @@ -170,7 +174,14 @@ impl Config { | |||
| 170 | } | 174 | } |
| 171 | } | 175 | } |
| 172 | if self.policy.max_sessions == 0 { | 176 | if self.policy.max_sessions == 0 { |
| 173 | - return Err(Error::Config("[policy] max_sessions must be at least 1".into())); | 177 | + return Err(Error::Config( |
| 178 | + "[policy] max_sessions must be at least 1".into(), | ||
| 179 | + )); | ||
| 180 | + } | ||
| 181 | + if !(1..=365).contains(&self.policy.session_max_days) { | ||
| 182 | + return Err(Error::Config( | ||
| 183 | + "[policy] session_max_days must be between 1 and 365".into(), | ||
| 184 | + )); | ||
| 174 | } | 185 | } |
| 175 | let hc = &self.backup.healthcheck_url; | 186 | let hc = &self.backup.healthcheck_url; |
| 176 | if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) { | 187 | if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) { |
crates/im-core/src/lib.rsmodified+1 -0
| @@ -8,6 +8,7 @@ pub mod error; | |||
| 8 | pub mod model; | 8 | pub mod model; |
| 9 | pub mod names; | 9 | pub mod names; |
| 10 | pub mod password; | 10 | pub mod password; |
| 11 | +pub mod photo; | ||
| 11 | pub mod secret; | 12 | pub mod secret; |
| 12 | pub mod store; | 13 | pub mod store; |
| 13 | pub mod time; | 14 | pub mod time; |
crates/im-core/src/model.rsmodified+18 -2
| @@ -25,8 +25,10 @@ pub struct User { | |||
| 25 | pub totp_enabled_at: Option<String>, | 25 | pub totp_enabled_at: Option<String>, |
| 26 | /// The last TOTP step that was accepted. A code of this step or an earlier one is refused. | 26 | /// The last TOTP step that was accepted. A code of this step or an earlier one is refused. |
| 27 | pub totp_last_step: Option<i64>, | 27 | pub totp_last_step: Option<i64>, |
| 28 | - /// `en` or `tr`. | 28 | + /// `en` or `tr`. Used only when `locale_auto` is false. |
| 29 | pub locale: String, | 29 | pub locale: String, |
| 30 | + /// True when the interface language follows the browser (`Accept-Language`) instead of `locale`. | ||
| 31 | + pub locale_auto: bool, | ||
| 30 | /// IANA time zone name. | 32 | /// IANA time zone name. |
| 31 | pub zoneinfo: String, | 33 | pub zoneinfo: String, |
| 32 | /// `system`, `light` or `dark`. | 34 | /// `system`, `light` or `dark`. |
| @@ -77,8 +79,10 @@ pub struct Session { | |||
| 77 | pub csrf_token: String, | 79 | pub csrf_token: String, |
| 78 | /// Creation time (the sign-in time). | 80 | /// Creation time (the sign-in time). |
| 79 | pub created_at: String, | 81 | pub created_at: String, |
| 80 | - /// Absolute expiry. | 82 | + /// Expiry, moved forward on use (idle extension). Never later than `hard_expires_at`. |
| 81 | pub expires_at: String, | 83 | pub expires_at: String, |
| 84 | + /// The hard cap: creation plus `session_max_days`. Idle extension stops here. | ||
| 85 | + pub hard_expires_at: String, | ||
| 82 | /// Last time the session was used. Written at most once every five minutes. | 86 | /// Last time the session was used. Written at most once every five minutes. |
| 83 | pub last_seen_at: String, | 87 | pub last_seen_at: String, |
| 84 | /// Address the session was created from. | 88 | /// Address the session was created from. |
| @@ -110,6 +114,14 @@ pub enum AuditAction { | |||
| 110 | TotpEnabled, | 114 | TotpEnabled, |
| 111 | /// Two-factor sign-in was turned off. | 115 | /// Two-factor sign-in was turned off. |
| 112 | TotpDisabled, | 116 | TotpDisabled, |
| 117 | + /// The display name was changed. | ||
| 118 | + NameChanged, | ||
| 119 | + /// A profile photo was uploaded. | ||
| 120 | + PhotoChanged, | ||
| 121 | + /// The profile photo was removed. | ||
| 122 | + PhotoRemoved, | ||
| 123 | + /// Language, time zone or theme was changed. | ||
| 124 | + PreferencesChanged, | ||
| 113 | /// A new set of recovery codes was issued. | 125 | /// A new set of recovery codes was issued. |
| 114 | RecoveryCodesIssued, | 126 | RecoveryCodesIssued, |
| 115 | /// One session was ended by its owner. | 127 | /// One session was ended by its owner. |
| @@ -130,6 +142,10 @@ impl AuditAction { | |||
| 130 | AuditAction::PasswordChanged => "password.changed", | 142 | AuditAction::PasswordChanged => "password.changed", |
| 131 | AuditAction::TotpEnabled => "totp.enabled", | 143 | AuditAction::TotpEnabled => "totp.enabled", |
| 132 | AuditAction::TotpDisabled => "totp.disabled", | 144 | AuditAction::TotpDisabled => "totp.disabled", |
| 145 | + AuditAction::NameChanged => "profile.name", | ||
| 146 | + AuditAction::PhotoChanged => "profile.photo", | ||
| 147 | + AuditAction::PhotoRemoved => "profile.photo_removed", | ||
| 148 | + AuditAction::PreferencesChanged => "preferences.changed", | ||
| 133 | AuditAction::RecoveryCodesIssued => "recovery.issued", | 149 | AuditAction::RecoveryCodesIssued => "recovery.issued", |
| 134 | AuditAction::SessionRevoked => "session.revoked", | 150 | AuditAction::SessionRevoked => "session.revoked", |
| 135 | AuditAction::SessionsRevoked => "sessions.revoked", | 151 | AuditAction::SessionsRevoked => "sessions.revoked", |
crates/im-core/src/names.rsmodified+62 -1
| @@ -6,9 +6,16 @@ | |||
| 6 | //! account look exactly like the first one. | 6 | //! account look exactly like the first one. |
| 7 | //! | 7 | //! |
| 8 | //! The check is a sanity check on the text, not proof that the address exists or receives mail. | 8 | //! The check is a sanity check on the text, not proof that the address exists or receives mail. |
| 9 | +//! | ||
| 10 | +//! This module also checks display names ([`parse_display_name`]). A name is shown in the topbar, | ||
| 11 | +//! in mail and in other apps, so control characters and bidirectional overrides are refused: they | ||
| 12 | +//! can make one name read as another. | ||
| 9 | 13 | ||
| 10 | use crate::error::{Error, Result}; | 14 | use crate::error::{Error, Result}; |
| 11 | 15 | ||
| 16 | +/// Longest display name, in characters. The schema has the same limit. | ||
| 17 | +pub const MAX_NAME_CHARS: usize = 100; | ||
| 18 | + | ||
| 12 | /// Longest address accepted, in bytes (RFC 5321 path limit). | 19 | /// Longest address accepted, in bytes (RFC 5321 path limit). |
| 13 | pub const MAX_EMAIL_LEN: usize = 254; | 20 | pub const MAX_EMAIL_LEN: usize = 254; |
| 14 | 21 | ||
| @@ -35,6 +42,32 @@ pub fn parse_email(input: &str) -> Result<String> { | |||
| 35 | Ok(email) | 42 | Ok(email) |
| 36 | } | 43 | } |
| 37 | 44 | ||
| 45 | +/// Checks a display name and returns its stored form. | ||
| 46 | +/// | ||
| 47 | +/// Rules: surrounding whitespace is removed; what is left has 1 to [`MAX_NAME_CHARS`] characters; | ||
| 48 | +/// no character is a control character (this includes NUL, tab and line breaks); and no character | ||
| 49 | +/// is a bidirectional override or isolate (U+202A to U+202E, U+2066 to U+2069). Those last ones | ||
| 50 | +/// let a name display differently from the order its characters are stored in. | ||
| 51 | +pub fn parse_display_name(input: &str) -> Result<String> { | ||
| 52 | + let name = input.trim(); | ||
| 53 | + let invalid = |why: &str| Error::Invalid(format!("the name {why}")); | ||
| 54 | + if name.is_empty() { | ||
| 55 | + return Err(invalid("must not be empty")); | ||
| 56 | + } | ||
| 57 | + if name.chars().count() > MAX_NAME_CHARS { | ||
| 58 | + return Err(invalid("must be at most 100 characters")); | ||
| 59 | + } | ||
| 60 | + if name.chars().any(|c| c.is_control() || is_bidi_control(c)) { | ||
| 61 | + return Err(invalid("must not contain control or direction characters")); | ||
| 62 | + } | ||
| 63 | + Ok(name.to_owned()) | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// The bidirectional embedding, override and isolate controls that [`parse_display_name`] refuses. | ||
| 67 | +fn is_bidi_control(c: char) -> bool { | ||
| 68 | + matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') | ||
| 69 | +} | ||
| 70 | + | ||
| 38 | /// The shape rules of [`parse_email`], for text that is already normalised. | 71 | /// The shape rules of [`parse_email`], for text that is already normalised. |
| 39 | fn check_shape(email: &str) -> Result<()> { | 72 | fn check_shape(email: &str) -> Result<()> { |
| 40 | let invalid = || Error::Invalid("email address is not valid".into()); | 73 | let invalid = || Error::Invalid("email address is not valid".into()); |
| @@ -59,7 +92,9 @@ fn check_shape(email: &str) -> Result<()> { | |||
| 59 | && label.len() <= MAX_LABEL_LEN | 92 | && label.len() <= MAX_LABEL_LEN |
| 60 | && !label.starts_with('-') | 93 | && !label.starts_with('-') |
| 61 | && !label.ends_with('-') | 94 | && !label.ends_with('-') |
| 62 | - && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'); | 95 | + && label |
| 96 | + .bytes() | ||
| 97 | + .all(|b| b.is_ascii_alphanumeric() || b == b'-'); | ||
| 63 | if !well_formed { | 98 | if !well_formed { |
| 64 | return Err(invalid()); | 99 | return Err(invalid()); |
| 65 | } | 100 | } |
| @@ -84,6 +119,32 @@ mod tests { | |||
| 84 | ); | 119 | ); |
| 85 | } | 120 | } |
| 86 | 121 | ||
| 122 | + #[test] | ||
| 123 | + fn display_names_are_trimmed_and_checked() { | ||
| 124 | + assert_eq!( | ||
| 125 | + parse_display_name(" Ada Lovelace ").unwrap(), | ||
| 126 | + "Ada Lovelace" | ||
| 127 | + ); | ||
| 128 | + assert_eq!(parse_display_name("Ayşe Çelik").unwrap(), "Ayşe Çelik"); | ||
| 129 | + let hundred = "a".repeat(MAX_NAME_CHARS); | ||
| 130 | + assert!(parse_display_name(&hundred).is_ok()); | ||
| 131 | + for bad in [ | ||
| 132 | + "", | ||
| 133 | + " ", | ||
| 134 | + "a\u{0}b", | ||
| 135 | + "ada\nlovelace", | ||
| 136 | + "ada\tlovelace", | ||
| 137 | + "\u{7}bell", | ||
| 138 | + "evil\u{202E}name", | ||
| 139 | + "\u{202A}ltr", | ||
| 140 | + "isolate\u{2066}x", | ||
| 141 | + "\u{2069}", | ||
| 142 | + &"a".repeat(MAX_NAME_CHARS + 1), | ||
| 143 | + ] { | ||
| 144 | + assert!(parse_display_name(bad).is_err(), "accepted {bad:?}"); | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | + | ||
| 87 | #[test] | 148 | #[test] |
| 88 | fn attack_strings_are_refused() { | 149 | fn attack_strings_are_refused() { |
| 89 | let long_local = format!("{}@example.com", "a".repeat(MAX_LOCAL_LEN + 1)); | 150 | let long_local = format!("{}@example.com", "a".repeat(MAX_LOCAL_LEN + 1)); |
crates/im-core/src/photo.rsadded+226 -0
| @@ -0,0 +1,226 @@ | |||
| 1 | +//! Profile photos: the decoding of an upload, the picture that is stored, and the files they live in. | ||
| 2 | +//! | ||
| 3 | +//! An upload is never stored as it was sent. [`normalize_photo`] decodes it with a fixed list of | ||
| 4 | +//! formats and decoder limits, applies its EXIF orientation, crops the centre square, scales it to at | ||
| 5 | +//! most [`MAX_SIDE`] pixels a side, and encodes the pixels again as lossless WebP. Everything else | ||
| 6 | +//! the file carried (metadata, trailing bytes, a second format hidden inside a valid image) is gone. | ||
| 7 | +//! The file name and the browser's content type are never looked at: the bytes decide. | ||
| 8 | +//! | ||
| 9 | +//! Files live at `data_dir/photos/<user id>` with mode 0600. A write goes to a temporary file that | ||
| 10 | +//! is fsynced and then renamed over the old one, so a reader sees the old photo or the new one, | ||
| 11 | +//! never half of either. | ||
| 12 | + | ||
| 13 | +use std::fs::{self, DirBuilder, File, OpenOptions}; | ||
| 14 | +use std::io::{Cursor, Write}; | ||
| 15 | +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; | ||
| 16 | +use std::path::{Path, PathBuf}; | ||
| 17 | + | ||
| 18 | +use image::metadata::Orientation; | ||
| 19 | +use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits}; | ||
| 20 | + | ||
| 21 | +use crate::error::{Error, Result}; | ||
| 22 | + | ||
| 23 | +/// Largest upload accepted, in bytes. The web layer streams the request and stops at this limit. | ||
| 24 | +pub const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024; | ||
| 25 | + | ||
| 26 | +/// Longest side of the stored picture, in pixels. The picture is a square of this size at most. | ||
| 27 | +pub const MAX_SIDE: u32 = 512; | ||
| 28 | + | ||
| 29 | +/// Longest side an input may have, in pixels. Larger inputs are refused before any pixel is decoded. | ||
| 30 | +const MAX_INPUT_SIDE: u32 = 8000; | ||
| 31 | + | ||
| 32 | +/// Most memory the decoder may allocate for one input, in bytes (256 MiB). | ||
| 33 | +const MAX_DECODE_ALLOC: u64 = 256 * 1024 * 1024; | ||
| 34 | + | ||
| 35 | +/// MIME type of every stored photo. Lossless WebP keeps transparency and needs no quality choice. | ||
| 36 | +pub const STORED_MIME: &str = "image/webp"; | ||
| 37 | + | ||
| 38 | +/// Directory name inside `data_dir` that holds the photos. | ||
| 39 | +const PHOTO_DIR: &str = "photos"; | ||
| 40 | + | ||
| 41 | +/// The message for an input that is not one of the accepted images. | ||
| 42 | +fn refused() -> Error { | ||
| 43 | + Error::Invalid("the file is not a PNG, JPEG, WebP or GIF image".into()) | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +/// Turns an upload into the stored picture: a square WebP of at most [`MAX_SIDE`] pixels. | ||
| 47 | +/// | ||
| 48 | +/// Refuses anything whose bytes are not PNG, JPEG, WebP or GIF, whatever its name says, and any | ||
| 49 | +/// image that is larger than the input limits or cannot be decoded. Only the first frame of an | ||
| 50 | +/// animated GIF is kept. | ||
| 51 | +pub fn normalize_photo(input: &[u8]) -> Result<Vec<u8>> { | ||
| 52 | + let format = image::guess_format(input).map_err(|_| refused())?; | ||
| 53 | + let accepted = matches!( | ||
| 54 | + format, | ||
| 55 | + ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::WebP | ImageFormat::Gif | ||
| 56 | + ); | ||
| 57 | + if !accepted { | ||
| 58 | + return Err(refused()); | ||
| 59 | + } | ||
| 60 | + | ||
| 61 | + let mut limits = Limits::default(); | ||
| 62 | + limits.max_image_width = Some(MAX_INPUT_SIDE); | ||
| 63 | + limits.max_image_height = Some(MAX_INPUT_SIDE); | ||
| 64 | + limits.max_alloc = Some(MAX_DECODE_ALLOC); | ||
| 65 | + let mut reader = ImageReader::with_format(Cursor::new(input), format); | ||
| 66 | + reader.limits(limits); | ||
| 67 | + let mut decoder = reader.into_decoder().map_err(decode_error)?; | ||
| 68 | + // Phones store the rotation in EXIF and leave the pixels sideways; apply it before cropping. | ||
| 69 | + let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms); | ||
| 70 | + let mut image = DynamicImage::from_decoder(decoder).map_err(decode_error)?; | ||
| 71 | + image.apply_orientation(orientation); | ||
| 72 | + | ||
| 73 | + let (width, height) = (image.width(), image.height()); | ||
| 74 | + let side = width.min(height); | ||
| 75 | + if side == 0 { | ||
| 76 | + return Err(refused()); | ||
| 77 | + } | ||
| 78 | + let square = image.crop_imm((width - side) / 2, (height - side) / 2, side, side); | ||
| 79 | + let scaled = if side > MAX_SIDE { | ||
| 80 | + square.resize_exact(MAX_SIDE, MAX_SIDE, image::imageops::FilterType::Lanczos3) | ||
| 81 | + } else { | ||
| 82 | + square | ||
| 83 | + }; | ||
| 84 | + | ||
| 85 | + let mut out = Cursor::new(Vec::new()); | ||
| 86 | + DynamicImage::ImageRgba8(scaled.to_rgba8()) | ||
| 87 | + .write_to(&mut out, ImageFormat::WebP) | ||
| 88 | + .map_err(|_| refused())?; | ||
| 89 | + Ok(out.into_inner()) | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +/// Every decode failure is the uploader's problem: the bytes are not an image this build reads. | ||
| 93 | +fn decode_error(_: image::ImageError) -> Error { | ||
| 94 | + refused() | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +/// The file that holds the photo of `user_id`. The id must be a plain identifier, so no id can | ||
| 98 | +/// name a path outside the photo directory. | ||
| 99 | +pub fn photo_path(data_dir: &Path, user_id: &str) -> Result<PathBuf> { | ||
| 100 | + let plain = !user_id.is_empty() | ||
| 101 | + && user_id.len() <= 64 | ||
| 102 | + && user_id.bytes().all(|b| b.is_ascii_alphanumeric()); | ||
| 103 | + if !plain { | ||
| 104 | + return Err(Error::Invalid("photo id is not valid".into())); | ||
| 105 | + } | ||
| 106 | + Ok(data_dir.join(PHOTO_DIR).join(user_id)) | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +/// Replaces the stored photo of `user_id` with `bytes`, which must already be normalised. | ||
| 110 | +/// | ||
| 111 | +/// The bytes go to a temporary file in the same directory, which is fsynced and renamed over the | ||
| 112 | +/// old file. The directory is fsynced too, so the rename survives a crash. | ||
| 113 | +pub fn write_photo(data_dir: &Path, user_id: &str, bytes: &[u8]) -> Result<()> { | ||
| 114 | + let path = photo_path(data_dir, user_id)?; | ||
| 115 | + let dir = data_dir.join(PHOTO_DIR); | ||
| 116 | + DirBuilder::new().recursive(true).mode(0o700).create(&dir)?; | ||
| 117 | + let temp = dir.join(format!(".{user_id}.{}.tmp", ulid::Ulid::generate())); | ||
| 118 | + let written = (|| -> Result<()> { | ||
| 119 | + let mut file = OpenOptions::new() | ||
| 120 | + .write(true) | ||
| 121 | + .create_new(true) | ||
| 122 | + .mode(0o600) | ||
| 123 | + .open(&temp)?; | ||
| 124 | + file.write_all(bytes)?; | ||
| 125 | + file.sync_all()?; | ||
| 126 | + fs::rename(&temp, &path)?; | ||
| 127 | + File::open(&dir)?.sync_all()?; | ||
| 128 | + Ok(()) | ||
| 129 | + })(); | ||
| 130 | + if written.is_err() { | ||
| 131 | + // Best effort: a leftover temporary file is harmless and never served. | ||
| 132 | + let _ = fs::remove_file(&temp); | ||
| 133 | + } | ||
| 134 | + written | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +/// The stored photo of `user_id`, or `None` when there is none. | ||
| 138 | +pub fn read_photo(data_dir: &Path, user_id: &str) -> Result<Option<Vec<u8>>> { | ||
| 139 | + match fs::read(photo_path(data_dir, user_id)?) { | ||
| 140 | + Ok(bytes) => Ok(Some(bytes)), | ||
| 141 | + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), | ||
| 142 | + Err(e) => Err(e.into()), | ||
| 143 | + } | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +/// Deletes the stored photo of `user_id`. Nothing to delete is not an error. | ||
| 147 | +pub fn remove_photo(data_dir: &Path, user_id: &str) -> Result<()> { | ||
| 148 | + match fs::remove_file(photo_path(data_dir, user_id)?) { | ||
| 149 | + Ok(()) => Ok(()), | ||
| 150 | + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), | ||
| 151 | + Err(e) => Err(e.into()), | ||
| 152 | + } | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +#[cfg(test)] | ||
| 156 | +mod tests { | ||
| 157 | + use super::*; | ||
| 158 | + | ||
| 159 | + /// A PNG of the given size, made with the same crate that reads uploads. | ||
| 160 | + fn png(width: u32, height: u32) -> Vec<u8> { | ||
| 161 | + let mut out = Cursor::new(Vec::new()); | ||
| 162 | + DynamicImage::new_rgb8(width, height) | ||
| 163 | + .write_to(&mut out, ImageFormat::Png) | ||
| 164 | + .expect("encode test png"); | ||
| 165 | + out.into_inner() | ||
| 166 | + } | ||
| 167 | + | ||
| 168 | + #[test] | ||
| 169 | + fn a_picture_is_stored_as_a_centred_square_of_at_most_512_pixels() { | ||
| 170 | + let stored = normalize_photo(&png(1000, 600)).expect("normalised"); | ||
| 171 | + assert_eq!( | ||
| 172 | + image::guess_format(&stored).expect("format"), | ||
| 173 | + ImageFormat::WebP | ||
| 174 | + ); | ||
| 175 | + let decoded = | ||
| 176 | + image::load_from_memory_with_format(&stored, ImageFormat::WebP).expect("decodes"); | ||
| 177 | + assert_eq!((decoded.width(), decoded.height()), (512, 512)); | ||
| 178 | + | ||
| 179 | + let small = normalize_photo(&png(40, 30)).expect("normalised"); | ||
| 180 | + let decoded = | ||
| 181 | + image::load_from_memory_with_format(&small, ImageFormat::WebP).expect("decodes"); | ||
| 182 | + assert_eq!((decoded.width(), decoded.height()), (30, 30)); | ||
| 183 | + } | ||
| 184 | + | ||
| 185 | + #[test] | ||
| 186 | + fn an_html_file_renamed_to_png_is_refused() { | ||
| 187 | + let html = b"<!DOCTYPE html><html><body><script>alert(1)</script></body></html>"; | ||
| 188 | + assert!(normalize_photo(html).is_err()); | ||
| 189 | + let mut polyglot = png(16, 16); | ||
| 190 | + polyglot.extend_from_slice(b"<script>alert(1)</script>"); | ||
| 191 | + // The trailing bytes are dropped by the re-encode, so the stored file has no script. | ||
| 192 | + let stored = normalize_photo(&polyglot).expect("normalised"); | ||
| 193 | + assert!(!stored.windows(8).any(|w| w == b"<script>")); | ||
| 194 | + } | ||
| 195 | + | ||
| 196 | + #[test] | ||
| 197 | + fn a_stored_photo_round_trips_and_is_removed() { | ||
| 198 | + let dir = tempfile::tempdir().expect("temp dir"); | ||
| 199 | + let id = "01HZ0000000000000000000000"; | ||
| 200 | + assert_eq!(read_photo(dir.path(), id).expect("read"), None); | ||
| 201 | + write_photo(dir.path(), id, b"first").expect("write"); | ||
| 202 | + write_photo(dir.path(), id, b"second").expect("replace"); | ||
| 203 | + assert_eq!( | ||
| 204 | + read_photo(dir.path(), id).expect("read").as_deref(), | ||
| 205 | + Some(&b"second"[..]) | ||
| 206 | + ); | ||
| 207 | + let mode = fs::metadata(photo_path(dir.path(), id).expect("path")) | ||
| 208 | + .expect("meta") | ||
| 209 | + .permissions(); | ||
| 210 | + assert_eq!( | ||
| 211 | + std::os::unix::fs::PermissionsExt::mode(&mode) & 0o777, | ||
| 212 | + 0o600 | ||
| 213 | + ); | ||
| 214 | + remove_photo(dir.path(), id).expect("remove"); | ||
| 215 | + remove_photo(dir.path(), id).expect("removing twice is fine"); | ||
| 216 | + assert_eq!(read_photo(dir.path(), id).expect("read"), None); | ||
| 217 | + } | ||
| 218 | + | ||
| 219 | + #[test] | ||
| 220 | + fn a_user_id_cannot_name_another_path() { | ||
| 221 | + let dir = Path::new("/data"); | ||
| 222 | + assert!(photo_path(dir, "../../etc/passwd").is_err()); | ||
| 223 | + assert!(photo_path(dir, "").is_err()); | ||
| 224 | + assert!(photo_path(dir, "01HZ0000000000000000000000").is_ok()); | ||
| 225 | + } | ||
| 226 | +} | ||
crates/im-core/src/store/directory.rsadded+42 -0
| @@ -0,0 +1,42 @@ | |||
| 1 | +//! The change feed of the people directory: one row per change a machine client may need to see. | ||
| 2 | +//! | ||
| 3 | +//! The rows are written in the same transaction as the change they describe, so a change is | ||
| 4 | +//! never visible without its row, and a row never describes a change that did not happen. Rows are | ||
| 5 | +//! read by the directory stream (contracts.md 3.2), which is built in a later step; until then they | ||
| 6 | +//! only accumulate. The sweeper prunes rows older than 30 days. | ||
| 7 | + | ||
| 8 | +use turso::Connection; | ||
| 9 | + | ||
| 10 | +use crate::error::Result; | ||
| 11 | +use crate::store::db_err; | ||
| 12 | +use crate::time::now_stamp; | ||
| 13 | + | ||
| 14 | +/// What a directory row says happened to a person. | ||
| 15 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 16 | +pub enum ChangeKind { | ||
| 17 | + /// The person's directory entry changed (name, email, photo, status). | ||
| 18 | + Member, | ||
| 19 | + /// The person is gone from the directory. | ||
| 20 | + Deleted, | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +impl ChangeKind { | ||
| 24 | + /// The stored text of the kind. The schema CHECK accepts exactly these two values. | ||
| 25 | + pub fn as_str(self) -> &'static str { | ||
| 26 | + match self { | ||
| 27 | + ChangeKind::Member => "member", | ||
| 28 | + ChangeKind::Deleted => "deleted", | ||
| 29 | + } | ||
| 30 | + } | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +/// Appends one change row. Runs inside the caller's transaction, so it commits with the change. | ||
| 34 | +pub(crate) async fn record_change(conn: &Connection, sub: &str, kind: ChangeKind) -> Result<()> { | ||
| 35 | + conn.execute( | ||
| 36 | + "INSERT INTO directory_changes (sub, kind, at) VALUES (?1, ?2, ?3)", | ||
| 37 | + (sub.to_string(), kind.as_str().to_string(), now_stamp()), | ||
| 38 | + ) | ||
| 39 | + .await | ||
| 40 | + .map_err(db_err)?; | ||
| 41 | + Ok(()) | ||
| 42 | +} | ||
crates/im-core/src/store/migrate.rsmodified+7 -1
| @@ -10,7 +10,13 @@ use crate::error::{Error, Result}; | |||
| 10 | use crate::time::now_stamp; | 10 | use crate::time::now_stamp; |
| 11 | 11 | ||
| 12 | /// `(version, sql)` in ascending order, with no gaps. Add each new file here. | 12 | /// `(version, sql)` in ascending order, with no gaps. Add each new file here. |
| 13 | -pub const MIGRATIONS: &[(u32, &str)] = &[(1, include_str!("../../migrations/0001_init.sql"))]; | 13 | +pub const MIGRATIONS: &[(u32, &str)] = &[ |
| 14 | + (1, include_str!("../../migrations/0001_init.sql")), | ||
| 15 | + ( | ||
| 16 | + 2, | ||
| 17 | + include_str!("../../migrations/0002_sessions_cap_and_language.sql"), | ||
| 18 | + ), | ||
| 19 | +]; | ||
| 14 | 20 | ||
| 15 | fn migration_err(e: turso::Error) -> Error { | 21 | fn migration_err(e: turso::Error) -> Error { |
| 16 | Error::Migration(e.to_string()) | 22 | Error::Migration(e.to_string()) |
crates/im-core/src/store/mod.rsmodified+2 -1
| @@ -7,6 +7,7 @@ | |||
| 7 | //! in effect are logged at boot. | 7 | //! in effect are logged at boot. |
| 8 | 8 | ||
| 9 | pub mod audit; | 9 | pub mod audit; |
| 10 | +pub mod directory; | ||
| 10 | pub mod migrate; | 11 | pub mod migrate; |
| 11 | pub mod sessions; | 12 | pub mod sessions; |
| 12 | pub mod snapshot; | 13 | pub mod snapshot; |
| @@ -322,6 +323,6 @@ mod tests { | |||
| 322 | }) | 323 | }) |
| 323 | .await | 324 | .await |
| 324 | .unwrap(); | 325 | .unwrap(); |
| 325 | - assert_eq!(applied, vec![1]); | 326 | + assert_eq!(applied, vec![1, 2]); |
| 326 | } | 327 | } |
| 327 | } | 328 | } |
crates/im-core/src/store/sessions.rsmodified+112 -17
| @@ -4,6 +4,10 @@ | |||
| 4 | //! A session row is the sign-in. Its cookie carries a random token; the row holds only the SHA-256 | 4 | //! A session row is the sign-in. Its cookie carries a random token; the row holds only the SHA-256 |
| 5 | //! of it. Ended sessions are deleted, and their ids are returned to the caller, so that later | 5 | //! of it. Ended sessions are deleted, and their ids are returned to the caller, so that later |
| 6 | //! back-channel logout jobs can be queued for them before the rows are gone. | 6 | //! back-channel logout jobs can be queued for them before the rows are gone. |
| 7 | +//! | ||
| 8 | +//! Lifetime: a session expires [`SESSION_IDLE`] after it was last used, and never later than its | ||
| 9 | +//! hard cap (`hard_expires_at`, the creation time plus the policy's `session_max_days`). `expires_at` | ||
| 10 | +//! is always the earlier of the two. Only [`Store::touch_session`] moves it forward. | ||
| 7 | 11 | ||
| 8 | use std::time::Duration; | 12 | use std::time::Duration; |
| 9 | 13 | ||
| @@ -14,13 +18,17 @@ use crate::model::Session; | |||
| 14 | use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; | 18 | use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; |
| 15 | use crate::time::{now_stamp, stamp_after, stamp_before}; | 19 | use crate::time::{now_stamp, stamp_after, stamp_before}; |
| 16 | 20 | ||
| 17 | -/// The least time between two writes of `last_seen_at` for one session, in seconds. Every request | 21 | +/// The least time between two writes of `last_seen_at` for one session. Every request reads the |
| 18 | -/// reads the session; only one of them in this window writes it. | 22 | +/// session; only one of them in this window writes it, and the idle expiry moves with that write. |
| 19 | const TOUCH_INTERVAL: Duration = Duration::from_secs(5 * 60); | 23 | const TOUCH_INTERVAL: Duration = Duration::from_secs(5 * 60); |
| 20 | 24 | ||
| 25 | +/// How long a session survives without use. Each use (at most one write per [`TOUCH_INTERVAL`]) | ||
| 26 | +/// extends it to this long from that use. Unit: seconds, fixed at 30 days (architecture section 5). | ||
| 27 | +pub const SESSION_IDLE: Duration = Duration::from_secs(30 * 24 * 60 * 60); | ||
| 28 | + | ||
| 21 | /// The columns of a session row, in the order [`map_session`] reads them. | 29 | /// The columns of a session row, in the order [`map_session`] reads them. |
| 22 | const SESSION_COLS: &str = "id, user_id, token_hash, csrf_token, created_at, expires_at, \ | 30 | const SESSION_COLS: &str = "id, user_id, token_hash, csrf_token, created_at, expires_at, \ |
| 23 | - last_seen_at, ip, user_agent, auth_time, amr"; | 31 | + last_seen_at, ip, user_agent, auth_time, amr, hard_expires_at"; |
| 24 | 32 | ||
| 25 | /// Maps a row selected with [`SESSION_COLS`]. | 33 | /// Maps a row selected with [`SESSION_COLS`]. |
| 26 | fn map_session(row: &turso::Row) -> Result<Session> { | 34 | fn map_session(row: &turso::Row) -> Result<Session> { |
| @@ -36,6 +44,7 @@ fn map_session(row: &turso::Row) -> Result<Session> { | |||
| 36 | user_agent: col_opt_text(row, 8)?, | 44 | user_agent: col_opt_text(row, 8)?, |
| 37 | auth_time: col_text(row, 9)?, | 45 | auth_time: col_text(row, 9)?, |
| 38 | amr: col_text(row, 10)?, | 46 | amr: col_text(row, 10)?, |
| 47 | + hard_expires_at: col_text(row, 11)?, | ||
| 39 | }) | 48 | }) |
| 40 | } | 49 | } |
| 41 | 50 | ||
| @@ -55,8 +64,10 @@ pub struct NewSession<'a> { | |||
| 55 | pub ip: Option<&'a str>, | 64 | pub ip: Option<&'a str>, |
| 56 | /// User agent at sign-in, already truncated by the caller. | 65 | /// User agent at sign-in, already truncated by the caller. |
| 57 | pub user_agent: Option<&'a str>, | 66 | pub user_agent: Option<&'a str>, |
| 58 | - /// How long the session lives from now. | 67 | + /// How long the session survives without use, from now. Normally [`SESSION_IDLE`]. |
| 59 | - pub ttl: Duration, | 68 | + pub idle: Duration, |
| 69 | + /// The hard cap: how long the session may live from now at most, however often it is used. | ||
| 70 | + pub max_age: Duration, | ||
| 60 | } | 71 | } |
| 61 | 72 | ||
| 62 | /// The result of creating a session: the new row, and the ids of the sessions that were ended to | 73 | /// The result of creating a session: the new row, and the ids of the sessions that were ended to |
| @@ -82,7 +93,11 @@ async fn end_sessions( | |||
| 82 | conn, | 93 | conn, |
| 83 | "SELECT id FROM sessions WHERE user_id = ?1 AND expires_at > ?2 AND id IS NOT ?3 \ | 94 | "SELECT id FROM sessions WHERE user_id = ?1 AND expires_at > ?2 AND id IS NOT ?3 \ |
| 84 | ORDER BY created_at ASC, id ASC", | 95 | ORDER BY created_at ASC, id ASC", |
| 85 | - (user_id.to_string(), now.to_string(), keep.map(str::to_owned)), | 96 | + ( |
| 97 | + user_id.to_string(), | ||
| 98 | + now.to_string(), | ||
| 99 | + keep.map(str::to_owned), | ||
| 100 | + ), | ||
| 86 | |row| col_text(row, 0), | 101 | |row| col_text(row, 0), |
| 87 | ) | 102 | ) |
| 88 | .await?; | 103 | .await?; |
| @@ -106,7 +121,15 @@ impl Store { | |||
| 106 | max_sessions: u32, | 121 | max_sessions: u32, |
| 107 | ) -> Result<CreatedSession> { | 122 | ) -> Result<CreatedSession> { |
| 108 | let now = now_stamp(); | 123 | let now = now_stamp(); |
| 109 | - let expires_at = stamp_after(new.ttl); | 124 | + let hard_expires_at = stamp_after(new.max_age); |
| 125 | + let idle_expires_at = stamp_after(new.idle); | ||
| 126 | + // Compared as text, which is the same order as time. Two separate clock reads, so the | ||
| 127 | + // comparison (not the duration) decides which one is earlier. | ||
| 128 | + let expires_at = if idle_expires_at < hard_expires_at { | ||
| 129 | + idle_expires_at | ||
| 130 | + } else { | ||
| 131 | + hard_expires_at.clone() | ||
| 132 | + }; | ||
| 110 | let cap = usize::try_from(max_sessions.max(1)).unwrap_or(usize::MAX); | 133 | let cap = usize::try_from(max_sessions.max(1)).unwrap_or(usize::MAX); |
| 111 | let session = Session { | 134 | let session = Session { |
| 112 | id: new_id(), | 135 | id: new_id(), |
| @@ -120,6 +143,7 @@ impl Store { | |||
| 120 | user_agent: new.user_agent.map(str::to_owned), | 143 | user_agent: new.user_agent.map(str::to_owned), |
| 121 | auth_time: now.clone(), | 144 | auth_time: now.clone(), |
| 122 | amr: new.amr.to_owned(), | 145 | amr: new.amr.to_owned(), |
| 146 | + hard_expires_at, | ||
| 123 | }; | 147 | }; |
| 124 | 148 | ||
| 125 | let conn = self.inner.conn.lock().await; | 149 | let conn = self.inner.conn.lock().await; |
| @@ -144,8 +168,8 @@ impl Store { | |||
| 144 | } | 168 | } |
| 145 | tx.execute( | 169 | tx.execute( |
| 146 | "INSERT INTO sessions (id, user_id, token_hash, csrf_token, created_at, expires_at, \ | 170 | "INSERT INTO sessions (id, user_id, token_hash, csrf_token, created_at, expires_at, \ |
| 147 | - last_seen_at, ip, user_agent, auth_time, amr) \ | 171 | + last_seen_at, ip, user_agent, auth_time, amr, hard_expires_at) \ |
| 148 | - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", | 172 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)", |
| 149 | ( | 173 | ( |
| 150 | session.id.clone(), | 174 | session.id.clone(), |
| 151 | session.user_id.clone(), | 175 | session.user_id.clone(), |
| @@ -158,6 +182,7 @@ impl Store { | |||
| 158 | session.user_agent.clone(), | 182 | session.user_agent.clone(), |
| 159 | session.auth_time.clone(), | 183 | session.auth_time.clone(), |
| 160 | session.amr.clone(), | 184 | session.amr.clone(), |
| 185 | + session.hard_expires_at.clone(), | ||
| 161 | ), | 186 | ), |
| 162 | ) | 187 | ) |
| 163 | .await | 188 | .await |
| @@ -204,17 +229,23 @@ impl Store { | |||
| 204 | Ok(found.is_some()) | 229 | Ok(found.is_some()) |
| 205 | } | 230 | } |
| 206 | 231 | ||
| 207 | - /// Records that the session was used. Writes `last_seen_at` only when the stored value is more | 232 | + /// Records that the session was used and extends its idle expiry: `expires_at` becomes |
| 208 | - /// than five minutes old, so a busy page does not write on every request. Returns whether it | 233 | + /// [`SESSION_IDLE`] from now, but never later than the row's hard cap. Writes only when the stored |
| 209 | - /// wrote. | 234 | + /// `last_seen_at` is more than five minutes old, so a busy page does not write on every request. |
| 235 | + /// Returns whether it wrote. | ||
| 210 | pub async fn touch_session(&self, session_id: &str) -> Result<bool> { | 236 | pub async fn touch_session(&self, session_id: &str) -> Result<bool> { |
| 237 | + let now = now_stamp(); | ||
| 238 | + let idle_until = stamp_after(SESSION_IDLE); | ||
| 211 | let conn = self.inner.conn.lock().await; | 239 | let conn = self.inner.conn.lock().await; |
| 212 | let changed = conn | 240 | let changed = conn |
| 213 | .execute( | 241 | .execute( |
| 214 | - "UPDATE sessions SET last_seen_at = ?2 WHERE id = ?1 AND last_seen_at < ?3", | 242 | + "UPDATE sessions SET last_seen_at = ?2, \ |
| 243 | + expires_at = CASE WHEN ?3 < hard_expires_at THEN ?3 ELSE hard_expires_at END \ | ||
| 244 | + WHERE id = ?1 AND last_seen_at < ?4", | ||
| 215 | ( | 245 | ( |
| 216 | session_id.to_string(), | 246 | session_id.to_string(), |
| 217 | - now_stamp(), | 247 | + now, |
| 248 | + idle_until, | ||
| 218 | stamp_before(TOUCH_INTERVAL), | 249 | stamp_before(TOUCH_INTERVAL), |
| 219 | ), | 250 | ), |
| 220 | ) | 251 | ) |
| @@ -310,7 +341,8 @@ mod tests { | |||
| 310 | amr: "pwd", | 341 | amr: "pwd", |
| 311 | ip: None, | 342 | ip: None, |
| 312 | user_agent: None, | 343 | user_agent: None, |
| 313 | - ttl: Duration::from_secs(3600), | 344 | + idle: SESSION_IDLE, |
| 345 | + max_age: Duration::from_secs(3600), | ||
| 314 | }, | 346 | }, |
| 315 | 2, | 347 | 2, |
| 316 | ) | 348 | ) |
| @@ -325,7 +357,70 @@ mod tests { | |||
| 325 | } | 357 | } |
| 326 | let live = store.list_sessions(&user.id).await.unwrap(); | 358 | let live = store.list_sessions(&user.id).await.unwrap(); |
| 327 | assert_eq!(live.len(), 2); | 359 | assert_eq!(live.len(), 2); |
| 328 | - assert!(store.session_by_token_hash("hash-0").await.unwrap().is_none()); | 360 | + assert!( |
| 329 | - assert!(store.session_by_token_hash("hash-2").await.unwrap().is_some()); | 361 | + store |
| 362 | + .session_by_token_hash("hash-0") | ||
| 363 | + .await | ||
| 364 | + .unwrap() | ||
| 365 | + .is_none() | ||
| 366 | + ); | ||
| 367 | + assert!( | ||
| 368 | + store | ||
| 369 | + .session_by_token_hash("hash-2") | ||
| 370 | + .await | ||
| 371 | + .unwrap() | ||
| 372 | + .is_some() | ||
| 373 | + ); | ||
| 374 | + } | ||
| 375 | + | ||
| 376 | + #[tokio::test] | ||
| 377 | + async fn idle_extension_never_passes_the_hard_cap() { | ||
| 378 | + let dir = tempfile::tempdir().unwrap(); | ||
| 379 | + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); | ||
| 380 | + let user = store | ||
| 381 | + .create_user("ada@example.com", "Ada", "hash", false) | ||
| 382 | + .await | ||
| 383 | + .unwrap(); | ||
| 384 | + // A two-hour cap, far shorter than the idle window: the session must never live longer. | ||
| 385 | + let created = store | ||
| 386 | + .create_session( | ||
| 387 | + &NewSession { | ||
| 388 | + user_id: &user.id, | ||
| 389 | + token_hash: "capped", | ||
| 390 | + csrf_token: "csrf", | ||
| 391 | + amr: "pwd", | ||
| 392 | + ip: None, | ||
| 393 | + user_agent: None, | ||
| 394 | + idle: SESSION_IDLE, | ||
| 395 | + max_age: Duration::from_secs(2 * 3600), | ||
| 396 | + }, | ||
| 397 | + 10, | ||
| 398 | + ) | ||
| 399 | + .await | ||
| 400 | + .unwrap(); | ||
| 401 | + let cap = created.session.hard_expires_at.clone(); | ||
| 402 | + assert!(created.session.expires_at <= cap); | ||
| 403 | + | ||
| 404 | + // Pretend the last use was long ago, then use it again: the expiry moves, but not past the cap. | ||
| 405 | + let conn = store.inner.conn.lock().await; | ||
| 406 | + conn.execute( | ||
| 407 | + "UPDATE sessions SET last_seen_at = ?2, expires_at = ?3 WHERE id = ?1", | ||
| 408 | + ( | ||
| 409 | + created.session.id.clone(), | ||
| 410 | + stamp_before(Duration::from_secs(3600)), | ||
| 411 | + stamp_after(Duration::from_secs(60)), | ||
| 412 | + ), | ||
| 413 | + ) | ||
| 414 | + .await | ||
| 415 | + .unwrap(); | ||
| 416 | + drop(conn); | ||
| 417 | + assert!(store.touch_session(&created.session.id).await.unwrap()); | ||
| 418 | + let live = store | ||
| 419 | + .session_by_token_hash("capped") | ||
| 420 | + .await | ||
| 421 | + .unwrap() | ||
| 422 | + .expect("live"); | ||
| 423 | + assert_eq!(live.expires_at, cap, "idle extension passed the hard cap"); | ||
| 424 | + assert_eq!(live.hard_expires_at, cap); | ||
| 330 | } | 425 | } |
| 331 | } | 426 | } |
crates/im-core/src/store/users.rsmodified+134 -40
| @@ -16,13 +16,16 @@ use turso::{Connection, Row}; | |||
| 16 | 16 | ||
| 17 | use crate::error::{Error, Result}; | 17 | use crate::error::{Error, Result}; |
| 18 | use crate::model::User; | 18 | use crate::model::User; |
| 19 | -use crate::store::{Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id}; | 19 | +use crate::store::directory::{ChangeKind, record_change}; |
| 20 | +use crate::store::{ | ||
| 21 | + Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id, | ||
| 22 | +}; | ||
| 20 | use crate::time::now_stamp; | 23 | use crate::time::now_stamp; |
| 21 | 24 | ||
| 22 | /// The columns of a user row, in the order [`map_user`] reads them. | 25 | /// The columns of a user row, in the order [`map_user`] reads them. |
| 23 | const USER_COLS: &str = "id, email, name, password_hash, is_admin, disabled_at, \ | 26 | const USER_COLS: &str = "id, email, name, password_hash, is_admin, disabled_at, \ |
| 24 | totp_secret_sealed, totp_enabled_at, totp_last_step, locale, zoneinfo, theme, \ | 27 | totp_secret_sealed, totp_enabled_at, totp_last_step, locale, zoneinfo, theme, \ |
| 25 | - photo_mime, picture_version, created_at, updated_at"; | 28 | + photo_mime, picture_version, created_at, updated_at, locale_auto"; |
| 26 | 29 | ||
| 27 | /// Maps a row selected with [`USER_COLS`]. | 30 | /// Maps a row selected with [`USER_COLS`]. |
| 28 | fn map_user(row: &Row) -> Result<User> { | 31 | fn map_user(row: &Row) -> Result<User> { |
| @@ -43,6 +46,7 @@ fn map_user(row: &Row) -> Result<User> { | |||
| 43 | picture_version: col_int(row, 13)?, | 46 | picture_version: col_int(row, 13)?, |
| 44 | created_at: col_text(row, 14)?, | 47 | created_at: col_text(row, 14)?, |
| 45 | updated_at: col_text(row, 15)?, | 48 | updated_at: col_text(row, 15)?, |
| 49 | + locale_auto: col_int(row, 16)? != 0, | ||
| 46 | }) | 50 | }) |
| 47 | } | 51 | } |
| 48 | 52 | ||
| @@ -172,38 +176,48 @@ impl Store { | |||
| 172 | .await | 176 | .await |
| 173 | } | 177 | } |
| 174 | 178 | ||
| 175 | - /// Changes the display name. The schema keeps it at 1 to 100 characters. | 179 | + /// Changes the display name, and writes its directory row, in one transaction. The caller has |
| 180 | + /// checked the name with `names::parse_display_name`; the schema keeps it at 1 to 100 characters. | ||
| 176 | pub async fn update_name(&self, id: &str, name: &str) -> Result<()> { | 181 | pub async fn update_name(&self, id: &str, name: &str) -> Result<()> { |
| 177 | let conn = self.inner.conn.lock().await; | 182 | let conn = self.inner.conn.lock().await; |
| 178 | - let changed = conn | 183 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 179 | - .execute( | 184 | + let outcome: Result<()> = async { |
| 180 | - "UPDATE users SET name = ?2, updated_at = ?3 WHERE id = ?1", | 185 | + let changed = tx |
| 181 | - (id.to_string(), name.to_string(), now_stamp()), | 186 | + .execute( |
| 182 | - ) | 187 | + "UPDATE users SET name = ?2, updated_at = ?3 WHERE id = ?1", |
| 183 | - .await | 188 | + (id.to_string(), name.to_string(), now_stamp()), |
| 184 | - .map_err(db_err)?; | 189 | + ) |
| 185 | - if changed == 0 { | 190 | + .await |
| 186 | - return Err(Error::NotFound); | 191 | + .map_err(db_err)?; |
| 192 | + if changed == 0 { | ||
| 193 | + return Err(Error::NotFound); | ||
| 194 | + } | ||
| 195 | + record_change(&tx, id, ChangeKind::Member).await | ||
| 187 | } | 196 | } |
| 188 | - Ok(()) | 197 | + .await; |
| 198 | + finish(tx, outcome).await | ||
| 189 | } | 199 | } |
| 190 | 200 | ||
| 191 | - /// Changes the language, time zone and theme. The schema rejects unknown languages and themes. | 201 | + /// Changes the language, time zone and theme. `locale_auto` true means the language follows the |
| 202 | + /// browser and `locale` is kept only for when it is turned off again. The schema rejects unknown | ||
| 203 | + /// languages and themes. | ||
| 192 | pub async fn update_preferences( | 204 | pub async fn update_preferences( |
| 193 | &self, | 205 | &self, |
| 194 | id: &str, | 206 | id: &str, |
| 195 | locale: &str, | 207 | locale: &str, |
| 208 | + locale_auto: bool, | ||
| 196 | zoneinfo: &str, | 209 | zoneinfo: &str, |
| 197 | theme: &str, | 210 | theme: &str, |
| 198 | ) -> Result<()> { | 211 | ) -> Result<()> { |
| 199 | let conn = self.inner.conn.lock().await; | 212 | let conn = self.inner.conn.lock().await; |
| 200 | let changed = conn | 213 | let changed = conn |
| 201 | .execute( | 214 | .execute( |
| 202 | - "UPDATE users SET locale = ?2, zoneinfo = ?3, theme = ?4, updated_at = ?5 \ | 215 | + "UPDATE users SET locale = ?2, locale_auto = ?3, zoneinfo = ?4, theme = ?5, \ |
| 203 | - WHERE id = ?1", | 216 | + updated_at = ?6 WHERE id = ?1", |
| 204 | ( | 217 | ( |
| 205 | id.to_string(), | 218 | id.to_string(), |
| 206 | locale.to_string(), | 219 | locale.to_string(), |
| 220 | + i64::from(locale_auto), | ||
| 207 | zoneinfo.to_string(), | 221 | zoneinfo.to_string(), |
| 208 | theme.to_string(), | 222 | theme.to_string(), |
| 209 | now_stamp(), | 223 | now_stamp(), |
| @@ -217,6 +231,54 @@ impl Store { | |||
| 217 | Ok(()) | 231 | Ok(()) |
| 218 | } | 232 | } |
| 219 | 233 | ||
| 234 | + /// Records that a photo was stored: sets its MIME type, bumps `picture_version` so caches see a | ||
| 235 | + /// new picture, and writes the directory row. One transaction. The file itself is written by the | ||
| 236 | + /// caller with [`crate::photo::write_photo`], before this call. | ||
| 237 | + pub async fn set_photo(&self, id: &str, mime: &str) -> Result<()> { | ||
| 238 | + let conn = self.inner.conn.lock().await; | ||
| 239 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 240 | + let outcome: Result<()> = async { | ||
| 241 | + let changed = tx | ||
| 242 | + .execute( | ||
| 243 | + "UPDATE users SET photo_mime = ?2, picture_version = picture_version + 1, \ | ||
| 244 | + updated_at = ?3 WHERE id = ?1", | ||
| 245 | + (id.to_string(), mime.to_string(), now_stamp()), | ||
| 246 | + ) | ||
| 247 | + .await | ||
| 248 | + .map_err(db_err)?; | ||
| 249 | + if changed == 0 { | ||
| 250 | + return Err(Error::NotFound); | ||
| 251 | + } | ||
| 252 | + record_change(&tx, id, ChangeKind::Member).await | ||
| 253 | + } | ||
| 254 | + .await; | ||
| 255 | + finish(tx, outcome).await | ||
| 256 | + } | ||
| 257 | + | ||
| 258 | + /// Records that the photo was removed. Returns false, and writes nothing, when there was no | ||
| 259 | + /// photo. Otherwise it clears the MIME type, bumps `picture_version` and writes the directory row. | ||
| 260 | + pub async fn clear_photo(&self, id: &str) -> Result<bool> { | ||
| 261 | + let conn = self.inner.conn.lock().await; | ||
| 262 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 263 | + let outcome: Result<bool> = async { | ||
| 264 | + let changed = tx | ||
| 265 | + .execute( | ||
| 266 | + "UPDATE users SET photo_mime = NULL, picture_version = picture_version + 1, \ | ||
| 267 | + updated_at = ?2 WHERE id = ?1 AND photo_mime IS NOT NULL", | ||
| 268 | + (id.to_string(), now_stamp()), | ||
| 269 | + ) | ||
| 270 | + .await | ||
| 271 | + .map_err(db_err)?; | ||
| 272 | + if changed == 0 { | ||
| 273 | + return Ok(false); | ||
| 274 | + } | ||
| 275 | + record_change(&tx, id, ChangeKind::Member).await?; | ||
| 276 | + Ok(true) | ||
| 277 | + } | ||
| 278 | + .await; | ||
| 279 | + finish(tx, outcome).await | ||
| 280 | + } | ||
| 281 | + | ||
| 220 | /// Stores a new argon2id hash. The caller has checked the policy and the current password. | 282 | /// Stores a new argon2id hash. The caller has checked the policy and the current password. |
| 221 | pub async fn set_password_hash(&self, id: &str, password_hash: &str) -> Result<()> { | 283 | pub async fn set_password_hash(&self, id: &str, password_hash: &str) -> Result<()> { |
| 222 | let conn = self.inner.conn.lock().await; | 284 | let conn = self.inner.conn.lock().await; |
| @@ -254,7 +316,8 @@ impl Store { | |||
| 254 | step: u64, | 316 | step: u64, |
| 255 | recovery_hashes: &[String], | 317 | recovery_hashes: &[String], |
| 256 | ) -> Result<()> { | 318 | ) -> Result<()> { |
| 257 | - let step = i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; | 319 | + let step = |
| 320 | + i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; | ||
| 258 | let now = now_stamp(); | 321 | let now = now_stamp(); |
| 259 | let conn = self.inner.conn.lock().await; | 322 | let conn = self.inner.conn.lock().await; |
| 260 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 323 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| @@ -263,12 +326,7 @@ impl Store { | |||
| 263 | .execute( | 326 | .execute( |
| 264 | "UPDATE users SET totp_secret_sealed = ?2, totp_enabled_at = ?3, \ | 327 | "UPDATE users SET totp_secret_sealed = ?2, totp_enabled_at = ?3, \ |
| 265 | totp_last_step = ?4, updated_at = ?3 WHERE id = ?1", | 328 | totp_last_step = ?4, updated_at = ?3 WHERE id = ?1", |
| 266 | - ( | 329 | + (user_id.to_string(), sealed_secret.to_string(), now, step), |
| 267 | - user_id.to_string(), | ||
| 268 | - sealed_secret.to_string(), | ||
| 269 | - now, | ||
| 270 | - step, | ||
| 271 | - ), | ||
| 272 | ) | 330 | ) |
| 273 | .await | 331 | .await |
| 274 | .map_err(db_err)?; | 332 | .map_err(db_err)?; |
| @@ -276,9 +334,12 @@ impl Store { | |||
| 276 | return Err(Error::NotFound); | 334 | return Err(Error::NotFound); |
| 277 | } | 335 | } |
| 278 | replace_codes(&tx, user_id, recovery_hashes).await?; | 336 | replace_codes(&tx, user_id, recovery_hashes).await?; |
| 279 | - tx.execute("DELETE FROM settings WHERE key = ?1", (pending_key(user_id),)) | 337 | + tx.execute( |
| 280 | - .await | 338 | + "DELETE FROM settings WHERE key = ?1", |
| 281 | - .map_err(db_err)?; | 339 | + (pending_key(user_id),), |
| 340 | + ) | ||
| 341 | + .await | ||
| 342 | + .map_err(db_err)?; | ||
| 282 | Ok(()) | 343 | Ok(()) |
| 283 | } | 344 | } |
| 284 | .await; | 345 | .await; |
| @@ -308,9 +369,12 @@ impl Store { | |||
| 308 | ) | 369 | ) |
| 309 | .await | 370 | .await |
| 310 | .map_err(db_err)?; | 371 | .map_err(db_err)?; |
| 311 | - tx.execute("DELETE FROM settings WHERE key = ?1", (pending_key(user_id),)) | 372 | + tx.execute( |
| 312 | - .await | 373 | + "DELETE FROM settings WHERE key = ?1", |
| 313 | - .map_err(db_err)?; | 374 | + (pending_key(user_id),), |
| 375 | + ) | ||
| 376 | + .await | ||
| 377 | + .map_err(db_err)?; | ||
| 314 | Ok(()) | 378 | Ok(()) |
| 315 | } | 379 | } |
| 316 | .await; | 380 | .await; |
| @@ -321,7 +385,8 @@ impl Store { | |||
| 321 | /// forward. A step that is not later than the recorded one, or any step while two-factor is off, | 385 | /// forward. A step that is not later than the recorded one, or any step while two-factor is off, |
| 322 | /// returns false. This is the replay guard: a code is spent by this single statement. | 386 | /// returns false. This is the replay guard: a code is spent by this single statement. |
| 323 | pub async fn accept_totp_step(&self, user_id: &str, step: u64) -> Result<bool> { | 387 | pub async fn accept_totp_step(&self, user_id: &str, step: u64) -> Result<bool> { |
| 324 | - let step = i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; | 388 | + let step = |
| 389 | + i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; | ||
| 325 | let conn = self.inner.conn.lock().await; | 390 | let conn = self.inner.conn.lock().await; |
| 326 | let changed = conn | 391 | let changed = conn |
| 327 | .execute( | 392 | .execute( |
| @@ -435,19 +500,36 @@ mod tests { | |||
| 435 | .create_user("ada@example.com", "Ada", "hash", false) | 500 | .create_user("ada@example.com", "Ada", "hash", false) |
| 436 | .await | 501 | .await |
| 437 | .unwrap(); | 502 | .unwrap(); |
| 503 | + store.set_totp_pending(&user.id, "v1:sealed").await.unwrap(); | ||
| 438 | store | 504 | store |
| 439 | - .set_totp_pending(&user.id, "v1:sealed") | 505 | + .enable_totp( |
| 440 | - .await | 506 | + &user.id, |
| 441 | - .unwrap(); | 507 | + "v1:sealed", |
| 442 | - store | 508 | + 5, |
| 443 | - .enable_totp(&user.id, "v1:sealed", 5, &["code-a".to_string(), "code-b".to_string()]) | 509 | + &["code-a".to_string(), "code-b".to_string()], |
| 510 | + ) | ||
| 444 | .await | 511 | .await |
| 445 | .unwrap(); | 512 | .unwrap(); |
| 446 | assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 2); | 513 | assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 2); |
| 447 | 514 | ||
| 448 | - assert!(store.consume_recovery_code(&user.id, "code-a").await.unwrap()); | 515 | + assert!( |
| 449 | - assert!(!store.consume_recovery_code(&user.id, "code-a").await.unwrap()); | 516 | + store |
| 450 | - assert!(!store.consume_recovery_code(&user.id, "unknown").await.unwrap()); | 517 | + .consume_recovery_code(&user.id, "code-a") |
| 518 | + .await | ||
| 519 | + .unwrap() | ||
| 520 | + ); | ||
| 521 | + assert!( | ||
| 522 | + !store | ||
| 523 | + .consume_recovery_code(&user.id, "code-a") | ||
| 524 | + .await | ||
| 525 | + .unwrap() | ||
| 526 | + ); | ||
| 527 | + assert!( | ||
| 528 | + !store | ||
| 529 | + .consume_recovery_code(&user.id, "unknown") | ||
| 530 | + .await | ||
| 531 | + .unwrap() | ||
| 532 | + ); | ||
| 451 | assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 1); | 533 | assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 1); |
| 452 | } | 534 | } |
| 453 | 535 | ||
| @@ -462,7 +544,19 @@ mod tests { | |||
| 462 | .create_user("ada@example.com", "Ada again", "hash", false) | 544 | .create_user("ada@example.com", "Ada again", "hash", false) |
| 463 | .await; | 545 | .await; |
| 464 | assert!(matches!(dup, Err(Error::Conflict(_))), "{dup:?}"); | 546 | assert!(matches!(dup, Err(Error::Conflict(_))), "{dup:?}"); |
| 465 | - assert!(store.user_by_email_folded("ada@example.com").await.unwrap().is_some()); | 547 | + assert!( |
| 466 | - assert!(store.user_by_email_folded("ADA@example.com").await.unwrap().is_none()); | 548 | + store |
| 549 | + .user_by_email_folded("ada@example.com") | ||
| 550 | + .await | ||
| 551 | + .unwrap() | ||
| 552 | + .is_some() | ||
| 553 | + ); | ||
| 554 | + assert!( | ||
| 555 | + store | ||
| 556 | + .user_by_email_folded("ADA@example.com") | ||
| 557 | + .await | ||
| 558 | + .unwrap() | ||
| 559 | + .is_none() | ||
| 560 | + ); | ||
| 467 | } | 561 | } |
| 468 | } | 562 | } |
crates/im-core/src/time.rsmodified+35 -0
| @@ -37,10 +37,45 @@ pub fn stamp_before(before: Duration) -> String { | |||
| 37 | format_stamp(OffsetDateTime::now_utc().saturating_sub(signed(before))) | 37 | format_stamp(OffsetDateTime::now_utc().saturating_sub(signed(before))) |
| 38 | } | 38 | } |
| 39 | 39 | ||
| 40 | +/// The IANA time zone names of the database compiled into this build, sorted. The bundled database | ||
| 41 | +/// is used on purpose, so every install offers the same list whatever the host has installed. | ||
| 42 | +pub fn zone_names() -> Vec<String> { | ||
| 43 | + let mut names: Vec<String> = jiff::tz::db() | ||
| 44 | + .available() | ||
| 45 | + .map(|name| name.as_str().to_owned()) | ||
| 46 | + .collect(); | ||
| 47 | + names.sort(); | ||
| 48 | + names | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// True only for an exact IANA name from [`zone_names`]. Matching is case-sensitive and nothing is | ||
| 52 | +/// trimmed, so the stored value is always the canonical name. | ||
| 53 | +pub fn is_zone(name: &str) -> bool { | ||
| 54 | + jiff::tz::db() | ||
| 55 | + .available() | ||
| 56 | + .any(|known| known.as_str() == name) | ||
| 57 | +} | ||
| 58 | + | ||
| 40 | #[cfg(test)] | 59 | #[cfg(test)] |
| 41 | mod tests { | 60 | mod tests { |
| 42 | use super::*; | 61 | use super::*; |
| 43 | 62 | ||
| 63 | + #[test] | ||
| 64 | + fn zones_are_checked_against_the_bundled_list() { | ||
| 65 | + assert!(is_zone("Europe/Istanbul")); | ||
| 66 | + assert!(is_zone("UTC")); | ||
| 67 | + for bad in [ | ||
| 68 | + "", | ||
| 69 | + "europe/istanbul", | ||
| 70 | + " Europe/Istanbul", | ||
| 71 | + "../../etc/passwd", | ||
| 72 | + "Mars/Olympus", | ||
| 73 | + ] { | ||
| 74 | + assert!(!is_zone(bad), "accepted {bad:?}"); | ||
| 75 | + } | ||
| 76 | + assert!(zone_names().len() > 300); | ||
| 77 | + } | ||
| 78 | + | ||
| 44 | #[test] | 79 | #[test] |
| 45 | fn stamps_have_fixed_width_and_sort_in_time_order() { | 80 | fn stamps_have_fixed_width_and_sort_in_time_order() { |
| 46 | let now = now_stamp(); | 81 | let now = now_stamp(); |
crates/im-core/src/totp.rsmodified+1 -2
| @@ -42,8 +42,7 @@ pub fn new_secret() -> [u8; SECRET_LEN] { | |||
| 42 | /// HOTP (RFC 4226) with HMAC-SHA1, reduced to [`DIGITS`] digits. | 42 | /// HOTP (RFC 4226) with HMAC-SHA1, reduced to [`DIGITS`] digits. |
| 43 | pub fn hotp(secret: &[u8], counter: u64) -> u32 { | 43 | pub fn hotp(secret: &[u8], counter: u64) -> u32 { |
| 44 | // HMAC accepts a key of any length, so construction cannot fail. | 44 | // HMAC accepts a key of any length, so construction cannot fail. |
| 45 | - let mut mac = | 45 | + let mut mac = <HmacSha1 as KeyInit>::new_from_slice(secret).expect("HMAC takes any key length"); |
| 46 | - <HmacSha1 as KeyInit>::new_from_slice(secret).expect("HMAC takes any key length"); | ||
| 47 | mac.update(&counter.to_be_bytes()); | 46 | mac.update(&counter.to_be_bytes()); |
| 48 | let tag = mac.finalize().into_bytes(); | 47 | let tag = mac.finalize().into_bytes(); |
| 49 | // Dynamic truncation (RFC 4226 section 5.3): the low nibble of the last byte picks a window. | 48 | // Dynamic truncation (RFC 4226 section 5.3): the low nibble of the last byte picks a window. |
crates/im-web/src/auth.rsmodified+12 -7
| @@ -11,7 +11,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; | |||
| 11 | use im_core::model::{Session, User, amr}; | 11 | use im_core::model::{Session, User, amr}; |
| 12 | use im_core::secret; | 12 | use im_core::secret; |
| 13 | use im_core::store::Store; | 13 | use im_core::store::Store; |
| 14 | -use im_core::store::sessions::NewSession; | 14 | +use im_core::store::sessions::{NewSession, SESSION_IDLE}; |
| 15 | use im_core::token::{constant_time_eq, generate_token, hash_token}; | 15 | use im_core::token::{constant_time_eq, generate_token, hash_token}; |
| 16 | use im_core::totp; | 16 | use im_core::totp; |
| 17 | use topcoat::Result; | 17 | use topcoat::Result; |
| @@ -27,8 +27,8 @@ use crate::state::AppState; | |||
| 27 | /// Logical name of the session cookie. `override_prefix_host()` stores it as `__Host-im_session`. | 27 | /// Logical name of the session cookie. `override_prefix_host()` stores it as `__Host-im_session`. |
| 28 | pub const SESSION_COOKIE: &str = "im_session"; | 28 | pub const SESSION_COOKIE: &str = "im_session"; |
| 29 | 29 | ||
| 30 | -/// How long a session lives, from sign-in. Both the row and the cookie use it. | 30 | +/// Seconds in a day, for the policy's day counts. |
| 31 | -pub const SESSION_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60); | 31 | +const DAY: u64 = 24 * 60 * 60; |
| 32 | 32 | ||
| 33 | /// Logical name of the pre-session CSRF cookie, used by the pages that run before a session exists. | 33 | /// Logical name of the pre-session CSRF cookie, used by the pages that run before a session exists. |
| 34 | pub const PRE_CSRF_COOKIE: &str = "im_precsrf"; | 34 | pub const PRE_CSRF_COOKIE: &str = "im_precsrf"; |
| @@ -140,9 +140,12 @@ pub fn check_csrf(session: &Session, submitted: &str) -> bool { | |||
| 140 | /// Creates a session for `user`, authenticated by `amr`, and sets the cookie. | 140 | /// Creates a session for `user`, authenticated by `amr`, and sets the cookie. |
| 141 | /// | 141 | /// |
| 142 | /// A session the browser already presented for the same person is ended first, so a sign-in always | 142 | /// A session the browser already presented for the same person is ended first, so a sign-in always |
| 143 | -/// rotates the session id. The cap of the policy is applied inside the store, in the same write. | 143 | +/// rotates the session id. The session lives [`SESSION_IDLE`] after its last use, up to the policy's |
| 144 | +/// `session_max_days` from now; the store keeps both limits. The per-person cap of the policy is | ||
| 145 | +/// applied inside the store, in the same write. | ||
| 144 | pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { | 146 | pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { |
| 145 | let state = app_context::<AppState>(cx); | 147 | let state = app_context::<AppState>(cx); |
| 148 | + let max_age = Duration::from_secs(u64::from(state.config.policy.session_max_days) * DAY); | ||
| 146 | if let Some(old) = presented_session(cx) | 149 | if let Some(old) = presented_session(cx) |
| 147 | .await? | 150 | .await? |
| 148 | .filter(|old| old.user_id == user.id) | 151 | .filter(|old| old.user_id == user.id) |
| @@ -163,7 +166,8 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { | |||
| 163 | amr, | 166 | amr, |
| 164 | ip: Some(ip.as_str()), | 167 | ip: Some(ip.as_str()), |
| 165 | user_agent: user_agent.as_deref(), | 168 | user_agent: user_agent.as_deref(), |
| 166 | - ttl: SESSION_TTL, | 169 | + idle: SESSION_IDLE, |
| 170 | + max_age, | ||
| 167 | }, | 171 | }, |
| 168 | state.config.policy.max_sessions, | 172 | state.config.policy.max_sessions, |
| 169 | ) | 173 | ) |
| @@ -171,14 +175,15 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { | |||
| 171 | // Sessions ended by the cap are not signed out elsewhere yet; their back-channel logout is queued | 175 | // Sessions ended by the cap are not signed out elsewhere yet; their back-channel logout is queued |
| 172 | // once the OpenID provider exists. | 176 | // once the OpenID provider exists. |
| 173 | state.live.bump(&Topic::Account(user.id.clone())); | 177 | state.live.bump(&Topic::Account(user.id.clone())); |
| 174 | - let max_age = time::Duration::seconds(i64::try_from(SESSION_TTL.as_secs()).unwrap_or(i64::MAX)); | 178 | + // The browser keeps the cookie for the hard cap; the server decides the real expiry. |
| 179 | + let cookie_age = time::Duration::seconds(i64::try_from(max_age.as_secs()).unwrap_or(i64::MAX)); | ||
| 175 | jar(cx).add( | 180 | jar(cx).add( |
| 176 | Cookie::build((SESSION_COOKIE, token)) | 181 | Cookie::build((SESSION_COOKIE, token)) |
| 177 | .path("/") | 182 | .path("/") |
| 178 | .secure(true) | 183 | .secure(true) |
| 179 | .http_only(true) | 184 | .http_only(true) |
| 180 | .same_site(SameSite::Lax) | 185 | .same_site(SameSite::Lax) |
| 181 | - .max_age(max_age) | 186 | + .max_age(cookie_age) |
| 182 | .build(), | 187 | .build(), |
| 183 | ); | 188 | ); |
| 184 | Ok(created.session) | 189 | Ok(created.session) |
crates/im-web/src/boot.rsmodified+9 -2
| @@ -10,16 +10,18 @@ use std::path::Path; | |||
| 10 | use std::sync::Arc; | 10 | use std::sync::Arc; |
| 11 | 11 | ||
| 12 | use im_core::config::Config; | 12 | use im_core::config::Config; |
| 13 | +use im_core::photo::MAX_UPLOAD_BYTES; | ||
| 13 | use im_core::secret; | 14 | use im_core::secret; |
| 14 | use im_core::store::Store; | 15 | use im_core::store::Store; |
| 15 | use tokio::net::TcpListener; | 16 | use tokio::net::TcpListener; |
| 16 | use tokio::signal::unix::{SignalKind, signal}; | 17 | use tokio::signal::unix::{SignalKind, signal}; |
| 17 | use tokio::sync::watch; | 18 | use tokio::sync::watch; |
| 18 | use topcoat::cookie::RouterBuilderCookieExt; | 19 | use topcoat::cookie::RouterBuilderCookieExt; |
| 19 | -use topcoat::router::{Router, RouterBuilderDiscoverExt, RouterService}; | 20 | +use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; |
| 20 | 21 | ||
| 21 | use crate::live::LiveHub; | 22 | use crate::live::LiveHub; |
| 22 | use crate::pages::not_found::NotFoundLayer; | 23 | use crate::pages::not_found::NotFoundLayer; |
| 24 | +use crate::pages::profile::PHOTO_ROUTE; | ||
| 23 | use crate::security::{self, SecurityHeaders}; | 25 | use crate::security::{self, SecurityHeaders}; |
| 24 | use crate::state::AppState; | 26 | use crate::state::AppState; |
| 25 | use crate::throttle::Throttle; | 27 | use crate::throttle::Throttle; |
| @@ -86,14 +88,19 @@ async fn open_state(config: Config) -> im_core::Result<AppState> { | |||
| 86 | }) | 88 | }) |
| 87 | } | 89 | } |
| 88 | 90 | ||
| 91 | +/// The request body limit of the photo upload: the picture plus room for the multipart framing and | ||
| 92 | +/// the CSRF field. The handler enforces the picture limit itself while streaming. | ||
| 93 | +const PHOTO_BODY_LIMIT: usize = MAX_UPLOAD_BYTES + 64 * 1024; | ||
| 94 | + | ||
| 89 | /// The router of the server: every route and page found by `discover`, the cookie jar, the security | 95 | /// The router of the server: every route and page found by `discover`, the cookie jar, the security |
| 90 | -/// headers on every response, and the styled 404 for browsers. | 96 | +/// headers on every response, the styled 404 for browsers, and the upload limit of the photo route. |
| 91 | pub fn router(state: AppState) -> Router { | 97 | pub fn router(state: AppState) -> Router { |
| 92 | let security = SecurityHeaders::new(security::headers_for(&state.config.base_url)); | 98 | let security = SecurityHeaders::new(security::headers_for(&state.config.base_url)); |
| 93 | Router::builder() | 99 | Router::builder() |
| 94 | .discover() | 100 | .discover() |
| 95 | .app_context(state) | 101 | .app_context(state) |
| 96 | .cookies() | 102 | .cookies() |
| 103 | + .layer(BodyLimit::max(PHOTO_BODY_LIMIT).at(PHOTO_ROUTE)) | ||
| 97 | .layer(security) | 104 | .layer(security) |
| 98 | .layer(NotFoundLayer) | 105 | .layer(NotFoundLayer) |
| 99 | .build() | 106 | .build() |
crates/im-web/src/i18n/account.rsmodified+171 -3
| @@ -36,7 +36,7 @@ pub enum Txt { | |||
| 36 | ErrPasswordSame, | 36 | ErrPasswordSame, |
| 37 | /// The new password contains the email address or a word of the name. | 37 | /// The new password contains the email address or a word of the name. |
| 38 | ErrPasswordIdentity, | 38 | ErrPasswordIdentity, |
| 39 | - /// The name is empty or too long. | 39 | + /// The display name is empty, too long, or holds a control or direction character. |
| 40 | ErrNameInvalid, | 40 | ErrNameInvalid, |
| 41 | /// The email address does not have a valid shape. | 41 | /// The email address does not have a valid shape. |
| 42 | ErrEmailInvalid, | 42 | ErrEmailInvalid, |
| @@ -168,6 +168,78 @@ pub enum Txt { | |||
| 168 | UnknownSystem, | 168 | UnknownSystem, |
| 169 | /// The label of the account menu. | 169 | /// The label of the account menu. |
| 170 | AccountMenu, | 170 | AccountMenu, |
| 171 | + /// The title of another person's public card. | ||
| 172 | + PersonTitle, | ||
| 173 | + /// The title of the profile page, and the menu item that opens it. | ||
| 174 | + ProfileTitle, | ||
| 175 | + /// The account home link text that opens the profile page. | ||
| 176 | + ProfileLinkText, | ||
| 177 | + /// The sentence under the profile title. | ||
| 178 | + ProfileIntro, | ||
| 179 | + /// The rule for the display name, under its field. | ||
| 180 | + NameHelp, | ||
| 181 | + /// The button that saves the display name. | ||
| 182 | + SaveName, | ||
| 183 | + /// The heading of the photo section. | ||
| 184 | + PhotoSection, | ||
| 185 | + /// What a photo may be, and what is stored. | ||
| 186 | + PhotoHelp, | ||
| 187 | + /// The label of the file picker. | ||
| 188 | + PhotoFile, | ||
| 189 | + /// The button that uploads a photo. | ||
| 190 | + PhotoUpload, | ||
| 191 | + /// The button that removes the photo. | ||
| 192 | + PhotoRemove, | ||
| 193 | + /// Says what shows once the photo is removed. | ||
| 194 | + PhotoRemoveHelp, | ||
| 195 | + /// The alternative text of the viewer's own photo. | ||
| 196 | + PhotoAlt, | ||
| 197 | + /// The alternative text of another person's photo. | ||
| 198 | + PhotoOfPerson, | ||
| 199 | + /// Explains that the email address cannot be changed yet. | ||
| 200 | + EmailLaterNote, | ||
| 201 | + /// Notice: the display name was saved. | ||
| 202 | + SavedName, | ||
| 203 | + /// Notice: the photo was saved. | ||
| 204 | + SavedPhoto, | ||
| 205 | + /// Notice: the photo was removed. | ||
| 206 | + SavedPhotoRemoved, | ||
| 207 | + /// Shown when the upload is not one of the accepted image types. | ||
| 208 | + ErrPhotoType, | ||
| 209 | + /// Shown when the upload is over the size limit. | ||
| 210 | + ErrPhotoTooLarge, | ||
| 211 | + /// Shown when the upload form was sent without a file. | ||
| 212 | + ErrPhotoMissing, | ||
| 213 | + /// The title of the preferences page, and the menu item that opens it. | ||
| 214 | + PreferencesTitle, | ||
| 215 | + /// The account home link text that opens the preferences page. | ||
| 216 | + PreferencesLinkText, | ||
| 217 | + /// The sentence under the preferences title. | ||
| 218 | + PreferencesIntro, | ||
| 219 | + /// The label of the language choice. | ||
| 220 | + LanguageLabel, | ||
| 221 | + /// The language choice that follows the browser. | ||
| 222 | + LangAuto, | ||
| 223 | + /// The English language choice. | ||
| 224 | + LangEnglish, | ||
| 225 | + /// The Turkish language choice. | ||
| 226 | + LangTurkish, | ||
| 227 | + /// The label of the time zone choice. | ||
| 228 | + TimeZoneLabel, | ||
| 229 | + /// The label of the theme choice. | ||
| 230 | + ThemeLabel, | ||
| 231 | + /// The theme choice that follows the device. | ||
| 232 | + ThemeSystem, | ||
| 233 | + /// The light theme choice. | ||
| 234 | + ThemeLight, | ||
| 235 | + /// The dark theme choice. | ||
| 236 | + ThemeDark, | ||
| 237 | + /// The button that saves the preferences. | ||
| 238 | + SavePreferences, | ||
| 239 | + /// Notice: the preferences were saved. | ||
| 240 | + SavedPreferences, | ||
| 241 | + /// Shown when a submitted preference is not one of the offered choices. | ||
| 242 | + ErrPreferenceInvalid, | ||
| 171 | } | 243 | } |
| 172 | 244 | ||
| 173 | /// The text of `key` in `lang`. | 245 | /// The text of `key` in `lang`. |
| @@ -209,8 +281,12 @@ pub fn text(lang: Lang, key: Txt) -> &'static str { | |||
| 209 | (Txt::ErrPasswordIdentity, Lang::Tr) => { | 281 | (Txt::ErrPasswordIdentity, Lang::Tr) => { |
| 210 | "Parola e-posta adresinizi ya da adınızı içermemelidir." | 282 | "Parola e-posta adresinizi ya da adınızı içermemelidir." |
| 211 | } | 283 | } |
| 212 | - (Txt::ErrNameInvalid, Lang::En) => "Enter your name, at most 100 characters.", | 284 | + (Txt::ErrNameInvalid, Lang::En) => { |
| 213 | - (Txt::ErrNameInvalid, Lang::Tr) => "Adınızı girin, en fazla 100 karakter.", | 285 | + "Enter a name of 1 to 100 characters, without control or direction characters." |
| 286 | + } | ||
| 287 | + (Txt::ErrNameInvalid, Lang::Tr) => { | ||
| 288 | + "1 ile 100 karakter arasında, denetim ya da yön karakteri içermeyen bir ad girin." | ||
| 289 | + } | ||
| 214 | (Txt::ErrEmailInvalid, Lang::En) => "Enter a valid email address.", | 290 | (Txt::ErrEmailInvalid, Lang::En) => "Enter a valid email address.", |
| 215 | (Txt::ErrEmailInvalid, Lang::Tr) => "Geçerli bir e-posta adresi girin.", | 291 | (Txt::ErrEmailInvalid, Lang::Tr) => "Geçerli bir e-posta adresi girin.", |
| 216 | (Txt::ErrCodeInvalid, Lang::En) => "The code is wrong, or it was already used.", | 292 | (Txt::ErrCodeInvalid, Lang::En) => "The code is wrong, or it was already used.", |
| @@ -369,6 +445,98 @@ pub fn text(lang: Lang, key: Txt) -> &'static str { | |||
| 369 | (Txt::UnknownSystem, Lang::Tr) => "bilinmeyen sistem", | 445 | (Txt::UnknownSystem, Lang::Tr) => "bilinmeyen sistem", |
| 370 | (Txt::AccountMenu, Lang::En) => "Account menu", | 446 | (Txt::AccountMenu, Lang::En) => "Account menu", |
| 371 | (Txt::AccountMenu, Lang::Tr) => "Hesap menüsü", | 447 | (Txt::AccountMenu, Lang::Tr) => "Hesap menüsü", |
| 448 | + (Txt::PersonTitle, Lang::En) => "Person", | ||
| 449 | + (Txt::PersonTitle, Lang::Tr) => "Kişi", | ||
| 450 | + (Txt::ProfileTitle, Lang::En) => "Profile", | ||
| 451 | + (Txt::ProfileTitle, Lang::Tr) => "Profil", | ||
| 452 | + (Txt::ProfileLinkText, Lang::En) => "Edit your profile", | ||
| 453 | + (Txt::ProfileLinkText, Lang::Tr) => "Profilinizi düzenleyin", | ||
| 454 | + (Txt::ProfileIntro, Lang::En) => "How other people in the family apps see you.", | ||
| 455 | + (Txt::ProfileIntro, Lang::Tr) => { | ||
| 456 | + "Aile uygulamalarındaki diğer kişilerin sizi nasıl gördüğü." | ||
| 457 | + } | ||
| 458 | + (Txt::NameHelp, Lang::En) => { | ||
| 459 | + "1 to 100 characters. Control and direction characters are not allowed." | ||
| 460 | + } | ||
| 461 | + (Txt::NameHelp, Lang::Tr) => { | ||
| 462 | + "1 ile 100 karakter. Denetim ve yön karakterleri kullanılamaz." | ||
| 463 | + } | ||
| 464 | + (Txt::SaveName, Lang::En) => "Save name", | ||
| 465 | + (Txt::SaveName, Lang::Tr) => "Adı kaydet", | ||
| 466 | + (Txt::PhotoSection, Lang::En) => "Photo", | ||
| 467 | + (Txt::PhotoSection, Lang::Tr) => "Fotoğraf", | ||
| 468 | + (Txt::PhotoHelp, Lang::En) => { | ||
| 469 | + "PNG, JPEG, WebP or GIF, up to 5 MB. It is cropped to a square and stored as a 512 pixel WebP." | ||
| 470 | + } | ||
| 471 | + (Txt::PhotoHelp, Lang::Tr) => { | ||
| 472 | + "PNG, JPEG, WebP veya GIF, en fazla 5 MB. Kareye kırpılır ve 512 piksel WebP olarak saklanır." | ||
| 473 | + } | ||
| 474 | + (Txt::PhotoFile, Lang::En) => "Choose a picture", | ||
| 475 | + (Txt::PhotoFile, Lang::Tr) => "Bir resim seçin", | ||
| 476 | + (Txt::PhotoUpload, Lang::En) => "Upload photo", | ||
| 477 | + (Txt::PhotoUpload, Lang::Tr) => "Fotoğraf yükle", | ||
| 478 | + (Txt::PhotoRemove, Lang::En) => "Remove photo", | ||
| 479 | + (Txt::PhotoRemove, Lang::Tr) => "Fotoğrafı kaldır", | ||
| 480 | + (Txt::PhotoRemoveHelp, Lang::En) => "Your initials are shown instead.", | ||
| 481 | + (Txt::PhotoRemoveHelp, Lang::Tr) => "Bunun yerine baş harfleriniz gösterilir.", | ||
| 482 | + (Txt::PhotoAlt, Lang::En) => "Your photo", | ||
| 483 | + (Txt::PhotoAlt, Lang::Tr) => "Fotoğrafınız", | ||
| 484 | + (Txt::PhotoOfPerson, Lang::En) => "Photo of this person", | ||
| 485 | + (Txt::PhotoOfPerson, Lang::Tr) => "Bu kişinin fotoğrafı", | ||
| 486 | + (Txt::EmailLaterNote, Lang::En) => { | ||
| 487 | + "Changing your email address is not available yet. It will need a confirmation link sent to both addresses." | ||
| 488 | + } | ||
| 489 | + (Txt::EmailLaterNote, Lang::Tr) => { | ||
| 490 | + "E-posta adresinizi değiştirme henüz kullanılamıyor. İki adrese de onay bağlantısı gönderilecek." | ||
| 491 | + } | ||
| 492 | + (Txt::SavedName, Lang::En) => "Your name was saved.", | ||
| 493 | + (Txt::SavedName, Lang::Tr) => "Adınız kaydedildi.", | ||
| 494 | + (Txt::SavedPhoto, Lang::En) => "Your photo was saved.", | ||
| 495 | + (Txt::SavedPhoto, Lang::Tr) => "Fotoğrafınız kaydedildi.", | ||
| 496 | + (Txt::SavedPhotoRemoved, Lang::En) => "Your photo was removed.", | ||
| 497 | + (Txt::SavedPhotoRemoved, Lang::Tr) => "Fotoğrafınız kaldırıldı.", | ||
| 498 | + (Txt::ErrPhotoType, Lang::En) => "Choose a PNG, JPEG, WebP or GIF image.", | ||
| 499 | + (Txt::ErrPhotoType, Lang::Tr) => "Lütfen bir PNG, JPEG, WebP veya GIF resmi seçin.", | ||
| 500 | + (Txt::ErrPhotoTooLarge, Lang::En) => "The photo is larger than 5 MB.", | ||
| 501 | + (Txt::ErrPhotoTooLarge, Lang::Tr) => "Fotoğraf 5 MB'tan büyük.", | ||
| 502 | + (Txt::ErrPhotoMissing, Lang::En) => "Choose a picture first.", | ||
| 503 | + (Txt::ErrPhotoMissing, Lang::Tr) => "Önce bir resim seçin.", | ||
| 504 | + (Txt::PreferencesTitle, Lang::En) => "Preferences", | ||
| 505 | + (Txt::PreferencesTitle, Lang::Tr) => "Tercihler", | ||
| 506 | + (Txt::PreferencesLinkText, Lang::En) => "Language, time zone and theme", | ||
| 507 | + (Txt::PreferencesLinkText, Lang::Tr) => "Dil, saat dilimi ve tema", | ||
| 508 | + (Txt::PreferencesIntro, Lang::En) => "These apply to every family app that reads them.", | ||
| 509 | + (Txt::PreferencesIntro, Lang::Tr) => { | ||
| 510 | + "Bunları okuyan tüm aile uygulamaları için geçerlidir." | ||
| 511 | + } | ||
| 512 | + (Txt::LanguageLabel, Lang::En) => "Language", | ||
| 513 | + (Txt::LanguageLabel, Lang::Tr) => "Dil", | ||
| 514 | + (Txt::LangAuto, Lang::En) => "Automatic (from my browser)", | ||
| 515 | + (Txt::LangAuto, Lang::Tr) => "Otomatik (tarayıcımdan)", | ||
| 516 | + (Txt::LangEnglish, Lang::En) => "English", | ||
| 517 | + (Txt::LangEnglish, Lang::Tr) => "İngilizce", | ||
| 518 | + (Txt::LangTurkish, Lang::En) => "Turkish", | ||
| 519 | + (Txt::LangTurkish, Lang::Tr) => "Türkçe", | ||
| 520 | + (Txt::TimeZoneLabel, Lang::En) => "Time zone", | ||
| 521 | + (Txt::TimeZoneLabel, Lang::Tr) => "Saat dilimi", | ||
| 522 | + (Txt::ThemeLabel, Lang::En) => "Theme", | ||
| 523 | + (Txt::ThemeLabel, Lang::Tr) => "Tema", | ||
| 524 | + (Txt::ThemeSystem, Lang::En) => "Match my device", | ||
| 525 | + (Txt::ThemeSystem, Lang::Tr) => "Cihazımla aynı", | ||
| 526 | + (Txt::ThemeLight, Lang::En) => "Light", | ||
| 527 | + (Txt::ThemeLight, Lang::Tr) => "Açık", | ||
| 528 | + (Txt::ThemeDark, Lang::En) => "Dark", | ||
| 529 | + (Txt::ThemeDark, Lang::Tr) => "Koyu", | ||
| 530 | + (Txt::SavePreferences, Lang::En) => "Save preferences", | ||
| 531 | + (Txt::SavePreferences, Lang::Tr) => "Tercihleri kaydet", | ||
| 532 | + (Txt::SavedPreferences, Lang::En) => "Your preferences were saved.", | ||
| 533 | + (Txt::SavedPreferences, Lang::Tr) => "Tercihleriniz kaydedildi.", | ||
| 534 | + (Txt::ErrPreferenceInvalid, Lang::En) => { | ||
| 535 | + "That choice is not available. Pick one from the list." | ||
| 536 | + } | ||
| 537 | + (Txt::ErrPreferenceInvalid, Lang::Tr) => { | ||
| 538 | + "Bu seçenek kullanılamıyor. Listeden birini seçin." | ||
| 539 | + } | ||
| 372 | } | 540 | } |
| 373 | } | 541 | } |
| 374 | 542 | ||
crates/im-web/src/pages/home.rsmodified+2 -0
| @@ -43,6 +43,8 @@ async fn home(cx: &Cx) -> Result<impl View> { | |||
| 43 | <dd>(two_factor)</dd> | 43 | <dd>(two_factor)</dd> |
| 44 | </dl> | 44 | </dl> |
| 45 | <nav class="links"> | 45 | <nav class="links"> |
| 46 | + <a href="/account/profile">(text(lang, Txt::ProfileLinkText))</a> | ||
| 47 | + <a href="/account/preferences">(text(lang, Txt::PreferencesLinkText))</a> | ||
| 46 | <a href="/account/security">(text(lang, Txt::SecurityLinkText))</a> | 48 | <a href="/account/security">(text(lang, Txt::SecurityLinkText))</a> |
| 47 | <a href="/account/sessions">(text(lang, Txt::SessionsLinkText))</a> | 49 | <a href="/account/sessions">(text(lang, Txt::SessionsLinkText))</a> |
| 48 | if is_admin { | 50 | if is_admin { |
crates/im-web/src/pages/mod.rsmodified+4 -0
| @@ -3,6 +3,10 @@ | |||
| 3 | pub mod home; | 3 | pub mod home; |
| 4 | pub mod login; | 4 | pub mod login; |
| 5 | pub mod not_found; | 5 | pub mod not_found; |
| 6 | +pub mod people; | ||
| 7 | +pub mod photo; | ||
| 8 | +pub mod preferences; | ||
| 9 | +pub mod profile; | ||
| 6 | pub mod security; | 10 | pub mod security; |
| 7 | pub mod sessions; | 11 | pub mod sessions; |
| 8 | pub mod setup; | 12 | pub mod setup; |
crates/im-web/src/pages/people.rsadded+72 -0
| @@ -0,0 +1,72 @@ | |||
| 1 | +//! `GET /people/{id}`: the public card of a person, for the signed-in people of the family. | ||
| 2 | +//! | ||
| 3 | +//! The card shows the name, the photo and the email address, and nothing else. A disabled or | ||
| 4 | +//! unknown person is a 404, the same answer, so the page does not say which of the two it is. | ||
| 5 | + | ||
| 6 | +use topcoat::Result; | ||
| 7 | +use topcoat::context::{Cx, app_context}; | ||
| 8 | +use topcoat::router::error::not_found; | ||
| 9 | +use topcoat::router::page; | ||
| 10 | +use topcoat::view::{View, view}; | ||
| 11 | + | ||
| 12 | +use crate::auth::require_user; | ||
| 13 | +use crate::i18n::Lang; | ||
| 14 | +use crate::i18n::account::{Txt, text}; | ||
| 15 | +use crate::pages::photo::path_id; | ||
| 16 | +use crate::state::AppState; | ||
| 17 | +use crate::views::{ViewerInfo, page_lang, shell}; | ||
| 18 | + | ||
| 19 | +/// `GET /people/{id}`. | ||
| 20 | +#[page("/people/{id}")] | ||
| 21 | +async fn person_page(cx: &Cx) -> Result<impl View> { | ||
| 22 | + let viewer = require_user(cx).await?; | ||
| 23 | + let state = app_context::<AppState>(cx); | ||
| 24 | + let lang = page_lang(cx, Some(&viewer)); | ||
| 25 | + let Some(id) = path_id(cx) else { | ||
| 26 | + return Err(not_found().into()); | ||
| 27 | + }; | ||
| 28 | + let Some(person) = state | ||
| 29 | + .store | ||
| 30 | + .user_by_id(&id) | ||
| 31 | + .await? | ||
| 32 | + .filter(|person| !person.is_disabled()) | ||
| 33 | + else { | ||
| 34 | + return Err(not_found().into()); | ||
| 35 | + }; | ||
| 36 | + Ok(person_view( | ||
| 37 | + cx, | ||
| 38 | + lang, | ||
| 39 | + ViewerInfo::of(&viewer), | ||
| 40 | + person.name, | ||
| 41 | + person.email, | ||
| 42 | + person.id, | ||
| 43 | + person.picture_version, | ||
| 44 | + )) | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// The card markup. | ||
| 48 | +fn person_view( | ||
| 49 | + cx: &Cx, | ||
| 50 | + lang: Lang, | ||
| 51 | + info: ViewerInfo, | ||
| 52 | + name: String, | ||
| 53 | + email: String, | ||
| 54 | + id: String, | ||
| 55 | + picture_version: i64, | ||
| 56 | +) -> impl View { | ||
| 57 | + let photo_src = format!("/photo/{id}?v={picture_version}"); | ||
| 58 | + view! { cx => | ||
| 59 | + shell(title: text(lang, Txt::PersonTitle), lang: lang, viewer: Some(info), | ||
| 60 | + <section class="card stack"> | ||
| 61 | + <div class="profile-photo"> | ||
| 62 | + <img class="avatar-large" src=(photo_src) alt=(text(lang, Txt::PhotoOfPerson)) width="128" height="128"> | ||
| 63 | + </div> | ||
| 64 | + <h1>(name)</h1> | ||
| 65 | + <dl class="facts"> | ||
| 66 | + <dt>(text(lang, Txt::Email))</dt> | ||
| 67 | + <dd>(email)</dd> | ||
| 68 | + </dl> | ||
| 69 | + </section> | ||
| 70 | + ) | ||
| 71 | + } | ||
| 72 | +} | ||
crates/im-web/src/pages/photo.rsadded+198 -0
| @@ -0,0 +1,198 @@ | |||
| 1 | +//! `GET /photo/{id}`: a person's profile photo, or their initials when they have none. | ||
| 2 | +//! | ||
| 3 | +//! Only a signed-in person gets one, and a disabled or unknown person is a 404. The photo is sent | ||
| 4 | +//! with the MIME type it was stored with (always WebP, see `im_core::photo`), a strong ETag made of | ||
| 5 | +//! its version, and `private` caching. The initials are an SVG built here from the name: every | ||
| 6 | +//! character of the name is XML-escaped, and the response carries a CSP that allows no script and | ||
| 7 | +//! no external resource, so even a crafted name cannot run anything if the file is opened directly. | ||
| 8 | + | ||
| 9 | +use http::header::{CACHE_CONTROL, CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH}; | ||
| 10 | +use im_core::photo::read_photo; | ||
| 11 | +use im_core::token::hash_token; | ||
| 12 | +use topcoat::Result; | ||
| 13 | +use topcoat::context::{Cx, app_context}; | ||
| 14 | +use topcoat::router::error::not_found; | ||
| 15 | +use topcoat::router::request::headers; | ||
| 16 | +use topcoat::router::{HeaderMap, HeaderValue, StatusCode, raw_path_params, route}; | ||
| 17 | + | ||
| 18 | +use crate::auth::require_user; | ||
| 19 | +use crate::state::AppState; | ||
| 20 | + | ||
| 21 | +/// The CSP of every photo answer. Nothing may load, and the initials SVG may only style itself. | ||
| 22 | +pub const PHOTO_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'"; | ||
| 23 | + | ||
| 24 | +/// Caching of a stored photo. The URL carries the picture version (`?v=`), so a changed photo gets | ||
| 25 | +/// a new URL; the browser may keep this one for an hour. | ||
| 26 | +const PHOTO_CACHE: &str = "private, max-age=3600"; | ||
| 27 | + | ||
| 28 | +/// Caching of the initials. They follow the name, which does not change the picture version, so the | ||
| 29 | +/// browser must ask again each time (a 304 when nothing changed). | ||
| 30 | +const INITIALS_CACHE: &str = "private, no-cache"; | ||
| 31 | + | ||
| 32 | +/// The status, headers and body of a photo answer. | ||
| 33 | +type Answer = (StatusCode, HeaderMap, Vec<u8>); | ||
| 34 | + | ||
| 35 | +/// `GET /photo/{id}`. | ||
| 36 | +#[route(GET "/photo/{id}")] | ||
| 37 | +async fn photo(cx: &Cx) -> Result<Answer> { | ||
| 38 | + require_user(cx).await?; | ||
| 39 | + let state = app_context::<AppState>(cx); | ||
| 40 | + let Some(id) = path_id(cx) else { | ||
| 41 | + return Err(not_found().into()); | ||
| 42 | + }; | ||
| 43 | + let Some(person) = state | ||
| 44 | + .store | ||
| 45 | + .user_by_id(&id) | ||
| 46 | + .await? | ||
| 47 | + .filter(|person| !person.is_disabled()) | ||
| 48 | + else { | ||
| 49 | + return Err(not_found().into()); | ||
| 50 | + }; | ||
| 51 | + | ||
| 52 | + if let Some(mime) = person.photo_mime.as_deref() { | ||
| 53 | + let etag = format!("\"{}\"", person.picture_version); | ||
| 54 | + if none_match(cx, &etag) { | ||
| 55 | + return Ok(answer( | ||
| 56 | + StatusCode::NOT_MODIFIED, | ||
| 57 | + &etag, | ||
| 58 | + mime, | ||
| 59 | + PHOTO_CACHE, | ||
| 60 | + Vec::new(), | ||
| 61 | + )); | ||
| 62 | + } | ||
| 63 | + let dir = state.config.data_dir.clone(); | ||
| 64 | + let read_id = id.clone(); | ||
| 65 | + let stored = tokio::task::spawn_blocking(move || read_photo(&dir, &read_id)) | ||
| 66 | + .await | ||
| 67 | + .map_err(|error| topcoat::Error::msg(error.to_string()))??; | ||
| 68 | + if let Some(bytes) = stored { | ||
| 69 | + return Ok(answer(StatusCode::OK, &etag, mime, PHOTO_CACHE, bytes)); | ||
| 70 | + } | ||
| 71 | + // The row names a photo whose file is gone. Showing the initials is the honest answer. | ||
| 72 | + tracing::warn!(user = %id, "photo row has no file; showing initials"); | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + let etag = format!( | ||
| 76 | + "\"i{}-{}\"", | ||
| 77 | + person.picture_version, | ||
| 78 | + &hash_token(&person.name)[..16] | ||
| 79 | + ); | ||
| 80 | + if none_match(cx, &etag) { | ||
| 81 | + return Ok(answer( | ||
| 82 | + StatusCode::NOT_MODIFIED, | ||
| 83 | + &etag, | ||
| 84 | + "image/svg+xml", | ||
| 85 | + INITIALS_CACHE, | ||
| 86 | + Vec::new(), | ||
| 87 | + )); | ||
| 88 | + } | ||
| 89 | + let svg = initials_svg(&person.name, &person.id); | ||
| 90 | + Ok(answer( | ||
| 91 | + StatusCode::OK, | ||
| 92 | + &etag, | ||
| 93 | + "image/svg+xml", | ||
| 94 | + INITIALS_CACHE, | ||
| 95 | + svg.into_bytes(), | ||
| 96 | + )) | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// The `{id}` of the matched route, or `None` when there is none. | ||
| 100 | +pub fn path_id(cx: &Cx) -> Option<String> { | ||
| 101 | + raw_path_params(cx) | ||
| 102 | + .find(|(name, _)| *name == "id") | ||
| 103 | + .map(|(_, value)| value.as_str().to_owned()) | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// True when the request's `If-None-Match` names `etag`, so the answer can be a 304. | ||
| 107 | +fn none_match(cx: &Cx, etag: &str) -> bool { | ||
| 108 | + headers(cx) | ||
| 109 | + .get_all(IF_NONE_MATCH) | ||
| 110 | + .iter() | ||
| 111 | + .filter_map(|value| value.to_str().ok()) | ||
| 112 | + .flat_map(|value| value.split(',')) | ||
| 113 | + .any(|tag| tag.trim() == etag) | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +/// Builds one photo answer with its headers. | ||
| 117 | +fn answer( | ||
| 118 | + status: StatusCode, | ||
| 119 | + etag: &str, | ||
| 120 | + mime: &str, | ||
| 121 | + cache: &'static str, | ||
| 122 | + body: Vec<u8>, | ||
| 123 | +) -> Answer { | ||
| 124 | + let mut headers = HeaderMap::new(); | ||
| 125 | + headers.insert( | ||
| 126 | + CONTENT_TYPE, | ||
| 127 | + HeaderValue::from_str(mime).unwrap_or(HeaderValue::from_static("application/octet-stream")), | ||
| 128 | + ); | ||
| 129 | + headers.insert(CACHE_CONTROL, HeaderValue::from_static(cache)); | ||
| 130 | + headers.insert( | ||
| 131 | + ETAG, | ||
| 132 | + HeaderValue::from_str(etag).unwrap_or(HeaderValue::from_static("\"\"")), | ||
| 133 | + ); | ||
| 134 | + headers.insert(CONTENT_SECURITY_POLICY, HeaderValue::from_static(PHOTO_CSP)); | ||
| 135 | + (status, headers, body) | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +/// The initials of `name` as a square SVG. The colour comes from `seed` (the person's id), so it is | ||
| 139 | +/// the same on every request. Everything taken from the name is XML-escaped. | ||
| 140 | +pub fn initials_svg(name: &str, seed: &str) -> String { | ||
| 141 | + let initials: String = name | ||
| 142 | + .split_whitespace() | ||
| 143 | + .filter_map(|word| word.chars().next()) | ||
| 144 | + .take(2) | ||
| 145 | + .flat_map(char::to_uppercase) | ||
| 146 | + .collect(); | ||
| 147 | + let initials = if initials.is_empty() { | ||
| 148 | + "?".to_owned() | ||
| 149 | + } else { | ||
| 150 | + initials | ||
| 151 | + }; | ||
| 152 | + let hue = u32::from_str_radix(&hash_token(seed)[..4], 16).unwrap_or(0) % 360; | ||
| 153 | + format!( | ||
| 154 | + "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"512\" height=\"512\" viewBox=\"0 0 512 512\" \ | ||
| 155 | + role=\"img\" aria-label=\"{label}\"><rect width=\"512\" height=\"512\" \ | ||
| 156 | + fill=\"hsl({hue} 45% 40%)\"/><text x=\"256\" y=\"256\" dy=\"0.35em\" text-anchor=\"middle\" \ | ||
| 157 | + font-family=\"system-ui, sans-serif\" font-size=\"200\" font-weight=\"600\" \ | ||
| 158 | + fill=\"#ffffff\">{initials}</text></svg>", | ||
| 159 | + label = xml_escape(name), | ||
| 160 | + initials = xml_escape(&initials), | ||
| 161 | + ) | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +/// Escapes the five characters that have a meaning in XML text and attribute values. | ||
| 165 | +fn xml_escape(text: &str) -> String { | ||
| 166 | + let mut out = String::with_capacity(text.len()); | ||
| 167 | + for c in text.chars() { | ||
| 168 | + match c { | ||
| 169 | + '&' => out.push_str("&"), | ||
| 170 | + '<' => out.push_str("<"), | ||
| 171 | + '>' => out.push_str(">"), | ||
| 172 | + '"' => out.push_str("""), | ||
| 173 | + '\'' => out.push_str("'"), | ||
| 174 | + other => out.push(other), | ||
| 175 | + } | ||
| 176 | + } | ||
| 177 | + out | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +#[cfg(test)] | ||
| 181 | +mod tests { | ||
| 182 | + use super::*; | ||
| 183 | + | ||
| 184 | + #[test] | ||
| 185 | + fn a_script_in_the_name_is_escaped_in_the_initials() { | ||
| 186 | + let svg = initials_svg("<script>alert(1)</script>", "01HZ0000000000000000000000"); | ||
| 187 | + assert!(!svg.contains("<script"), "unescaped markup: {svg}"); | ||
| 188 | + assert!(svg.contains("<script>")); | ||
| 189 | + assert!(svg.starts_with("<svg ")); | ||
| 190 | + } | ||
| 191 | + | ||
| 192 | + #[test] | ||
| 193 | + fn initials_are_the_first_letters_of_two_words() { | ||
| 194 | + let svg = initials_svg("ada lovelace byron", "seed"); | ||
| 195 | + assert!(svg.contains(">AL</text>"), "{svg}"); | ||
| 196 | + assert!(initials_svg(" ", "seed").contains(">?</text>")); | ||
| 197 | + } | ||
| 198 | +} | ||
crates/im-web/src/pages/preferences.rsadded+193 -0
| @@ -0,0 +1,193 @@ | |||
| 1 | +//! The preferences of the signed-in person: the interface language, the time zone and the theme. | ||
| 2 | +//! | ||
| 3 | +//! Every choice is checked against its list before it is stored: the language against `auto`, `en` | ||
| 4 | +//! and `tr`; the time zone against the IANA names compiled into the build; the theme against | ||
| 5 | +//! `system`, `light` and `dark`. The schema repeats the language and theme rules. The theme is | ||
| 6 | +//! applied as a class on `<html>` (see `views::shell`), never as an inline style. | ||
| 7 | + | ||
| 8 | +use im_core::model::AuditAction; | ||
| 9 | +use im_core::time::{is_zone, zone_names}; | ||
| 10 | +use serde::Deserialize; | ||
| 11 | +use serde_json::json; | ||
| 12 | +use topcoat::Result; | ||
| 13 | +use topcoat::context::{Cx, app_context}; | ||
| 14 | +use topcoat::router::content::Form; | ||
| 15 | +use topcoat::router::error::see_other; | ||
| 16 | +use topcoat::router::page; | ||
| 17 | +use topcoat::view::{View, view}; | ||
| 18 | + | ||
| 19 | +use crate::audit::{Actor, record}; | ||
| 20 | +use crate::auth::{Viewer, require_csrf, require_user}; | ||
| 21 | +use crate::i18n::Lang; | ||
| 22 | +use crate::i18n::account::{Txt, text}; | ||
| 23 | +use crate::live::Topic; | ||
| 24 | +use crate::state::AppState; | ||
| 25 | +use crate::views::{ViewerInfo, alert, notice, page_lang, shell}; | ||
| 26 | + | ||
| 27 | +/// The language choices. `auto` follows the browser; the others are stored as they are. | ||
| 28 | +const LANGUAGES: [&str; 3] = ["auto", "en", "tr"]; | ||
| 29 | + | ||
| 30 | +/// The theme choices, as stored in `users.theme`. | ||
| 31 | +const THEMES: [&str; 3] = ["system", "light", "dark"]; | ||
| 32 | + | ||
| 33 | +/// The query of `GET /account/preferences`. | ||
| 34 | +#[derive(Deserialize, Default)] | ||
| 35 | +struct PreferencesQuery { | ||
| 36 | + #[serde(default)] | ||
| 37 | + notice: String, | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +/// The preferences form. Every field defaults to empty, so a missing one is refused, not a 400. | ||
| 41 | +#[derive(Deserialize, Default)] | ||
| 42 | +struct PreferencesForm { | ||
| 43 | + #[serde(default)] | ||
| 44 | + csrf: String, | ||
| 45 | + #[serde(default)] | ||
| 46 | + language: String, | ||
| 47 | + #[serde(default)] | ||
| 48 | + zoneinfo: String, | ||
| 49 | + #[serde(default)] | ||
| 50 | + theme: String, | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// What the preferences page shows. | ||
| 54 | +struct PreferencesData { | ||
| 55 | + csrf: String, | ||
| 56 | + language: String, | ||
| 57 | + zoneinfo: String, | ||
| 58 | + theme: String, | ||
| 59 | + flash_notice: Option<String>, | ||
| 60 | + flash_alert: Option<String>, | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +impl PreferencesData { | ||
| 64 | + /// The stored preferences of `viewer`, with no notice and no alert. | ||
| 65 | + fn of(viewer: &Viewer) -> Self { | ||
| 66 | + Self { | ||
| 67 | + csrf: viewer.session.csrf_token.clone(), | ||
| 68 | + language: if viewer.user.locale_auto { | ||
| 69 | + "auto".to_owned() | ||
| 70 | + } else { | ||
| 71 | + viewer.user.locale.clone() | ||
| 72 | + }, | ||
| 73 | + zoneinfo: viewer.user.zoneinfo.clone(), | ||
| 74 | + theme: viewer.user.theme.clone(), | ||
| 75 | + flash_notice: None, | ||
| 76 | + flash_alert: None, | ||
| 77 | + } | ||
| 78 | + } | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +/// `GET /account/preferences`. | ||
| 82 | +#[page("/account/preferences")] | ||
| 83 | +async fn preferences_page(cx: &Cx, Form(query): Form<PreferencesQuery>) -> Result<impl View> { | ||
| 84 | + let viewer = require_user(cx).await?; | ||
| 85 | + let lang = page_lang(cx, Some(&viewer)); | ||
| 86 | + let mut data = PreferencesData::of(&viewer); | ||
| 87 | + if query.notice == "saved" { | ||
| 88 | + data.flash_notice = Some(text(lang, Txt::SavedPreferences).to_owned()); | ||
| 89 | + } | ||
| 90 | + Ok(preferences_view(cx, lang, ViewerInfo::of(&viewer), data)) | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +/// `POST /account/preferences`. | ||
| 94 | +#[page(POST "/account/preferences")] | ||
| 95 | +async fn save_preferences(cx: &Cx, Form(form): Form<PreferencesForm>) -> Result<impl View> { | ||
| 96 | + let viewer = require_csrf(cx, &form.csrf).await?; | ||
| 97 | + let state = app_context::<AppState>(cx); | ||
| 98 | + let lang = page_lang(cx, Some(&viewer)); | ||
| 99 | + | ||
| 100 | + let valid = LANGUAGES.contains(&form.language.as_str()) | ||
| 101 | + && THEMES.contains(&form.theme.as_str()) | ||
| 102 | + && is_zone(&form.zoneinfo); | ||
| 103 | + if !valid { | ||
| 104 | + let mut data = PreferencesData::of(&viewer); | ||
| 105 | + data.flash_alert = Some(text(lang, Txt::ErrPreferenceInvalid).to_owned()); | ||
| 106 | + return Ok(preferences_view(cx, lang, ViewerInfo::of(&viewer), data)); | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + // "Automatic" keeps the stored language value, which the schema requires to be a real one. | ||
| 110 | + let automatic = form.language == "auto"; | ||
| 111 | + let locale = if automatic { | ||
| 112 | + viewer.user.locale.as_str() | ||
| 113 | + } else { | ||
| 114 | + form.language.as_str() | ||
| 115 | + }; | ||
| 116 | + state | ||
| 117 | + .store | ||
| 118 | + .update_preferences( | ||
| 119 | + &viewer.user.id, | ||
| 120 | + locale, | ||
| 121 | + automatic, | ||
| 122 | + &form.zoneinfo, | ||
| 123 | + &form.theme, | ||
| 124 | + ) | ||
| 125 | + .await?; | ||
| 126 | + state.live.bump(&Topic::Account(viewer.user.id.clone())); | ||
| 127 | + record( | ||
| 128 | + cx, | ||
| 129 | + Actor::User(&viewer.user.id), | ||
| 130 | + AuditAction::PreferencesChanged, | ||
| 131 | + Some(("user", &viewer.user.id)), | ||
| 132 | + json!({ "language": form.language, "theme": form.theme }), | ||
| 133 | + ) | ||
| 134 | + .await; | ||
| 135 | + Err(see_other("/account/preferences?notice=saved").into()) | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +/// The preferences page markup. | ||
| 139 | +fn preferences_view(cx: &Cx, lang: Lang, info: ViewerInfo, data: PreferencesData) -> impl View { | ||
| 140 | + let PreferencesData { | ||
| 141 | + csrf, | ||
| 142 | + language, | ||
| 143 | + zoneinfo, | ||
| 144 | + theme, | ||
| 145 | + flash_notice, | ||
| 146 | + flash_alert, | ||
| 147 | + } = data; | ||
| 148 | + let zones = zone_names(); | ||
| 149 | + view! { cx => | ||
| 150 | + shell(title: text(lang, Txt::PreferencesTitle), lang: lang, viewer: Some(info), | ||
| 151 | + <section class="stack"> | ||
| 152 | + <h1>(text(lang, Txt::PreferencesTitle))</h1> | ||
| 153 | + <p class="muted">(text(lang, Txt::PreferencesIntro))</p> | ||
| 154 | + if let Some(message) = flash_notice { | ||
| 155 | + notice(message: message) | ||
| 156 | + } | ||
| 157 | + if let Some(message) = flash_alert { | ||
| 158 | + alert(message: message) | ||
| 159 | + } | ||
| 160 | + <section class="card stack"> | ||
| 161 | + <form method="post" action="/account/preferences" class="stack"> | ||
| 162 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 163 | + <label class="field"> | ||
| 164 | + <span class="field-label">(text(lang, Txt::LanguageLabel))</span> | ||
| 165 | + <select name="language"> | ||
| 166 | + <option value="auto" selected=(language == "auto")>(text(lang, Txt::LangAuto))</option> | ||
| 167 | + <option value="en" selected=(language == "en")>(text(lang, Txt::LangEnglish))</option> | ||
| 168 | + <option value="tr" selected=(language == "tr")>(text(lang, Txt::LangTurkish))</option> | ||
| 169 | + </select> | ||
| 170 | + </label> | ||
| 171 | + <label class="field"> | ||
| 172 | + <span class="field-label">(text(lang, Txt::TimeZoneLabel))</span> | ||
| 173 | + <select name="zoneinfo"> | ||
| 174 | + for zone in zones { | ||
| 175 | + <option value=(zone.clone()) selected=(zone == zoneinfo)>(zone)</option> | ||
| 176 | + } | ||
| 177 | + </select> | ||
| 178 | + </label> | ||
| 179 | + <label class="field"> | ||
| 180 | + <span class="field-label">(text(lang, Txt::ThemeLabel))</span> | ||
| 181 | + <select name="theme"> | ||
| 182 | + <option value="system" selected=(theme == "system")>(text(lang, Txt::ThemeSystem))</option> | ||
| 183 | + <option value="light" selected=(theme == "light")>(text(lang, Txt::ThemeLight))</option> | ||
| 184 | + <option value="dark" selected=(theme == "dark")>(text(lang, Txt::ThemeDark))</option> | ||
| 185 | + </select> | ||
| 186 | + </label> | ||
| 187 | + <button type="submit" class="button primary">(text(lang, Txt::SavePreferences))</button> | ||
| 188 | + </form> | ||
| 189 | + </section> | ||
| 190 | + </section> | ||
| 191 | + ) | ||
| 192 | + } | ||
| 193 | +} | ||
crates/im-web/src/pages/profile.rsadded+312 -0
| @@ -0,0 +1,312 @@ | |||
| 1 | +//! The profile of the signed-in person: the display name, the profile photo, and the email address. | ||
| 2 | +//! | ||
| 3 | +//! The email address is shown read-only until the mail step exists; changing it needs the | ||
| 4 | +//! confirmation links that mail carries. The photo is the only upload in `im` so far. Its bytes are | ||
| 5 | +//! read as a stream with a hard limit, and the CSRF field has to arrive before the first byte of the | ||
| 6 | +//! picture, so an upload from another site is refused before it is read at all. What is read is | ||
| 7 | +//! decoded and re-encoded by `im_core::photo` before anything is written. | ||
| 8 | + | ||
| 9 | +use im_core::model::AuditAction; | ||
| 10 | +use im_core::names::parse_display_name; | ||
| 11 | +use im_core::photo::{self, MAX_UPLOAD_BYTES, STORED_MIME}; | ||
| 12 | +use serde::Deserialize; | ||
| 13 | +use serde_json::json; | ||
| 14 | +use topcoat::Result; | ||
| 15 | +use topcoat::context::{Cx, app_context}; | ||
| 16 | +use topcoat::router::content::Form; | ||
| 17 | +use topcoat::router::content::multipart::Multipart; | ||
| 18 | +use topcoat::router::error::{SeeOther, see_other}; | ||
| 19 | +use topcoat::router::{page, route}; | ||
| 20 | +use topcoat::view::{View, view}; | ||
| 21 | + | ||
| 22 | +use crate::audit::{Actor, record}; | ||
| 23 | +use crate::auth::{Viewer, require_csrf, require_user}; | ||
| 24 | +use crate::i18n::Lang; | ||
| 25 | +use crate::i18n::account::{Txt, text}; | ||
| 26 | +use crate::live::Topic; | ||
| 27 | +use crate::pages::login::CsrfForm; | ||
| 28 | +use crate::state::AppState; | ||
| 29 | +use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; | ||
| 30 | + | ||
| 31 | +/// Path of the photo upload. The router raises the body limit for this path (see `boot.rs`). | ||
| 32 | +pub const PHOTO_ROUTE: &str = "/account/profile/photo"; | ||
| 33 | + | ||
| 34 | +/// The query of `GET /account/profile`. | ||
| 35 | +#[derive(Deserialize, Default)] | ||
| 36 | +struct ProfileQuery { | ||
| 37 | + #[serde(default)] | ||
| 38 | + notice: String, | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/// The name form. | ||
| 42 | +#[derive(Deserialize, Default)] | ||
| 43 | +struct NameForm { | ||
| 44 | + #[serde(default)] | ||
| 45 | + csrf: String, | ||
| 46 | + #[serde(default)] | ||
| 47 | + name: String, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// What the profile page shows. | ||
| 51 | +struct ProfileData { | ||
| 52 | + csrf: String, | ||
| 53 | + user_id: String, | ||
| 54 | + name: String, | ||
| 55 | + email: String, | ||
| 56 | + has_photo: bool, | ||
| 57 | + picture_version: i64, | ||
| 58 | + flash_notice: Option<String>, | ||
| 59 | + flash_alert: Option<String>, | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +impl ProfileData { | ||
| 63 | + /// The page data of `viewer`, with no notice and no alert. | ||
| 64 | + fn of(viewer: &Viewer) -> Self { | ||
| 65 | + Self { | ||
| 66 | + csrf: viewer.session.csrf_token.clone(), | ||
| 67 | + user_id: viewer.user.id.clone(), | ||
| 68 | + name: viewer.user.name.clone(), | ||
| 69 | + email: viewer.user.email.clone(), | ||
| 70 | + has_photo: viewer.user.photo_mime.is_some(), | ||
| 71 | + picture_version: viewer.user.picture_version, | ||
| 72 | + flash_notice: None, | ||
| 73 | + flash_alert: None, | ||
| 74 | + } | ||
| 75 | + } | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// `GET /account/profile`. | ||
| 79 | +#[page("/account/profile")] | ||
| 80 | +async fn profile_page(cx: &Cx, Form(query): Form<ProfileQuery>) -> Result<impl View> { | ||
| 81 | + let viewer = require_user(cx).await?; | ||
| 82 | + let lang = page_lang(cx, Some(&viewer)); | ||
| 83 | + let mut data = ProfileData::of(&viewer); | ||
| 84 | + data.flash_notice = match query.notice.as_str() { | ||
| 85 | + "saved-name" => Some(text(lang, Txt::SavedName).to_owned()), | ||
| 86 | + "saved-photo" => Some(text(lang, Txt::SavedPhoto).to_owned()), | ||
| 87 | + "removed-photo" => Some(text(lang, Txt::SavedPhotoRemoved).to_owned()), | ||
| 88 | + _ => None, | ||
| 89 | + }; | ||
| 90 | + Ok(profile_view(cx, lang, ViewerInfo::of(&viewer), data)) | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +/// `POST /account/profile/name`. | ||
| 94 | +#[page(POST "/account/profile/name")] | ||
| 95 | +async fn change_name(cx: &Cx, Form(form): Form<NameForm>) -> Result<impl View> { | ||
| 96 | + let viewer = require_csrf(cx, &form.csrf).await?; | ||
| 97 | + let state = app_context::<AppState>(cx); | ||
| 98 | + let lang = page_lang(cx, Some(&viewer)); | ||
| 99 | + let name = match parse_display_name(&form.name) { | ||
| 100 | + Ok(name) => name, | ||
| 101 | + Err(_) => { | ||
| 102 | + // The field keeps the stored name: the typed one may hold control characters. | ||
| 103 | + let mut data = ProfileData::of(&viewer); | ||
| 104 | + data.flash_alert = Some(text(lang, Txt::ErrNameInvalid).to_owned()); | ||
| 105 | + return Ok(profile_view(cx, lang, ViewerInfo::of(&viewer), data)); | ||
| 106 | + } | ||
| 107 | + }; | ||
| 108 | + state.store.update_name(&viewer.user.id, &name).await?; | ||
| 109 | + state.live.bump(&Topic::Account(viewer.user.id.clone())); | ||
| 110 | + record( | ||
| 111 | + cx, | ||
| 112 | + Actor::User(&viewer.user.id), | ||
| 113 | + AuditAction::NameChanged, | ||
| 114 | + Some(("user", &viewer.user.id)), | ||
| 115 | + json!({}), | ||
| 116 | + ) | ||
| 117 | + .await; | ||
| 118 | + Err(see_other("/account/profile?notice=saved-name").into()) | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +/// `POST /account/profile/photo`. A multipart form: the `csrf` field first, then the `photo` file. | ||
| 122 | +#[page(POST "/account/profile/photo")] | ||
| 123 | +async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result<impl View> { | ||
| 124 | + let state = app_context::<AppState>(cx); | ||
| 125 | + let mut token = String::new(); | ||
| 126 | + let mut checked: Option<Viewer> = None; | ||
| 127 | + let mut picture: Option<Vec<u8>> = None; | ||
| 128 | + let mut too_large = false; | ||
| 129 | + | ||
| 130 | + while let Some(mut part) = multipart.next_field().await? { | ||
| 131 | + let name = part.name().unwrap_or_default().to_owned(); | ||
| 132 | + match name.as_str() { | ||
| 133 | + "csrf" => token = part.text().await?, | ||
| 134 | + "photo" => { | ||
| 135 | + // Refused before any byte of the picture is read, unless the token is right. | ||
| 136 | + if checked.is_none() { | ||
| 137 | + checked = Some(require_csrf(cx, &token).await?); | ||
| 138 | + } | ||
| 139 | + let mut bytes = Vec::new(); | ||
| 140 | + while let Some(chunk) = part.chunk().await? { | ||
| 141 | + if bytes.len() + chunk.len() > MAX_UPLOAD_BYTES { | ||
| 142 | + too_large = true; | ||
| 143 | + break; | ||
| 144 | + } | ||
| 145 | + bytes.extend_from_slice(&chunk); | ||
| 146 | + } | ||
| 147 | + picture = Some(bytes); | ||
| 148 | + if too_large { | ||
| 149 | + break; | ||
| 150 | + } | ||
| 151 | + } | ||
| 152 | + _ => { | ||
| 153 | + part.bytes().await?; | ||
| 154 | + } | ||
| 155 | + } | ||
| 156 | + } | ||
| 157 | + | ||
| 158 | + let viewer = match checked { | ||
| 159 | + Some(viewer) => viewer, | ||
| 160 | + None => require_csrf(cx, &token).await?, | ||
| 161 | + }; | ||
| 162 | + let lang = page_lang(cx, Some(&viewer)); | ||
| 163 | + let problem = if too_large { | ||
| 164 | + Some(text(lang, Txt::ErrPhotoTooLarge)) | ||
| 165 | + } else { | ||
| 166 | + None | ||
| 167 | + }; | ||
| 168 | + let Some(bytes) = picture.filter(|_| problem.is_none()) else { | ||
| 169 | + let message = problem.unwrap_or(text(lang, Txt::ErrPhotoMissing)); | ||
| 170 | + return Ok(upload_problem(cx, lang, viewer, message)); | ||
| 171 | + }; | ||
| 172 | + | ||
| 173 | + // Decoding is CPU work and runs off the request threads. | ||
| 174 | + let stored = tokio::task::spawn_blocking(move || photo::normalize_photo(&bytes)) | ||
| 175 | + .await | ||
| 176 | + .map_err(|error| topcoat::Error::msg(error.to_string()))?; | ||
| 177 | + let stored = match stored { | ||
| 178 | + Ok(stored) => stored, | ||
| 179 | + Err(im_core::Error::Invalid(_)) => { | ||
| 180 | + return Ok(upload_problem( | ||
| 181 | + cx, | ||
| 182 | + lang, | ||
| 183 | + viewer, | ||
| 184 | + text(lang, Txt::ErrPhotoType), | ||
| 185 | + )); | ||
| 186 | + } | ||
| 187 | + Err(error) => return Err(error.into()), | ||
| 188 | + }; | ||
| 189 | + | ||
| 190 | + // The file first, then the row: the row only ever names a file that is already in place. | ||
| 191 | + let dir = state.config.data_dir.clone(); | ||
| 192 | + let user_id = viewer.user.id.clone(); | ||
| 193 | + let size = stored.len(); | ||
| 194 | + tokio::task::spawn_blocking(move || photo::write_photo(&dir, &user_id, &stored)) | ||
| 195 | + .await | ||
| 196 | + .map_err(|error| topcoat::Error::msg(error.to_string()))??; | ||
| 197 | + state.store.set_photo(&viewer.user.id, STORED_MIME).await?; | ||
| 198 | + state.live.bump(&Topic::Account(viewer.user.id.clone())); | ||
| 199 | + record( | ||
| 200 | + cx, | ||
| 201 | + Actor::User(&viewer.user.id), | ||
| 202 | + AuditAction::PhotoChanged, | ||
| 203 | + Some(("user", &viewer.user.id)), | ||
| 204 | + json!({ "stored_bytes": size }), | ||
| 205 | + ) | ||
| 206 | + .await; | ||
| 207 | + Err(see_other("/account/profile?notice=saved-photo").into()) | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +/// The profile page with an alert about the upload. Takes its values by value, so the page does not | ||
| 211 | +/// borrow from the request's locals. | ||
| 212 | +fn upload_problem(cx: &Cx, lang: Lang, viewer: Viewer, message: &str) -> impl View { | ||
| 213 | + let mut data = ProfileData::of(&viewer); | ||
| 214 | + data.flash_alert = Some(message.to_owned()); | ||
| 215 | + profile_view(cx, lang, ViewerInfo::of(&viewer), data) | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +/// `POST /account/profile/photo/remove`. The row changes first; the file goes after it. | ||
| 219 | +#[route(POST "/account/profile/photo/remove")] | ||
| 220 | +async fn remove_photo(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | ||
| 221 | + let viewer = require_csrf(cx, &form.csrf).await?; | ||
| 222 | + let state = app_context::<AppState>(cx); | ||
| 223 | + if state.store.clear_photo(&viewer.user.id).await? { | ||
| 224 | + state.live.bump(&Topic::Account(viewer.user.id.clone())); | ||
| 225 | + let dir = state.config.data_dir.clone(); | ||
| 226 | + let user_id = viewer.user.id.clone(); | ||
| 227 | + let removed = tokio::task::spawn_blocking(move || photo::remove_photo(&dir, &user_id)) | ||
| 228 | + .await | ||
| 229 | + .map_err(|error| topcoat::Error::msg(error.to_string()))?; | ||
| 230 | + if let Err(error) = removed { | ||
| 231 | + // The row no longer names the file, so a leftover file is never served. | ||
| 232 | + tracing::error!(error = %error, "removed photo file could not be deleted"); | ||
| 233 | + } | ||
| 234 | + record( | ||
| 235 | + cx, | ||
| 236 | + Actor::User(&viewer.user.id), | ||
| 237 | + AuditAction::PhotoRemoved, | ||
| 238 | + Some(("user", &viewer.user.id)), | ||
| 239 | + json!({}), | ||
| 240 | + ) | ||
| 241 | + .await; | ||
| 242 | + } | ||
| 243 | + Ok(see_other("/account/profile?notice=removed-photo")) | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +/// The profile page markup. | ||
| 247 | +fn profile_view(cx: &Cx, lang: Lang, info: ViewerInfo, data: ProfileData) -> impl View { | ||
| 248 | + let ProfileData { | ||
| 249 | + csrf, | ||
| 250 | + user_id, | ||
| 251 | + name, | ||
| 252 | + email, | ||
| 253 | + has_photo, | ||
| 254 | + picture_version, | ||
| 255 | + flash_notice, | ||
| 256 | + flash_alert, | ||
| 257 | + } = data; | ||
| 258 | + let photo_src = format!("/photo/{user_id}?v={picture_version}"); | ||
| 259 | + view! { cx => | ||
| 260 | + shell(title: text(lang, Txt::ProfileTitle), lang: lang, viewer: Some(info), | ||
| 261 | + <section class="stack"> | ||
| 262 | + <h1>(text(lang, Txt::ProfileTitle))</h1> | ||
| 263 | + <p class="muted">(text(lang, Txt::ProfileIntro))</p> | ||
| 264 | + if let Some(message) = flash_notice { | ||
| 265 | + notice(message: message) | ||
| 266 | + } | ||
| 267 | + if let Some(message) = flash_alert { | ||
| 268 | + alert(message: message) | ||
| 269 | + } | ||
| 270 | + | ||
| 271 | + <section class="card stack"> | ||
| 272 | + <h2>(text(lang, Txt::PhotoSection))</h2> | ||
| 273 | + <div class="profile-photo"> | ||
| 274 | + <img class="avatar-large" src=(photo_src) alt=(text(lang, Txt::PhotoAlt)) width="128" height="128"> | ||
| 275 | + </div> | ||
| 276 | + <p class="muted">(text(lang, Txt::PhotoHelp))</p> | ||
| 277 | + <form method="post" action="/account/profile/photo" enctype="multipart/form-data" class="stack"> | ||
| 278 | + <input type="hidden" name="csrf" value=(csrf.clone())> | ||
| 279 | + <label class="field"> | ||
| 280 | + <span class="field-label">(text(lang, Txt::PhotoFile))</span> | ||
| 281 | + <input type="file" name="photo" accept="image/png,image/jpeg,image/webp,image/gif" required=""> | ||
| 282 | + </label> | ||
| 283 | + <button type="submit" class="button primary">(text(lang, Txt::PhotoUpload))</button> | ||
| 284 | + </form> | ||
| 285 | + if has_photo { | ||
| 286 | + <form method="post" action="/account/profile/photo/remove" class="stack"> | ||
| 287 | + <input type="hidden" name="csrf" value=(csrf.clone())> | ||
| 288 | + <p class="muted">(text(lang, Txt::PhotoRemoveHelp))</p> | ||
| 289 | + <button type="submit" class="button ghost">(text(lang, Txt::PhotoRemove))</button> | ||
| 290 | + </form> | ||
| 291 | + } | ||
| 292 | + </section> | ||
| 293 | + | ||
| 294 | + <section class="card stack"> | ||
| 295 | + <h2>(text(lang, Txt::Name))</h2> | ||
| 296 | + <form method="post" action="/account/profile/name" class="stack"> | ||
| 297 | + <input type="hidden" name="csrf" value=(csrf.clone())> | ||
| 298 | + field(label: text(lang, Txt::Name), name: "name", kind: "text", autocomplete: "name", value: name) | ||
| 299 | + <p class="hint">(text(lang, Txt::NameHelp))</p> | ||
| 300 | + <button type="submit" class="button primary">(text(lang, Txt::SaveName))</button> | ||
| 301 | + </form> | ||
| 302 | + </section> | ||
| 303 | + | ||
| 304 | + <section class="card stack"> | ||
| 305 | + <h2>(text(lang, Txt::Email))</h2> | ||
| 306 | + <p>(email)</p> | ||
| 307 | + <p class="muted">(text(lang, Txt::EmailLaterNote))</p> | ||
| 308 | + </section> | ||
| 309 | + </section> | ||
| 310 | + ) | ||
| 311 | + } | ||
| 312 | +} | ||
crates/im-web/src/pages/setup.rsmodified+25 -16
| @@ -3,7 +3,7 @@ | |||
| 3 | //! reveal that the instance was set up. | 3 | //! reveal that the instance was set up. |
| 4 | 4 | ||
| 5 | use im_core::model::{AuditAction, amr}; | 5 | use im_core::model::{AuditAction, amr}; |
| 6 | -use im_core::names::{normalize_email, parse_email}; | 6 | +use im_core::names::{normalize_email, parse_display_name, parse_email}; |
| 7 | use im_core::password::{check_policy, hash_password_async}; | 7 | use im_core::password::{check_policy, hash_password_async}; |
| 8 | use serde::Deserialize; | 8 | use serde::Deserialize; |
| 9 | use serde_json::Value; | 9 | use serde_json::Value; |
| @@ -67,24 +67,33 @@ async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View> | |||
| 67 | } | 67 | } |
| 68 | let csrf = pre_csrf_token(cx); | 68 | let csrf = pre_csrf_token(cx); |
| 69 | let lang = page_lang(cx, None); | 69 | let lang = page_lang(cx, None); |
| 70 | - let name = form.name.trim().to_owned(); | ||
| 71 | let typed_email = form.email.clone(); | 70 | let typed_email = form.email.clone(); |
| 72 | 71 | ||
| 73 | - let problem = | 72 | + // A refused name is not shown back: it may hold control characters, which must not reach HTML. |
| 74 | - if name.is_empty() || name.chars().count() > 200 || name.chars().any(char::is_control) { | 73 | + let name = match parse_display_name(&form.name) { |
| 75 | - Some(text(lang, Txt::ErrNameInvalid).to_owned()) | 74 | + Ok(name) => name, |
| 76 | - } else { | 75 | + Err(_) => { |
| 77 | - match parse_email(&normalize_email(&form.email)) { | 76 | + let problem = text(lang, Txt::ErrNameInvalid).to_owned(); |
| 78 | - Err(_) => Some(text(lang, Txt::ErrEmailInvalid).to_owned()), | 77 | + return Ok(setup_view( |
| 79 | - Ok(email) => match check_policy(&form.password, &email, &name) { | 78 | + cx, |
| 80 | - Err(violation) => Some(policy_problem(lang, violation)), | 79 | + lang, |
| 81 | - Ok(()) if form.password != form.password_again => { | 80 | + csrf, |
| 82 | - Some(text(lang, Txt::ErrPasswordsDiffer).to_owned()) | 81 | + String::new(), |
| 83 | - } | 82 | + typed_email, |
| 84 | - Ok(()) => None, | 83 | + Some(problem), |
| 85 | - }, | 84 | + )); |
| 85 | + } | ||
| 86 | + }; | ||
| 87 | + let problem = match parse_email(&normalize_email(&form.email)) { | ||
| 88 | + Err(_) => Some(text(lang, Txt::ErrEmailInvalid).to_owned()), | ||
| 89 | + Ok(email) => match check_policy(&form.password, &email, &name) { | ||
| 90 | + Err(violation) => Some(policy_problem(lang, violation)), | ||
| 91 | + Ok(()) if form.password != form.password_again => { | ||
| 92 | + Some(text(lang, Txt::ErrPasswordsDiffer).to_owned()) | ||
| 86 | } | 93 | } |
| 87 | - }; | 94 | + Ok(()) => None, |
| 95 | + }, | ||
| 96 | + }; | ||
| 88 | if let Some(problem) = problem { | 97 | if let Some(problem) = problem { |
| 89 | return Ok(setup_view(cx, lang, csrf, name, typed_email, Some(problem))); | 98 | return Ok(setup_view(cx, lang, csrf, name, typed_email, Some(problem))); |
| 90 | } | 99 | } |
crates/im-web/src/pages/tests.rsmodified+3 -2
| @@ -5,7 +5,7 @@ use std::time::Duration; | |||
| 5 | 5 | ||
| 6 | use http::header::{CONTENT_TYPE, COOKIE}; | 6 | use http::header::{CONTENT_TYPE, COOKIE}; |
| 7 | use im_core::password::hash_password; | 7 | use im_core::password::hash_password; |
| 8 | -use im_core::store::sessions::NewSession; | 8 | +use im_core::store::sessions::{NewSession, SESSION_IDLE}; |
| 9 | use im_core::token::{generate_token, hash_token}; | 9 | use im_core::token::{generate_token, hash_token}; |
| 10 | use topcoat::router::{Body, to_bytes}; | 10 | use topcoat::router::{Body, to_bytes}; |
| 11 | 11 | ||
| @@ -50,7 +50,8 @@ async fn signed_in(state: &AppState) -> String { | |||
| 50 | amr: "pwd", | 50 | amr: "pwd", |
| 51 | ip: None, | 51 | ip: None, |
| 52 | user_agent: None, | 52 | user_agent: None, |
| 53 | - ttl: Duration::from_secs(3600), | 53 | + idle: SESSION_IDLE, |
| 54 | + max_age: Duration::from_secs(3600), | ||
| 54 | }, | 55 | }, |
| 55 | 10, | 56 | 10, |
| 56 | ) | 57 | ) |
crates/im-web/src/security.rsmodified+63 -5
| @@ -1,11 +1,18 @@ | |||
| 1 | -//! The security headers of every response, and the Content-Security-Policy they carry. | 1 | +//! The security headers of every response, the cache policy that goes with them, and the |
| 2 | +//! Content-Security-Policy they carry. | ||
| 2 | //! | 3 | //! |
| 3 | //! The policy allows scripts and styles from the origin itself and nothing else. No page may use an | 4 | //! The policy allows scripts and styles from the origin itself and nothing else. No page may use an |
| 4 | //! inline script, an inline style or an inline event handler: all behaviour lives in | 5 | //! inline script, an inline style or an inline event handler: all behaviour lives in |
| 5 | //! `crates/im-web/assets/*.js`. Changing [`CSP`] is a security change, so keep it in step with | 6 | //! `crates/im-web/assets/*.js`. Changing [`CSP`] is a security change, so keep it in step with |
| 6 | //! `docs/conventions.md` section 5. | 7 | //! `docs/conventions.md` section 5. |
| 8 | +//! | ||
| 9 | +//! Cache policy by path: pages (everything that is not a static asset or a photo) are `no-store`, | ||
| 10 | +//! so a page with a secret (recovery codes, a TOTP secret) is never kept by a browser or a proxy. | ||
| 11 | +//! Assets set their own long-lived policy. Photos set their own `private` policy and their own CSP | ||
| 12 | +//! (see `pages/photo.rs`), so this layer leaves both alone. | ||
| 7 | 13 | ||
| 8 | use topcoat::context::Cx; | 14 | use topcoat::context::Cx; |
| 15 | +use topcoat::router::request::uri; | ||
| 9 | use topcoat::router::response::response_headers; | 16 | use topcoat::router::response::response_headers; |
| 10 | use topcoat::router::{Body, HeaderMap, HeaderValue, Layer, LayerFuture, Next, Path, header}; | 17 | use topcoat::router::{Body, HeaderMap, HeaderValue, Layer, LayerFuture, Next, Path, header}; |
| 11 | 18 | ||
| @@ -16,6 +23,9 @@ pub const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self | |||
| 16 | /// One year, in seconds. Sent only when the public origin is https. | 23 | /// One year, in seconds. Sent only when the public origin is https. |
| 17 | const HSTS: &str = "max-age=31536000"; | 24 | const HSTS: &str = "max-age=31536000"; |
| 18 | 25 | ||
| 26 | +/// The cache policy of every page: nothing is stored, not even for going back in the history. | ||
| 27 | +const NO_STORE: &str = "no-store"; | ||
| 28 | + | ||
| 19 | /// The headers that every response carries, for an instance at `base_url`. | 29 | /// The headers that every response carries, for an instance at `base_url`. |
| 20 | pub fn headers_for(base_url: &str) -> HeaderMap { | 30 | pub fn headers_for(base_url: &str) -> HeaderMap { |
| 21 | let mut headers = HeaderMap::new(); | 31 | let mut headers = HeaderMap::new(); |
| @@ -41,18 +51,47 @@ pub fn headers_for(base_url: &str) -> HeaderMap { | |||
| 41 | headers | 51 | headers |
| 42 | } | 52 | } |
| 43 | 53 | ||
| 44 | -/// Adds a fixed set of headers to every response of the router. | 54 | +/// What kind of answer a path gets, which decides its headers. |
| 55 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 56 | +pub enum Answer { | ||
| 57 | + /// A static file under `/assets/`, with its own cache policy. | ||
| 58 | + Asset, | ||
| 59 | + /// A profile photo under `/photo/`, with its own cache policy and its own CSP. | ||
| 60 | + Photo, | ||
| 61 | + /// Everything else: pages, forms, streams. Never stored. | ||
| 62 | + Page, | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +/// The kind of answer for a request path. | ||
| 66 | +pub fn answer_for(path: &str) -> Answer { | ||
| 67 | + if path.starts_with("/assets/") { | ||
| 68 | + Answer::Asset | ||
| 69 | + } else if path.starts_with("/photo/") { | ||
| 70 | + Answer::Photo | ||
| 71 | + } else { | ||
| 72 | + Answer::Page | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// Adds the security headers to every response, and `Cache-Control: no-store` to every page. | ||
| 45 | /// | 77 | /// |
| 46 | /// It uses the per-request response headers, which the router applies after the layers have run, | 78 | /// It uses the per-request response headers, which the router applies after the layers have run, |
| 47 | -/// so error responses (404, 500) carry them as well. | 79 | +/// so error responses (404, 500) carry them as well. A photo gets the same headers without the |
| 80 | +/// page CSP, because the photo handler sends a stricter one of its own. | ||
| 48 | pub struct SecurityHeaders { | 81 | pub struct SecurityHeaders { |
| 49 | headers: HeaderMap, | 82 | headers: HeaderMap, |
| 83 | + photo_headers: HeaderMap, | ||
| 50 | } | 84 | } |
| 51 | 85 | ||
| 52 | impl SecurityHeaders { | 86 | impl SecurityHeaders { |
| 53 | /// A layer that adds `headers` to every response. | 87 | /// A layer that adds `headers` to every response. |
| 54 | pub fn new(headers: HeaderMap) -> Self { | 88 | pub fn new(headers: HeaderMap) -> Self { |
| 55 | - Self { headers } | 89 | + let mut photo_headers = headers.clone(); |
| 90 | + photo_headers.remove(header::CONTENT_SECURITY_POLICY); | ||
| 91 | + Self { | ||
| 92 | + headers, | ||
| 93 | + photo_headers, | ||
| 94 | + } | ||
| 56 | } | 95 | } |
| 57 | } | 96 | } |
| 58 | 97 | ||
| @@ -63,7 +102,15 @@ impl Layer for SecurityHeaders { | |||
| 63 | 102 | ||
| 64 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { | 103 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { |
| 65 | Box::pin(async move { | 104 | Box::pin(async move { |
| 66 | - response_headers(cx).extend(self.headers.clone()); | 105 | + let answer = answer_for(uri(cx).path()); |
| 106 | + let mut headers = match answer { | ||
| 107 | + Answer::Photo => self.photo_headers.clone(), | ||
| 108 | + Answer::Asset | Answer::Page => self.headers.clone(), | ||
| 109 | + }; | ||
| 110 | + if answer == Answer::Page { | ||
| 111 | + headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE)); | ||
| 112 | + } | ||
| 113 | + response_headers(cx).extend(headers); | ||
| 67 | next.run(cx, body).await | 114 | next.run(cx, body).await |
| 68 | }) | 115 | }) |
| 69 | } | 116 | } |
| @@ -73,6 +120,17 @@ impl Layer for SecurityHeaders { | |||
| 73 | mod tests { | 120 | mod tests { |
| 74 | use super::*; | 121 | use super::*; |
| 75 | 122 | ||
| 123 | + #[test] | ||
| 124 | + fn only_pages_are_marked_no_store() { | ||
| 125 | + assert_eq!(answer_for("/login"), Answer::Page); | ||
| 126 | + assert_eq!(answer_for("/account/profile"), Answer::Page); | ||
| 127 | + assert_eq!(answer_for("/setup"), Answer::Page); | ||
| 128 | + assert_eq!(answer_for("/photo/01HZ"), Answer::Photo); | ||
| 129 | + assert_eq!(answer_for("/assets/main.css"), Answer::Asset); | ||
| 130 | + // A prefix match on the segment only: a page whose name starts the same is still a page. | ||
| 131 | + assert_eq!(answer_for("/photographs"), Answer::Page); | ||
| 132 | + } | ||
| 133 | + | ||
| 76 | #[test] | 134 | #[test] |
| 77 | fn hsts_only_for_https_origins() { | 135 | fn hsts_only_for_https_origins() { |
| 78 | assert!( | 136 | assert!( |
crates/im-web/src/views/mod.rsmodified+21 -3
| @@ -21,6 +21,8 @@ pub struct ViewerInfo { | |||
| 21 | pub is_admin: bool, | 21 | pub is_admin: bool, |
| 22 | /// The session's CSRF token, for the sign-out form in the menu. | 22 | /// The session's CSRF token, for the sign-out form in the menu. |
| 23 | pub csrf: String, | 23 | pub csrf: String, |
| 24 | + /// `system`, `light` or `dark`. Becomes a class on `<html>`. | ||
| 25 | + pub theme: String, | ||
| 24 | } | 26 | } |
| 25 | 27 | ||
| 26 | impl ViewerInfo { | 28 | impl ViewerInfo { |
| @@ -30,14 +32,25 @@ impl ViewerInfo { | |||
| 30 | name: viewer.user.name.clone(), | 32 | name: viewer.user.name.clone(), |
| 31 | is_admin: viewer.user.is_admin, | 33 | is_admin: viewer.user.is_admin, |
| 32 | csrf: viewer.session.csrf_token.clone(), | 34 | csrf: viewer.session.csrf_token.clone(), |
| 35 | + theme: viewer.user.theme.clone(), | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + | ||
| 39 | + /// The class of `<html>` for this theme. Anything unknown falls back to the device's choice. | ||
| 40 | + pub fn theme_class(&self) -> &'static str { | ||
| 41 | + match self.theme.as_str() { | ||
| 42 | + "light" => "theme-light", | ||
| 43 | + "dark" => "theme-dark", | ||
| 44 | + _ => "theme-system", | ||
| 33 | } | 45 | } |
| 34 | } | 46 | } |
| 35 | } | 47 | } |
| 36 | 48 | ||
| 37 | -/// The language of a page: the signed-in person's stored choice when they have one, else the | 49 | +/// The language of a page: the signed-in person's stored choice when they have one and have not |
| 38 | -/// request's `Accept-Language`. | 50 | +/// chosen "automatic", else the request's `Accept-Language`. |
| 39 | pub fn page_lang(cx: &Cx, viewer: Option<&Viewer>) -> Lang { | 51 | pub fn page_lang(cx: &Cx, viewer: Option<&Viewer>) -> Lang { |
| 40 | let stored = viewer | 52 | let stored = viewer |
| 53 | + .filter(|viewer| !viewer.user.locale_auto) | ||
| 41 | .map(|viewer| viewer.user.locale.as_str()) | 54 | .map(|viewer| viewer.user.locale.as_str()) |
| 42 | .filter(|locale| !locale.is_empty()); | 55 | .filter(|locale| !locale.is_empty()); |
| 43 | request_lang(cx, stored) | 56 | request_lang(cx, stored) |
| @@ -56,9 +69,12 @@ pub async fn shell( | |||
| 56 | #[default] child: Child<'_>, | 69 | #[default] child: Child<'_>, |
| 57 | ) -> Result<impl View> { | 70 | ) -> Result<impl View> { |
| 58 | let document_title = format!("{title} \u{b7} im"); | 71 | let document_title = format!("{title} \u{b7} im"); |
| 72 | + let theme_class = viewer | ||
| 73 | + .as_ref() | ||
| 74 | + .map_or("theme-system", ViewerInfo::theme_class); | ||
| 59 | Ok(view! { | 75 | Ok(view! { |
| 60 | <!DOCTYPE html> | 76 | <!DOCTYPE html> |
| 61 | - <html lang=(lang.code()) data-theme="system"> | 77 | + <html lang=(lang.code()) class=(theme_class)> |
| 62 | <head> | 78 | <head> |
| 63 | <meta charset="utf-8"> | 79 | <meta charset="utf-8"> |
| 64 | <meta name="viewport" content="width=device-width, initial-scale=1"> | 80 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| @@ -99,6 +115,8 @@ pub async fn user_menu(lang: Lang, viewer: ViewerInfo) -> Result<impl View> { | |||
| 99 | </summary> | 115 | </summary> |
| 100 | <div class="user-menu-panel"> | 116 | <div class="user-menu-panel"> |
| 101 | <nav class="user-menu-links" aria-label=(text(lang, Txt::AccountMenu))> | 117 | <nav class="user-menu-links" aria-label=(text(lang, Txt::AccountMenu))> |
| 118 | + <a href="/account/profile">(text(lang, Txt::ProfileTitle))</a> | ||
| 119 | + <a href="/account/preferences">(text(lang, Txt::PreferencesTitle))</a> | ||
| 102 | <a href="/account/security">(text(lang, Txt::SecurityTitle))</a> | 120 | <a href="/account/security">(text(lang, Txt::SecurityTitle))</a> |
| 103 | <a href="/account/sessions">(text(lang, Txt::SessionsTitle))</a> | 121 | <a href="/account/sessions">(text(lang, Txt::SessionsTitle))</a> |
| 104 | if viewer.is_admin { | 122 | if viewer.is_admin { |
style/_components.scssmodified+23 -0
| @@ -485,3 +485,26 @@ textarea::placeholder { | |||
| 485 | .user-menu-logout { | 485 | .user-menu-logout { |
| 486 | margin: 0; | 486 | margin: 0; |
| 487 | } | 487 | } |
| 488 | + | ||
| 489 | +/* Profile photos. The picture is always square; the initials image is served the same way. */ | ||
| 490 | +.avatar { | ||
| 491 | + width: 4rem; | ||
| 492 | + height: 4rem; | ||
| 493 | + border-radius: 50%; | ||
| 494 | + object-fit: cover; | ||
| 495 | + flex: none; | ||
| 496 | +} | ||
| 497 | + | ||
| 498 | +.avatar-large { | ||
| 499 | + width: 8rem; | ||
| 500 | + height: 8rem; | ||
| 501 | + border-radius: 50%; | ||
| 502 | + object-fit: cover; | ||
| 503 | +} | ||
| 504 | + | ||
| 505 | +.profile-photo { | ||
| 506 | + display: flex; | ||
| 507 | + align-items: center; | ||
| 508 | + gap: var(--space-4); | ||
| 509 | + flex-wrap: wrap; | ||
| 510 | +} | ||
style/_tokens.scssmodified+3 -3
| @@ -2,7 +2,7 @@ | |||
| 2 | //! partial reads these custom properties, so a theme changes in one place. | 2 | //! partial reads these custom properties, so a theme changes in one place. |
| 3 | //! | 3 | //! |
| 4 | //! Dark applies in two cases. The OS asks for it (`prefers-color-scheme: dark`) and the page is not | 4 | //! Dark applies in two cases. The OS asks for it (`prefers-color-scheme: dark`) and the page is not |
| 5 | -//! forced to light, or the page sets `data-theme="dark"`. `data-theme="light"` forces light whatever | 5 | +//! forced to light, or the page sets the class `theme-dark`. The class `theme-light` forces light whatever |
| 6 | //! the OS says. The dark rules carry one more attribute than the light ones, so they win on the same | 6 | //! the OS says. The dark rules carry one more attribute than the light ones, so they win on the same |
| 7 | //! element without `!important`. | 7 | //! element without `!important`. |
| 8 | 8 | ||
| @@ -78,13 +78,13 @@ | |||
| 78 | } | 78 | } |
| 79 | 79 | ||
| 80 | @media (prefers-color-scheme: dark) { | 80 | @media (prefers-color-scheme: dark) { |
| 81 | - :root:not([data-theme="light"]) { | 81 | + :root:not(.theme-light) { |
| 82 | color-scheme: dark; | 82 | color-scheme: dark; |
| 83 | @include dark-tokens; | 83 | @include dark-tokens; |
| 84 | } | 84 | } |
| 85 | } | 85 | } |
| 86 | 86 | ||
| 87 | -:root[data-theme="dark"] { | 87 | +:root.theme-dark { |
| 88 | color-scheme: dark; | 88 | color-scheme: dark; |
| 89 | @include dark-tokens; | 89 | @include dark-tokens; |
| 90 | } | 90 | } |