diff --git a/Cargo.lock b/Cargo.lock index 3e8de2c..c8c5852 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -57,6 +57,18 @@ dependencies = [ "subtle", ] +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -87,6 +99,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "antithesis_sdk" version = "0.3.0" @@ -109,6 +171,12 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "anymap3" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9" + [[package]] name = "arc-swap" version = "1.9.3" @@ -167,6 +235,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "autocfg" version = "1.5.1" @@ -260,7 +334,16 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" dependencies = [ - "digest", + "digest 0.11.3", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", ] [[package]] @@ -366,7 +449,7 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" dependencies = [ - "nom", + "nom 7.1.3", ] [[package]] @@ -440,7 +523,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ - "block-buffer", + "block-buffer 0.12.1", "crypto-common 0.2.2", "inout 0.2.5", ] @@ -456,12 +539,51 @@ dependencies = [ "libloading", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + [[package]] name = "cmov" version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]] +name = "codemap" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e769b5c8c8283982a987c6e948e540254f1058d5a74b8794914d4ef5fc2a24" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -477,12 +599,36 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "aes-gcm", + "base64 0.22.1", + "hkdf", + "hmac", + "percent-encoding", + "rand 0.8.8", + "sha2 0.10.9", + "subtle", + "time", + "version_check", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -608,7 +754,7 @@ dependencies = [ "cfg-if", "cpufeatures 0.3.1", "curve25519-dalek-derive", - "digest", + "digest 0.11.3", "fiat-crypto", "rand_core 0.10.1", "rustc_version", @@ -661,6 +807,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "datasketches" version = "0.2.0" @@ -676,13 +828,24 @@ dependencies = [ "serde_core", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", + "subtle", +] + [[package]] name = "digest" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer", + "block-buffer 0.12.1", "const-oid", "crypto-common 0.2.2", "ctutils", @@ -723,7 +886,7 @@ dependencies = [ "curve25519-dalek", "ed25519", "rand_core 0.10.1", - "sha2", + "sha2 0.11.1", "signature", "subtle", "zeroize", @@ -735,6 +898,45 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +[[package]] +name = "elsa" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9abf33c656a7256451ebb7d0082c5a471820c31269e49d807c538c252352186e" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "email-encoding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "420b9da095f052ea597503e39073b5b3c522f7db933fbac202d91d24492693fd" +dependencies = [ + "base64 0.23.1", + "memchr", +] + +[[package]] +name = "email_address" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" + +[[package]] +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "env_filter" version = "2.0.0" @@ -835,6 +1037,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "fs4" version = "0.13.1" @@ -851,6 +1062,15 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -868,6 +1088,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" version = "0.3.34" @@ -882,6 +1108,7 @@ checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", "futures-macro", + "futures-sink", "futures-task", "pin-project-lite", "slab", @@ -984,6 +1211,60 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" +[[package]] +name = "grass" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7a68216437ef68f0738e48d6c7bb9e6e6a92237e001b03d838314b068f33c94" +dependencies = [ + "clap", + "getrandom 0.2.17", + "grass_compiler", +] + +[[package]] +name = "grass_compiler" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d9e3df7f0222ce5184154973d247c591d9aadc28ce7a73c6cd31100c9facff6" +dependencies = [ + "codemap", + "indexmap", + "lasso", + "once_cell", + "phf", + "rand 0.8.8", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", + "allocator-api2 0.2.21", +] + [[package]] name = "hashbrown" version = "0.16.1" @@ -1019,6 +1300,24 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "home" version = "0.5.12" @@ -1028,6 +1327,17 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "hostname" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" +dependencies = [ + "cfg-if", + "libc", + "windows-link", +] + [[package]] name = "htmlescape" version = "0.3.1" @@ -1044,6 +1354,41 @@ dependencies = [ "itoa", ] +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -1053,6 +1398,41 @@ dependencies = [ "typenum", ] +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -1239,19 +1619,40 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] -name = "im-core" -version = "0.1.0" +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" dependencies = [ - "argon2", - "base64 0.23.1", - "chacha20poly1305", - "ed25519-dalek", - "hex", - "ipnet", - "rand 0.10.3", - "serde", + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "im-core" +version = "0.1.0" +dependencies = [ + "argon2", + "base64 0.23.1", + "chacha20poly1305", + "ed25519-dalek", + "hex", + "ipnet", + "rand 0.10.3", + "serde", "serde_json", - "sha2", + "sha2 0.11.1", "subtle", "tempfile", "thiserror", @@ -1266,6 +1667,20 @@ dependencies = [ [[package]] name = "im-web" version = "0.1.0" +dependencies = [ + "futures-util", + "grass", + "hex", + "http", + "im-core", + "serde", + "sha2 0.11.1", + "tempfile", + "tokio", + "topcoat", + "tracing", + "tracing-subscriber", +] [[package]] name = "indexmap" @@ -1330,6 +1745,12 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.12.1" @@ -1375,6 +1796,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "lasso" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e14eda50a3494b3bf7b9ce51c52434a761e383d7238ce1dd5dcec2fbc13e9fb" +dependencies = [ + "hashbrown 0.14.5", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -1387,6 +1817,23 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" +[[package]] +name = "lettre" +version = "0.11.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae" +dependencies = [ + "email-encoding", + "email_address", + "fastrand", + "hostname", + "httpdate", + "idna", + "mime", + "nom 8.0.0", + "quoted_printable", +] + [[package]] name = "levenshtein_automata" version = "0.2.1" @@ -1514,6 +1961,12 @@ dependencies = [ "regex-automata", ] +[[package]] +name = "matchit" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8863b587001c1b9a8a4e36008cebc6b3612cb1226fe2de94858e06092687b608" + [[package]] name = "measure_time" version = "0.9.0" @@ -1578,12 +2031,52 @@ dependencies = [ "libmimalloc-sys", ] +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + [[package]] name = "minimal-lexical" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "murmurhash32" version = "0.3.1" @@ -1600,6 +2093,15 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -1649,6 +2151,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "oneshot" version = "0.1.13" @@ -1733,6 +2241,12 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + [[package]] name = "phc" version = "0.6.1" @@ -1744,6 +2258,48 @@ dependencies = [ "getrandom 0.4.3", ] +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared", + "rand 0.8.8", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -1838,6 +2394,15 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -1879,6 +2444,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "quoted_printable" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478e0585659a122aa407eb7e3c0e1fa51b1d8a870038bd29f0cf4a8551eea972" + [[package]] name = "r-efi" version = "5.3.0" @@ -2020,6 +2591,26 @@ dependencies = [ "bitflags", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "regex" version = "1.13.1" @@ -2199,6 +2790,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_spanned" version = "1.1.2" @@ -2208,12 +2810,46 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha1_smol" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha2" version = "0.11.1" @@ -2222,7 +2858,7 @@ checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", "cpufeatures 0.3.1", - "digest", + "digest 0.11.3", ] [[package]] @@ -2266,6 +2902,16 @@ dependencies = [ "tracing", ] +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "signature" version = "3.0.0" @@ -2317,12 +2963,28 @@ version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "softaes" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4fdfe13e1c42e45f497416afb8dc4e783bf0e25b7be9077c1c77c5fb14cb998" +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -2511,7 +3173,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfadb8526b6da90704feb293b0701a6aae62ea14983143344be2dc5ce30f1d82" dependencies = [ "fnv", - "nom", + "nom 7.1.3", "ordered-float", "serde", "serde_json", @@ -2645,8 +3307,14 @@ version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ + "bytes", + "libc", + "mio", "pin-project-lite", + "signal-hook-registry", + "socket2", "tokio-macros", + "windows-sys 0.61.2", ] [[package]] @@ -2660,6 +3328,32 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + [[package]] name = "toml" version = "1.1.8+spec-1.1.0" @@ -2684,6 +3378,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + [[package]] name = "toml_parser" version = "1.1.5+spec-1.1.0" @@ -2699,6 +3405,336 @@ version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" +[[package]] +name = "topcoat" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70b5093d8133b513742b7461a28d374107b8bf9168aa60f4f567ad89acd2ed9e" +dependencies = [ + "futures-util", + "inventory", + "serde", + "tokio", + "tokio-tungstenite", + "topcoat-asset", + "topcoat-cookie", + "topcoat-core", + "topcoat-core-macro", + "topcoat-font", + "topcoat-font-macro", + "topcoat-l10n", + "topcoat-mail", + "topcoat-router", + "topcoat-router-macro", + "topcoat-runtime", + "topcoat-runtime-macro", + "topcoat-session", + "topcoat-view", + "topcoat-view-macro", +] + +[[package]] +name = "topcoat-asset" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac70debf9eee62714ce45416eae27b283c3a44a0f9ebcb2ac088fda48b533f3e" +dependencies = [ + "http", + "memchr", + "percent-encoding", + "serde", + "sha2 0.11.1", + "thiserror", + "tokio", + "toml", + "topcoat-core", + "topcoat-router", + "topcoat-view", +] + +[[package]] +name = "topcoat-cookie" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79aba10192abe21fbd01dfcb46bb04dab5ae64adb4432d9f078eb05f94e6a5" +dependencies = [ + "cookie", + "getrandom 0.2.17", + "http", + "serde", + "serde_json", + "topcoat-core", + "topcoat-router", +] + +[[package]] +name = "topcoat-core" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffff49b885744cdb89ee158c5d81cc8c619692bd9f4ab3cae92ad1adc0ce612e" +dependencies = [ + "anymap3", + "base64 0.22.1", + "elsa", + "http", + "pin-project-lite", + "siphasher", + "thiserror", + "tokio", +] + +[[package]] +name = "topcoat-core-grammar" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b788a2010234cd29fc050268e52ceb393d2124b20f669a83d8f61a9dbf895bb6" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "topcoat-core-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e3786bf2ee2c8b4f728d3fb53c41f639aa66583788b3135acbd63c11458b25b" +dependencies = [ + "quote", + "syn 3.0.9", + "topcoat-core-grammar", +] + +[[package]] +name = "topcoat-font" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa4656294aac116def1e7633f03117a84b65126c503242793ff4adc78577fb8" +dependencies = [ + "heck", + "inventory", + "serde", + "serde_json", + "topcoat-asset", + "topcoat-core", + "topcoat-router", + "topcoat-view", + "topcoat-view-macro", +] + +[[package]] +name = "topcoat-font-grammar" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b462fae28641a1bb24eab1fa9c473520389ca690331ca53fd6143d5b2746045e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "topcoat-core-grammar", + "topcoat-font", +] + +[[package]] +name = "topcoat-font-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40776cd3087aaea5e0c8b597126b1c09dbfb0d69833088d7f3b229305bbbb87f" +dependencies = [ + "quote", + "syn 3.0.9", + "topcoat-font-grammar", +] + +[[package]] +name = "topcoat-l10n" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34da63b3a5aea3d6c243d9fa8c98ca79b181b985f6a0a042f630672f54d12e9e" +dependencies = [ + "icu_locale", + "icu_locale_core", + "topcoat-core", + "topcoat-view", +] + +[[package]] +name = "topcoat-mail" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54a13c10c6399d9eb9b0bde38bd3d947eba56ddfaea99d9a4f971b74b6a651db" +dependencies = [ + "lettre", + "thiserror", + "time", + "topcoat-core", + "topcoat-router", + "topcoat-view", +] + +[[package]] +name = "topcoat-router" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9488065b08f293208b0f1aeb6667d5836b66c12dfced5e330f9a8f1d7f1ca1a" +dependencies = [ + "bytes", + "form_urlencoded", + "futures-core", + "futures-sink", + "futures-util", + "heck", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "inventory", + "ipnet", + "matchit", + "multer", + "percent-encoding", + "pin-project-lite", + "ref-cast", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "tokio", + "tokio-tungstenite", + "topcoat-core", + "topcoat-view", +] + +[[package]] +name = "topcoat-router-grammar" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3f51fa1a1e538bd34e02f88ebba554ac5931e55c688303a58a8e78123dfb04" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", + "topcoat-core-grammar", +] + +[[package]] +name = "topcoat-router-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c1b56d3bf19d54bddf300d6d57ca754531d7ad5481afca0b2302ac33f5d43af" +dependencies = [ + "quote", + "syn 3.0.9", + "topcoat-router-grammar", +] + +[[package]] +name = "topcoat-runtime" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03b22136b99694b349a950cd757387a04b080fdb131eecdd51d0511e1a45ebf5" +dependencies = [ + "futures-util", + "pin-project-lite", + "ref-cast", + "serde", + "serde_json", + "tokio", + "topcoat-asset", + "topcoat-core", + "topcoat-router", + "topcoat-view", + "topcoat-view-macro", +] + +[[package]] +name = "topcoat-runtime-grammar" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab93a83c38a045a4f541c2e548d30ba5dfdd3173c18de8b1c7b049709c29db97" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_json", + "syn 3.0.9", + "topcoat-core-grammar", + "topcoat-router", + "topcoat-runtime", +] + +[[package]] +name = "topcoat-runtime-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5acb1db0bdba3c36e4f80f7ef530945779a1b0294b1087e7d877e33005da6283" +dependencies = [ + "quote", + "syn 3.0.9", + "topcoat-runtime-grammar", +] + +[[package]] +name = "topcoat-session" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2325c30a484b1b1b6f5012b50bc18994d37c33c6bd2f71be8ff509b591a17457" +dependencies = [ + "base64 0.22.1", + "getrandom 0.4.3", + "sha2 0.11.1", + "thiserror", + "tokio", + "topcoat-cookie", + "topcoat-core", + "topcoat-router", + "web-time", +] + +[[package]] +name = "topcoat-view" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db4553b91f30e30c71c2bd95ae8e931a33326c6ffb604663b9d214008f12947c" +dependencies = [ + "futures-core", + "futures-util", + "http", + "memchr", + "pin-project-lite", + "siphasher", + "smallvec", + "topcoat-core", +] + +[[package]] +name = "topcoat-view-grammar" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75dd093ffc848370da4cce7670ccdfd4e98eab48e178d5d0da5509f747d85ca6" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", + "topcoat-core-grammar", + "topcoat-view", +] + +[[package]] +name = "topcoat-view-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffa1688d165704f08d58c03710453d0d39553292bea61b18be7959a996c3e39b" +dependencies = [ + "quote", + "syn 3.0.9", + "topcoat-view-grammar", +] + [[package]] name = "tracing" version = "0.1.44" @@ -2773,6 +3809,22 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", +] + [[package]] name = "turso" version = "0.8.3" @@ -3084,6 +4136,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.29.0" @@ -3359,6 +4417,9 @@ name = "winnow" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] [[package]] name = "wit-bindgen" diff --git a/Cargo.toml b/Cargo.toml index ecac8b8..23f6f16 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,10 @@ argon2 = "0.6.0" base64 = "0.23.1" chacha20poly1305 = "0.11.0" ed25519-dalek = { version = "3.0.0", features = ["rand_core"] } +futures-util = "0.3.34" +grass = "0.13.4" hex = "0.4.3" +http = "1.5.0" ipnet = "2.12.2" rand = "0.10.3" serde = { version = "1.0.229", features = ["derive"] } @@ -27,9 +30,12 @@ time = { version = "0.3.55", features = ["formatting", "parsing", "macros"] } tokio = { version = "1.54.1", features = ["sync", "rt", "rt-multi-thread", "macros"] } toml = "1.1.8" tracing = "0.1.44" +tracing-subscriber = "0.3.23" turso = "0.8.3" ulid = "3.0.0" tempfile = "3.27.0" +# web framework +topcoat = { version = "0.11.0", default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "multipart"] } # internal crates im-core = { path = "crates/im-core" } diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index 383a7af..89ea73b 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -91,6 +91,16 @@ impl Store { self.inner.readers[start].lock().await } + /// Runs `SELECT 1` on a pooled reader and fails when the database does not answer. The health + /// route calls it with a deadline, so a stuck lock shows up as a failed probe. + pub async fn ping(&self) -> Result<()> { + let conn = self.read_conn().await; + fetch_opt(&conn, "SELECT 1", (), |row| col_int(row, 0)) + .await? + .ok_or_else(missing_row) + .map(|_| ()) + } + /// Number of user rows. Used to decide whether first-run setup is still open. pub async fn user_count(&self) -> Result { let conn = self.read_conn().await; diff --git a/crates/im-web/Cargo.toml b/crates/im-web/Cargo.toml index 99b0b57..c993af1 100644 --- a/crates/im-web/Cargo.toml +++ b/crates/im-web/Cargo.toml @@ -5,9 +5,28 @@ edition.workspace = true license.workspace = true publish = false -[lints] -workspace = true - [[bin]] name = "im" path = "src/main.rs" + +[dependencies] +futures-util.workspace = true +http.workspace = true +im-core.workspace = true +serde.workspace = true +# `net` and `signal` for the listener and the shutdown signals, `time` for the database probe timeout. +tokio = { workspace = true, features = ["net", "signal", "time"] } +topcoat.workspace = true +tracing.workspace = true +tracing-subscriber = { workspace = true, features = ["env-filter"] } + +[dev-dependencies] +tempfile.workspace = true + +[build-dependencies] +grass.workspace = true +hex.workspace = true +sha2.workspace = true + +[lints] +workspace = true diff --git a/crates/im-web/assets/nav.js b/crates/im-web/assets/nav.js new file mode 100644 index 0000000..219f017 --- /dev/null +++ b/crates/im-web/assets/nav.js @@ -0,0 +1,528 @@ +/* + * nav.js: the one script of im. Everything in it is progressive enhancement. A page works without + * it as plain HTML; this file only makes the same pages feel like one application. + * + * What it does: + * - Soft navigation. A click on a same-origin link, or a submit of a same-origin form, is fetched + * with fetch(). The
element and the of the answer replace the current ones, and + * the URL goes into the history. Back and forward fetch the page again and restore the scroll. + * - Live refresh. Each distinct data-live URL on the page gets one EventSource. A `changed` event + * re-fetches the current page after a short debounce. A refresh keeps the scroll position, the + * focused control and the fields the user edited, so a page that changes under the user does not + * lose their typing. + * - Server restarting. /-/alive is held open on every page. While it is down, or while a form POST + * got no answer, a bar says so. The bar text comes from data-restart-text on <body>, so the + * server translates it. + * - Offline pages. Registers /assets/sw.js, which answers failed page loads with the offline page. + * + * What it never does: send a POST twice. A POST that got no answer is not repeated. Its form stays + * as the user left it, and the bar says the server could not be reached. + * + * The file is one IIFE with no globals. It is loaded with `defer`, so <main> and the data-live + * attributes exist when it runs. + */ +(function () { + "use strict"; + + // Without these the page is plain HTML, which is the behaviour we want anyway. + if (!window.fetch || !window.DOMParser || !window.EventSource || !window.history) { + return; + } + + /** The server-held stream that tells the page the server is up. */ + const ALIVE_PATH = "/-/alive"; + + /** Paths that always do a full page load. Assets are static; the API is not for pages. */ + const HARD_PREFIXES = ["/assets/", "/api/"]; + + /** Milliseconds between a `changed` event and the refresh it causes. Coalesces a burst of events. */ + const REFRESH_DEBOUNCE_MS = 250; + + /** Reconnect delays for a stream the browser gave up on. The last value repeats. */ + const RECONNECT_MS = [1000, 2000, 3000]; + + /** Asks for HTML, so the server answers with a page and not with JSON. */ + const ACCEPT = "text/html, application/xhtml+xml"; + + /** Input types whose value must never be kept or replayed by this script. */ + const SKIPPED_TYPES = ["password", "file", "hidden", "submit", "button", "reset", "image"]; + + /** Newest navigation (link, form, history move). An older answer that arrives later is dropped. */ + let navSeq = 0; + + /** Page-changing requests in flight. A live refresh waits until there are none. */ + let busy = 0; + + /** The URL the page currently shows, without caring about its hash. */ + let currentHref = location.href; + + /** Set while /-/alive is unreachable. */ + let serverDown = false; + + /** Set when a form POST got no answer. Cleared by the next answer. */ + let postUnanswered = false; + + /** The timer of the pending live refresh. */ + let refreshTimer = 0; + + /** The restart bar, created the first time it is needed. */ + let restartBar = null; + + /** Open live streams, by absolute URL. Each value is what hold() returned. */ + const streams = new Map(); + + // --------------------------------------------------------------------------------------------- + // Which links and forms are ours to handle. + + /** Parses `href` against the current page. Null when it is not a URL. */ + function parseUrl(href) { + try { + return new URL(href, location.href); + } catch (error) { + return null; + } + } + + /** True when `url` may be fetched and swapped in: same origin, and not an asset or API path. */ + function isSoftTarget(url) { + if (!url || url.origin !== location.origin) { + return false; + } + return !HARD_PREFIXES.some((prefix) => url.pathname.startsWith(prefix)); + } + + /** The URL without its fragment. A change of only the fragment is a same-page jump, not a load. */ + function withoutHash(href) { + return href.split("#")[0]; + } + + // --------------------------------------------------------------------------------------------- + // The restart bar. + + /** Shows or hides the bar, as the union of "server down" and "a POST got no answer". */ + function updateRestartBar() { + const show = serverDown || postUnanswered; + if (show && !restartBar) { + restartBar = document.createElement("div"); + restartBar.className = "restart-bar"; + restartBar.setAttribute("role", "status"); + restartBar.textContent = document.body.dataset.restartText || ""; + document.body.appendChild(restartBar); + } + if (restartBar) { + restartBar.hidden = !show; + } + } + + /** Counts page-changing requests so the page can dim while one is running. */ + function addBusy(delta) { + busy += delta; + document.body.classList.toggle("is-loading", busy > 0); + } + + // --------------------------------------------------------------------------------------------- + // Streams: one EventSource per URL, kept open with reconnects. + + /** + * Opens an EventSource to `url` and keeps it open. The browser reconnects by itself while it + * still tries; once it gives up (readyState CLOSED), this reopens the stream after 1, 2 and then + * 3 seconds. `hooks.events` maps event names to handlers, `hooks.lost` runs when the connection + * drops, and `hooks.back` runs when it opens again after a drop. Returns a handle with close(). + */ + function hold(url, hooks) { + const link = { source: null, failures: 0, timer: 0, lost: false, closed: false }; + + const connect = () => { + const source = new EventSource(url); + link.source = source; + source.addEventListener("open", () => { + link.failures = 0; + if (link.lost) { + link.lost = false; + if (hooks.back) hooks.back(); + } + }); + for (const [name, handler] of Object.entries(hooks.events || {})) { + source.addEventListener(name, handler); + } + source.addEventListener("error", () => { + if (link.closed) return; + if (!link.lost) { + link.lost = true; + if (hooks.lost) hooks.lost(); + } + if (source.readyState !== EventSource.CLOSED) return; + source.close(); + const delay = RECONNECT_MS[Math.min(link.failures, RECONNECT_MS.length - 1)]; + link.failures += 1; + link.timer = setTimeout(connect, delay); + }); + }; + + connect(); + return { + close() { + link.closed = true; + clearTimeout(link.timer); + if (link.source) link.source.close(); + }, + }; + } + + /** Holds /-/alive. It only drives the restart bar; the server sends nothing else on it yet. */ + function holdAlive() { + hold(ALIVE_PATH, { + lost: () => { + serverDown = true; + updateRestartBar(); + }, + back: () => { + serverDown = false; + updateRestartBar(); + }, + }); + } + + /** + * Makes the open streams match the data-live URLs of the page: one stream per distinct URL, and + * a stream whose URL is no longer on the page is closed. + */ + function syncStreams() { + const wanted = new Set(); + for (const el of document.querySelectorAll("[data-live]")) { + const url = parseUrl(el.getAttribute("data-live")); + if (isSoftTarget(url)) { + wanted.add(url.href); + } + } + for (const [href, handle] of streams) { + if (!wanted.has(href)) { + handle.close(); + streams.delete(href); + } + } + for (const href of wanted) { + if (!streams.has(href)) { + streams.set( + href, + hold(href, { + events: { changed: () => scheduleRefresh() }, + // Changes made while the stream was down are caught up by one refresh. + back: () => scheduleRefresh(), + }) + ); + } + } + } + + /** Re-fetches the current page soon. Several `changed` events in a row make one refresh. */ + function scheduleRefresh() { + clearTimeout(refreshTimer); + refreshTimer = setTimeout(() => { + refreshTimer = 0; + navigate(location.href, "refresh", 0); + }, REFRESH_DEBOUNCE_MS); + } + + // --------------------------------------------------------------------------------------------- + // Form fields and focus, kept across a live refresh. + + /** The named controls of `root` whose value the script may keep. */ + function keepableControls(root) { + return Array.from(root.querySelectorAll("input, textarea, select")).filter( + (el) => el.name && !SKIPPED_TYPES.includes(el.type) + ); + } + + /** True when the user changed the control, so its server value is not the one shown. */ + function isDirty(el) { + if (el.type === "checkbox" || el.type === "radio") { + return el.checked !== el.defaultChecked; + } + if (el.tagName === "SELECT") { + return Array.from(el.options).some((o) => o.selected !== o.defaultSelected); + } + return el.value !== el.defaultValue; + } + + /** + * A key that finds the same control in a re-rendered <main>: its id, or its name plus its index + * among the controls with that name. Null for an element with neither. + */ + function keyOf(el, root) { + if (el.id) return JSON.stringify(["id", el.id]); + if (!el.name) return null; + const same = Array.from(root.querySelectorAll("[name]")).filter((n) => n.name === el.name); + return JSON.stringify(["name", el.name, same.indexOf(el)]); + } + + /** The element that `key` names in `root`, or null. */ + function findByKey(key, root) { + if (!key) return null; + const [kind, value, index] = JSON.parse(key); + if (kind === "id") { + return Array.from(root.querySelectorAll("[id]")).find((n) => n.id === value) || null; + } + const same = Array.from(root.querySelectorAll("[name]")).filter((n) => n.name === value); + return same[index] || null; + } + + /** What a refresh must put back: the scroll, the focused control and the fields the user changed. */ + function captureState() { + const main = document.querySelector("main"); + const active = document.activeElement; + const dirty = main + ? keepableControls(main) + .filter(isDirty) + .map((el) => ({ + key: keyOf(el, main), + checked: el.checked, + value: el.value, + })) + : []; + return { + y: window.scrollY, + focus: main && active && main.contains(active) ? keyOf(active, main) : null, + fields: dirty, + }; + } + + /** Puts back what captureState() saw. Fields the server no longer renders are skipped. */ + function restoreState(state) { + const main = document.querySelector("main"); + if (!main || !state) return; + for (const saved of state.fields) { + const el = findByKey(saved.key, main); + if (!el || !keepableControls(main).includes(el)) continue; + if (el.type === "checkbox" || el.type === "radio") { + el.checked = saved.checked; + } else { + el.value = saved.value; + } + } + const focused = findByKey(state.focus, main); + if (focused) focused.focus({ preventScroll: true }); + window.scrollTo(0, state.y); + } + + // --------------------------------------------------------------------------------------------- + // Swapping the page in. + + /** + * Replaces <main> and the title with the ones of `doc`, and syncs the live streams. Returns false + * when `doc` has no <main>, so the caller can fall back to a full load. + */ + function swapIn(doc) { + const fresh = doc.querySelector("main"); + const old = document.querySelector("main"); + if (!fresh || !old) return false; + document.title = doc.title; + const lang = doc.documentElement.getAttribute("lang"); + if (lang) document.documentElement.setAttribute("lang", lang); + old.replaceWith(document.adoptNode(fresh)); + syncStreams(); + return true; + } + + /** Remembers the scroll position of the page being left, so Back can return to it. */ + function saveScroll() { + history.replaceState(Object.assign({}, history.state, { y: window.scrollY }), ""); + } + + /** + * Fetches `href` with a GET. Resolves to the response and its text, or to null when the request + * failed before any answer. Non-HTML answers come back with `text` set to null. + */ + async function getPage(href) { + try { + const res = await fetch(href, { headers: { Accept: ACCEPT }, credentials: "same-origin" }); + const isHtml = (res.headers.get("content-type") || "").includes("text/html"); + return { res, text: isHtml ? await res.text() : null }; + } catch (error) { + // The connection failed, or the body was cut off. Either way there is no page to show. + return null; + } + } + + /** + * Shows a fetched page. `mode` is "push" (a new history entry), "pop" (Back or Forward) or + * "refresh" (a live refresh in place). `finalHref` is the URL after redirects. + */ + function show(text, finalHref, mode, state) { + const doc = new DOMParser().parseFromString(text, "text/html"); + if (!swapIn(doc)) { + location.assign(finalHref); + return; + } + currentHref = finalHref; + const main = document.querySelector("main"); + if (mode === "refresh") { + restoreState(state); + return; + } + if (mode === "push") { + history.pushState({ y: 0 }, "", finalHref); + const hash = new URL(finalHref).hash.slice(1); + const target = hash ? document.getElementById(hash) : null; + if (target) { + target.scrollIntoView(); + } else { + window.scrollTo(0, 0); + } + } + if (mode === "pop") { + window.scrollTo(0, state); + } + if (main) { + main.setAttribute("tabindex", "-1"); + main.focus({ preventScroll: true }); + } + } + + // --------------------------------------------------------------------------------------------- + // Navigation: links, GET forms, POST forms, Back and Forward, and live refresh. + + /** + * Loads `href` into the page. `mode` is "push", "pop" or "refresh" (see show()). `y` is the scroll + * to restore on "pop". A failed GET for a link or a history move falls back to a full load, which + * shows the browser's own error. A failed refresh does nothing: the bar covers a dead server. + */ + async function navigate(href, mode, y) { + const refresh = mode === "refresh"; + if (refresh && busy > 0) return; + const seq = refresh ? navSeq : ++navSeq; + const state = refresh ? captureState() : y; + if (mode === "push") saveScroll(); + + addBusy(1); + const answer = await getPage(href); + addBusy(-1); + + // A newer navigation started, or a refresh was superseded: this answer is out of date. + if (seq !== navSeq) return; + if (!answer) { + if (!refresh) location.assign(href); + return; + } + postUnanswered = false; + updateRestartBar(); + if (answer.text === null) { + // A download or another non-page answer: let the browser handle that URL. + if (!refresh) location.assign(answer.res.url || href); + return; + } + show(answer.text, answer.res.url || href, mode, state); + } + + /** + * Sends a form. A GET form becomes a navigation to the URL with the form's fields. A POST is sent + * once with fetch(); when it gets no answer the form is kept and the bar is shown. It is never + * sent again by this script. + */ + async function submitForm(form, submitter, action, method) { + const data = new FormData(form, submitter || undefined); + if (method === "get") { + const url = new URL(action.href); + url.search = new URLSearchParams(data).toString(); + navigate(url.href, "push", 0); + return; + } + + // A form that is already sending is not sent twice by a second submit. + form.dataset.sending = "1"; + const enctype = (submitter && submitter.getAttribute("formenctype")) || form.enctype || ""; + const body = enctype.startsWith("multipart/") ? data : new URLSearchParams(data); + + const seq = ++navSeq; + addBusy(1); + let res = null; + let text = null; + try { + res = await fetch(action.href, { + method: "POST", + body, + headers: { Accept: ACCEPT }, + credentials: "same-origin", + redirect: "follow", + }); + if ((res.headers.get("content-type") || "").includes("text/html")) { + text = await res.text(); + } + } catch (error) { + // No answer. The request may or may not have reached the server, so it is not repeated. + res = null; + } + addBusy(-1); + delete form.dataset.sending; + + if (seq !== navSeq) return; + if (!res) { + postUnanswered = true; + updateRestartBar(); + return; + } + postUnanswered = false; + updateRestartBar(); + if (text === null) { + // The POST was answered with a download or another non-page. Show its final URL with a GET. + location.assign(res.url || action.href); + return; + } + show(text, res.url || action.href, "push", 0); + } + + // Links. A click on a link we handle is taken over; anything else is left to the browser. + document.addEventListener("click", (event) => { + if (event.defaultPrevented || event.button !== 0) return; + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + const link = event.target instanceof Element ? event.target.closest("a[href]") : null; + if (!link || link.hasAttribute("data-hard") || link.hasAttribute("download")) return; + if (link.target && link.target !== "_self") return; + const raw = link.getAttribute("href"); + if (raw.startsWith("//")) return; + const url = parseUrl(raw); + if (!isSoftTarget(url)) return; + // A link to a fragment of this page is an ordinary scroll. + if (withoutHash(url.href) === withoutHash(location.href) && url.hash) return; + event.preventDefault(); + navigate(url.href, "push", 0); + }); + + // Forms. A submit we handle is taken over; the browser does not send it. + document.addEventListener("submit", (event) => { + const form = event.target; + if (!(form instanceof HTMLFormElement) || event.defaultPrevented) return; + if (form.hasAttribute("data-hard") || (form.target && form.target !== "_self")) return; + const method = (form.getAttribute("method") || "get").toLowerCase(); + if (method !== "get" && method !== "post") return; + const action = parseUrl(form.getAttribute("action") || location.href); + if (!isSoftTarget(action)) return; + if (form.dataset.sending) { + event.preventDefault(); + return; + } + event.preventDefault(); + submitForm(form, event.submitter, action, method); + }); + + // Back and Forward. A jump inside the page only moves the scroll; anything else is fetched. + window.addEventListener("popstate", (event) => { + if (withoutHash(location.href) === withoutHash(currentHref)) { + currentHref = location.href; + return; + } + const y = event.state && typeof event.state.y === "number" ? event.state.y : 0; + navigate(location.href, "pop", y); + }); + + // --------------------------------------------------------------------------------------------- + // Start. + + holdAlive(); + syncStreams(); + + // The worker only answers failed page loads. It is registered at the root so it can. + if ("serviceWorker" in navigator) { + navigator.serviceWorker.register("/assets/sw.js", { scope: "/" }).catch(() => {}); + } +})(); diff --git a/crates/im-web/assets/offline.html b/crates/im-web/assets/offline.html new file mode 100644 index 0000000..889ee73 --- /dev/null +++ b/crates/im-web/assets/offline.html @@ -0,0 +1,20 @@ +<!DOCTYPE html> +<html lang="en"> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width, initial-scale=1"> +<meta name="robots" content="noindex"> +<meta http-equiv="refresh" content="5"> +<title>im · offline + + + +
+
+

im is offline

+

The server is not answering. This page checks again every 5 seconds.

+

Sunucu yanıt vermiyor. Bu sayfa her 5 saniyede bir yeniden dener.

+
+
+ + diff --git a/crates/im-web/assets/pages.js b/crates/im-web/assets/pages.js new file mode 100644 index 0000000..faa95d2 --- /dev/null +++ b/crates/im-web/assets/pages.js @@ -0,0 +1,9 @@ +/* + * pages.js: small behaviours of individual pages (a dropdown search, a copy button and so on). It + * is empty for now. The file exists so the shell can load it and its content hash is already in the + * page links. Each behaviour, when it is added, does nothing unless its own data attribute is on the + * page. Like nav.js, it is one IIFE with no globals. + */ +(function () { + "use strict"; +})(); diff --git a/crates/im-web/assets/sw.js b/crates/im-web/assets/sw.js new file mode 100644 index 0000000..30a845f --- /dev/null +++ b/crates/im-web/assets/sw.js @@ -0,0 +1,46 @@ +/* + * sw.js: the service worker of im. It does one thing. When a page load fails because the server + * cannot be reached, it answers with /assets/offline.html, which checks again every few seconds. + * Everything else goes to the network untouched, so a page never shows data that is out of date. + */ + +/** The cache that holds the offline page. Bump the number when offline.html changes. */ +const CACHE = "im-offline-1"; + +/** The page answered when a navigation fails. */ +const OFFLINE_PAGE = "/assets/offline.html"; + +self.addEventListener("install", (event) => { + event.waitUntil( + caches + .open(CACHE) + .then((cache) => cache.add(OFFLINE_PAGE)) + .then(() => self.skipWaiting()) + ); +}); + +self.addEventListener("activate", (event) => { + // Drop the caches of earlier versions, then take control of the open pages. + event.waitUntil( + caches + .keys() + .then((keys) => Promise.all(keys.filter((key) => key !== CACHE).map((key) => caches.delete(key)))) + .then(() => self.clients.claim()) + ); +}); + +self.addEventListener("fetch", (event) => { + const request = event.request; + // Only a GET navigation is answered. Retrying a POST here would send the form a second time. + if (request.mode !== "navigate" || request.method !== "GET") { + return; + } + event.respondWith( + fetch(request).catch(() => + caches + .open(CACHE) + .then((cache) => cache.match(OFFLINE_PAGE)) + .then((page) => page || Response.error()) + ) + ); +}); diff --git a/crates/im-web/build.rs b/crates/im-web/build.rs new file mode 100644 index 0000000..83ba611 --- /dev/null +++ b/crates/im-web/build.rs @@ -0,0 +1,57 @@ +//! Build script of the `im` binary. It compiles `style/main.scss` into `OUT_DIR/main.css`, and it +//! emits the build identity and the content hashes that the page links use as cache-busting +//! queries: `IM_MAIN_CSS_V`, `IM_NAV_JS_V`, `IM_PAGES_JS_V` and `IM_BUILD_SHA`. +//! +//! It does not decide what is served: `src/assets.rs` embeds the files. It does not decide what a +//! page links to either: `src/assets.rs` builds the `?v=` URLs from these values. It only compiles +//! and hashes, so a changed file gets a new hash and an unchanged file keeps its URL. + +use std::{env, fs, path::PathBuf}; + +use hex::encode; +use sha2::{Digest, Sha256}; + +/// Number of hex characters of the SHA-256 that make a content version. Twelve characters are 48 +/// bits, which is plenty to tell two builds of one file apart. +const VERSION_HEX_LEN: usize = 12; + +fn main() { + println!("cargo:rerun-if-env-changed=IM_BUILD_SHA"); + println!("cargo:rerun-if-changed=../../style"); + println!("cargo:rerun-if-changed=assets"); + println!("cargo:rerun-if-changed=build.rs"); + + // The commit identity shown by `/healthz`. The release script sets it; a local build says `dev`. + let sha = env::var("IM_BUILD_SHA").unwrap_or_else(|_| "dev".to_owned()); + println!("cargo:rustc-env=IM_BUILD_SHA={sha}"); + + let manifest = + PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("cargo sets the manifest dir")); + let out = PathBuf::from(env::var("OUT_DIR").expect("cargo sets OUT_DIR")); + + // The stylesheet is compiled from the repository-level `style/` directory. Its partials are + // `@use`d relative to `main.scss`, so no load path is needed. + let css = grass::from_path( + manifest.join("../../style/main.scss"), + &grass::Options::default(), + ) + .unwrap_or_else(|e| panic!("compiling style/main.scss: {e}")); + fs::write(out.join("main.css"), &css).expect("writing the compiled stylesheet to OUT_DIR"); + println!( + "cargo:rustc-env=IM_MAIN_CSS_V={}", + content_version(css.as_bytes()) + ); + + for (var, file) in [ + ("IM_NAV_JS_V", "assets/nav.js"), + ("IM_PAGES_JS_V", "assets/pages.js"), + ] { + let bytes = fs::read(manifest.join(file)).unwrap_or_else(|e| panic!("reading {file}: {e}")); + println!("cargo:rustc-env={var}={}", content_version(&bytes)); + } +} + +/// The first `VERSION_HEX_LEN` hex characters of the SHA-256 of `bytes`. +fn content_version(bytes: &[u8]) -> String { + encode(Sha256::digest(bytes))[..VERSION_HEX_LEN].to_owned() +} diff --git a/crates/im-web/src/assets.rs b/crates/im-web/src/assets.rs new file mode 100644 index 0000000..8088929 --- /dev/null +++ b/crates/im-web/src/assets.rs @@ -0,0 +1,75 @@ +//! The static files of the UI, compiled into the binary and served from `/assets/`. +//! +//! The CSS is compiled from `style/` by `build.rs`. The scripts and the offline page are in +//! `crates/im-web/assets/`. Each link to a file that changes with a build carries the first 12 +//! hex digits of its SHA-256 as `?v=`, so a changed file gets a new URL and an unchanged one keeps +//! its cache entry. Files whose URL does not change (the service worker and the offline page) are +//! served with `no-cache`. + +use topcoat::Result; +use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, route}; + +/// Link to the stylesheet, with its content version. +pub const MAIN_CSS_HREF: &str = concat!("/assets/main.css?v=", env!("IM_MAIN_CSS_V")); + +/// Link to the script that makes navigation soft and drives the live pages. +pub const NAV_JS_HREF: &str = concat!("/assets/nav.js?v=", env!("IM_NAV_JS_V")); + +/// Link to the script of individual pages. +pub const PAGES_JS_HREF: &str = concat!("/assets/pages.js?v=", env!("IM_PAGES_JS_V")); + +const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); +const NAV_JS: &str = include_str!("../assets/nav.js"); +const PAGES_JS: &str = include_str!("../assets/pages.js"); +const OFFLINE_HTML: &str = include_str!("../assets/offline.html"); +const SW_JS: &str = include_str!("../assets/sw.js"); + +/// A content-versioned file. The URL changes with the bytes, so the browser may keep it for a year. +const IMMUTABLE: &str = "public, max-age=31536000, immutable"; + +/// A file whose URL stays the same across builds. The browser must ask again each time. +const REVALIDATE: &str = "no-cache"; + +/// The status, headers and body of an asset answer. +type Asset = (StatusCode, HeaderMap, &'static str); + +/// Builds the answer for one asset: the content type and the cache policy. +fn asset(content_type: &'static str, cache: &'static str, body: &'static str) -> Asset { + let mut headers = HeaderMap::new(); + headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type)); + headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); + (StatusCode::OK, headers, body) +} + +/// `GET /assets/main.css`. +#[route(GET "/assets/main.css")] +async fn main_css() -> Result { + Ok(asset("text/css; charset=utf-8", IMMUTABLE, MAIN_CSS)) +} + +/// `GET /assets/nav.js`. +#[route(GET "/assets/nav.js")] +async fn nav_js() -> Result { + Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, NAV_JS)) +} + +/// `GET /assets/pages.js`. +#[route(GET "/assets/pages.js")] +async fn pages_js() -> Result { + Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, PAGES_JS)) +} + +/// `GET /assets/offline.html`. Also precached by the service worker. +#[route(GET "/assets/offline.html")] +async fn offline_html() -> Result { + Ok(asset("text/html; charset=utf-8", REVALIDATE, OFFLINE_HTML)) +} + +/// `GET /assets/sw.js`. It is served at the root scope, which needs the `Service-Worker-Allowed` +/// header; without it the browser would limit the worker to `/assets/`. +#[route(GET "/assets/sw.js")] +async fn sw_js() -> Result { + let (status, mut headers, body) = asset("text/javascript; charset=utf-8", REVALIDATE, SW_JS); + headers.insert("service-worker-allowed", HeaderValue::from_static("/")); + Ok((status, headers, body)) +} diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs new file mode 100644 index 0000000..cb9cae4 --- /dev/null +++ b/crates/im-web/src/boot.rs @@ -0,0 +1,199 @@ +//! Boot: the order in which the server comes up, the router it serves, and the shutdown. +//! +//! The order follows `docs/conventions.md` section 2: load the configuration, create the data +//! directory with mode 0700, load or create the instance key, open the database (which applies +//! the pragmas and the migrations), build the router, bind the listener, and serve until SIGTERM or +//! Ctrl-C. Stored UI overrides are not layered on the file yet, because no page writes them. + +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::sync::Arc; + +use im_core::config::Config; +use im_core::secret; +use im_core::store::Store; +use tokio::net::TcpListener; +use tokio::signal::unix::{SignalKind, signal}; +use tokio::sync::watch; +use topcoat::cookie::RouterBuilderCookieExt; +use topcoat::router::{Router, RouterBuilderDiscoverExt, RouterService}; + +use crate::live::LiveHub; +use crate::pages::not_found::NotFoundLayer; +use crate::security::{self, SecurityHeaders}; +use crate::state::AppState; + +/// Name of the instance key file inside the data directory. +const KEY_FILE: &str = "im.key"; + +/// Runs the server until a stop signal arrives. Returns once every connection has finished. +pub async fn serve(config_path: &Path) -> im_core::Result<()> { + let config = Config::load(config_path)?; + let listen = config.listen; + let state = open_state(config).await?; + + let listener = TcpListener::bind(listen).await.map_err(|error| { + std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) + })?; + tracing::info!( + listen = %listen, + data_dir = %state.config.data_dir.display(), + build = env!("IM_BUILD_SHA"), + "im starting" + ); + + // One stop flag. The signal task sets it; the server watches it and then drains. + let (stop_tx, stop_rx) = watch::channel(false); + tokio::spawn(async move { + shutdown_signal().await; + tracing::info!("shutdown signal received"); + stop_tx.send_replace(true); + }); + + topcoat::serve_until( + listener, + RouterService::new(router(state)), + wait_stop(stop_rx), + ) + .await?; + tracing::info!("im stopped"); + Ok(()) +} + +/// Creates the data directory and opens the key and the database. Everything the router needs +/// that touches the disk is ready when this returns. +async fn open_state(config: Config) -> im_core::Result { + std::fs::create_dir_all(&config.data_dir)?; + // The directory holds the instance key. Only this user may enter it. + std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?; + let data_dir = config.data_dir.canonicalize()?; + if let Some(parent) = config + .database + .parent() + .filter(|p| !p.as_os_str().is_empty()) + { + std::fs::create_dir_all(parent)?; + } + let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; + let store = Store::open(&config.database).await?; + Ok(AppState { + config: Arc::new(config), + store, + key: Arc::new(key), + live: Arc::new(LiveHub::default()), + }) +} + +/// The router of the server: every route and page found by `discover`, the cookie jar, the security +/// headers on every response, and the styled 404 for browsers. +pub fn router(state: AppState) -> Router { + let security = SecurityHeaders::new(security::headers_for(&state.config.base_url)); + Router::builder() + .discover() + .app_context(state) + .cookies() + .layer(security) + .layer(NotFoundLayer) + .build() +} + +/// Resolves when the shared stop flag is set. +async fn wait_stop(mut stop: watch::Receiver) { + let _ = stop.wait_for(|stopped| *stopped).await; +} + +/// Resolves on Ctrl-C or SIGTERM. A handler that cannot be installed is logged and never resolves, +/// so the other one still works. +async fn shutdown_signal() { + let ctrl_c = async { + if let Err(error) = tokio::signal::ctrl_c().await { + tracing::error!(error = %error, "cannot listen for Ctrl-C"); + std::future::pending::<()>().await; + } + }; + let terminate = async { + match signal(SignalKind::terminate()) { + Ok(mut term) => { + term.recv().await; + } + Err(error) => { + tracing::error!(error = %error, "cannot listen for SIGTERM"); + std::future::pending::<()>().await; + } + } + }; + tokio::select! { + () = ctrl_c => {} + () = terminate => {} + } +} + +#[cfg(test)] +pub(crate) use tests::test_state; + +#[cfg(test)] +mod tests { + use super::*; + use http::header::{ACCEPT, CONTENT_SECURITY_POLICY, X_CONTENT_TYPE_OPTIONS}; + use topcoat::router::response::Response; + use topcoat::router::{Body, to_bytes}; + + /// An app state over a fresh temp directory: the database and the key live there, and nothing + /// is written outside it. The directory is returned so it lives as long as the state. + pub(crate) async fn test_state() -> (tempfile::TempDir, AppState) { + let dir = tempfile::tempdir().expect("temp dir"); + let text = format!( + "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7650\"\nbase_url = \"http://127.0.0.1:7650\"\n", + dir.path().join("im.db").display(), + dir.path().display(), + ); + let config = Config::parse(&text).expect("test config"); + let key = secret::load_or_create_key(&dir.path().join(KEY_FILE)).expect("key"); + let store = Store::open(&config.database).await.expect("store"); + let state = AppState { + config: Arc::new(config), + store, + key: Arc::new(key), + live: Arc::new(LiveHub::default()), + }; + (dir, state) + } + + async fn get(state: AppState, path: &str, accept: Option<&str>) -> Response { + let mut request = http::Request::get(path); + if let Some(accept) = accept { + request = request.header(ACCEPT, accept); + } + let request = request.body(Body::empty()).expect("request"); + router(state).handle(request).await + } + + #[tokio::test] + async fn a_page_carries_the_content_security_policy_and_nosniff() { + let (_dir, state) = test_state().await; + let response = get(state, "/", Some("text/html")).await; + assert_eq!(response.status(), 200); + assert_eq!( + response.headers()[CONTENT_SECURITY_POLICY] + .to_str() + .expect("ascii"), + security::CSP + ); + assert_eq!(response.headers()[X_CONTENT_TYPE_OPTIONS], "nosniff"); + } + + #[tokio::test] + async fn an_unknown_path_for_a_browser_gets_the_styled_404() { + let (_dir, state) = test_state().await; + let response = get(state, "/no/such/page", Some("text/html")).await; + assert_eq!(response.status(), 404); + let body = to_bytes(response.into_body(), 64 * 1024) + .await + .expect("body"); + let html = String::from_utf8_lossy(&body); + assert!( + html.contains("Page not found"), + "styled 404 body, got: {html}" + ); + } +} diff --git a/crates/im-web/src/health.rs b/crates/im-web/src/health.rs new file mode 100644 index 0000000..2c905c5 --- /dev/null +++ b/crates/im-web/src/health.rs @@ -0,0 +1,63 @@ +//! `GET /healthz`, the probe of `docs/contracts.md` section 4.1. +//! +//! It answers `200` with `ok ` when the database answers `SELECT 1` within one second, +//! and `503` with `fail database` otherwise. It needs no login and reads no user data. + +use std::time::Duration; + +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, route}; + +use crate::state::AppState; + +/// The longest the database probe may take. A lock held by a long write shows up as a failed probe. +const PROBE_DEADLINE: Duration = Duration::from_secs(1); + +/// `GET /healthz`. +#[route(GET "/healthz")] +async fn healthz(cx: &Cx) -> Result<(StatusCode, HeaderMap, String)> { + let state = app_context::(cx); + let (status, body) = match tokio::time::timeout(PROBE_DEADLINE, state.store.ping()).await { + Ok(Ok(())) => (StatusCode::OK, format!("ok {}", env!("IM_BUILD_SHA"))), + Ok(Err(error)) => { + tracing::error!(error = %error, "healthz: the database probe failed"); + (StatusCode::SERVICE_UNAVAILABLE, "fail database".to_owned()) + } + Err(_) => { + tracing::error!("healthz: the database probe took longer than one second"); + (StatusCode::SERVICE_UNAVAILABLE, "fail database".to_owned()) + } + }; + let mut headers = HeaderMap::new(); + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/plain; charset=utf-8"), + ); + Ok((status, headers, body)) +} + +#[cfg(test)] +mod tests { + use http::Request; + use topcoat::router::Body; + + use crate::boot::{router, test_state}; + + #[tokio::test] + async fn healthz_answers_ok_with_the_build_sha() { + let (_dir, state) = test_state().await; + let request = Request::get("/healthz") + .body(Body::empty()) + .expect("request"); + let response = router(state).handle(request).await; + assert_eq!(response.status(), 200); + let body = topcoat::router::to_bytes(response.into_body(), 1024) + .await + .expect("body"); + assert_eq!( + body.as_ref(), + format!("ok {}", env!("IM_BUILD_SHA")).as_bytes() + ); + } +} diff --git a/crates/im-web/src/i18n/mod.rs b/crates/im-web/src/i18n/mod.rs new file mode 100644 index 0000000..5f336b9 --- /dev/null +++ b/crates/im-web/src/i18n/mod.rs @@ -0,0 +1,116 @@ +//! Languages of the UI and how a request picks one. English and Turkish are the only ones. +//! +//! Every visible string is keyed by an enum in an area module (`shell.rs` for now), and each +//! module's `t` function matches on `(key, lang)` exhaustively. A key without a Turkish text +//! therefore fails to compile instead of showing English on a Turkish page. +//! +//! This module decides the language. It does not format sentences with values; those get small +//! helper functions next to their keys. + +pub mod shell; + +use topcoat::context::Cx; +use topcoat::router::request::headers; +use topcoat::router::{HeaderMap, header}; + +/// A UI language. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Lang { + En, + Tr, +} + +impl Lang { + /// Parses a stored language code. Anything other than `en` or `tr` is `None`, which means "no + /// preference" to the caller. + pub fn from_code(code: &str) -> Option { + match code { + "en" => Some(Lang::En), + "tr" => Some(Lang::Tr), + _ => None, + } + } + + /// The language of a `Accept-Language` tag such as `tr-TR`, by its primary subtag. None for a + /// language this build has no text for. + fn from_tag(tag: &str) -> Option { + let primary = tag.split('-').next()?.trim(); + Lang::from_code(&primary.to_ascii_lowercase()) + } + + /// The value of ``. + pub fn code(self) -> &'static str { + match self { + Lang::En => "en", + Lang::Tr => "tr", + } + } +} + +/// The language of the current request. See [`resolve`]. +pub fn lang(cx: &Cx, user_locale: Option<&str>) -> Lang { + resolve(user_locale, headers(cx)) +} + +/// The user's stored language when it names one, else the best `Accept-Language` entry this build +/// can serve, else English. +/// +/// `user_locale` is the stored value of the account (`en`, `tr`, or nothing for "automatic"). +pub fn resolve(user_locale: Option<&str>, request_headers: &HeaderMap) -> Lang { + user_locale + .and_then(Lang::from_code) + .or_else(|| accept_language(request_headers)) + .unwrap_or(Lang::En) +} + +/// The supported entry with the highest quality. Ties keep the first one listed. Entries with +/// `q=0`, an unreadable quality, or a language this build does not have are skipped. +fn accept_language(request_headers: &HeaderMap) -> Option { + let mut best: Option<(f32, Lang)> = None; + for value in request_headers.get_all(header::ACCEPT_LANGUAGE) { + let Ok(text) = value.to_str() else { + continue; + }; + for item in text.split(',') { + let mut parts = item.split(';'); + let tag = parts.next().unwrap_or_default().trim(); + let quality = parts + .find_map(|part| part.trim().strip_prefix("q=")) + .map_or(Some(1.0), |q| q.parse::().ok()); + let Some(quality) = quality.filter(|q| *q > 0.0) else { + continue; + }; + let Some(lang) = Lang::from_tag(tag) else { + continue; + }; + if best.is_none_or(|(best_quality, _)| quality > best_quality) { + best = Some((quality, lang)); + } + } + } + best.map(|(_, lang)| lang) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn accept(value: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert( + header::ACCEPT_LANGUAGE, + value.parse().expect("header value"), + ); + headers + } + + #[test] + fn the_stored_language_wins_then_accept_language_then_english() { + assert_eq!(resolve(Some("tr"), &accept("en")), Lang::Tr); + assert_eq!(resolve(None, &accept("en;q=0.2, tr;q=0.9")), Lang::Tr); + assert_eq!(resolve(None, &accept("tr-TR,tr;q=0.9,en;q=0.8")), Lang::Tr); + assert_eq!(resolve(None, &accept("fr, de;q=0.5")), Lang::En); + assert_eq!(resolve(Some("auto"), &accept("tr;q=0")), Lang::En); + assert_eq!(resolve(None, &HeaderMap::new()), Lang::En); + } +} diff --git a/crates/im-web/src/i18n/shell.rs b/crates/im-web/src/i18n/shell.rs new file mode 100644 index 0000000..dd9fcdb --- /dev/null +++ b/crates/im-web/src/i18n/shell.rs @@ -0,0 +1,55 @@ +//! Strings of the shell and of the first pages: the topbar, the restart bar, the 404 page and the +//! start page. Area modules hold their own strings as they arrive. + +use super::Lang; + +/// One variant per phrase. Add a variant, then its English and Turkish texts in [`t`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum K { + /// The badge shown beside an administrator's name. + Admin, + /// The link on the 404 page that returns to the start page. + BackHome, + /// The title of the start page. + ImIsRunning, + /// The sentence under the 404 title. + NotFoundBody, + /// The title of the 404 page. + NotFoundTitle, + /// The sentence on the start page. + RunningBody, + /// The bar shown while the server cannot be reached. + ServerRestarting, + /// The accessible name of the service switcher. + Services, + /// The first link on every page, which jumps past the topbar. + SkipToContent, +} + +/// The text of `key` in `lang`. +pub fn t(lang: Lang, key: K) -> &'static str { + match (key, lang) { + (K::Admin, Lang::En) => "Admin", + (K::Admin, Lang::Tr) => "Yönetici", + (K::BackHome, Lang::En) => "Back to the start", + (K::BackHome, Lang::Tr) => "Başlangıca dön", + (K::ImIsRunning, Lang::En) => "im is running", + (K::ImIsRunning, Lang::Tr) => "im çalışıyor", + (K::NotFoundBody, Lang::En) => "The page does not exist, or you do not have access to it.", + (K::NotFoundBody, Lang::Tr) => "Sayfa yok ya da bu sayfayı görme izniniz yok.", + (K::NotFoundTitle, Lang::En) => "Page not found", + (K::NotFoundTitle, Lang::Tr) => "Sayfa bulunamadı", + (K::RunningBody, Lang::En) => { + "The server answers requests. Sign-in is not part of this build yet." + } + (K::RunningBody, Lang::Tr) => { + "Sunucu istekleri yanıtlıyor. Oturum açma bu sürümde henüz yok." + } + (K::ServerRestarting, Lang::En) => "The server is restarting. Reconnecting…", + (K::ServerRestarting, Lang::Tr) => "Sunucu yeniden başlatılıyor. Yeniden bağlanılıyor…", + (K::Services, Lang::En) => "Services", + (K::Services, Lang::Tr) => "Hizmetler", + (K::SkipToContent, Lang::En) => "Skip to content", + (K::SkipToContent, Lang::Tr) => "İçeriğe geç", + } +} diff --git a/crates/im-web/src/live.rs b/crates/im-web/src/live.rs new file mode 100644 index 0000000..2893ec3 --- /dev/null +++ b/crates/im-web/src/live.rs @@ -0,0 +1,199 @@ +//! Live updates: a change counter per topic, and the server-sent event stream that carries it to +//! the browser. +//! +//! A write that changes what a page shows calls [`LiveHub::bump`] after it commits. A stream that +//! subscribed to that topic wakes and sends one `changed` event without data. The browser then +//! fetches the page again (`nav.js`), so an event carries no state and a missed one cannot leave the +//! page wrong for long. Nothing polls, and a topic nobody listens to is dropped. +//! +//! The hub is not a queue and not an authorisation check. Each route that opens a stream +//! authenticates and authorises first, then calls [`stream_changes`]. +//! +//! Nothing bumps a topic or opens [`stream_changes`] yet, so the items here are kept ahead of the +//! pages that use them. + +#![allow(dead_code)] // The hub and its topics wait for the pages that bump and follow them. + +use std::collections::HashMap; +use std::future::Future; +use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use futures_util::{Stream, StreamExt, future::select_all, stream}; +use tokio::sync::watch; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::content::sse::{Event, KeepAlive, Sse}; +use topcoat::router::response::{IntoResponse, Response}; +use topcoat::router::{HeaderValue, route}; + +/// How long a client waits before it reconnects when a stream ends. Sent once, at the start. +pub const STREAM_RETRY: Duration = Duration::from_millis(1000); + +/// Silence after which the server sends a keep-alive comment, so proxies keep the stream open. +pub const KEEP_ALIVE: Duration = Duration::from_secs(30); + +/// What a live page follows. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Topic { + /// A user's own settings, sessions or sign-ins. Keyed by user id. Streamed only to that user. + Account(String), + /// The audit log: an entry was written. Global. Admin pages only. + AdminAudit, +} + +/// The change counters of all open topics. Cheap to share: every clone of the app state holds the +/// same `Arc`. +#[derive(Default)] +pub struct LiveHub { + topics: Mutex>>, +} + +impl LiveHub { + /// Locks the map. A panic in another holder must not stop every live page, so a poisoned lock + /// is used as it is. + fn topics(&self) -> MutexGuard<'_, HashMap>> { + self.topics.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Subscribes to `topic`. The receiver starts as seen, so a bump after this call wakes it. + /// Subscribe before reading the state: a change between the two is then not lost. Topics that + /// nobody holds any more are dropped here, so the map stays small. + pub fn subscribe(&self, topic: &Topic) -> watch::Receiver { + let mut topics = self.topics(); + topics.retain(|_, sender| sender.receiver_count() > 0); + topics + .entry(topic.clone()) + .or_insert_with(|| watch::channel(0).0) + .subscribe() + } + + /// Wakes the subscribers of `topic`. Does nothing when nobody listens. + pub fn bump(&self, topic: &Topic) { + let mut topics = self.topics(); + let Some(sender) = topics.get(topic) else { + return; + }; + sender.send_modify(|generation| *generation = generation.wrapping_add(1)); + if sender.receiver_count() == 0 { + topics.remove(topic); + } + } +} + +/// The state a stream carries between wakes. +struct Follow { + wakes: Vec>, + fingerprint: F, + last: String, +} + +/// Opens the `changed` stream for `topics`. The stream sends an event only when `fingerprint` +/// differs from the value it last sent, so a bump that changes nothing the viewer sees sends +/// nothing. Nothing is sent on connect: the page already shows the state that `fingerprint` read. +/// +/// `fingerprint` must be cheap and must describe everything the page shows. A read that fails ends +/// the stream, and the browser reconnects. +pub async fn stream_changes( + cx: &Cx, + hub: &LiveHub, + topics: &[Topic], + fingerprint: F, +) -> Result +where + F: Fn() -> Fut + Send + 'static, + Fut: Future> + Send, +{ + // Subscribed before the first read, so a change in between still wakes the stream. + let wakes: Vec> = + topics.iter().map(|topic| hub.subscribe(topic)).collect(); + let last = fingerprint().await?; + let follow = Follow { + wakes, + fingerprint, + last, + }; + let events = stream::unfold(follow, |mut follow| async move { + loop { + if !wait_any(&mut follow.wakes).await { + return None; + } + match (follow.fingerprint)().await { + Ok(now) if now != follow.last => { + follow.last = now; + return Some((changed_event(), follow)); + } + Ok(_) => continue, + Err(error) => { + tracing::error!(error = %error, "live: could not read the page state"); + return None; + } + } + } + }); + events_response(cx, events) +} + +/// The data-less `changed` event. +fn changed_event() -> Result { + Ok(Event::new().event("changed").data("1")) +} + +/// Resolves when one of `wakes` changes. False when that topic is gone, which ends the stream. +/// With no topics at all it never resolves: the stream then only sends keep-alives. +async fn wait_any(wakes: &mut [watch::Receiver]) -> bool { + if wakes.is_empty() { + std::future::pending::<()>().await; + } + let waits = wakes.iter_mut().map(|wake| Box::pin(wake.changed())); + let (result, _, _) = select_all(waits).await; + result.is_ok() +} + +/// The response of a live stream: `retry` once, then the events, with keep-alives while idle. +/// `X-Accel-Buffering: no` stops a reverse proxy from holding the events back. +pub fn events_response( + cx: &Cx, + events: impl Stream> + Send + 'static, +) -> Result { + let retry = stream::once(std::future::ready(Ok(Event::new().retry(STREAM_RETRY)))); + let stream = Sse::new(retry.chain(events)) + .keep_alive(KeepAlive::new().interval(KEEP_ALIVE).text("keepalive")); + let mut response = stream.into_response(cx)?; + response + .headers_mut() + .insert("x-accel-buffering", HeaderValue::from_static("no")); + Ok(response) +} + +/// `GET /-/alive`. Every page holds this stream, so the browser learns when the server stops and +/// starts again. Anonymous viewers may hold it, and it reveals nothing: for now it sends only the +/// `retry` hint and keep-alives. +#[route(GET "/-/alive")] +async fn alive(cx: &Cx) -> Result { + events_response(cx, stream::pending::>()) +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[tokio::test] + async fn a_bump_wakes_only_the_subscribers_of_its_topic() { + let hub = LiveHub::default(); + let mine = Topic::Account("user-a".to_owned()); + let other = Topic::Account("user-b".to_owned()); + let mut wake_mine = hub.subscribe(&mine); + let wake_other = hub.subscribe(&other); + + hub.bump(&mine); + + tokio::time::timeout(Duration::from_secs(1), wake_mine.changed()) + .await + .expect("woken") + .expect("open"); + assert!(!wake_other.has_changed().expect("open")); + } +} diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index be73ee2..6eb392c 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -1,5 +1,101 @@ -//! The `im` binary. Placeholder until the server, CLI and UI land; it only prints its name. +//! The `im` binary: the command line, logging and the process lifetime. +//! +//! `im [--config ] [serve]` runs the server; a bare `im` does the same. `im admin ...` is the +//! operator command line, which is not built yet. The configuration file is the `--config` path, +//! then `IM_CONFIG`, then `config/im.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. -fn main() { - println!("im"); +mod assets; +mod boot; +mod health; +mod i18n; +mod live; +mod pages; +mod security; +mod state; +mod views; + +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +use tracing_subscriber::EnvFilter; + +/// Printed with a usage error. +const USAGE: &str = "usage: im [--config ] [serve]"; + +/// The configuration file when neither `--config` nor `IM_CONFIG` names one. +const DEFAULT_CONFIG: &str = "config/im.toml"; + +/// The environment variable that names the configuration file. +const CONFIG_ENV: &str = "IM_CONFIG"; + +/// The parsed command line: the `--config` path and the positional words. +struct Cli { + config: Option, + words: Vec, +} + +/// Splits the arguments into the `--config ` pair and the positional words. +fn parse_args(args: impl Iterator) -> Result { + let mut config = None; + let mut words = Vec::new(); + let mut args = args; + while let Some(arg) = args.next() { + if arg == "--config" { + let path = args.next().ok_or("--config needs a path")?; + config = Some(PathBuf::from(path)); + } else { + words.push(arg); + } + } + Ok(Cli { config, words }) +} + +/// The configuration path: the flag, else `IM_CONFIG`, else the default. +fn config_path(flag: Option) -> PathBuf { + flag.or_else(|| std::env::var_os(CONFIG_ENV).map(PathBuf::from)) + .unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG)) +} + +/// Logs to stderr. The level comes from `RUST_LOG`, and defaults to `info`. +fn init_logging() { + let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); + tracing_subscriber::fmt() + .with_env_filter(filter) + .with_writer(std::io::stderr) + .init(); +} + +/// Runs the server and maps its outcome to an exit status. +async fn serve(config: &Path) -> ExitCode { + match boot::serve(config).await { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + tracing::error!(error = %error, "im stopped with an error"); + ExitCode::FAILURE + } + } +} + +#[tokio::main] +async fn main() -> ExitCode { + init_logging(); + let cli = match parse_args(std::env::args().skip(1)) { + Ok(cli) => cli, + Err(message) => { + eprintln!("im: {message}\n{USAGE}"); + return ExitCode::from(2); + } + }; + let words: Vec<&str> = cli.words.iter().map(String::as_str).collect(); + match words.as_slice() { + [] | ["serve"] => serve(&config_path(cli.config)).await, + ["admin", ..] => { + eprintln!("im: admin commands are not implemented yet"); + ExitCode::from(2) + } + _ => { + eprintln!("im: unknown command\n{USAGE}"); + ExitCode::from(2) + } + } } diff --git a/crates/im-web/src/pages/home.rs b/crates/im-web/src/pages/home.rs new file mode 100644 index 0000000..5577a3a --- /dev/null +++ b/crates/im-web/src/pages/home.rs @@ -0,0 +1,26 @@ +//! The start page. For now it only shows that the server runs; it becomes the account home once +//! sign-in exists. + +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::page; +use topcoat::view::{View, view}; + +use crate::i18n::lang; +use crate::i18n::shell::{K, t}; +use crate::views::{notice, shell}; + +/// `GET /`. +#[page("/")] +async fn home(cx: &Cx) -> Result { + let lang = lang(cx, None); + Ok(view! { + shell(title: t(lang, K::ImIsRunning), lang: lang, viewer: None, +
+

"im"

+

(t(lang, K::ImIsRunning))

+ notice(message: t(lang, K::RunningBody)) +
+ ) + }) +} diff --git a/crates/im-web/src/pages/mod.rs b/crates/im-web/src/pages/mod.rs new file mode 100644 index 0000000..2f18c8a --- /dev/null +++ b/crates/im-web/src/pages/mod.rs @@ -0,0 +1,4 @@ +//! The pages and the page-level layers. One file per page. + +pub mod home; +pub mod not_found; diff --git a/crates/im-web/src/pages/not_found.rs b/crates/im-web/src/pages/not_found.rs new file mode 100644 index 0000000..b1e4e74 --- /dev/null +++ b/crates/im-web/src/pages/not_found.rs @@ -0,0 +1,74 @@ +//! The styled 404 page. Topcoat answers an unknown path with a bare text body. For a browser +//! (`Accept` names `text/html`) the layer below rewrites that answer to a page in the regular +//! shell. Other clients keep the plain 404, and so does any request whose path exists. + +use http::header::ACCEPT; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::error::{NotFoundError, rewrite}; +use topcoat::router::page; +use topcoat::router::request::headers; +use topcoat::router::response::Response; +use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode}; +use topcoat::view::{View, component, view}; + +use crate::i18n::shell::{K, t}; +use crate::i18n::{Lang, lang}; +use crate::views::{empty_state, shell}; + +/// Where a browser's 404 is sent. The page below answers with status 404 itself. +const NOT_FOUND_PATH: &str = "/-/not-found"; + +/// Rewrites a 404 for a browser to the styled page. Pathless, so it sees every request. +pub struct NotFoundLayer; + +impl Layer for NotFoundLayer { + fn path(&self) -> Option<&Path> { + None + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(styled_not_found(cx, body, next)) + } +} + +/// Runs the rest of the chain. If it ended in a 404 and the client asked for HTML, the request is +/// rewritten to [`NOT_FOUND_PATH`]. Every other outcome is returned unchanged. +async fn styled_not_found(cx: &Cx, body: Body, next: Next<'_>) -> Result { + let result = next.run(cx, body).await; + let missing = matches!(&result, Err(error) if error.downcast_ref::().is_some()); + let wants_html = headers(cx) + .get(ACCEPT) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value.contains("text/html")); + if !missing || !wants_html { + return result; + } + Err(rewrite(NOT_FOUND_PATH, Body::empty()) + .method(Method::GET) + .into()) +} + +/// The 404 page itself. +#[page("/-/not-found")] +async fn not_found_page(cx: &Cx) -> Result { + let lang = lang(cx, None); + Ok(view! { + (StatusCode::NOT_FOUND) + shell(title: t(lang, K::NotFoundTitle), lang: lang, viewer: None, not_found_body(lang: lang)) + }) +} + +/// The 404 content: the code, then the empty-state card with the explanation and a way back. +#[component] +async fn not_found_body(lang: Lang) -> Result { + Ok(view! { +
+

"404"

+ empty_state(title: t(lang, K::NotFoundTitle), +

(t(lang, K::NotFoundBody))

+ (t(lang, K::BackHome)) + ) +
+ }) +} diff --git a/crates/im-web/src/security.rs b/crates/im-web/src/security.rs new file mode 100644 index 0000000..8687abb --- /dev/null +++ b/crates/im-web/src/security.rs @@ -0,0 +1,85 @@ +//! The security headers of every response, and the Content-Security-Policy they carry. +//! +//! The policy allows scripts and styles from the origin itself and nothing else. No page may use an +//! inline script, an inline style or an inline event handler: all behaviour lives in +//! `crates/im-web/assets/*.js`. Changing [`CSP`] is a security change, so keep it in step with +//! `docs/conventions.md` section 5. + +use topcoat::context::Cx; +use topcoat::router::response::response_headers; +use topcoat::router::{Body, HeaderMap, HeaderValue, Layer, LayerFuture, Next, Path, header}; + +/// The Content-Security-Policy of every response. +pub const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \ + form-action 'self'; frame-ancestors 'none'; base-uri 'none'"; + +/// One year, in seconds. Sent only when the public origin is https. +const HSTS: &str = "max-age=31536000"; + +/// The headers that every response carries, for an instance at `base_url`. +pub fn headers_for(base_url: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert( + header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); + headers.insert( + header::REFERRER_POLICY, + HeaderValue::from_static("same-origin"), + ); + headers.insert( + header::CONTENT_SECURITY_POLICY, + HeaderValue::from_static(CSP), + ); + if base_url.starts_with("https://") { + headers.insert( + header::STRICT_TRANSPORT_SECURITY, + HeaderValue::from_static(HSTS), + ); + } + headers +} + +/// Adds a fixed set of headers to every response of the router. +/// +/// It uses the per-request response headers, which the router applies after the layers have run, +/// so error responses (404, 500) carry them as well. +pub struct SecurityHeaders { + headers: HeaderMap, +} + +impl SecurityHeaders { + /// A layer that adds `headers` to every response. + pub fn new(headers: HeaderMap) -> Self { + Self { headers } + } +} + +impl Layer for SecurityHeaders { + fn path(&self) -> Option<&Path> { + None + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(async move { + response_headers(cx).extend(self.headers.clone()); + next.run(cx, body).await + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hsts_only_for_https_origins() { + assert!( + headers_for("https://im.example.com").contains_key(header::STRICT_TRANSPORT_SECURITY) + ); + assert!( + !headers_for("http://127.0.0.1:7650").contains_key(header::STRICT_TRANSPORT_SECURITY) + ); + } +} diff --git a/crates/im-web/src/state.rs b/crates/im-web/src/state.rs new file mode 100644 index 0000000..5c4f8ca --- /dev/null +++ b/crates/im-web/src/state.rs @@ -0,0 +1,22 @@ +//! The state shared by every route. Topcoat hands it to each handler through the app context. + +use std::sync::Arc; + +use im_core::config::Config; +use im_core::store::Store; + +use crate::live::LiveHub; + +/// Everything a request handler reaches through the app context. Every field is cheap to clone. +#[allow(dead_code)] // The key and the hub are read by the sign-in and live pages that come next. +#[derive(Clone)] +pub struct AppState { + /// The configuration the process booted with. + pub config: Arc, + /// The database. Reads go to a pooled reader and writes to the single writer. + pub store: Store, + /// The instance key (`im.key`). Seals secrets at rest. + pub key: Arc<[u8; 32]>, + /// The change counters of the live pages. + pub live: Arc, +} diff --git a/crates/im-web/src/views/mod.rs b/crates/im-web/src/views/mod.rs new file mode 100644 index 0000000..7eb0b78 --- /dev/null +++ b/crates/im-web/src/views/mod.rs @@ -0,0 +1,89 @@ +//! Shared page chrome: the HTML shell and the small components every page is built from. +//! +//! `view!` escapes text and attribute values, so user data is safe in it by default. Nothing here +//! emits an inline script, style or event handler; see `security.rs`. + +use topcoat::Result; +use topcoat::view::{Child, View, component, view}; + +use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; +use crate::i18n::Lang; +use crate::i18n::shell::{K, t}; + +/// What the shell shows about the signed-in person. Nothing signs a person in yet, so every page +/// is built for an anonymous viewer. +#[allow(dead_code)] // Built by the sign-in code, which comes next. +pub struct ViewerInfo { + /// The name shown in the topbar. + pub name: String, + /// Whether the topbar shows the administrator badge. + pub is_admin: bool, +} + +/// The HTML document around a page. `title` is the page's own title; the document title adds the +/// app name. `child` is the page, placed in `
`. +/// +/// The topbar has the wordmark on the left, the service switcher in the middle (empty for now) and +/// the viewer's name on the right. `nav.js` reads the restart text from ``. +#[component] +pub async fn shell( + title: &str, + lang: Lang, + viewer: Option<&ViewerInfo>, + #[default] child: Child<'_>, +) -> Result { + let document_title = format!("{title} \u{b7} im"); + Ok(view! { + + + + + + (document_title) + + + + + + +
+ "im" + +
+ if let Some(viewer) = viewer { + (viewer.name.as_str()) + if viewer.is_admin { + (t(lang, K::Admin)) + } + } +
+
+
(child)
+ + + }) +} + +/// An error message for a failed action. Forms show it above their fields. +#[allow(dead_code)] // The first form that can fail a check uses it. +#[component] +pub async fn alert(message: &str) -> Result { + Ok(view! { }) +} + +/// A plain message that is not an error, such as a confirmation or a hint. +#[component] +pub async fn notice(message: &str) -> Result { + Ok(view! {
(message)
}) +} + +/// A section with nothing in it yet: a title, then what to do next. +#[component] +pub async fn empty_state(title: &str, #[default] child: Child<'_>) -> Result { + Ok(view! { +
+

(title)

+ (child) +
+ }) +} diff --git a/docs/attack-plan.md b/docs/attack-plan.md new file mode 100644 index 0000000..b000206 --- /dev/null +++ b/docs/attack-plan.md @@ -0,0 +1,71 @@ +# Attack plan + +How `im` (first), `in` and `iz` are attacked after each build step. Every finding becomes a fix commit plus, +when cheap, one regression test. Attacks run only against local instances on `127.0.0.1` with scratch data. + +## 1. im: authentication + +- Login: username enumeration by message, status, timing (unknown vs wrong password vs disabled); throttle + bypass (case/whitespace variants of the email, IPv6 /64 rotation, `X-Forwarded-For` spoofing without a + trusted proxy); throttle memory growth with random keys. +- Pre-CSRF: login without the cookie/field, with mismatched values, cross-site form post. +- 2FA: skip `/login/2fa` by going to `/` with the pending cookie; tamper/replay the pending cookie; reuse a TOTP + step; brute force within the window; recovery code reuse and race (two parallel submissions). +- Sessions: fixation (does login rotate the token?), cookie flags, logout really deletes, revoked session still + works on live streams, `max_sessions` race. +- Password reset / invite / email change: token reuse, parallel redemption race, expired token, token for + another user, enumeration through `/forgot`, links leaking into logs or redirects, email change to a taken + address at confirm time, confirm only one half. +- Setup: `/setup` after the first user exists; two parallel setups. + +## 2. im: OIDC + +- `/authorize`: open redirect via `redirect_uri` (prefix, case, trailing slash, userinfo `@`, encoded chars, + fragments), missing/plain PKCE, `response_type` other than `code`, scope injection, `state`/`nonce` echo + injection (XSS in error page), unknown/disabled client. +- `/token`: code reuse (must revoke the family), code for another client, wrong `redirect_uri`, wrong verifier, + expired code, client auth with the wrong secret, both basic and post at once, oversized bodies. +- Refresh: reuse of a rotated token (family revocation), refresh after logout/disable, refresh for another + client. +- Client credentials: scopes beyond `allowed_scopes`, `audience` not a family key, disabled client. +- JWT: `alg: none`, alg confusion, unknown `kid`, expired, `aud` array tricks, signature of another key, + retired key still accepted after 7 days. +- `/userinfo`, `/introspect`, `/revoke`: token of another client, revoked tokens. +- Back-channel: does every session end reach every client; is the outbox retried; does a failure block logout. +- `/logout`: `post_logout_redirect_uri` not registered (open redirect), missing `id_token_hint`. + +## 3. im: machine APIs + +- Directory/photo/family without a token, with a user access token instead of a client token, with the wrong + audience or scope, with an expired token. +- Stream: cursor from the future, negative, huge; resync path; connection exhaustion. +- Photo: path traversal in `{sub}`, huge upload, polyglot image (HTML/SVG in a PNG), content-type served. + +## 4. im: web + +- CSRF on every POST (missing, wrong, other session's token). +- Authorization: every admin route as a member and as anonymous (expect 404); last-admin demotion/disable; + self-disable; IDOR on sessions/apps revoke (another user's id). +- XSS: names, emails, client names, service names, user agents, audit data rendered everywhere (including the + admin pages and mails); CSP effectiveness. +- Headers on every response type (pages, JSON, SSE, assets, errors). +- Input limits: very long names, emails, passwords (argon2 cost DoS), huge forms, unicode tricks (homoglyph + emails, RTL override in names, NUL bytes). +- `safe_next` bypasses on every `next` parameter. +- Live: streams leak other users' data or keep running after sign-out. + +## 5. Operational + +- Kill the process mid-write; restart; integrity check. Disk full during photo upload. +- Backup → restore → compare. Restore refuses a tampered set. +- Config: unknown keys, missing file, bad values, secret files with loose permissions. +- Concurrency: 50 parallel logins, 20 parallel token exchanges with one code, SQLite busy errors surfacing as + 500s. + +## 6. in and iz + +The same web, CSRF, authz, XSS and header checks, plus: path traversal in names and blob keys, quota races with +parallel uploads, chunk index/size abuse, Range header abuse, share-link password brute force, grant leakage +through folder moves, trashed items reachable by grantees or links, service object namespace escape, iz role +escalation, viewer writes, cross-task IDOR on attachments/comments, mail header injection via names and +subjects, rule loops, reminder spam, zip bombs in sheet/slides viewers, SVG/HTML served inline. diff --git a/style/_base.scss b/style/_base.scss new file mode 100644 index 0000000..8d46022 --- /dev/null +++ b/style/_base.scss @@ -0,0 +1,117 @@ +//! Element defaults: the reset, the body type, links, headings and focus. Nothing here is a class; +//! a page gets its look from elements it writes plainly, and from the component classes. + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html { + -webkit-text-size-adjust: 100%; + text-size-adjust: 100%; +} + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font-family: var(--font-sans); + font-size: 1rem; + line-height: 1.55; + -webkit-font-smoothing: antialiased; +} + +h1, +h2, +h3 { + line-height: 1.25; + margin: 0 0 var(--space-3); + font-weight: 650; + letter-spacing: -0.01em; +} + +h1 { + font-size: var(--text-xl); +} + +h2 { + font-size: var(--text-lg); +} + +h3 { + font-size: 1rem; +} + +p { + margin: 0 0 var(--space-3); +} + +a { + color: var(--accent); + text-decoration-thickness: 1px; + text-underline-offset: 0.2em; +} + +a:hover { + color: var(--accent-strong); +} + +img, +svg { + display: block; + max-width: 100%; +} + +code, +kbd, +pre { + font-family: var(--font-mono); + font-size: 0.92em; +} + +:focus-visible { + outline: 2px solid var(--focus); + outline-offset: 2px; + border-radius: 2px; +} + +::selection { + background: var(--accent-soft); +} + +// The `hidden` attribute must win over any display rule a component sets. +[hidden] { + display: none !important; +} + +// Visible only to screen readers. +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +// The first focusable element. It is off screen until a keyboard user tabs to it. +.skip-link { + position: absolute; + top: var(--space-2); + left: var(--space-2); + z-index: 100; + padding: var(--space-2) var(--space-3); + background: var(--surface); + color: var(--text); + border-radius: var(--radius-sm); + box-shadow: var(--shadow-lift); + transform: translateY(-200%); +} + +.skip-link:focus { + transform: none; +} diff --git a/style/_components.scss b/style/_components.scss new file mode 100644 index 0000000..99cc0c5 --- /dev/null +++ b/style/_components.scss @@ -0,0 +1,315 @@ +//! Components: buttons, form controls, cards, alerts, tables, badges, the empty state, the 404 page +//! and the "server restarting" bar. Each is one class (or one element) with its states. + +// --- Buttons ----------------------------------------------------------------------------------- + +.button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: var(--space-2); + min-height: 2.25rem; + padding: var(--space-2) var(--space-4); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + background: var(--surface); + color: var(--text); + font: inherit; + font-weight: 550; + text-decoration: none; + cursor: pointer; + box-shadow: var(--shadow); + transition: background-color 120ms ease, border-color 120ms ease; +} + +.button:hover { + background: var(--surface-2); + color: var(--text); +} + +.button:disabled, +.button[aria-disabled="true"] { + opacity: 0.55; + cursor: not-allowed; +} + +.button.primary { + background: var(--accent); + border-color: var(--accent); + color: var(--accent-text); +} + +.button.primary:hover { + background: var(--accent-strong); + border-color: var(--accent-strong); + color: var(--accent-text); +} + +.button.danger { + color: var(--danger); + border-color: var(--danger); +} + +.button.ghost { + background: transparent; + box-shadow: none; + border-color: transparent; +} + +// --- Form controls ---------------------------------------------------------------------------- + +label { + display: block; + font-weight: 550; + font-size: var(--text-sm); + margin-bottom: var(--space-1); +} + +input:not([type="checkbox"]):not([type="radio"]), +select, +textarea { + width: 100%; + min-height: 2.25rem; + padding: var(--space-2) var(--space-3); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + background: var(--surface); + color: var(--text); + font: inherit; +} + +textarea { + min-height: 6rem; + resize: vertical; +} + +input:focus, +select:focus, +textarea:focus { + outline: 2px solid var(--focus); + outline-offset: 0; + border-color: transparent; +} + +input::placeholder, +textarea::placeholder { + color: var(--muted); + opacity: 0.8; +} + +.field { + display: grid; + gap: var(--space-1); +} + +.field + .field { + margin-top: var(--space-4); +} + +.field-hint { + color: var(--muted); + font-size: var(--text-sm); +} + +// --- Cards and text --------------------------------------------------------------------------- + +.card { + padding: var(--space-6); + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + box-shadow: var(--shadow); +} + +.card > :last-child { + margin-bottom: 0; +} + +.card-title { + margin-bottom: var(--space-2); +} + +.muted { + color: var(--muted); +} + +.kicker { + margin-bottom: var(--space-2); + color: var(--muted); + font-size: var(--text-sm); + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +// --- Alerts ----------------------------------------------------------------------------------- + +.alert, +.notice { + padding: var(--space-3) var(--space-4); + border-radius: var(--radius-sm); + border: 1px solid transparent; +} + +.alert { + background: var(--danger-soft); + color: var(--danger); + border-color: var(--danger); +} + +.notice { + background: var(--accent-soft); + color: var(--text); + border-color: var(--accent-soft); +} + +// --- Tables and badges ------------------------------------------------------------------------ + +.table-wrap { + overflow-x: auto; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); +} + +.table { + width: 100%; + border-collapse: collapse; + font-size: var(--text-sm); +} + +.table th, +.table td { + padding: var(--space-2) var(--space-3); + text-align: left; + border-bottom: 1px solid var(--border); + vertical-align: top; +} + +.table th { + color: var(--muted); + font-weight: 600; + background: var(--surface-2); +} + +.table tr:last-child td { + border-bottom: 0; +} + +.badge { + display: inline-block; + padding: 0.1rem var(--space-2); + border-radius: 999px; + background: var(--surface-2); + color: var(--muted); + font-size: 0.8rem; + font-weight: 600; + white-space: nowrap; +} + +.badge.accent { + background: var(--accent-soft); + color: var(--accent-strong); +} + +// --- Empty state and the 404 page ------------------------------------------------------------- + +.empty-state { + display: grid; + justify-items: center; + gap: var(--space-3); + padding: var(--space-8) var(--space-6); + text-align: center; + color: var(--muted); + border: 1px dashed var(--border); + border-radius: var(--radius); +} + +.empty-state h2 { + margin: 0; + color: var(--text); +} + +.empty-state p { + margin: 0; + max-width: 34rem; +} + +.not-found { + text-align: center; + padding-block: var(--space-8); +} + +.not-found-code { + margin: 0; + font-size: 3.5rem; + font-weight: 700; + letter-spacing: -0.03em; + color: var(--accent); + line-height: 1; +} + +// --- Server restarting bar -------------------------------------------------------------------- + +// Pinned to the bottom edge. nav.js creates it only while the server is unreachable, so a page +// that never loses the server never shows it. +.restart-bar { + position: fixed; + left: 50%; + bottom: var(--space-4); + z-index: 50; + transform: translateX(-50%); + display: flex; + align-items: center; + gap: var(--space-3); + max-width: calc(100vw - 2 * var(--space-4)); + padding: var(--space-2) var(--space-4); + border-radius: 999px; + background: var(--warn-soft); + color: var(--warn); + border: 1px solid var(--warn); + box-shadow: var(--shadow-lift); + font-size: var(--text-sm); + font-weight: 550; + animation: restart-in 180ms ease-out; +} + +.restart-bar::before { + content: ""; + width: 0.55rem; + height: 0.55rem; + border-radius: 50%; + background: currentColor; + animation: restart-pulse 1.2s ease-in-out infinite; +} + +@keyframes restart-in { + from { + opacity: 0; + transform: translate(-50%, 0.5rem); + } +} + +@keyframes restart-pulse { + 50% { + opacity: 0.25; + } +} + +// While the page is loading a soft navigation or a refresh, its content dims a little. +.is-loading main { + opacity: 0.6; + transition: opacity 120ms ease; +} + +@media (prefers-reduced-motion: reduce) { + .restart-bar, + .restart-bar::before { + animation: none; + } + + .is-loading main, + .button { + transition: none; + } +} diff --git a/style/_layout.scss b/style/_layout.scss new file mode 100644 index 0000000..a4b2827 --- /dev/null +++ b/style/_layout.scss @@ -0,0 +1,110 @@ +//! Page frame: the sticky top bar (wordmark, service switcher, right-hand slot) and the main column. +//! Below 720 px the top bar wraps onto two rows and the card grid goes to one column. + +.topbar { + position: sticky; + top: 0; + z-index: 20; + display: flex; + align-items: center; + gap: var(--space-4); + min-height: 3.25rem; + padding: var(--space-2) var(--space-6); + background: var(--topbar); + backdrop-filter: saturate(1.4) blur(8px); + border-bottom: 1px solid var(--border); +} + +.topbar-brand { + display: inline-flex; + align-items: baseline; + gap: var(--space-2); + color: var(--text); + font-weight: 700; + font-size: var(--text-lg); + text-decoration: none; + letter-spacing: -0.02em; +} + +.topbar-brand:hover { + color: var(--accent); +} + +// The service switcher fills the middle of the bar. It is empty until there are services to list. +.switcher { + display: flex; + align-items: center; + flex: 1 1 auto; + gap: var(--space-1); + min-width: 0; + overflow-x: auto; +} + +.switcher:empty { + display: none; +} + +.switcher a { + padding: var(--space-1) var(--space-3); + border-radius: var(--radius-sm); + color: var(--muted); + text-decoration: none; + white-space: nowrap; +} + +.switcher a[aria-current="page"], +.switcher a:hover { + background: var(--surface-2); + color: var(--text); +} + +.topbar-end { + display: flex; + align-items: center; + gap: var(--space-3); + margin-left: auto; + color: var(--muted); + font-size: var(--text-sm); +} + +.page { + width: 100%; + max-width: var(--content-width); + margin: 0 auto; + padding: var(--space-8) var(--space-6) var(--space-8); +} + +.page > * + * { + margin-top: var(--space-6); +} + +.grid-cards { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr)); + gap: var(--space-4); +} + +@media (max-width: 720px) { + .topbar { + flex-wrap: wrap; + gap: var(--space-2) var(--space-3); + padding: var(--space-2) var(--space-4); + } + + .switcher { + order: 3; + flex-basis: 100%; + } + + .topbar-end { + margin-left: 0; + } + + .page { + padding: var(--space-6) var(--space-4); + } + + .grid-cards { + grid-template-columns: 1fr; + } +} diff --git a/style/_tokens.scss b/style/_tokens.scss new file mode 100644 index 0000000..8329f6f --- /dev/null +++ b/style/_tokens.scss @@ -0,0 +1,90 @@ +//! Design tokens: the colours of the light and dark themes, spacing, radii and type. Every other +//! partial reads these custom properties, so a theme changes in one place. +//! +//! Dark applies in two cases. The OS asks for it (`prefers-color-scheme: dark`) and the page is not +//! forced to light, or the page sets `data-theme="dark"`. `data-theme="light"` forces light whatever +//! the OS says. The dark rules carry one more attribute than the light ones, so they win on the same +//! element without `!important`. + +/// The light palette. Contrast of `--text` on `--bg` and `--surface` is above 7:1. +@mixin light-tokens { + --bg: #f5f5f2; + --surface: #ffffff; + --surface-2: #eeeeea; + --text: #1c1e22; + --muted: #5b6070; + --border: #d9dbe0; + --accent: #3350c4; + --accent-strong: #2a43a8; + --accent-text: #ffffff; + --accent-soft: #e6ebff; + --danger: #b42318; + --danger-soft: #fdecea; + --warn: #7a4f00; + --warn-soft: #fff4d6; + --ok: #1e7a3a; + --ok-soft: #e4f4ea; + --focus: #3350c4; + --topbar: #ffffffe6; +} + +/// The dark palette. Same roles as the light one. +@mixin dark-tokens { + --bg: #111215; + --surface: #1a1c21; + --surface-2: #22252c; + --text: #e8eaef; + --muted: #a1a7b5; + --border: #2d3139; + --accent: #9fb2ff; + --accent-strong: #c2d0ff; + --accent-text: #0d1220; + --accent-soft: #1f2a4f; + --danger: #ff8a80; + --danger-soft: #3a1d1b; + --warn: #f2c265; + --warn-soft: #3a2e10; + --ok: #7fd09a; + --ok-soft: #173424; + --focus: #9fb2ff; + --topbar: #1a1c21e6; +} + +:root { + color-scheme: light; + @include light-tokens; + + --font-sans: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", + sans-serif; + --font-mono: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace; + + --radius: 10px; + --radius-sm: 6px; + --shadow: 0 1px 2px rgb(0 0 0 / 0.06); + --shadow-lift: 0 4px 14px rgb(0 0 0 / 0.08); + + --space-1: 0.25rem; + --space-2: 0.5rem; + --space-3: 0.75rem; + --space-4: 1rem; + --space-6: 1.5rem; + --space-8: 2rem; + + --text-sm: 0.875rem; + --text-lg: 1.125rem; + --text-xl: 1.5rem; + + --content-width: 56rem; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + color-scheme: dark; + @include dark-tokens; + } +} + +:root[data-theme="dark"] { + color-scheme: dark; + @include dark-tokens; +} diff --git a/style/main.scss b/style/main.scss new file mode 100644 index 0000000..d8e7b52 --- /dev/null +++ b/style/main.scss @@ -0,0 +1,8 @@ +//! The stylesheet of `im`. `build.rs` compiles this file with grass into `OUT_DIR/main.css`, and the +//! binary embeds the result. The order matters: tokens first, then the element defaults, the layout +//! and the components that use the tokens. + +@use "tokens"; +@use "base"; +@use "layout"; +@use "components";