From a4cbd4be58bb9584e30799e2add742f9d372334a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 08:59:02 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=89=20init:=20workspace,=20im-core=20b?= =?UTF-8?q?asics,=20store=20and=20initial=20schema?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 7 + Cargo.lock | 3527 +++++++++++++++++++++++ Cargo.toml | 57 + config/im.example.toml | 33 + crates/im-core/Cargo.toml | 32 + crates/im-core/migrations/0001_init.sql | 237 ++ crates/im-core/src/config.rs | 181 ++ crates/im-core/src/error.rs | 39 + crates/im-core/src/lib.rs | 14 + crates/im-core/src/password.rs | 125 + crates/im-core/src/secret.rs | 137 + crates/im-core/src/store/migrate.rs | 64 + crates/im-core/src/store/mod.rs | 290 ++ crates/im-core/src/store/snapshot.rs | 116 + crates/im-core/src/time.rs | 54 + crates/im-core/src/token.rs | 62 + crates/im-web/Cargo.toml | 13 + crates/im-web/src/main.rs | 5 + docs/architecture.md | 295 ++ docs/contracts.md | 241 ++ docs/conventions.md | 169 ++ docs/reference/old-inventory.md | 311 ++ 22 files changed, 6009 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 config/im.example.toml create mode 100644 crates/im-core/Cargo.toml create mode 100644 crates/im-core/migrations/0001_init.sql create mode 100644 crates/im-core/src/config.rs create mode 100644 crates/im-core/src/error.rs create mode 100644 crates/im-core/src/lib.rs create mode 100644 crates/im-core/src/password.rs create mode 100644 crates/im-core/src/secret.rs create mode 100644 crates/im-core/src/store/migrate.rs create mode 100644 crates/im-core/src/store/mod.rs create mode 100644 crates/im-core/src/store/snapshot.rs create mode 100644 crates/im-core/src/time.rs create mode 100644 crates/im-core/src/token.rs create mode 100644 crates/im-web/Cargo.toml create mode 100644 crates/im-web/src/main.rs create mode 100644 docs/architecture.md create mode 100644 docs/contracts.md create mode 100644 docs/conventions.md create mode 100644 docs/reference/old-inventory.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..33ae565 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +target/ +config/im.toml +data/ +*.db +*.db-wal +*.db-shm +*.key diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..3e8de2c --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,3527 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + +[[package]] +name = "aead" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" +dependencies = [ + "crypto-common 0.2.2", + "inout 0.2.5", +] + +[[package]] +name = "aegis" +version = "0.9.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41585f248ed9406567ae6d61ca2a55ed3dc7348e65203a01229881253acb95e3" +dependencies = [ + "cc", + "softaes", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher 0.4.4", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead 0.5.2", + "aes", + "cipher 0.4.4", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "allocator-api2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c880a97d28a3681c0267bd29cff89621202715b065127cd445fa0f0fe0aa2880" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "antithesis_sdk" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8ed6751597568a284314fd9e2db420665898600109dedc7d8d9b588f00ae9c4" +dependencies = [ + "libc", + "libloading", + "linkme", + "once_cell", + "rand 0.8.8", + "rustc_version_runtime", + "serde", + "serde_json", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arc-swap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" +dependencies = [ + "rustversion", +] + +[[package]] +name = "argon2" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures 0.3.1", + "password-hash", +] + +[[package]] +name = "aristo" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcdeefa800110050103e2459a2f8dbdbd560ad046e30f1f87e24ce19c2cb8bde" +dependencies = [ + "aristo-macros", +] + +[[package]] +name = "aristo-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d64a66d21a80182b35b1741997a6d2456911f54b7eb1918aa4e2382fc205268d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "assoc" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfdc70193dadb9d7287fa4b633f15f90c876915b31f6af17da307fc59c9859a8" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bigdecimal" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fa3f3d8cbf4dffcfe4991de61d012bef509a409ecbe9dd41049bfe32b4d4653" +dependencies = [ + "autocfg", + "libm", + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "bindgen" +version = "0.69.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools 0.12.1", + "lazy_static", + "lazycell", + "log", + "prettyplease 0.2.37", + "proc-macro2", + "quote", + "regex", + "rustc-hash 1.1.0", + "shlex 1.3.0", + "syn 2.0.119", + "which", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bitpacking" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96a7139abd3d9cebf8cd6f920a389cf3dc9576172e32f4563f188cae3c3eb019" +dependencies = [ + "crunchy", +] + +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "blake2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" +dependencies = [ + "digest", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bon" +version = "3.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05442cd7005532d0cfedec676b5b9333d2b4c7c3afabe2b1a9ce2742fbe2ee6" +dependencies = [ + "bon-macros", +] + +[[package]] +name = "bon-macros" +version = "3.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93833e97ac7c46ba97045afcf247238c27057538fcf2f06344662ddd5f567be6" +dependencies = [ + "darling", + "ident_case", + "prettyplease 0.3.0", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "branches" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7436b21fd6195415058eb41c9090e156b556bc7e0377bb57c5c026a421521525" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex 2.0.1", +] + +[[package]] +name = "census" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f4c707c6a209cbe82d10abd08e1ea8995e9ea937d2550646e02798948992be0" + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cfg_block" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18758054972164c3264f7c8386f5fc6da6114cb46b619fd365d4e3b2dc3ae487" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cipher 0.5.2", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chacha20poly1305" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb" +dependencies = [ + "aead 0.6.1", + "chacha20", + "cipher 0.5.2", + "poly1305", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout 0.1.4", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer", + "crypto-common 0.2.2", + "inout 0.2.5", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32c" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "getrandom 0.4.3", + "hybrid-array", + "rand_core 0.10.1", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher 0.4.4", +] + +[[package]] +name = "ctutils" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe3e9d21d39e6f39ff46e03d5b621424f88ee23d8a1672c6bfc9ccc7f2da4f6a" +dependencies = [ + "cmov", +] + +[[package]] +name = "curve25519-dalek" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rand_core 0.10.1", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.9", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "datasketches" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745" + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "downcast-rs" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" + +[[package]] +name = "ed25519" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" +dependencies = [ + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" +dependencies = [ + "curve25519-dalek", + "ed25519", + "rand_core 0.10.1", + "sha2", + "signature", + "subtle", + "zeroize", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "env_filter" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6" +dependencies = [ + "env_filter", + "log", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fastbloom" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7f34442dbe69c60fe8eaf58a8cafff81a1f278816d8ab4db255b3bef4ac3c4" +dependencies = [ + "getrandom 0.3.4", + "libm", + "siphasher", +] + +[[package]] +name = "fastdivide" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afc2bd4d5a73106dd53d10d73d3401c2f32730ba2c0b93ddb888a8983680471" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "fs4" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4" +dependencies = [ + "rustix 1.1.6", + "windows-sys 0.59.0", +] + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "genawaiter" +version = "0.99.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86bd0361bcbde39b13475e6e36cb24c329964aa2611be285289d1e4b751c1a0" +dependencies = [ + "genawaiter-macro", +] + +[[package]] +name = "genawaiter-macro" +version = "0.99.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b32dfe1fdfc0bbde1f22a5da25355514b5e450c33a6af6770884c8750aedfbc" + +[[package]] +name = "generator" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1be81b31c9ce4caf7f3178eeb90662bb1864d3ad363ec6bdada3201adff19c37" +dependencies = [ + "cc", + "cfg-if", + "libc", + "log", + "rustversion", + "windows-link", + "windows-result", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2 0.2.21", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "htmlescape" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9025058dae765dee5070ec375f591e2ba14638c63feff74f13805a72e523163" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collator" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24cb0205c419b2036da3f9082964905d6849b3f2130dd4a517940c45899a544b" +dependencies = [ + "icu_collator_data", + "icu_collections", + "icu_locale_core", + "icu_locale_fallback", + "icu_normalizer", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "zerovec", +] + +[[package]] +name = "icu_collator_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "183f47e821a327661c1ebe152f61d5b6c2000010d228cadbbf226e0e2b8c2634" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe8fa57bcddc15cb921582ee5259c5b77da39f946f188ca5213fad24d9241236" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_locale_data", + "icu_locale_fallback", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a64014dac577a11d8d2cee48517c73c1984bd72ab11031e934269bd3cefb2ad9" + +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[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", + "subtle", + "tempfile", + "thiserror", + "time", + "tokio", + "toml", + "tracing", + "turso", + "ulid", +] + +[[package]] +name = "im-web" +version = "0.1.0" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "inout" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "intrusive-collections" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86" +dependencies = [ + "memoffset", +] + +[[package]] +name = "inventory" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" +dependencies = [ + "rustversion", +] + +[[package]] +name = "io-uring" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb" +dependencies = [ + "bitflags", + "cfg-if", + "libc", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + +[[package]] +name = "levenshtein_automata" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c2cdeb66e45e9f36bfad5bbdb4d2384e70936afbee843c6f6543f0c551ebb25" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libmimalloc-sys" +version = "0.1.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9" +dependencies = [ + "cc", +] + +[[package]] +name = "linkme" +version = "0.3.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3045e122bd98aef8ec3ad58ce84f0791f64e70163d1a02710af4aa11a4d54cc5" +dependencies = [ + "linkme-impl", +] + +[[package]] +name = "linkme-impl" +version = "0.3.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77060ebe535362c3da75682cd17b0431017b6e7c5661e714fc69a7ad017d1301" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "loom" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "lru" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "lz4_flex" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "measure_time" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51c55d61e72fc3ab704396c5fa16f4c184db37978ae4e94ca8959693a235fc0e" +dependencies = [ + "log", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miette" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" +dependencies = [ + "cfg-if", + "miette-derive", + "unicode-width", +] + +[[package]] +name = "miette-derive" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "mimalloc" +version = "0.1.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862" +dependencies = [ + "libmimalloc-sys", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "murmurhash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "oneshot" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "269bca4c2591a28585d6bf10d9ed0332b7d76900a1b02bec41bdc3a2cdcda107" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "ordered-float" +version = "5.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ownedbytes" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fbd56f7631767e61784dc43f8580f403f4475bd4aaa4da003e6295e1bab4a7e" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "owo-colors" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" + +[[package]] +name = "pack1" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3b7bb0ecf2e447b1f20ee94ee79ef6eed1e9d4b3c36ce1903b9dea3bf205523" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "password-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b" +dependencies = [ + "getrandom 0.4.3", + "phc", +] + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "phc" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892" +dependencies = [ + "base64ct", + "ctutils", + "getrandom 0.4.3", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "poly1305" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c" +dependencies = [ + "cpufeatures 0.3.1", + "universal-hash 0.6.1", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash 0.5.1", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn 3.0.9", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" +dependencies = [ + "anyhow", + "itertools 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "rapidhash" +version = "4.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5da7e78a036ce858e8d55b7e7dc8ba3a88b78350fd2155d3591bbd966b58589e" +dependencies = [ + "rustversion", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "roaring" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18bd8a37d17a58532776dcdf6041ce64929adca78e8489d5cacbafe99229d3e1" +dependencies = [ + "bytemuck", + "byteorder", +] + +[[package]] +name = "rust-stemmers" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e46a2036019fdb888131db7a4c847a1063a7493f971ed94ea82c67eada63ca54" +dependencies = [ + "serde", + "serde_derive", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustc_version_runtime" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dd18cd2bae1820af0b6ad5e54f4a51d0f3fcc53b05f845675074efcc7af071d" +dependencies = [ + "rustc_version", + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[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.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "shuttle" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab17edba38d63047f46780cf7360acf7467fec2c048928689a5c1dd1c2b4e31" +dependencies = [ + "assoc", + "bitvec", + "cfg-if", + "generator", + "hex", + "owo-colors", + "rand 0.8.8", + "rand_core 0.6.4", + "rand_pcg", + "scoped-tls", + "smallvec", + "tracing", +] + +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "simsimd" +version = "6.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4fb3bc3cdce07a7d7d4caa4c54f8aa967f6be41690482b54b24100a2253fa70" +dependencies = [ + "cc", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "sketches-ddsketch" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e53e2f8d4e9c692f23a90208fad6a64862f413e286d533f1f649f160e2d5caee" +dependencies = [ + "serde", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "softaes" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4fdfe13e1c42e45f497416afb8dc4e783bf0e25b7be9077c1c77c5fb14cb998" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tantivy" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "861facfabd71044968f364837f9a083b56464ba5a59079f88706ee5c451ca069" +dependencies = [ + "aho-corasick", + "arc-swap", + "base64 0.22.1", + "bitpacking", + "bon", + "byteorder", + "census", + "crc32fast", + "crossbeam-channel", + "datasketches", + "downcast-rs", + "fastdivide", + "fnv", + "fs4", + "htmlescape", + "itertools 0.14.0", + "levenshtein_automata", + "log", + "lru", + "lz4_flex", + "measure_time", + "memmap2", + "once_cell", + "oneshot", + "rayon", + "regex", + "rust-stemmers", + "rustc-hash 2.1.3", + "serde", + "serde_json", + "sketches-ddsketch", + "smallvec", + "tantivy-bitpacker", + "tantivy-columnar", + "tantivy-common", + "tantivy-fst", + "tantivy-query-grammar", + "tantivy-stacker", + "tantivy-tokenizer-api", + "tempfile", + "thiserror", + "time", + "typetag", + "uuid", + "winapi", +] + +[[package]] +name = "tantivy-bitpacker" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fed3d674429bcd2de5d0a6d1aa5495fed8afd9c5ecce993019caf7615f53fa4" +dependencies = [ + "bitpacking", +] + +[[package]] +name = "tantivy-columnar" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c57166f5bcfd478f370ab8445afb4678dce44801fa5ce5c451aaf8595583c5dc" +dependencies = [ + "downcast-rs", + "fastdivide", + "itertools 0.14.0", + "serde", + "tantivy-bitpacker", + "tantivy-common", + "tantivy-sstable", + "tantivy-stacker", +] + +[[package]] +name = "tantivy-common" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbf10915aa75da3c3b0d58b58853d2e889efbaf32d4982a4c3715dde6bba23e5" +dependencies = [ + "async-trait", + "byteorder", + "ownedbytes", + "serde", + "time", +] + +[[package]] +name = "tantivy-fst" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d60769b80ad7953d8a7b2c70cdfe722bbcdcac6bccc8ac934c40c034d866fc18" +dependencies = [ + "byteorder", + "regex-syntax", + "utf8-ranges", +] + +[[package]] +name = "tantivy-query-grammar" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfadb8526b6da90704feb293b0701a6aae62ea14983143344be2dc5ce30f1d82" +dependencies = [ + "fnv", + "nom", + "ordered-float", + "serde", + "serde_json", +] + +[[package]] +name = "tantivy-sstable" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a2cfc3ac5164cbadc28965ffb145a8f47582a60ae5897859ad8d4316596c606" +dependencies = [ + "futures-util", + "itertools 0.14.0", + "tantivy-bitpacker", + "tantivy-common", + "tantivy-fst", + "zstd", +] + +[[package]] +name = "tantivy-stacker" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cbb051742da9d53ca9e8fff43a9b10e319338b24e2c0e15d0372df19ffeb951" +dependencies = [ + "murmurhash32", + "tantivy-common", +] + +[[package]] +name = "tantivy-tokenizer-api" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eac258c2c6390673f2685813afeeafcb8c4e0ee7de8dd3fc46838dcc37263f98" +dependencies = [ + "serde", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", + "tokio-macros", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror", + "time", + "tracing-subscriber", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "turso" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1cf9c519a3a971e845a42c870930557cb53c2368c5737d4c78f8fbfd0444e98" +dependencies = [ + "mimalloc", + "thiserror", + "tracing", + "tracing-subscriber", + "turso_core", + "turso_sdk_kit", + "turso_sync_sdk_kit", +] + +[[package]] +name = "turso_core" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "810ee7b139fd6aa9304cb2fa278c1be0bb964c92457e2a24c1d384196ce5e217" +dependencies = [ + "aegis", + "aes", + "aes-gcm", + "allocator-api2 0.4.0", + "antithesis_sdk", + "arc-swap", + "aristo", + "bigdecimal", + "bitflags", + "branches", + "bumpalo", + "bytemuck", + "cfg_aliases", + "cfg_block", + "chrono", + "crc32c", + "crc32fast", + "crossbeam-epoch", + "crossbeam-utils", + "either", + "fallible-iterator", + "fastbloom", + "getrandom 0.2.17", + "getrandom 0.3.4", + "hex", + "icu_collator", + "icu_locale", + "intrusive-collections", + "io-uring", + "libc", + "libloading", + "libm", + "loom", + "miette", + "num-bigint", + "num-traits", + "pack1", + "parking_lot", + "pastey", + "polling", + "rand 0.9.5", + "rapidhash", + "regex", + "regex-syntax", + "roaring", + "rustc-hash 2.1.3", + "rustix 1.1.6", + "ryu", + "serde_json", + "shuttle", + "simdutf8", + "simsimd", + "smallvec", + "strum", + "strum_macros", + "tantivy", + "tempfile", + "thiserror", + "tracing", + "tracing-subscriber", + "turso_ext", + "turso_macros", + "turso_parser", + "twox-hash", + "uncased", + "uuid", + "windows-sys 0.61.2", +] + +[[package]] +name = "turso_ext" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5003ed7e98f082fe4114627c8d7c7ab569c27766e9bd350a0c09af06ad3fd46" +dependencies = [ + "chrono", + "getrandom 0.4.3", + "turso_macros", +] + +[[package]] +name = "turso_macros" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74770c0d0c8b272b479b5343f19dbd2f8f2677d85a4d6222fc214dcac2882beb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "turso_parser" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bb856ec8306ad7ed1c13fc61de6a79452bf646ca53d99bb4cc646d5bfc4ff" +dependencies = [ + "bitflags", + "memchr", + "miette", + "strum", + "strum_macros", + "thiserror", + "turso_macros", +] + +[[package]] +name = "turso_sdk_kit" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819a17926d04dbeb5b03f00cdab6ed7351bbb6778d00840364b9af62bca02914" +dependencies = [ + "bindgen", + "env_logger", + "parking_lot", + "tracing", + "tracing-appender", + "tracing-subscriber", + "turso_core", + "turso_ext", + "turso_sdk_kit_macros", +] + +[[package]] +name = "turso_sdk_kit_macros" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f315d7f8c5bba49d1c7ca000664a455085cb95f0fa8031c6dc1f67d6d0f28e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "turso_sync_engine" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8d37dca9e05cc090ca3d73083f82fc63b0d11c33550308ca5d93668a8441b71" +dependencies = [ + "base64 0.22.1", + "bytes", + "crc32c", + "genawaiter", + "http", + "libc", + "prost", + "roaring", + "serde", + "serde_json", + "thiserror", + "tracing", + "turso_core", + "turso_parser", + "uuid", +] + +[[package]] +name = "turso_sync_sdk_kit" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fe4b961c9cc90f6339447dabfe83ed13a498721e41378932ab7eaf8ddd6976" +dependencies = [ + "bindgen", + "env_logger", + "genawaiter", + "parking_lot", + "tracing", + "tracing-appender", + "tracing-subscriber", + "turso_core", + "turso_sdk_kit", + "turso_sdk_kit_macros", + "turso_sync_engine", +] + +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" +dependencies = [ + "rand 0.10.3", +] + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "typetag" +version = "0.2.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c90e86058a30d42a1a928dfb4b49bb33c98c3a2b4909492e6b0881cd94798ec2" +dependencies = [ + "erased-serde", + "inventory", + "once_cell", + "serde", + "typetag-impl", +] + +[[package]] +name = "typetag-impl" +version = "0.2.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f153acc4e99a5f2a5aefa09fb078be54e26271b2813f6041200b224c098d8328" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "ulid" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "947dde63b6d514cc5e044edad4e0ca7261afd1099d16c83d942cb2b2f348689c" +dependencies = [ + "rand 0.10.3", + "web-time", +] + +[[package]] +name = "uncased" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "universal-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" +dependencies = [ + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[package]] +name = "utf8-ranges" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcfc827f90e53a02eaef5e535ee14266c1d569214c6aa70133a624d8a3164ba" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "sha1_smol", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix 0.38.44", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.2+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..ecac8b8 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,57 @@ +[workspace] +resolver = "3" +members = [ + "crates/im-core", + "crates/im-web", +] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "AGPL-3.0-or-later" + +[workspace.dependencies] +argon2 = "0.6.0" +base64 = "0.23.1" +chacha20poly1305 = "0.11.0" +ed25519-dalek = { version = "3.0.0", features = ["rand_core"] } +hex = "0.4.3" +ipnet = "2.12.2" +rand = "0.10.3" +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +sha2 = "0.11.1" +subtle = "2.6.1" +thiserror = "2.0.21" +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" +turso = "0.8.3" +ulid = "3.0.0" +tempfile = "3.27.0" +# internal crates +im-core = { path = "crates/im-core" } + +[workspace.lints.rust] +unsafe_code = "forbid" + +[profile.dev] +# Line tables keep file:line in backtraces but drop variable info; binaries and links are much smaller. +debug = "line-tables-only" + +[profile.dev.package.argon2] +# Password hashing (argon2id) takes hundreds of ms per call when unoptimized; release is unaffected. +opt-level = 3 + +[profile.dev.package.sha2] +# Hashing session and token digests on every request is too slow unoptimized. +opt-level = 3 + +[profile.dev.package.turso] +# The embedded database engine is too slow unoptimized to run the store tests quickly. +opt-level = 3 + +[profile.release] +lto = true +codegen-units = 1 diff --git a/config/im.example.toml b/config/im.example.toml new file mode 100644 index 0000000..79d1c2b --- /dev/null +++ b/config/im.example.toml @@ -0,0 +1,33 @@ +# im configuration. This file is committed as the example. The live file is config/im.toml (gitignored), +# and it is created from this one on first run when it is missing. Secrets never go in this file: enter +# them in the admin UI, where they are sealed in the database. + +# SQLite-format database. Relative paths are relative to the working directory. +database = "data/im.db" + +# Holds the instance key (im.key), photos and backups. Created with mode 0700 when missing. +data_dir = "data" + +# Address the HTTP server binds to. Put a TLS-terminating reverse proxy in front of it in production. +listen = "127.0.0.1:8080" + +# Public origin, with no trailing slash. This is the OpenID issuer and the origin of links in mail. +base_url = "http://localhost:8080" + +# Proxies whose X-Forwarded-For header is believed, as addresses or CIDR networks. Empty means the +# TCP peer is always the client address. +trusted_proxies = [] + +[mail] +# Development only: write mail to data/mail-log/ instead of sending it. +log_only = true + +[backup] +# Directory for scheduled backups. Empty turns them off. +dir = "" +# Hours between two scheduled backups. At least 1. +interval_hours = 24 +# Snapshot sets kept. At least 1. +keep = 7 +# Dead-man URL pinged after each run. Empty for none. +healthcheck_url = "" diff --git a/crates/im-core/Cargo.toml b/crates/im-core/Cargo.toml new file mode 100644 index 0000000..fdba214 --- /dev/null +++ b/crates/im-core/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "im-core" +version.workspace = true +edition.workspace = true +license.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +argon2.workspace = true +base64.workspace = true +chacha20poly1305.workspace = true +ed25519-dalek.workspace = true +hex.workspace = true +ipnet.workspace = true +rand.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +subtle.workspace = true +thiserror.workspace = true +time.workspace = true +tokio.workspace = true +toml.workspace = true +tracing.workspace = true +turso.workspace = true +ulid.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/im-core/migrations/0001_init.sql b/crates/im-core/migrations/0001_init.sql new file mode 100644 index 0000000..06aaaa9 --- /dev/null +++ b/crates/im-core/migrations/0001_init.sql @@ -0,0 +1,237 @@ +-- 0001: the whole initial schema of im. Every table, its constraints and its lookup indexes. +-- Ids are ULID text; timestamps are fixed-width UTC RFC 3339 text; booleans are INTEGER 0/1. +-- Never edit this file once it has been applied anywhere; add 0002_... instead. + +CREATE TABLE users ( + id TEXT PRIMARY KEY, + email TEXT NOT NULL, + email_folded TEXT NOT NULL UNIQUE, + name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 100), + password_hash TEXT NOT NULL, + is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)), + disabled_at TEXT, + -- Sealed TOTP secret. Held while enrolling (totp_enabled_at NULL) and kept after enabling. + totp_secret_sealed TEXT, + totp_enabled_at TEXT, + totp_last_step INTEGER, + locale TEXT NOT NULL DEFAULT 'en' CHECK (locale IN ('en', 'tr')), + zoneinfo TEXT NOT NULL DEFAULT 'Europe/Istanbul', + theme TEXT NOT NULL DEFAULT 'system' CHECK (theme IN ('system', 'light', 'dark')), + photo_mime TEXT, + picture_version INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +-- Ten codes per set, shown once. Only their hashes are stored; used_at marks a consumed code. +CREATE TABLE recovery_codes ( + user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + code_hash TEXT NOT NULL, + used_at TEXT, + PRIMARY KEY (user_id, code_hash) +); + +-- Browser sessions. The id is the OIDC `sid`. Ended sessions are deleted, after their +-- back-channel logout jobs are queued. +CREATE TABLE sessions ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + token_hash TEXT NOT NULL UNIQUE, + csrf_token TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + last_seen_at TEXT NOT NULL, + ip TEXT, + user_agent TEXT, + auth_time TEXT NOT NULL, + amr TEXT NOT NULL CHECK (amr IN ('pwd', 'pwd otp', 'pwd rc')) +); +CREATE INDEX sessions_user ON sessions (user_id); +CREATE INDEX sessions_expires ON sessions (expires_at); + +-- OIDC clients. secret_hash is the hash of the client secret; the secret itself is shown once. +CREATE TABLE clients ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + secret_hash TEXT NOT NULL, + secret_rotated_at TEXT NOT NULL, + redirect_uris TEXT NOT NULL DEFAULT '[]' CHECK (json_valid (redirect_uris)), + post_logout_redirect_uris TEXT NOT NULL DEFAULT '[]' CHECK (json_valid (post_logout_redirect_uris)), + backchannel_logout_uri TEXT, + allowed_scopes TEXT NOT NULL, + service_key TEXT UNIQUE, + created_at TEXT NOT NULL, + disabled_at TEXT +); + +-- The switcher list. im's own row (key 'im') is maintained at boot from base_url. +CREATE TABLE services ( + key TEXT PRIMARY KEY CHECK ( + length(key) BETWEEN 1 AND 32 + AND key GLOB '[a-z]*' + AND key NOT GLOB '*[^a-z0-9-]*' + ), + name TEXT NOT NULL, + url TEXT NOT NULL, + position INTEGER NOT NULL DEFAULT 0, + client_id TEXT REFERENCES clients (id) ON DELETE SET NULL, + healthy INTEGER CHECK (healthy IS NULL OR healthy IN (0, 1)), + checked_at TEXT, + check_ms INTEGER, + check_error TEXT +); + +-- One-time authorization codes. A second use of a used code revokes the refresh tokens issued +-- from it (refresh_tokens.code_hash). +CREATE TABLE auth_codes ( + code_hash TEXT PRIMARY KEY, + client_id TEXT NOT NULL REFERENCES clients (id) ON DELETE CASCADE, + user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + session_id TEXT NOT NULL REFERENCES sessions (id) ON DELETE CASCADE, + redirect_uri TEXT NOT NULL, + scope TEXT NOT NULL, + nonce TEXT, + -- PKCE S256 is mandatory for every client (contracts.md 2.3). + code_challenge TEXT NOT NULL, + expires_at TEXT NOT NULL, + used_at TEXT +); +CREATE INDEX auth_codes_expires ON auth_codes (expires_at); + +-- Refresh tokens, rotated on every use. Presenting a used token revokes its whole family. +CREATE TABLE refresh_tokens ( + id TEXT PRIMARY KEY, + token_hash TEXT NOT NULL UNIQUE, + family_id TEXT NOT NULL, + client_id TEXT NOT NULL REFERENCES clients (id) ON DELETE CASCADE, + user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + session_id TEXT NOT NULL REFERENCES sessions (id) ON DELETE CASCADE, + -- Plain text, not a foreign key: authorization codes are swept while their tokens live on. + code_hash TEXT, + scope TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + used_at TEXT, + revoked_at TEXT +); +CREATE INDEX refresh_tokens_family ON refresh_tokens (family_id); +CREATE INDEX refresh_tokens_session ON refresh_tokens (session_id); + +-- Which clients a browser session has signed in to. Drives back-channel logout and the +-- "connected apps" list. +CREATE TABLE client_sessions ( + session_id TEXT NOT NULL REFERENCES sessions (id) ON DELETE CASCADE, + client_id TEXT NOT NULL REFERENCES clients (id) ON DELETE CASCADE, + first_at TEXT NOT NULL, + last_at TEXT NOT NULL, + PRIMARY KEY (session_id, client_id) +); +CREATE INDEX client_sessions_client ON client_sessions (client_id); + +-- Token-signing keys. kid is the first 16 hex characters of the SHA-256 of the public key. The +-- current key is the newest one that is active and not retired. +CREATE TABLE signing_keys ( + kid TEXT PRIMARY KEY, + private_sealed TEXT NOT NULL, + public_raw BLOB NOT NULL, + created_at TEXT NOT NULL, + activates_at TEXT NOT NULL, + retires_at TEXT +); +CREATE INDEX signing_keys_current ON signing_keys (activates_at) WHERE retires_at IS NULL; + +-- Invitations. The token is stored as its hash. A new invite for an address deletes its older +-- pending invites. +CREATE TABLE invites ( + token_hash TEXT PRIMARY KEY, + email_folded TEXT NOT NULL, + is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)), + invited_by TEXT REFERENCES users (id) ON DELETE SET NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + accepted_at TEXT +); +CREATE INDEX invites_email ON invites (email_folded); + +-- Single-use links for password reset and both halves of an email change. The two halves of one +-- email change share pair_id. +CREATE TABLE account_links ( + token_hash TEXT PRIMARY KEY, + kind TEXT NOT NULL CHECK (kind IN ('reset', 'email_old', 'email_new')), + user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + pair_id TEXT, + new_email TEXT, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + used_at TEXT +); +CREATE INDEX account_links_user ON account_links (user_id); +CREATE INDEX account_links_pair ON account_links (pair_id); + +-- Outgoing mail, sent by the mail worker with retries. Links in bodies are never logged. +CREATE TABLE mail_outbox ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL CHECK (kind IN ( + 'invite', 'reset', 'email_old', 'email_new', 'email_done', 'notice', 'test', 'security' + )), + to_addr TEXT NOT NULL, + subject TEXT NOT NULL, + body_text TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')), + attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0), + next_attempt_at TEXT NOT NULL, + last_error TEXT, + created_at TEXT NOT NULL, + sent_at TEXT +); +CREATE INDEX mail_outbox_due ON mail_outbox (state, next_attempt_at); + +-- Back-channel logout deliveries to clients, sent by the back-channel worker. +CREATE TABLE backchannel_outbox ( + id TEXT PRIMARY KEY, + client_id TEXT NOT NULL REFERENCES clients (id) ON DELETE CASCADE, + sid TEXT, + sub TEXT NOT NULL, + reason TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')), + attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0), + next_attempt_at TEXT NOT NULL, + last_error TEXT, + created_at TEXT NOT NULL, + done_at TEXT +); +CREATE INDEX backchannel_outbox_due ON backchannel_outbox (state, next_attempt_at); + +-- The change feed for machine clients. seq is the cursor. Rows older than 30 days are pruned. +CREATE TABLE directory_changes ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + sub TEXT NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('member', 'deleted')), + at TEXT NOT NULL +); +CREATE INDEX directory_changes_at ON directory_changes (at); + +-- Append-only record of changes. actor_id and target_id are not foreign keys, so the trail +-- survives the deletion of the user it names. data never holds secrets. +CREATE TABLE audit_log ( + id TEXT PRIMARY KEY, + at TEXT NOT NULL, + actor_id TEXT, + actor_kind TEXT NOT NULL CHECK (actor_kind IN ('user', 'client', 'cli', 'system', 'anonymous')), + action TEXT NOT NULL, + target_kind TEXT, + target_id TEXT, + ip TEXT, + data TEXT CHECK (data IS NULL OR json_valid (data)) +); +CREATE INDEX audit_log_at ON audit_log (at); +CREATE INDEX audit_log_actor ON audit_log (actor_id, at); +CREATE INDEX audit_log_target ON audit_log (target_kind, target_id, at); + +-- Runtime setting overrides (admin UI values and the sealed SMTP password). Precedence is +-- override, then config file, then built-in default. +CREATE TABLE settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL +); diff --git a/crates/im-core/src/config.rs b/crates/im-core/src/config.rs new file mode 100644 index 0000000..9cec896 --- /dev/null +++ b/crates/im-core/src/config.rs @@ -0,0 +1,181 @@ +//! The instance configuration, read from TOML. +//! +//! Only non-secret, deployment-level settings live here. Secrets are never in this file: they are +//! entered in the admin UI and sealed in the database, or kept in a separate file that only the +//! service user can read. Every struct rejects unknown keys, so a typo fails at boot instead of +//! silently doing nothing. + +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; + +use ipnet::IpNet; +use serde::{Deserialize, Deserializer}; + +use crate::error::{Error, Result}; + +/// The example file. It is written to the config path on first run when that path is missing. +const EXAMPLE: &str = include_str!("../../../config/im.example.toml"); + +/// Parses each entry as a CIDR network, or as a single address (a /32 or /128). +fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result, D::Error> { + let entries = Vec::::deserialize(deserializer)?; + entries + .iter() + .map(|entry| { + entry + .parse::() + .or_else(|_| entry.parse::().map(IpNet::from)) + .map_err(|_| serde::de::Error::custom(format!("invalid trusted proxy `{entry}`"))) + }) + .collect() +} + +/// Outbound mail settings that do not involve a secret. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct MailConfig { + /// When true, mail is written to `data_dir/mail-log/` instead of being sent. For development + /// only; a production instance sends mail through the SMTP sender set in the admin UI. + pub log_only: bool, +} + +/// Scheduled backups. Off while `dir` is empty. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct BackupConfig { + /// Directory that receives one snapshot set per run. Empty turns backups off. + pub dir: PathBuf, + /// Hours between two scheduled backups. Must be at least 1 when backups are on. + pub interval_hours: u64, + /// Number of snapshot sets kept; older sets are deleted after a successful run. At least 1. + pub keep: u32, + /// Dead-man URL pinged after each run (`/start`, then success or `/fail`). Empty for none. + pub healthcheck_url: String, +} + +impl Default for BackupConfig { + fn default() -> Self { + Self { + dir: PathBuf::new(), + interval_hours: 24, + keep: 7, + healthcheck_url: String::new(), + } + } +} + +impl BackupConfig { + /// True when a backup directory is set. + pub fn enabled(&self) -> bool { + !self.dir.as_os_str().is_empty() + } +} + +/// The whole file. Field names are the TOML keys. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + /// Path of the SQLite-format database file. + pub database: PathBuf, + /// Directory for the instance key, photos, backups and other files beside the database. + pub data_dir: PathBuf, + /// Address the HTTP server binds to. + pub listen: SocketAddr, + /// Public origin of this instance, such as `https://id.example.com`. No trailing slash. Used + /// for links in mail and for the OpenID issuer. + pub base_url: String, + /// Peers whose `X-Forwarded-For` header is believed. Entries are addresses or CIDR networks. + /// Empty by default, so the TCP peer is always the client. + #[serde(default, deserialize_with = "deserialize_trusted_proxies")] + pub trusted_proxies: Vec, + /// Mail settings without secrets. + #[serde(default)] + pub mail: MailConfig, + /// Scheduled backups. + #[serde(default)] + pub backup: BackupConfig, +} + +impl Config { + /// Reads and validates the file at `path`. + /// + /// When the file does not exist, the example file is written there first (creating its parent + /// directory), so a fresh checkout runs with development defaults. + pub fn load(path: &Path) -> Result { + let text = match std::fs::read_to_string(path) { + Ok(text) => text, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + std::fs::create_dir_all(parent)?; + } + std::fs::write(path, EXAMPLE)?; + EXAMPLE.to_owned() + } + Err(e) => return Err(e.into()), + }; + Self::parse(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display()))) + } + + /// Parses and validates TOML text. Used by [`Config::load`] and by tests. + pub fn parse(text: &str) -> Result { + let config: Config = toml::from_str(text).map_err(|e| Error::Config(format!("{e}")))?; + config.validate()?; + Ok(config) + } + + /// The cross-field rules that cannot be expressed per field. Run after parsing. + pub fn validate(&self) -> Result<()> { + if self.database.as_os_str().is_empty() { + return Err(Error::Config("database must not be empty".into())); + } + if self.data_dir.as_os_str().is_empty() { + return Err(Error::Config("data_dir must not be empty".into())); + } + validate_base_url(&self.base_url)?; + if self.backup.enabled() { + if self.backup.interval_hours == 0 { + return Err(Error::Config( + "[backup] interval_hours must be at least 1".into(), + )); + } + if self.backup.keep == 0 { + return Err(Error::Config("[backup] keep must be at least 1".into())); + } + } + let hc = &self.backup.healthcheck_url; + if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) { + return Err(Error::Config( + "[backup] healthcheck_url must be an http or https URL".into(), + )); + } + Ok(()) + } +} + +/// Checks that `base_url` is an http(s) origin with a path of at most `/`. +fn validate_base_url(url: &str) -> Result<()> { + let rest = url + .strip_prefix("https://") + .or_else(|| url.strip_prefix("http://")) + .ok_or_else(|| Error::Config("base_url must start with http:// or https://".into()))?; + if rest.is_empty() || rest.ends_with('/') || url.chars().any(char::is_whitespace) { + return Err(Error::Config( + "base_url must be an origin with no trailing slash or spaces".into(), + )); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_file_parses_and_rejects_unknown_keys() { + Config::parse(EXAMPLE).expect("the example must be valid"); + let typo = format!("{EXAMPLE}\nlisen = \"0.0.0.0:1\"\n"); + assert!(Config::parse(&typo).is_err()); + } +} diff --git a/crates/im-core/src/error.rs b/crates/im-core/src/error.rs new file mode 100644 index 0000000..c0af2ea --- /dev/null +++ b/crates/im-core/src/error.rs @@ -0,0 +1,39 @@ +//! The error type shared by every `im-core` module. +//! +//! `Invalid` and `Conflict` carry text that is safe to show the user. Every other variant is a +//! server-side failure: the web layer answers with a generic page and logs the cause. + +/// Everything `im-core` can fail with. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// A filesystem operation failed. + #[error("io error: {0}")] + Io(#[from] std::io::Error), + /// The database rejected a statement or could not be opened. + #[error("database error: {0}")] + Database(String), + /// A migration could not be recorded or applied. + #[error("migration error: {0}")] + Migration(String), + /// The configuration file is unreadable or breaks a cross-field rule. + #[error("config error: {0}")] + Config(String), + /// Sealing, opening, hashing or the instance key failed. + #[error("crypto error: {0}")] + Crypto(String), + /// The row asked for does not exist, or the caller may not know that it does. + #[error("not found")] + NotFound, + /// The request clashes with existing state, such as a taken email address. Shown to the user. + #[error("conflict: {0}")] + Conflict(String), + /// The caller may not do this. Shown to the user. + #[error("forbidden: {0}")] + Forbidden(String), + /// The input is malformed or breaks a policy. Shown to the user. + #[error("invalid value: {0}")] + Invalid(String), +} + +/// `Result` with the crate error. +pub type Result = std::result::Result; diff --git a/crates/im-core/src/lib.rs b/crates/im-core/src/lib.rs new file mode 100644 index 0000000..8f89589 --- /dev/null +++ b/crates/im-core/src/lib.rs @@ -0,0 +1,14 @@ +//! Domain core of `im`: errors, time, secrets, tokens, passwords, configuration and the store. +//! +//! This crate has no HTTP code. It holds the pieces every other part of `im` depends on, so that +//! the web binary cannot get a security primitive or a database rule wrong by re-implementing it. + +pub mod config; +pub mod error; +pub mod password; +pub mod secret; +pub mod store; +pub mod time; +pub mod token; + +pub use error::{Error, Result}; diff --git a/crates/im-core/src/password.rs b/crates/im-core/src/password.rs new file mode 100644 index 0000000..053cf08 --- /dev/null +++ b/crates/im-core/src/password.rs @@ -0,0 +1,125 @@ +//! Password hashing with argon2id, and the password policy. +//! +//! Hashes are PHC strings with a random salt. Hashing and verifying take hundreds of milliseconds +//! by design, so the async wrappers move that work onto the blocking thread pool; a request task +//! must never run argon2 inline. + +use argon2::Argon2; +use argon2::password_hash::phc::PasswordHash; +use argon2::password_hash::{PasswordHasher, PasswordVerifier}; + +use crate::error::{Error, Result}; + +/// Shortest accepted password, in characters. Length is the main defence against guessing, so it +/// is set well above what people choose by habit. +pub const MIN_PASSWORD_CHARS: usize = 10; + +/// Longest accepted password, in characters. Bounds the work an attacker can force argon2 to do +/// per request. +pub const MAX_PASSWORD_CHARS: usize = 256; + +/// Shortest word of the name or email local part that a password may not contain, in characters. +/// Shorter words are too common to forbid: a two-letter word would reject many good passwords. +pub const MIN_FORBIDDEN_WORD_CHARS: usize = 4; + +/// Hashes `pw` with argon2id (default parameters) and a fresh random salt. Returns a PHC string. +pub fn hash_password(pw: &str) -> Result { + Argon2::default() + .hash_password(pw.as_bytes()) + .map(|h| h.to_string()) + .map_err(|e| Error::Crypto(format!("argon2: {e}"))) +} + +/// Returns true only if `pw` matches the PHC string `hash`. A malformed hash gives false, never +/// a panic. +pub fn verify_password(pw: &str, hash: &str) -> bool { + let Ok(parsed) = PasswordHash::new(hash) else { + return false; + }; + Argon2::default() + .verify_password(pw.as_bytes(), &parsed) + .is_ok() +} + +/// [`hash_password`] on the blocking thread pool. +pub async fn hash_password_async(pw: String) -> Result { + tokio::task::spawn_blocking(move || hash_password(&pw)) + .await + .map_err(|e| Error::Crypto(format!("hashing task failed: {e}")))? +} + +/// [`verify_password`] on the blocking thread pool. +pub async fn verify_password_async(pw: String, hash: String) -> Result { + tokio::task::spawn_blocking(move || verify_password(&pw, &hash)) + .await + .map_err(|e| Error::Crypto(format!("verify task failed: {e}"))) +} + +/// Checks a new password against the policy. +/// +/// Rules: 10 to 256 characters; it must not contain the email local part (when that is at least +/// [`MIN_FORBIDDEN_WORD_CHARS`] long) or any word of the name that is at least that long, compared +/// case-insensitively. The rule that the password differs from the current one needs the stored +/// hash and is checked by the caller. +/// +/// Returns `Error::Invalid` with a message that is safe to show the user. +pub fn check_policy(password: &str, email: &str, name: &str) -> Result<()> { + let chars = password.chars().count(); + if chars < MIN_PASSWORD_CHARS { + return Err(Error::Invalid(format!( + "password must be at least {MIN_PASSWORD_CHARS} characters" + ))); + } + if chars > MAX_PASSWORD_CHARS { + return Err(Error::Invalid(format!( + "password must be at most {MAX_PASSWORD_CHARS} characters" + ))); + } + + let lowered = password.to_lowercase(); + let local_part = email.split('@').next().unwrap_or_default(); + let forbidden = std::iter::once(local_part) + .chain(name.split(|c: char| !c.is_alphanumeric())) + .map(str::to_lowercase) + .filter(|word| word.chars().count() >= MIN_FORBIDDEN_WORD_CHARS); + for word in forbidden { + if lowered.contains(&word) { + return Err(Error::Invalid( + "password must not contain your email address or name".into(), + )); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hash_then_verify_accepts_only_the_same_password() { + let hash = hash_password("correct horse").unwrap(); + assert!(hash.starts_with("$argon2id$")); + assert!(verify_password("correct horse", &hash)); + assert!(!verify_password("wrong", &hash)); + assert!(!verify_password("pw", "not a phc string")); + } + + #[test] + fn policy_enforces_length_bounds() { + assert!(check_policy("short", "a@example.com", "Ada").is_err()); + assert!(check_policy("nine-char", "a@example.com", "Ada").is_err()); + assert!(check_policy("ten-chars!", "a@example.com", "Ada").is_ok()); + let long = "x".repeat(MAX_PASSWORD_CHARS + 1); + assert!(check_policy(&long, "a@example.com", "Ada").is_err()); + } + + #[test] + fn policy_rejects_email_local_part_and_name_words_case_insensitively() { + let email = "tahinli@example.com"; + assert!(check_policy("My-TAHINLI-pass", email, "Ada").is_err()); + assert!(check_policy("correct Lovelace horse", email, "Ada Lovelace").is_err()); + // Words under four characters do not count, so "Ada" alone does not block a password. + assert!(check_policy("my ada horse 1", email, "Ada").is_ok()); + } +} diff --git a/crates/im-core/src/secret.rs b/crates/im-core/src/secret.rs new file mode 100644 index 0000000..362a310 --- /dev/null +++ b/crates/im-core/src/secret.rs @@ -0,0 +1,137 @@ +//! The instance key and XChaCha20-Poly1305 sealing of secrets at rest. +//! +//! A sealed value is `v1:` followed by base64(nonce || ciphertext). The nonce is random for every +//! seal, so sealing the same plaintext twice gives different text. The key never goes in the +//! database; it lives in a 0600 file beside the data. + +use std::path::Path; + +use base64::prelude::{BASE64_STANDARD, Engine as _}; +use chacha20poly1305::aead::Aead; +use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; + +use crate::error::{Error, Result}; + +const PREFIX: &str = "v1:"; +const NONCE_LEN: usize = 24; + +/// Loads the 32-byte instance key at `path`, creating it if it is missing. +/// +/// A new key is written with mode 0600 and `O_EXCL`, so two starts cannot both create it. An +/// existing key with any group or world permission is refused, because a leaked key defeats every +/// sealed secret. +pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]> { + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + std::fs::create_dir_all(parent)?; + } + match create_key(path) { + Ok(key) => Ok(key), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => read_key(path), + Err(e) => Err(e.into()), + } +} + +fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { + use std::io::Write; + + use rand::TryRng; + + let mut key = [0u8; 32]; + rand::rngs::SysRng + .try_fill_bytes(&mut key) + .map_err(std::io::Error::other)?; + + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(path)?; + let written = file.write_all(&key).and_then(|()| file.sync_all()); + if let Err(e) = written { + // A truncated key would be rejected at the next start, so remove it now. + drop(file); + let _ = std::fs::remove_file(path); + return Err(e); + } + Ok(key) +} + +fn read_key(path: &Path) -> Result<[u8; 32]> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(path)?.permissions().mode(); + if mode & 0o077 != 0 { + return Err(Error::Crypto(format!( + "instance key {} is group/world accessible (mode {:o}); expected 0600", + path.display(), + mode & 0o777 + ))); + } + } + let bytes = std::fs::read(path)?; + <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| { + Error::Crypto(format!( + "instance key {} has length {}, expected 32", + path.display(), + bytes.len() + )) + }) +} + +/// Seals `plaintext` under `key`. Output: `"v1:" + base64(nonce || ciphertext)`. +/// +/// Errors if the cipher rejects the input. The caller must then refuse to store the value, never +/// store it in clear. +pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result { + let mut nonce = [0u8; NONCE_LEN]; + rand::fill(&mut nonce); + let cipher = XChaCha20Poly1305::new(key.into()); + let ciphertext = cipher + .encrypt(&XNonce::from(nonce), plaintext) + .map_err(|_| Error::Crypto("sealing failed".into()))?; + let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len()); + blob.extend_from_slice(&nonce); + blob.extend_from_slice(&ciphertext); + Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob))) +} + +/// Opens a value produced by [`seal`] under the same key. +/// +/// Any failure (bad prefix, bad base64, short input, wrong key, tampering) is an error. The +/// messages are fixed strings, so nothing about the plaintext or the key can leak through them. +pub fn open(key: &[u8; 32], sealed: &str) -> Result> { + let encoded = sealed + .strip_prefix(PREFIX) + .ok_or_else(|| Error::Crypto("sealed value has no v1 prefix".into()))?; + let blob = BASE64_STANDARD + .decode(encoded) + .map_err(|_| Error::Crypto("sealed value is not valid base64".into()))?; + if blob.len() < NONCE_LEN { + return Err(Error::Crypto("sealed value is too short".into())); + } + let (nonce, ciphertext) = blob.split_at(NONCE_LEN); + let nonce = <[u8; NONCE_LEN]>::try_from(nonce) + .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?; + let cipher = XChaCha20Poly1305::new(key.into()); + cipher + .decrypt(&XNonce::from(nonce), ciphertext) + .map_err(|_| Error::Crypto("sealed value failed authentication".into())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn seal_then_open_returns_the_plaintext_and_rejects_another_key() { + let key = [7u8; 32]; + let sealed = seal(&key, b"hello secret").unwrap(); + assert!(sealed.starts_with("v1:")); + assert_eq!(open(&key, &sealed).unwrap(), b"hello secret"); + assert!(open(&[8u8; 32], &sealed).is_err()); + } +} diff --git a/crates/im-core/src/store/migrate.rs b/crates/im-core/src/store/migrate.rs new file mode 100644 index 0000000..48cda05 --- /dev/null +++ b/crates/im-core/src/store/migrate.rs @@ -0,0 +1,64 @@ +//! Migration runner. Applied versions are recorded in `schema_migrations`. +//! +//! A migration file is never edited once applied; a change is a new numbered file. Each migration +//! runs in its own transaction together with its `schema_migrations` row, so a failure leaves +//! nothing half-applied. + +use turso::Connection; + +use crate::error::{Error, Result}; +use crate::time::now_stamp; + +/// `(version, sql)` in ascending order, with no gaps. Add each new file here. +pub const MIGRATIONS: &[(u32, &str)] = &[(1, include_str!("../../migrations/0001_init.sql"))]; + +fn migration_err(e: turso::Error) -> Error { + Error::Migration(e.to_string()) +} + +/// Applies every migration whose version is not yet recorded. Running it again is a no-op. +pub async fn migrate(conn: &Connection) -> Result<()> { + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)", + ) + .await + .map_err(migration_err)?; + + let applied = applied_versions(conn).await?; + for &(version, sql) in MIGRATIONS { + let version = i64::from(version); + if applied.contains(&version) { + continue; + } + let tx = conn.unchecked_transaction().await.map_err(migration_err)?; + tx.execute_batch(sql).await.map_err(migration_err)?; + tx.execute( + "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, ?2)", + (version, now_stamp()), + ) + .await + .map_err(migration_err)?; + tx.commit().await.map_err(migration_err)?; + tracing::info!(version, "applied database migration"); + } + Ok(()) +} + +async fn applied_versions(conn: &Connection) -> Result> { + let mut rows = conn + .query("SELECT version FROM schema_migrations ORDER BY version", ()) + .await + .map_err(migration_err)?; + let mut versions = Vec::new(); + while let Some(row) = rows.next().await.map_err(migration_err)? { + match row.get_value(0).map_err(migration_err)? { + turso::Value::Integer(v) => versions.push(v), + _ => { + return Err(Error::Migration( + "schema_migrations.version is not an integer".into(), + )); + } + } + } + Ok(versions) +} diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs new file mode 100644 index 0000000..383a7af --- /dev/null +++ b/crates/im-core/src/store/mod.rs @@ -0,0 +1,290 @@ +//! Turso-backed storage. All persistent state lives in this database; the key file and photos sit +//! beside it in `data_dir`. +//! +//! Connections: one writer behind a tokio mutex, and a pool of read-only connections. Writes, +//! transactions and read-then-write sequences use the writer; a pure SELECT may use a reader. Every +//! connection gets WAL, `synchronous = FULL`, `foreign_keys = ON` and a busy timeout, and the values +//! in effect are logged at boot. + +pub mod migrate; +pub mod snapshot; + +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use tokio::sync::{Mutex, MutexGuard}; +use turso::transaction::Transaction; +use turso::{Builder, Connection, Database, IntoParams, Row, Value}; + +use crate::error::{Error, Result}; +use crate::time::now_stamp; + +/// How long a statement waits for a lock held by another connection before it fails. +const BUSY_TIMEOUT: Duration = Duration::from_millis(5000); + +/// Number of read-only connections in the pool. +const READER_COUNT: usize = 4; + +/// Handle to the database. Cheap to clone; every clone shares the same connections. +/// +/// Rule for [`Store::read_conn`]: use it only for a function that is a pure SELECT and does not +/// need to see a write made in the same call. Anything in a transaction, any write, and any +/// read-then-write sequence goes through the writer. +#[derive(Clone)] +pub struct Store { + inner: Arc, +} + +struct Inner { + /// Kept alive for as long as the connections are in use. + _db: Database, + /// The single writer. + conn: Mutex, + /// Read-only connections, each with `PRAGMA query_only = 1`. + readers: Vec>, + /// Round-robin start index for `read_conn`. + next_reader: AtomicUsize, +} + +impl Store { + /// Opens (creating if needed) the database at `path`, applies the connection pragmas and runs + /// any pending migrations. Readers are opened after migrations so their schema view is current. + pub async fn open(path: &Path) -> Result { + let path_str = path.to_str().ok_or_else(|| { + Error::Config(format!("database path is not UTF-8: {}", path.display())) + })?; + let db = Builder::new_local(path_str).build().await.map_err(db_err)?; + let conn = db.connect().map_err(db_err)?; + apply_pragmas(&conn).await; + migrate::migrate(&conn).await?; + + let mut readers = Vec::with_capacity(READER_COUNT); + for _ in 0..READER_COUNT { + let reader = db.connect().map_err(db_err)?; + apply_pragmas(&reader).await; + apply_query_only(&reader).await?; + readers.push(Mutex::new(reader)); + } + Ok(Store { + inner: Arc::new(Inner { + _db: db, + conn: Mutex::new(conn), + readers, + next_reader: AtomicUsize::new(0), + }), + }) + } + + /// Returns a read-only pooled connection. It tries each reader without waiting, starting at the + /// round-robin index, and falls back to waiting on the start reader when all are busy. + pub async fn read_conn(&self) -> MutexGuard<'_, Connection> { + let len = self.inner.readers.len(); + let start = self.inner.next_reader.fetch_add(1, Ordering::Relaxed) % len; + for offset in 0..len { + let idx = (start + offset) % len; + if let Some(guard) = self.inner.readers.get(idx).and_then(|m| m.try_lock().ok()) { + return guard; + } + } + self.inner.readers[start].lock().await + } + + /// 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; + let row = fetch_opt(&conn, "SELECT COUNT(*) FROM users", (), |row| { + col_int(row, 0) + }) + .await? + .ok_or_else(missing_row)?; + u64::try_from(row).map_err(|_| Error::Database("negative count".into())) + } + + /// The stored value of a runtime setting, or `None` when it has no override. + pub async fn setting(&self, key: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + "SELECT value FROM settings WHERE key = ?1", + (key.to_string(),), + |row| col_text(row, 0), + ) + .await + } + + /// Stores (or replaces) a runtime setting. Writes through the writer connection. + pub async fn set_setting(&self, key: &str, value: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3) \ + ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", + (key.to_string(), value.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + Ok(()) + } +} + +/// Ends a transaction: commits when `outcome` is `Ok`, rolls back otherwise, and returns the +/// outcome. Every multi-statement write ends with this, so no path leaves a transaction open. +pub async fn finish(tx: Transaction<'_>, outcome: Result) -> Result { + match outcome { + Ok(value) => { + tx.commit().await.map_err(db_err)?; + Ok(value) + } + Err(e) => { + let _ = tx.rollback().await; + Err(e) + } + } +} + +/// Converts a Turso error to the crate error. +pub(crate) fn db_err(e: turso::Error) -> Error { + Error::Database(e.to_string()) +} + +fn missing_row() -> Error { + Error::Database("expected a row that is not there".into()) +} + +/// Makes a connection refuse writes. Turso takes `1`, not `ON`. Failure is fatal: a reader that +/// could write would break the pool's rule. +async fn apply_query_only(conn: &Connection) -> Result<()> { + let mut rows = conn + .query("PRAGMA query_only = 1", ()) + .await + .map_err(db_err)?; + while rows.next().await.map_err(db_err)?.is_some() {} + Ok(()) +} + +/// Applies the connection pragmas. A pragma that is not supported is logged and skipped, never +/// fatal. The values actually in effect are logged afterwards. +async fn apply_pragmas(conn: &Connection) { + for sql in [ + "PRAGMA journal_mode = WAL", + "PRAGMA synchronous = FULL", + "PRAGMA foreign_keys = ON", + ] { + let applied = async { + let mut rows = conn.query(sql, ()).await?; + while rows.next().await?.is_some() {} + Ok::<(), turso::Error>(()) + } + .await; + if let Err(e) = applied { + tracing::warn!(pragma = sql, error = %e, "database pragma not applied"); + } + } + if let Err(e) = conn.busy_timeout(BUSY_TIMEOUT) { + tracing::warn!(error = %e, "busy_timeout not applied"); + } + for name in ["journal_mode", "synchronous", "foreign_keys"] { + match fetch_opt(conn, &format!("PRAGMA {name}"), (), |row| { + col_to_string(row, 0) + }) + .await + { + Ok(value) => tracing::info!(pragma = name, value = ?value, "database pragma in effect"), + Err(e) => tracing::warn!(pragma = name, error = %e, "could not read database pragma"), + } + } +} + +/// Runs a query and maps every row. Returns an empty vector for no rows. +pub(crate) async fn fetch_all( + conn: &Connection, + sql: &str, + params: P, + map: impl Fn(&Row) -> Result, +) -> Result> +where + P: IntoParams, +{ + let mut rows = conn.query(sql, params).await.map_err(db_err)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(db_err)? { + out.push(map(&row)?); + } + Ok(out) +} + +/// Runs a query and maps its first row, or returns `None` when there is none. +pub(crate) async fn fetch_opt( + conn: &Connection, + sql: &str, + params: P, + map: impl Fn(&Row) -> Result, +) -> Result> +where + P: IntoParams, +{ + let mut rows = conn.query(sql, params).await.map_err(db_err)?; + match rows.next().await.map_err(db_err)? { + Some(row) => Ok(Some(map(&row)?)), + None => Ok(None), + } +} + +/// Reads a text column. Any other type is a database error. +pub(crate) fn col_text(row: &Row, i: usize) -> Result { + match row.get_value(i).map_err(db_err)? { + Value::Text(s) => Ok(s), + _ => Err(Error::Database(format!("column {i} is not text"))), + } +} + +/// Reads an integer column. Any other type is a database error. +pub(crate) fn col_int(row: &Row, i: usize) -> Result { + match row.get_value(i).map_err(db_err)? { + Value::Integer(n) => Ok(n), + _ => Err(Error::Database(format!("column {i} is not an integer"))), + } +} + +/// Reads a column as text, accepting integers too. Used for PRAGMA results, which are text for +/// some pragmas and integers for others. +pub(crate) fn col_to_string(row: &Row, i: usize) -> Result { + match row.get_value(i).map_err(db_err)? { + Value::Text(s) => Ok(s), + Value::Integer(n) => Ok(n.to_string()), + _ => Err(Error::Database(format!( + "column {i} is not text or integer" + ))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn open_twice_applies_migrations_once_and_keeps_data() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("im.db"); + { + let store = Store::open(&path).await.unwrap(); + store.set_setting("invite_days", "7").await.unwrap(); + } + let store = Store::open(&path).await.unwrap(); + assert_eq!(store.user_count().await.unwrap(), 0); + assert_eq!( + store.setting("invite_days").await.unwrap().as_deref(), + Some("7") + ); + assert_eq!(store.setting("missing").await.unwrap(), None); + + let conn = store.read_conn().await; + let applied = fetch_all(&conn, "SELECT version FROM schema_migrations", (), |row| { + col_int(row, 0) + }) + .await + .unwrap(); + assert_eq!(applied, vec![1]); + } +} diff --git a/crates/im-core/src/store/snapshot.rs b/crates/im-core/src/store/snapshot.rs new file mode 100644 index 0000000..9b01bab --- /dev/null +++ b/crates/im-core/src/store/snapshot.rs @@ -0,0 +1,116 @@ +//! Consistent, self-contained copies of the database for backups. +//! +//! Method: `VACUUM INTO` on the writer connection, which holds its lock for the whole copy so no +//! other statement can interleave. The copy is then checkpointed so that the main file alone holds +//! every row, and fsynced. A live database file is never copied byte for byte. + +use std::path::Path; + +use turso::Builder; + +use super::{col_int, db_err, fetch_all}; +use crate::error::{Error, Result}; +use crate::store::Store; + +impl Store { + /// Writes a consistent copy of the database to `dest`. `dest` must not exist yet. + pub async fn snapshot_to(&self, dest: &Path) -> Result<()> { + if std::fs::symlink_metadata(dest).is_ok() { + return Err(Error::Conflict(format!( + "snapshot target already exists: {}", + dest.display() + ))); + } + let text = path_text(dest)?; + let sql = format!("VACUUM INTO {}", sql_string_literal(text)?); + { + let conn = self.inner.conn.lock().await; + conn.execute(&sql, ()).await.map_err(db_err)?; + } + make_self_contained(dest).await?; + std::fs::File::open(dest)?.sync_all()?; + Ok(()) + } +} + +fn path_text(path: &Path) -> Result<&str> { + path.to_str() + .ok_or_else(|| Error::Config(format!("snapshot path is not UTF-8: {}", path.display()))) +} + +/// Quotes `text` as an SQL string literal, refusing NUL bytes. +fn sql_string_literal(text: &str) -> Result { + if text.contains('\0') { + return Err(Error::Invalid("path contains NUL".into())); + } + Ok(format!("'{}'", text.replace('\'', "''"))) +} + +/// `VACUUM INTO` writes a WAL-mode file, so its rows may still sit in a `-wal` sidecar. This +/// checkpoints the copy until every frame is in the main file, then removes sidecars that are +/// empty. A sidecar that still holds bytes is an error, so the main file alone is the database. +async fn make_self_contained(dest: &Path) -> Result<()> { + let db = Builder::new_local(path_text(dest)?) + .build() + .await + .map_err(db_err)?; + let conn = db.connect().map_err(db_err)?; + // Columns of the checkpoint result: busy flag, frames in the log, frames checkpointed. + let status = fetch_all(&conn, "PRAGMA wal_checkpoint(TRUNCATE)", (), |row| { + Ok((col_int(row, 0)?, col_int(row, 1)?, col_int(row, 2)?)) + }) + .await?; + drop(conn); + drop(db); + match status.as_slice() { + [(0, log, done)] if log == done => {} + other => { + return Err(Error::Database(format!( + "checkpoint of the snapshot did not complete: {other:?}" + ))); + } + } + for suffix in ["-wal", "-shm"] { + let mut sidecar = dest.as_os_str().to_owned(); + sidecar.push(suffix); + let sidecar = Path::new(&sidecar); + match std::fs::metadata(sidecar) { + Err(_) => {} + Ok(meta) if meta.len() == 0 => std::fs::remove_file(sidecar)?, + Ok(meta) => { + return Err(Error::Database(format!( + "snapshot still has {} bytes in {}", + meta.len(), + sidecar.display() + ))); + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn snapshot_opens_with_its_data_and_refuses_an_existing_target() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); + store + .set_setting("base_url", "https://id.example") + .await + .unwrap(); + + let snap = dir.path().join("snap").join("im.db"); + std::fs::create_dir_all(snap.parent().unwrap()).unwrap(); + store.snapshot_to(&snap).await.unwrap(); + assert!(store.snapshot_to(&snap).await.is_err()); + + let copy = Store::open(&snap).await.unwrap(); + assert_eq!( + copy.setting("base_url").await.unwrap().as_deref(), + Some("https://id.example") + ); + } +} diff --git a/crates/im-core/src/time.rs b/crates/im-core/src/time.rs new file mode 100644 index 0000000..f857df8 --- /dev/null +++ b/crates/im-core/src/time.rs @@ -0,0 +1,54 @@ +//! UTC timestamps as stored in the database. +//! +//! The format is RFC 3339 with 9 fractional digits and a `Z` suffix. It has a fixed width, so +//! comparing two stamps as text gives the same order as comparing the times. + +use std::time::Duration; + +use time::{ + OffsetDateTime, SignedDuration, format_description::FormatItem, macros::format_description, +}; + +const FORMAT: &[FormatItem<'static>] = + format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z"); + +fn format_stamp(at: OffsetDateTime) -> String { + // The format description only uses fields that always format, so this cannot fail. + at.format(FORMAT).unwrap_or_default() +} + +/// Converts a `std` duration to the signed form `time` uses, saturating on overflow. +fn signed(d: Duration) -> SignedDuration { + SignedDuration::try_from(d).unwrap_or(SignedDuration::MAX) +} + +/// The current time as a stamp. +pub fn now_stamp() -> String { + format_stamp(OffsetDateTime::now_utc()) +} + +/// The stamp for `now + after`. Saturates at the maximum representable time instead of panicking. +pub fn stamp_after(after: Duration) -> String { + format_stamp(OffsetDateTime::now_utc().saturating_add(signed(after))) +} + +/// The stamp for `now - before`. Saturates at the minimum representable time instead of panicking. +pub fn stamp_before(before: Duration) -> String { + format_stamp(OffsetDateTime::now_utc().saturating_sub(signed(before))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stamps_have_fixed_width_and_sort_in_time_order() { + let now = now_stamp(); + let later = stamp_after(Duration::from_secs(3600)); + let much_later = stamp_after(Duration::from_secs(7200)); + assert_eq!(now.len(), 30, "bad stamp: {now}"); + assert!(now.ends_with('Z')); + assert!(now < later && later < much_later); + assert!(stamp_before(Duration::from_secs(3600)) < now); + } +} diff --git a/crates/im-core/src/token.rs b/crates/im-core/src/token.rs new file mode 100644 index 0000000..634bb08 --- /dev/null +++ b/crates/im-core/src/token.rs @@ -0,0 +1,62 @@ +//! Random tokens, codes, and the hashing and comparison rules that go with them. +//! +//! A token is 32 random bytes in base64url. Only its SHA-256 (hex) is stored, so a database leak +//! does not reveal live tokens. Codes typed by people use a readable alphabet with no look-alike +//! characters. + +use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; +use sha2::{Digest, Sha256}; +use subtle::ConstantTimeEq; + +/// Alphabet for codes typed by people: lowercase letters and the digits 2 to 9, without `l`, `o`, +/// `0` and `1`, which are easy to confuse. It has exactly 32 symbols, so the low five bits of a +/// random byte pick one uniformly, with no modulo bias. +pub const READABLE_ALPHABET: &[u8; 32] = b"abcdefghijkmnpqrstuvwxyz23456789"; + +/// A fresh token: 32 random bytes, base64url without padding (43 characters). +pub fn generate_token() -> String { + BASE64_URL_SAFE_NO_PAD.encode(random_32()) +} + +/// `len` random characters from [`READABLE_ALPHABET`]. +pub fn random_readable(len: usize) -> String { + let mut buf = vec![0u8; len]; + rand::fill(buf.as_mut_slice()); + buf.iter() + .map(|b| char::from(READABLE_ALPHABET[usize::from(b & 31)])) + .collect() +} + +/// The hex SHA-256 of `token`. This is what the database stores in place of the token. +pub fn hash_token(token: &str) -> String { + hex::encode(Sha256::digest(token.as_bytes())) +} + +/// Compares two byte strings in time that does not depend on where they first differ. +/// +/// Different lengths return false at once; the length of a secret is not itself secret here, +/// because every token of a kind has the same length. +pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { + a.ct_eq(b).into() +} + +/// 32 random bytes from the thread RNG, which is seeded from the operating system. It cannot fail, +/// so callers need no error path. +pub(crate) fn random_32() -> [u8; 32] { + let mut buf = [0u8; 32]; + rand::fill(&mut buf); + buf +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn constant_time_eq_matches_plain_equality() { + assert!(constant_time_eq(b"same", b"same")); + assert!(!constant_time_eq(b"same", b"diff")); + assert!(!constant_time_eq(b"short", b"longer")); + assert!(constant_time_eq(b"", b"")); + } +} diff --git a/crates/im-web/Cargo.toml b/crates/im-web/Cargo.toml new file mode 100644 index 0000000..99b0b57 --- /dev/null +++ b/crates/im-web/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "im-web" +version.workspace = true +edition.workspace = true +license.workspace = true +publish = false + +[lints] +workspace = true + +[[bin]] +name = "im" +path = "src/main.rs" diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs new file mode 100644 index 0000000..be73ee2 --- /dev/null +++ b/crates/im-web/src/main.rs @@ -0,0 +1,5 @@ +//! The `im` binary. Placeholder until the server, CLI and UI land; it only prints its name. + +fn main() { + println!("im"); +} diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..1b37d97 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,295 @@ +# im architecture + +`im` is the family's account service: an OpenID Connect provider, the people directory, and the service +registry. It is the root of the family: `in` and `iz` depend on it, it depends on nothing. Read +`docs/contracts.md` (the cross-app API) and `docs/conventions.md` (how code is written) first. + +Status: design for the rebuild. The previous implementation (`~/Documents/Code/Rust/old_im`) is a feature +reference only; its known defects are listed in section 11 so they are not carried over. + +--- + +## 1. Goals + +- **Boring and safe.** im guards every other app. It changes rarely and carefully. +- **Feature parity** with old im: password + TOTP sign-in, invites, password reset, two-sided email change, + profile photo, preferences, sessions, connected apps, admin panel (users, services/clients, SMTP, policy, + message, audit log, health), backups, CLI. +- **Better than old im:** CSRF on every form, recovery codes, admin 2FA reset, key rotation, refresh-token reuse + detection, back-channel logout, client-credentials machine tokens, no per-request introspection by apps, + security headers and a strict CSP, every page translated. + +Not goals now (listed in `docs/backlog.md`): passkeys, social sign-in, SCIM, multiple organisations, consent +screens (every family client is first-party and trusted). + +--- + +## 2. Crates and modules + +``` +im/ + Cargo.toml config/im.example.toml deploy/im.service style/*.scss docs/ + crates/ + im-core/ domain, store, migrations, config, secret, password, token, time, totp, jwt, authz, audit types, i18n-free + im-web/ binary `im`: pages, OIDC endpoints, machine APIs, live, mail worker, back-channel worker, CLI +``` + +**im-core** +- `error.rs`, `time.rs`, `config.rs` (+ `settings.rs` for UI overrides), `secret.rs` (instance key, seal/open) +- `password.rs` (argon2id, policy check), `token.rs` (random tokens, hashing, constant-time compare, readable codes) +- `totp.rs` (RFC 6238, SHA-1, 6 digits, 30 s, ±1 step, replay guard by last step) +- `jwt.rs` (EdDSA sign/verify, header/claims structs; ed25519-dalek; no generic JWT library needed) +- `names.rs` (email normalisation: trim, lowercase domain and local part, basic shape check) +- `authz.rs` (actor kinds and actions, section 6) +- `model.rs` (User, Session, Client, Service, Invite, ...) +- `store/` (`mod.rs` + one file per area: `users.rs`, `sessions.rs`, `oidc.rs`, `clients.rs`, `invites.rs`, + `links.rs` (reset/email-change), `mail.rs` (outbox), `backchannel.rs`, `directory.rs` (change feed), + `audit.rs`, `settings.rs`, `snapshot.rs`, `migrate.rs`) + +**im-web** +- `main.rs`, `boot.rs`, `state.rs`, `admin_cli.rs` +- `auth.rs` (session cookie, `current_user`, `require_user`, `require_admin`, `require_csrf`, pre-CSRF, `safe_next`, + pending-2FA sealed cookie), `throttle.rs`, `client_ip.rs` +- `oidc/` (`discovery.rs`, `authorize.rs`, `token.rs`, `userinfo.rs`, `logout.rs`, `revoke.rs`, `introspect.rs`, + `jwks.rs`, `keys.rs` (rotation worker)) +- `api/` machine routes (`directory.rs`, `family.rs`, `photo.rs`, `machine_auth.rs` = verify our own + client-credentials JWTs) +- `pages/` (one file per page or area) +- `views/` (`shell`, components), `i18n/` (key enums per area) +- `live.rs`, `mail/` (SMTP transport via `lettre`, outbox worker, templates), `backchannel.rs` (outbox worker), + `health.rs` (service probe worker), `audit.rs` (writer), `assets.rs` +- `assets/nav.js`, `assets/pages.js` (small page behaviours: dropdown search, copy button, QR toggle, photo + upload progress), `assets/offline.html`, `assets/sw.js` + +--- + +## 3. Data model + +Conventions from `docs/conventions.md` section 4. Every table below is in `0001_init.sql` unless noted. + +**users** +- `id` TEXT PK (ULID; this is the OIDC `sub`, never reused) +- `email` TEXT NOT NULL, `email_folded` TEXT NOT NULL UNIQUE (normalised) +- `name` TEXT NOT NULL (1–100 chars) +- `password_hash` TEXT NOT NULL (argon2id PHC) +- `is_admin` INTEGER NOT NULL DEFAULT 0, `disabled_at` TEXT NULL +- `totp_secret_sealed` TEXT NULL, `totp_enabled_at` TEXT NULL, `totp_last_step` INTEGER NULL +- `locale` TEXT NOT NULL DEFAULT 'en' CHECK (locale IN ('en','tr')) +- `zoneinfo` TEXT NOT NULL DEFAULT 'Europe/Istanbul' (IANA name, validated against the `jiff` tz database) +- `theme` TEXT NOT NULL DEFAULT 'system' CHECK IN ('system','light','dark') +- `photo_mime` TEXT NULL, `picture_version` INTEGER NOT NULL DEFAULT 0 +- `created_at`, `updated_at` TEXT NOT NULL + +**recovery_codes**: `user_id` FK CASCADE, `code_hash` TEXT, `used_at` TEXT NULL; PK (user_id, code_hash). +Ten codes, `xxxx-xxxx` from the readable alphabet, shown once, regenerated as a set. + +**sessions** (browser sessions at im) +- `id` TEXT PK (ULID; this is the OIDC `sid`), `user_id` FK CASCADE, `token_hash` TEXT UNIQUE, `csrf_token` TEXT +- `created_at`, `expires_at`, `last_seen_at` TEXT; `ip` TEXT, `user_agent` TEXT +- `auth_time` TEXT, `amr` TEXT ('pwd' or 'pwd otp' or 'pwd rc') +- Ended sessions are deleted (their back-channel jobs are queued first). + +**clients** (OIDC clients; one per family app, plus any extra) +- `id` TEXT PK (the `client_id`, ULID), `name` TEXT, `secret_hash` TEXT, `secret_rotated_at` TEXT +- `redirect_uris` TEXT (JSON array), `post_logout_redirect_uris` TEXT (JSON array), `backchannel_logout_uri` TEXT NULL +- `allowed_scopes` TEXT (space-separated; `openid profile email` plus machine scopes) +- `service_key` TEXT NULL UNIQUE (family key such as `in`; NULL for a client that is not a family service) +- `created_at`, `disabled_at` NULL + +**services** (the switcher list) +- `key` TEXT PK (`^[a-z][a-z0-9-]{0,31}$`), `name` TEXT, `url` TEXT (origin), `position` INTEGER, + `client_id` TEXT NULL REFERENCES clients ON DELETE SET NULL +- `healthy` INTEGER NULL, `checked_at` TEXT NULL, `check_ms` INTEGER NULL, `check_error` TEXT NULL +- im's own row (`key = 'im'`) is maintained at boot from `base_url` and cannot be removed. + +**auth_codes**: `code_hash` PK, `client_id`, `user_id`, `session_id`, `redirect_uri`, `scope`, `nonce`, +`code_challenge`, `expires_at`, `used_at` NULL. A second use of a used code revokes the refresh tokens issued +from it (`refresh_tokens.code_hash`). + +**refresh_tokens**: `id` PK, `token_hash` UNIQUE, `family_id` (first token of the chain), `client_id`, +`user_id`, `session_id` FK sessions CASCADE, `code_hash`, `scope`, `created_at`, `expires_at` (30 days), +`used_at` NULL, `revoked_at` NULL. Rotation on every use; presenting a used token revokes the whole family. + +**client_sessions**: (`session_id`, `client_id`) PK, `first_at`, `last_at`. Which apps a browser session has +signed in to: drives back-channel logout and the "connected apps" list. + +**signing_keys**: `kid` PK (first 16 hex of SHA-256 of the public key), `private_sealed`, `public_raw` BLOB, +`created_at`, `activates_at`, `retires_at` NULL. Exactly one key is "current": the newest with +`activates_at <= now` and no `retires_at`. + +**invites**: `token_hash` PK, `email_folded`, `is_admin`, `invited_by` NULL FK SET NULL, `created_at`, +`expires_at`, `accepted_at` NULL. Creating a new invite for an address deletes its older pending invites. + +**account_links** (password reset and email change) +- `token_hash` PK, `kind` CHECK IN ('reset','email_old','email_new'), `user_id` FK CASCADE, `pair_id` NULL + (both email-change halves share it), `new_email` NULL, `created_at`, `expires_at`, `used_at` NULL. + +**mail_outbox**: `id` PK, `kind` (invite|reset|email_old|email_new|email_done|notice|test|security), +`to_addr`, `subject`, `body_text`, `state` CHECK IN ('pending','sent','failed','abandoned'), `attempts`, +`next_attempt_at`, `last_error`, `created_at`, `sent_at`. Links in bodies are never logged. + +**backchannel_outbox**: `id` PK, `client_id`, `sid` NULL, `sub`, `reason`, `state`, `attempts`, +`next_attempt_at`, `last_error`, `created_at`, `done_at`. + +**directory_changes**: `seq` INTEGER PK AUTOINCREMENT, `sub`, `kind` CHECK IN ('member','deleted'), `at`. +The cursor of the directory stream is `seq`. Rows older than 30 days are pruned; a cursor older than the oldest +row gets `resync`. + +**audit_log**: per conventions section 10. + +**settings**: `key` PK, `value`, `updated_at` (UI overrides and sealed SMTP password). + +Files beside the DB in `data_dir`: `im.key`, `photos/` (0600, written by temp file + fsync + rename). + +--- + +## 4. Routes + +### 4.1 Browser pages + +| Path | Who | What | +|---|---|---| +| `GET/POST /setup` | only while no user exists | create the first admin | +| `GET/POST /login` | anonymous | email + password; then `/login/2fa` when TOTP is on | +| `GET/POST /login/2fa` | pending cookie | TOTP code or recovery code | +| `POST /logout` | user | end this session (back-channel to its apps) | +| `GET/POST /logout` (OIDC end-session) | any | section 4.2 | +| `GET/POST /forgot`, `GET/POST /reset/{token}` | anonymous | password reset by mail | +| `GET/POST /invite/{token}` | anonymous | accept an invite: name + password | +| `GET/POST /email/{token}` | anonymous | confirm one side of an email change; GET never mutates | +| `GET /` | user | account home: profile card, connected apps, switcher | +| `GET /account/profile` + POSTs | user | name, photo upload/remove, email change request | +| `GET /account/security` + POSTs | user | password change, TOTP enroll/disable, recovery codes | +| `GET /account/sessions` + POST revoke | user | own browser sessions; revoke one or all others | +| `GET /account/apps` + POST revoke | user | apps signed in to; sign out of one app | +| `GET /account/preferences` + POST | user | language, time zone, theme | +| `GET /people/{id}` | user | public profile card | +| `GET /admin/users` (+ `/{id}`) and POSTs | admin | list, invite, disable/enable, delete, revoke sessions, rescue email, reset 2FA, promote/demote (not self, not the last admin) | +| `GET /admin/services` and POSTs | admin | services + their clients: add (key, name, origin → client with derived URIs, secret shown once), rename, reorder, rotate secret, edit scopes, remove | +| `GET /admin/clients` and POSTs | admin | non-family OIDC clients | +| `GET /admin/mail` and POSTs | admin | SMTP sender (password write-only, sealed), check connection, send test, outbox with retry | +| `GET /admin/message` + POST | admin | notice mail to everyone or one person (queued) | +| `GET /admin/settings` + POST | admin | policy (section 7), base URL, trusted proxies; UI > file > default | +| `GET /admin/keys` + POST rotate | admin | signing keys and their state | +| `GET /admin/audit` | admin | filters (action, actor, target, date range), keyset paging | +| `GET /admin/health` | admin | services health, outboxes, disk, DB size, last backup | +| `GET /photo/{id}` | user | photo bytes or initials SVG | +| `GET /-/alive`, `GET /.../events` | per page | live streams | +| `GET /healthz`, `GET /assets/*` | anyone | | + +### 4.2 OIDC and machine endpoints + +As in `docs/contracts.md` sections 2–4: `/.well-known/openid-configuration`, `/jwks.json`, `/authorize`, +`/token` (authorization_code, refresh_token, client_credentials), `/userinfo`, `/logout` (RP-initiated), +`/revoke` (RFC 7009), `/introspect` (RFC 7662; for debugging and third-party clients; family apps do not use +it), `/api/v1/directory`, `/api/v1/directory/stream`, `/api/v1/people/{sub}/photo`, `/api/v1/family`. + +`/authorize` without a session redirects to `/login?next=`. After sign-in the user returns +there and is redirected to the client. Invalid `client_id` or `redirect_uri` renders an error page (never +redirects). Other errors redirect to the client with `error=` and `state`. + +--- + +## 5. Sign-in, sessions, 2FA + +- Login order (forge): pre-CSRF → throttle (account key and IP key) → lookup (unknown → dummy verify) → password + → disabled check (revealed only after a correct password) → 2FA step or session. +- Pending 2FA: sealed cookie `__Host-im_pending` (`user_id|expires|next|amr`), SameSite=Strict, 5 minutes. +- Second factor: 6 digits → TOTP with replay guard; `xxxx-xxxx` → recovery code (consumed). Throttled per user. +- Session: 30 days idle-extended up to `session_max_days` (policy), cookie `__Host-im_session`. At most + `max_sessions` per user: the oldest is ended (with back-channel) when exceeded. +- Password change ends every other session; reset ends all. Disable and delete end all and queue + back-channel logout by `sub`. +- TOTP enroll: secret generated and held sealed in a pending state until a valid code confirms it; enrolling + again while enabled requires the current code (old defect: re-visiting enroll reset it). Disabling TOTP + requires the password and a code. Admin "reset 2FA" clears TOTP and recovery codes and is audited and mailed + to the user. +- Password policy: 10–256 chars, not containing the email local part or name words of ≥4 chars, not equal to + the current one. + +--- + +## 6. Authorization + +`authz::authorize(actor, action) -> Result<(), Denied>` where `actor` is `Anonymous`, `User { id, is_admin }` +or `Client { id, scopes, service_key }`, and `action` is an enum (`ViewOwnAccount`, `EditOwnAccount`, +`ViewPerson`, `Administer`, `ReadDirectory`, `ReadFamily`, ...). Admin pages answer 404 to non-admins. +Rules that are not role checks (last admin cannot be demoted or disabled, an admin cannot disable themself) live +in the store as single conditional statements so they cannot race. + +--- + +## 7. Policy settings (admin, UI > file > default) + +| Key | Default | Kind | +|---|---|---| +| `registration` | `invite` (`invite` only; open sign-up is in the backlog) | ReadOnly | +| `invite_days` | 7 | Live | +| `reset_minutes` | 60 | Live | +| `email_change_hours` | 24 | Live | +| `session_max_days` | 30 | Live | +| `max_sessions` | 10 | Live | +| `require_2fa_for_admins` | true | Live (an admin without TOTP is sent to enroll after sign-in) | +| `base_url`, `trusted_proxies` | from file | Restart | +| `listen`, `database`, `data_dir` | from file | ReadOnly | + +--- + +## 8. Workers (spawned at boot, stop with the stop flag) + +- **mail**: sends `mail_outbox` rows (5 attempts, backoff 1/5/15/60 min, then `abandoned`); SMTP via `lettre`, + 465 implicit TLS, otherwise STARTTLS required. With no sender configured, rows wait without spending an + attempt. Dev mode (`[mail] log_only = true`) writes mails to `data_dir/mail-log/` instead. +- **backchannel**: delivers `backchannel_outbox` rows per contracts.md 2.5. +- **keys**: daily; creates the next key 24 h before rotation, retires old keys after 7 days. +- **health**: probes services every 60 s (2 s timeout), updates `services`, bumps the admin health topic. +- **sweeper**: hourly; deletes expired codes, links, sessions (queuing back-channel), old directory changes, + sent mail older than 30 days. +- **backup** (optional, `[backup] dir`): `VACUUM INTO` snapshot + photos + manifest on an interval, keeps N, + pings a dead-man URL (`/start`, success, `/fail`). + +--- + +## 9. Live + +Topics: `Account(user_id)` (sessions, apps, profile, security changes; drives `/-/alive` `account` events, so a +revoked session leaves at once), `AdminUsers`, `AdminServices`, `AdminMail`, `AdminAudit`, `AdminHealth`, +`Person(user_id)`. The directory stream for machines is separate (contracts.md 3.2) and reads +`directory_changes`. + +--- + +## 10. CLI + +`im admin create-admin ` (prompts for name and password; `IM_PASSWORD` for scripts), +`im admin reset-2fa `, `im admin disable `, `im admin create-client ` +(prints the secret once), `im admin rotate-key`, `im admin backup --out DIR`, `im admin backup-verify SET`, +`im admin restore --from SET --data-dir NEW`, `im admin audit-purge --older-than-days N`. +The CLI opens the database directly; it refuses to run while the server holds it unless `--online` is given, +in which case it talks to the running server over a unix socket in `data_dir/run/` with a per-boot token +(forge `admin_client.rs` pattern). + +--- + +## 11. Old defects not to repeat + +From the inventory of old im: no CSRF tokens; signing key never rotated; refresh reuse not detected; access +token scope hard-coded; email-change links leaked in a redirect query when mail failed; any client could claim +unowned service rows; `/directory`, `/photo` and `/family` open to any client; live profile frames broadcast to +everyone; revisiting enroll reset a confirmed TOTP; no way to disable TOTP or reset it for a locked-out user; +login pages English-only; deleted users left reset links, email changes and photos behind; SMTP password left +behind when the sender was cleared; cookie lifetime and DB lifetime disagreed; pack archives held the plaintext +key; Google Fonts loaded from a third party; generated CSS committed. + +--- + +## 12. Build order + +1. Scaffold: workspace, core basics (error, time, secret, token, password, config, store + migrate + 0001), + boot, `/healthz`, assets pipeline, shell, `nav.js`, i18n skeleton, security headers, 404 page. +2. Accounts: setup, login, 2FA, sessions, logout, throttle, account pages, preferences, photo. +3. Mail outbox + SMTP; invites, password reset, email change. +4. OIDC: keys, discovery, JWKS, authorize, token (all grants), userinfo, logout, revoke, introspect, back-channel. +5. Machine APIs: directory + stream, photo, family. +6. Admin: users, services/clients, mail, message, settings, keys, audit, health. +7. Live topics, backups, CLI, deploy unit, README. diff --git a/docs/contracts.md b/docs/contracts.md new file mode 100644 index 0000000..c910d5a --- /dev/null +++ b/docs/contracts.md @@ -0,0 +1,241 @@ +# Family contracts, v1 + +Status: normative. This file is copied byte for byte into `im/docs/contracts.md`, `in/docs/contracts.md` and +`iz/docs/contracts.md`. A change is made in all three repos in the same sitting, and the version line below is +bumped. The apps share no code. They share only the HTTP contracts written here. + +Contract version: **1** + +--- + +## 1. The family + +| Key | App | Role | Default listen | +|---|---|---|---| +| `im` | Account | OpenID Connect provider, people directory, service registry. Depends on nothing. | `127.0.0.1:7650` | +| `in` | Files | Personal drive. Blob store for the other apps. Depends on `im`. | `127.0.0.1:7655` | +| `iz` | Board | Task board. Depends on `im`, optionally on `in`. | `127.0.0.1:7654` | + +Production origins are `https://.` behind a TLS-terminating reverse proxy (Ferron). Apps bind +`127.0.0.1` only. + +### 1.1 Design rules + +1. **No app is down because another is down.** A signed-in user keeps working in `in` and `iz` while `im` is + unreachable. Only new sign-ins need `im`. Nothing calls `im` on the request path of an ordinary page. +2. **Standards first.** Where a standard exists (OIDC Core, OIDC Discovery, OIDC RP-Initiated Logout, OIDC + Back-Channel Logout, OAuth 2.0 client credentials, RFC 7009 revocation, RFC 7662 introspection), it is used + as written. Extensions are named and listed here. +3. **Machine calls carry a short-lived JWT** issued by `im` through the client credentials grant, with an + audience and scopes. Static shared bearer keys are not used. +4. **Every machine API is versioned** under `/api/v1/`. A consumer accepts unknown JSON fields. A provider keeps + v1 working for at least one release after v2 ships. +5. **Errors are JSON with a real HTTP status** (section 7). + +--- + +## 2. Identity (OIDC) + +`im` is the issuer. Its issuer URL is its public origin with no trailing slash, for example +`https://im.example.com`. + +### 2.1 Discovery + +`GET /.well-known/openid-configuration` returns standard metadata, including: + +- `issuer`, `authorization_endpoint` (`/authorize`), `token_endpoint` (`/token`), `userinfo_endpoint` + (`/userinfo`), `jwks_uri` (`/jwks.json`), `end_session_endpoint` (`/logout`), `revocation_endpoint` + (`/revoke`), `introspection_endpoint` (`/introspect`) +- `response_types_supported: ["code"]`, `grant_types_supported: ["authorization_code", "refresh_token", "client_credentials"]` +- `code_challenge_methods_supported: ["S256"]`, `id_token_signing_alg_values_supported: ["EdDSA"]` +- `token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"]` +- `backchannel_logout_supported: true`, `backchannel_logout_session_supported: true` +- `scopes_supported: ["openid", "profile", "email", "directory.read", "files.service"]` + +Clients fetch discovery once at boot and cache it. They may hard-code the paths above as a fallback. + +### 2.2 Keys + +- Signing algorithm: **EdDSA (Ed25519)**. `jwks.json` publishes every key that is active or retired within + the last 7 days, as `{"kty":"OKP","crv":"Ed25519","x":...,"kid":...,"use":"sig","alg":"EdDSA"}`. +- `im` rotates the signing key every 90 days and on admin demand. A new key is published 24 hours before it + signs anything. +- Clients cache the JWKS for 1 hour, and refetch at most once a minute when a token names an unknown `kid`. + +### 2.3 Sign-in (authorization code + PKCE) + +1. App redirects the browser to `/authorize` with `response_type=code`, `client_id`, `redirect_uri` (exact match + with a registered URI), `scope` containing `openid` (and `profile email`), `state` (≥128 bits), + `nonce` (≥128 bits), `code_challenge`, `code_challenge_method=S256`. PKCE is mandatory. +2. `im` signs the user in (password, then TOTP or a recovery code if enrolled) and redirects back with + `code` and `state`. Codes live 60 seconds and are single use. A reused code revokes every token issued from it. +3. App posts to `/token` (`grant_type=authorization_code`, `code`, `redirect_uri`, `code_verifier`), client auth + by `client_secret_basic` or `client_secret_post`. Response: `access_token` (JWT, 10 min), `id_token`, + `refresh_token`, `token_type: "Bearer"`, `expires_in`. +4. App validates the `id_token`: signature against JWKS, `iss` exact, `aud` equals its `client_id`, `exp` in the + future, `iat` not more than 5 minutes in the future, `nonce` equal to the one it sent. + +**ID token claims:** `iss`, `sub` (the user's ULID, stable forever), `aud`, `exp`, `iat`, `auth_time`, `nonce`, +`sid` (the `im` browser session id), `email`, `email_verified` (always true: `im` only stores confirmed +addresses), `name`, and the `im` extensions `admin` (bool), `locale` (`en`|`tr`), `zoneinfo` (IANA name, for +example `Europe/Istanbul`), `picture_version` (integer, bumps when the photo changes). + +### 2.4 App sessions + +After step 4 the app creates **its own local session** (its own table, its own `__Host-` cookie, its own CSRF +token), keyed by `sub`, and stores `sid` beside it. The app does not call `im` again for this session. + +- Local session lifetime: at most 12 hours of absolute age. After that the app sends the browser through + `/authorize` again. While the `im` session is alive this is an invisible redirect. +- The app may keep the `refresh_token` only if it needs to call `/userinfo` later. Apps in this family do not. + They discard it. + +### 2.5 Sign-out and revocation + +- **App-initiated sign-out:** the app deletes its local session, then redirects to + `/logout?id_token_hint=...&post_logout_redirect_uri=&state=...` (OIDC RP-Initiated Logout). `im` + ends the `im` session and every app session tied to it (back-channel, below). +- **Back-Channel Logout** (OIDC Back-Channel Logout 1.0): each client registers a `backchannel_logout_uri` + (`/auth/backchannel-logout`). When an `im` session ends (sign-out, admin revoke, password change or + reset, user disabled or deleted, session expired by policy), `im` POSTs `logout_token=` (form-encoded) + to every client that was used in that session. The token carries `iss`, `aud`, `iat`, `exp` (2 min), `jti`, + `events: {"http://schemas.openid.net/event/backchannel-logout": {}}`, and `sid` (and `sub`). For "disable" and + "delete" it carries only `sub`, which means "every session of this user". +- The app validates it like an ID token (no `nonce`; it must carry `events` and must not carry `nonce`), + rejects a reused `jti` for 10 minutes, deletes the matching local sessions, and answers `200` with an empty + body. Any other answer is a failure. +- `im` delivers through a durable outbox: retries with backoff (10 s, 30 s, 1 min, 5 min, then every 15 min) + for 24 hours. Combined with the 12-hour local session cap (2.4), a missed delivery cannot keep a revoked + user signed in for longer than 12 hours, even if the app was down. +- The directory stream (section 3) also carries `disabled: true` and `deleted` events. An app that sees one + deletes the user's local sessions as well. Two independent paths; either one is enough. + +### 2.6 Machine-to-machine tokens + +- A client that calls another app's API asks `im` for a token: `POST /token` + `grant_type=client_credentials&scope=&audience=` with its client auth. (`audience` is the + RFC 8707-style extension parameter; its value is a family key such as `in`.) +- `im` checks the scopes against the client's allowed scopes (set by the admin) and returns an + `access_token` JWT: `iss`, `sub` = `client:`, `azp` = `client_id`, `aud` = target key, `scope` + (space separated), `iat`, `exp` (10 min), `jti`, plus `svc` = the caller's family key. +- The receiving app verifies signature, `iss`, `aud` equals its own key, `exp`, and the scope it needs. It + treats `svc` as the caller's identity. Callers cache the token until 60 s before `exp`. + +| Scope | Granted by default to | Lets the caller | +|---|---|---| +| `directory.read` | every family client | read the people directory and photos at `im` (section 3) | +| `files.service` | `iz` | store and read its own objects in `in` (section 5) | + +--- + +## 3. People directory (im) + +All routes need a client-credentials token with `aud = "im"` and scope `directory.read`. + +### 3.1 Member record + +```json +{ + "sub": "01J...", + "email": "a@example.com", + "name": "Ayşe Yılmaz", + "admin": false, + "disabled": false, + "locale": "tr", + "zoneinfo": "Europe/Istanbul", + "picture_version": 3, + "updated_at": "2026-10-28T09:00:00.000000000Z" +} +``` + +### 3.2 Routes + +- `GET /api/v1/directory` → `{"members":[...], "cursor":""}`. Every account, disabled ones + included (`disabled: true`). Deleted accounts are absent. +- `GET /api/v1/directory/stream` → `text/event-stream`. Optional `Last-Event-ID` (or `?cursor=`) resumes from a + cursor. Events: + - `event: member`, `data: `: a member was created or changed (including disabled/enabled). + - `event: deleted`, `data: {"sub":"..."}`: the account is gone. + - `event: resync`, `data: {}`: the cursor is too old; fetch `GET /api/v1/directory` again. + - Each event has an `id:` that is a cursor. Keep-alive comments every 30 s. `im` closes the stream after + 50 minutes; the client reconnects with its last cursor. +- `GET /api/v1/people/{sub}/photo` → image bytes with the stored `Content-Type`, or `404` when there is no photo. + `ETag: "p"`. With `?v=` matching, `Cache-Control: private, max-age=31536000, + immutable`; otherwise `private, no-cache`. Honors `If-None-Match` with `304`. + +Apps mirror the directory into a local `members` table (full fetch, then the stream), so pages never call `im` +to show a name or an avatar. Apps proxy photos through their own origin and cache them on disk keyed by +`(sub, picture_version)`; a browser never talks to `im` for a photo. + +--- + +## 4. Service registry and switcher (im) + +- `GET /api/v1/family` (token with `aud = "im"`, scope `directory.read`) → + `{"services":[{"key":"in","name":"Files","url":"https://in.example.com","healthy":true,"checked_at":"..."}]}` + in the admin's order. `im` is included as `{"key":"im","name":"Account",...}`. +- The list is owned by `im`'s admin. A service row is created with its OIDC client (the admin gives a key, + a name and the origin; the redirect and back-channel URIs are derived from the origin). Apps do not register + themselves. +- `im` probes each row's `GET /healthz` every 60 s (2 s timeout) and reports `healthy`. Apps fetch the list + every 5 minutes and render the switcher from their copy; a stale copy is fine. + +### 4.1 Health + +Every app serves `GET /healthz` without auth: `200`, body `ok `, `Content-Type: text/plain`. +It checks that the process answers and that a `SELECT 1` on its database succeeds within 1 s; otherwise +`503` with `fail `. + +--- + +## 5. Object store (in) + +`in` stores bytes for other apps in a per-service namespace with its own quota. All routes need a +client-credentials token with `aud = "in"` and scope `files.service`. The namespace is the token's `svc`. +An object is named by the caller's `external_id` (1–128 chars of `[A-Za-z0-9._-]`). + +| Method and path | Request | Success | +|---|---|---| +| `PUT /api/v1/objects/{external_id}` | Raw body; `Content-Type` (stored as given, re-sniffed for display); optional `X-Object-Name` (UTF-8, percent-encoded, ≤255 bytes); optional `If-None-Match: *` | `201` (created) or `200` (replaced), JSON `{"external_id","size","sha256","content_type","created_at"}` | +| `GET /api/v1/objects/{external_id}` | Optional `Range: bytes=a-b` (one range) | `200` or `206`, the bytes, `ETag: ""`, `Content-Length`, `Accept-Ranges: bytes` | +| `HEAD /api/v1/objects/{external_id}` | — | Headers as GET | +| `DELETE /api/v1/objects/{external_id}` | — | `204`; also `204` when already absent (idempotent) | +| `GET /api/v1/usage` | — | `{"quota_bytes": n, "used_bytes": n, "objects": n}` | + +- Uploads stream to disk; the body is never held in memory. A body larger than the remaining quota is refused + with `413` and error code `quota_exceeded` before or while it is read. +- `PUT` is atomic: the new bytes are visible only after they are fully written and fsynced. +- Service objects never appear in a person's drive and do not count against any person's quota. +- The quota per service is set in `in`'s admin page (default 10 GiB). + +--- + +## 6. Users across apps + +- The user id everywhere is `im`'s `sub` (a ULID). Apps never invent their own user ids for people. +- An app learns a user when they first sign in or when the directory names them. A member that the directory + lists but who never signed in still exists in the app (so they can be assigned, mentioned, mailed). +- App-level roles (for example `iz` Admin, Member, Viewer) belong to the app. `im`'s `admin` flag means + "instance administrator" and every app treats it as its own top role. + +--- + +## 7. Errors + +Machine routes answer errors as: + +```json +{"error": "quota_exceeded", "message": "The service quota of 10 GiB is used up."} +``` + +with the matching status: `400 invalid_request`, `401 invalid_token` (with `WWW-Authenticate: Bearer +error="invalid_token"`), `403 insufficient_scope`, `404 not_found`, `409 conflict`, `413 quota_exceeded` or +`too_large`, `429 rate_limited` (with `Retry-After`), `500 internal`, `503 unavailable`. `error` is a stable +machine word; `message` is English for logs and may change. OAuth endpoints (`/token`, `/revoke`, +`/introspect`) use the OAuth error format from their RFCs instead. + +--- + +## 8. Change log + +- **v1** (2026-10-28): first version. diff --git a/docs/conventions.md b/docs/conventions.md new file mode 100644 index 0000000..12c49e4 --- /dev/null +++ b/docs/conventions.md @@ -0,0 +1,169 @@ +# Code conventions + +These rules are the same in `im`, `in` and `iz` (the file is copied into each repo). They are taken from +`forge` (`~/Documents/Code/Rust/forge`, see its `docs/architecture.md`), which is the reference +implementation: when a rule here is unclear, read how forge does it and do the same. + +## 1. Workspace + +- Edition 2024, resolver 3, `unsafe_code = "forbid"` in `[workspace.lints.rust]`, every member ends with + `[lints] workspace = true` and `publish = false`. +- Every dependency version lives in the root `[workspace.dependencies]`, added with `cargo add` at its latest + release (never copied from another project). Members write `foo.workspace = true`. +- Topcoat 0.11 with `default-features = false` and an explicit feature list. Turso (latest stable) for the + database. +- Two crates per app: `-core` (domain types, store, migrations, config, secrets, auth primitives, pure + logic; no HTTP) and `-web` (the binary named ``: Topcoat UI, HTTP APIs, background workers, CLI). + Add a crate only for a real boundary. +- Dev profile: `debug = "line-tables-only"`; `opt-level = 3` for `argon2`, `sha2` and the turso crates, each with + a one-line reason. Release: `lto = true`, `codegen-units = 1`. + +## 2. Boot + +`main.rs` dispatches on positional words: no word or `serve` runs the server, `admin ` runs the CLI. +Config path: `--config `, then `_CONFIG`, then `config/.toml`. Exit 2 on usage errors, 1 on +failure. + +`serve` order: load and validate config → create `data_dir` (0700) → load or create `.key` (32 bytes, 0600, +`O_EXCL`) → open the store (pragmas, migrations) → layer stored UI overrides on the file config → spawn +workers → build the router → bind → serve until SIGTERM/Ctrl-C, with one stop flag shared by every listener and +worker. + +Logging: `tracing` + `tracing-subscriber` (`env-filter`), stderr, default `info`, structured fields. Never log +tokens, passwords, cookies, or secrets. + +## 3. Config + +- `config/.example.toml` is committed. `config/.toml` is gitignored. A missing file is created from + the example (dev defaults) on first run. +- `#[serde(deny_unknown_fields)]` on every struct. One `Config::validate()` for cross-field rules, used at load + and when a UI override is saved. +- Secrets never live in the TOML. They are entered in the admin UI (sealed in the DB) or in a separate file + readable only by the service user. +- Runtime settings: a `settings` key/value table with precedence **UI override → file → built-in default**, and + each field marked `Live`, `Restart` or `ReadOnly` (forge `server_settings.rs`). + +## 4. Store + +- One writer connection behind a tokio `Mutex`, plus a pool of 4 `PRAGMA query_only` readers. Pure reads use a + reader; writes, transactions and read-then-write sequences use the writer. +- Pragmas on every connection: `journal_mode=WAL`, `synchronous=FULL`, `foreign_keys=ON`, busy timeout 5 s. + Read them back and log them at boot. +- Migrations: `crates/-core/migrations/NNNN_snake_name.sql`, each starting with a comment that says what + it does; listed in `store/migrate.rs` as `(version, include_str!(...))`; each applied in its own transaction + with a `schema_migrations` row. Never edit an applied migration. +- Ids are ULID text. Timestamps are UTC RFC 3339 with 9 fractional digits and `Z` (fixed width, so text order is + time order) from `time.rs` (`now_stamp()`, `stamp_after(d)`). Booleans are `INTEGER` 0/1 with a `CHECK`. +- Column lists are constants (`USER_COLS`) next to their `map_user(row)`; SQL uses `?1, ?2`; ownership goes in + the `WHERE` (`... WHERE id = ?1 AND owner_id = ?2`). +- Multi-statement writes: `unchecked_transaction()` + an async block returning `Result` + one `finish(tx, + outcome)` helper that commits or rolls back. +- Constraints live in the schema (`NOT NULL`, `CHECK`, `UNIQUE`, `REFERENCES ... ON DELETE ...`), not only in Rust. +- Backups: `snapshot_to(path)` with `VACUUM INTO` on the writer, then checkpoint the copy so it is one + self-contained file, then fsync. `admin backup --out DIR` writes the snapshot, the blob tree (where the app + has one) and a `manifest.json` with a sha256 per file. `admin backup-verify SET` checks hashes, + `integrity_check` and contiguous migrations. Never copy a live DB file. + +## 5. HTTP and pages + +- Routes with `#[route(...)]` / `#[page(...)]` and `.discover()`. Anything that must not be public is + registered explicitly on a separate router. +- Handler shape: (1) authenticate, (2) load and authorize, (3) build the view, (4) return it. +- Forms: every field `#[serde(default)]`; every state-changing POST carries a `csrf` field checked in constant + time **before** any side effect (`require_csrf`). Pre-session forms use the `__Host-_precsrf` cookie + (SameSite=Strict). Post/Redirect/Get with notices in the query string (`?notice=...`), not cookies. +- Session cookie: `__Host-_session`, random 32 bytes base64url; the DB stores only its SHA-256. + HttpOnly, Secure, SameSite=Lax, Path=/. +- `safe_next()` for every return path: one leading `/`, not `//` or `/\`, no control characters, ≤2048 bytes. +- One security-headers layer on `/`: `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, + `Referrer-Policy: same-origin`, `Strict-Transport-Security` when the base URL is https, and + `Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; + form-action 'self'; frame-ancestors 'none'; base-uri 'none'`. **No inline scripts or styles anywhere**; all JS + is in `assets/*.js`. +- Styled 404 page for `Accept: text/html`; 404 for "missing" and for "exists but you may not see it". +- Request bodies are capped per route (`BodyLimit`); upload routes stream. +- Assets (CSS compiled from `style/*.scss` with `grass` in `build.rs`, JS, fonts) are embedded with + `include_str!`/`include_bytes!`, served by routes with `Cache-Control: public, max-age=31536000, immutable`, + and linked with a content-hash query (`/assets/main.css?v=<12 hex>`). Fonts are self-hosted. Nothing is + loaded from a third-party origin. + +## 6. Auth primitives + +- Passwords: argon2id (`Argon2::default()`), PHC strings, always on `spawn_blocking`. Unknown accounts verify + against a fixed dummy hash so timing does not reveal them. +- Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once. +- Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second + factors per user; checked before any lookup; `429` with `Retry-After`. +- Secrets at rest: `seal`/`open` with XChaCha20-Poly1305 under the instance key, `v1:` + base64(nonce || + ciphertext). +- Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left. + +## 7. Authorization + +One pure function per app, `authz::authorize(actor, resource, role, action) -> Result<(), Denied>`, with +`Denied::{NotFound, Forbidden}`. Every page, form handler, API route and live stream goes through it. It is +unit-tested as a truth table. + +## 8. Live pages + +- `LiveHub` of `watch::Sender` per `Topic` (an enum keyed by what a page is about). Writes call + `live.bump(&topic)` after commit. +- A page that updates live renders `data-live=""`. The stream route authenticates and authorizes + first, then `stream_changes(cx, hub, topics, fingerprint)`: subscribe, read a fingerprint, and send a + data-less `event: changed` only when the fingerprint changes. `retry: 1000`, keep-alive every 30 s, + `X-Accel-Buffering: no`. +- `GET /-/alive` is held by every page (anonymous-safe). It drives the "server restarting" bar and carries + `account` events (sign-out, preference change) for the viewer. +- `assets/nav.js` (one file, progressive enhancement): soft navigation for same-origin links and forms + (`data-hard` opts out), keeps focus/scroll/typed input across swaps, opens one EventSource per distinct + `data-live` URL, re-fetches the page on `changed`, reconnects after 1/2/3 s, never re-sends a POST. + Pages work without JS. + +## 9. Errors + +- One `thiserror` enum per crate: `Io`, `Database`, `Migration`, `Config`, `Crypto`, `NotFound`, + `Conflict(String)`, `Forbidden(String)`, `Invalid(String)`. +- `Invalid` and `Conflict` text is for the user (shown as an alert). Everything else is a 500 with a generic + page and a logged cause. +- Security-sensitive answers are identical for "unknown" and "wrong". + +## 10. Audit + +Append-only `audit_log` (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data JSON). Written +after the change commits; a failed audit write is logged and never fails the request. Never store secrets in +`data`. Admin page with filters and keyset paging. Purge only through `admin audit-purge --older-than-days N`. + +## 11. i18n + +English and Turkish. `Lang::{En, Tr}`; resolution: the user's stored language, else `Accept-Language`, else +English. Keys are enums per area with an exhaustive `match` on `(key, lang)`, so a missing translation does not +compile. **Every** page, including sign-in, error and mail text, is translated. Sentences with values use small +format helpers, not concatenation in views. + +## 12. Comments and naming + +- `//!` on every module: what it is, what it is not, the invariant it keeps. `///` on every public item and on + every policy constant (with its unit and reason). Inline comments explain why, in full sentences. +- No commented-out code. No `TODO` without a line in `docs/backlog.md`. + +## 13. Tests + +Few and meaningful. Unit tests for pure logic that is easy to get wrong (authz truth table, token and CSRF +compare, `safe_next`, parsers, time math, quota math), store tests on a real temp database (`tempfile`) for +tricky queries and constraints, and one or two in-process router tests per security rule (CSRF refused, +hidden resource is 404, admin page refuses members). No snapshot tests, no browser tests, no mocks of the +database. Tests never write outside their temp dir. + +## 14. Deploy + +`deploy/.service`: dedicated user, `ProtectSystem=strict`, `ReadWritePaths=` the data dir only, +`ProtectHome=yes`, `PrivateTmp=yes`, `PrivateDevices=yes`, `NoNewPrivileges=yes`, `CapabilityBoundingSet=`, +`RestrictNamespaces=yes`, `RestrictSUIDSGID=yes`, `LockPersonality=yes`, `MemoryDenyWriteExecute=yes`, +`SystemCallArchitectures=native`, `SystemCallFilter=@system-service`, `UMask=0077`, `Restart=on-failure`. +`/healthz` per contracts.md 4.1. + +## 15. Git + +Commit messages follow forge's style: gitmoji + type + description, for example +`✨ feat: sign-in with TOTP and recovery codes`, `🐛 fix: ...`, `♻️ refactor: ...`, `📝 docs: ...`. +No co-author or "generated with" lines. diff --git a/docs/reference/old-inventory.md b/docs/reference/old-inventory.md new file mode 100644 index 0000000..35cffaf --- /dev/null +++ b/docs/reference/old-inventory.md @@ -0,0 +1,311 @@ +# im: feature inventory (rebuild reference) + +Source: /home/tahinli/Documents/Code/Rust/old_im (read-only survey). Workspace crates: im-core (domain + storage, feature `server`), im-web (topcoat web app, binary `im-web`), im-client (app-side SDK). + +## 1. Purpose summary + +1. im is a self-hosted OpenID Connect identity provider (OIDC, RS256, PKCE S256) and account portal for a small family of sibling apps. +2. Users sign in with email + Argon2id password, optional TOTP 2FA; they manage sessions, profile photo, preferences, password, and email change. +3. Admins manage users (invite, disable, delete, sign-out-everywhere), OIDC clients, the sibling service registry, SMTP, policy settings, a filterable audit log, and service health. +4. Sibling apps ("in" = Files, "iz" = Board) integrate via OIDC, mirror the member directory over HTTP + SSE, read profile photos, introspect app sessions, and register themselves in the family registry. +5. Single binary, Turso (SQLite-compatible) storage, files beside the DB; backup/restore via `pack`/`unpack`; systemd user unit with GitHub Actions deploy. + +## 2. User-facing features + +Routes are method + path as registered in `crates/im-web/src`. Pages return HTML; POST handlers redirect (303) with `?ok=` or `?error=` codes. + +### 2.1 Landing and profile (`pages.rs`) +- `GET /` signed out: login card. Signed in: landing with sections via `?section=` = `profile` | `sessions` | `apps` | `preferences` | `password`. +- Profile card: photo or initial avatar, 2FA chip, admin chip, email, member since, link to public profile, "activate 2FA" link when off, admin panel link when admin. +- Stats card (`stats.rs`): sign_ins (all sessions ever), active_sessions (not revoked, not expired), connected_apps (distinct clients with live app sessions). +- Sessions section: list of sessions as `
` items; device label parsed from User-Agent (Edge, Firefox, Chromium, Chrome, Safari; iPhone, iPad, Android, Windows, macOS, ChromeOS, Linux); shows address, created, last seen; `POST /sessions/revoke` (`session`=token hash) revokes one owned session (cascades to refresh_tokens and app_sessions of that session). +- Apps section: connected apps (`list_connected_apps`) with revoke. +- Preferences: `POST /preferences`: theme `light|dark`; ui `instrument|ledger`; language `en|tr`; timezone from zone_options UTC-12..UTC+14 plus UTC (default `UTC+03:00`). Redirect `/?section=preferences`. +- Password: `POST /password` (current, password, password_confirm). Rules below. Revokes all other sessions, keeps current. Redirect `/?section=password&ok=password`. + +### 2.2 Login and 2FA (`auth.rs`, `pages.rs`) +- `GET /login` (optional `back`, `error`, `ok`). `POST /login` (email, password, back). + - Rate limited per account (key = trimmed email); over limit → `/login?error=rate_limited`. + - Bad credentials (also unknown email, disabled user, same message) → `/login?error=bad_login&back=...`. + - Account with confirmed TOTP → sealed pending cookie `im_pending` (JSON {user, purpose "login", back, exp}, TTL 10 min or policy `pending_minutes`) → redirect `/login/totp`. + - Account without 2FA → session issued immediately (2FA is optional). + - `safe_back`: only local paths (or same-origin family URLs) accepted. +- `GET /login/totp`, `POST /login/totp` (code). Rate limit key `totp:{user}`. Bad → `/login/totp?error=bad_code`. Success → `im_session` cookie and redirect to back. Replay protection via `users.totp_last_step`. +- `POST /logout`: signs out everywhere (central session revoked; cookie cleared) → `/`. +- `GET /logout?back=`: RP-initiated logout; `back` must be local path or same origin as a family service; clears central session. +- `GET /api/me`: 204 when signed in, 401 otherwise (used by client JS). + +### 2.3 2FA enrollment (`pages.rs`, `totp.rs`) +- `GET /enroll`: generates a 20-byte secret (stored sealed, `totp_confirmed = 0`), shows base32 secret grouped by 4, `otpauth://totp/im:{email}?secret=...&issuer=im`, QR as SVG (`qrcode` crate). Page strings are English-only. +- `POST /enroll` (code). Bad → `/enroll?error=bad_code`; good → `totp_confirmed = 1`, redirect `/?ok=enrolled`. +- No UI or route to disable TOTP once enrolled. Re-visiting `/enroll` after confirmation regenerates the secret (`set_totp` resets confirmed flag) — see oddities. +- Verification: HMAC-SHA1, 6 digits, 30 s step, +/-1 step drift. Secret 160-bit. + +### 2.4 Invitations and account creation +- Invite creation: admin only (see 2.8). Invite token = 32 random bytes, base64url, stored as SHA-256 hex (`invites.token`). Expiry = policy `invite_days` (default 7). +- `GET /invite/{token}`: form with name, password, password_confirm; invalid/expired/accepted token shows error. +- `POST /invite` (token, name, password, password_confirm): creates user (transactional, marks invite accepted), auto-signs-in, redirect `/`. TOTP not forced. +- Invite refused if email already has an account. Multiple pending invites for one email are allowed. +- Mail: invite email in English only (`invite_mail`), link `{issuer}/invite/{token}`, mentions INVITE_DAYS. If no SMTP configured, dev mode prints the link to stdout; admin UI shows the link once. + +### 2.5 Password reset (`pages.rs`, `accounts.rs`) +- `GET /forgot`; `POST /forgot` (email): always redirects `/forgot?ok=sent` (no enumeration). Rate limit key `forgot:{email}`. If account exists, creates reset link (retires previous unused links; expiry policy `reset_minutes`, default 60) and mails `{issuer}/reset/{token}` in the account's language. +- `GET /reset/{token}`; `POST /reset` (token, password, password_confirm): success → `/login?ok=reset`; errors → `/reset/{token}?error=...`. On success marks link used, sets hash, revokes all sessions, clears login failures. + +### 2.6 Email change (two-sided confirmation) (`pages.rs`, `auth.rs`, `accounts.rs`) +- `POST /email_change` (email): validates address (trim, lowercase, contains @ and dotted domain; taken → error). Creates a pair of tokens (old-address token, new-address token) in `email_changes`, expiry ~ policy-driven. Mails both: "leaving" link to old address, "gaining" link to new address (`{issuer}/email/{token}`). +- If mail send fails, both confirmation links are returned in the redirect query `links=` (see security oddities). +- `GET /email/{token}` shows confirmation page (GET never mutates). `POST /email` (token) confirms that side. Results: `/login?ok=email_changed` when both sides confirmed; `/login?ok=email_half_confirmed` otherwise; errors. At completion the new address is re-checked for being taken. +- Pending state shown on profile via `pending_email_change`. + +### 2.7 Profile photo (`photo.rs`) +- `POST /api/profile_photo` (multipart, field file): limit 5 MiB (`PHOTO_LIMIT_BYTES`); BodyLimit set to limit + 4096. Sniffs magic bytes: PNG, JPEG, GIF, WEBP, AVIF. Errors `/?error=no_file|photo_too_big|not_an_image|unavailable`; success `/?ok=photo_saved`. Stores file at `/photos/`, row increments `photo_version`. +- `POST /api/delete_profile_photo` → `/?ok=photo_removed`. +- `GET /photo/{user_id}`: auth by session cookie OR HTTP Basic app credentials; otherwise 404. Unknown user or no photo → SVG initial tile. Headers: ETag `"p{version}"`; with `?v=` matching version: `private, max-age=31536000, immutable`; otherwise `private, no-cache`; 304 on If-None-Match. + +### 2.8 Public profile (`people.rs`) +- `GET /people/{user_id}`: requires signed-in viewer; unknown id or signed out → router not-found. Shows name, email, member since, 2FA/admin chips, stats. Edit link only for self. + +### 2.9 Admin panel (`admin.rs`) +- `GET /admin` (admin only; non-admin → 303 `/`). Sections via `?section=`: `users` (default), `services` (alias `clients`), `message`, `settings`, `logs`, `health`. A `mail` section exists but is only reached by redirects; the nav has no Mail tab (oddity). +- Admin role cannot be granted from the panel. Only CLI `promote`/`demote` or an invite with role admin. +- Users section: table with per-user session rows (device, address, created, last seen, revoke button), disable/enable, delete, sign out everywhere, per-user email edit fold. + - `POST /admin/invite` (email, role `member|admin`): mails invite or shows link once via `invited=`; logs `invite_created`. + - `POST /admin/uninvite` (invite=hash): removes pending invite; logs `invite_revoked`. + - `POST /admin/user_email` (user, email): direct rescue edit, no confirmation; logs `email_changed`. + - `POST /admin/delete` (user): deletes user (see 4 for what survives); logs `user_deleted`. + - `POST /admin/revoke` (user): sign out everywhere; logs `sessions_revoked`. + - `POST /admin/session_revoke` (user, session): one session; logs. + - `POST /admin/disable` and `POST /admin/enable` (user): disable revokes all sessions; `notify_profile` broadcast; logs `user_disabled`/`user_enabled`. +- Services section: `POST /admin/services_add` (key, name, url); `POST /admin/services_edit` (key, name, url, limit_amount, limit_unit `MiB|GiB`); `POST /admin/services_remove` (key; refuses owned rows; closes gap); `POST /admin/services_move` (key, dir `up|down`; swaps with neighbor). Keys: lowercase letters, digits, dashes. Name non-empty. URL http(s), no spaces. Edit: only name and storage limit may change for existing rows; URL change refused. +- Clients section (OIDC clients): `POST /admin/clients_add` (name, redirect_uris split by whitespace or comma); client secret shown once via show-once shelf (10 min one-time ticket in `shown=`). `POST /admin/clients_rotate` (client): new secret, shown once. `POST /admin/clients_revoke` (client): deletes client, its refresh tokens and app sessions (not central sessions). +- Settings section: `POST /admin/settings` (invite_days, session_days, max_sessions, pending_minutes, reset_minutes, login_attempts_per_hour). Values < 1 clamped to default. +- SMTP: `POST /admin/smtp` (host, port u16 default 587, username, password optional (blank keeps old), from_name, from); saves and re-probes in background. `POST /admin/smtp_test` sends test mail to admin's email. `POST /admin/smtp_check` runs connection probe (15 s timeout). Standing shown as NotConfigured / Unchecked / Connected / Refused, with recorded check time, latency, error. +- Message section: `POST /admin/message` (to = `everyone` (excludes admin) or user id; subject; body). Sends sequentially; aborts on first failure. +- Logs section: audit events table. Filters: kind, actor, from/to dates, dir (`newest|oldest`), q (substring). Default 50 rows per page (cookie `im_rows_logs`, clamp 5 to 200, fit-to-viewport script). Cursor paging `before` / `after` as `rfc3339~id`; position note `X-Y / Z`. +- Health section: table of services with `/healthz` result and latency. + +### 2.10 Logout of sibling apps +- Apps call `GET /logout?back=` (see 2.2) to end the central session. + +### 2.11 Family registry (cross-app, see 3.8/3.9) +- Services are listed in the admin panel and in the family flyout (signed-in chrome) with health dots. im's own row is excluded from the flyout. + +## 3. Machine and API endpoints (cross-app contract) + +Base: `issuer` (config, default `http://127.0.0.1:7650`). Auth schemes: "Basic" = HTTP Basic `client_id:client_secret` checked against `oidc_clients` (secret stored as hash). "Bearer" = RS256 JWT from /token. + +### 3.1 OIDC discovery and keys +- `GET /.well-known/openid-configuration` (no auth). JSON: `issuer`, `authorization_endpoint` `{issuer}/authorize`, `token_endpoint` `/token`, `userinfo_endpoint` `/userinfo`, `jwks_uri` `/jwks.json`, `response_types_supported` ["code"], `grant_types_supported` ["authorization_code","refresh_token"], `subject_types_supported` ["public"], `id_token_signing_alg_values_supported` ["RS256"], `scopes_supported` ["openid","profile","email"], `claims_supported` iss, sub, aud, exp, iat, nonce, email, name, `code_challenge_methods_supported` ["S256"]. No introspection_endpoint or end_session_endpoint listed. +- `GET /jwks.json` (no auth). `{"keys":[{"kty":"RSA","alg":"RS256","use":"sig","kid":...,"n":...,"e":...}]}`. kid = first 16 hex of SHA-256 of public DER. + +### 3.2 Authorization code flow +- `GET /authorize` (no auth; needs central session). Query: `client_id`, `redirect_uri` (must exactly match a registered URI), `response_type=code`, `scope` (must include `openid`; only openid/profile/email), `code_challenge` (required), `code_challenge_method=S256`, `state`, `nonce`. + - No central session → 303 `/login?back=/authorize?...`. + - Bad client or redirect_uri → bare 400 "invalid request" (no redirect). + - Other errors → 302 to redirect_uri with `?error=` (`unsupported_response_type`, `invalid_scope`, `invalid_request`) and `state`. + - Success → 303 `redirect_uri?code=...&state=...`. Code: 32 random bytes, stored as hash, TTL 60 s, single use (peek then consume in immediate transaction). +- `POST /token` (form-encoded). Client auth: `client_secret_post` only (client_id and client_secret in body). + - `grant_type=authorization_code`: `code`, `redirect_uri`, `client_id`, `client_secret`, `code_verifier` (PKCE S256 check). Response JSON: + - `access_token`: RS256 JWT, claims iss, sub, aud=client_id, exp (now+900), iat, scope "openid profile email" (hardcoded). + - `id_token`: RS256 JWT, claims iss, sub, aud=client_id, exp, iat, email, name, nonce. + - `refresh_token`: opaque, 30 days (`REFRESH_DAYS`), stored hash; bound to central session_hash. + - `expires_in`: 900; `token_type`: "Bearer"; `app_session`: opaque app session token (30 days, non-OIDC, used by `/introspect`). + - `grant_type=refresh_token`: `refresh_token`, `client_id`, `client_secret`. Rotates: old revoked, new issued. No reuse detection (reuse does not revoke the chain). + - Errors: JSON `{"error": "invalid_request" | "invalid_client" | "invalid_grant" | "unsupported_grant_type"}` with 400 (401 for invalid_client). +- `GET /userinfo`: `Authorization: Bearer `. Verifies signature, requires aud to be a registered client. Returns `{"sub","email","name"}`. Failure: 401 `invalid_token` with `WWW-Authenticate: Bearer`. + +### 3.3 Introspection +- `POST /introspect` (form: `token`, `client_id`, `client_secret`). Token is an app_session (opaque). Response JSON: `{"active": true, "sub", "email", "name", "admin", "photo_version", "timezone", "exp"}` or `{"active": false}`. Active requires: client_id match, central session alive, user not disabled, app session not expired/revoked. Invalid client → 401 `{"error":"invalid_client"}`. + +### 3.4 Directory (member mirror) +- `GET /directory` (Basic). JSON array of non-disabled members: `sub`, `email`, `name`, `admin`, `photo_version`, `timezone`, `disabled` (false). Invalid client → 401 `{"error":"invalid_client"}`. +- `GET /directory/live` (Basic). SSE. First frame: comment "directory live" and `retry: 5000`. Events: + - `event: profile`, data = member JSON (may carry `disabled: true`, although the full list excludes disabled members). + - `event: revoked`, data `{"sub": ""}`. + - Ticks are silent. Keep-alive comments. Stream window 50 minutes (`WINDOW`), then closes; client reconnects. + +### 3.5 Profile photo +- `GET /photo/{user_id}` with Basic credentials (see 2.7). Used by sibling apps to show avatars. + +### 3.6 Live SSE for browsers +- `GET /live` (session cookie; signed-in users). SSE, 50-min window, per-connection resolved session. + - `event: profile` data `{"kind":"profile","sub":""}` for any member change (not filtered to the viewer). + - `event: revoked` (empty data) sent to matching user + session hash, or all sessions of a user. + - Tick → default message with data `{}`. +- Client JS (`live_script`): EventSource `/live`; on `revoked` navigates home; on error probes `/api/me`, on 401 navigates home. + +### 3.7 Health +- `GET /healthz` (no auth): body `ok {IM_BUILD_SHA}` (build SHA from env, default `dev`). +- im itself probes each service's `{url}/healthz`: 2 s timeout, success status and body starting "ok". Shared reqwest client, 30 s cache (`CACHE_TTL`). + +### 3.8 Family registry +- `GET /family` (Basic). JSON array ordered by position: `key`, `name`, `url`, `limit_bytes`. (`owner` and `client_id` are not serialized.) +- `POST /family/register` (Basic). JSON body `{key, name, url}`. Owner and client_id = authenticated client id. + - Success: returns the service JSON (200). + - 409 `{"error":"owned"}` if another client owns the key. + - 400 `{"error":"invalid","reason":...}` on validation failure. + - Claims unowned rows; refreshing own row updates url/owner/client_id; name stays admin's. + +### 3.9 Local-process hints +- `IM_BUILD_SHA` env used in /healthz; `IM_*` env vars used by the im-client example only. + +## 4. Data model + +Storage: Turso (single writer, one connection behind `tokio::sync::Mutex`, `BEGIN IMMEDIATE` transactions). Schema: SCHEMA const in `crates/im-core/src/store.rs`, plus guarded ALTERs in `Store::migrate`. No `migrations/` directory exists. Files beside DB: `storage/photos/`, `im.key` (32-byte at-rest key, mode 0600). + +Tables: +- `users`: id (ULID PK), email (UNIQUE COLLATE NOCASE), name, password_hash (Argon2id PHC), totp_secret (BLOB, sealed), totp_confirmed (bool), totp_last_step (replay guard), admin (bool), disabled (bool), created_at, photo_mime, photo_version (int, cache key), theme (default `light`), language (default `en`), ui (default `instrument`), timezone (default `UTC+03:00`). +- `invites`: token (hash PK), email, invited_by (user id, nulled on inviter delete), admin (bool, role), created_at, expires_at, accepted_at. +- `sessions`: token_hash PK, user_id FK, created_at, expires_at, revoked_at, ip, agent (User-Agent), seen_at (throttled to 5 min). +- `oidc_clients`: client_id PK, name, secret_hash, redirect_uris (JSON text), created_at. +- `auth_codes`: code_hash PK, client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, expires_at (60 s), consumed_at. +- `refresh_tokens`: token_hash PK, user_id, client_id, session_hash FK sessions, expires_at, revoked_at. +- `signing_keys`: kid PK, private_der_enc (PKCS#8, sealed), public_der, created_at, active (default 1; never set to 0 in code). +- `app_sessions`: token_hash PK, user_id, client_id, session_hash, created_at, expires_at, revoked_at. +- `events`: id (ULID PK), at, kind, actor, detail (audit log). +- `reset_links`: token (hash PK), user_id, created_at, expires_at, used_at. +- `email_changes`: old_token_hash PK, new_token_hash UNIQUE, user_id, old_email, new_email, created_at, expires_at, confirmed_old_at, confirmed_new_at, used_at. +- `login_attempts`: key, at; index on key+at (rolling 1 h window). +- `settings`: key PK, value. Policy keys (invite_days, session_days, max_sessions, pending_minutes, reset_minutes, login_attempts_per_hour), smtp_* keys (host, port, username, from, from_name, password sealed as `smtp_password`), smtp_check_at, smtp_check_ms, smtp_check_error. +- `services`: key PK, name, url, position, owner (client id; null if unowned), client_id, storage_limit_bytes. + +Migration ALTERs (`migrate`): users.photo_mime, photo_version, theme, language, ui, timezone, totp_last_step; services.client_id, storage_limit_bytes; sessions.ip, agent, seen_at. Services seed from config only when table is empty. + +Sealed values use the `v1:` envelope (see 6). + +## 5. Config keys + +File: `config/im.toml` (also written with DEFAULTS by `Config::load()` if missing). Path resolution beside the binary's working dir (`%h/im` in deploy). + +| Key | Default | Notes | +|---|---|---| +| `database` | `im.db` | Turso DB path; key file and storage dir live beside it | +| `listen` | `127.0.0.1:7650` | bind address | +| `issuer` | `http://127.0.0.1:7650` | must be http(s); trailing slash trimmed; https makes cookies Secure | +| `[[services]]` | in/Files/`http://127.0.0.1:7655`, im/Account/`http://127.0.0.1:7650`, iz/Board/`http://127.0.0.1:7654` | first-boot seed only; key in/im/iz; url http(s) | +| `[smtp]` | commented example | host, port (587 default), username, from, from_name, password (password stored sealed in DB, not in TOML) | + +Policy defaults (admin-editable in `settings`; values < 1 clamp to default): +- `invite_days` 7 +- `session_days` 30 (DB expiry; the cookie MaxAge is a constant 30 days, see oddities) +- `max_sessions` 5 (oldest revoked when exceeded) +- `pending_minutes` 10 +- `reset_minutes` 60 +- `login_attempts_per_hour` 10 + +Constants: `MIN_PASSWORD_CHARS` 10; `SESSION_DAYS` 30; `CODE_SECONDS` 60; `TOKEN_SECONDS` 900; `REFRESH_DAYS` 30; `APP_SESSION_DAYS` 30; `PHOTO_LIMIT_BYTES` 5 MiB; live `WINDOW` 50 min; `CACHE_TTL` 30 s (health); health timeout 2 s; SMTP probe timeout 15 s; probe timeout for SMTP check; `DEFAULT_TIMEZONE` "UTC+03:00"; Argon2 m=19456 KiB, t=2, p=1; show-once secret TTL 10 min; photo max-age 31536000. + +Env: `IM_BUILD_SHA` (build-time, default `dev`); im-client example reads `IM_ISSUER`, `IM_CLIENT_ID`, `IM_CLIENT_SECRET`. + +CLI (`im-web` binary; no subcommand = serve): +- `invite [--admin]`; `revoke `; `promote `; `demote ` +- `create-client `; `rotate-client `; `revoke-client ` +- `pack [--root DIR] [--out FILE]`; `unpack FILE [--root DIR] [--force]` + +Serve startup: seed services when empty; `register_self` (im's own row claimed with owner "im" from issuer on each boot); sweep orphan photo files (deletes unknown files and `*.incoming-*` / `*.tmp`; reports rows missing files); create signing key if none; BodyLimit on `/api/profile_photo`; cookies; assets bundle; trusted proxies `nearest(1)`; graceful shutdown on SIGTERM/Ctrl+C. + +## 6. Security mechanisms + +- Passwords: Argon2id (m=19456 KiB, t=2, p=1, v0x13), PHC strings. `dummy_verify` for unknown emails to equalize timing. Rules: min 10 chars; reject if it contains the email, local part, or name words (>= 3 chars, substring); change must differ from current; wrong current rejected. +- Tokens: 32 random bytes, base64url no pad; stored as SHA-256 hex. Compared with `subtle` (constant time) where applicable. +- Cookies: `im_session` (raw random token; HttpOnly, SameSite=Lax, Secure iff issuer is https, Path=/, Max-Age 30 days constant); `im_pending` (sealed JSON; 10 min). App cookie in im-client: sealed JSON, MaxAge 30 days. +- Sealing: XChaCha20-Poly1305, `v1:` envelope (base64 of 24-byte nonce || ciphertext), key = 32-byte `im.key` (mode 0600, created on first boot). +- Sealed at rest: TOTP secrets, signing private key (PKCS#8), SMTP password, pending cookie. +- JWT: RS256 (PKCS#1 v1.5 + SHA-256), hand-rolled `sign_jwt`; RSA-2048 key generated on first boot; no rotation mechanism. +- PKCE: S256 required on /authorize; verified at /token. +- Auth codes: single use, 60 s TTL, peek then consume in immediate transaction. +- Refresh: rotation on each use; old revoked; no reuse-detection chain revocation. +- Login rate limit: per-key rolling 1 h window, `login_attempts_per_hour` (default 10); keys: email (login), `totp:{user}`, `forgot:{email}`. Limits successful-login lockout by design (DoS possible). +- Session policy: `max_sessions` cap (oldest revoked); sessions revoked on disable, delete, password reset, password change (others), sign-out-everywhere; `seen_at` throttled to 5 min. +- Disabled users: refused at login, at session resolve, at introspection. +- Open redirects: `safe_back` allows local paths and same-origin family URLs only; redirect_uri exact match. +- Email confirmation: email change requires both old and new addresses to confirm; GET confirmation pages do not mutate. +- Forgot password: always same response (no enumeration). +- Show-once secrets: client secrets and invite links shown once via in-memory shelf (`SHOWN_SECRETS`, 10-minute TTL, one-time ticket). +- Basic auth for cross-app endpoints checks client_id:secret against `oidc_clients`. +- Trusted proxy: client label from `nearest(1)` proxy (X-Forwarded-For). +- Photo upload: magic-byte sniffing; 5 MiB limit; BodyLimit. +- Audit: events logged for admin and account actions; introspection deliberately not logged; `log` never fails the caller. +- Pack archives: 0600 mode; unpack refuses unsafe paths; manifest version must be 1; tightens .toml, .keys, .key to 0600. Pack archive contains plaintext `.key` (not encrypted). +- Not present: CSP, HSTS, X-Frame-Options, CSRF tokens (relies on SameSite=Lax + same-origin forms). + +## 7. im-client crate public API + +Crate: `crates/im-client` (features: `oidc` default on). Directory mirror always available. + +OIDC (`oidc` feature): +- `Config { issuer, client_id, client_secret, redirect_uri, cookie_name, cookie_key: [u8; 32] }`. +- `mount(builder, config)`: adds routes: + - `GET /auth/login?next=`: sets PKCE pair cookie `{cookie_name}_pkce` (10 min); redirects to `/authorize` (scope openid profile email). + - `GET /auth/callback`: state check; code exchange; id_token validation (JWKS cached 1 h, refetch on unknown kid; nonce check); introspection of app_session; sets app cookie. Errors redirect to `/?auth_error=...`. + - `GET /auth/logout`: clears app cookie only (does not end the central session). +- `current_user(cx) -> Option` where `User { sub, email, name, admin, photo_version }`; introspects per request. +- App session cookie: sealed JSON `{app_session, exp}`, MaxAge 30 days. +- Refresh tokens are ignored by the client (app session lasts 30 days). +- `Error` enum: `Http`, `Refused`, `Token`. + +Directory mirror (`directory` module): +- `DirectoryClient::new(issuer, client_id, client_secret)`; methods `directory()` (full list), `photo(sub)` (bytes), `open_stream()` returning `DirectoryStream` with `next()` yielding `DirectoryEvent`. +- `DirectoryMember { sub, email, name, admin, photo_version, timezone (default "UTC+03:00"), disabled }`. +- `DirectoryEvent { Profile(DirectoryMember), Revoked { sub } }`. +- `spawn_sync(client, on_member, on_resync)`: full pass, then stream; backoff 1 s doubling to 30 s cap; `on_resync` after reconnect. +- Oddity: module doc comment has a truncated sentence about `open_stream` and events. + +Example: `crates/im-client/examples/demo.rs`: smoke-test app at redirect `http://127.0.0.1:7656/auth/callback`, env IM_ISSUER / IM_CLIENT_ID / IM_CLIENT_SECRET, fixed DEV_COOKIE_KEY [42; 32]; routes `/` and `/me`. + +## 8. UI pages and style + +Pages (all server-rendered via topcoat `view!`): +- Signed out: `/` (login card), `/login`, `/login/totp`, `/invite/{token}`, `/forgot`, `/reset/{token}`, `/email/{token}`, `/enroll` (hardcoded English for these pages). +- Signed in: `/` landing (sections profile, sessions, apps, preferences, password), `/enroll`, `/people/{user_id}`, `/admin` (users, services, message, settings, logs, health; mail reached only via redirect). +- Errors shown via `error_text` and OK messages via `ok_text`; mapping in i18n.rs. Landing uses the user's language; `lang_of` returns English when signed out. +- Shell (`layout.rs` `shell`): `lang` attribute; `data-theme="dark"` only when user theme is dark; `data-ui` = instrument (default) or ledger. Google Fonts link loads IBM Plex Mono only (Newsreader used by ledger is not loaded; falls back to Georgia). +- Signed-in chrome: "im" mark with family flyout (sibling marks, health dots; CSS hover/focus). +- Avatar: photo or initial span; avatar viewer JS and XHR upload-progress JS (`avatar_script`). +- Soft navigation JS (`soft_nav_script`): fetch + DOM swap; `data-hard` opts out. +- Themed dropdown (`dropdown.rs`): replaces `select.auth-input`; search box when > 7 options or `data-search`; keyboard support; panel appended to body; only on signed-in pages. +- Logs fit-to-viewport script (`LOG_FIT_SCRIPT`), cookie `im_rows_logs`, clamp 5 to 200 rows, default 50. +- Session list: `
` modal cards; admin popovers use top-layer dialogs. +- Styles: `style/main.scss` and `style/_ledger.scss` compiled by `build.rs` (grass) to `crates/im-web/assets/main.css` (generated, 1304 lines, not in .gitignore). Tokens: --ink #1a1b1d, --accent #46557b, --font-sans system-ui, --font-mono IBM Plex Mono. Two data-ui languages (instrument: default; ledger: warm paper, serif display) plus dark variants. Responsive breakpoint at 720px. +- Assets served through topcoat `asset!("assets/main.css")` bundle. + +## 9. Oddities, bugs, half-finished items + +Security: +- `/email_change` leaks both confirmation links in the redirect query (`links=`) when mail sending fails. +- Any registered OIDC client can call `/family/register` for an unowned key and URL; im then GETs `{url}/healthz` from signed-in pages (SSRF-like probe). +- Any valid client can claim unowned service rows. +- `/photo`, `/directory`, `/family` are accessible to any registered client (no per-client scoping). +- Live `profile` frames are broadcast to all signed-in users (not filtered per viewer). +- No CSP, HSTS, X-Frame-Options; no CSRF tokens (SameSite=Lax + same-origin forms only). +- Signing key never rotated (`active` never set to 0). +- Refresh token reuse does not revoke the chain. +- Access token `scope` hardcoded to "openid profile email". +- Login rate limit can lock out a legitimate user (per-account DoS). +- Admin user email edit (`/admin/user_email`) bypasses two-sided confirmation (intentional rescue but unguarded). +- Admin cannot disable TOTP for locked-out users; no UI to remove 2FA. +- `login` allows sign-in without 2FA (2FA is optional for everyone). +- `verify_login` receives untrimmed email while rate-limit key is trimmed (inconsistent). + +Functional / consistency: +- `SESSION_DAYS` const (30) vs policy `session_days`: cookie Max-Age is the constant while DB expiry uses policy. +- `delete_user` does not delete `reset_links`, `email_changes`, `auth_codes`, `events`, or the photo file (orphans). +- Duplicate pending invites for the same email are allowed. +- `set_smtp` with empty host removes smtp keys but NOT `smtp_password`. +- `NavMail` i18n key is unused; the admin mail section is unreachable from the nav. +- `connected_chip` TR and EN branches are identical (trivial). +- Unused `let _ = issuer;` in the enroll page (dead code). +- `/enroll` revisit regenerates the TOTP secret for already-confirmed users (`set_totp` resets `totp_confirmed = 0`), which could lock out a user who has not yet re-scanned. +- Login, TOTP, invite, enroll, forgot, reset, and email-confirm pages are English-only even for Turkish users. +- `invite_mail` English only. +- im-client module doc has a truncated sentence. +- `store.rs` `migrate` comment for services.client_id sits under the timezone ALTER (comment placement mismatch). +- `migrations/` directory absent; schema is in `store.rs`. +- Pack archive holds plaintext `*.key` (unencrypted at-rest key). +- `connected_chip` and some i18n keys duplicated; `kind_word` lacks labels for several audit kinds (forgot_limited, user_demoted, services_updated, email_changed, email_change_asked); raw kind strings shown instead. +- `main.css` is a generated artifact and is not git-ignored. +- Discovery document omits introspection and end-session endpoints even though they exist. +- Deploy: GitHub Actions `.github/workflows/main.yml` runs `cargo test --workspace`, bundles assets, deploys over SSH to `$HOME/im` with `current` / `current.new` / `current.previous` swap; systemd unit `deploy/im.service` (`ExecStart=%h/im/current/im-web`, Restart=on-failure, WantedBy=default.target); health-check and rollback loop; served-stylesheet hash check. +- Release profile: fat LTO, codegen-units=1; `dist` profile: thin LTO, codegen-units=16. +- Coverage gaps in this survey: admin logs/health markup and test modules were surveyed, not read line-by-line; i18n full key list not enumerated; `main.css` not read in detail.