commit 353f08e0bb2ad8837a31ddfc64e3e0d527a34027 Author: mnovak <2+mnovak@noreply.gitea.marek-novak.cz> Date: Thu Nov 5 09:05:13 2026 +0100 Fundamentum client v0.5.0 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..6816f1f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2647 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "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", + "aes", + "cipher", + "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 = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[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 = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.119", +] + +[[package]] +name = "bip39" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc" +dependencies = [ + "bitcoin_hashes", + "serde", + "unicode-normalization", +] + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +dependencies = [ + "borsh", + "serde", +] + +[[package]] +name = "bitcoin_hashes" +version = "0.14.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bca4c7abb40c8817d77403c880988cfd484f23ab2365726afb2f798363e2c4a2" +dependencies = [ + "hex-conservative", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[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 = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +dependencies = [ + "find-msvc-tools", + "shlex 2.0.1", +] + +[[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 = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20 0.9.1", + "cipher", + "poly1305", + "zeroize", +] + +[[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", + "zeroize", +] + +[[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 = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "core-models" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee3344d349528f449816cfa85e558c439bdca5a6d8a738cfb21e69f0b2b1952f" +dependencies = [ + "hax-lib", + "pastey", + "rand", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +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 = "crabgrind" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7459e07732f6de74001fcf73a3fdfbb0f368e4fd8e2392f4a2206a065e6e95" +dependencies = [ + "bindgen", + "cc", + "pkg-config", +] + +[[package]] +name = "crc32fast" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +dependencies = [ + "cfg-if", +] + +[[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 = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[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", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto 0.2.9", + "rustc_version", + "subtle", + "zeroize", +] + +[[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", + "fiat-crypto 0.3.0", + "rustc_version", + "subtle", +] + +[[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 = "custos-local" +version = "0.5.0" +dependencies = [ + "data-encoding", + "getrandom 0.3.4", + "serde_json", + "sha2 0.10.9", + "tessera", + "thiserror", + "zeroize", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid 0.10.2", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.2", + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der 0.7.10", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "signature 2.2.0", + "spki 0.7.3", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8 0.10.2", + "signature 2.2.0", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek 4.1.3", + "ed25519", + "rand_core 0.6.4", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array", + "group", + "hkdf 0.12.4", + "pem-rfc7468", + "pkcs8 0.10.2", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "envelope" +version = "0.5.0" +dependencies = [ + "proptest", + "tessera", + "thiserror", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[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 = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[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 = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[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-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", +] + +[[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 = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hax-lib" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a33cb227f97ee5c419064c31d7c55a7d895f28d8019ccdadc311cc036500c4" +dependencies = [ + "hax-lib-macros", + "num-bigint", + "num-traits", +] + +[[package]] +name = "hax-lib-macros" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28da835a5f153e9f3d0cc1f42ee605a1cfa9093c93348193793d60a1b0908b51" +dependencies = [ + "hax-lib-macros-types", + "proc-macro-error2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "hax-lib-macros-types" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed327e9a28d6ee018a4a9ba842d4ee27e378c8a591d2beb6f42f32b24a02fcb" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_json", + "uuid", +] + +[[package]] +name = "hex-conservative" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3fef046dca3ca91ee1408a8c1b80ab777e80a4d308d1bf4e7adb3fcb047e08" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac 0.12.1", +] + +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac 0.13.0", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "hpke-rs" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812de62ab573b876c6c40d7553bae9402ae3bad95b64af06f964388eecb9b7b1" +dependencies = [ + "hpke-rs-crypto", + "hpke-rs-libcrux", + "hpke-rs-rust-crypto", + "libcrux-sha3", + "log", + "serde", + "subtle", + "tls_codec", + "zeroize", +] + +[[package]] +name = "hpke-rs-crypto" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c461da2e0c9c93d875b597f0c78214fb0d2d5c57834b2ef2a2fa057fa20e24" +dependencies = [ + "rand", + "zeroize", +] + +[[package]] +name = "hpke-rs-libcrux" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c1ace95ef11fbbd84527eada5fc1304f66720fc4c008db30d888d62d3c52613" +dependencies = [ + "hpke-rs-crypto", + "libcrux-aead", + "libcrux-ecdh", + "libcrux-hkdf", + "libcrux-kem", + "libcrux-traits", + "rand", + "rand_chacha 0.10.0", + "rand_core 0.10.1", + "zeroize", +] + +[[package]] +name = "hpke-rs-rust-crypto" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a606ac19851da841862ef5f39d26d6227bfcfb4047417801a66c1f6e6652d71" +dependencies = [ + "aes-gcm", + "chacha20poly1305", + "hkdf 0.13.0", + "hpke-rs-crypto", + "k256", + "ml-kem", + "p256", + "p384", + "rand", + "rand_chacha 0.10.0", + "rand_core 0.10.1", + "sha2 0.11.1", + "subtle", + "x-wing", + "x25519-dalek 2.0.1", + "zeroize", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "ctutils", + "typenum", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "k256" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" +dependencies = [ + "cfg-if", + "elliptic-curve", +] + +[[package]] +name = "keccak" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", +] + +[[package]] +name = "kem" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01737161ba802849cfd486b5bd209d38ba4943494c249a8126005170c7621edd" +dependencies = [ + "crypto-common 0.2.2", + "rand_core 0.10.1", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libcrux-aead" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22acbe68be84b7b41aaba6e39b87036fc4324dee628d94773750bf3d7e906d69" +dependencies = [ + "libcrux-aes", + "libcrux-chacha20poly1305", + "libcrux-secrets", + "libcrux-traits", +] + +[[package]] +name = "libcrux-aes" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57cc95b11dbc797b1e169467b1fc4205c4e6ee2ce516a035ad7342ce5f6ae971" +dependencies = [ + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-secrets", + "libcrux-traits", +] + +[[package]] +name = "libcrux-chacha20poly1305" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "537e6eee5cdc9a980014d058784b0be09614f0596df789b114f7833aa9f35d75" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-poly1305", + "libcrux-secrets", + "libcrux-traits", +] + +[[package]] +name = "libcrux-curve25519" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4f3cfd5e31cb9745e290ee061222c380ec42884654b09fc7d12a5b0ed63e028" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-secrets", + "libcrux-traits", +] + +[[package]] +name = "libcrux-ecdh" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a227590b89ff55ce7cd97b5a7468c82d231db8f3b890bb4d4fb6d271e7524d7" +dependencies = [ + "libcrux-curve25519", + "libcrux-p256", + "rand", + "tls_codec", +] + +[[package]] +name = "libcrux-hacl-rs" +version = "0.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66106db376ae249af86911aee048cf73ea1f394d6653026fc988dd22cf2a4ace" +dependencies = [ + "libcrux-macros", +] + +[[package]] +name = "libcrux-hkdf" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc94e651dca4d47edbcdd88bb2428ce16a2bd86b7a4e7170da87b505478f9839" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-hmac", + "libcrux-secrets", +] + +[[package]] +name = "libcrux-hmac" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "500ad9b32c715161b594172ca1fb11503a1c033b393ff4c0c33505ce51c1943c" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-sha2", + "libcrux-traits", +] + +[[package]] +name = "libcrux-intrinsics" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98a0c574d4eb81d0814bc2b91e4a433d7e0b35851b1d62eb5dd95c064f1f76d0" +dependencies = [ + "core-models", + "hax-lib", +] + +[[package]] +name = "libcrux-kem" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "541a7377fb35060892e0620982e224e47419f10da8c212453bf642dafe529691" +dependencies = [ + "libcrux-curve25519", + "libcrux-ecdh", + "libcrux-ml-kem", + "libcrux-p256", + "libcrux-sha3", + "libcrux-traits", + "rand", +] + +[[package]] +name = "libcrux-macros" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffd6aa2dcd5be681662001b81d493f1569c6d49a32361f470b0c955465cd0338" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "libcrux-ml-kem" +version = "0.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8160f7d64fd2716b4fd05cc886a042f8dcda18d9206c0d506e2c67bdf97daa" +dependencies = [ + "hax-lib", + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-secrets", + "libcrux-sha3", + "libcrux-traits", + "rand", + "tls_codec", +] + +[[package]] +name = "libcrux-p256" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3400732702d578be622257b98cec85e9b0cd34a67f1f06d3ebe9ae34963cdf02" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-secrets", + "libcrux-sha2", + "libcrux-traits", +] + +[[package]] +name = "libcrux-platform" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d9e21d7ed31a92ac539bd69a8c970b183ee883872d2d19ce27036e24cb8ecc4" +dependencies = [ + "libc", +] + +[[package]] +name = "libcrux-poly1305" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a9144949845813a0b8787d08cbba47baabe59c83f3043e558e6e92385c40cc" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", +] + +[[package]] +name = "libcrux-secrets" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79054fc9037cb70d6a546cf094cea7d7df06af5e49d230ba24103d27ccc886f1" +dependencies = [ + "crabgrind", + "hax-lib", +] + +[[package]] +name = "libcrux-sha2" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e46e1be0b77098cc6ce82137864936ecad3a1b9fd4303dd51202ca140dd1e" +dependencies = [ + "libcrux-hacl-rs", + "libcrux-macros", + "libcrux-traits", +] + +[[package]] +name = "libcrux-sha3" +version = "0.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c09f5c39afae0528e1f70a3c1e3c6ee649ec1f19dda26fc9b6ea91108fb879ef" +dependencies = [ + "hax-lib", + "libcrux-intrinsics", + "libcrux-platform", + "libcrux-traits", +] + +[[package]] +name = "libcrux-traits" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fa7a21e8c2e8baa8b40f0b176740f2ca4baadd79d1b00e48d6b1e363c42085a" +dependencies = [ + "libcrux-secrets", + "rand", +] + +[[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 = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "ml-dsa" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f6d49c3f3f0e10e18ca975ffda66f8da0ec36521c1d911adcbc521bf0743f5c" +dependencies = [ + "const-oid 0.10.2", + "crypto-common 0.2.2", + "ctutils", + "hybrid-array", + "module-lattice", + "pkcs8 0.11.0", + "shake", + "signature 3.0.0", +] + +[[package]] +name = "ml-kem" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84ca78b66f46050d49fa21693ae8adab2081d8101b65d8067316b6b70b64a0d1" +dependencies = [ + "hybrid-array", + "kem", + "module-lattice", + "rand_core 0.10.1", + "sha3", + "shake", +] + +[[package]] +name = "module-lattice" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4a1e412c8ee83a1c678f427806219c49c96b2511b9f07497514f0e43fb26155" +dependencies = [ + "ctutils", + "hybrid-array", + "num-traits", +] + +[[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 = "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-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 = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "openmls" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce4173f914cbc2dd28d9499f19e92f3e1bfebd9eea1607889924a77ca63d3ffc" +dependencies = [ + "log", + "openmls_serialization_helpers", + "openmls_traits", + "rayon", + "serde", + "serde_bytes", + "thiserror", + "tls_codec", + "zeroize", +] + +[[package]] +name = "openmls_basic_credential" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbd3f0c3422e7c7a8496f042b547b0c28d0793f8ba97feb401966e58196a1e40" +dependencies = [ + "ed25519-dalek", + "ml-dsa", + "openmls_traits", + "p256", + "p384", + "rand_core 0.6.4", + "serde", + "tls_codec", + "zeroize", +] + +[[package]] +name = "openmls_memory_storage" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce927945a16eaa19302ed5ccef052f01ba68f2ba7ae67e4ac4ff2fc661445364" +dependencies = [ + "log", + "openmls_traits", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "openmls_rust_crypto" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36bf3fe824ead6e81d22f49a9cd7feffca3494979fac14c1248e19516e3625f1" +dependencies = [ + "aes-gcm", + "chacha20poly1305", + "ed25519-dalek", + "hkdf 0.13.0", + "hmac 0.13.0", + "hpke-rs", + "hpke-rs-crypto", + "hpke-rs-rust-crypto", + "ml-dsa", + "openmls_memory_storage", + "openmls_traits", + "p256", + "p384", + "rand_chacha 0.3.1", + "rand_core 0.10.1", + "rand_core 0.6.4", + "sha2 0.11.1", + "thiserror", + "tls_codec", +] + +[[package]] +name = "openmls_serialization_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e2cf2193541e83ce1a89aaa44c2fd4783abd54853823075a32b60ef032284c0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "thiserror", +] + +[[package]] +name = "openmls_traits" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac13edad8698eb1917cbc1dab99591fa1594d84320904fe3fc5121854f95831c" +dependencies = [ + "serde", + "tls_codec", +] + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der 0.7.10", + "spki 0.7.3", +] + +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der 0.8.3", + "spki 0.8.1", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[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", +] + +[[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 = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[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 = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags", + "chacha20 0.10.2", + "core_detect", + "num-traits", + "rand", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[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 = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20 0.10.2", + "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.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e6af7f3e25ded52c41df4e0b1af2d047e45896c2f3281792ed68a1c243daedb" +dependencies = [ + "ppv-lite86", + "rand_core 0.10.1", +] + +[[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.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core 0.10.1", +] + +[[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 = "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 = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac 0.12.1", + "subtle", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[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 = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der 0.7.10", + "generic-array", + "pkcs8 0.10.2", + "subtle", + "zeroize", +] + +[[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_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[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 = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha3" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759" +dependencies = [ + "digest 0.11.3", + "keccak", + "sponge-cursor", +] + +[[package]] +name = "shake" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a" +dependencies = [ + "digest 0.11.3", + "keccak", + "sponge-cursor", +] + +[[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 = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der 0.7.10", +] + +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der 0.8.3", +] + +[[package]] +name = "sponge-cursor" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[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 = "tabellarius-client" +version = "0.5.0" +dependencies = [ + "chacha20poly1305", + "data-encoding", + "envelope", + "openmls", + "openmls_basic_credential", + "openmls_memory_storage", + "openmls_rust_crypto", + "openmls_traits", + "serde", + "serde_json", + "sha2 0.10.9", + "tabellarius-proto", + "tessera", + "thiserror", + "ureq", + "zeroize", +] + +[[package]] +name = "tabellarius-proto" +version = "0.5.0" +dependencies = [ + "data-encoding", + "ed25519-dalek", + "getrandom 0.3.4", + "sha2 0.10.9", + "thiserror", + "zeroize", +] + +[[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", + "windows-sys 0.61.2", +] + +[[package]] +name = "tessera" +version = "0.5.0" +dependencies = [ + "bip39", + "chacha20poly1305", + "data-encoding", + "ed25519-dalek", + "hkdf 0.12.4", + "proptest", + "sha2 0.10.9", + "static_assertions", + "thiserror", + "zeroize", +] + +[[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 = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tls_codec" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18cc98286004cea38f717e2b03d990fc774fbfd38a82720de40e5c94365067c8" +dependencies = [ + "serde", + "serde_bytes", + "tls_codec_derive", + "zeroize", +] + +[[package]] +name = "tls_codec_derive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "674f41dd95f76cdeb005c83f9444e20cf43daebef37cde9e49a9ca6f4e87b423" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[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_edit" +version = "0.25.18+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec6e78bd70db9420d8d212fa9dc97f116448a1ceff5d00eabb991d407e21396" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[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 = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[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 = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[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", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[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.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +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.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "x-wing" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01576e56599d01d75c5efcd5b30fa5de29e776f5a225e43fbf8c92c7302d4c8b" +dependencies = [ + "kem", + "ml-kem", + "sha3", + "shake", + "x25519-dalek 3.0.0", +] + +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek 4.1.3", + "rand_core 0.6.4", + "serde", + "zeroize", +] + +[[package]] +name = "x25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6" +dependencies = [ + "curve25519-dalek 5.0.0", + "rand_core 0.10.1", +] + +[[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 = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..bd90ad7 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,22 @@ +[workspace] +resolver = "3" +members = ["crates/*"] + +[workspace.package] +version = "0.5.0" +edition = "2024" +license = "Apache-2.0 OR MIT" +repository = "https://gitea.marek-novak.cz/mnovak/fundamentum-client" +publish = false + +[workspace.lints.rust] +unsafe_code = "forbid" + +[workspace.dependencies] +ed25519-dalek = { version = "2.2", default-features = false, features = ["std", "zeroize", "fast"] } +sha2 = "0.10" +hkdf = "0.12" +bip39 = { version = "2", default-features = false, features = ["std"] } +zeroize = { version = "1.8", features = ["derive"] } +thiserror = "2" +data-encoding = "2" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..beee171 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 The Fundamentum Domi contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ba445ce --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +# Fundamentum Domi: the client crates + +One identity and one relay for every Domi app. This repository holds the client side of Fundamentum 0.5.0 +(tag `v0.5.0`), published so that public code (Fabrica's core, the apps) can depend on it: + +| Crate | What | +| :-- | :-- | +| `tessera` | identity: root key from a mnemonic, subkey certificates, match code, hybrid logical clock, merge, revocation, backup | +| `envelope` | the signed event envelope (`TEV1`), strict decoding | +| `tabellarius-proto` | the Tabellarius wire protocol: mailbox ids, per-mailbox request signatures, limits | +| `custos-local` | Windows: the app side of Custos' local API (subkey seed, certificate request) | +| `tabellarius-client` | the Tabellarius client: OpenMLS groups, sealed invites, offline outbox, encrypted state | + +The formats are in `docs/TESSERA.md` and `docs/TABELLARIUS.md`. Depend by tag: + +```toml +tessera = { git = "https://gitea.marek-novak.cz/mnovak/fundamentum-client.git", tag = "v0.5.0" } +``` + +This is a snapshot made at each release of the private Fundamentum repository, which also holds the relay +(AGPL-3.0) and the client's tests against it. Changes are made there, not here. + +**Licence:** Apache-2.0 OR MIT (`LICENSE-APACHE`, `LICENSE-MIT`). diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml new file mode 100644 index 0000000..ba23f30 --- /dev/null +++ b/crates/client/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "tabellarius-client" +description = "Tabellarius client: MLS groups (OpenMLS) of Domi devices, signed event logs, offline-first sync (docs/TABELLARIUS.md)" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[lints] +workspace = true + +[dependencies] +tessera = { path = "../tessera" } +envelope = { path = "../envelope" } +tabellarius-proto = { path = "../proto" } +openmls = "0.9" +openmls_rust_crypto = "0.6" +openmls_basic_credential = "0.6" +openmls_memory_storage = "0.6" +openmls_traits = "0.6" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +chacha20poly1305 = "0.10" +sha2.workspace = true +zeroize.workspace = true +thiserror.workspace = true +data-encoding.workspace = true + +# The native driver only (docs/V1_1B.md §1); the browser talks through fetch. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +ureq = "3" + diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs new file mode 100644 index 0000000..b13fbd9 --- /dev/null +++ b/crates/client/src/lib.rs @@ -0,0 +1,1739 @@ +//! The Tabellarius client (docs/TABELLARIUS.md): an app's devices and the people it shares with form MLS groups +//! (OpenMLS); every change is a signed TEV1 envelope inside an MLS application message; the relay sees only +//! ciphertext in random mailboxes. Offline first: `send` never needs the relay, `sync` reports whether it was +//! reachable. +//! +//! ```no_run +//! # use tabellarius_client::*; +//! # fn device() -> Device { unimplemented!() } +//! # fn store() -> Box { unimplemented!() } +//! let mut c = Client::open("https://relay.example", device(), store())?; +//! let mine = c.self_group()?; // your own devices +//! c.send(&mine, vec![AppEvent { kind: "expense".into(), body: b"{...}".to_vec() }])?; +//! let report = c.sync()?; // upload, download, verify, merge +//! for e in c.log(&mine)? { /* apply(state, e) */ } +//! # Ok::<(), ClientError>(()) +//! ``` + +#[cfg(not(target_arch = "wasm32"))] +mod native; +mod store; +mod transport; + +#[cfg(not(target_arch = "wasm32"))] +pub use native::{Client, Ureq}; +#[cfg(not(target_arch = "wasm32"))] +pub use store::EncryptedFileStore; +pub use store::{MemoryStore, StateStore}; +pub use transport::{DeviceSigner, HttpRequest, HttpResponse, Transport}; + +use envelope::Envelope; +use openmls::prelude::tls_codec::{Deserialize as _, Serialize as _}; +use openmls::prelude::*; +use openmls_basic_credential::SignatureKeyPair; +use openmls_memory_storage::MemoryStorage; +use openmls_rust_crypto::RustCrypto; +use openmls_traits::OpenMlsProvider; +use openmls_traits::crypto::OpenMlsCrypto; +use openmls_traits::types::{HpkeAeadType, HpkeCiphertext, HpkeConfig, HpkeKdfType, HpkeKemType, SignatureScheme}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::sync::Arc; +use tabellarius_proto::{ + LIVE_MAX_SUBS, LIVE_METHOD, MAX_BATCH, MailboxKey, b64, group_mailbox, live_path, random32, unb64, unb64_32, +}; +use tessera::{BackupSecret, Clock, Hlc, Id, Log, PublicKey, Revocation, RevocationSet, Subkey, SubkeyCert}; + +const CS: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519; +const HPKE: HpkeConfig = HpkeConfig(HpkeKemType::DhKem25519, HpkeKdfType::HkdfSha256, HpkeAeadType::ChaCha20Poly1305); +const HPKE_INFO: &[u8] = b"tabellarius invite v1"; +/// How far ahead of this device's clock an event may be. +const MAX_DRIFT_MS: u64 = 5 * 60 * 1000; +/// Envelopes per MLS message, by size. +const BATCH_BYTES: usize = 200 * 1024; +/// The event kind that carries a `TRV1` revocation (docs/V1_1.md §1). Not an app event: `log` leaves it out. +pub const REVOKE_KIND: &str = "tessera.revoke"; +/// The associated data of every backup part (docs/V1_1.md §3). +const BACKUP_AAD: &[u8] = b"tabellarius backup v1"; +/// Plaintext per backup part: one part per relay message. +const BACKUP_PART: usize = 200 * 1024; + +/// What Custos gives a native app: its subkey and the cert from the person's root. +pub struct Device { + pub subkey: Subkey, + pub cert: SubkeyCert, +} + +/// One change, as the app sees it. `body` follows the app's own versioned schema. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AppEvent { + pub kind: String, + pub body: Vec, +} + +/// An event in a group's log: verified when it arrived, in its final order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VerifiedEvent { + pub hlc: Hlc, + pub author: PublicKey, + pub root: PublicKey, + pub schema: u32, + pub kind: String, + pub body: Vec, + pub hash: [u8; 32], + /// The signed envelope, for re-verification or rebuilding. + pub envelope: Vec, +} + +/// A group, by its MLS group id (base64url). +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct GroupId(pub String); + +impl std::fmt::Display for GroupId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GroupInfo { + pub id: GroupId, + pub name: String, + pub is_self: bool, + pub active: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MemberInfo { + /// The MLS leaf index: what `remove` takes. + pub index: u32, + pub root: PublicKey, + pub subkey: PublicKey, + pub me: bool, +} + +/// What a `sync` did. `rejected` holds every dropped event, member or message with its reason; the app logs +/// them. +#[derive(Clone, Debug, Default)] +pub struct SyncReport { + pub relay_ok: bool, + pub sent: usize, + pub received: usize, + pub joined: Vec, + pub added: usize, + pub rejected: Vec, +} + +/// A message from a live socket, as it concerns this device (docs/V1_1B.md §3). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LiveNotice { + /// The group has new mail: sync. + Mail(GroupId), + /// The relay refused or ended the group's subscription, with its reason (`unregistered_key`: this device + /// was removed; `stale`: subscribe again). + Ended(GroupId, String), + /// The answer to a ping. + Pong, +} + +#[derive(Debug, thiserror::Error)] +pub enum ClientError { + #[error("the relay is unreachable: {0}")] + Offline(String), + #[error("the relay refused: {0}")] + Relay(String), + #[error("no such group")] + NoGroup, + #[error("not an invite token")] + BadToken, + #[error("MLS: {0}")] + Mls(String), + #[error("state: {0}")] + State(String), + #[error("{0}")] + Invalid(String), +} + +type Result = std::result::Result; + +fn mls(e: E) -> ClientError { + ClientError::Mls(format!("{e:?}")) +} + +fn sha(b: &[u8]) -> String { + b64(&Sha256::digest(b)) +} + +// ---------- the OpenMLS provider ---------- + +#[derive(Default)] +struct Provider { + crypto: RustCrypto, + storage: MemoryStorage, +} + +impl OpenMlsProvider for Provider { + type CryptoProvider = RustCrypto; + type RandProvider = RustCrypto; + type StorageProvider = MemoryStorage; + + fn storage(&self) -> &MemoryStorage { + &self.storage + } + fn crypto(&self) -> &RustCrypto { + &self.crypto + } + fn rand(&self) -> &RustCrypto { + &self.crypto + } +} + +fn create_config() -> MlsGroupCreateConfig { + MlsGroupCreateConfig::builder() + .ciphersuite(CS) + .wire_format_policy(PURE_CIPHERTEXT_WIRE_FORMAT_POLICY) + .use_ratchet_tree_extension(true) + .max_past_epochs(5) + .sender_ratchet_configuration(SenderRatchetConfiguration::new(20, 1000)) + .build() +} + +fn join_config() -> MlsGroupJoinConfig { + MlsGroupJoinConfig::builder() + .wire_format_policy(PURE_CIPHERTEXT_WIRE_FORMAT_POLICY) + .use_ratchet_tree_extension(true) + .max_past_epochs(5) + .sender_ratchet_configuration(SenderRatchetConfiguration::new(20, 1000)) + .build() +} + +// ---------- byte frames (all of them travel encrypted) ---------- + +struct Reader<'a>(&'a [u8]); + +impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + if self.0.len() < n { + return None; + } + let (a, b) = self.0.split_at(n); + self.0 = b; + Some(a) + } + fn u16(&mut self) -> Option { + Some(u16::from_be_bytes(self.take(2)?.try_into().ok()?) as usize) + } + fn u32(&mut self) -> Option { + Some(u32::from_be_bytes(self.take(4)?.try_into().ok()?) as usize) + } + fn u64(&mut self) -> Option { + Some(u64::from_be_bytes(self.take(8)?.try_into().ok()?)) + } + fn var16(&mut self) -> Option<&'a [u8]> { + let n = self.u16()?; + self.take(n) + } + fn var32(&mut self) -> Option<&'a [u8]> { + let n = self.u32()?; + self.take(n) + } + fn done(&self) -> bool { + self.0.is_empty() + } +} + +fn put16(out: &mut Vec, b: &[u8]) { + out.extend_from_slice(&(b.len() as u16).to_be_bytes()); + out.extend_from_slice(b); +} + +fn put32(out: &mut Vec, b: &[u8]) { + out.extend_from_slice(&(b.len() as u32).to_be_bytes()); + out.extend_from_slice(b); +} + +/// An app event inside an envelope: `str16 kind ‖ body`. +fn event_payload(e: &AppEvent) -> Vec { + let mut out = Vec::with_capacity(2 + e.kind.len() + e.body.len()); + put16(&mut out, e.kind.as_bytes()); + out.extend_from_slice(&e.body); + out +} + +fn parse_payload(p: &[u8]) -> Option<(String, Vec)> { + let mut r = Reader(p); + let kind = String::from_utf8(r.var16()?.to_vec()).ok()?; + Some((kind, r.0.to_vec())) +} + +/// `TBA1 ‖ u32 count ‖ (u32 len ‖ envelope)*`: what one MLS application message carries. +fn batches(envelopes: &[Vec]) -> Vec> { + let mut out = Vec::new(); + let mut cur: Vec<&Vec> = Vec::new(); + let mut size = 0; + let mut flush = |cur: &mut Vec<&Vec>| { + if cur.is_empty() { + return; + } + let mut b = b"TBA1".to_vec(); + b.extend_from_slice(&(cur.len() as u32).to_be_bytes()); + for e in cur.iter() { + put32(&mut b, e); + } + out.push(b); + cur.clear(); + }; + for e in envelopes { + if size + e.len() > BATCH_BYTES { + flush(&mut cur); + size = 0; + } + size += e.len() + 4; + cur.push(e); + } + flush(&mut cur); + out +} + +fn parse_batch(b: &[u8]) -> Option>> { + let mut r = Reader(b); + if r.take(4)? != b"TBA1" { + return None; + } + let n = r.u32()?; + let mut out = Vec::with_capacity(n.min(10_000)); + for _ in 0..n { + out.push(r.var32()?.to_vec()); + } + r.done().then_some(out) +} + +/// The credential (docs/TABELLARIUS.md §2): `TDC1 ‖ u16 len ‖ cert ‖ mailbox key ‖ binding`. +fn credential_identity(cert: &SubkeyCert, mailbox_key: &[u8; 32], binding: &tessera::Signature) -> Vec { + let mut out = b"TDC1".to_vec(); + put16(&mut out, &cert.to_bytes()); + out.extend_from_slice(mailbox_key); + out.extend_from_slice(binding.as_bytes()); + out +} + +/// The cert inside a `TDC1` credential, unchecked. +fn cert_of(identity: &[u8]) -> Option { + let mut r = Reader(identity); + (r.take(4)? == b"TDC1").then_some(())?; + SubkeyCert::from_bytes(r.var16()?).ok() +} + +/// A member as the group knows it: checked, with what the group needs from it. +struct Checked { + cert: SubkeyCert, + mailbox_key: [u8; 32], +} + +/// Whether a member's credential is acceptable for a group of `app` (and, for a self group, of `self_root`). +fn check_member( + identity: &[u8], + mls_key: &[u8], + app: &Id, + self_root: Option<&PublicKey>, + now_s: u64, +) -> std::result::Result { + let mut r = Reader(identity); + if r.take(4) != Some(b"TDC1".as_slice()) { + return Err("its credential is not a Domi credential".into()); + } + let cert = r.var16().and_then(|c| SubkeyCert::from_bytes(c).ok()).ok_or("its certificate does not decode")?; + let mailbox_key: [u8; 32] = r.take(32).and_then(|k| k.try_into().ok()).ok_or("its credential is truncated")?; + let binding: [u8; 64] = r.take(64).and_then(|k| k.try_into().ok()).ok_or("its credential is truncated")?; + if !r.done() { + return Err("its credential has trailing bytes".into()); + } + cert.verify(&cert.root(), now_s).map_err(|e| format!("its certificate: {e}"))?; + if cert.app_id() != app { + return Err(format!("a device of another app ({}) cannot join a {app} group", cert.app_id())); + } + if let Some(root) = self_root + && cert.root() != *root + { + return Err("a device of another person cannot join a self group".into()); + } + let ok = tessera::verify_credential_sig( + &cert.subkey(), + &[mls_key, mailbox_key.as_slice()].concat(), + &tessera::Signature::from_bytes(binding), + ); + if !ok { + return Err("its credential's binding signature is not valid".into()); + } + Ok(Checked { cert, mailbox_key }) +} + +// ---------- saved state ---------- + +#[derive(Clone, Default, Serialize, Deserialize)] +struct GroupState { + /// The MLS group id, base64url. + id: String, + name: String, + is_self: bool, + /// This device's MLS signature public key in this group. + sig_pub: String, + /// This device's mailbox key seed for this group. + mailbox_key: String, + mailbox_ready: bool, + cursor: u64, + outbox: Vec, + /// Hashes of ciphertexts this device sent: skipped when they come back. + own: Vec, + /// The log's envelopes, base64url. + log: Vec, + /// Every root that has been a member: events from them stay verifiable. + roots: Vec, + active: bool, + last_sent: Option, +} + +#[derive(Clone, Serialize, Deserialize)] +struct OpenInvite { + group: String, + mailbox: String, + my_key: String, + hpke_private: String, + cursor: u64, +} + +#[derive(Clone, Serialize, Deserialize)] +struct PendingJoin { + mailbox: String, + access_key: String, + reply_private: String, + sig_pub: String, + group_mailbox_key: String, + sent: String, + cursor: u64, +} + +#[derive(Default, Serialize, Deserialize)] +struct Saved { + version: u32, + /// The OpenMLS storage: base64url key → base64url value. + mls: Vec<(String, String)>, + clock: (u64, u32), + groups: Vec, + invites: Vec, + joins: Vec, + /// SHA-256 of the last backup uploaded (docs/V1_1.md §3): the same log is not uploaded twice. + #[serde(default)] + last_backup: Option, +} + +/// A message from a mailbox: its seq and bytes. +type Fetched = (u64, Vec); + +/// One backup being reassembled: its latest seq, its part count, the parts so far. +type BackupParts = (u64, u16, std::collections::BTreeMap>); + +enum Net { + Down(String), + Refused(u16, String), +} + +impl From for ClientError { + fn from(n: Net) -> Self { + match n { + Net::Down(e) => ClientError::Offline(e), + Net::Refused(s, e) => ClientError::Relay(format!("{s} {e}")), + } + } +} + +// ---------- the client ---------- + +/// The client's core (docs/V1_1B.md §1): every operation, over any [`Transport`] and [`DeviceSigner`]. An +/// operation that talks to the relay or signs with the device key is `async`; the native [`Client`] drives it +/// to completion at once, the browser package through its event loop. +pub struct Core { + relay: String, + signer: S, + cert: SubkeyCert, + app: Id, + store: Box, + provider: Provider, + saved: Saved, + clock: Clock, + now_ms: Arc u64 + Send + Sync>, + schema: u32, + transport: T, +} + +impl Core { + /// Opens the client for the app of `cert`, the cert of `signer`'s key, with its state from `store` (or + /// empty). `now_ms` is the clock (Unix milliseconds). + pub fn open( + relay: &str, + cert: SubkeyCert, + signer: S, + transport: T, + store: Box, + now_ms: Arc u64 + Send + Sync>, + ) -> Result { + if cert.subkey() != signer.public() { + return Err(ClientError::Invalid("the cert is for another key than the device's".into())); + } + let saved: Saved = match store.load().map_err(|e| ClientError::State(e.to_string()))? { + Some(b) => { + serde_json::from_slice(&b).map_err(|_| ClientError::State("the saved state does not parse".into()))? + } + None => Saved { version: 1, ..Saved::default() }, + }; + let provider = Provider::default(); + { + let mut values = provider.storage.values.write().map_err(|_| ClientError::State("storage lock".into()))?; + for (k, v) in &saved.mls { + values.insert( + unb64(k).ok_or(ClientError::State("bad key".into()))?, + unb64(v).ok_or(ClientError::State("bad value".into()))?, + ); + } + } + let mut clock = Clock::default(); + let _ = clock.observe(Hlc { wall: saved.clock.0, logical: saved.clock.1 }, saved.clock.0); + Ok(Core { + relay: relay.trim_end_matches('/').to_owned(), + app: cert.app_id().clone(), + signer, + cert, + store, + provider, + saved, + clock, + now_ms, + schema: 1, + transport, + }) + } + + /// The schema version written into new events (default 1). + pub fn set_schema(&mut self, schema: u32) { + self.schema = schema; + } + + fn now_s(&self) -> u64 { + (self.now_ms)() / 1000 + } + + /// The whole state, unencrypted, for a [`StateStore`]. + pub fn export_state(&self) -> Result> { + let mut saved = Saved { + version: 1, + mls: Vec::new(), + clock: (self.clock.last().wall, self.clock.last().logical), + groups: self.saved.groups.clone(), + invites: self.saved.invites.clone(), + joins: self.saved.joins.clone(), + last_backup: self.saved.last_backup.clone(), + }; + let values = self.provider.storage.values.read().map_err(|_| ClientError::State("storage lock".into()))?; + saved.mls = values.iter().map(|(k, v)| (b64(k), b64(v))).collect(); + saved.mls.sort(); + serde_json::to_vec(&saved).map_err(|e| ClientError::State(e.to_string())) + } + + fn save(&self) -> Result<()> { + let bytes = zeroize::Zeroizing::new(self.export_state()?); + self.store.save(&bytes).map_err(|e| ClientError::State(e.to_string())) + } + + // ---- the relay ---- + + async fn call( + &self, + key: &MailboxKey, + method: &str, + path: &str, + body: Option, + ) -> std::result::Result { + let bytes = body.map(|b| b.to_string().into_bytes()).unwrap_or_default(); + let h = key.sign_request(method, path, &bytes, self.now_s()); + let mut headers: Vec<(&'static str, String)> = h.pairs().iter().map(|(n, v)| (*n, v.to_string())).collect(); + if matches!(method, "PUT" | "POST") { + headers.push(("content-type", "application/json".into())); + } + let req = HttpRequest { method: method.to_owned(), url: format!("{}{path}", self.relay), headers, body: bytes }; + let resp = self.transport.send(req).await.map_err(Net::Down)?; + let status = resp.status; + let v: Value = serde_json::from_slice(&resp.body).unwrap_or(Value::Null); + if (200..300).contains(&status) { + Ok(v) + } else { + Err(Net::Refused(status, v["error"].as_str().unwrap_or("error").to_owned())) + } + } + + async fn upload(&self, key: &MailboxKey, mailbox: &str, messages: &[String]) -> std::result::Result, Net> { + let mut seqs = Vec::new(); + for chunk in messages.chunks(MAX_BATCH.min(8)) { + let v = self + .call(key, "POST", &format!("/v1/mailboxes/{mailbox}/messages"), Some(json!({ "messages": chunk }))) + .await?; + seqs.extend(v["seqs"].as_array().into_iter().flatten().filter_map(Value::as_u64)); + } + Ok(seqs) + } + + async fn fetch( + &self, + key: &MailboxKey, + mailbox: &str, + after: u64, + ) -> std::result::Result<(Vec, bool), Net> { + let v = self.call(key, "GET", &format!("/v1/mailboxes/{mailbox}/messages?after={after}"), None).await?; + let msgs = v["messages"] + .as_array() + .into_iter() + .flatten() + .filter_map(|m| Some((m["seq"].as_u64()?, unb64(m["data"].as_str()?)?))) + .collect(); + Ok((msgs, v["more"] == true)) + } + + // ---- groups ---- + + fn group_index(&self, g: &GroupId) -> Result { + self.saved.groups.iter().position(|s| s.id == g.0).ok_or(ClientError::NoGroup) + } + + fn mls_group(&self, gs: &GroupState) -> Result { + let id = unb64(&gs.id).ok_or(ClientError::NoGroup)?; + MlsGroup::load(self.provider.storage(), &openmls::group::GroupId::from_slice(&id)) + .map_err(mls)? + .ok_or(ClientError::NoGroup) + } + + fn signer(&self, sig_pub: &str) -> Result { + let public = unb64(sig_pub).ok_or(ClientError::State("bad key".into()))?; + SignatureKeyPair::read(self.provider.storage(), &public, SignatureScheme::ED25519) + .ok_or(ClientError::State("the group's signature key is missing".into())) + } + + /// A fresh MLS signature key and mailbox key for one group, and the credential that binds them to this + /// device's cert. + async fn member_keys(&self) -> Result<(SignatureKeyPair, MailboxKey, CredentialWithKey)> { + let sig = SignatureKeyPair::new(SignatureScheme::ED25519).map_err(mls)?; + sig.store(self.provider.storage()).map_err(mls)?; + let mbox = MailboxKey::generate(); + let identity = self.credential(sig.public(), &mbox.public()).await?; + let cwk = CredentialWithKey { + credential: BasicCredential::new(identity).into(), + signature_key: sig.to_public_vec().into(), + }; + Ok((sig, mbox, cwk)) + } + + /// This device's credential for a group where it uses `mls_key` and `mailbox_key`, bound by the device key. + async fn credential(&self, mls_key: &[u8], mailbox_key: &[u8; 32]) -> Result> { + let binding = self + .signer + .sign_credential_tbs(&[mls_key, mailbox_key.as_slice()].concat()) + .await + .map_err(|e| ClientError::Invalid(format!("the device key did not sign: {e}")))?; + Ok(credential_identity(&self.cert, mailbox_key, &binding)) + } + + async fn create_group(&mut self, name: &str, is_self: bool) -> Result { + let (sig, mbox, cwk) = self.member_keys().await?; + let gid = random32(); + MlsGroup::new_with_group_id( + &self.provider, + &sig, + &create_config(), + openmls::group::GroupId::from_slice(&gid), + cwk, + ) + .map_err(mls)?; + let gs = GroupState { + id: b64(&gid), + name: name.to_owned(), + is_self, + sig_pub: b64(sig.public()), + mailbox_key: b64(mbox.seed().as_ref()), + roots: vec![self.cert.root().to_string()], + active: true, + ..GroupState::default() + }; + self.saved.groups.push(gs); + let i = self.saved.groups.len() - 1; + let _ = self.ensure_mailbox(i).await; + self.save()?; + Ok(GroupId(b64(&gid))) + } + + /// The group of this person's own devices for this app; created on first use. + pub async fn self_group(&mut self) -> Result { + match self.saved.groups.iter().find(|g| g.is_self && g.active) { + Some(g) => Ok(GroupId(g.id.clone())), + None => self.create_group("self", true).await, + } + } + + /// A new group shared with people you will invite. + pub async fn open_group(&mut self, name: &str) -> Result { + self.create_group(name, false).await + } + + pub fn groups(&self) -> Vec { + self.saved + .groups + .iter() + .map(|g| GroupInfo { + id: GroupId(g.id.clone()), + name: g.name.clone(), + is_self: g.is_self, + active: g.active, + }) + .collect() + } + + fn mailbox_of(gs: &GroupState) -> Result { + Ok(b64(&group_mailbox(&unb64(&gs.id).ok_or(ClientError::NoGroup)?))) + } + + fn key_of(seed: &str) -> Result { + Ok(MailboxKey::from_seed(&unb64_32(seed).ok_or(ClientError::State("bad mailbox key".into()))?)) + } + + /// Creates the group's mailbox on the relay if this device has not yet. + async fn ensure_mailbox(&mut self, i: usize) -> std::result::Result<(), Net> { + let gs = &self.saved.groups[i]; + if gs.mailbox_ready { + return Ok(()); + } + let (Ok(mailbox), Ok(key)) = (Self::mailbox_of(gs), Self::key_of(&gs.mailbox_key)) else { return Ok(()) }; + match self.call(&key, "PUT", &format!("/v1/mailboxes/{mailbox}"), None).await { + Ok(_) | Err(Net::Refused(409, _)) => { + self.saved.groups[i].mailbox_ready = true; + Ok(()) + } + Err(e) => Err(e), + } + } + + pub fn members(&self, g: &GroupId) -> Result> { + let gs = &self.saved.groups[self.group_index(g)?]; + let group = self.mls_group(gs)?; + let me = group.own_leaf_index(); + Ok(group + .members() + .filter_map(|m| { + let c = check_member(m.credential.serialized_content(), &m.signature_key, &self.app, None, 0) + .ok() + .or_else(|| { + // Show members whose cert has since expired too. + let mut r = Reader(m.credential.serialized_content()); + r.take(4)?; + let cert = SubkeyCert::from_bytes(r.var16()?).ok()?; + Some(Checked { cert, mailbox_key: [0; 32] }) + })?; + Some(MemberInfo { + index: m.index.u32(), + root: c.cert.root(), + subkey: c.cert.subkey(), + me: m.index == me, + }) + }) + .collect()) + } + + // ---- events ---- + + fn log_of(gs: &GroupState) -> Log { + Log::from_stored(gs.log.iter().filter_map(|e| Envelope::decode(&unb64(e)?).ok()).collect()) + } + + /// The revocations in a group's log (docs/V1_1.md §1), checked against the group's roots. + fn revocations_of(gs: &GroupState) -> RevocationSet { + let roots: Vec = gs.roots.iter().filter_map(|r| PublicKey::from_text(r)).collect(); + let mut set = RevocationSet::default(); + for e in Self::log_of(gs).events() { + if let Some((kind, body)) = parse_payload(e.payload()) + && kind == REVOKE_KIND + && let Ok(r) = Revocation::from_bytes(&body) + { + let _ = set.add(r, &roots); + } + } + set + } + + /// Hashes of the stored events that a revocation in the log rules out. + fn revoked_hashes(gs: &GroupState) -> Vec<[u8; 32]> { + let set = Self::revocations_of(gs); + Self::log_of(gs) + .events() + .iter() + .filter(|e| set.check(&e.author(), &e.hash()).is_err()) + .map(|e| e.hash()) + .collect() + } + + /// The group's log, in its final order: every event a revocation rules out is left out, and so are the + /// revocations themselves (they are not app events). + pub fn log(&self, g: &GroupId) -> Result> { + let gs = &self.saved.groups[self.group_index(g)?]; + let set = Self::revocations_of(gs); + Ok(Self::log_of(gs) + .events() + .iter() + .filter(|e| set.check(&e.author(), &e.hash()).is_ok()) + .filter_map(|e| { + let (kind, body) = parse_payload(e.payload())?; + if kind == REVOKE_KIND { + return None; + } + Some(VerifiedEvent { + hlc: e.hlc(), + author: e.author(), + root: e.cert().root(), + schema: e.schema(), + kind, + body, + hash: e.hash(), + envelope: e.as_bytes().to_vec(), + }) + }) + .collect()) + } + + /// The log's canonical bytes (tessera `Log::to_bytes`): equal on every device that has the same events. + pub fn log_bytes(&self, g: &GroupId) -> Result> { + Ok(Self::log_of(&self.saved.groups[self.group_index(g)?]).to_bytes()) + } + + fn store_log(gs: &mut GroupState, log: &Log) { + gs.log = log.events().iter().map(|e| b64(e.as_bytes())).collect(); + } + + /// Encrypts `envelopes` for the group's current epoch and queues them. + fn queue(&mut self, i: usize, envelopes: &[Vec]) -> Result<()> { + let gs = self.saved.groups[i].clone(); + let mut group = self.mls_group(&gs)?; + let signer = self.signer(&gs.sig_pub)?; + for b in batches(envelopes) { + let out = group.create_message(&self.provider, &signer, &b).map_err(mls)?.to_bytes().map_err(mls)?; + let g = &mut self.saved.groups[i]; + g.own.push(sha(&out)); + g.last_sent = Some(b64(&out)); + g.outbox.push(b64(&out)); + } + Ok(()) + } + + /// Signs `events`, applies them to the local log at once, and queues them for the group. Never needs the + /// relay. + pub async fn send(&mut self, g: &GroupId, events: Vec) -> Result<()> { + let i = self.group_index(g)?; + if !self.saved.groups[i].active { + return Err(ClientError::Invalid("this device is no longer in the group".into())); + } + let mut sealed = Vec::with_capacity(events.len()); + for e in &events { + let hlc = self.clock.tick((self.now_ms)()).map_err(|e| ClientError::Invalid(e.to_string()))?; + let tbs = Envelope::to_be_signed(&self.signer.public(), &self.cert, self.schema, hlc, &event_payload(e)) + .map_err(|e| ClientError::Invalid(e.to_string()))?; + let sig = self + .signer + .sign_event_tbs(&tbs) + .await + .map_err(|e| ClientError::Invalid(format!("the device key did not sign: {e}")))?; + sealed.push(Envelope::with_signature(tbs, sig).map_err(|e| ClientError::Invalid(e.to_string()))?); + } + let merged = tessera::merge(&Self::log_of(&self.saved.groups[i]), sealed.clone(), |_| Ok::<(), ()>(())).log; + Self::store_log(&mut self.saved.groups[i], &merged); + let raw: Vec> = sealed.iter().map(|e| e.as_bytes().to_vec()).collect(); + self.queue(i, &raw)?; + self.save() + } + + /// Test hook: queues envelopes as they are, unchecked, as a hostile member would. + #[doc(hidden)] + pub fn send_envelopes_unchecked(&mut self, g: &GroupId, envelopes: Vec>) -> Result<()> { + let i = self.group_index(g)?; + self.queue(i, &envelopes)?; + self.save() + } + + /// The last ciphertext this device produced for the group (tests and diagnostics). + #[doc(hidden)] + pub fn last_sent_ciphertext(&self, g: &GroupId) -> Result> { + let gs = &self.saved.groups[self.group_index(g)?]; + gs.last_sent.as_deref().and_then(unb64).ok_or(ClientError::NoGroup) + } + + /// Test hook: processes one ciphertext as if it came from the relay. + #[doc(hidden)] + pub fn process_raw(&mut self, g: &GroupId, ciphertext: &[u8]) -> std::result::Result { + let i = self.group_index(g).map_err(|e| e.to_string())?; + let mut report = SyncReport::default(); + let r = self.process_group_message(i, ciphertext, &mut report); + let _ = self.save(); + r + } + + /// Processes one message from the group mailbox: a commit (members checked first) or a batch of events + /// (each verified). Returns how many events were new. + fn process_group_message( + &mut self, + i: usize, + data: &[u8], + report: &mut SyncReport, + ) -> std::result::Result { + let gs = self.saved.groups[i].clone(); + let mut group = self.mls_group(&gs).map_err(|e| e.to_string())?; + let msg = MlsMessageIn::tls_deserialize_exact(data).map_err(|_| "a message that is not MLS".to_owned())?; + let pm = msg.try_into_protocol_message().map_err(|_| "an MLS message that is not for a group".to_owned())?; + let processed = group + .process_message(&self.provider, pm) + .map_err(|e| format!("a message this device cannot read ({e:?})"))?; + let committer_root = match processed.sender() { + Sender::Member(idx) => group.member(*idx).and_then(|c| cert_of(c.serialized_content())).map(|c| c.root()), + _ => None, + }; + match processed.into_content() { + ProcessedMessageContent::ApplicationMessage(a) => { + let envelopes = parse_batch(&a.into_bytes()).ok_or("a message that is not an event batch")?; + let roots: Vec = gs.roots.iter().filter_map(|r| PublicKey::from_text(r)).collect(); + let now = (self.now_ms)(); + let mut decoded = Vec::new(); + for raw in envelopes { + match Envelope::decode(&raw) { + Ok(e) => decoded.push(e), + Err(e) => report.rejected.push(format!("{}: an event dropped: {e}", gs.name)), + } + } + let merged = tessera::merge(&Self::log_of(&gs), decoded, |e| { + e.verify(&roots, now, MAX_DRIFT_MS)?; + parse_payload(e.payload()).map(|_| ()).ok_or(envelope::VerifyError::BadSignature) + }); + for (e, why) in &merged.rejected { + report.rejected.push(format!("{}: an event dropped (author {}): {why}", gs.name, e.author())); + } + for e in merged.log.events() { + let _ = self.clock.observe(e.hlc(), now); + } + let before = Self::revoked_hashes(&gs); + Self::store_log(&mut self.saved.groups[i], &merged.log); + let after = Self::revoked_hashes(&self.saved.groups[i]); + let newly = after.iter().filter(|h| !before.contains(h)).count(); + if newly > 0 { + report.rejected.push(format!( + "{}: {newly} event(s) dropped: written by a revoked key, not among the events its revocation kept", + gs.name + )); + } + Ok(merged.added.saturating_sub(newly)) + } + ProcessedMessageContent::StagedCommitMessage(sc) => { + let self_root = gs.is_self.then(|| self.cert.root()); + // Removing some of another person's devices (while that person stays) needs their revocation for + // each one; removing all of a person's devices removes the person, as in v0.2 (docs/V1_1.md §1). + let revoked = Self::revocations_of(&gs); + let removed: Vec = sc + .remove_proposals() + .filter_map(|rp| { + group.member(rp.remove_proposal().removed()).and_then(|c| cert_of(c.serialized_content())) + }) + .collect(); + let leaves_of = |root: &PublicKey| { + group + .members() + .filter(|m| cert_of(m.credential.serialized_content()).is_some_and(|c| c.root() == *root)) + .count() + }; + for cert in &removed { + let root = cert.root(); + let whole_person = removed.iter().filter(|c| c.root() == root).count() == leaves_of(&root); + if Some(root) != committer_root && !whole_person && !revoked.is_revoked(&cert.subkey()) { + return Err(format!( + "{}: a commit removes one of another person's devices without a revocation; not applied", + gs.name + )); + } + } + // A renewed credential is checked like a new member's. + if let Some(leaf) = sc.update_path_leaf_node() { + check_member( + leaf.credential().serialized_content(), + leaf.signature_key().as_slice(), + &self.app, + self_root.as_ref(), + self.now_s(), + ) + .map_err(|why| { + format!("{}: a commit updates a member to a refused credential ({why}); not applied", gs.name) + })?; + } + let mut new_roots = Vec::new(); + for add in sc.add_proposals() { + let leaf = add.add_proposal().key_package().leaf_node(); + let c = check_member( + leaf.credential().serialized_content(), + leaf.signature_key().as_slice(), + &self.app, + self_root.as_ref(), + self.now_s(), + ) + .map_err(|why| { + format!("{}: a commit adds a member that is refused ({why}); not applied", gs.name) + })?; + new_roots.push(c.cert.root().to_string()); + } + group + .merge_staged_commit(&self.provider, *sc) + .map_err(|e| format!("a commit could not be applied ({e:?})"))?; + let g = &mut self.saved.groups[i]; + for r in new_roots { + if !g.roots.contains(&r) { + g.roots.push(r); + } + } + if !group.is_active() { + g.active = false; + } + Ok(0) + } + _ => Ok(0), + } + } + + // ---- invites ---- + + /// An invite token (`tab1:…`, for a QR code or a link). Needs the relay. Whoever holds the token can ask to + /// join once; this device admits a valid device of this app (for a self group, of this person). + pub async fn invite(&mut self, g: &GroupId) -> Result { + let i = self.group_index(g)?; + self.ensure_mailbox(i).await?; + let id = random32(); + let mailbox = b64(&id); + let mine = MailboxKey::generate(); + let access = MailboxKey::generate(); + self.call(&mine, "PUT", &format!("/v1/mailboxes/{mailbox}"), None).await?; + self.call( + &mine, + "POST", + &format!("/v1/mailboxes/{mailbox}/keys"), + Some(json!({ "key": b64(&access.public()) })), + ) + .await?; + let kp = self.provider.crypto().derive_hpke_keypair(HPKE, &random32()).map_err(mls)?; + let mut t = b"TIN1".to_vec(); + put16(&mut t, self.relay.as_bytes()); + t.extend_from_slice(&id); + t.extend_from_slice(access.seed().as_ref()); + put16(&mut t, &kp.public); + put16(&mut t, self.app.as_str().as_bytes()); + self.saved.invites.push(OpenInvite { + group: g.0.clone(), + mailbox, + my_key: b64(mine.seed().as_ref()), + hpke_private: b64(kp.private.as_ref()), + cursor: 0, + }); + self.save()?; + Ok(format!("tab1:{}", b64(&t))) + } + + /// Asks to join with an invite token. Needs the relay. The group arrives on a later `sync`, once the + /// inviting device has admitted this one. + pub async fn join(&mut self, token: &str) -> Result<()> { + let raw = token.trim().strip_prefix("tab1:").and_then(unb64).ok_or(ClientError::BadToken)?; + let mut r = Reader(&raw); + if r.take(4) != Some(b"TIN1".as_slice()) { + return Err(ClientError::BadToken); + } + let relay = r.var16().and_then(|u| String::from_utf8(u.to_vec()).ok()).ok_or(ClientError::BadToken)?; + let id: [u8; 32] = r.take(32).and_then(|b| b.try_into().ok()).ok_or(ClientError::BadToken)?; + let access: [u8; 32] = r.take(32).and_then(|b| b.try_into().ok()).ok_or(ClientError::BadToken)?; + let inviter = r.var16().ok_or(ClientError::BadToken)?.to_vec(); + let _app = r.var16().ok_or(ClientError::BadToken)?; + if !r.done() { + return Err(ClientError::BadToken); + } + if relay.trim_end_matches('/') != self.relay { + return Err(ClientError::Invalid(format!("this invite is for another relay ({relay})"))); + } + let (sig, mbox, cwk) = self.member_keys().await?; + let bundle = KeyPackage::builder().build(CS, &self.provider, &sig, cwk).map_err(mls)?; + let kp = bundle.key_package().tls_serialize_detached().map_err(mls)?; + let reply = self.provider.crypto().derive_hpke_keypair(HPKE, &random32()).map_err(mls)?; + let mut plain = b"TIJ1".to_vec(); + put32(&mut plain, &kp); + put16(&mut plain, &reply.public); + let ct = self.provider.crypto().hpke_seal(HPKE, &inviter, HPKE_INFO, b"", &plain).map_err(mls)?; + let sealed = ct.tls_serialize_detached().map_err(mls)?; + let access_key = MailboxKey::from_seed(&access); + let mailbox = b64(&id); + self.upload(&access_key, &mailbox, &[b64(&sealed)]).await?; + self.saved.joins.push(PendingJoin { + mailbox, + access_key: b64(&access), + reply_private: b64(reply.private.as_ref()), + sig_pub: b64(sig.public()), + group_mailbox_key: b64(mbox.seed().as_ref()), + sent: sha(&sealed), + cursor: 0, + }); + self.save() + } + + fn hpke_open(&self, private: &str, sealed: &[u8]) -> Option> { + let ct = HpkeCiphertext::tls_deserialize_exact(sealed).ok()?; + let sk = unb64(private)?; + self.provider.crypto().hpke_open(HPKE, &ct, &sk, HPKE_INFO, b"").ok() + } + + /// Admits the devices that answered this device's invites. One answer per token: the invite is spent + /// whether the device was admitted or refused. + async fn serve_invites(&mut self, report: &mut SyncReport) -> std::result::Result<(), Net> { + for inv in self.saved.invites.clone() { + let Ok(mine) = Self::key_of(&inv.my_key) else { continue }; + let (msgs, _) = self.fetch(&mine, &inv.mailbox, inv.cursor).await?; + let mut answer = None; + for (seq, data) in msgs { + if let Some(x) = self.saved.invites.iter_mut().find(|x| x.mailbox == inv.mailbox) { + x.cursor = seq; + } + if let Some(plain) = self.hpke_open(&inv.hpke_private, &data) { + answer = Some(plain); + break; + } + } + let Some(plain) = answer else { continue }; + match self.admit(&inv, &mine, &plain).await { + Ok(()) => report.added += 1, + Err(why) => report.rejected.push(why), + } + let _ = self + .call(&mine, "DELETE", &format!("/v1/mailboxes/{}/keys/{}", inv.mailbox, b64(&mine.public())), None) + .await; + self.saved.invites.retain(|x| x.mailbox != inv.mailbox); + } + Ok(()) + } + + /// Checks a join request and, if the device is acceptable, adds it: the commit, its mailbox key, the sealed + /// Welcome on the invite mailbox, and the history. + async fn admit(&mut self, inv: &OpenInvite, mine: &MailboxKey, plain: &[u8]) -> std::result::Result<(), String> { + let i = self.group_index(&GroupId(inv.group.clone())).map_err(|e| e.to_string())?; + let gs = self.saved.groups[i].clone(); + let mut r = Reader(plain); + if r.take(4) != Some(b"TIJ1".as_slice()) { + return Err(format!("{}: an invite answer that does not parse", gs.name)); + } + let kp_bytes = r.var32().ok_or("a truncated invite answer")?; + let reply_pub = r.var16().ok_or("a truncated invite answer")?.to_vec(); + let kp = KeyPackageIn::tls_deserialize_exact(kp_bytes) + .map_err(|_| format!("{}: a key package that does not parse", gs.name))? + .validate(self.provider.crypto(), ProtocolVersion::Mls10) + .map_err(|e| format!("{}: a key package that is not valid ({e:?})", gs.name))?; + let leaf = kp.leaf_node(); + let self_root = gs.is_self.then(|| self.cert.root()); + let checked = check_member( + leaf.credential().serialized_content(), + leaf.signature_key().as_slice(), + &self.app, + self_root.as_ref(), + self.now_s(), + ) + .map_err(|why| format!("{}: a device was refused: {why}", gs.name))?; + + let mut group = self.mls_group(&gs).map_err(|e| e.to_string())?; + let signer = self.signer(&gs.sig_pub).map_err(|e| e.to_string())?; + let mailbox = Self::mailbox_of(&gs).map_err(|e| e.to_string())?; + let key = Self::key_of(&gs.mailbox_key).map_err(|e| e.to_string())?; + let (commit, welcome, _) = + group.add_members(&self.provider, &signer, core::slice::from_ref(&kp)).map_err(|e| format!("{e:?}"))?; + let commit = commit.to_bytes().map_err(|e| format!("{e:?}"))?; + let seq = match self.upload(&key, &mailbox, &[b64(&commit)]).await { + Ok(s) => s.first().copied().unwrap_or(0), + Err(_) => { + let _ = group.clear_pending_commit(self.provider.storage()); + return Err(format!("{}: the relay did not take the commit; invite again", gs.name)); + } + }; + group.merge_pending_commit(&self.provider).map_err(|e| format!("{e:?}"))?; + self.call( + &key, + "POST", + &format!("/v1/mailboxes/{mailbox}/keys"), + Some(json!({ "key": b64(&checked.mailbox_key) })), + ) + .await + .map_err(|_| format!("{}: the relay did not register the new device's key", gs.name))?; + { + let g = &mut self.saved.groups[i]; + g.own.push(sha(&commit)); + let root = checked.cert.root().to_string(); + if !g.roots.contains(&root) { + g.roots.push(root); + } + } + // The reply, sealed to the joiner: where to start reading, what the group is, and the Welcome. + let mut reply = b"TIR1".to_vec(); + reply.extend_from_slice(&seq.to_be_bytes()); + reply.push(gs.is_self as u8); + put16(&mut reply, gs.name.as_bytes()); + reply.extend_from_slice(&welcome.to_bytes().map_err(|e| format!("{e:?}"))?); + let ct = + self.provider.crypto().hpke_seal(HPKE, &reply_pub, HPKE_INFO, b"", &reply).map_err(|e| format!("{e:?}"))?; + let sealed = ct.tls_serialize_detached().map_err(|e| format!("{e:?}"))?; + self.upload(mine, &inv.mailbox, &[b64(&sealed)]) + .await + .map_err(|_| format!("{}: the relay did not take the Welcome", gs.name))?; + // History: everything so far, for a device that joins late. + let history: Vec> = + Self::log_of(&self.saved.groups[i]).events().iter().map(|e| e.as_bytes().to_vec()).collect(); + if !history.is_empty() { + self.queue(i, &history).map_err(|e| e.to_string())?; + } + Ok(()) + } + + /// Picks up the groups this device was admitted to. + async fn finish_joins(&mut self, report: &mut SyncReport) -> std::result::Result<(), Net> { + let joins = self.saved.joins.clone(); + for j in joins { + let Ok(access) = Self::key_of(&j.access_key) else { continue }; + let (msgs, _) = self.fetch(&access, &j.mailbox, j.cursor).await?; + for (seq, data) in msgs { + if let Some(x) = self.saved.joins.iter_mut().find(|x| x.mailbox == j.mailbox) { + x.cursor = seq; + } + if sha(&data) == j.sent { + continue; + } + let Some(plain) = self.hpke_open(&j.reply_private, &data) else { continue }; + match self.enter(&j, &plain) { + Ok(g) => report.joined.push(g), + Err(why) => report.rejected.push(why), + } + let _ = self + .call( + &access, + "DELETE", + &format!("/v1/mailboxes/{}/keys/{}", j.mailbox, b64(&access.public())), + None, + ) + .await; + self.saved.joins.retain(|x| x.mailbox != j.mailbox); + break; + } + } + Ok(()) + } + + /// Joins from a sealed reply: checks every member, then keeps the group. + fn enter(&mut self, j: &PendingJoin, plain: &[u8]) -> std::result::Result { + let mut r = Reader(plain); + if r.take(4) != Some(b"TIR1".as_slice()) { + return Err("an invite reply that does not parse".into()); + } + let seq = r.u64().ok_or("a truncated invite reply")?; + let is_self = r.take(1).ok_or("a truncated invite reply")?[0] == 1; + let name = String::from_utf8(r.var16().ok_or("a truncated invite reply")?.to_vec()) + .map_err(|_| "a group name that is not text")?; + let welcome = MlsMessageIn::tls_deserialize_exact(r.0).map_err(|_| "a Welcome that does not parse")?; + let welcome = match welcome.extract() { + MlsMessageBodyIn::Welcome(w) => w, + _ => return Err("an invite reply without a Welcome".into()), + }; + let staged = StagedWelcome::new_from_welcome(&self.provider, &join_config(), welcome, None) + .map_err(|e| format!("a Welcome this device cannot use ({e:?})"))?; + let mut group = + staged.into_group(&self.provider).map_err(|e| format!("a Welcome this device cannot use ({e:?})"))?; + let self_root = is_self.then(|| self.cert.root()); + let now = self.now_s(); + let checked: Vec> = group + .members() + .map(|m| { + check_member(m.credential.serialized_content(), &m.signature_key, &self.app, self_root.as_ref(), now) + }) + .collect(); + let mut roots = Vec::new(); + for c in checked { + match c { + Ok(c) => { + let root = c.cert.root().to_string(); + if !roots.contains(&root) { + roots.push(root); + } + } + Err(why) => { + let _ = group.delete(self.provider.storage()); + return Err(format!("{name}: refused to join: a member is not acceptable ({why})")); + } + } + } + let id = b64(group.group_id().as_slice()); + self.saved.groups.push(GroupState { + id: id.clone(), + name, + is_self, + sig_pub: j.sig_pub.clone(), + mailbox_key: j.group_mailbox_key.clone(), + mailbox_ready: true, + cursor: seq, + roots, + active: true, + ..GroupState::default() + }); + Ok(GroupId(id)) + } + + // ---- removal ---- + + /// Removes a member: commits the removal and takes its mailbox key off the relay. Needs the relay. + pub async fn remove(&mut self, g: &GroupId, member: u32) -> Result<()> { + let i = self.group_index(g)?; + let gs = self.saved.groups[i].clone(); + let mut group = self.mls_group(&gs)?; + if group.own_leaf_index().u32() == member { + return Err(ClientError::Invalid("a device cannot remove itself here".into())); + } + let target = + group.members().find(|m| m.index.u32() == member).ok_or(ClientError::Invalid("no such member".into()))?; + let mut r = Reader(target.credential.serialized_content()); + r.take(4); + r.var16(); + let their_key: Option<[u8; 32]> = r.take(32).and_then(|k| k.try_into().ok()); + let signer = self.signer(&gs.sig_pub)?; + let (commit, _, _) = + group.remove_members(&self.provider, &signer, &[LeafNodeIndex::new(member)]).map_err(mls)?; + let commit = commit.to_bytes().map_err(mls)?; + let mailbox = Self::mailbox_of(&gs)?; + let key = Self::key_of(&gs.mailbox_key)?; + if let Err(e) = self.upload(&key, &mailbox, &[b64(&commit)]).await { + let _ = group.clear_pending_commit(self.provider.storage()); + return Err(e.into()); + } + group.merge_pending_commit(&self.provider).map_err(mls)?; + self.saved.groups[i].own.push(sha(&commit)); + if let Some(k) = their_key { + let _ = self.call(&key, "DELETE", &format!("/v1/mailboxes/{mailbox}/keys/{}", b64(&k)), None).await; + } + self.save() + } + + // ---- revocation, renewal (docs/V1_1.md §1, §2) ---- + + /// The hashes of the events in the group's log written by `subkey` that are still valid: what its + /// revocation keeps. + pub fn events_by(&self, g: &GroupId, subkey: &PublicKey) -> Result> { + let gs = &self.saved.groups[self.group_index(g)?]; + let set = Self::revocations_of(gs); + Ok(Self::log_of(gs) + .events() + .iter() + .filter(|e| e.author() == *subkey && set.check(&e.author(), &e.hash()).is_ok()) + .map(|e| e.hash()) + .collect()) + } + + /// [`Core::events_by`] over every group, deduplicated: the list a revocation of `subkey` sends to Custos + /// (docs/TESSERA.md §12, `revoke`). + pub fn events_by_all(&self, subkey: &PublicKey) -> Vec<[u8; 32]> { + let mut all = std::collections::BTreeSet::new(); + for g in self.groups() { + all.extend(self.events_by(&g.id, subkey).unwrap_or_default()); + } + all.into_iter().collect() + } + + /// Applies a revocation Custos signed (docs/TESSERA.md §12) in every active group the key was in, as a + /// member or as the author of an event: [`Core::revoke`] there. A group whose log already holds these + /// statements only gets any leaf of the key that is still there removed, so calling this on every sync + /// is safe. Needs the relay. Returns how many leaves it removed. + pub async fn apply_revocation(&mut self, statements: &[Revocation]) -> Result { + let Some(first) = statements.first() else { return Ok(0) }; + let (root, subkey) = (first.root(), first.subkey()); + if statements.iter().any(|r| r.root() != root || r.subkey() != subkey) { + return Err(ClientError::Invalid("the statements revoke more than one key".into())); + } + let mut removed = 0; + for g in self.groups().into_iter().filter(|g| g.active) { + let gs = &self.saved.groups[self.group_index(&g.id)?]; + if !gs.roots.iter().any(|r| PublicKey::from_text(r) == Some(root)) { + continue; + } + let log = Self::log_of(gs); + let wrote = log.events().iter().any(|e| e.author() == subkey); + let held: std::collections::BTreeSet> = log + .events() + .iter() + .filter_map(|e| parse_payload(e.payload())) + .filter(|(kind, _)| kind == REVOKE_KIND) + .map(|(_, body)| body) + .collect(); + let member = self.members(&g.id)?.iter().any(|m| m.subkey == subkey); + if !member && !wrote { + continue; + } + removed += if statements.iter().all(|r| held.contains(&r.to_bytes())) { + self.remove_revoked(&g.id, Some(&[subkey])).await? + } else { + self.revoke(&g.id, statements.to_vec()).await? + }; + } + Ok(removed) + } + + /// Sends revocation statements into the group as events. Never needs the relay. Every member applies + /// them once complete; a device of the same person removes the revoked leaves on its next sync, and + /// another person's device may. + pub async fn announce_revocation(&mut self, g: &GroupId, statements: Vec) -> Result<()> { + let gs = &self.saved.groups[self.group_index(g)?]; + let roots: Vec = gs.roots.iter().filter_map(|r| PublicKey::from_text(r)).collect(); + for r in &statements { + if !roots.contains(&r.root()) { + return Err(ClientError::Invalid("the revocation's root is not a member of this group".into())); + } + r.verify(&r.root()).map_err(|e| ClientError::Invalid(e.to_string()))?; + } + let events = statements.iter().map(|r| AppEvent { kind: REVOKE_KIND.into(), body: r.to_bytes() }).collect(); + self.send(g, events).await + } + + /// Revokes: announces the statements, uploads them, then removes every leaf whose credential names a + /// revoked subkey and deregisters its mailbox key. Needs the relay. Returns how many leaves it removed. + pub async fn revoke(&mut self, g: &GroupId, statements: Vec) -> Result { + let subkeys: Vec = statements.iter().map(|r| r.subkey()).collect(); + self.announce_revocation(g, statements).await?; + let i = self.group_index(g)?; + let mut report = SyncReport::default(); + self.flush(i, &mut report).await?; + self.save()?; + self.remove_revoked(g, Some(&subkeys)).await + } + + /// Removes the leaves of revoked subkeys (all revoked ones in force, or only `only`). Returns the count. + async fn remove_revoked(&mut self, g: &GroupId, only: Option<&[PublicKey]>) -> Result { + let i = self.group_index(g)?; + let set = Self::revocations_of(&self.saved.groups[i]); + let targets: Vec = self + .members(g)? + .into_iter() + .filter(|m| !m.me && set.is_revoked(&m.subkey) && only.is_none_or(|o| o.contains(&m.subkey))) + .map(|m| m.index) + .collect(); + for idx in &targets { + self.remove(g, *idx).await?; + } + Ok(targets.len()) + } + + /// Takes a renewed cert for this device's subkey (same person, same app) and updates this device's leaf + /// in every group it is in, so new devices accept it. Needs the relay. + pub async fn renew(&mut self, cert: SubkeyCert) -> Result<()> { + if cert.subkey() != self.signer.public() || cert.root() != self.cert.root() || cert.app_id() != &self.app { + return Err(ClientError::Invalid("the new cert is for another key, person or app".into())); + } + cert.verify(&cert.root(), self.now_s()).map_err(|e| ClientError::Invalid(format!("the new cert: {e}")))?; + self.cert = cert; + for i in 0..self.saved.groups.len() { + if !self.saved.groups[i].active { + continue; + } + let gs = self.saved.groups[i].clone(); + let mut group = self.mls_group(&gs)?; + let signer = self.signer(&gs.sig_pub)?; + let mbox = Self::key_of(&gs.mailbox_key)?; + let identity = self.credential(signer.public(), &mbox.public()).await?; + let cwk = CredentialWithKey { + credential: BasicCredential::new(identity).into(), + signature_key: signer.to_public_vec().into(), + }; + let params = LeafNodeParameters::builder().with_credential_with_key(cwk).build(); + let commit = group + .self_update(&self.provider, &signer, params) + .map_err(mls)? + .into_commit() + .to_bytes() + .map_err(mls)?; + self.ensure_mailbox(i).await?; + let mailbox = Self::mailbox_of(&gs)?; + if let Err(e) = self.upload(&mbox, &mailbox, &[b64(&commit)]).await { + let _ = group.clear_pending_commit(self.provider.storage()); + return Err(e.into()); + } + group.merge_pending_commit(&self.provider).map_err(mls)?; + self.saved.groups[i].own.push(sha(&commit)); + } + self.save() + } + + // ---- the root-sealed backup (docs/V1_1.md §3) ---- + + fn backup_mailbox(secret: &BackupSecret) -> (MailboxKey, String) { + let key = MailboxKey::from_seed(&secret.mailbox_seed()); + let id = Sha256::digest([b"tabellarius backup v1".as_slice(), &key.public()].concat()); + (key, b64(&id)) + } + + /// Uploads the self group's log, sealed with the app's backup secret, to its backup mailbox. Does nothing + /// if the log has not changed since the last backup. Needs the relay. Returns whether it uploaded. + pub async fn backup(&mut self, secret: &BackupSecret) -> Result { + let Some(gs) = self.saved.groups.iter().find(|g| g.is_self && g.active).cloned() else { return Ok(false) }; + let log = Self::log_of(&gs); + let mut blob = (log.events().len() as u32).to_be_bytes().to_vec(); + for e in log.events() { + put32(&mut blob, e.as_bytes()); + } + let digest = sha(&blob); + if self.saved.last_backup.as_deref() == Some(digest.as_str()) { + return Ok(false); + } + let (key, mailbox) = Self::backup_mailbox(secret); + match self.call(&key, "PUT", &format!("/v1/mailboxes/{mailbox}"), None).await { + Ok(_) | Err(Net::Refused(409, _)) => {} + Err(e) => return Err(e.into()), + } + let id = random32(); + let chunks: Vec<&[u8]> = blob.chunks(BACKUP_PART).collect(); + let mut messages = Vec::with_capacity(chunks.len()); + for (n, chunk) in chunks.iter().enumerate() { + let mut plain = id[..16].to_vec(); + plain.extend_from_slice(&(n as u16).to_be_bytes()); + plain.extend_from_slice(&(chunks.len() as u16).to_be_bytes()); + plain.extend_from_slice(chunk); + let nonce: [u8; 24] = random32()[..24].try_into().expect("24 bytes"); + messages.push(b64(&secret.seal(&nonce, BACKUP_AAD, &plain))); + } + let mut first = None; + for batch in messages.chunks(8) { + let seqs = self.upload(&key, &mailbox, batch).await?; + first = first.or(seqs.first().copied()); + } + // Everything before this backup has been replaced: acked, the relay drops it after its retention. + if let Some(f) = first.filter(|f| *f > 1) { + let _ = + self.call(&key, "POST", &format!("/v1/mailboxes/{mailbox}/ack"), Some(json!({ "seq": f - 1 }))).await; + } + self.saved.last_backup = Some(digest); + self.save()?; + Ok(true) + } + + /// The envelopes of the latest complete backup in the app's backup mailbox (none if there is none). Needs + /// the relay. Feed them to [`Core::import`] in a new self group. + pub async fn restore(&self, secret: &BackupSecret) -> Result>> { + let (key, mailbox) = Self::backup_mailbox(secret); + let mut parts: std::collections::BTreeMap, BackupParts> = Default::default(); + let mut after = 0; + loop { + let (msgs, more) = match self.fetch(&key, &mailbox, after).await { + Ok(x) => x, + Err(Net::Refused(403 | 404, _)) => return Ok(Vec::new()), + Err(e) => return Err(e.into()), + }; + for (seq, data) in msgs { + after = seq; + let Some(plain) = secret.open(BACKUP_AAD, &data) else { continue }; + if plain.len() < 20 { + continue; + } + let (id, n, total) = ( + plain[..16].to_vec(), + u16::from_be_bytes([plain[16], plain[17]]), + u16::from_be_bytes([plain[18], plain[19]]), + ); + let e = parts.entry(id).or_insert((seq, total, Default::default())); + e.0 = e.0.max(seq); + e.2.insert(n, plain[20..].to_vec()); + } + if !more { + break; + } + } + let latest = + parts.into_values().filter(|(_, total, got)| got.len() == *total as usize).max_by_key(|(seq, _, _)| *seq); + let Some((_, _, got)) = latest else { return Ok(Vec::new()) }; + let blob: Vec = got.into_values().flatten().collect(); + let mut r = Reader(&blob); + let n = r.u32().ok_or(ClientError::State("a backup that does not parse".into()))?; + let mut out = Vec::with_capacity(n); + for _ in 0..n { + out.push(r.var32().ok_or(ClientError::State("a backup that does not parse".into()))?.to_vec()); + } + Ok(out) + } + + /// Brings history into a group: each envelope verified against the group's roots (at its own time), merged + /// into the log and sent to the group's other devices. Returns how many were new. + pub fn import(&mut self, g: &GroupId, envelopes: Vec>) -> Result { + let i = self.group_index(g)?; + let gs = self.saved.groups[i].clone(); + let roots: Vec = gs.roots.iter().filter_map(|r| PublicKey::from_text(r)).collect(); + let now = (self.now_ms)(); + let decoded: Vec = envelopes.iter().filter_map(|b| Envelope::decode(b).ok()).collect(); + let merged = tessera::merge(&Self::log_of(&gs), decoded, |e| e.verify(&roots, now, MAX_DRIFT_MS)); + if !merged.rejected.is_empty() { + return Err(ClientError::Invalid(format!( + "{} event(s) in the history do not verify", + merged.rejected.len() + ))); + } + for e in merged.log.events() { + let _ = self.clock.observe(e.hlc(), now); + } + Self::store_log(&mut self.saved.groups[i], &merged.log); + let raw: Vec> = merged.log.events().iter().map(|e| e.as_bytes().to_vec()).collect(); + self.queue(i, &raw)?; + self.save()?; + Ok(merged.added) + } + + // ---- live subscribe (docs/V1_1B.md §3; the driver owns the socket) ---- + + /// The first message for a live socket (`/v1/live`): a subscription for each of `groups` this device is + /// still in, from its cursor, signed with the group's mailbox key. At most [`LIVE_MAX_SUBS`] groups. + pub fn live_subscribe(&self, groups: &[GroupId]) -> Result { + if groups.len() > LIVE_MAX_SUBS { + return Err(ClientError::Invalid(format!("at most {LIVE_MAX_SUBS} groups per live socket"))); + } + let mut subs = Vec::with_capacity(groups.len()); + for g in groups { + let gs = &self.saved.groups[self.group_index(g)?]; + if !gs.active { + continue; + } + let mailbox = Self::mailbox_of(gs)?; + let h = Self::key_of(&gs.mailbox_key)?.sign_request( + LIVE_METHOD, + &live_path(&mailbox, gs.cursor), + b"", + self.now_s(), + ); + subs.push(json!({ + "mailbox": mailbox, "after": gs.cursor, "key": h.key, "time": h.time, "nonce": h.nonce, "sig": h.sig, + })); + } + Ok(json!({ "subscribe": subs }).to_string()) + } + + /// What a message from a live socket means for this device. `None`: not about any of its groups. + pub fn live_notice(&self, text: &str) -> Option { + let v: Value = serde_json::from_str(text).ok()?; + if v["pong"] == true { + return Some(LiveNotice::Pong); + } + let mailbox = v["mailbox"].as_str()?; + let gs = self.saved.groups.iter().find(|g| Self::mailbox_of(g).is_ok_and(|m| m == mailbox))?; + let g = GroupId(gs.id.clone()); + Some(match v["error"].as_str() { + Some(e) => LiveNotice::Ended(g, e.to_owned()), + None => LiveNotice::Mail(g), + }) + } + + // ---- sync ---- + + async fn flush(&mut self, i: usize, report: &mut SyncReport) -> std::result::Result<(), Net> { + self.ensure_mailbox(i).await?; + let gs = &self.saved.groups[i]; + if gs.outbox.is_empty() || !gs.active { + return Ok(()); + } + let (Ok(mailbox), Ok(key)) = (Self::mailbox_of(gs), Self::key_of(&gs.mailbox_key)) else { return Ok(()) }; + let out = gs.outbox.clone(); + self.upload(&key, &mailbox, &out).await?; + report.sent += out.len(); + self.saved.groups[i].outbox.clear(); + Ok(()) + } + + async fn pull_group(&mut self, i: usize, report: &mut SyncReport) -> std::result::Result<(), Net> { + if !self.saved.groups[i].active { + return Ok(()); + } + let gs = self.saved.groups[i].clone(); + let (Ok(mailbox), Ok(key)) = (Self::mailbox_of(&gs), Self::key_of(&gs.mailbox_key)) else { return Ok(()) }; + let start = gs.cursor; + loop { + let cursor = self.saved.groups[i].cursor; + let (msgs, more) = match self.fetch(&key, &mailbox, cursor).await { + Ok(x) => x, + Err(Net::Refused(403, e)) => { + report + .rejected + .push(format!("{}: the relay no longer admits this device ({e}): it was removed", gs.name)); + return Ok(()); + } + Err(e) => return Err(e), + }; + for (seq, data) in msgs { + self.saved.groups[i].cursor = seq; + if self.saved.groups[i].own.contains(&sha(&data)) { + continue; + } + match self.process_group_message(i, &data, report) { + Ok(n) => report.received += n, + Err(why) => report.rejected.push(why), + } + } + if !more { + break; + } + } + let cursor = self.saved.groups[i].cursor; + if cursor > start { + let _ = + self.call(&key, "POST", &format!("/v1/mailboxes/{mailbox}/ack"), Some(json!({ "seq": cursor }))).await; + } + Ok(()) + } + + async fn sync_inner(&mut self, report: &mut SyncReport) -> std::result::Result<(), Net> { + for i in 0..self.saved.groups.len() { + self.flush(i, report).await?; + self.pull_group(i, report).await?; + } + self.finish_joins(report).await?; + self.serve_invites(report).await?; + for i in 0..self.saved.groups.len() { + self.flush(i, report).await?; + self.pull_group(i, report).await?; + } + Ok(()) + } + + /// Uploads what is queued, downloads and verifies what is new, admits invited devices, picks up groups this + /// device was admitted to. An unreachable relay is `relay_ok: false`, not an error. + pub async fn sync(&mut self) -> Result { + let mut report = SyncReport { relay_ok: true, ..SyncReport::default() }; + match self.sync_inner(&mut report).await { + Ok(()) => {} + Err(Net::Down(_)) => report.relay_ok = false, + Err(Net::Refused(s, e)) => report.rejected.push(format!("the relay refused a request ({s} {e})")), + } + if report.relay_ok { + let mine = self.cert.root(); + let groups: Vec = + self.saved.groups.iter().filter(|g| g.active).map(|g| GroupId(g.id.clone())).collect(); + for g in groups { + let own: Vec = + self.members(&g)?.into_iter().filter(|m| m.root == mine).map(|m| m.subkey).collect(); + if let Err(e) = self.remove_revoked(&g, Some(&own)).await { + report.rejected.push(format!("a revoked device could not be removed yet: {e}")); + } + } + } + self.save()?; + Ok(report) + } + + /// `sync`, then the group's log. + pub async fn pull(&mut self, g: &GroupId) -> Result> { + self.sync().await?; + self.log(g) + } +} diff --git a/crates/client/src/native.rs b/crates/client/src/native.rs new file mode 100644 index 0000000..71980a0 --- /dev/null +++ b/crates/client/src/native.rs @@ -0,0 +1,161 @@ +//! The native driver (docs/V1_1B.md §1): [`Client`] is the [`Core`] over `ureq` and the app's [`Subkey`], +//! with the blocking API apps have used since v0.2. Neither the transport nor the signer ever waits, so each +//! operation completes the first time its future is polled: no executor, no thread. + +use crate::{ + AppEvent, Core, Device, GroupId, HttpRequest, HttpResponse, Result, StateStore, SyncReport, Transport, + VerifiedEvent, +}; +use std::future::Future; +use std::ops::{Deref, DerefMut}; +use std::sync::Arc; +use std::task::{Context, Poll, Waker}; +use std::time::Duration; +use tessera::{BackupSecret, Revocation, Subkey, SubkeyCert}; + +/// The blocking HTTP transport: no redirects, 15 s for a whole request. +pub struct Ureq(ureq::Agent); + +impl Default for Ureq { + fn default() -> Self { + Ureq( + ureq::Agent::config_builder() + .max_redirects(0) + .http_status_as_error(false) + .timeout_global(Some(Duration::from_secs(15))) + .build() + .into(), + ) + } +} + +impl Transport for Ureq { + async fn send(&self, req: HttpRequest) -> std::result::Result { + fn with(mut r: ureq::RequestBuilder, headers: &[(&'static str, String)]) -> ureq::RequestBuilder { + for (n, v) in headers { + r = r.header(*n, v); + } + r + } + let resp = match req.method.as_str() { + "GET" => with(self.0.get(&req.url), &req.headers).call(), + "DELETE" => with(self.0.delete(&req.url), &req.headers).call(), + "PUT" => with(self.0.put(&req.url), &req.headers).send(&req.body[..]), + _ => with(self.0.post(&req.url), &req.headers).send(&req.body[..]), + }; + let mut resp = resp.map_err(|e| e.to_string())?; + let status = resp.status().as_u16(); + let body = resp.body_mut().read_to_vec().unwrap_or_default(); + Ok(HttpResponse { status, body }) + } +} + +/// Runs a core operation over the native transport and signer: it is ready on the first poll. +fn now(f: F) -> F::Output { + let mut f = std::pin::pin!(f); + match f.as_mut().poll(&mut Context::from_waker(Waker::noop())) { + Poll::Ready(v) => v, + // Unreachable: `Ureq` and `Subkey` never return Pending, and the core awaits nothing else. + Poll::Pending => unreachable!("a native operation waited"), + } +} + +fn system_ms() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0) +} + +/// The native client. Every operation that does not talk to the relay or sign (`groups`, `log`, `members`, +/// `import`, …) is the [`Core`]'s, reached through `Deref`. +pub struct Client(Core); + +impl Deref for Client { + type Target = Core; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for Client { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl Client { + /// Opens the client for `device`'s app, with its state from `store` (or empty). + pub fn open(relay: &str, device: Device, store: Box) -> Result { + Core::open(relay, device.cert, device.subkey, Ureq::default(), store, Arc::new(system_ms)).map(Client) + } + + /// The group of this person's own devices for this app; created on first use. + pub fn self_group(&mut self) -> Result { + now(self.0.self_group()) + } + + /// A new group shared with people you will invite. + pub fn open_group(&mut self, name: &str) -> Result { + now(self.0.open_group(name)) + } + + /// Signs `events`, applies them to the local log at once, and queues them for the group. Never needs the + /// relay. + pub fn send(&mut self, g: &GroupId, events: Vec) -> Result<()> { + now(self.0.send(g, events)) + } + + /// An invite token (`tab1:…`). Needs the relay. See [`Core::invite`]. + pub fn invite(&mut self, g: &GroupId) -> Result { + now(self.0.invite(g)) + } + + /// Asks to join with an invite token. Needs the relay. See [`Core::join`]. + pub fn join(&mut self, token: &str) -> Result<()> { + now(self.0.join(token)) + } + + /// Removes a member. Needs the relay. + pub fn remove(&mut self, g: &GroupId, member: u32) -> Result<()> { + now(self.0.remove(g, member)) + } + + /// See [`Core::apply_revocation`]. + pub fn apply_revocation(&mut self, statements: &[Revocation]) -> Result { + now(self.0.apply_revocation(statements)) + } + + /// See [`Core::announce_revocation`]. + pub fn announce_revocation(&mut self, g: &GroupId, statements: Vec) -> Result<()> { + now(self.0.announce_revocation(g, statements)) + } + + /// See [`Core::revoke`]. + pub fn revoke(&mut self, g: &GroupId, statements: Vec) -> Result { + now(self.0.revoke(g, statements)) + } + + /// See [`Core::renew`]. + pub fn renew(&mut self, cert: SubkeyCert) -> Result<()> { + now(self.0.renew(cert)) + } + + /// See [`Core::backup`]. + pub fn backup(&mut self, secret: &BackupSecret) -> Result { + now(self.0.backup(secret)) + } + + /// See [`Core::restore`]. + pub fn restore(&self, secret: &BackupSecret) -> Result>> { + now(self.0.restore(secret)) + } + + /// Uploads what is queued, downloads and verifies what is new, admits invited devices, picks up groups this + /// device was admitted to. An unreachable relay is `relay_ok: false`, not an error. + pub fn sync(&mut self) -> Result { + now(self.0.sync()) + } + + /// `sync`, then the group's log. + pub fn pull(&mut self, g: &GroupId) -> Result> { + now(self.0.pull(g)) + } +} diff --git a/crates/client/src/store.rs b/crates/client/src/store.rs new file mode 100644 index 0000000..c3e7baf --- /dev/null +++ b/crates/client/src/store.rs @@ -0,0 +1,117 @@ +//! Where the client keeps its state (docs/TABELLARIUS.md §5). The state holds MLS secrets, so on disk it is +//! always encrypted, with a key the app keeps in Custos. + +#[cfg(not(target_arch = "wasm32"))] +use chacha20poly1305::aead::{Aead, KeyInit, Payload}; +#[cfg(not(target_arch = "wasm32"))] +use chacha20poly1305::{XChaCha20Poly1305, XNonce}; +use std::io; +#[cfg(not(target_arch = "wasm32"))] +use std::path::PathBuf; +use std::sync::Mutex; +use zeroize::Zeroizing; + +/// `Send`, so a [`crate::Client`] can live in a server task or a Tauri app's state. +pub trait StateStore: Send { + fn load(&self) -> io::Result>>; + fn save(&self, state: &[u8]) -> io::Result<()>; +} + +/// State in memory only: tests, and apps that persist it themselves. +#[derive(Default)] +pub struct MemoryStore(Mutex>>>); + +impl MemoryStore { + pub fn with(state: Vec) -> MemoryStore { + MemoryStore(Mutex::new(Some(Zeroizing::new(state)))) + } +} + +impl StateStore for MemoryStore { + fn load(&self) -> io::Result>> { + Ok(self.0.lock().map_err(|_| io::Error::other("lock"))?.as_ref().map(|s| s.to_vec())) + } + + fn save(&self, state: &[u8]) -> io::Result<()> { + *self.0.lock().map_err(|_| io::Error::other("lock"))? = Some(Zeroizing::new(state.to_vec())); + Ok(()) + } +} + +#[cfg(not(target_arch = "wasm32"))] +const MAGIC: &[u8; 4] = b"TSF1"; + +#[cfg(not(target_arch = "wasm32"))] +/// State in a file: `TSF1 ‖ nonce (24) ‖ XChaCha20-Poly1305(key, nonce, state, aad = TSF1)`, written to a temporary +/// file and renamed. The key comes from Custos (`domi:///tabellarius-state`), never from a file. +pub struct EncryptedFileStore { + path: PathBuf, + key: Zeroizing<[u8; 32]>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl EncryptedFileStore { + pub fn new(path: impl Into, key: [u8; 32]) -> EncryptedFileStore { + EncryptedFileStore { path: path.into(), key: Zeroizing::new(key) } + } + + fn cipher(&self) -> XChaCha20Poly1305 { + XChaCha20Poly1305::new_from_slice(self.key.as_ref()).expect("32-byte key") + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl StateStore for EncryptedFileStore { + fn load(&self) -> io::Result>> { + let bytes = match std::fs::read(&self.path) { + Ok(b) => b, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e), + }; + if bytes.len() < 4 + 24 || &bytes[..4] != MAGIC { + return Err(io::Error::other("not a Tabellarius state file")); + } + let nonce = XNonce::from_slice(&bytes[4..28]); + let plain = self + .cipher() + .decrypt(nonce, Payload { msg: &bytes[28..], aad: MAGIC }) + .map_err(|_| io::Error::other("the state file does not open with this key (wrong key or damaged)"))?; + Ok(Some(plain)) + } + + fn save(&self, state: &[u8]) -> io::Result<()> { + let nonce_bytes = tabellarius_proto::random32(); + let nonce = XNonce::from_slice(&nonce_bytes[..24]); + let ct = self + .cipher() + .encrypt(nonce, Payload { msg: state, aad: MAGIC }) + .map_err(|_| io::Error::other("encryption"))?; + let mut out = MAGIC.to_vec(); + out.extend_from_slice(&nonce_bytes[..24]); + out.extend_from_slice(&ct); + let tmp = self.path.with_extension("tmp"); + std::fs::write(&tmp, &out)?; + std::fs::rename(&tmp, &self.path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_file_is_ciphertext_and_opens_only_with_its_key() { + let dir = + std::env::temp_dir().join(format!("tsf-{}", tabellarius_proto::b64(&tabellarius_proto::random32()[..6]))); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("state.tsf"); + let s = EncryptedFileStore::new(&path, [7; 32]); + assert_eq!(s.load().unwrap(), None); + s.save(b"MARKER-SECRET-STATE").unwrap(); + let raw = std::fs::read(&path).unwrap(); + assert!(!raw.windows(6).any(|w| w == b"MARKER")); + assert_eq!(s.load().unwrap().unwrap(), b"MARKER-SECRET-STATE"); + assert!(EncryptedFileStore::new(&path, [8; 32]).load().is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/client/src/transport.rs b/crates/client/src/transport.rs new file mode 100644 index 0000000..21b11cb --- /dev/null +++ b/crates/client/src/transport.rs @@ -0,0 +1,51 @@ +//! What the core needs from its surroundings (docs/V1_1B.md §1, §2): a way to reach the relay and the device +//! key. The native driver implements both without ever waiting; the browser's wait on `fetch` and WebCrypto. + +use std::future::Future; +use tessera::{PublicKey, Signature, Subkey}; + +/// One HTTP request to the relay, already signed with a mailbox key. +#[derive(Clone, Debug)] +pub struct HttpRequest { + pub method: String, + pub url: String, + pub headers: Vec<(&'static str, String)>, + pub body: Vec, +} + +/// The relay's answer: any status, and the body. +#[derive(Clone, Debug)] +pub struct HttpResponse { + pub status: u16, + pub body: Vec, +} + +/// Reaches the relay. `Err` only when it could not be reached (offline); every HTTP status is an `Ok` answer. +/// No redirects are followed. +pub trait Transport { + fn send(&self, req: HttpRequest) -> impl Future>; +} + +/// The device key: the app subkey its cert certifies. The domains are prepended here, never by the caller, +/// so a signer cannot be asked to sign one kind of statement as another. +pub trait DeviceSigner { + fn public(&self) -> PublicKey; + /// A signature over `tessera::EVENT_DOMAIN ‖ tbs`. + fn sign_event_tbs(&self, tbs: &[u8]) -> impl Future>; + /// A signature over `tessera::CREDENTIAL_DOMAIN ‖ tbs`. + fn sign_credential_tbs(&self, tbs: &[u8]) -> impl Future>; +} + +impl DeviceSigner for Subkey { + fn public(&self) -> PublicKey { + Subkey::public(self) + } + + async fn sign_event_tbs(&self, tbs: &[u8]) -> Result { + Ok(Subkey::sign_event_tbs(self, tbs)) + } + + async fn sign_credential_tbs(&self, tbs: &[u8]) -> Result { + Ok(Subkey::sign_credential_tbs(self, tbs)) + } +} diff --git a/crates/custos-local/Cargo.toml b/crates/custos-local/Cargo.toml new file mode 100644 index 0000000..0f5e9b8 --- /dev/null +++ b/crates/custos-local/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "custos-local" +description = "The app side of Custos' local API on Windows: keep a subkey seed in Custos and ask Custos to certify the subkey (docs/TESSERA.md §10)" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[lints] +workspace = true + +[dependencies] +tessera = { path = "../tessera" } +serde_json = "1" +getrandom = "0.3" +sha2.workspace = true +data-encoding.workspace = true +zeroize.workspace = true +thiserror.workspace = true diff --git a/crates/custos-local/examples/request_subkey.rs b/crates/custos-local/examples/request_subkey.rs new file mode 100644 index 0000000..4f276d6 --- /dev/null +++ b/crates/custos-local/examples/request_subkey.rs @@ -0,0 +1,29 @@ +//! Asks the running Custos for a subkey cert, as a Domi app would. +//! +//! `cargo run -p custos-local --example request_subkey -- [purpose] [app name]` + +use tessera::{Id, match_code}; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let app_id = Id::new(args.first().map(String::as_str).unwrap_or("demo")).expect("an app id: a-z, 0-9, '-'"); + let purpose = Id::new(args.get(1).map(String::as_str).unwrap_or("sync")).expect("a purpose: a-z, 0-9, '-'"); + let app = args.get(2).cloned().unwrap_or_else(|| format!("{app_id} (request_subkey example)")); + + let run = || -> Result<(), custos_local::LocalError> { + let mut custos = custos_local::Custos::connect()?; + let subkey = custos.subkey(&app, &app_id)?; + println!("subkey {}", subkey.public()); + println!("match {} <- Custos shows the same code", match_code(&subkey.public())); + let cert = custos.request_cert(&app, &app_id, &purpose, &subkey)?; + println!("root {}", cert.root()); + println!("app {} / {}", cert.app_id(), cert.purpose()); + println!("valid {} .. {} (Unix seconds)", cert.not_before(), cert.not_after()); + println!("cert {}", cert.to_text()); + Ok(()) + }; + if let Err(e) = run() { + eprintln!("error: {e}"); + std::process::exit(1); + } +} diff --git a/crates/custos-local/src/lib.rs b/crates/custos-local/src/lib.rs new file mode 100644 index 0000000..606d729 --- /dev/null +++ b/crates/custos-local/src/lib.rs @@ -0,0 +1,319 @@ +//! The app side of Custos' local API (docs/TESSERA.md §10): a Domi app on the same Windows machine keeps its +//! subkey seed in Custos and asks Custos to certify the subkey with the person's root. +//! +//! ```no_run +//! # use tessera::Id; +//! let mut custos = custos_local::Custos::connect().unwrap(); +//! let app_id = Id::new("fiscus").unwrap(); +//! let subkey = custos.subkey("Fiscus Domi", &app_id).unwrap(); +//! println!("Custos will show {}", tessera::match_code(&subkey.public())); +//! let cert = custos.request_cert("Fiscus Domi", &app_id, &Id::new("sync").unwrap(), &subkey).unwrap(); +//! ``` +//! +//! The seed lives in Custos under `domi:///tessera-subkey`; the root never leaves Custos, and no +//! answer contains private key material other than the app's own secrets, in its own namespace: the subkey +//! seed, the state keys and the backup secret. +//! +//! v1.1 (docs/TESSERA.md §12): on every sync an app applies the revocations the person started in Custos and +//! backs up its self group: +//! +//! ```ignore +//! for statements in custos.revocations_to_apply("Fiscus Domi", &app_id, |k| client.events_by_all(k))? { +//! client.apply_revocation(&statements)?; +//! } +//! client.backup(&custos.backup_secret("Fiscus Domi", &app_id)?)?; +//! ``` + +use data_encoding::BASE64URL_NOPAD; +use serde_json::{Value, json}; +use sha2::Digest; +use std::io::{Read, Write}; +use tessera::{BackupSecret, Id, PublicKey, Revocation, Subkey, SubkeyCert}; +use zeroize::Zeroizing; + +/// The pipe Custos listens on; `CUSTOS_PIPE` overrides it (tests, a second Custos). +pub const PIPE: &str = r"\\.\pipe\custos-domi"; +const SEED_NAME: &str = "tessera-subkey"; + +#[derive(Debug, thiserror::Error)] +pub enum LocalError { + #[error("Custos is not running (or this is not Windows): {0}")] + NotRunning(std::io::Error), + #[error("talking to Custos failed: {0}")] + Io(std::io::Error), + #[error("Custos refused: {error} ({message})")] + Refused { error: String, message: String }, + #[error("Custos sent an answer this app does not understand")] + BadAnswer, + #[error("the certificate Custos sent does not match the request: {0}")] + WrongCert(&'static str), + #[error("no random numbers from the OS")] + Random, + #[error("the revocation Custos sent does not match the request")] + WrongRevocation, +} + +/// A revocation the person started in Custos (Domi identity → a key → Revoke). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PendingRevocation { + pub subkey: PublicKey, + /// Unix seconds, as Custos chose it. + pub revoked_at: u64, + /// `None` until a device of this app sent the list of events to keep. + pub statements: Option>, +} + +/// A connection to Custos. +pub struct Custos { + pipe: std::fs::File, +} + +impl Custos { + pub fn connect() -> Result { + let name = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_owned()); + let pipe = std::fs::OpenOptions::new().read(true).write(true).open(name).map_err(LocalError::NotRunning)?; + Ok(Custos { pipe }) + } + + /// One request, one answer. Answers with `"ok": false` become [`LocalError::Refused`]. + fn call(&mut self, req: &Value) -> Result { + let out = Zeroizing::new(serde_json::to_vec(req).map_err(|_| LocalError::BadAnswer)?); + self.pipe.write_all(&out).map_err(LocalError::Io)?; + let mut buf = Zeroizing::new(Vec::new()); + let mut chunk = Zeroizing::new(vec![0u8; 64 * 1024]); + let v: Value = loop { + let n = self.pipe.read(&mut chunk).map_err(LocalError::Io)?; + if n == 0 { + return Err(LocalError::BadAnswer); + } + buf.extend_from_slice(&chunk[..n]); + match serde_json::from_slice(&buf) { + Ok(v) => break v, + Err(e) if e.is_eof() => continue, + Err(_) => return Err(LocalError::BadAnswer), + } + }; + if v["ok"] == true { + return Ok(v); + } + Err(LocalError::Refused { + error: v["error"].as_str().unwrap_or("unknown").to_owned(), + message: v["message"].as_str().unwrap_or("").to_owned(), + }) + } + + /// This app's subkey: the seed kept in Custos, or a new one from the OS CSPRNG stored there first. + /// Custos asks the person once whether `app` may use the namespace `app_id`. + pub fn subkey(&mut self, app: &str, app_id: &Id) -> Result { + let seed = self.random_secret(app, &format!("domi://{app_id}/{SEED_NAME}"), "Domi subkey")?; + Ok(Subkey::from_seed(&seed)) + } + + /// The key that encrypts this app's Tabellarius state file at `state_path` (one per file), kept in Custos. + pub fn state_key(&mut self, app: &str, app_id: &Id, state_path: &str) -> Result, LocalError> { + let id: String = + sha2::Sha256::digest(state_path.as_bytes()).iter().take(6).map(|b| format!("{b:02x}")).collect(); + self.random_secret(app, &format!("domi://{app_id}/tabellarius-state-{id}"), "Tabellarius state key") + } + + /// 32 bytes kept in Custos under `r`: read, or made from the OS CSPRNG and stored first. + fn random_secret(&mut self, app: &str, r: &str, what: &str) -> Result, LocalError> { + match self.call(&json!({ "op": "get", "ref": r, "app": app })) { + Ok(v) => { + let text = Zeroizing::new(v["value"].as_str().ok_or(LocalError::BadAnswer)?.to_owned()); + let seed = Zeroizing::new(BASE64URL_NOPAD.decode(text.as_bytes()).map_err(|_| LocalError::BadAnswer)?); + Ok(Zeroizing::new(seed.as_slice().try_into().map_err(|_| LocalError::BadAnswer)?)) + } + Err(LocalError::Refused { error, .. }) if error == "not_found" => { + let mut seed = Zeroizing::new([0u8; 32]); + getrandom::fill(seed.as_mut()).map_err(|_| LocalError::Random)?; + let text = Zeroizing::new(BASE64URL_NOPAD.encode(seed.as_ref())); + let label = format!("{app}: {what}"); + self.call(&json!({ "op": "set", "ref": r, "value": text.as_str(), "label": label, "app": app }))?; + Ok(seed) + } + Err(e) => Err(e), + } + } + + /// Asks Custos to certify `subkey` for `app_id` and `purpose`. Custos shows the subkey's match code + /// (`tessera::match_code`); show the same code in the app while this waits. Blocks until the person + /// answers. The cert is checked before it is returned. + pub fn request_cert( + &mut self, + app: &str, + app_id: &Id, + purpose: &Id, + subkey: &Subkey, + ) -> Result { + self.request_cert_for(app, app_id, purpose, &subkey.public()) + } + + /// [`Custos::request_cert`] for a key this app does not hold: another device of the same person (an app's + /// server-side device, paired through this desktop). Custos shows the key's match code; the other device + /// shows the same code, so the person approves only the key they see there. + pub fn request_cert_for( + &mut self, + app: &str, + app_id: &Id, + purpose: &Id, + key: &PublicKey, + ) -> Result { + let v = self.call(&json!({ + "op": "subkey", + "app": app, + "app_id": app_id.as_str(), + "purpose": purpose.as_str(), + "subkey": key.to_string(), + }))?; + let cert = SubkeyCert::from_text(v["cert"].as_str().ok_or(LocalError::BadAnswer)?) + .map_err(|_| LocalError::BadAnswer)?; + check(&cert, app_id, purpose, key, now())?; + Ok(cert) + } +} + +impl Custos { + /// The revocations the person started for this app's subkeys and for device keys. + pub fn revocations(&mut self, app: &str, app_id: &Id) -> Result, LocalError> { + let v = self.call(&json!({ "op": "revocations", "app": app, "app_id": app_id.as_str() }))?; + let list = v["revocations"].as_array().ok_or(LocalError::BadAnswer)?; + list.iter() + .map(|r| { + let subkey = r["subkey"].as_str().and_then(PublicKey::from_text).ok_or(LocalError::BadAnswer)?; + let revoked_at = r["revoked_at"].as_u64().ok_or(LocalError::BadAnswer)?; + let statements = match &r["statements"] { + Value::Null => None, + s => Some(statements(s, &subkey, revoked_at)?), + }; + Ok(PendingRevocation { subkey, revoked_at, statements }) + }) + .collect() + } + + /// Sends the hashes of the events `pending`'s key wrote that stay valid (`Client::events_by_all`); Custos + /// signs the revocation with the root. If another device of this app answered first, Custos returns + /// what it signed then. + pub fn revoke( + &mut self, + app: &str, + app_id: &Id, + pending: &PendingRevocation, + accepted: &[[u8; 32]], + ) -> Result, LocalError> { + let v = self.call(&json!({ + "op": "revoke", + "app": app, + "app_id": app_id.as_str(), + "subkey": pending.subkey.to_string(), + "revoked_at": pending.revoked_at, + "accepted": BASE64URL_NOPAD.encode(&accepted.concat()), + }))?; + statements(&v["statements"], &pending.subkey, pending.revoked_at) + } + + /// Every revocation this app has to apply, signed: answers the ones still waiting with `accepted_of` + /// (`|k| client.events_by_all(k)`). Hand each to `Client::apply_revocation`. + pub fn revocations_to_apply( + &mut self, + app: &str, + app_id: &Id, + accepted_of: impl Fn(&PublicKey) -> Vec<[u8; 32]>, + ) -> Result>, LocalError> { + let mut out = Vec::new(); + for p in self.revocations(app, app_id)? { + out.push(match &p.statements { + Some(s) => s.clone(), + None => self.revoke(app, app_id, &p, &accepted_of(&p.subkey))?, + }); + } + Ok(out) + } + + /// This app's backup secret (docs/TESSERA.md §12), derived by Custos from the root. Nothing reads it back + /// out of [`BackupSecret`]. + pub fn backup_secret(&mut self, app: &str, app_id: &Id) -> Result { + let v = self.call(&json!({ "op": "backup_key", "app": app, "app_id": app_id.as_str() }))?; + let text = Zeroizing::new(v["secret"].as_str().ok_or(LocalError::BadAnswer)?.to_owned()); + let bytes = Zeroizing::new(BASE64URL_NOPAD.decode(text.as_bytes()).map_err(|_| LocalError::BadAnswer)?); + let secret: [u8; 32] = bytes.as_slice().try_into().map_err(|_| LocalError::BadAnswer)?; + Ok(BackupSecret::from_bytes(secret)) + } +} + +/// Signed statements from an answer: one root, the asked-for key and time, each signature valid. +fn statements(v: &Value, subkey: &PublicKey, revoked_at: u64) -> Result, LocalError> { + let list: Vec = v + .as_array() + .ok_or(LocalError::BadAnswer)? + .iter() + .map(|t| t.as_str().and_then(|t| Revocation::from_text(t).ok()).ok_or(LocalError::BadAnswer)) + .collect::>()?; + let root = list.first().ok_or(LocalError::WrongRevocation)?.root(); + let ok = list + .iter() + .all(|r| r.root() == root && r.subkey() == *subkey && r.revoked_at() == revoked_at && r.verify(&root).is_ok()); + if !ok { + return Err(LocalError::WrongRevocation); + } + Ok(list) +} + +fn now() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} + +/// Whether `cert` is what was asked for, and valid now under the root it names. +fn check(cert: &SubkeyCert, app_id: &Id, purpose: &Id, key: &PublicKey, now: u64) -> Result<(), LocalError> { + if cert.subkey() != *key { + return Err(LocalError::WrongCert("another subkey")); + } + if cert.app_id() != app_id || cert.purpose() != purpose { + return Err(LocalError::WrongCert("another app id or purpose")); + } + cert.verify(&cert.root(), now).map_err(|_| LocalError::WrongCert("not valid now")) +} + +#[cfg(test)] +mod tests { + use super::*; + use tessera::{CertRequest, RootKey, certify}; + + #[test] + fn a_cert_is_checked_against_the_request() { + let root = RootKey::from_mnemonic( + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \ + abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art", + ) + .unwrap(); + let sub = Subkey::from_seed(&[1; 32]); + let (fiscus, sync) = (Id::new("fiscus").unwrap(), Id::new("sync").unwrap()); + let cert = certify(&root, &CertRequest::standard(sub.public(), fiscus.clone(), sync.clone(), 1000)).unwrap(); + let key = sub.public(); + assert!(check(&cert, &fiscus, &sync, &key, 1000).is_ok()); + assert!(check(&cert, &Id::new("calenda").unwrap(), &sync, &key, 1000).is_err()); + assert!(check(&cert, &fiscus, &sync, &Subkey::from_seed(&[2; 32]).public(), 1000).is_err()); + assert!(check(&cert, &fiscus, &sync, &key, 1000 + 366 * 86_400).is_err()); + } + + #[test] + fn statements_are_checked_against_the_request() { + let root = RootKey::from_mnemonic( + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art", + ) + .unwrap(); + let lost = Subkey::from_seed(&[1; 32]).public(); + let signed = tessera::revoke(&root, lost, 1000, vec![[7; 32]]).unwrap(); + let answer = json!(signed.iter().map(|r| r.to_text()).collect::>()); + assert_eq!(statements(&answer, &lost, 1000).unwrap(), signed); + assert!(matches!(statements(&answer, &lost, 999), Err(LocalError::WrongRevocation))); + let other = Subkey::from_seed(&[2; 32]).public(); + assert!(matches!(statements(&answer, &other, 1000), Err(LocalError::WrongRevocation))); + assert!(matches!(statements(&json!([]), &lost, 1000), Err(LocalError::WrongRevocation))); + let mut forged = signed[0].to_bytes(); + let n = forged.len(); + forged[n - 1] ^= 1; + let forged = json!([data_encoding::BASE64URL_NOPAD.encode(&forged)]); + assert!(matches!(statements(&forged, &lost, 1000), Err(LocalError::WrongRevocation))); + } +} diff --git a/crates/envelope/Cargo.toml b/crates/envelope/Cargo.toml new file mode 100644 index 0000000..c08b43a --- /dev/null +++ b/crates/envelope/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "envelope" +description = "The signed Domi event envelope (TEV1): strict decoding, verification against trusted roots (docs/TESSERA.md §8)" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[lints] +workspace = true + +[dependencies] +tessera = { path = "../tessera" } +thiserror.workspace = true + +[dev-dependencies] +proptest = "1" diff --git a/crates/envelope/src/lib.rs b/crates/envelope/src/lib.rs new file mode 100644 index 0000000..b2dd456 --- /dev/null +++ b/crates/envelope/src/lib.rs @@ -0,0 +1,296 @@ +//! The Domi event envelope, `TEV1` (docs/TESSERA.md §8). +//! +//! Decoding is strict and total: it returns a whole [`Envelope`] or a [`DecodeError`] that says why, never +//! a panic and never part of an event. Encoding is canonical, so `decode(b).as_bytes() == b`. A decoded +//! envelope is not trusted until [`Envelope::verify`] passes. + +use std::fmt; +use tessera::{CertError, Hlc, Id, LogEvent, OrderKey, PublicKey, Signature, Subkey, SubkeyCert, verify_event_sig}; + +pub const MAGIC: &[u8; 4] = b"TEV1"; +/// The largest payload (MLS ciphertext) one event may carry. +pub const MAX_PAYLOAD: usize = 256 * 1024; +/// The largest envelope: the payload plus room for every other field. +pub const MAX_ENVELOPE: usize = MAX_PAYLOAD + 1024; + +const CERT_MIN: usize = 4 + 32 + 32 + 2 + 2 + 8 + 8 + 64; +const CERT_MAX: usize = CERT_MIN + 2 * 31; + +/// The fields in their only allowed order: (tag, name, smallest and largest length). +const FIELDS: [(u8, &str, usize, usize); 7] = [ + (1, "app", 1, 32), + (2, "schema", 4, 4), + (3, "hlc", 12, 12), + (4, "author", 32, 32), + (5, "cert", CERT_MIN, CERT_MAX), + (6, "payload", 0, MAX_PAYLOAD), + (7, "sig", 64, 64), +]; + +/// One signed event. +#[derive(Clone, PartialEq, Eq)] +pub struct Envelope { + app: Id, + schema: u32, + hlc: Hlc, + author: PublicKey, + cert: SubkeyCert, + payload: Vec, + sig: Signature, + /// The canonical encoding; the signature covers `bytes[..sig_at]`. + bytes: Vec, + sig_at: usize, + hash: [u8; 32], +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum DecodeError { + #[error("the envelope is {0} bytes, more than the limit")] + TooLarge(usize), + #[error("too short to be an envelope")] + TooShort, + #[error("not a TEV1 envelope")] + BadMagic, + #[error("unknown field {0}")] + UnknownField(u8), + #[error("field {found} where field {expected} must be")] + FieldOutOfOrder { expected: u8, found: u8 }, + #[error("the envelope ends inside field {field}")] + Truncated { field: &'static str }, + #[error("field {field} has a wrong length ({len})")] + BadLength { field: &'static str, len: u64 }, + #[error("field {field} is invalid: {reason}")] + Invalid { field: &'static str, reason: &'static str }, + #[error("bytes after the last field")] + TrailingBytes, + #[error("the certificate does not decode: {0}")] + Cert(CertError), +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum SealError { + #[error("the certificate is for another key than the one signing")] + CertForAnotherKey, + #[error("the payload is larger than {MAX_PAYLOAD} bytes")] + PayloadTooLarge, + #[error("the bytes are not the to-be-signed part of an envelope")] + NotToBeSigned, + #[error("the signature does not verify for the author")] + BadSignature, +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum VerifyError { + #[error("the author is not the key the certificate certifies")] + AuthorNotCert, + #[error("the certificate is for another app")] + WrongApp, + #[error("the certificate's identity is not a member of this group")] + UnknownRoot, + #[error("the certificate was not valid at the event's time: {0}")] + Cert(CertError), + #[error("the event's clock is too far in the future")] + FromTheFuture, + #[error("the event's signature is not valid")] + BadSignature, +} + +fn put(out: &mut Vec, tag: u8, value: &[u8]) { + out.push(tag); + out.extend_from_slice(&(value.len() as u32).to_be_bytes()); + out.extend_from_slice(value); +} + +impl Envelope { + /// Signs an event with `subkey`, whose cert is `cert`. The app is the cert's app. + pub fn seal( + subkey: &Subkey, + cert: &SubkeyCert, + schema: u32, + hlc: Hlc, + payload: &[u8], + ) -> Result { + let tbs = Envelope::to_be_signed(&subkey.public(), cert, schema, hlc, payload)?; + let sig = subkey.sign_event_tbs(&tbs); + Envelope::with_signature(tbs, sig) + } + + /// The bytes `author` signs (after `EVENT_DOMAIN`), for a signer that cannot sign at once (a WebCrypto + /// key in the browser, docs/V1_1B.md §2). Finish with [`Envelope::with_signature`]. + pub fn to_be_signed( + author: &PublicKey, + cert: &SubkeyCert, + schema: u32, + hlc: Hlc, + payload: &[u8], + ) -> Result, SealError> { + if cert.subkey() != *author { + return Err(SealError::CertForAnotherKey); + } + if payload.len() > MAX_PAYLOAD { + return Err(SealError::PayloadTooLarge); + } + let mut bytes = MAGIC.to_vec(); + put(&mut bytes, 1, cert.app_id().as_str().as_bytes()); + put(&mut bytes, 2, &schema.to_be_bytes()); + put(&mut bytes, 3, &hlc.to_bytes()); + put(&mut bytes, 4, author.as_bytes()); + put(&mut bytes, 5, &cert.to_bytes()); + put(&mut bytes, 6, payload); + Ok(bytes) + } + + /// Finishes an envelope from [`Envelope::to_be_signed`]'s bytes and the author's signature over them. + /// Refuses a signature that does not verify, so a broken signer cannot make an event others would drop. + pub fn with_signature(tbs: Vec, sig: Signature) -> Result { + let mut bytes = tbs; + let sig_at = bytes.len(); + put(&mut bytes, 7, sig.as_bytes()); + let e = Envelope::decode(&bytes).map_err(|_| SealError::NotToBeSigned)?; + if e.sig_at != sig_at || !verify_event_sig(&e.author, &e.bytes[..sig_at], &sig) { + return Err(SealError::BadSignature); + } + Ok(e) + } + + /// Decodes untrusted bytes. All or nothing. + pub fn decode(b: &[u8]) -> Result { + if b.len() > MAX_ENVELOPE { + return Err(DecodeError::TooLarge(b.len())); + } + if b.len() < MAGIC.len() { + return Err(DecodeError::TooShort); + } + if &b[..4] != MAGIC { + return Err(DecodeError::BadMagic); + } + let mut pos = 4; + let mut values: [&[u8]; 7] = [&[]; 7]; + let mut sig_at = 0; + for (i, &(tag, field, min, max)) in FIELDS.iter().enumerate() { + let found = *b.get(pos).ok_or(DecodeError::Truncated { field })?; + if found != tag { + return Err(if (1..=7).contains(&found) { + DecodeError::FieldOutOfOrder { expected: tag, found } + } else { + DecodeError::UnknownField(found) + }); + } + if tag == 7 { + sig_at = pos; + } + let len_bytes: [u8; 4] = + b.get(pos + 1..pos + 5).and_then(|s| s.try_into().ok()).ok_or(DecodeError::Truncated { field })?; + let len = u32::from_be_bytes(len_bytes) as usize; + if len < min || len > max { + return Err(DecodeError::BadLength { field, len: len as u64 }); + } + let start = pos + 5; + values[i] = b.get(start..start + len).ok_or(DecodeError::Truncated { field })?; + pos = start + len; + } + if pos != b.len() { + return Err(DecodeError::TrailingBytes); + } + let invalid = |field, reason| DecodeError::Invalid { field, reason }; + let app = std::str::from_utf8(values[0]) + .ok() + .and_then(|s| Id::new(s).ok()) + .ok_or(invalid("app", "not an id (a-z, 0-9, '-')"))?; + let schema = u32::from_be_bytes(values[1].try_into().map_err(|_| invalid("schema", "length"))?); + let hlc = Hlc::from_bytes(values[2].try_into().map_err(|_| invalid("hlc", "length"))?); + let author = PublicKey::from_bytes(values[3].try_into().map_err(|_| invalid("author", "length"))?); + let cert = SubkeyCert::from_bytes(values[4]).map_err(DecodeError::Cert)?; + let sig = Signature::from_bytes(values[6].try_into().map_err(|_| invalid("sig", "length"))?); + Ok(Envelope { + app, + schema, + hlc, + author, + cert, + payload: values[5].to_vec(), + sig, + bytes: b.to_vec(), + sig_at, + hash: tessera::hash(b), + }) + } + + pub fn as_bytes(&self) -> &[u8] { + &self.bytes + } + + pub fn hash(&self) -> [u8; 32] { + self.hash + } + + pub fn app(&self) -> &Id { + &self.app + } + + pub fn schema(&self) -> u32 { + self.schema + } + + pub fn hlc(&self) -> Hlc { + self.hlc + } + + pub fn author(&self) -> PublicKey { + self.author + } + + pub fn cert(&self) -> &SubkeyCert { + &self.cert + } + + pub fn payload(&self) -> &[u8] { + &self.payload + } + + /// Whether this event comes from an app subkey of one of `roots`, for this app, made while its cert + /// was valid, and not from the future (`now_ms` + `max_drift_ms`). The first failure is the reason. + pub fn verify(&self, roots: &[PublicKey], now_ms: u64, max_drift_ms: u64) -> Result<(), VerifyError> { + if self.author != self.cert.subkey() { + return Err(VerifyError::AuthorNotCert); + } + if self.cert.app_id() != &self.app { + return Err(VerifyError::WrongApp); + } + let root = self.cert.root(); + if !roots.contains(&root) { + return Err(VerifyError::UnknownRoot); + } + self.cert.verify(&root, self.hlc.wall / 1000).map_err(VerifyError::Cert)?; + if self.hlc.wall > now_ms.saturating_add(max_drift_ms) { + return Err(VerifyError::FromTheFuture); + } + if !verify_event_sig(&self.author, &self.bytes[..self.sig_at], &self.sig) { + return Err(VerifyError::BadSignature); + } + Ok(()) + } +} + +impl LogEvent for Envelope { + fn order_key(&self) -> OrderKey { + OrderKey { hlc: self.hlc, author: self.author, hash: self.hash } + } + + fn encoded(&self) -> &[u8] { + &self.bytes + } +} + +/// Metadata only; the payload is shown by its length. +impl fmt::Debug for Envelope { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Envelope") + .field("app", &self.app) + .field("schema", &self.schema) + .field("hlc", &self.hlc) + .field("author", &self.author) + .field("payload_len", &self.payload.len()) + .finish_non_exhaustive() + } +} diff --git a/crates/envelope/tests/mandatory.rs b/crates/envelope/tests/mandatory.rs new file mode 100644 index 0000000..22983af --- /dev/null +++ b/crates/envelope/tests/mandatory.rs @@ -0,0 +1,349 @@ +//! The mandatory tests for the envelope (docs/TESSERA.md §8): hostile input, verification, convergence. +//! Written before the code. + +use envelope::{DecodeError, Envelope, MAX_PAYLOAD, SealError, VerifyError}; +use proptest::prelude::*; +use tessera::{CertError, CertRequest, Clock, Hlc, Id, Log, PublicKey, RootKey, Subkey, SubkeyCert, certify, merge}; + +const ALICE: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \ + abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art"; +const MALLORY: &str = "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth \ + useful legal winner thank year wave sausage worth title"; + +const DAY: u64 = 86_400; +const NOW_S: u64 = 1_793_000_000; +const NOW_MS: u64 = NOW_S * 1000; +const DRIFT: u64 = 5 * 60 * 1000; + +fn root(m: &str) -> RootKey { + RootKey::from_mnemonic(m).unwrap() +} + +fn cert_for(root: &RootKey, sub: &Subkey, app: &str) -> SubkeyCert { + let req = CertRequest { + subkey: sub.public(), + app_id: Id::new(app).unwrap(), + purpose: Id::new("sync").unwrap(), + not_before: NOW_S - DAY, + not_after: NOW_S + 30 * DAY, + }; + certify(root, &req).unwrap() +} + +/// Alice's Fiscus subkey and an event from it at `NOW`. +fn alice_event(payload: &[u8]) -> (Subkey, SubkeyCert, Envelope) { + let sub = Subkey::from_seed(&[1; 32]); + let cert = cert_for(&root(ALICE), &sub, "fiscus"); + let e = Envelope::seal(&sub, &cert, 1, Hlc { wall: NOW_MS, logical: 0 }, payload).unwrap(); + (sub, cert, e) +} + +fn alice() -> Vec { + vec![root(ALICE).public()] +} + +/// Builds envelope bytes field by field, independently of the crate, so tests can make what `seal` never +/// would. `fields` are (tag, value); the signature (tag 7) is computed over everything before it. +fn raw(fields: &[(u8, Vec)], signer: &Subkey) -> Vec { + let mut out = b"TEV1".to_vec(); + for (tag, v) in fields { + out.push(*tag); + out.extend_from_slice(&(v.len() as u32).to_be_bytes()); + out.extend_from_slice(v); + } + let sig = signer.sign_event_tbs(&out); + out.push(7); + out.extend_from_slice(&64u32.to_be_bytes()); + out.extend_from_slice(sig.as_bytes()); + out +} + +fn fields(app: &str, hlc: Hlc, author: &Subkey, cert: &SubkeyCert, payload: &[u8]) -> Vec<(u8, Vec)> { + vec![ + (1, app.as_bytes().to_vec()), + (2, 1u32.to_be_bytes().to_vec()), + (3, hlc.to_bytes().to_vec()), + (4, author.public().as_bytes().to_vec()), + (5, cert.to_bytes()), + (6, payload.to_vec()), + ] +} + +// ---------- round trip ---------- + +#[test] +fn a_sealed_event_decodes_to_itself_and_verifies() { + let (sub, cert, e) = alice_event(b"ciphertext"); + let back = Envelope::decode(e.as_bytes()).unwrap(); + assert_eq!(back.as_bytes(), e.as_bytes()); + assert_eq!(back.app().as_str(), "fiscus"); + assert_eq!(back.schema(), 1); + assert_eq!(back.author(), sub.public()); + assert_eq!(back.cert(), &cert); + assert_eq!(back.payload(), b"ciphertext"); + assert_eq!(back.verify(&alice(), NOW_MS, DRIFT), Ok(())); + // The independent encoder agrees with seal byte for byte. + let same = raw(&fields("fiscus", Hlc { wall: NOW_MS, logical: 0 }, &sub, &cert, b"ciphertext"), &sub); + assert_eq!(same, e.as_bytes()); +} + +#[test] +fn seal_refuses_a_cert_for_another_key_and_an_oversized_payload() { + let sub = Subkey::from_seed(&[1; 32]); + let other = Subkey::from_seed(&[2; 32]); + let cert = cert_for(&root(ALICE), &other, "fiscus"); + assert!(Envelope::seal(&sub, &cert, 1, Hlc::default(), b"x").is_err()); + let cert = cert_for(&root(ALICE), &sub, "fiscus"); + assert!(Envelope::seal(&sub, &cert, 1, Hlc::default(), &vec![0; MAX_PAYLOAD + 1]).is_err()); + assert!(Envelope::seal(&sub, &cert, 1, Hlc::default(), &vec![0; MAX_PAYLOAD]).is_ok()); +} + +/// The two-step seal for a signer that cannot sign at once (docs/V1_1B.md §2) makes the same bytes as `seal`, +/// and refuses a signature that is not the author's. +#[test] +fn the_two_step_seal_equals_seal_and_refuses_a_wrong_signature() { + let (sub, cert, e) = alice_event(b"two steps"); + let hlc = Hlc { wall: NOW_MS, logical: 0 }; + let tbs = Envelope::to_be_signed(&sub.public(), &cert, 1, hlc, b"two steps").unwrap(); + let sig = sub.sign_event_tbs(&tbs); + assert_eq!(Envelope::with_signature(tbs.clone(), sig).unwrap().as_bytes(), e.as_bytes()); + + let other = Subkey::from_seed(&[9; 32]); + assert_eq!(Envelope::with_signature(tbs.clone(), other.sign_event_tbs(&tbs)).unwrap_err(), SealError::BadSignature); + // A signature in the credential domain is not an event signature. + assert_eq!( + Envelope::with_signature(tbs.clone(), sub.sign_credential_tbs(&tbs)).unwrap_err(), + SealError::BadSignature + ); + assert_eq!(Envelope::with_signature(tbs[..10].to_vec(), sig).unwrap_err(), SealError::NotToBeSigned); + assert_eq!(Envelope::to_be_signed(&other.public(), &cert, 1, hlc, b"x").unwrap_err(), SealError::CertForAnotherKey); +} + +// ---------- hostile events: dropped with a reason ---------- + +#[test] +fn a_wrong_signature_is_rejected() { + let (_, _, e) = alice_event(b"x"); + let mut b = e.as_bytes().to_vec(); + let last = b.len() - 1; + b[last] ^= 1; + let d = Envelope::decode(&b).unwrap(); + assert_eq!(d.verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::BadSignature)); + // Signed by a key other than the author's. + let sub = Subkey::from_seed(&[1; 32]); + let cert = cert_for(&root(ALICE), &sub, "fiscus"); + let forged = + raw(&fields("fiscus", Hlc { wall: NOW_MS, logical: 0 }, &sub, &cert, b"x"), &Subkey::from_seed(&[9; 32])); + assert_eq!(Envelope::decode(&forged).unwrap().verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::BadSignature)); +} + +#[test] +fn an_expired_or_premature_cert_is_rejected() { + let sub = Subkey::from_seed(&[1; 32]); + let cert = cert_for(&root(ALICE), &sub, "fiscus"); + let late = Hlc { wall: (NOW_S + 30 * DAY) * 1000, logical: 0 }; + let e = Envelope::seal(&sub, &cert, 1, late, b"x").unwrap(); + assert_eq!(e.verify(&alice(), late.wall, DRIFT), Err(VerifyError::Cert(CertError::Expired))); + let early = Hlc { wall: (NOW_S - DAY - 1) * 1000, logical: 0 }; + let e = Envelope::seal(&sub, &cert, 1, early, b"x").unwrap(); + assert_eq!(e.verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::Cert(CertError::NotYetValid))); + // An event made while the cert was valid stays valid after it expires: logs can be rebuilt. + let (_, _, e) = alice_event(b"x"); + assert_eq!(e.verify(&alice(), (NOW_S + 400 * DAY) * 1000, DRIFT), Ok(())); +} + +#[test] +fn a_cert_from_a_root_outside_the_group_is_rejected() { + let sub = Subkey::from_seed(&[1; 32]); + let cert = cert_for(&root(MALLORY), &sub, "fiscus"); + let e = Envelope::seal(&sub, &cert, 1, Hlc { wall: NOW_MS, logical: 0 }, b"x").unwrap(); + assert_eq!(e.verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::UnknownRoot)); + let both = vec![root(ALICE).public(), root(MALLORY).public()]; + assert_eq!(e.verify(&both, NOW_MS, DRIFT), Ok(())); +} + +#[test] +fn an_event_for_another_app_or_author_is_rejected() { + let sub = Subkey::from_seed(&[1; 32]); + let cert = cert_for(&root(ALICE), &sub, "calenda"); + let hlc = Hlc { wall: NOW_MS, logical: 0 }; + let wrong_app = raw(&fields("fiscus", hlc, &sub, &cert, b"x"), &sub); + assert_eq!(Envelope::decode(&wrong_app).unwrap().verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::WrongApp)); + // The author field names another key than the cert (and that key signed). + let other = Subkey::from_seed(&[2; 32]); + let cert = cert_for(&root(ALICE), &sub, "fiscus"); + let wrong_author = raw(&fields("fiscus", hlc, &other, &cert, b"x"), &other); + assert_eq!( + Envelope::decode(&wrong_author).unwrap().verify(&alice(), NOW_MS, DRIFT), + Err(VerifyError::AuthorNotCert) + ); +} + +#[test] +fn an_event_from_the_future_is_rejected() { + let sub = Subkey::from_seed(&[1; 32]); + let cert = cert_for(&root(ALICE), &sub, "fiscus"); + let e = Envelope::seal(&sub, &cert, 1, Hlc { wall: NOW_MS + DRIFT + 1, logical: 0 }, b"x").unwrap(); + assert_eq!(e.verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::FromTheFuture)); +} + +#[test] +fn malformed_bodies_are_typed_errors() { + let (sub, cert, e) = alice_event(b"x"); + let hlc = Hlc { wall: NOW_MS, logical: 0 }; + let good = e.as_bytes().to_vec(); + + let mut magic = good.clone(); + magic[3] = b'2'; + assert_eq!(Envelope::decode(&magic).err(), Some(DecodeError::BadMagic)); + + let mut trailing = good.clone(); + trailing.push(0); + assert_eq!(Envelope::decode(&trailing).err(), Some(DecodeError::TrailingBytes)); + + assert!(matches!(Envelope::decode(&good[..good.len() - 1]), Err(DecodeError::Truncated { .. }))); + assert_eq!(Envelope::decode(b"TE").err(), Some(DecodeError::TooShort)); + + let mut f = fields("fiscus", hlc, &sub, &cert, b"x"); + f.insert(2, (9, b"surprise".to_vec())); + assert_eq!(Envelope::decode(&raw(&f, &sub)).err(), Some(DecodeError::UnknownField(9))); + + let mut f = fields("fiscus", hlc, &sub, &cert, b"x"); + f.swap(1, 2); + assert_eq!(Envelope::decode(&raw(&f, &sub)).err(), Some(DecodeError::FieldOutOfOrder { expected: 2, found: 3 })); + + let mut f = fields("fiscus", hlc, &sub, &cert, b"x"); + f.insert(1, (1, b"fiscus".to_vec())); + assert_eq!(Envelope::decode(&raw(&f, &sub)).err(), Some(DecodeError::FieldOutOfOrder { expected: 2, found: 1 })); + + let mut f = fields("fiscus", hlc, &sub, &cert, b"x"); + f[1].1 = vec![0, 0, 1]; + assert!(matches!(Envelope::decode(&raw(&f, &sub)), Err(DecodeError::BadLength { field: "schema", .. }))); + + let f = fields("Fiscus", hlc, &sub, &cert, b"x"); + assert!(matches!(Envelope::decode(&raw(&f, &sub)), Err(DecodeError::Invalid { field: "app", .. }))); + + let mut f = fields("fiscus", hlc, &sub, &cert, b"x"); + let mut bad_cert = cert.to_bytes(); + bad_cert[0] = b'X'; + f[4].1 = bad_cert; + assert!(matches!(Envelope::decode(&raw(&f, &sub)), Err(DecodeError::Cert(_)))); + + let mut huge = good.clone(); + huge.resize(envelope::MAX_ENVELOPE + 1, 0); + assert!(matches!(Envelope::decode(&huge), Err(DecodeError::TooLarge(_)))); + + // A length that claims more than there is. + let mut lie = good.clone(); + lie[5..9].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(Envelope::decode(&lie).is_err()); + + // Every error has a reason. + for b in [&magic, &trailing, &huge, &lie] { + assert!(!Envelope::decode(b).unwrap_err().to_string().is_empty()); + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(2000))] + + /// Random bytes: never a panic, and every rejection says why. + #[test] + fn random_bytes_never_panic(b in prop::collection::vec(any::(), 0..600), magic in any::()) { + let mut b = b; + if magic && b.len() >= 4 { + b[..4].copy_from_slice(b"TEV1"); + } + match Envelope::decode(&b) { + Ok(e) => prop_assert_eq!(e.as_bytes(), &b[..]), + Err(err) => prop_assert!(!err.to_string().is_empty()), + } + } + + /// A valid envelope with random damage: either a typed error, or a whole envelope that is exactly the + /// input — and then it verifies only if nothing changed. + #[test] + fn damaged_envelopes_are_all_or_nothing( + edits in prop::collection::vec((any::(), any::(), 0u8..3), 1..4), + ) { + let (_, _, e) = alice_event(b"some ciphertext"); + let original = e.as_bytes().to_vec(); + let mut b = original.clone(); + for (at, byte, kind) in edits { + if b.is_empty() { break; } + let i = at.index(b.len()); + match kind { + 0 => b[i] ^= byte | 1, + 1 => { b.remove(i); } + _ => b.insert(i, byte), + } + } + match Envelope::decode(&b) { + Ok(d) => { + prop_assert_eq!(d.as_bytes(), &b[..]); + if d.verify(&alice(), NOW_MS, DRIFT).is_ok() { + prop_assert_eq!(&b, &original); + } + } + Err(err) => prop_assert!(!err.to_string().is_empty()), + } + } +} + +// ---------- two devices converge ---------- + +#[test] +fn two_devices_writing_offline_converge_in_either_order() { + let r = root(ALICE); + let (pc, phone) = (Subkey::from_seed(&[1; 32]), Subkey::from_seed(&[2; 32])); + let (pc_cert, phone_cert) = (cert_for(&r, &pc, "fiscus"), cert_for(&r, &phone, "fiscus")); + let (mut pc_clock, mut phone_clock) = (Clock::default(), Clock::default()); + // Both offline, writing at overlapping times; the phone's clock is 2 s behind. + let mut a = Vec::new(); + let mut b = Vec::new(); + for i in 0..5u64 { + let t = NOW_MS + i * 1000; + a.push(Envelope::seal(&pc, &pc_cert, 1, pc_clock.tick(t).unwrap(), format!("pc {i}").as_bytes()).unwrap()); + b.push( + Envelope::seal( + &phone, + &phone_cert, + 1, + phone_clock.tick(t - 2000).unwrap(), + format!("phone {i}").as_bytes(), + ) + .unwrap(), + ); + } + let roots = alice(); + let check = |e: &Envelope| e.verify(&roots, NOW_MS + 10_000, DRIFT); + // Each device has its own log; then they exchange in either order. + let pc_log = merge(&Log::new(), a.clone(), check).log; + let phone_log = merge(&Log::new(), b.clone(), check).log; + let on_pc = merge(&pc_log, phone_log.events().to_vec(), check).log; + let on_phone = merge(&phone_log, pc_log.events().to_vec(), check).log; + assert_eq!(on_pc.len(), 10); + assert_eq!(on_pc.to_bytes(), on_phone.to_bytes(), "byte-identical"); + // Receiving everything again changes nothing. + let again = merge(&on_pc, [a, b].concat(), check); + assert_eq!(again.added, 0); + assert_eq!(again.log.to_bytes(), on_pc.to_bytes()); +} + +#[test] +fn a_hostile_event_leaves_the_log_unchanged() { + let (_, _, good) = alice_event(b"x"); + let roots = alice(); + let check = |e: &Envelope| e.verify(&roots, NOW_MS, DRIFT); + let log = merge(&Log::new(), vec![good], check).log; + let before = log.to_bytes(); + let sub = Subkey::from_seed(&[5; 32]); + let evil = + Envelope::seal(&sub, &cert_for(&root(MALLORY), &sub, "fiscus"), 1, Hlc { wall: NOW_MS, logical: 1 }, b"y") + .unwrap(); + let m = merge(&log, vec![evil], check); + assert_eq!(m.log.to_bytes(), before); + assert_eq!(m.rejected.len(), 1); + assert_eq!(m.rejected[0].1, VerifyError::UnknownRoot); + assert!(!m.rejected[0].1.to_string().is_empty()); +} diff --git a/crates/proto/Cargo.toml b/crates/proto/Cargo.toml new file mode 100644 index 0000000..b092b17 --- /dev/null +++ b/crates/proto/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "tabellarius-proto" +description = "Tabellarius wire protocol: mailbox ids, per-mailbox request signatures, limits (docs/TABELLARIUS.md §3)" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[lints] +workspace = true + +[dependencies] +ed25519-dalek.workspace = true +sha2.workspace = true +zeroize.workspace = true +thiserror.workspace = true +data-encoding.workspace = true +getrandom = "0.3" diff --git a/crates/proto/src/lib.rs b/crates/proto/src/lib.rs new file mode 100644 index 0000000..7a496c4 --- /dev/null +++ b/crates/proto/src/lib.rs @@ -0,0 +1,201 @@ +//! The Tabellarius wire protocol (docs/TABELLARIUS.md §3), shared by the relay and the client. +//! +//! - Mailbox ids: a group's is `SHA-256("tabellarius mailbox v1" ‖ group id)`, an invite's is random. +//! - Every request is signed by a random **per-mailbox** key ([`MailboxKey`]), never by an identity key. + +use data_encoding::{BASE64URL_NOPAD, HEXLOWER}; +use ed25519_dalek::{Signer, SigningKey, VerifyingKey}; +use sha2::{Digest, Sha256}; +use std::fmt; +use zeroize::Zeroizing; + +/// The largest message (MLS ciphertext) the relay keeps. +pub const MAX_MESSAGE: usize = 300 * 1024; +/// The most messages in one upload. +pub const MAX_BATCH: usize = 100; +/// The largest request body. +pub const MAX_BODY: usize = 2 * 1024 * 1024; +/// The most messages one fetch returns. +pub const FETCH_LIMIT: usize = 200; +/// How far a request's time may be from the relay's, in seconds. +pub const MAX_SKEW: u64 = 120; + +/// Live subscribe (docs/V1_1B.md §3): the most subscriptions on one socket. +pub const LIVE_MAX_SUBS: usize = 32; +/// The most open subscriptions per mailbox key, over all sockets. +pub const LIVE_MAX_PER_KEY: u32 = 4; +/// A socket with nothing from its client for this long is closed. +pub const LIVE_IDLE_SECS: u64 = 600; +/// The method a subscription is signed with. +pub const LIVE_METHOD: &str = "LIVE"; + +/// The path a subscription to `mailbox` from `after` is signed with (method [`LIVE_METHOD`], empty body). +pub fn live_path(mailbox: &str, after: u64) -> String { + format!("/v1/mailboxes/{mailbox}/live?after={after}") +} + +pub const H_KEY: &str = "tab-key"; +pub const H_TIME: &str = "tab-time"; +pub const H_NONCE: &str = "tab-nonce"; +pub const H_SIG: &str = "tab-sig"; + +const REQUEST_DOMAIN: &[u8] = b"tabellarius request v1\0"; +const MAILBOX_DOMAIN: &[u8] = b"tabellarius mailbox v1"; + +pub fn b64(b: &[u8]) -> String { + BASE64URL_NOPAD.encode(b) +} + +pub fn unb64(s: &str) -> Option> { + BASE64URL_NOPAD.decode(s.as_bytes()).ok() +} + +pub fn unb64_32(s: &str) -> Option<[u8; 32]> { + unb64(s)?.try_into().ok() +} + +/// A group's mailbox id. +pub fn group_mailbox(group_id: &[u8]) -> [u8; 32] { + Sha256::new().chain_update(MAILBOX_DOMAIN).chain_update(group_id).finalize().into() +} + +/// 32 bytes from the OS CSPRNG. +pub fn random32() -> [u8; 32] { + let mut b = [0u8; 32]; + getrandom::fill(&mut b).expect("the OS has randomness"); + b +} + +/// What a request's signature covers. +pub fn signed_bytes(method: &str, path_and_query: &str, time: u64, nonce: &str, body: &[u8]) -> Vec { + let body_hash = HEXLOWER.encode(&Sha256::digest(body)); + let mut out = REQUEST_DOMAIN.to_vec(); + out.extend_from_slice(format!("{method}\n{path_and_query}\n{time}\n{nonce}\n{body_hash}").as_bytes()); + out +} + +/// The four headers of a signed request. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SignedHeaders { + pub key: String, + pub time: String, + pub nonce: String, + pub sig: String, +} + +impl SignedHeaders { + pub fn pairs(&self) -> [(&'static str, &str); 4] { + [(H_KEY, &self.key), (H_TIME, &self.time), (H_NONCE, &self.nonce), (H_SIG, &self.sig)] + } +} + +/// A random key for one mailbox. It identifies a device in that mailbox and nowhere else. +pub struct MailboxKey(SigningKey); + +impl MailboxKey { + pub fn generate() -> MailboxKey { + let seed = Zeroizing::new(random32()); + MailboxKey(SigningKey::from_bytes(&seed)) + } + + /// From a seed kept in the client's encrypted state. + pub fn from_seed(seed: &[u8; 32]) -> MailboxKey { + MailboxKey(SigningKey::from_bytes(seed)) + } + + /// For the client's encrypted state only. + pub fn seed(&self) -> Zeroizing<[u8; 32]> { + Zeroizing::new(self.0.to_bytes()) + } + + pub fn public(&self) -> [u8; 32] { + self.0.verifying_key().to_bytes() + } + + pub fn sign_request(&self, method: &str, path_and_query: &str, body: &[u8], time: u64) -> SignedHeaders { + let nonce = b64(&random32()[..16]); + let sig = self.0.sign(&signed_bytes(method, path_and_query, time, &nonce, body)); + SignedHeaders { key: b64(&self.public()), time: time.to_string(), nonce, sig: b64(&sig.to_bytes()) } + } +} + +impl fmt::Debug for MailboxKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("MailboxKey([redacted])") + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum AuthError { + #[error("unsigned")] + Unsigned, + #[error("stale")] + Stale, + #[error("bad_signature")] + BadSignature, +} + +/// Checks a request's signature and time. Returns the key and nonce; registration and replay are the +/// relay's to check. +pub fn verify_request( + method: &str, + path_and_query: &str, + body: &[u8], + headers: [Option<&str>; 4], + now: u64, +) -> Result<([u8; 32], Vec), AuthError> { + let [Some(key), Some(time), Some(nonce), Some(sig)] = headers else { return Err(AuthError::Unsigned) }; + let key = unb64_32(key).ok_or(AuthError::Unsigned)?; + let t: u64 = time.parse().map_err(|_| AuthError::Unsigned)?; + let nonce_bytes = unb64(nonce).filter(|n| n.len() == 16).ok_or(AuthError::Unsigned)?; + let sig: [u8; 64] = unb64(sig).and_then(|s| s.try_into().ok()).ok_or(AuthError::Unsigned)?; + if now.abs_diff(t) > MAX_SKEW { + return Err(AuthError::Stale); + } + let vk = VerifyingKey::from_bytes(&key).map_err(|_| AuthError::BadSignature)?; + vk.verify_strict( + &signed_bytes(method, path_and_query, t, nonce, body), + &ed25519_dalek::Signature::from_bytes(&sig), + ) + .map_err(|_| AuthError::BadSignature)?; + Ok((key, nonce_bytes)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_signed_request_verifies_and_any_change_breaks_it() { + let k = MailboxKey::generate(); + let h = k.sign_request("POST", "/v1/mailboxes/x/messages", b"{}", 1000); + fn hs(h: &SignedHeaders) -> [Option<&str>; 4] { + [Some(h.key.as_str()), Some(h.time.as_str()), Some(h.nonce.as_str()), Some(h.sig.as_str())] + } + assert_eq!(verify_request("POST", "/v1/mailboxes/x/messages", b"{}", hs(&h), 1000).unwrap().0, k.public()); + assert_eq!( + verify_request("POST", "/v1/mailboxes/y/messages", b"{}", hs(&h), 1000), + Err(AuthError::BadSignature) + ); + assert_eq!( + verify_request("POST", "/v1/mailboxes/x/messages", b"{ }", hs(&h), 1000), + Err(AuthError::BadSignature) + ); + assert_eq!( + verify_request("GET", "/v1/mailboxes/x/messages", b"{}", hs(&h), 1000), + Err(AuthError::BadSignature) + ); + assert_eq!( + verify_request("POST", "/v1/mailboxes/x/messages", b"{}", hs(&h), 1000 + MAX_SKEW + 1), + Err(AuthError::Stale) + ); + assert_eq!(verify_request("POST", "/", b"", [None, None, None, None], 1000), Err(AuthError::Unsigned)); + assert_eq!(format!("{k:?}"), "MailboxKey([redacted])"); + } + + #[test] + fn group_mailboxes_are_distinct_and_stable() { + assert_eq!(group_mailbox(b"g1"), group_mailbox(b"g1")); + assert_ne!(group_mailbox(b"g1"), group_mailbox(b"g2")); + } +} diff --git a/crates/tessera/Cargo.toml b/crates/tessera/Cargo.toml new file mode 100644 index 0000000..b1fc72f --- /dev/null +++ b/crates/tessera/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "tessera" +description = "Domi identity: root key from a mnemonic, subkey certificates, match code, hybrid logical clock, deterministic merge (docs/TESSERA.md)" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[lints] +workspace = true + +[dependencies] +ed25519-dalek.workspace = true +sha2.workspace = true +hkdf.workspace = true +bip39.workspace = true +zeroize.workspace = true +thiserror.workspace = true +data-encoding.workspace = true +chacha20poly1305 = "0.10" + +[dev-dependencies] +proptest = "1" +static_assertions = "1" diff --git a/crates/tessera/src/backup.rs b/crates/tessera/src/backup.rs new file mode 100644 index 0000000..208da92 --- /dev/null +++ b/crates/tessera/src/backup.rs @@ -0,0 +1,76 @@ +//! The backup secret (docs/TESSERA.md §12, docs/V1_1.md §3): per app, derived from the root secret, so the +//! 24 words bring it back with every device lost. It seals the app's backup and names its relay mailbox. +//! +//! Custos derives it and hands an app only its own; the app keeps it as an opaque value. Nothing reads the +//! secret back out: it seals, opens, and gives the backup mailbox's access-key seed (a relay credential of +//! the kind invite tokens carry; it lets its holder fetch ciphertext, nothing more). + +use chacha20poly1305::aead::{Aead, KeyInit, Payload}; +use chacha20poly1305::{XChaCha20Poly1305, XNonce}; +use hkdf::Hkdf; +use sha2::Sha256; +use std::fmt; +use zeroize::Zeroizing; + +const BACKUP_SALT: &[u8] = b"tessera backup v1"; +const SEAL_INFO: &[u8] = b"seal"; +const MAILBOX_INFO: &[u8] = b"mailbox"; + +/// An app's backup secret: 32 bytes from `HKDF-SHA256(salt "tessera backup v1", ikm = root secret, +/// info = app id)`. +pub struct BackupSecret(Zeroizing<[u8; 32]>); + +pub(crate) fn derive(root_secret: &[u8; 32], app_id: &crate::Id) -> BackupSecret { + let mut out = Zeroizing::new([0u8; 32]); + Hkdf::::new(Some(BACKUP_SALT), root_secret) + .expand(app_id.as_str().as_bytes(), out.as_mut()) + .expect("32 bytes is a valid HKDF length"); + BackupSecret(out) +} + +impl BackupSecret { + /// The 32 bytes Custos hands the app. + pub fn from_bytes(b: [u8; 32]) -> BackupSecret { + BackupSecret(Zeroizing::new(b)) + } + + fn expand(&self, info: &[u8]) -> Zeroizing<[u8; 32]> { + let mut out = Zeroizing::new([0u8; 32]); + Hkdf::::from_prk(self.0.as_ref()) + .expect("32 bytes is a valid PRK") + .expand(info, out.as_mut()) + .expect("32 bytes is a valid HKDF length"); + out + } + + /// `nonce ‖ XChaCha20-Poly1305(seal key, plain, aad)`. The caller supplies a fresh random nonce. + pub fn seal(&self, nonce: &[u8; 24], aad: &[u8], plain: &[u8]) -> Vec { + let key = self.expand(SEAL_INFO); + let ct = XChaCha20Poly1305::new(key.as_ref().into()) + .encrypt(XNonce::from_slice(nonce), Payload { msg: plain, aad }) + .expect("encryption does not fail"); + [nonce.as_slice(), &ct].concat() + } + + /// The plaintext, or `None` if `sealed` was not sealed with this secret and `aad`. + pub fn open(&self, aad: &[u8], sealed: &[u8]) -> Option> { + if sealed.len() < 24 { + return None; + } + let key = self.expand(SEAL_INFO); + XChaCha20Poly1305::new(key.as_ref().into()) + .decrypt(XNonce::from_slice(&sealed[..24]), Payload { msg: &sealed[24..], aad }) + .ok() + } + + /// The seed of the backup mailbox's access key (a Tabellarius `MailboxKey`). + pub fn mailbox_seed(&self) -> Zeroizing<[u8; 32]> { + self.expand(MAILBOX_INFO) + } +} + +impl fmt::Debug for BackupSecret { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("BackupSecret([redacted])") + } +} diff --git a/crates/tessera/src/cert.rs b/crates/tessera/src/cert.rs new file mode 100644 index 0000000..0c00b65 --- /dev/null +++ b/crates/tessera/src/cert.rs @@ -0,0 +1,175 @@ +//! Subkey certificates (`TSC1`) and the match code (docs/TESSERA.md §4, §5). + +use crate::keys::{RootSigner, SignError, verify_cert_sig}; +use crate::{Id, PublicKey, Reader, Signature}; +use data_encoding::BASE64URL_NOPAD; +use sha2::{Digest, Sha256}; + +pub const CERT_MAGIC: &[u8; 4] = b"TSC1"; +const SKEW: u64 = 5 * 60; +const YEAR: u64 = 365 * 86_400; + +/// What a cert will say, before the root signs it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CertRequest { + pub subkey: PublicKey, + pub app_id: Id, + pub purpose: Id, + /// Unix seconds, inclusive. + pub not_before: u64, + /// Unix seconds, exclusive. + pub not_after: u64, +} + +impl CertRequest { + /// The validity Custos issues: from five minutes ago (clock skew) for 365 days. + pub fn standard(subkey: PublicKey, app_id: Id, purpose: Id, now: u64) -> CertRequest { + CertRequest { + subkey, + app_id, + purpose, + not_before: now.saturating_sub(SKEW), + not_after: now.saturating_add(YEAR), + } + } + + /// The bytes the root signs (after `CERT_DOMAIN`): everything in the cert before `sig`. + pub fn tbs(&self, root: &PublicKey) -> Vec { + let mut out = Vec::with_capacity(4 + 32 + 32 + 66 + 16); + out.extend_from_slice(CERT_MAGIC); + out.extend_from_slice(root.as_bytes()); + out.extend_from_slice(self.subkey.as_bytes()); + self.app_id.encode(&mut out); + self.purpose.encode(&mut out); + out.extend_from_slice(&self.not_before.to_be_bytes()); + out.extend_from_slice(&self.not_after.to_be_bytes()); + out + } +} + +/// A subkey certified by a root. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SubkeyCert { + root: PublicKey, + req: CertRequest, + sig: Signature, +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum CertError { + #[error("malformed certificate: {0}")] + Malformed(&'static str), + #[error("the certificate belongs to another identity")] + WrongRoot, + #[error("the certificate's signature is not valid (tampered)")] + BadSignature, + #[error("the certificate is not valid yet")] + NotYetValid, + #[error("the certificate has expired")] + Expired, + #[error("the root did not sign: {0}")] + Sign(SignError), +} + +/// Has `signer` certify `req`, and checks the signature it got back. +pub fn certify(signer: &impl RootSigner, req: &CertRequest) -> Result { + if req.not_after <= req.not_before { + return Err(CertError::Malformed("not_after must be later than not_before")); + } + let root = signer.root_public(); + let tbs = req.tbs(&root); + let sig = signer.sign_cert_tbs(&tbs).map_err(CertError::Sign)?; + if !verify_cert_sig(&root, &tbs, &sig) { + return Err(CertError::BadSignature); + } + Ok(SubkeyCert { root, req: req.clone(), sig }) +} + +impl SubkeyCert { + pub fn root(&self) -> PublicKey { + self.root + } + + pub fn subkey(&self) -> PublicKey { + self.req.subkey + } + + pub fn app_id(&self) -> &Id { + &self.req.app_id + } + + pub fn purpose(&self) -> &Id { + &self.req.purpose + } + + pub fn not_before(&self) -> u64 { + self.req.not_before + } + + pub fn not_after(&self) -> u64 { + self.req.not_after + } + + /// Checks the cert against the root the caller trusts, at `now` (Unix seconds). + pub fn verify(&self, root: &PublicKey, now: u64) -> Result<(), CertError> { + if self.root != *root { + return Err(CertError::WrongRoot); + } + if !verify_cert_sig(&self.root, &self.req.tbs(&self.root), &self.sig) { + return Err(CertError::BadSignature); + } + if now < self.req.not_before { + return Err(CertError::NotYetValid); + } + if now >= self.req.not_after { + return Err(CertError::Expired); + } + Ok(()) + } + + pub fn to_bytes(&self) -> Vec { + let mut out = self.req.tbs(&self.root); + out.extend_from_slice(self.sig.as_bytes()); + out + } + + pub fn from_bytes(b: &[u8]) -> Result { + let mut r = Reader::new(b); + let m = CertError::Malformed; + if r.take(4) != Some(CERT_MAGIC.as_slice()) { + return Err(m("not a TSC1 certificate")); + } + let root = PublicKey::from_bytes(r.array().ok_or(m("too short"))?); + let subkey = PublicKey::from_bytes(r.array().ok_or(m("too short"))?); + let app_id = Id::decode(&mut r).ok_or(m("invalid app id"))?; + let purpose = Id::decode(&mut r).ok_or(m("invalid purpose"))?; + let not_before = r.u64().ok_or(m("too short"))?; + let not_after = r.u64().ok_or(m("too short"))?; + let sig = Signature::from_bytes(r.array().ok_or(m("too short"))?); + if !r.is_empty() { + return Err(m("trailing bytes")); + } + if not_after <= not_before { + return Err(m("not_after must be later than not_before")); + } + Ok(SubkeyCert { root, req: CertRequest { subkey, app_id, purpose, not_before, not_after }, sig }) + } + + /// base64url without padding, for JSON and QR codes. + pub fn to_text(&self) -> String { + BASE64URL_NOPAD.encode(&self.to_bytes()) + } + + pub fn from_text(s: &str) -> Result { + let b = BASE64URL_NOPAD.decode(s.as_bytes()).map_err(|_| CertError::Malformed("not base64url"))?; + SubkeyCert::from_bytes(&b) + } +} + +/// Six digits for `subkey`, shown by the app and by Custos: `u32_be(SHA-256("tessera match v1" ‖ subkey)[0..4]) +/// mod 1 000 000`. +pub fn match_code(subkey: &PublicKey) -> String { + let h = Sha256::new().chain_update(b"tessera match v1").chain_update(subkey.as_bytes()).finalize(); + let n = u32::from_be_bytes([h[0], h[1], h[2], h[3]]) % 1_000_000; + format!("{n:06}") +} diff --git a/crates/tessera/src/hlc.rs b/crates/tessera/src/hlc.rs new file mode 100644 index 0000000..0a405db --- /dev/null +++ b/crates/tessera/src/hlc.rs @@ -0,0 +1,90 @@ +//! The hybrid logical clock (docs/TESSERA.md §6). Time is a parameter: Unix milliseconds. + +/// A timestamp, ordered by `wall` then `logical`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Hlc { + /// Unix milliseconds. + pub wall: u64, + pub logical: u32, +} + +impl Hlc { + pub fn to_bytes(&self) -> [u8; 12] { + let mut b = [0u8; 12]; + b[..8].copy_from_slice(&self.wall.to_be_bytes()); + b[8..].copy_from_slice(&self.logical.to_be_bytes()); + b + } + + pub fn from_bytes(b: &[u8; 12]) -> Hlc { + let (w, l) = b.split_at(8); + Hlc { + wall: u64::from_be_bytes(w.try_into().unwrap_or_default()), + logical: u32::from_be_bytes(l.try_into().unwrap_or_default()), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum ClockError { + #[error("the other clock is too far ahead of this one")] + TooFarAhead, + #[error("the logical counter would overflow")] + Overflow, +} + +/// One device's clock. +#[derive(Clone, Debug)] +pub struct Clock { + last: Hlc, + max_drift_ms: u64, +} + +impl Default for Clock { + /// A clock that accepts remote clocks up to five minutes ahead. + fn default() -> Clock { + Clock::with_max_drift(5 * 60 * 1000) + } +} + +impl Clock { + pub fn with_max_drift(max_drift_ms: u64) -> Clock { + Clock { last: Hlc::default(), max_drift_ms } + } + + /// The last timestamp this clock produced. + pub fn last(&self) -> Hlc { + self.last + } + + /// A timestamp for a local event. + pub fn tick(&mut self, now: u64) -> Result { + let wall = self.last.wall.max(now); + let logical = + if wall == self.last.wall { self.last.logical.checked_add(1).ok_or(ClockError::Overflow)? } else { 0 }; + self.last = Hlc { wall, logical }; + Ok(self.last) + } + + /// Moves the clock past a remote timestamp. Refuses one more than `max_drift` ahead of `now`, without + /// changing the clock. + pub fn observe(&mut self, remote: Hlc, now: u64) -> Result { + if remote.wall > now.saturating_add(self.max_drift_ms) { + return Err(ClockError::TooFarAhead); + } + let last = self.last; + let wall = last.wall.max(remote.wall).max(now); + let base = match (wall == last.wall, wall == remote.wall) { + (true, true) => Some(last.logical.max(remote.logical)), + (true, false) => Some(last.logical), + (false, true) => Some(remote.logical), + (false, false) => None, + }; + let logical = match base { + Some(l) => l.checked_add(1).ok_or(ClockError::Overflow)?, + None => 0, + }; + self.last = Hlc { wall, logical }; + Ok(self.last) + } +} diff --git a/crates/tessera/src/id.rs b/crates/tessera/src/id.rs new file mode 100644 index 0000000..032ad99 --- /dev/null +++ b/crates/tessera/src/id.rs @@ -0,0 +1,49 @@ +//! Ids: app ids, purposes and the envelope's `app` (docs/TESSERA.md §2). + +use std::fmt; + +/// 1–32 bytes of `[a-z0-9-]`, not starting or ending with `-`: exactly one encoding per value. +#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Id(String); + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[error("an id is 1-32 characters of a-z, 0-9 and '-', not starting or ending with '-'")] +pub struct IdError; + +impl Id { + pub fn new(s: &str) -> Result { + let ok = (1..=32).contains(&s.len()) + && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + && !s.starts_with('-') + && !s.ends_with('-'); + if ok { Ok(Id(s.to_owned())) } else { Err(IdError) } + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + /// `str8`: one length byte, then the bytes. + pub(crate) fn encode(&self, out: &mut Vec) { + out.push(self.0.len() as u8); + out.extend_from_slice(self.0.as_bytes()); + } + + pub(crate) fn decode(r: &mut crate::Reader) -> Option { + let n = r.u8()? as usize; + let s = std::str::from_utf8(r.take(n)?).ok()?; + Id::new(s).ok() + } +} + +impl fmt::Display for Id { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl fmt::Debug for Id { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Id({})", self.0) + } +} diff --git a/crates/tessera/src/keys.rs b/crates/tessera/src/keys.rs new file mode 100644 index 0000000..c737430 --- /dev/null +++ b/crates/tessera/src/keys.rs @@ -0,0 +1,232 @@ +//! Keys: the root key and its derivation, subkeys, public keys and signatures (docs/TESSERA.md §3). +//! +//! The secret types ([`RootKey`], [`Subkey`]) have no method that returns their bytes, are not `Clone`, +//! and print `[redacted]`. `tests/surface.rs` locks this. + +use crate::cert::CERT_MAGIC; +use data_encoding::BASE64URL_NOPAD; +use ed25519_dalek::{Signer, SigningKey, VerifyingKey}; +use hkdf::Hkdf; +use sha2::Sha256; +use std::fmt; +use zeroize::Zeroizing; + +/// Prefix of every message a root signs: it can only ever sign certs. +pub const CERT_DOMAIN: &[u8] = b"tessera cert v1\0"; +/// Prefix of every message a subkey signs as an event author. +pub const EVENT_DOMAIN: &[u8] = b"tessera event v1\0"; +/// Prefix of what a subkey signs to vouch for a device's keys in a group (docs/TABELLARIUS.md §2). +pub const CREDENTIAL_DOMAIN: &[u8] = b"tessera credential v1\0"; +/// Prefix of every revocation a root signs (docs/TESSERA.md §12): its second and only other statement. +pub const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0"; + +const ROOT_SALT: &[u8] = b"tessera root v1"; +const ROOT_INFO: &[u8] = b"ed25519"; +const MNEMONIC_WORDS: usize = 24; + +/// An Ed25519 public key: a root or a subkey. +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct PublicKey([u8; 32]); + +impl PublicKey { + pub fn from_bytes(b: [u8; 32]) -> PublicKey { + PublicKey(b) + } + + pub fn as_bytes(&self) -> &[u8; 32] { + &self.0 + } + + /// Parses the base64url form that `Display` prints. + pub fn from_text(s: &str) -> Option { + let b = BASE64URL_NOPAD.decode(s.as_bytes()).ok()?; + Some(PublicKey(b.try_into().ok()?)) + } +} + +/// base64url without padding. +impl fmt::Display for PublicKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&BASE64URL_NOPAD.encode(&self.0)) + } +} + +impl fmt::Debug for PublicKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "PublicKey({self})") + } +} + +/// An Ed25519 signature. +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct Signature([u8; 64]); + +impl Signature { + pub fn from_bytes(b: [u8; 64]) -> Signature { + Signature(b) + } + + pub fn as_bytes(&self) -> &[u8; 64] { + &self.0 + } +} + +impl fmt::Debug for Signature { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Signature({}…)", BASE64URL_NOPAD.encode(&self.0[..6])) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum MnemonicError { + #[error("a Domi recovery phrase has 24 words")] + WordCount, + #[error("the recovery phrase has a word that is not in the list, or a wrong checksum")] + Invalid, +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum SignError { + #[error("the root signs only certificates that name it")] + NotACert, + #[error("{0}")] + Other(String), +} + +/// What can sign certs with a root: [`RootKey`] here, the Custos vault in practice. +pub trait RootSigner { + fn root_public(&self) -> PublicKey; + /// Signs `CERT_DOMAIN ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` and this root's key. + fn sign_cert_tbs(&self, tbs: &[u8]) -> Result; +} + +/// What can sign revocations with a root (v1.1): [`RootKey`] here, the Custos vault in practice. +pub trait RevokeSigner: RootSigner { + /// Signs `REVOKE_DOMAIN ‖ tbs`. Refuses a `tbs` that does not start with `TRV1` and this root's key. + fn sign_revocation_tbs(&self, tbs: &[u8]) -> Result; +} + +/// The root key, derived from a mnemonic (docs/TESSERA.md §3). For recovery and tests: the real one stays +/// in Custos. +pub struct RootKey(SigningKey); + +impl RootKey { + /// Words are separated by any whitespace; case does not matter. Exactly 24 BIP39 English words. + pub fn from_mnemonic(phrase: &str) -> Result { + let words: Vec = phrase.split_whitespace().map(|w| w.to_lowercase()).collect(); + let normalized = Zeroizing::new(words.join(" ")); + drop(Zeroizing::new(words)); + if normalized.split(' ').count() != MNEMONIC_WORDS { + return Err(MnemonicError::WordCount); + } + let m = bip39::Mnemonic::parse_in_normalized(bip39::Language::English, &normalized) + .map_err(|_| MnemonicError::Invalid)?; + let seed = Zeroizing::new(m.to_seed_normalized("")); + let mut secret = Zeroizing::new([0u8; 32]); + Hkdf::::new(Some(ROOT_SALT), seed.as_ref()) + .expand(ROOT_INFO, secret.as_mut()) + .map_err(|_| MnemonicError::Invalid)?; + Ok(RootKey(SigningKey::from_bytes(&secret))) + } + + pub fn public(&self) -> PublicKey { + PublicKey(self.0.verifying_key().to_bytes()) + } + + /// The app's backup secret (docs/TESSERA.md §12): from the root secret, so the 24 words bring it back. + pub fn backup_secret(&self, app_id: &crate::Id) -> crate::BackupSecret { + crate::backup::derive(&Zeroizing::new(self.0.to_bytes()), app_id) + } +} + +impl RevokeSigner for RootKey { + fn sign_revocation_tbs(&self, tbs: &[u8]) -> Result { + if !names_root_as(tbs, crate::revoke::REVOCATION_MAGIC, &self.public()) { + return Err(SignError::NotACert); + } + Ok(Signature(self.0.sign(&[REVOKE_DOMAIN, tbs].concat()).to_bytes())) + } +} + +impl RootSigner for RootKey { + fn root_public(&self) -> PublicKey { + self.public() + } + + fn sign_cert_tbs(&self, tbs: &[u8]) -> Result { + if !names_root(tbs, &self.public()) { + return Err(SignError::NotACert); + } + Ok(Signature(self.0.sign(&[CERT_DOMAIN, tbs].concat()).to_bytes())) + } +} + +impl fmt::Debug for RootKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("RootKey([redacted])") + } +} + +/// Whether `tbs` starts like a cert for `root`: `TSC1 ‖ root`. Custos' vault applies the same check. +pub(crate) fn names_root(tbs: &[u8], root: &PublicKey) -> bool { + names_root_as(tbs, CERT_MAGIC, root) +} + +/// Whether `tbs` starts `magic ‖ root`. +fn names_root_as(tbs: &[u8], magic: &[u8; 4], root: &PublicKey) -> bool { + tbs.len() > 36 && &tbs[..4] == magic && tbs[4..36] == root.0 +} + +/// An app's subkey. The app makes the 32-byte seed from the OS CSPRNG and keeps it in Custos. +pub struct Subkey(SigningKey); + +impl Subkey { + pub fn from_seed(seed: &[u8; 32]) -> Subkey { + Subkey(SigningKey::from_bytes(seed)) + } + + pub fn public(&self) -> PublicKey { + PublicKey(self.0.verifying_key().to_bytes()) + } + + /// Signs `EVENT_DOMAIN ‖ tbs`. + pub fn sign_event_tbs(&self, tbs: &[u8]) -> Signature { + Signature(self.0.sign(&[EVENT_DOMAIN, tbs].concat()).to_bytes()) + } + + /// Signs `CREDENTIAL_DOMAIN ‖ tbs`: vouches for keys this device uses in a group. + pub fn sign_credential_tbs(&self, tbs: &[u8]) -> Signature { + Signature(self.0.sign(&[CREDENTIAL_DOMAIN, tbs].concat()).to_bytes()) + } +} + +impl fmt::Debug for Subkey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Subkey([redacted])") + } +} + +fn verify(key: &PublicKey, domain: &[u8], tbs: &[u8], sig: &Signature) -> bool { + let Ok(vk) = VerifyingKey::from_bytes(&key.0) else { return false }; + let sig = ed25519_dalek::Signature::from_bytes(&sig.0); + vk.verify_strict(&[domain, tbs].concat(), &sig).is_ok() +} + +/// Whether `sig` is `author`'s signature over `EVENT_DOMAIN ‖ tbs` (strict: no malleable signatures, no +/// weak keys). +pub fn verify_event_sig(author: &PublicKey, tbs: &[u8], sig: &Signature) -> bool { + verify(author, EVENT_DOMAIN, tbs, sig) +} + +/// Whether `sig` is `subkey`'s signature over `CREDENTIAL_DOMAIN ‖ tbs`. +pub fn verify_credential_sig(subkey: &PublicKey, tbs: &[u8], sig: &Signature) -> bool { + verify(subkey, CREDENTIAL_DOMAIN, tbs, sig) +} + +pub(crate) fn verify_revocation_sig(root: &PublicKey, tbs: &[u8], sig: &Signature) -> bool { + verify(root, REVOKE_DOMAIN, tbs, sig) +} + +pub(crate) fn verify_cert_sig(root: &PublicKey, tbs: &[u8], sig: &Signature) -> bool { + verify(root, CERT_DOMAIN, tbs, sig) +} diff --git a/crates/tessera/src/lib.rs b/crates/tessera/src/lib.rs new file mode 100644 index 0000000..81c8078 --- /dev/null +++ b/crates/tessera/src/lib.rs @@ -0,0 +1,74 @@ +//! Tessera: the Domi identity (docs/TESSERA.md). +//! +//! - [`RootKey`]: the root Ed25519 key, derived from a 24-word BIP39 mnemonic. In practice it lives in the +//! Custos vault, which implements [`RootSigner`]; this type is for recovery and tests. +//! - [`SubkeyCert`]: a subkey for one app, certified by the root; [`certify`] makes one, `verify` checks it. +//! - [`match_code`]: six digits the app and Custos both show. +//! - [`Clock`] / [`Hlc`]: a hybrid logical clock; [`merge`]: the deterministic union of event logs. +//! - [`revoke`] / [`RevocationSet`]: withdrawing a subkey (v1.1); [`BackupSecret`]: sealing an app's backup. +//! +//! Pure: no I/O, no network, no clock. Time is always a parameter (Unix seconds for certs, milliseconds for +//! the clock). + +mod backup; +mod cert; +mod hlc; +mod id; +mod keys; +mod merge; +mod revoke; + +pub use backup::BackupSecret; +pub use cert::{CERT_MAGIC, CertError, CertRequest, SubkeyCert, certify, match_code}; +pub use hlc::{Clock, ClockError, Hlc}; +pub use id::{Id, IdError}; +pub use keys::{ + CERT_DOMAIN, CREDENTIAL_DOMAIN, EVENT_DOMAIN, MnemonicError, PublicKey, REVOKE_DOMAIN, RevokeSigner, RootKey, + RootSigner, SignError, Signature, Subkey, verify_credential_sig, verify_event_sig, +}; +pub use merge::{Log, LogEvent, Merged, OrderKey, merge}; +pub use revoke::{ + REVOCATION_MAGIC, REVOCATION_PART_MAX, REVOCATION_PARTS_MAX, Revocation, RevocationError, RevocationSet, revoke, +}; + +use sha2::{Digest, Sha256}; + +/// SHA-256 of `bytes`: the hash in an event's order key. +pub fn hash(bytes: &[u8]) -> [u8; 32] { + Sha256::digest(bytes).into() +} + +/// A cursor over bytes being decoded. Every read checks the length; nothing panics. +pub(crate) struct Reader<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> Reader<'a> { + pub(crate) fn new(bytes: &'a [u8]) -> Self { + Reader { bytes, pos: 0 } + } + + pub(crate) fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let end = self.pos.checked_add(n)?; + let s = self.bytes.get(self.pos..end)?; + self.pos = end; + Some(s) + } + + pub(crate) fn array(&mut self) -> Option<[u8; N]> { + self.take(N)?.try_into().ok() + } + + pub(crate) fn u8(&mut self) -> Option { + Some(self.take(1)?[0]) + } + + pub(crate) fn u64(&mut self) -> Option { + Some(u64::from_be_bytes(self.array()?)) + } + + pub(crate) fn is_empty(&self) -> bool { + self.pos == self.bytes.len() + } +} diff --git a/crates/tessera/src/merge.rs b/crates/tessera/src/merge.rs new file mode 100644 index 0000000..857990a --- /dev/null +++ b/crates/tessera/src/merge.rs @@ -0,0 +1,108 @@ +//! The deterministic merge of event logs (docs/TESSERA.md §7). + +use crate::{Hlc, PublicKey}; +use std::collections::BTreeMap; + +/// Where an event sits in every log: by clock, then author, then the hash of its bytes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct OrderKey { + pub hlc: Hlc, + pub author: PublicKey, + /// SHA-256 of the encoded event ([`crate::hash`]). + pub hash: [u8; 32], +} + +/// An event a log can hold. `order_key` must be derived from `encoded`, so equal bytes give equal keys. +pub trait LogEvent { + fn order_key(&self) -> OrderKey; + fn encoded(&self) -> &[u8]; +} + +/// Verified events, each once, sorted by order key. +#[derive(Clone, Debug)] +pub struct Log { + events: Vec, +} + +impl Default for Log { + fn default() -> Self { + Log { events: Vec::new() } + } +} + +impl Log { + pub fn new() -> Log { + Log::default() + } + + /// A log read back from the app's own storage, whose events were verified when they arrived. + /// Sorts and de-duplicates them. + pub fn from_stored(events: Vec) -> Log { + let map: BTreeMap = events.into_iter().map(|e| (e.order_key(), e)).collect(); + Log { events: map.into_values().collect() } + } + + pub fn events(&self) -> &[E] { + &self.events + } + + pub fn len(&self) -> usize { + self.events.len() + } + + pub fn is_empty(&self) -> bool { + self.events.is_empty() + } + + pub fn contains(&self, hash: &[u8; 32]) -> bool { + self.events.iter().any(|e| e.order_key().hash == *hash) + } + + /// `u32 length ‖ encoded event` for each event, in order. + pub fn to_bytes(&self) -> Vec { + let mut out = Vec::new(); + for e in &self.events { + let b = e.encoded(); + out.extend_from_slice(&(b.len() as u32).to_be_bytes()); + out.extend_from_slice(b); + } + out + } +} + +/// The result of [`merge`]. +#[derive(Debug)] +pub struct Merged { + pub log: Log, + /// How many events were new. + pub added: usize, + /// Events that failed `verify`, each with its reason. None of them is in `log`. + pub rejected: Vec<(E, R)>, +} + +/// The union of `log` and the events of `batch` that pass `verify`, de-duplicated and ordered. Events +/// already in `log` are not verified again. Any order and any repetition of the same batches gives the same +/// log. +pub fn merge( + log: &Log, + batch: impl IntoIterator, + mut verify: impl FnMut(&E) -> Result<(), R>, +) -> Merged { + let mut map: BTreeMap = log.events.iter().map(|e| (e.order_key(), e.clone())).collect(); + let mut added = 0; + let mut rejected = Vec::new(); + for e in batch { + let key = e.order_key(); + if map.contains_key(&key) { + continue; + } + match verify(&e) { + Ok(()) => { + map.insert(key, e); + added += 1; + } + Err(why) => rejected.push((e, why)), + } + } + Merged { log: Log { events: map.into_values().collect() }, added, rejected } +} diff --git a/crates/tessera/src/revoke.rs b/crates/tessera/src/revoke.rs new file mode 100644 index 0000000..46bc286 --- /dev/null +++ b/crates/tessera/src/revoke.rs @@ -0,0 +1,227 @@ +//! Revocation (`TRV1`, docs/TESSERA.md §12, docs/V1_1.md §1): the root withdraws a subkey and names exactly +//! which of its events stay valid. Every other event by that subkey is rejected, whatever time it claims, so +//! a stolen subkey cannot backdate into its cert's validity. + +use crate::keys::{RevokeSigner, SignError, verify_revocation_sig}; +use crate::{PublicKey, Reader, Signature}; +use data_encoding::BASE64URL_NOPAD; +use std::collections::{BTreeMap, BTreeSet}; + +pub const REVOCATION_MAGIC: &[u8; 4] = b"TRV1"; +/// Hashes per statement: one statement fits in one event (256 KiB payload) with room to spare. +pub const REVOCATION_PART_MAX: usize = 7_000; +/// At most this many parts: 1.8 million events per revoked subkey per group. +pub const REVOCATION_PARTS_MAX: usize = 256; + +/// One root-signed revocation statement (one part of it, if the list is long). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Revocation { + root: PublicKey, + subkey: PublicKey, + revoked_at: u64, + part: u16, + parts: u16, + accepted: Vec<[u8; 32]>, + sig: Signature, +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum RevocationError { + #[error("malformed revocation: {0}")] + Malformed(&'static str), + #[error("the revocation belongs to another identity")] + WrongRoot, + #[error("the revocation's root is not a member of this group")] + UnknownRoot, + #[error("the revocation's signature is not valid (tampered)")] + BadSignature, + #[error("the root did not sign: {0}")] + Sign(SignError), + #[error("too many events to keep in one revocation")] + TooLarge, + #[error("written by a revoked key, and not among the events its revocation kept")] + Revoked, +} + +fn tbs(root: &PublicKey, subkey: &PublicKey, revoked_at: u64, part: u16, parts: u16, accepted: &[[u8; 32]]) -> Vec { + let mut out = Vec::with_capacity(4 + 64 + 8 + 4 + 4 + accepted.len() * 32); + out.extend_from_slice(REVOCATION_MAGIC); + out.extend_from_slice(root.as_bytes()); + out.extend_from_slice(subkey.as_bytes()); + out.extend_from_slice(&revoked_at.to_be_bytes()); + out.extend_from_slice(&part.to_be_bytes()); + out.extend_from_slice(&parts.to_be_bytes()); + out.extend_from_slice(&(accepted.len() as u32).to_be_bytes()); + for h in accepted { + out.extend_from_slice(h); + } + out +} + +/// Has `signer` revoke `subkey` at `revoked_at` (Unix seconds), keeping the events whose hashes are in +/// `accepted` (deduplicated and sorted here). A long list comes back as several parts, each signed. +pub fn revoke( + signer: &impl RevokeSigner, + subkey: PublicKey, + revoked_at: u64, + accepted: Vec<[u8; 32]>, +) -> Result, RevocationError> { + let sorted: Vec<[u8; 32]> = accepted.into_iter().collect::>().into_iter().collect(); + let chunks: Vec<&[[u8; 32]]> = + if sorted.is_empty() { vec![&[][..]] } else { sorted.chunks(REVOCATION_PART_MAX).collect() }; + if chunks.len() > REVOCATION_PARTS_MAX { + return Err(RevocationError::TooLarge); + } + let root = signer.root_public(); + let parts = chunks.len() as u16; + chunks + .into_iter() + .enumerate() + .map(|(i, chunk)| { + let t = tbs(&root, &subkey, revoked_at, i as u16, parts, chunk); + let sig = signer.sign_revocation_tbs(&t).map_err(RevocationError::Sign)?; + let r = Revocation { root, subkey, revoked_at, part: i as u16, parts, accepted: chunk.to_vec(), sig }; + r.verify(&root)?; + Ok(r) + }) + .collect() +} + +impl Revocation { + pub fn root(&self) -> PublicKey { + self.root + } + + pub fn subkey(&self) -> PublicKey { + self.subkey + } + + pub fn revoked_at(&self) -> u64 { + self.revoked_at + } + + /// This part's hashes, sorted. + pub fn accepted(&self) -> &[[u8; 32]] { + &self.accepted + } + + /// The bytes the root signs (after `REVOKE_DOMAIN`). + pub fn tbs(&self) -> Vec { + tbs(&self.root, &self.subkey, self.revoked_at, self.part, self.parts, &self.accepted) + } + + /// Checks the statement against the root the caller trusts. + pub fn verify(&self, root: &PublicKey) -> Result<(), RevocationError> { + if self.root != *root { + return Err(RevocationError::WrongRoot); + } + if !verify_revocation_sig(&self.root, &self.tbs(), &self.sig) { + return Err(RevocationError::BadSignature); + } + Ok(()) + } + + pub fn to_bytes(&self) -> Vec { + let mut out = self.tbs(); + out.extend_from_slice(self.sig.as_bytes()); + out + } + + /// base64url without padding, for JSON (the Custos pipe). + pub fn to_text(&self) -> String { + BASE64URL_NOPAD.encode(&self.to_bytes()) + } + + pub fn from_text(s: &str) -> Result { + let b = BASE64URL_NOPAD.decode(s.as_bytes()).map_err(|_| RevocationError::Malformed("not base64url"))?; + Revocation::from_bytes(&b) + } + + /// Strict: the magic, every length, sorted unique hashes, a part inside its count, no trailing bytes. + pub fn from_bytes(b: &[u8]) -> Result { + let m = RevocationError::Malformed; + let mut r = Reader::new(b); + if r.take(4) != Some(REVOCATION_MAGIC.as_slice()) { + return Err(m("not a TRV1 revocation")); + } + let root = PublicKey::from_bytes(r.array().ok_or(m("truncated"))?); + let subkey = PublicKey::from_bytes(r.array().ok_or(m("truncated"))?); + let revoked_at = r.u64().ok_or(m("truncated"))?; + let part = u16::from_be_bytes(r.array().ok_or(m("truncated"))?); + let parts = u16::from_be_bytes(r.array().ok_or(m("truncated"))?); + if parts == 0 || part >= parts || parts as usize > REVOCATION_PARTS_MAX { + return Err(m("a part outside its count")); + } + let count = u32::from_be_bytes(r.array().ok_or(m("truncated"))?) as usize; + if count > REVOCATION_PART_MAX { + return Err(m("too many hashes in one part")); + } + let mut accepted = Vec::with_capacity(count); + for _ in 0..count { + let h: [u8; 32] = r.array().ok_or(m("truncated"))?; + if accepted.last().is_some_and(|prev: &[u8; 32]| *prev >= h) { + return Err(m("hashes not sorted and unique")); + } + accepted.push(h); + } + let sig = Signature::from_bytes(r.array().ok_or(m("truncated"))?); + if !r.is_empty() { + return Err(m("trailing bytes")); + } + Ok(Revocation { root, subkey, revoked_at, part, parts, accepted, sig }) + } +} + +/// One statement being collected: its parts so far. +#[derive(Default)] +struct Statement { + parts: u16, + have: BTreeSet, + accepted: BTreeSet<[u8; 32]>, +} + +/// The revocations a group's log holds, applied to its events. The same statements give the same answers in +/// any order: parts of one statement add up, separate statements for one subkey keep only what all keep. +#[derive(Default)] +pub struct RevocationSet { + /// (subkey, revoked_at, parts) → the statement's parts. + statements: BTreeMap<(PublicKey, u64, u16), Statement>, +} + +impl RevocationSet { + /// Adds one part, after checking it is signed by its root and that the root is one of the group's. + pub fn add(&mut self, r: Revocation, group_roots: &[PublicKey]) -> Result<(), RevocationError> { + if !group_roots.contains(&r.root) { + return Err(RevocationError::UnknownRoot); + } + r.verify(&r.root)?; + let s = self.statements.entry((r.subkey, r.revoked_at, r.parts)).or_default(); + s.parts = r.parts; + s.have.insert(r.part); + s.accepted.extend(r.accepted); + Ok(()) + } + + fn complete(&self, subkey: &PublicKey) -> impl Iterator { + self.statements + .iter() + .filter(move |((k, _, _), s)| k == subkey && s.have.len() == s.parts as usize) + .map(|(_, s)| s) + } + + /// Whether a complete revocation of `subkey` is in force. + pub fn is_revoked(&self, subkey: &PublicKey) -> bool { + self.complete(subkey).next().is_some() + } + + /// Whether the event `hash` by `author` stays valid: yes unless a complete revocation of `author` is in + /// force and does not list it (every one in force must list it). + pub fn check(&self, author: &PublicKey, hash: &[u8; 32]) -> Result<(), RevocationError> { + for s in self.complete(author) { + if !s.accepted.contains(hash) { + return Err(RevocationError::Revoked); + } + } + Ok(()) + } +} diff --git a/crates/tessera/tests/mandatory.rs b/crates/tessera/tests/mandatory.rs new file mode 100644 index 0000000..f4fdd09 --- /dev/null +++ b/crates/tessera/tests/mandatory.rs @@ -0,0 +1,332 @@ +//! The mandatory tests for tessera (docs/TESSERA.md). Written before the code. + +use proptest::prelude::*; +use tessera::{ + CertError, CertRequest, Clock, ClockError, Hlc, Id, Log, LogEvent, OrderKey, PublicKey, RootKey, RootSigner, + Subkey, SubkeyCert, certify, match_code, merge, +}; + +/// `abandon` × 23 + `art`: the BIP39 mnemonic of 32 zero bytes. +const ZERO_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \ + abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art"; +/// Its root public key (docs/TESSERA.md §9). CustosPublic pins the same value. +const ROOT_PUB_ZERO: &str = "vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs"; +/// The match code of the subkey `07` × 32. +const MATCH_SEVENS: &str = "016810"; + +const DAY: u64 = 86_400; +const NOW: u64 = 1_793_000_000; + +fn root() -> RootKey { + RootKey::from_mnemonic(ZERO_MNEMONIC).unwrap() +} + +fn other_root() -> RootKey { + RootKey::from_mnemonic( + "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful \ + legal winner thank year wave sausage worth title", + ) + .unwrap() +} + +fn request(sub: &Subkey) -> CertRequest { + CertRequest { + subkey: sub.public(), + app_id: Id::new("fiscus").unwrap(), + purpose: Id::new("sync").unwrap(), + not_before: NOW - DAY, + not_after: NOW + 365 * DAY, + } +} + +// ---------- mnemonic round trip ---------- + +#[test] +fn the_same_mnemonic_gives_the_same_root_every_time() { + let a = root().public(); + for _ in 0..3 { + assert_eq!(root().public(), a); + } + assert_eq!(a.to_string(), ROOT_PUB_ZERO, "the pinned vector"); + // Spacing and case do not change the words. + let messy = format!(" {} ", ZERO_MNEMONIC.to_uppercase().replace(' ', " ")); + assert_eq!(RootKey::from_mnemonic(&messy).unwrap().public(), a); + assert_ne!(other_root().public(), a); +} + +#[test] +fn a_wrong_mnemonic_is_refused() { + let bad_checksum = ZERO_MNEMONIC.replace(" art", " abandon"); + assert!(RootKey::from_mnemonic(&bad_checksum).is_err()); + assert!(RootKey::from_mnemonic("abandon abandon").is_err()); + assert!(RootKey::from_mnemonic(&ZERO_MNEMONIC.replace(" art", " notaword")).is_err()); + // 12 words is a valid BIP39 mnemonic, but a Domi root is always 24. + let twelve = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + assert!(RootKey::from_mnemonic(twelve).is_err()); +} + +// ---------- certificates ---------- + +#[test] +fn a_valid_cert_passes_and_round_trips() { + let sub = Subkey::from_seed(&[1; 32]); + let cert = certify(&root(), &request(&sub)).unwrap(); + assert_eq!(cert.verify(&root().public(), NOW), Ok(())); + let back = SubkeyCert::from_bytes(&cert.to_bytes()).unwrap(); + assert_eq!(back, cert); + assert_eq!(back.subkey(), sub.public()); + assert_eq!(back.app_id().as_str(), "fiscus"); + assert_eq!(back.purpose().as_str(), "sync"); + assert_eq!(SubkeyCert::from_text(&cert.to_text()).unwrap(), cert); +} + +#[test] +fn expired_and_not_yet_valid_certs_are_rejected() { + let sub = Subkey::from_seed(&[1; 32]); + let cert = certify(&root(), &request(&sub)).unwrap(); + let r = root().public(); + assert_eq!(cert.verify(&r, NOW - DAY - 1), Err(CertError::NotYetValid)); + assert_eq!(cert.verify(&r, NOW - DAY), Ok(()), "not_before is inclusive"); + assert_eq!(cert.verify(&r, NOW + 365 * DAY - 1), Ok(())); + assert_eq!(cert.verify(&r, NOW + 365 * DAY), Err(CertError::Expired), "not_after is exclusive"); +} + +#[test] +fn a_cert_from_another_root_is_rejected() { + let sub = Subkey::from_seed(&[1; 32]); + let cert = certify(&other_root(), &request(&sub)).unwrap(); + assert_eq!(cert.verify(&root().public(), NOW), Err(CertError::WrongRoot)); +} + +#[test] +fn every_tampered_byte_is_rejected() { + let sub = Subkey::from_seed(&[1; 32]); + let cert = certify(&root(), &request(&sub)).unwrap(); + let bytes = cert.to_bytes(); + for i in 0..bytes.len() { + for bit in 0..8 { + let mut b = bytes.clone(); + b[i] ^= 1 << bit; + if let Ok(c) = SubkeyCert::from_bytes(&b) { + assert!(c.verify(&root().public(), NOW).is_err(), "byte {i} bit {bit} accepted"); + } + } + } +} + +#[test] +fn a_signer_claiming_another_root_cannot_make_a_valid_cert() { + // A RootSigner whose public key does not match its signatures. + struct Liar(RootKey, PublicKey); + impl RootSigner for Liar { + fn root_public(&self) -> PublicKey { + self.1 + } + fn sign_cert_tbs(&self, tbs: &[u8]) -> Result { + self.0.sign_cert_tbs(tbs) + } + } + let sub = Subkey::from_seed(&[1; 32]); + let liar = Liar(other_root(), root().public()); + assert!(certify(&liar, &request(&sub)).is_err(), "certify checks the signature it got back"); +} + +#[test] +fn a_root_key_signs_only_cert_shaped_messages() { + assert!(root().sign_cert_tbs(b"pay 100 CZK to mallory").is_err()); + let sub = Subkey::from_seed(&[1; 32]); + // A tbs naming another root is refused too. + let tbs = request(&sub).tbs(&other_root().public()); + assert!(root().sign_cert_tbs(&tbs).is_err()); +} + +#[test] +fn malformed_certs_are_rejected_on_decoding() { + let sub = Subkey::from_seed(&[1; 32]); + let good = certify(&root(), &request(&sub)).unwrap().to_bytes(); + assert!(SubkeyCert::from_bytes(&good[..good.len() - 1]).is_err()); + let mut long = good.clone(); + long.push(0); + assert!(SubkeyCert::from_bytes(&long).is_err(), "trailing bytes"); + let mut magic = good.clone(); + magic[0] = b'X'; + assert!(SubkeyCert::from_bytes(&magic).is_err()); + let mut empty_validity = request(&sub); + empty_validity.not_after = empty_validity.not_before; + assert!(certify(&root(), &empty_validity).is_err()); + for bad in ["", "Fiscus", "-fiscus", "fiscus-", "fis cus", "fiscus/x", &"a".repeat(33)] { + assert!(Id::new(bad).is_err(), "{bad:?}"); + } + assert!(Id::new(&"a".repeat(32)).is_ok()); +} + +// ---------- match code ---------- + +#[test] +fn match_code_vector() { + let code = match_code(&PublicKey::from_bytes([7; 32])); + assert_eq!(code.len(), 6); + assert!(code.bytes().all(|b| b.is_ascii_digit())); + assert_eq!(code, MATCH_SEVENS); + assert_ne!(match_code(&PublicKey::from_bytes([8; 32])), code); +} + +// ---------- secrets stay secret ---------- + +#[test] +fn event_and_credential_signatures_do_not_cross() { + let sub = Subkey::from_seed(&[1; 32]); + let sig = sub.sign_credential_tbs(b"keys"); + assert!(tessera::verify_credential_sig(&sub.public(), b"keys", &sig)); + assert!(!tessera::verify_event_sig(&sub.public(), b"keys", &sig), "a credential signature is never an event"); + let ev = sub.sign_event_tbs(b"keys"); + assert!(!tessera::verify_credential_sig(&sub.public(), b"keys", &ev)); +} + +#[test] +fn secret_types_print_redacted() { + let s = format!("{:?} {:?}", root(), Subkey::from_seed(&[1; 32])); + assert_eq!(s, "RootKey([redacted]) Subkey([redacted])"); +} + +// ---------- hybrid logical clock ---------- + +#[test] +fn the_clock_never_goes_backwards() { + let mut c = Clock::default(); + let a = c.tick(1000).unwrap(); + let b = c.tick(1000).unwrap(); + let d = c.tick(500).unwrap(); // the wall clock jumped back + let e = c.tick(2000).unwrap(); + assert!(a < b && b < d && d < e); + assert_eq!(e, Hlc { wall: 2000, logical: 0 }); + assert_eq!(Hlc::from_bytes(&e.to_bytes()), e); +} + +#[test] +fn the_clock_follows_a_remote_clock_within_the_drift() { + let mut c = Clock::with_max_drift(60_000); + c.tick(1000).unwrap(); + let remote = Hlc { wall: 5000, logical: 7 }; + let seen = c.observe(remote, 1000).unwrap(); + assert!(seen > remote); + assert!(c.tick(1000).unwrap() > seen); + assert_eq!(c.observe(Hlc { wall: 1000 + 60_001, logical: 0 }, 1000), Err(ClockError::TooFarAhead)); +} + +#[test] +fn the_logical_counter_does_not_wrap() { + let mut c = Clock::default(); + c.observe(Hlc { wall: 10, logical: u32::MAX - 1 }, 10).unwrap(); + assert_eq!(c.tick(10), Err(ClockError::Overflow)); + // A later wall clock resets the counter. + assert_eq!(c.tick(11), Ok(Hlc { wall: 11, logical: 0 })); +} + +// ---------- merge ---------- + +/// A minimal event: its bytes, an author and a clock. Valid unless `bad`. +#[derive(Clone, Debug)] +struct Ev { + bytes: Vec, + key: OrderKey, + bad: bool, +} + +impl Ev { + fn new(author: u8, wall: u64, logical: u32, body: u8, bad: bool) -> Ev { + let bytes = vec![author, (wall % 256) as u8, logical as u8, body, bad as u8]; + let key = OrderKey { + hlc: Hlc { wall, logical }, + author: PublicKey::from_bytes([author; 32]), + hash: tessera::hash(&bytes), + }; + Ev { bytes, key, bad } + } +} + +impl LogEvent for Ev { + fn order_key(&self) -> OrderKey { + self.key + } + fn encoded(&self) -> &[u8] { + &self.bytes + } +} + +fn check(e: &Ev) -> Result<(), &'static str> { + if e.bad { Err("bad signature") } else { Ok(()) } +} + +fn arb_events() -> impl Strategy> { + // Few authors and clocks, so ties on (hlc, author) happen and the hash decides. + prop::collection::vec((0u8..3, 0u64..4, 0u32..2, any::(), prop::bool::weighted(0.15)), 1..40) + .prop_map(|v| v.into_iter().map(|(a, w, l, b, bad)| Ev::new(a, w, l, b, bad)).collect()) +} + +/// Merges `batches` into an empty log one after another. +fn merge_all(batches: &[Vec]) -> Log { + let mut log = Log::new(); + for b in batches { + log = merge(&log, b.iter().cloned(), check).log; + } + log +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn merge_is_order_independent_and_idempotent( + events in arb_events(), + split in prop::collection::vec(0usize..4, 40), + perm_seed in any::(), + dups in prop::collection::vec(any::(), 0..10), + ) { + // Split into up to 4 batches, then shuffle the batches and the events in them, and duplicate some. + let mut batches: Vec> = vec![Vec::new(); 4]; + for (i, e) in events.iter().enumerate() { + batches[split[i % split.len()]].push(e.clone()); + } + for d in &dups { + let e = d.get(&events).clone(); + batches[d.index(4)].push(e); + } + let reference = merge_all(std::slice::from_ref(&events)); + + let mut shuffled = batches.clone(); + let mut s = perm_seed; + for b in shuffled.iter_mut() { + for i in (1..b.len()).rev() { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + b.swap(i, (s >> 33) as usize % (i + 1)); + } + } + shuffled.rotate_left((perm_seed % 4) as usize); + let merged = merge_all(&shuffled); + prop_assert_eq!(merged.to_bytes(), reference.to_bytes()); + + // Merging everything again changes nothing. + let again = merge(&merged, batches.concat(), check); + prop_assert_eq!(again.added, 0); + prop_assert_eq!(again.log.to_bytes(), reference.to_bytes()); + + // Only valid events, each once, in order-key order. + let keys: Vec = merged.events().iter().map(|e| e.order_key()).collect(); + prop_assert!(keys.windows(2).all(|w| w[0] < w[1])); + prop_assert!(merged.events().iter().all(|e| !e.bad)); + let valid: std::collections::BTreeSet<_> = events.iter().filter(|e| !e.bad).map(|e| e.key.hash).collect(); + prop_assert_eq!(merged.len(), valid.len()); + } +} + +#[test] +fn rejected_events_come_back_with_their_reason() { + let good = Ev::new(1, 1, 0, 1, false); + let bad = Ev::new(1, 2, 0, 2, true); + let m = merge(&Log::new(), vec![good.clone(), bad.clone(), bad.clone()], check); + assert_eq!(m.added, 1); + assert_eq!(m.log.len(), 1); + assert_eq!(m.rejected.len(), 2); + assert!(m.rejected.iter().all(|(e, why)| e.key == bad.key && *why == "bad signature")); +} diff --git a/crates/tessera/tests/revocation.rs b/crates/tessera/tests/revocation.rs new file mode 100644 index 0000000..6d81f6f --- /dev/null +++ b/crates/tessera/tests/revocation.rs @@ -0,0 +1,204 @@ +//! v1.1a: revocation (`TRV1`, docs/V1_1.md §1) and the backup secret (§3). +//! +//! - A revocation is root-signed in its own domain; the root's signer refuses to sign it as a cert and the +//! other way round. +//! - It keeps exactly the listed events of the revoked subkey; every other event by that subkey is +//! rejected, whatever time it claims. Unrelated authors are untouched. +//! - Split statements count only when complete; the result does not depend on the order they arrive in; +//! two statements for one subkey keep only what both keep. +//! - The backup secret is the same from the 24 words every time, differs per app, and seals so that only +//! the same secret opens. + +use proptest::prelude::*; +use tessera::{ + BackupSecret, CertRequest, Id, PublicKey, Revocation, RevocationError, RevocationSet, RevokeSigner, RootKey, + RootSigner, Subkey, hash, revoke, +}; + +fn root(n: u8) -> RootKey { + let m = bip39::Mnemonic::from_entropy(&[n; 32]).unwrap(); + RootKey::from_mnemonic(&m.to_string()).unwrap() +} + +fn h(n: u32) -> [u8; 32] { + hash(&n.to_be_bytes()) +} + +const T: u64 = 1_793_700_000; + +#[test] +fn a_revocation_round_trips_and_verifies_under_its_root() { + let r = root(1); + let sub = Subkey::from_seed(&[5; 32]).public(); + let parts = revoke(&r, sub, T, vec![h(3), h(1), h(2), h(1)]).unwrap(); + assert_eq!(parts.len(), 1); + let p = &parts[0]; + assert_eq!((p.root(), p.subkey(), p.revoked_at()), (r.public(), sub, T)); + assert_eq!( + p.accepted(), + &[h(1), h(2), h(3)].iter().copied().collect::>().into_iter().collect::>() + ); + let back = Revocation::from_bytes(&p.to_bytes()).unwrap(); + assert_eq!(&back, p); + assert!(back.verify(&r.public()).is_ok()); + assert_eq!(back.verify(&root(2).public()), Err(RevocationError::WrongRoot)); +} + +#[test] +fn a_tampered_or_malformed_revocation_is_refused() { + let r = root(1); + let bytes = revoke(&r, Subkey::from_seed(&[5; 32]).public(), T, vec![h(1)]).unwrap()[0].to_bytes(); + for i in [5, 40, 70, 80, bytes.len() - 1] { + let mut b = bytes.clone(); + b[i] ^= 1; + let bad = Revocation::from_bytes(&b).map(|x| x.verify(&r.public())); + assert!(!matches!(bad, Ok(Ok(()))), "flip at {i} still verifies"); + } + for cut in 0..bytes.len() { + assert!(Revocation::from_bytes(&bytes[..cut]).is_err(), "a truncation at {cut} decoded"); + } + let mut extra = bytes.clone(); + extra.push(0); + assert!(Revocation::from_bytes(&extra).is_err(), "trailing bytes"); + let mut as_cert = bytes; + as_cert[..4].copy_from_slice(b"TSC1"); + assert!(Revocation::from_bytes(&as_cert).is_err(), "a cert is not a revocation"); +} + +#[test] +fn a_root_signs_a_revocation_and_a_cert_only_in_their_own_domains() { + let r = root(1); + let sub = Subkey::from_seed(&[5; 32]).public(); + let req = CertRequest::standard(sub, Id::new("fiscus").unwrap(), Id::new("sync").unwrap(), T); + let cert_tbs = req.tbs(&r.public()); + assert!(r.sign_revocation_tbs(&cert_tbs).is_err(), "a cert's tbs is not signed as a revocation"); + let rev_tbs = revoke(&r, sub, T, vec![]).unwrap()[0].tbs(); + assert!(r.sign_cert_tbs(&rev_tbs).is_err(), "a revocation's tbs is not signed as a cert"); + let other = revoke(&root(2), sub, T, vec![]).unwrap()[0].tbs(); + assert!(r.sign_revocation_tbs(&other).is_err(), "a root signs only revocations that name it"); +} + +#[test] +fn only_the_listed_events_of_a_revoked_subkey_stay_valid() { + let r = root(1); + let lost = Subkey::from_seed(&[5; 32]).public(); + let other = Subkey::from_seed(&[6; 32]).public(); + let mut set = RevocationSet::default(); + for p in revoke(&r, lost, T, vec![h(1), h(2)]).unwrap() { + set.add(p, &[r.public()]).unwrap(); + } + assert!(set.check(&lost, &h(1)).is_ok()); + assert!(set.check(&lost, &h(2)).is_ok()); + assert!(set.check(&lost, &h(3)).is_err(), "written after, or backdated: rejected either way"); + assert!(set.check(&other, &h(3)).is_ok(), "other authors are untouched"); + assert!(set.is_revoked(&lost) && !set.is_revoked(&other)); +} + +#[test] +fn a_revocation_from_a_root_outside_the_group_is_refused() { + let lost = Subkey::from_seed(&[5; 32]).public(); + let mut set = RevocationSet::default(); + let p = revoke(&root(9), lost, T, vec![]).unwrap().remove(0); + assert_eq!(set.add(p, &[root(1).public()]), Err(RevocationError::UnknownRoot)); + assert!(set.check(&lost, &h(1)).is_ok()); +} + +#[test] +fn a_long_list_is_split_and_counts_only_when_complete() { + let r = root(1); + let lost = Subkey::from_seed(&[5; 32]).public(); + let kept: Vec<[u8; 32]> = (0..tessera::REVOCATION_PART_MAX as u32 * 2 + 10).map(h).collect(); + let parts = revoke(&r, lost, T, kept.clone()).unwrap(); + assert_eq!(parts.len(), 3); + for p in &parts { + assert!(p.to_bytes().len() < 240 * 1024, "a part fits in one event"); + } + let mut set = RevocationSet::default(); + set.add(parts[0].clone(), &[r.public()]).unwrap(); + set.add(parts[2].clone(), &[r.public()]).unwrap(); + assert!(set.check(&lost, &h(u32::MAX)).is_ok(), "incomplete: not in force yet"); + set.add(parts[1].clone(), &[r.public()]).unwrap(); + assert!(set.check(&lost, &h(u32::MAX)).is_err(), "complete: in force"); + assert!(kept.iter().all(|k| set.check(&lost, k).is_ok())); +} + +#[test] +fn two_revocations_of_one_subkey_keep_only_what_both_keep() { + let r = root(1); + let lost = Subkey::from_seed(&[5; 32]).public(); + let mut set = RevocationSet::default(); + for p in revoke(&r, lost, T, vec![h(1), h(2), h(3)]).unwrap() { + set.add(p, &[r.public()]).unwrap(); + } + for p in revoke(&r, lost, T + 60, vec![h(2), h(3), h(4)]).unwrap() { + set.add(p, &[r.public()]).unwrap(); + } + let kept: Vec = (1..=4).filter(|n| set.check(&lost, &h(*n)).is_ok()).collect(); + assert_eq!(kept, vec![2, 3], "a later statement never widens what is kept"); +} + +proptest! { + #[test] + fn the_result_does_not_depend_on_arrival_order(seed in any::(), keep in proptest::collection::vec(0u32..40, 0..30)) { + let r = root(1); + let lost = Subkey::from_seed(&[5; 32]).public(); + let mut parts = revoke(&r, lost, T, keep.iter().map(|n| h(*n)).collect()).unwrap(); + parts.extend(revoke(&r, lost, T + 1, (0..40).filter(|n| n % 3 != 0).map(h).collect()).unwrap()); + let build = |order: &[Revocation]| { + let mut set = RevocationSet::default(); + for p in order { + set.add(p.clone(), &[r.public()]).unwrap(); + } + (0..40).map(|n| set.check(&lost, &h(n)).is_ok()).collect::>() + }; + let a = build(&parts); + let mut shuffled = parts.clone(); + let mut s = seed; + for i in (1..shuffled.len()).rev() { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + shuffled.swap(i, (s >> 33) as usize % (i + 1)); + } + prop_assert_eq!(a, build(&shuffled)); + } +} + +#[test] +fn the_backup_secret_comes_back_from_the_words_and_differs_per_app() { + let fiscus = Id::new("fiscus").unwrap(); + let a = root(1).backup_secret(&fiscus); + let b = root(1).backup_secret(&fiscus); + let other_app = root(1).backup_secret(&Id::new("calenda").unwrap()); + let other_person = root(2).backup_secret(&fiscus); + let nonce = [7u8; 24]; + let sealed = a.seal(&nonce, b"aad", b"the self group's log"); + assert_eq!(b.open(b"aad", &sealed).as_deref(), Some(b"the self group's log".as_slice())); + assert_eq!(b.open(b"other aad", &sealed), None); + assert_eq!(other_app.open(b"aad", &sealed), None); + assert_eq!(other_person.open(b"aad", &sealed), None); + assert!(!sealed.windows(4).any(|w| w == b"self"), "sealed, not readable"); + assert_ne!(*a.mailbox_seed(), *other_app.mailbox_seed()); + assert_eq!(*a.mailbox_seed(), *b.mailbox_seed()); + // An app gets the 32 bytes from Custos; nothing reads them back out. + let from_custos = BackupSecret::from_bytes([1u8; 32]); + assert_eq!(from_custos.open(b"", &from_custos.seal(&nonce, b"", b"x")).as_deref(), Some(b"x".as_slice())); + assert_eq!(format!("{from_custos:?}"), "BackupSecret([redacted])"); +} + +#[test] +fn the_backup_secret_test_vector() { + // docs/TESSERA.md §12: the zero-entropy mnemonic, app "fiscus". Custos derives the same. + let s = root(0).backup_secret(&Id::new("fiscus").unwrap()); + let mailbox = data_encoding::BASE64URL_NOPAD.encode(s.mailbox_seed().as_ref()); + let sealed = data_encoding::BASE64URL_NOPAD.encode(&s.seal(&[0u8; 24], b"", b"")); + assert_eq!((mailbox.as_str(), sealed.as_str()), (VECTOR_MAILBOX, VECTOR_SEALED_EMPTY)); +} + +const VECTOR_MAILBOX: &str = "IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU"; +const VECTOR_SEALED_EMPTY: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAci_JRbtsx5prR83KT9Y7LA"; + +#[allow(dead_code)] +fn _signer_bound(_: &impl RevokeSigner) {} +#[allow(dead_code)] +fn _root_signer(_: &impl RootSigner) {} +#[allow(dead_code)] +fn _key(_: PublicKey) {} diff --git a/crates/tessera/tests/surface.rs b/crates/tessera/tests/surface.rs new file mode 100644 index 0000000..c9296d7 --- /dev/null +++ b/crates/tessera/tests/surface.rs @@ -0,0 +1,150 @@ +//! No key export: no public API of tessera returns private key bytes. +//! +//! - Compile time: the secret types implement none of the traits that would hand out their bytes. +//! - The API surface is locked: every `pub fn` in `src/` is listed here. A new public function fails this +//! test until someone has checked that it returns no secret and added it to the list. + +use static_assertions::assert_not_impl_any; +use tessera::{RootKey, Subkey}; + +assert_not_impl_any!(RootKey: Clone, AsRef<[u8]>, std::ops::Deref, Into<[u8; 32]>, Into>, std::fmt::Display); +assert_not_impl_any!(Subkey: Clone, AsRef<[u8]>, std::ops::Deref, Into<[u8; 32]>, Into>, std::fmt::Display); + +/// Every public function, as `file: signature` with whitespace collapsed. Each returns only public data. +const SURFACE: &[&str] = &[ + "backup.rs: pub fn from_bytes(b: [u8; 32]) -> BackupSecret", + "backup.rs: pub fn mailbox_seed(&self) -> Zeroizing<[u8; 32]>", + "backup.rs: pub fn open(&self, aad: &[u8], sealed: &[u8]) -> Option>", + "backup.rs: pub fn seal(&self, nonce: &[u8; 24], aad: &[u8], plain: &[u8]) -> Vec", + "cert.rs: pub fn app_id(&self) -> &Id", + "cert.rs: pub fn certify(signer: &impl RootSigner, req: &CertRequest) -> Result", + "cert.rs: pub fn from_bytes(b: &[u8]) -> Result", + "cert.rs: pub fn from_text(s: &str) -> Result", + "cert.rs: pub fn match_code(subkey: &PublicKey) -> String", + "cert.rs: pub fn not_after(&self) -> u64", + "cert.rs: pub fn not_before(&self) -> u64", + "cert.rs: pub fn purpose(&self) -> &Id", + "cert.rs: pub fn root(&self) -> PublicKey", + "cert.rs: pub fn standard(subkey: PublicKey, app_id: Id, purpose: Id, now: u64) -> CertRequest", + "cert.rs: pub fn subkey(&self) -> PublicKey", + "cert.rs: pub fn tbs(&self, root: &PublicKey) -> Vec", + "cert.rs: pub fn to_bytes(&self) -> Vec", + "cert.rs: pub fn to_text(&self) -> String", + "cert.rs: pub fn verify(&self, root: &PublicKey, now: u64) -> Result<(), CertError>", + "hlc.rs: pub fn from_bytes(b: &[u8; 12]) -> Hlc", + "hlc.rs: pub fn last(&self) -> Hlc", + "hlc.rs: pub fn observe(&mut self, remote: Hlc, now: u64) -> Result", + "hlc.rs: pub fn tick(&mut self, now: u64) -> Result", + "hlc.rs: pub fn to_bytes(&self) -> [u8; 12]", + "hlc.rs: pub fn with_max_drift(max_drift_ms: u64) -> Clock", + "id.rs: pub fn as_str(&self) -> &str", + "id.rs: pub fn new(s: &str) -> Result", + "keys.rs: pub fn as_bytes(&self) -> &[u8; 32]", + "keys.rs: pub fn backup_secret(&self, app_id: &crate::Id) -> crate::BackupSecret", + "keys.rs: pub fn as_bytes(&self) -> &[u8; 64]", + "keys.rs: pub fn from_bytes(b: [u8; 32]) -> PublicKey", + "keys.rs: pub fn from_bytes(b: [u8; 64]) -> Signature", + "keys.rs: pub fn from_mnemonic(phrase: &str) -> Result", + "keys.rs: pub fn from_seed(seed: &[u8; 32]) -> Subkey", + "keys.rs: pub fn from_text(s: &str) -> Option", + "keys.rs: pub fn public(&self) -> PublicKey", + "keys.rs: pub fn public(&self) -> PublicKey", + "keys.rs: pub fn sign_credential_tbs(&self, tbs: &[u8]) -> Signature", + "keys.rs: pub fn sign_event_tbs(&self, tbs: &[u8]) -> Signature", + "keys.rs: pub fn verify_credential_sig(subkey: &PublicKey, tbs: &[u8], sig: &Signature) -> bool", + "keys.rs: pub fn verify_event_sig(author: &PublicKey, tbs: &[u8], sig: &Signature) -> bool", + "lib.rs: pub fn hash(bytes: &[u8]) -> [u8; 32]", + "merge.rs: pub fn contains(&self, hash: &[u8; 32]) -> bool", + "merge.rs: pub fn events(&self) -> &[E]", + "merge.rs: pub fn from_stored(events: Vec) -> Log", + "merge.rs: pub fn is_empty(&self) -> bool", + "merge.rs: pub fn len(&self) -> usize", + "merge.rs: pub fn merge( log: &Log, batch: impl IntoIterator, mut verify: impl FnMut(&E) -> Result<(), R>, ) -> Merged", + "merge.rs: pub fn new() -> Log", + "merge.rs: pub fn to_bytes(&self) -> Vec", + "revoke.rs: pub fn accepted(&self) -> &[[u8; 32]]", + "revoke.rs: pub fn add(&mut self, r: Revocation, group_roots: &[PublicKey]) -> Result<(), RevocationError>", + "revoke.rs: pub fn check(&self, author: &PublicKey, hash: &[u8; 32]) -> Result<(), RevocationError>", + "revoke.rs: pub fn from_bytes(b: &[u8]) -> Result", + "revoke.rs: pub fn from_text(s: &str) -> Result", + "revoke.rs: pub fn is_revoked(&self, subkey: &PublicKey) -> bool", + "revoke.rs: pub fn revoke( signer: &impl RevokeSigner, subkey: PublicKey, revoked_at: u64, accepted: Vec<[u8; 32]>, ) -> Result, RevocationError>", + "revoke.rs: pub fn revoked_at(&self) -> u64", + "revoke.rs: pub fn root(&self) -> PublicKey", + "revoke.rs: pub fn subkey(&self) -> PublicKey", + "revoke.rs: pub fn tbs(&self) -> Vec", + "revoke.rs: pub fn to_bytes(&self) -> Vec", + "revoke.rs: pub fn to_text(&self) -> String", + "revoke.rs: pub fn verify(&self, root: &PublicKey) -> Result<(), RevocationError>", +]; + +/// `pub fn` signatures in `src/`, up to the opening brace, whitespace collapsed. +fn public_fns() -> Vec { + let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut out = Vec::new(); + for entry in std::fs::read_dir(&src).unwrap() { + let path = entry.unwrap().path(); + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + let text = std::fs::read_to_string(&path).unwrap(); + let mut rest = text.as_str(); + while let Some(at) = rest.find("pub fn ") { + let sig_and_more = &rest[at..]; + // The first `{` or `;` outside brackets (`[u8; 32]` has a `;` inside). + let mut depth = 0i32; + let end = sig_and_more + .char_indices() + .find(|&(_, c)| { + match c { + '[' | '(' => depth += 1, + ']' | ')' => depth -= 1, + _ => {} + } + depth == 0 && (c == '{' || c == ';') + }) + .unwrap() + .0; + let sig: String = sig_and_more[..end].split_whitespace().collect::>().join(" "); + out.push(format!("{name}: {sig}")); + rest = &sig_and_more[end..]; + } + } + out.sort(); + out +} + +#[test] +fn the_public_surface_is_locked() { + let mut want: Vec = SURFACE.iter().map(|s| s.to_string()).collect(); + want.sort(); + let got = public_fns(); + let new: Vec<_> = got.iter().filter(|s| !want.contains(s)).collect(); + let gone: Vec<_> = want.iter().filter(|s| !got.contains(s)).collect(); + assert!(new.is_empty() && gone.is_empty(), "review the surface.\nnew: {new:#?}\ngone: {gone:#?}"); +} + +#[test] +fn only_public_data_comes_back_as_bytes() { + // The few functions that return raw bytes, and why each is public data. + let allowed = [ + "pub fn as_bytes(&self) -> &[u8; 32]", // PublicKey + "pub fn as_bytes(&self) -> &[u8; 64]", // Signature + "pub fn hash(bytes: &[u8]) -> [u8; 32]", // SHA-256 + "pub fn tbs(&self, root: &PublicKey) -> Vec", // the unsigned cert + "pub fn to_bytes(&self) -> Vec", // cert, log + "pub fn to_bytes(&self) -> [u8; 12]", // Hlc + "pub fn tbs(&self) -> Vec", // the unsigned revocation + "pub fn seal(&self, nonce: &[u8; 24], aad: &[u8], plain: &[u8]) -> Vec", // ciphertext + ]; + // The one secret that comes out, and why: the backup mailbox's access-key seed is a relay credential (it + // lets its holder fetch ciphertext, as an invite token's access key does), never an identity key. + let secret_ok = ["pub fn mailbox_seed(&self) -> Zeroizing<[u8; 32]>"]; + for f in public_fns() { + let sig = f.split_once(": ").unwrap().1; + let returns_bytes = sig.contains("-> [u8") || sig.contains("-> &[u8") || sig.contains("-> Vec"); + assert!(!returns_bytes || allowed.contains(&sig), "returns bytes: {f}"); + assert!( + secret_ok.contains(&sig) || (!sig.contains("SigningKey") && !sig.contains("Zeroizing")), + "exposes a secret type: {f}" + ); + } +} diff --git a/docs/TABELLARIUS.md b/docs/TABELLARIUS.md new file mode 100644 index 0000000..d35fe16 --- /dev/null +++ b/docs/TABELLARIUS.md @@ -0,0 +1,195 @@ +# Tabellarius — the relay and MLS groups (design note, day 2) + +*Tabellarius*: the Roman letter carrier. He carried sealed tablets and could not read them. + +Written before the code. Every app syncs its own encrypted event log through one relay, between your own +devices and between people, without the relay being able to read anything or tell who is who. + +## 1. Layers + +``` +AppEvent { kind, body } the app's change + → TEV1 envelope (docs/TESSERA.md §8) signed by the app's subkey, carries its cert + → TBA1 batch of envelopes one MLS application message + → MLS PrivateMessage (OpenMLS) encrypted to the group's current epoch + → relay mailbox ciphertext, seq, size, time — nothing else +``` + +**Deviation from the plan, on purpose.** The plan put the MLS ciphertext *inside* the envelope. But the +envelope carries the Tessera cert and the author's subkey in the clear, so a relay that stored envelopes would +learn who wrote what, and could link one person's mailboxes through their root key. The privacy rules win: the +envelope travels **inside** MLS. The relay stores only MLS ciphertext. Receivers still verify every envelope +on its own (`Envelope::verify` against the group members' roots), so an event stays attributable and +re-verifiable after it leaves MLS, for example in a history batch for a new device (§6). + +## 2. Identity inside MLS + +- **Ciphersuite** `MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519`. Handshake messages are encrypted + too (`PURE_CIPHERTEXT_WIRE_FORMAT_POLICY`): commits travel as PrivateMessages, so the relay does not learn + who added or removed whom. +- **MLS signature key**: a fresh Ed25519 key per device per group, generated by OpenMLS. The Tessera subkey + never leaves tessera (it has no byte export), so it cannot be the MLS key itself. Instead it vouches for it. +- **Credential** (`BasicCredential`, identity bytes, `TDC1`): + ``` + "TDC1" ‖ u16 len ‖ SubkeyCert ‖ mailbox_key (32) ‖ binding (64) + binding = Ed25519(subkey, "tessera credential v1\0" ‖ mls_signature_key ‖ mailbox_key) (Subkey::sign_credential_tbs) + ``` + A member is accepted only if its cert verifies under its root now, its cert is for the group's app, and the + binding signature by the cert's subkey covers its leaf's MLS signature key and mailbox key. +- **The group's roots** are the roots of its members' certs; `Envelope::verify` uses them. A **self group** + accepts only members whose root is the creator's root (your own devices). +- New members are checked when a commit adds them and, on joining, every member of the Welcome's tree. + A commit that adds an invalid member is not merged; it is reported as rejected. + +## 3. The relay: mailboxes + +A mailbox id is 32 bytes, base64url: +- a **group mailbox** is `SHA-256("tabellarius mailbox v1" ‖ MLS group id)`; +- an **invite mailbox** is 32 random bytes. + +What the relay stores, and why (SQLite, nothing else): + +| Table | Columns | Why | +|:--|:--|:--| +| `messages` | `mailbox_id, seq, size, received_at, ciphertext` | the mail | +| `keys` | `key, mailbox_id` — `key` is **unique across all mailboxes** | who may read and write a mailbox | +| `acks` | `key, seq` | retention: what every member has fetched | +| `nonces` | `key, nonce, expires` (5 minutes) | replay protection | + +No accounts, no IP addresses, no user agents, no app names, no certs. The relay's own logs are counts and +status codes, never ids or keys. Caddy's access log for this vhost is off. + +### Requests + +Every request except `GET /v1/health` is signed by a **random per-mailbox Ed25519 key**. A device makes a new +one for every group it joins and every invite. The relay never sees a Tessera key or cert, so it cannot link +mailboxes to each other or to a person. A key registered in one mailbox cannot be registered in another. + +``` +Tab-Key: base64url(public key) +Tab-Time: Unix seconds +Tab-Nonce: base64url(16 random bytes) +Tab-Sig: base64url(Ed25519("tabellarius request v1\0" ‖ METHOD ‖ "\n" ‖ path?query ‖ "\n" ‖ time ‖ "\n" ‖ nonce ‖ "\n" ‖ hex(SHA-256(body)))) +``` + +| Check | Answer | +|:--|:--| +| any header missing or malformed | 401 `unsigned` | +| `|now − time| > 120 s` | 401 `stale` | +| bad signature | 401 `bad_signature` | +| key not registered in this mailbox (except `PUT` creating it) | 403 `unregistered_key` | +| nonce already seen for this key | 401 `replayed` | +| more than 120 requests a minute for this key | 429 `slow_down` | + +A rejected request changes nothing and stores nothing (not even its nonce). + +| Endpoint | What | +|:--|:--| +| `PUT /v1/mailboxes/{id}` | create; the signing key becomes its first key. 409 `exists`, 409 `key_in_use` | +| `POST /v1/mailboxes/{id}/keys` `{"key"}` | a member registers another member's key. 409 `key_in_use` | +| `DELETE /v1/mailboxes/{id}/keys/{key}` | deregister (removal, or leaving). The last key gone → the mailbox and its mail are deleted | +| `POST /v1/mailboxes/{id}/messages` `{"messages":[b64…]}` | append; at most 100 per batch, 300 KiB each, 2 MiB per request. A message already in the mailbox (same bytes) is not stored again; its seq is returned. → `{"seqs":[…]}` | +| `GET /v1/mailboxes/{id}/messages?after=N` | up to 200 messages with `seq > N` → `{"messages":[{"seq","data"}],"more"}` | +| `POST /v1/mailboxes/{id}/ack` `{"seq"}` | this key has everything up to `seq` | +| `GET /v1/health` | `ok`, unsigned | +| `GET /v1/live` | v1.1b: a WebSocket of notices `{"mailbox","seq"}`; each subscription is signed in the first message (docs/V1_1B.md §3) | + +Every answer carries `Access-Control-Allow-Origin: *`, and `OPTIONS` answers a preflight, so a PWA on another +origin can call the relay (docs/V1_1B.md §4). Caddy strips `Origin`, `Referer` and `User-Agent` first. + +### Retention (config values) +A message is deleted once **every key of its mailbox has acknowledged it and it is older than 30 days** +(`retention_acked_days`). Every message is deleted after **90 days** regardless (`retention_max_days`). The +plan said "30 days after the last ack"; the relay does not record when an ack happened, so it counts from +receipt. That can delete earlier than the plan for a member who acked late, never later than 90 days. + +## 4. Invites + +An invite is a capability: whoever holds the token can ask to join, and the inviter's device accepts any +**valid** credential (a valid cert for the group's app; for a self group, the same root). + +1. The inviter's `invite(group)` creates an invite mailbox (its own fresh key) and registers a second fresh + key whose secret goes into the token. It also makes a one-time HPKE key pair. +2. Token: `tab1:` + base64url(`relay url ‖ invite mailbox ‖ access key secret ‖ inviter HPKE public key ‖ app`), + about 150 bytes, small enough for a QR code. It carries no identity. +3. The joiner's `join(token)` makes its MLS signature key, a group mailbox key and a KeyPackage with its + credential. It HPKE-seals the KeyPackage to the inviter's key (`info = "tabellarius invite v1"`) and posts it + to the invite mailbox. The relay never sees the credential. +4. The inviter's next `sync` opens it and checks the credential (§2). It then commits the Add to the group + mailbox, registers the joiner's mailbox key there, and posts `TIW1 ‖ seq ‖ Welcome` to the invite mailbox + (`seq`: where the joiner starts reading the group mailbox). Then it sends the group's history (§6). +5. The joiner's next `sync` reads the Welcome, checks every member, joins, and deregisters its invite key. + +## 5. Sync, offline first + +- `send(group, events)` seals each event in an envelope (HLC from the device clock), applies them to the local + log, encrypts one TBA1 batch per MLS message, and queues the ciphertext in the **outbox**. It never needs the + relay. +- `sync(group)`: + 1. uploads the outbox; + 2. pulls since the cursor; processes commits (credential checks, then merge) and application messages + (every envelope verified, then `tessera::merge`); + 3. acks. + + Messages it sent itself are recognised by hash and skipped. If the relay is unreachable, `sync` returns + `relay_ok: false` and changes nothing; the app shows "last synced" quietly. +- Rejected events and members come back in `SyncReport::rejected` with the reason, never half-applied. +- Group state (OpenMLS storage, keys, cursors, the log, the outbox) is saved through a `StateStore`. The file + store encrypts it (XChaCha20-Poly1305) with a 32-byte key **held in Custos**. The state never lies on disk in + the clear. + +## 6. History for a new member + +MLS gives a new member nothing from before it joined. A new device of yours must still see the whole log, so +after an Add the inviter sends the existing envelopes as ordinary TBA1 batches. Each envelope is still signed +by its author and verified by the receiver, and duplicates disappear in `merge`. + +## 7. Removal + +`remove(group, member)` commits a Remove and deregisters the member's mailbox key (it is in the member's +credential). The removed device can no longer fetch (403). Even with the ciphertext in hand, it cannot decrypt +anything from the next epoch on. + +## 7a. v1.1: revocation, renewal, backup (docs/V1_1.md) + +- **Revocation.** + - A `TRV1` statement (docs/TESSERA.md §12) travels as an event of kind `tessera.revoke`. + - `log()` leaves out every event a complete revocation rules out, and the revocations themselves. + - Events ruled out on arrival are reported in `SyncReport::rejected`. + - `revoke(group, statements)` announces, uploads, then removes the revoked leaves and deregisters their + mailbox keys. + - A device of the same person that sees a revocation in force removes the leaves on its next sync. +- **Who may remove whom.** A commit that removes some of another person's devices, while that person stays in + the group, needs that person's revocation in the log for each one; otherwise it is not applied. Removing + all of a person's devices removes the person, as in v0.2. +- **Renewal.** + - `renew(cert)` takes a new cert for the same subkey and commits a self-update with the new credential in + every group. + - A member's updated credential is checked like a new member's. + - A device whose cert has expired cannot be joined (the joiner checks every leaf), so renew before expiry. +- **The root-sealed backup.** + - `backup(secret)` uploads the self group's log to the backup mailbox: id = SHA-256(`tabellarius backup + v1` ‖ the access key's public key), access key from the secret's mailbox seed. It goes in 200 KiB parts, + each `seal(nonce, aad = "tabellarius backup v1", id ‖ part ‖ parts ‖ chunk)`: the relay sees ciphertext + of known sizes, no header. + - It acks the previous backups, so the relay drops them after its retention. + - An unchanged log is not uploaded again. + - `restore(secret)` returns the envelopes of the latest complete backup; `import(group, envelopes)` + verifies each at its own time and sends them into a new self group. + - **Retention:** the relay keeps every message at most 90 days, so a backup survives 90 days after its + last upload. + +## 8. Known limits (v1) + +- **Concurrent commits.** If two members commit in the same epoch, the one the relay ordered second is + dropped by the others. Its sender sees the conflict on the next sync, discards its own commit, and must redo + it. Day 2 tests commits sequentially. +- The relay sees **timing and sizes**: when a mailbox is written and fetched, and how large each message is. + Fetching several mailboxes from one connection links them by IP. Caddy drops access logs, but the network + path still sees it. +- A leaked invite token lets its holder join until the inviter's device accepts the first answer. One answer + per token is accepted; the token is dead afterwards. +- A browser sends a CORS preflight before each request (the URL changes with `?after=N`): twice the round + trips (docs/V1_1B.md Status). +- Live subscribe (v1.1b) tells a client *that* a mailbox has mail, never what. Native apps still poll; the + browser package listens. diff --git a/docs/TESSERA.md b/docs/TESSERA.md new file mode 100644 index 0000000..a885eb8 --- /dev/null +++ b/docs/TESSERA.md @@ -0,0 +1,255 @@ +# Tessera and the event envelope — design note (v1) + +*A tessera hospitalis was a token broken between two families so they could recognise each other.* + +Status: written before the code on day 1. Every format here is versioned by its magic; a change bumps it. + +## 1. What it is for + +One Domi identity per person, held in Custos. Every Domi app gets its **own subkey**, certified by that +identity, so no app ever creates long-term identity on its own. Apps then sign their events with the subkey; +anyone who knows the person's root public key can check that an event really came from one of their apps. + +| Piece | Lives in | Holds secrets? | +|:--|:--|:--| +| Root key | the Custos vault, never leaves it (CustosPublic `custos-vault`, `docs/IDENTITY.md` there) | yes | +| Root derivation, cert format, cert verification, match code, HLC, merge | `crates/tessera` | no, except in-memory `RootKey`/`Subkey` | +| Event envelope | `crates/envelope` | no | +| Asking Custos for a cert on Windows | `crates/custos-local` | no | + +`tessera` and `envelope` are **pure**: no I/O, no network, no clock. Time is always a parameter. + +## 2. Encoding primitives + +All multi-byte integers are big-endian. `str8` = one length byte, then that many bytes. Text fields are +restricted ASCII so there is exactly one encoding of every value: + +- **id** (`app_id`, `purpose`, envelope `app`): 1–32 bytes of `[a-z0-9-]`, not starting or ending with `-`. + +Base64 in JSON and QR codes is **base64url without padding**. + +## 3. The root key + +``` +entropy 32 bytes from the OS CSPRNG (Custos makes it; tessera only takes it as a parameter) +mnemonic BIP39, English, 24 words = bip39::Mnemonic::from_entropy(entropy) +seed BIP39 seed of the mnemonic with the empty passphrase (PBKDF2-HMAC-SHA512, 2048 rounds, 64 bytes) +root Ed25519 secret key = HKDF-SHA256(salt = "tessera root v1", ikm = seed, info = "ed25519")[0..32] +``` + +- The same mnemonic gives the same root public key, every time (test vector in §9). +- **Order (decided):** entropy → mnemonic shown **once** → root imported into the vault → entropy, seed and + mnemonic dropped (zeroized). A key that was created non-extractable first could never be backed up, so the + code makes the other order impossible: Custos' `Enrollment` is a typestate (`begin → show → confirm → + import`), and `import` exists only on the type that `show` returns. +- `tessera::RootKey::from_mnemonic` exists for recovery (v1.1) and tests. It has no method that returns the + secret; it can only sign certs and report its public key. + +## 4. Subkey certificate (`TSC1`) + +``` +"TSC1" 4 +root 32 the root public key that signs this cert +subkey 32 the subkey's Ed25519 public key +app_id str8 id; "device" is reserved for device subkeys +purpose str8 id, e.g. "sync"; for device subkeys "device" +not_before 8 u64 Unix seconds +not_after 8 u64 Unix seconds, > not_before +sig 64 Ed25519(root, "tessera cert v1\0" ‖ every byte above) +``` + +`tbs` ("to be signed") is every byte before `sig`. The domain prefix means the root can only ever sign +something that parses as a cert: Custos' vault refuses a `tbs` that does not start with `TSC1` and name its +own root. + +`verify(cert, root, now)` checks, in this order, and returns the first failure: + +| Check | Error | +|:--|:--| +| `cert.root == root` | `WrongRoot` | +| signature valid (`verify_strict`) | `BadSignature` (tampered) | +| `now >= not_before` | `NotYetValid` | +| `now < not_after` | `Expired` | + +Decoding is strict: wrong magic, a wrong length, an invalid id, `not_after <= not_before` or trailing bytes +are errors. + +**Validity Custos issues:** `not_before = now − 5 min` (clock skew between devices), `not_after = now + 365 days`. +Renewal and revocation are v1.1. + +## 5. Match code + +Six digits the app and Custos both show, so the person approves the key the app actually holds: + +``` +match = u32_be(SHA-256("tessera match v1" ‖ subkey_pub)[0..4]) mod 1 000 000, zero-padded to 6 digits +``` + +The code is not secret. Test vector in §9. + +## 6. Hybrid logical clock + +`Hlc { wall: u64 ms, logical: u32 }`, ordered by `wall` then `logical`; encoded as 12 bytes. + +- `Clock::tick(now)`: `wall' = max(last.wall, now)`; `logical' = last.logical + 1` if `wall' == last.wall`, + else 0. +- `Clock::observe(remote, now)`: refuses `remote.wall > now + max_drift` (`TooFarAhead`); then + `wall' = max(last.wall, remote.wall, now)` and `logical'` per the HLC paper (the larger logical of the + clocks that hold `wall'`, plus one). +- A logical counter that would overflow is an error, never a wrap. + +## 7. Merge + +`merge(log, batch, verify) -> (log', rejected)`: + +- Each event has an **order key** `(hlc, author, hash)`, where `hash = SHA-256(encoded event)`. +- Every event in `batch` is verified with the caller's `verify`; a failure goes to `rejected` with its + reason and is never inserted (the app logs it). +- `log'` = the union of `log` and the verified events, de-duplicated by `hash`, sorted by order key. +- The log's bytes are `u32 length ‖ encoded event` for each event in order. Merging the same batches in any + order, any number of times, gives byte-identical logs (property test). + +The events already in `log` are not verified again: they were verified when they arrived. + +## 8. The event envelope (`TEV1`) + +``` +"TEV1" 4 +then exactly these fields, in this order, each as tag (1) ‖ length (u32) ‖ value: + 1 app id + 2 schema u32 (4 bytes): the version of the payload's schema + 3 hlc 12 bytes + 4 author 32 bytes: the subkey public key + 5 cert a TSC1 cert (§4) + 6 payload 0–256 KiB: MLS ciphertext from day 2; opaque here + 7 sig 64 bytes: Ed25519(author, "tessera event v1\0" ‖ every byte before field 7) +``` + +Decoding is strict and total: it returns a whole `Envelope` or a typed error with a reason (`BadMagic`, +`UnknownField`, `FieldOutOfOrder`, `BadLength`, `Invalid`, `TrailingBytes`, `TooLarge`, …). An unknown tag is +`UnknownField`, a known tag in the wrong place is `FieldOutOfOrder`. Encoding is canonical: decoding and +encoding again gives the same bytes. A decoded envelope is not yet trusted. + +`Envelope::verify(roots, now, max_drift)` checks: + +| Check | Error | +|:--|:--| +| `author == cert.subkey` | `AuthorNotCert` | +| `cert.app_id == app` (app boundaries) | `WrongApp` | +| `cert.root` is one of the trusted `roots` (the group's members) | `UnknownRoot` | +| the cert is valid at the event's time (`hlc.wall / 1000`), §4 | `Cert(…)` | +| `hlc.wall <= now + max_drift` | `FromTheFuture` | +| the signature is valid (`verify_strict`) | `BadSignature` | + +The cert is checked at the event's own time, so a log stays verifiable after a cert expires and rebuilding +from it is deterministic. The cost: whoever steals a subkey can backdate events into its validity. Revocation +(v1.1) closes this; until then validity is one year. + +## 9. Test vectors + +| Input | Output | +|:--|:--| +| entropy `00` × 32 | mnemonic `abandon` × 23 + `art` | +| that mnemonic | root public key in `crates/tessera/tests/mandatory.rs` (`ROOT_PUB_ZERO`), also pinned in CustosPublic | +| subkey public key `07` × 32 | match code in `crates/tessera/tests/mandatory.rs` | + +## 10. Asking Custos for a cert (`custos-local`, Windows) + +Custos' local API is the named pipe `\\.\pipe\custos-domi` (Custos `docs/02_app.md`; only the current +Windows user can open it; Custos identifies the caller by its executable). Day 1 adds one operation: + +``` +→ {"op":"subkey","app":"Fiscus Domi","app_id":"fiscus","purpose":"sync","subkey":""} +← {"ok":true,"cert":"","match":"123456"} +← {"ok":false,"error":"denied"|"locked"|"no_identity"|"bad_request","message":"…"} +``` + +1. The app makes its subkey itself (`Subkey::from_seed` with 32 bytes from the OS CSPRNG) and keeps the seed + in Custos (`set domi:///tessera-subkey`), never in a file. +2. It shows the match code of its subkey and sends the request. +3. Custos shows the app (program path and signer), the app id, the purpose and the match code. One click + approves. Custos signs the cert with the root, records it (Domi identity → apps), and answers. + +No answer ever contains private key material: only the cert (public keys and a signature). + +## 11. Not in v1 + +Revocation, renewal, recovery UI (v1.1), MLS and the relay (day 2), WASM (v1.1). + +## 12. v1.1: revocation and the backup secret (docs/V1_1.md) + +### Revocation (`TRV1`) +``` +"TRV1" 4 +root 32 the root that withdraws the subkey +subkey 32 the revoked subkey +revoked_at 8 u64 Unix seconds +part 2 u16, this part's index +parts 2 u16, how many parts the statement has (1..256) +count 4 u32, hashes in this part (0..7000) +hashes count×32 SHA-256 of each event by the subkey that stays valid: sorted, unique +sig 64 Ed25519(root, "tessera revoke v1\0" ‖ every byte above) +``` +- The root signs it through `RevokeSigner::sign_revocation_tbs`, in its own domain. A signer refuses a `tbs` + that does not start `TRV1 ‖ its own root`, and the cert signer refuses a `TRV1`, so neither statement can + pass for the other. +- Decoding is strict: wrong magic, a part outside its count, unsorted or repeated hashes, a short field or + trailing bytes are errors. +- **`RevocationSet`** applies a group's statements: + - A statement counts once all its parts are in (parts add up). + - An event by a revoked subkey stays valid only if every complete statement for that subkey lists it, so a + later statement never widens what is kept. + - The answer does not depend on the order statements arrive in. + - Statements are accepted only from a root of the group. + +### The backup secret +``` +backup secret = HKDF-SHA256(salt "tessera backup v1", ikm = root secret (the Ed25519 seed, §3), info = app id) +seal key = HKDF-Expand(backup secret, "seal") XChaCha20-Poly1305: nonce (24) ‖ ciphertext +mailbox seed = HKDF-Expand(backup secret, "mailbox") the backup mailbox's Tabellarius access key +``` +- Custos derives it (the root never leaves Custos) and hands an app only its own. +- `BackupSecret` has no method that returns the secret: it seals, opens, and gives the mailbox seed. That seed + is a relay credential of the kind invite tokens carry, the one exception in `tests/surface.rs`. + +**Test vector** (the zero-entropy mnemonic of §9, app `fiscus`): +- mailbox seed: `IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU` +- `seal(nonce = 24 zero bytes, aad = "", plain = "")`: `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAci_JRbtsx5prR83KT9Y7LA` + +### Custos' part (`custos-local`, three more pipe operations) + +The person starts a revocation **in Custos** (Domi identity → a key → Revoke). Custos cannot call an app, so +each app asks, on every sync, whether there is anything to do: + +``` +→ {"op":"revocations","app":"Fiscus Domi","app_id":"fiscus"} +← {"ok":true,"revocations":[{"subkey":"","revoked_at":1793000000,"statements":["",…]|null}]} + +→ {"op":"revoke","app":"Fiscus Domi","app_id":"fiscus","subkey":"","revoked_at":1793000000, + "accepted":""} +← {"ok":true,"statements":["",…]} + +→ {"op":"backup_key","app":"Fiscus Domi","app_id":"fiscus"} +← {"ok":true,"secret":""} +``` + +- **All three need the app's namespace grant** (`domi:///…`, the one its subkey seed lives in), so an + app reaches only its own revocations and its own backup secret. +- **`revocations`** lists the revocations the person started for this app's subkeys and for device keys. + `statements` is `null` until a device of this app sent its list. +- **`revoke`** signs only a revocation the person started, at the `revoked_at` Custos chose (otherwise + `not_found`), and only once: a second call gets the statements already signed. The app sends the hashes of + every event by that subkey in all its groups (`Client::events_by_all`). +- **An app that does not answer:** Custos shows the revocation as waiting. A second, explicit click signs it + with an empty list, which throws away every event that key wrote (docs/V1_1.md decision 2). A device key + (`app_id` `device`) is signed at once with an empty list: in v1.1a no app log holds events by one. +- With the statements in hand the app calls `Client::apply_revocation`: in every group the key was in, it + announces them, removes the key's leaves and takes their mailbox keys off the relay. It skips a group that + already has them, so calling it on every sync is safe. +- **`backup_key`** gives the app its backup secret (above). The app keeps it as `BackupSecret` and calls + `Client::backup` after each sync and `Client::restore` on a new device. +- **Limits:** one pipe message is at most 1 MiB, so one `revoke` carries up to 24,000 kept events. + +Custos' vault signs `TRV1` only for a key the person marked revoked, at that time (CustosPublic +docs/IDENTITY.md), so an app with the namespace grant can choose which events stay, not which key is +revoked. diff --git a/docs/V1_1.md b/docs/V1_1.md new file mode 100644 index 0000000..ce992d7 --- /dev/null +++ b/docs/V1_1.md @@ -0,0 +1,206 @@ +# Fundamentum v1.1 — revocation, recovery, the browser, live sync (design note, proposals) + +Written before any v1.1 code, so the open decisions can be made first. **(proposal)** marks my judgment; +each has an alternative and its cost. Nothing here changes v1's formats; every new structure is a new +magic with its own signing domain. + +**The gate (roadmap):** lose a phone, revoke it, and recover everything from the 24 words, with no data loss. + +v1.1 is too big for one session. Proposed split: + +| Day | Contents | +|:--|:--| +| **v1.1a** | revocation (§1), renewal (§2), the root-sealed backup and recovery (§3), Custos UI for all three | +| **v1.1b** | a sans-IO client and its WASM build (§4), live subscribe on the relay (§5), the JS package for PWAs (§6) | + +v1.1a alone passes the gate for the desktop apps. v1.1b is what the phone apps need. + +--- + +## 1. Revocation + +### What a lost phone holds +- One device subkey per Domi app it ran (`TSC1` certs for that app) and, in the browser, the device key from + day-1 pairing. +- For each group it was in: an MLS leaf, its signature key, the group state and a mailbox key. + +Revoking it has to do three separate things: +1. **Readers stop trusting its signatures.** Nothing it signs from now on is accepted. +2. **It stops reading.** It leaves every MLS group, so it cannot decrypt future epochs. +3. **The relay stops serving it.** Its mailbox keys are deregistered. + +### The revocation statement (`TRV1`) +``` +"TRV1" 4 +root 32 the root that certified the subkey +subkey 32 the revoked subkey +revoked_at 8 u64 Unix seconds, when the person revoked it +accepted u32 count ‖ count × 32 SHA-256 of every event by this subkey that stays valid, sorted +sig 64 Ed25519(root, "tessera revoke v1\0" ‖ every byte above) +``` +- Custos signs it. Its vault refuses a `tbs` that does not start with `TRV1` and name its own root, exactly + as it does for `TSC1`, so the root still signs only things that parse as one of its two statements. +- It travels as an ordinary event (`kind = "tessera.revoke"`) in each group the subkey was in. Any device of + the same person sends it. + +### Why a list of accepted events, not a time (proposal) +v1 checks a cert at the event's own time, so a thief who has the subkey can **backdate** an event to +before `revoked_at`, and a time cutoff would accept it. Instead, the revocation names exactly which of that +subkey's events stay valid: those already in the revoking device's log. Every other event by that subkey, +whenever it claims to be from, is rejected. + +- This is deterministic: every device applies the same list once the logs converge. +- **The cost:** events the lost phone wrote but never synced are lost too. They exist only on the phone. +- Size: 32 bytes per kept event (1,000 events from one phone in one group = 32 KB, once). +- *Alternative:* a time cutoff (`revoked_at` only). Simpler and smaller, but it leaves the backdating hole open. + +### Applying it (`tessera::merge`) +The verifier gets the group's revocations as a second input. Merging becomes two passes: +1. Collect every valid `TRV1` in the log: root-signed, by a root of the group, for a subkey that root certified. +2. Drop each event whose author is revoked and whose hash is not in that revocation's list. It goes to + `rejected` with the reason "revoked". + +Revoking twice is idempotent: the lists are intersected, never widened. + +### MLS and the relay +- **The revoking device:** + - commits a `Remove` of every leaf whose credential names a revoked subkey; + - deregisters the mailbox key in that credential (v0.2.0's `remove` does both); + - then sends the `TRV1` event. +- A member device that sees a valid `TRV1` before the `Remove` lands may commit the `Remove` itself, so a + revocation finishes even if the revoking device goes offline. +- **Shared groups:** another person's device in the group accepts a `Remove` of your leaf only with your + `TRV1` beside it (a member removing someone else needs a reason the others can verify). *(proposal)* + +### In Custos +- **Domi identity → Devices → Revoke.** Custos groups certs by the label it recorded when it issued them + ("Phone browser", "Fiscus on Mark's PC"), so one revoke covers every key of that device. +- The `accepted` list comes from the app's own log: Custos asks each app on this PC (pipe op `revoke`) for + that subkey's event hashes. An app that is not running cannot answer. +- **(Decision)** Revoke then: (a) waits until each app has answered, or (b) lets the person revoke with an + empty list for apps that did not answer. That throws away everything that phone wrote in those apps. I + propose (a), with (b) behind a second, explicit click. + +## 2. Renewal +- Certs live 365 days. An app asks Custos for a fresh cert for the same subkey when 30 days are left (same + `subkey` op, one click, the same match code). +- An expired cert keeps its old events valid (they are checked at their own time); the subkey just signs + nothing new until renewed. +- No new format. + +## 3. Recovery from the 24 words + +`RootKey::from_mnemonic` already gives back the same root, so every group still trusts it. What is lost +with every device is the **data** and the **MLS state**. + +- **Shared groups:** the other members still hold the group. They re-invite your new device; the credential + check passes because the root matches. Their copy of the log comes with the history (v0.2.0 §6). +- **Your self group** (your own devices only): if every device is gone, nobody holds it. Hence: + +### The root-sealed backup (proposal) +- Custos derives, per app, a backup key and a backup mailbox from the **root secret**, never stored: + - `backup_key = HKDF(root secret, "tessera backup v1", app_id)` + - `mailbox access key = HKDF(root secret, "tessera backup mailbox v1", app_id)` + - The mailbox id is the hash of that key's public half. + - Both come back from the 24 words alone. Custos hands an app its own pair only (pipe op `backup_key`). +- Each desktop app, after a sync, uploads its self group's verified log: `TBK1 ‖ XChaCha20-Poly1305(backup_key, + envelopes)`. The relay keeps the latest few; they are ciphertext like everything else. +- **Recovery:** + 1. Custos: "Restore from 24 words". + 2. Each app asks for its backup pair, downloads the latest blob, verifies every envelope, opens a new self + group and sends the history into it. + 3. Your other people re-invite you into shared groups. +- **Cost:** the relay can tell that one backup mailbox gets written now and then. It cannot tell whose it is + or what is in it, and it cannot link it to any group mailbox. +- *Alternative:* no backup. Recovery then works only if one device survives (an always-on node such as + fiscus-node counts). Simpler, but it fails the gate for anyone with one PC and one phone who loses both. + +## 4. The client in the browser (WASM) + +**The probe (2026-11-04)** answers the open point from the plan ("whether OpenMLS runs well in WASM"): +**it builds.** `tessera`, `envelope`, `tabellarius-proto` and OpenMLS 0.9 all compile for +`wasm32-unknown-unknown` once the browser's clock and randomness are switched on. The client itself stops +only at its HTTP transport. Details under "Probe" at the end. The client needs two changes: +- **Transport:** the client is blocking (`ureq`). Proposal: split it into a **sans-IO core** (a state machine + that says which request to make and consumes the answer) and two thin drivers: `ureq` (native, unchanged + API) and `fetch` (browser, async). The tests drive the core directly. +- **Signing:** in the browser the device subkey is a non-extractable WebCrypto key. Tessera gets a `Signer` + trait (`public`, `sign_event_tbs`, `sign_credential_tbs`), async in the browser. `Subkey` implements it on + native. +- **MLS keys:** OpenMLS makes its own signature key per group; in the browser it lives in the client state. + That state is encrypted with a non-extractable WebCrypto AES-GCM key and kept in IndexedDB (the same rule as + the desktop's Custos-held state key). + +## 5. Live subscribe + +- **`GET /v1/live`**, a WebSocket. + - The first message is a list of `(mailbox, after)`, each signed as a v0.2.0 request: a browser cannot set + headers on a WebSocket. + - The relay then sends `{"mailbox", "seq"}` whenever a message arrives, never the message. The client + fetches as today. +- **Limits:** 32 mailboxes per connection, 4 connections per mailbox key, idle timeout 10 minutes. +- **Privacy:** no worse than polling. One connection for several mailboxes links them by connection, as + fetching them from one IP already does. Apps that care open one connection per group. +- Caddy proxies it; the access log stays off. + +## 6. The JS package (`@domi/fundamentum`) + +- `wasm-bindgen` over the sans-IO core and the fetch driver, in the Fundamentum repo, served by each PWA + itself (Domi: nothing fetched from a CDN). +- The API mirrors the Rust one (`open`, `selfGroup`, `openGroup`, `invite`, `join`, `send`, `sync`, `log`, + `remove`, `revoke`) plus `subscribe(onChange)`. + +## Decisions wanted before v1.1a starts + +| # | Question | Proposal | +|:--|:--|:--| +| 1 | Revocation keeps a list of accepted events (closes backdating) or uses a time cutoff | the list | +| 2 | Revoke while an app did not answer | wait; an explicit second click to drop its events | +| 3 | Another person's device may `Remove` your leaf only with your `TRV1` | yes, refined in v1.1a (below) | +| 4 | Root-sealed backup on the relay, so recovery works with every device lost | yes | +| 5 | Split v1.1 into v1.1a (revocation, renewal, recovery) and v1.1b (WASM, live, JS) | yes | +| 6 | The v1 gate (live relay, two real devices) before v1.1 starts, or in parallel | in parallel: v1.1a needs no server | + +## Status + +**v1.1a in the crates (Fundamentum v0.3.0):** `TRV1` and `RevocationSet`, `RevokeSigner`, `BackupSecret` +(tessera); `revoke`, `announce_revocation`, `events_by`, `renew`, `backup`, `restore`, `import` and the +removal rule (client). The gate's scenario passes against the in-process relay: a phone is revoked, its +later and backdated events are dropped on every device, and with every device lost the self group comes back +from the backup. + +**Decision 3, refined while building it.** As written, it would also have stopped anyone removing a +*person* from a shared group, which v0.2 deliberately allows. The intent was to stop one person cutting off +another's device while that person stays. So: +- removing **some** of another person's devices needs their revocation for each one; +- removing **all** of them removes the person, as before. + +**Custos' half (Fundamentum v0.3.1, CustosPublic v0.10.0, Custos 0.5.0):** the pipe ops `revocations`, +`revoke` and `backup_key` (docs/TESSERA.md §12); Domi identity → a key → **Revoke**, **Revoke without +waiting** (decision 2's second click) and **Restore from 24 words**. The vault signs `TRV1` only for a key +the person revoked, at the time they did. CustosPublic and Custos check the backup secret against the +test vector of §12. + +**One change to §1 "In Custos":** Custos cannot call an app over the pipe, so the person starts the +revocation in Custos and each app asks on its next sync (`revocations`), then sends its list (`revoke`). +Device keys are signed at once with an empty list: no app log holds their events in v1.1a. + +**Still to do for v1.1a:** each app, on every sync, calls `revocations_to_apply` → `apply_revocation`, then +`backup`; and offers `restore` on a new device. Then the gate by hand on two real devices. + +## Probe + +`cargo build --target wasm32-unknown-unknown`, rustc 1.94.1 from the server's nixpkgs-unstable pin +(`0726a0ec`), in WSL, on Fundamentum `95b7579` (v0.2.1). Not run in a browser yet: this shows the code +compiles, not that it works there. + +| Crate | Result | Needs | +|:--|:--|:--| +| `tessera` | builds | nothing | +| `envelope` | builds | nothing | +| `tabellarius-proto` | builds | the browser random source (`getrandom` 0.2 `js`, 0.3 and 0.4 `wasm_js` + `--cfg getrandom_backend="wasm_js"`) | +| OpenMLS 0.9 + `openmls_rust_crypto`, `_basic_credential`, `_memory_storage` | builds | the same, plus OpenMLS's own `js` feature (time and randomness from JavaScript) | +| `tabellarius-client` | fails at `ring` (C code, via `ureq` → `rustls`) | the sans-IO split (§4): the browser build has no `ureq`, it talks through `fetch` | + +The browser build therefore needs no change to the crypto, the formats or OpenMLS: only the transport and +a `Signer` for the WebCrypto device key. diff --git a/docs/V1_1B.md b/docs/V1_1B.md new file mode 100644 index 0000000..d8cbed7 --- /dev/null +++ b/docs/V1_1B.md @@ -0,0 +1,176 @@ +# Fundamentum v1.1b — the client in the browser, live subscribe, the JS package (design note) + +Written before the v1.1b code. It turns `docs/V1_1.md` §4–§6 (accepted with decision 5 on 2026-11-04) into +what gets built. **(choice)** marks where this note settles something §4–§6 left open; each says what +it costs. Nothing here changes a v1 or v1.1a format. + +**The goal:** a PWA on a phone is a Domi device. It joins the self group, sends and reads verified events, +and hears about new mail without polling. Its device key and its state never leave the browser unencrypted. + +Two releases: + +| Release | Contents | +|:--|:--| +| **v0.4.0** | the client split into an async core and a blocking native driver (§1); `DeviceSigner` (§2); live subscribe on the relay (§3); CORS (§4) | +| **v0.5.0** | `crates/wasm` (fetch transport, WebCrypto signer) and the JS package `@domi/fundamentum` (§5), tested in a browser against a local relay | + +## 1. One core, two drivers + +§4 proposed a sans-IO state machine. **(choice)** The core is `async` code generic over a transport and a +signer, and Rust's `async` produces the state machine. A hand-written state machine for `sync` (several +mailboxes, `more` pages, invites, joins, acks) would duplicate every control path the client already has, and +every bug fix would have to be made twice. + +```rust +pub trait Transport { + /// `Err` only when the relay could not be reached (offline); any HTTP status is an `Ok` response. + fn send(&self, req: HttpRequest) -> impl Future>; +} +pub struct Core { … } // every operation that talks to the relay or signs is `async` +pub struct Client(Core); // native: the v0.3 API, unchanged, blocking +``` + +- **Native** (`Client`): the API every app uses today keeps its exact signatures. Its transport (`ureq`) + and signer (`Subkey`) never wait, so each call polls the core's future exactly once. There is no executor + and no thread. The core never waits on anything else (no timers, no channels). +- **Browser** (`crates/wasm`): the same core over `fetch` and a WebCrypto signer, driven by the browser's + event loop through `wasm-bindgen-futures`. +- The tests stay as they are. They drive `Client`, so they test the core. +- `ureq` is a dependency only off `wasm32`. `EncryptedFileStore` is native only. The clock is a parameter + of `Core::open` (`std::time` panics in the browser). +- **Cost:** `Core` is generic, so a native app compiles one instance and the browser another. That is fine. + +## 2. The device key in the browser + +```rust +pub trait DeviceSigner { + fn public(&self) -> PublicKey; + fn sign_event_tbs(&self, tbs: &[u8]) -> impl Future>; // EVENT_DOMAIN ‖ tbs + fn sign_credential_tbs(&self, tbs: &[u8]) -> impl Future>; // CREDENTIAL_DOMAIN ‖ tbs +} +``` +- `tessera::Subkey` implements it (native). +- In the browser the private key is a **non-extractable** WebCrypto Ed25519 key, the one day-1 pairing + certified. Rust prepends the domain, and JavaScript calls `crypto.subtle.sign("Ed25519", key, message)`. + JavaScript never chooses the domain, so it cannot be tricked into signing one statement as another. +- `envelope` gains a two-step seal for a signer that cannot be called synchronously: + - `Envelope::to_be_signed(author, cert, schema, hlc, payload)` gives the bytes to sign. + - `Envelope::with_signature(tbs, sig)` finishes the envelope. It checks the signature against the author + before returning, so a broken signer cannot produce an envelope that others would drop. + - `seal` is unchanged. +- No hand-written crypto: Ed25519 is WebCrypto's in the browser and `ed25519-dalek` everywhere it is checked. + +## 3. Live subscribe + +As in V1_1 §5, with the details settled: + +- **`GET /v1/live`** upgrades to a WebSocket. +- **Subscribing.** The client's first message (text, JSON) lists up to 32 subscriptions: + ```json + {"subscribe": [{"mailbox": "", "after": 17, "key": "…", "time": "…", "nonce": "…", "sig": "…"}]} + ``` + - Each one is signed like a request, with method `LIVE`, path `/v1/mailboxes/{id}/live?after={after}` and + an empty body. The relay checks it like any request: time, signature, registration in that mailbox, + replay, rate. A subscription that fails is answered `{"mailbox", "error"}`, and the others still count. + - A WebSocket from a browser cannot carry the `Tab-*` headers, which is why the signatures travel in the + message. +- **Notices.** The relay sends `{"mailbox", "seq"}` when that mailbox holds a message with a higher seq than + `after`. It sends one at once if there already is one, and then one per append. It never sends the + message itself; the client fetches as it does today. Notices only say "something is new": a client that + misses one loses nothing, because its next fetch starts from its cursor. +- **Removed keys.** A key deregistered while subscribed gets `{"mailbox", "error": "unregistered_key"}`, and + that subscription ends. The relay checks the registration again before every notice. +- **Keeping it open.** The client sends `{"ping": true}` at least every 5 minutes, and the relay answers + `{"pong": true}`. After **10 minutes** with nothing from the client, the relay closes the socket. +- **Limits:** 32 subscriptions per connection; **4 open subscriptions per mailbox key** (the 5th is refused + `too_many`). Rate counting is the same per key as for requests. +- **In memory only.** Nothing about a socket is stored or logged. One process-wide broadcast of + `(mailbox, seq)` feeds every socket. A socket that falls behind it is told to re-fetch everything it + watches (`{"mailbox", "seq": null}` for each). +- **The core is sans-IO here.** `Core::live_subscribe()` returns the signed first message for every active + group, and `Core::live_notice(text)` names the group that has mail. The drivers own the socket. The + browser package uses it; the native `Client` gets no socket yet (desktop apps keep polling). +- **Privacy:** no worse than polling, as V1_1 §5 says. A socket that watches several mailboxes links them, + as fetching them from one address already does. The JS package therefore opens one socket per group by + default. + +## 4. CORS + +A PWA at `fiscus.…` calling `tabellarius.…` needs CORS. **(choice)** The relay answers every request with +`Access-Control-Allow-Origin: *`, and a preflight (`OPTIONS`) with the methods, the `content-type` and +`tab-*` headers, and `max-age` one day. +- `*` is safe here because nothing is authorised by a cookie or by the origin. Every request is authorised + only by its signature, and browsers never send cookies to a `*` origin. +- **Caddy strips `Origin`, `Referer` and `User-Agent` before the relay sees them.** The relay never learns + which app a request came from. (The browser still sends `Origin`, so the TLS endpoint sees it, as it sees + the address. Caddy's access log stays off.) +- The CORS handling is ~20 lines in the relay, tested, not a new dependency. +- *Alternative:* proxy the relay under each app's own origin (`fiscus.…/tabellarius/`). No CORS, but every + app's vhost then knows which app talks to the relay, and the relay would need one configuration per app. + +## 5. The JS package (`@domi/fundamentum`, v0.5.0) + +- `crates/wasm` (`wasm-bindgen`) wraps `Core`. `packages/fundamentum` holds the + generated module and a small hand-written `index.js`. Each PWA serves it itself; nothing comes from a CDN. +- **API** (mirrors the Rust one): + - `Fundamentum.open({relay, cert, key, state})` takes the cert text, the non-extractable `CryptoKey` and + the previously saved state. + - Then: `selfGroup`, `openGroup`, `groups`, `invite`, `join`, `send`, `sync`, `log`, `members`, `remove`, + `applyRevocation`, `backup`, `restore`, `import`. + - `subscribe(onChange)` opens the sockets and runs `sync` when a notice arrives. +- **State:** after every call that changes it, the package hands the encrypted state to `onSave(bytes)`. + It is encrypted with a non-extractable WebCrypto AES-GCM key (V1_1 §4), and the app keeps it in IndexedDB. + - The plaintext exists only inside the page, which already holds the wasm memory that contains it. This + is the same trust boundary as the desktop app's process. +- **Calls are serialised:** the package queues them, so two `sync`s never run at once. If one still + overlaps, the core answers `busy` instead of panicking. +- **The browser build:** `wasm32-unknown-unknown`, with the browser's randomness (`getrandom` `wasm_js`) + and OpenMLS's `js` feature, built in WSL with nix (rustup targets are not installed on the dev machine). It + is checked by a test page against a local relay: a native CLI device and a browser device join one group, + exchange events both ways, and the browser hears the live notice. + +## Status + +**v0.4.0:** +- `Core` with `Transport` and `DeviceSigner`. `Client` is the native driver, and its API is + unchanged. +- The two-step seal: `Envelope::to_be_signed` and `with_signature`. +- `/v1/live`, with `Core::live_subscribe` and `live_notice`. +- CORS, and Caddy stripping `Origin`, `Referer` and `User-Agent`. + +Tested against the in-process relay: +- A core whose transport and signer really wait pairs and syncs with a native device. +- A device hears that its group has mail, and later that it was removed. +- The relay's checks and limits on subscriptions hold. +- The preflight works. + +Not built for `wasm32` yet; that comes with `crates/wasm` in v0.5.0. + +**v0.5.0:** `crates/wasm` and `packages/fundamentum` (`index.js`; `pkg/` is built by `build.sh` in +`nix develop .#wasm` and is not in git). The wasm module is 3.1 MB. + +The browser check (packages/fundamentum/README.md) passed on 2026-11-04 in the desktop app's Chromium, +against a local relay, cross-origin: +- A native CLI device and a browser device joined one self group. The browser's credential and events were + signed by its non-extractable WebCrypto key; `exportKey` refused with `InvalidAccessError`. +- Events went both ways, and the browser heard the CLI's event live and synced it. +- The sealed state reopened to the same log. It does not show the group id, and a wrong AES key does not + open it. + +**Seen while testing it:** a browser sends a CORS preflight (`OPTIONS`) before each relay request, because +the URL changes (`?after=N`) and preflights are cached per URL. That doubles the round trips. The answers +are small and unsigned, and do not count against the rate limit. +- *Possible later:* put `after` into a signed header so the URL stays the same. That would be a protocol + change. + +**Not checked:** +- A real phone. +- WebKit/Firefox. Ed25519 in WebCrypto is recent there. +- The live server (it needs the `nixos-rebuild` for v0.4.0's relay). + +## Not in v1.1b +- Pairing a phone end to end (the PWA asking the factor service for its cert, as day 1 did for the Custos web + vault). This needs the live server. +- A native WebSocket driver for desktop apps. +- Service-worker push while the PWA is closed: no third-party push service (Domi rule), so a closed PWA + syncs when it is opened. diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..c775577 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 120 +use_small_heuristics = "Max"