commit 6d3ea3e2a62751bd798235d8acb2e2498dc46555 Author: yc Date: Fri Nov 20 21:47:33 2026 +0100 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fd0c03b --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/target +*.mwid2 +*.mwiv2 +/tests/work diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..6f88a5c --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,247 @@ +# Meow v2 — Architecture Rust + +Ce document décrit la ré-architecture de `meowlib` / `meowsrv` / `meowcli` / `meowjsonlib` +en Rust. La progression est suivie dans [`ROADMAP.md`](ROADMAP.md). + +> **Décision** : protocole **v2 en rupture nette**, sans compatibilité réseau avec la v1 en Go +> (OpenPGP). Les clients et serveurs v1 et v2 ne communiquent pas entre eux. La migration se +> fait en bloc (serveur, puis CLI, puis application Flutter). Les données v1 importables +> (pseudo, serveurs, historique) passent par un outil d'import (phase 10). Les contacts, eux, +> doivent refaire une invitation, car leurs clés ne sont pas transposables. + +--- + +## 1. Constat sur la v1 (Go) + +| Problème v1 | Conséquence | Réponse v2 | +|---|---|---| +| OpenPGP (gopenpgp) pour tout : clés base64 de ~600 octets, paquets PGP, S2K pour le stockage | Lent, volumineux (QR codes énormes), surface d'attaque large | Primitives brutes : X25519, Ed25519, XChaCha20-Poly1305, HKDF-SHA256, Argon2id. Clés de 32 octets. | +| `PackedUserMessage.signature` = signature **détachée, en clair, sur le texte en clair** | Un serveur qui connaît la clé publique d'un contact peut confirmer l'auteur ou deviner le contenu. Pas de déniabilité. | Pas de signature sur les messages : l'authentification passe par la session Double Ratchet (AEAD avec les identités en données associées). Déniabilité au sens Signal. | +| Trois couches empilées (asym + sym + DR) avec un état DR sérialisé en JSON | Coûteux, état fragile | Une seule couche pair-à-pair : Double Ratchet. L'état est sérialisé en protobuf et chiffré au repos. | +| `ConversationRequest.lookup_signature` jamais vérifiée (`// todo sign it`) | N'importe qui connaissant une clé de lookup peut **vider la boîte** d'un autre | Le pull est authentifié : signature Ed25519 de la clé de mailbox, liée au serveur, à un horodatage et à l'id de requête (anti-rejeu). | +| Singleton global `GetConfig().GetIdentity()` partout | Code non testable, non ré-entrant, une seule identité par processus | Pas d'état global. `MeowClient` est un objet possédé, injectable et clonable (`Arc`). | +| API FFI : 63 fonctions C, paramètres JSON, framing binaire maison, chemins de fichiers en paramètre | Fragile, lent (double sérialisation), erreurs en JSON | `flutter_rust_bridge` v2 : types Dart générés, `Future`/`Stream` natifs, erreurs typées. | +| Inbox/outbox sous forme de fichiers protobuf + une base SQLite par file d'envoi + Badger + SQLite par pair | 4 mécanismes de persistance, incohérences possibles | Une seule base SQLite par identité (WAL), transactions. Les blobs sensibles sont chiffrés au niveau applicatif. | +| Redis obligatoire, logs envoyés en dur vers Loki | Difficile à tester, fuite de métadonnées | Trait `ServerStore` avec un backend mémoire (dev/tests) et un backend Redis (prod). Logs locaux uniquement, sans clés ni mailbox en clair. | +| `meowsrv/config/*.json` contient clé privée serveur et secret LiveKit | Secrets versionnés | Clé serveur dans un fichier `0600` séparé (`server.key`), secrets passés par variables d'environnement. | +| TTL des invitations : `time.Duration(timeout*1000000)` interprète des secondes comme des millisecondes, et `mwiv:` est stockée sans expiration | Les invitations ne meurent jamais, et la réponse expire après 86 s au lieu de 24 h | TTL Redis réels (`SET EX`). Purge des mailbox via TTL configurable. | +| Accusés de livraison serveur : écriture dans `dvyrq:{uuid}` mais lecture dans `msg:{uuid}` | Le suivi de livraison ne fonctionne pas | Phase 5 : accusés de bout en bout, chiffrés dans le ratchet (pas de suivi côté serveur). | + +--- + +## 2. Vue d'ensemble des crates + +``` +rust/ +├── Cargo.toml workspace +├── proto/meow.proto schéma unique du protocole v2 (source de vérité, aussi pour Dart) +├── crates/ +│ ├── meow-proto (lib) types prost générés + helpers d'encodage. Aucune logique. +│ ├── meow-crypto (lib) primitives : clés, sealed box, KDF, AEAD, Double Ratchet, chiffrement au repos +│ ├── meow-core (lib) protocole pur, sans E/S : cartes, invitation 4 étapes, codec de messages, +│ │ requêtes serveur scellées, authentification des pulls +│ ├── meow-store (lib) [à créer] persistance client : SQLite chiffrée (identité, contacts, serveurs, +│ │ sessions, messages, file d'envoi) [phase 4] +│ ├── meow-client (lib) façade asynchrone haut niveau : transport HTTP, envoi/réception, +│ │ files d'envoi, long-poll, événements +│ ├── meow-server (lib+bin `meowsrv`) serveur axum, stores mémoire/Redis +│ ├── meow-cli (bin `meow`) CLI clap, parité avec meowcli +│ └── meow-ffi (lib cdylib) [à créer] pont flutter_rust_bridge → bastet [phase 7] +└── tests/e2e.sh test bout-en-bout (équivalent de meowcli/test.sh) +``` + +Les dépendances vont uniquement vers le bas : + +``` +meow-cli ─┐ meow-ffi ─┐ + ▼ ▼ + meow-client ──► meow-store + │ + ▼ +meow-server ──► meow-core ──► meow-crypto + │ + ▼ + meow-proto +``` + +* `meow-core` ne fait **aucune E/S** (ni réseau, ni disque, ni horloge implicite : le temps est + passé en paramètre). Il est donc entièrement testable de façon déterministe et réutilisable + côté serveur, CLI et mobile. +* `meow-crypto` n'expose que des types forts (`SigningKey`, `DhSecret`, `MailboxId`…) et met à + zéro les secrets avec `zeroize`. Il n'expose jamais d'octets bruts de clé privée hors de la + sérialisation explicite. + +--- + +## 3. Cryptographie v2 + +| Usage | Primitive | Crate | +|---|---|---| +| Signature (identité par contact, mailbox, carte serveur) | Ed25519 | `ed25519-dalek` | +| Accord de clé | X25519 | `x25519-dalek` | +| AEAD | XChaCha20-Poly1305 (nonce aléatoire de 24 octets) | `chacha20poly1305` | +| KDF | HKDF-SHA256, avec des labels de domaine `meow/v2/...` | `hkdf`, `sha2` | +| Dérivation de mot de passe | Argon2id (m=64 MiB, t=3, p=1 ; réglable) | `argon2` | +| Aléa | `OsRng` | `rand_core` | + +### 3.1 Sealed box (requêtes serveur, invitations) + +Construction ECIES équivalente à HPKE en mode base (RFC 9180) : + +``` +eph ← X25519 éphémère +shared = DH(eph, recipient_pk) +okm(64) = HKDF(ikm=shared, salt=eph_pk‖recipient_pk, info="meow/v2/seal/"‖context) +k_req, k_resp = okm[0..32], okm[32..64] +ciphertext = XChaCha20-Poly1305(k_req, nonce, plaintext, aad=context) +``` + +`k_resp` sert à chiffrer la **réponse** du serveur. Le serveur reste sans état, et le client n'a +pas besoin de s'identifier auprès de lui : les requêtes sont **anonymes** par construction. + +### 3.2 Clés par contact + +Comme en v1, chaque contact a ses propres clés, ce qui empêche de corréler les contacts entre eux : + +| Clé | Type | Rôle | +|---|---|---| +| `identity` | Ed25519 | Signe le transcript de l'invitation (preuve de possession) | +| `dh` | X25519 | Clé statique utilisée pour l'accord initial (X3DH simplifié) | +| `mailbox` | Ed25519 | La clé publique **est** l'adresse de la boîte aux lettres (`MailboxId`). La clé privée signe les pulls. | +| `ratchet` | X25519 | Clé initiale du Double Ratchet (rôle de « signed prekey » côté invité) | + +### 3.3 Invitation en 4 étapes (le transport est indépendant : fichier, QR, serveur, BLE) + +``` +Initiateur (I) Invité (V) +1. Offer { inv_id, nom, offer_dh (X25519 temp), + answer_mailbox (Ed25519 temp), msg, + answer_servers, expires_at } ───────► + 2. Crée ses clés + Card_V + Answer = seal(offer_dh, {Card_V, + sig_V(H(offer) ‖ Card_V)}) + ◄─────── (fichier, ou dépôt dans answer_mailbox) +3. Ouvre Answer, vérifie sig_V, crée ses clés + Card_I + eph_I ← X25519 ; th = H(offer ‖ Card_V ‖ Card_I ‖ eph_I) + SK = HKDF( DH(I.dh, V.dh) ‖ DH(eph_I, V.dh) ‖ DH(eph_I, V.ratchet) ; salt = th ) + DR.init_sender(SK, V.ratchet) → I peut envoyer immédiatement + Confirm = seal(V.dh, {Card_I, eph_I, sig_I(th), + first_message = DR(HandshakeAck)}) ───► + 4. Ouvre Confirm, vérifie sig_I, recalcule SK + DR.init_receiver(SK, V.ratchet_kp) + déchiffre first_message → chaîne d'envoi prête + ◄─────── envoie DR(HandshakeAck) dans I.mailbox +5. Réception de l'ack → contact « Active » des deux côtés +``` + +Pourquoi `first_message` : dans un Double Ratchet, le receveur ne peut pas émettre avant d'avoir reçu un +message. Embarquer le premier message de l'initiateur dans le Confirm permet à l'invité d'émettre +l'ack dès l'étape 4. L'initiateur, lui, peut envoyer dès l'étape 3 (les messages attendent dans la +mailbox de l'invité et sont lisibles après l'étape 4). + +Chaque étape est liée aux précédentes par le transcript `th` : un Answer ou un Confirm rejoué, +falsifié ou destiné à un autre invité est rejeté. Les 10 premiers octets de `th` donnent un +« numéro de sécurité » identique des deux côtés (`meow contact show`). La vérification visuelle (SAS) +de `peer_secure` reste disponible au-dessus (phase 8). + +### 3.4 Messages entre pairs + +``` +UserMessage (protobuf) → padding par paliers (256 o, 1 Kio, 4 Kio, 16 Kio, 64 Kio…) + → DoubleRatchet.encrypt(ad = "meow/v2/msg" ‖ id_émetteur ‖ id_destinataire) + → PeerEnvelope { header, ciphertext } + → Deposit { mailbox = contact.mailbox, payload = PeerEnvelope } + → Request scellée vers chaque serveur de pull du contact +``` + +Le Double Ratchet suit la spécification Signal (KDF_RK = HKDF, KDF_CK = HMAC-SHA256). Les clés +sautées sont bornées (`MAX_SKIP = 1000`). Le chiffrement des en-têtes est prévu en phase 8. + +### 3.5 Authentification des pulls + +``` +MailboxAuth { mailbox, timestamp, signature } +signature = Ed25519_sign(mailbox_sk, + "meow/v2/pull" ‖ server_sign_pk ‖ mailbox ‖ timestamp ‖ request_id) +``` + +Le serveur rejette si `|now - timestamp| > 300 s`, si la signature est invalide ou si +`request_id` a déjà été vu (cache anti-rejeu avec TTL de 600 s). + +--- + +## 4. Protocole serveur + +* `GET /v2/card` → `ServerCard` (protobuf) autosignée. Le client l'épingle à l'ajout (TOFU), + et un changement de clé est signalé explicitement. +* `POST /v2/rpc` → corps `SealedRequest`, réponse `SealedResponse` (protobuf binaire). +* `GET /healthz`, `GET /v2/stats` (compteurs agrégés, optionnel). +* Phase 8 : `GET /v2/ws` (WebSocket) pour le push. + +Les opérations (`oneof` de `Request`) : + +| Requête | Effet | +|---|---| +| `Post { deposits[] }` | Stocke chaque payload dans `mailbox`, avec un TTL. Retourne les ids serveur. | +| `Pull { auths[], wait_seconds }` | Vide les mailbox authentifiées. Long-poll si elles sont vides (≤ 120 s). | +| `InvitationPublish { payload, ttl, shortcode_len, password }` | Retourne `shortcode` et `expiry`. | +| `InvitationFetch { shortcode, password }` | 3 échecs → invitation détruite. Comparaison en temps constant. | +| `Ping` | Retourne l'heure du serveur (synchronisation des horodatages). | + +Stockage (`ServerStore`, trait asynchrone) : + +* `MemoryStore` : `HashMap` + `tokio::sync::Notify`, pour le dev et les tests. +* `RedisStore` : `LIST mb:{hex}` (avec `EXPIRE`), `PUBLISH mbch:{hex}`, `SET inv:{code} EX`, + `SET invpw:{code}`, `INCR invfa:{code}`, `SET replay:{id} NX EX`. + +--- + +## 5. API publique de la bibliothèque client (`meow-client`) + +```rust +let client = MeowClient::open(path, Password::from(...)).await?; // ou ::create(path, nickname, pw) +client.servers().add("http://localhost:8080").await?; // récupère et épingle la ServerCard +let offer = client.invitations().create("alice", &servers, msg).await?; // étape 1 → InvitationOffer +let answer = client.invitations().answer(&offer, "bob", &servers).await?; // étape 2 +let confirm= client.invitations().accept(&answer).await?; // étape 3 +client.invitations().finalize(&confirm).await?; // étape 4 +client.messages().send_text(contact_id, "hello").await?; +let report = client.sync(Duration::from_secs(30)).await?; // pull/long-poll + traitement +let mut events = client.subscribe(); // Stream +``` + +* Tous les types publics sont des structs Rust idiomatiques (`ContactId`, `Contact`, + `Message`, `Event::{MessageReceived, ContactActivated, DeliveryAck, …}`). Le protobuf + reste interne. +* Erreurs : `thiserror`, un `enum Error` par crate, sans `unwrap` dans les bibliothèques. +* Le cœur est asynchrone (`tokio`). La FFI expose les mêmes méthodes via `flutter_rust_bridge` + (`Future` ↔ `Future`, `Stream` ↔ `Stream`). + +--- + +## 6. Stockage client + +* Une base SQLite par identité (`rusqlite`, `bundled`), en mode WAL. +* Clé maîtresse = Argon2id(mot de passe, sel). Toutes les colonnes sensibles (clés, état DR, + contenu des messages) sont chiffrées en XChaCha20-Poly1305 avec la clé maîtresse et une AAD + `table‖id`. Les index ne contiennent que des identifiants aléatoires. +* Phase 4 : contacts cachés. Des emplacements de taille fixe sont chiffrés avec des clés dérivées + de mots de passe secondaires, et les emplacements vides sont remplis d'aléa indiscernable, ce + qui conserve la déniabilité de la v1. +* Phase 1–3 (provisoire, pour la CLI) : un fichier d'identité unique `*.mwid2` chiffré + (Argon2id + XChaCha20-Poly1305), sauvegardé de façon atomique (écriture puis renommage) et + protégé par un verrou exclusif `*.mwid2.lock` (`File::try_lock`). Deux processus ne peuvent pas + ouvrir la même identité, car le dernier à écrire ferait reculer l'état du ratchet. Ce fichier est + remplacé par `meow-store` en phase 4. +* Invariant : tout changement d'état (ratchet, contact) est **persisté avant** que les octets + correspondants ne quittent l'appareil. + +--- + +## 7. Conventions + +* Edition 2021, MSRV = stable courante. `cargo fmt`, `cargo clippy -D warnings`. +* `#![forbid(unsafe_code)]` partout, sauf dans `meow-ffi`. +* Tests : unitaires dans chaque crate, protocole complet dans `meow-core/tests`, serveur via + `axum` en mémoire, et bout-en-bout avec `tests/e2e.sh`. +* Logs : `tracing`. Jamais de clé, de mailbox ou de contenu au niveau `info`. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..ea886d3 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,23 @@ +# CLAUDE.md — rust/ + +Meow v2 workspace (Rust rewrite of meowlib / meowsrv / meowcli). Protocol v2 is a clean break: +no wire compatibility with the Go v1 stack. + +* Read `ROADMAP.md` first: pick the next ⬜ lot, update its status and the journal when done. +* `ARCHITECTURE.md` is the design reference (crypto constructions, handshake, server API). Keep it in sync. +* Toolchain lives in `~/.cargo/bin` (not on PATH by default): `export PATH=$HOME/.cargo/bin:$PATH`. + +## Commands + +```bash +scripts/check.sh # fmt --check, clippy -D warnings, cargo test --workspace +tests/e2e.sh # full CLI + 2 servers scenario; E2E_STORAGE=redis://... for Redis +``` + +## Rules + +* `meow-core` does no I/O and takes time as a parameter. Keep it that way. +* No `unsafe` (except the future `meow-ffi`); no `unwrap`/`expect` in library code outside tests. +* Persist ratchet/contact state **before** sending the resulting bytes. +* `proto/meow.proto` is the single wire schema (compiled by protox, no protoc needed). Bump/extend, never renumber. +* Never log keys, mailbox ids or message content at `info` level. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..8ef59f3 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2614 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures 0.2.17", + "password-hash", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "beef" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + +[[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 = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[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", + "inout", + "zeroize", +] + +[[package]] +name = "clap" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "futures-core", + "memchr", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[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 = "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 = "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", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "rand_core 0.6.4", + "serde", + "sha2", + "subtle", + "zeroize", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + +[[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.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +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 = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fixedbitset" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-sink", + "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", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[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 = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "logos" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff472f899b4ec2d99161c51f60ff7075eeb3097069a36050d8037a6325eb8154" +dependencies = [ + "logos-derive 0.15.1", +] + +[[package]] +name = "logos" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb2c55a318a87600ea870ff8c2012148b44bf18b74fad48d0f835c38c7d07c5f" +dependencies = [ + "logos-derive 0.16.1", +] + +[[package]] +name = "logos-codegen" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "192a3a2b90b0c05b27a0b2c43eecdb7c415e29243acc3f89cc8247a5b693045c" +dependencies = [ + "beef", + "fnv", + "lazy_static", + "proc-macro2", + "quote", + "regex-syntax", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "logos-codegen" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58b3ffaa284e1350d017a57d04ada118c4583cf260c8fb01e0fe28a2e9cf8970" +dependencies = [ + "fnv", + "proc-macro2", + "quote", + "regex-automata", + "regex-syntax", + "syn 2.0.119", +] + +[[package]] +name = "logos-derive" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "605d9697bcd5ef3a42d38efc51541aa3d6a4a25f7ab6d1ed0da5ac632a26b470" +dependencies = [ + "logos-codegen 0.15.1", +] + +[[package]] +name = "logos-derive" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52d3a9855747c17eaf4383823f135220716ab49bea5fbea7dd42cc9a92f8aa31" +dependencies = [ + "logos-codegen 0.16.1", +] + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "meow-cli" +version = "0.2.0" +dependencies = [ + "anyhow", + "clap", + "meow-client", + "meow-crypto", + "tokio", + "tracing-subscriber", +] + +[[package]] +name = "meow-client" +version = "0.2.0" +dependencies = [ + "futures-util", + "meow-core", + "meow-crypto", + "meow-proto", + "meow-server", + "postcard", + "reqwest", + "serde", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "meow-core" +version = "0.2.0" +dependencies = [ + "meow-crypto", + "meow-proto", + "prost", + "serde", + "thiserror", +] + +[[package]] +name = "meow-crypto" +version = "0.2.0" +dependencies = [ + "argon2", + "chacha20poly1305", + "ed25519-dalek", + "hkdf", + "hmac", + "postcard", + "rand_core 0.6.4", + "serde", + "sha2", + "subtle", + "thiserror", + "x25519-dalek", + "zeroize", +] + +[[package]] +name = "meow-proto" +version = "0.2.0" +dependencies = [ + "prost", + "prost-build", + "protox", +] + +[[package]] +name = "meow-server" +version = "0.2.0" +dependencies = [ + "anyhow", + "async-trait", + "axum", + "clap", + "futures-util", + "meow-core", + "meow-crypto", + "meow-proto", + "redis", + "reqwest", + "serde", + "subtle", + "thiserror", + "tokio", + "toml", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "miette" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" +dependencies = [ + "cfg-if", + "miette-derive", + "unicode-width", +] + +[[package]] +name = "miette-derive" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multimap" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-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 = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[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 = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", + "serde", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn 3.0.10", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ef0b569d1d907ab3a28596aee62cf1f61dacb0529a4bedcd8e7460e2d5228b4" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6e4d69d0fa3e7f6f9cf6b53a0e83e4fc99ba3586f65ce166cff30bd13bb4ad2" +dependencies = [ + "heck", + "itertools", + "log", + "multimap", + "petgraph", + "prettyplease", + "prost", + "prost-types", + "regex", + "syn 3.0.10", + "tempfile", +] + +[[package]] +name = "prost-derive" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad9c5423459fa2f729b8d9235fab810aa29628b171467744fc86d21460ad70d" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "prost-reflect" +version = "0.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01b80ea363c31af2de2b92e3c07ed1156628f7838c4afb4df75ee78a37fedbd1" +dependencies = [ + "logos 0.16.1", + "miette", + "prost", + "prost-types", +] + +[[package]] +name = "prost-types" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f29a7c4c7a84cef41a53d338a2d10d4f1b043ea5c3dde26db22ee2c9c1b1c75b" +dependencies = [ + "prost", +] + +[[package]] +name = "protox" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f25a07a73c6717f0b9bbbd685918f5df9815f7efba450b83d9c9dea41f0e3a1" +dependencies = [ + "bytes", + "miette", + "prost", + "prost-reflect", + "prost-types", + "protox-parse", + "thiserror", +] + +[[package]] +name = "protox-parse" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "072eee358134396a4643dff81cfff1c255c9fbd3fb296be14bdb6a26f9156366" +dependencies = [ + "logos 0.15.1", + "miette", + "prost-types", + "thiserror", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[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 = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20 0.10.2", + "getrandom 0.4.3", + "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_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "redis" +version = "0.32.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "014cc767fefab6a3e798ca45112bccad9c6e0e218fbd49720042716c73cfef44" +dependencies = [ + "bytes", + "cfg-if", + "combine", + "futures-util", + "itoa", + "num-bigint", + "percent-encoding", + "pin-project-lite", + "ryu", + "socket2", + "tokio", + "tokio-util", + "url", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[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 = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +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 = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "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", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "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.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[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-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[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.10", + "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 = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +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 = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core 0.6.4", + "serde", + "zeroize", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" +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 = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[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..6c08497 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,24 @@ +[workspace] +resolver = "2" +members = [ + "crates/meow-proto", + "crates/meow-crypto", + "crates/meow-core", + "crates/meow-client", + "crates/meow-server", + "crates/meow-cli", +] + +[workspace.package] +version = "0.2.0" +edition = "2021" +license = "AGPL-3.0-or-later" + +[workspace.lints.rust] +unsafe_code = "forbid" + + +[profile.release] +lto = "thin" +codegen-units = 1 +strip = true diff --git a/README.md b/README.md new file mode 100644 index 0000000..1901818 --- /dev/null +++ b/README.md @@ -0,0 +1,52 @@ +# Meow v2 — Rust + +Réécriture en Rust de `meowlib`, `meowsrv` et `meowcli`, avec un protocole v2. Voir : + +* [`ARCHITECTURE.md`](ARCHITECTURE.md) : crates, cryptographie, protocole, API ; +* [`ROADMAP.md`](ROADMAP.md) : lots de travail et état d'avancement. + +## Démarrage rapide + +```bash +# toolchain (si absente) : https://rustup.rs +cargo build --release + +# serveur (stockage mémoire ; --storage redis://127.0.0.1:6379/0 pour Redis) +./target/release/meowsrv --listen 127.0.0.1:8080 --name "mon serveur" + +# client +export MEOW_PASSWORD='un mot de passe solide' +meow() { ./target/release/meow -i bob.mwid2 "$@"; } +meow identity create bob +meow server add http://127.0.0.1:8080 +meow invitation create alice # → bob-alice.mwiv2, à transmettre à alice +meow server-invitation create carol # → URL à transmettre à carol +meow send alice "bonjour" +meow # synchronise (= meow sync) +meow longpoll # écoute en continu +``` + +## Tests + +```bash +scripts/check.sh # fmt + clippy -D warnings + tests unitaires et d'intégration +tests/e2e.sh # bout-en-bout : 2 serveurs meowsrv + CLI (équivalent de meowcli/test.sh) +E2E_STORAGE=redis://127.0.0.1:6379/15 tests/e2e.sh # idem avec Redis +MEOW_TEST_REDIS=redis://127.0.0.1:6379/15 cargo test -p meow-server # test du backend Redis +``` + +## Configuration du serveur + +Priorité : options en ligne de commande, puis variables d'environnement `MEOWSRV_*`, puis fichier +TOML (`--config`), puis valeurs par défaut. + +```toml +listen = "0.0.0.0:8080" +public_url = "https://meow.example.org" # annoncée dans la carte signée : doit être exacte +name = "meow example" +description = "serveur de test" +storage = "redis://127.0.0.1:6379/0" +key_file = "/var/lib/meowsrv/server.key" # créée en 0600 au premier démarrage +mailbox_ttl_days = 30 +log = "info" +``` diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..79aaf6d --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,179 @@ +# Meow v2 (Rust) — Roadmap + +Le travail est découpé en **lots** indépendants. Chaque lot : +* tient dans une session de travail (≈ une demi-journée d'agent) ; +* laisse le workspace dans un état qui compile, avec `cargo test` vert ; +* a un **critère de fin** vérifiable. + +Légende : ✅ fait · 🟡 partiel · ⬜ à faire. L'architecture cible est décrite dans +[`ARCHITECTURE.md`](ARCHITECTURE.md). + +Pour reprendre le travail : lire ce fichier, prendre le premier lot ⬜ dont les dépendances sont +✅, puis mettre à jour ce fichier à la fin du lot. Avant de clore un lot, `scripts/check.sh` **et** +`tests/e2e.sh` doivent passer. + +### Ordre conseillé pour la suite + +1. **3.8** livraison au moins une fois (correction de fond, petit lot). +2. **4.1 → 4.5** `meow-store` (prérequis du mobile). +3. **5.5, 5.6, 5.9** file d'envoi, accusés, flux d'événements (prérequis de l'UI). +4. **7.1 → 7.3** FFI et intégration dans bastet. +5. Le reste (phases 8–10) selon les priorités. + +### Journal + +| Date | Lots | Notes | +|---|---|---| +| 2026-11-20 | 0.x, 1.1–1.4, 2.1–2.4, 3.1–3.4, 4.0, 5.1–5.4, 6.1–6.5 | Squelette complet et fonctionnel. 29 tests Rust + `tests/e2e.sh` (≈ 60 appels CLI, 2 serveurs, mémoire et Redis, bascule quand un serveur tombe). Décision : protocole v2 sans compatibilité v1. | + +--- + +## Phase 0 — Fondations + +| Lot | Contenu | Fin | État | +|---|---|---|---| +| 0.1 | Workspace Cargo, conventions (fmt, clippy, `forbid(unsafe)`), `.gitignore` | `cargo build` OK | ✅ | +| 0.2 | `proto/meow.proto` v2 + crate `meow-proto` (prost + protox, **sans protoc**) | Les types sont générés au build | ✅ | +| 0.3 | Script `scripts/check.sh` (fmt + clippy + test) | Le script passe | ✅ | + +## Phase 1 — `meow-crypto` + +| Lot | Contenu | Fin | État | +|---|---|---|---| +| 1.1 | Types de clés (Ed25519, X25519), sérialisation, `zeroize`, `MailboxId` | Tests aller-retour | ✅ | +| 1.2 | AEAD XChaCha20-Poly1305, HKDF à labels, sealed box avec clé de réponse | Tests : chiffrement, altération, mauvaise clé | ✅ | +| 1.3 | Chiffrement au repos par mot de passe (Argon2id) | Tests | ✅ | +| 1.4 | Double Ratchet (spécification Signal), messages hors ordre, `MAX_SKIP`, état sérialisable | Tests : ping-pong, désordre, rejeu refusé, état persisté puis rechargé | ✅ | +| 1.5 | Vecteurs de test figés (KAT) pour les labels v2, et fuzzing des décodeurs (`cargo-fuzz`) | CI fuzz 5 min sans crash | ⬜ | +| 1.6 | Montée de version vers ed25519/x25519-dalek 3.x, chacha20poly1305 0.11 et rand_core 0.10 (on est volontairement sur la génération précédente, stable et cohérente) | Tests verts | ⬜ | + +## Phase 2 — `meow-core` (protocole pur, sans E/S) + +| Lot | Contenu | Fin | État | +|---|---|---|---| +| 2.1 | Modèle : `ContactKeys`, `Contact`, `ServerInfo`, `ContactCard` ↔ proto | Tests | ✅ | +| 2.2 | Invitation 4 étapes (Offer, Answer, Confirm, Ack) avec transcript signé | Test du flux complet et des falsifications | ✅ | +| 2.3 | Codec des messages : `UserMessage` → padding → DR → `PeerEnvelope` | Aller-retour, désordre | ✅ | +| 2.4 | Requêtes serveur : construction, scellement, ouverture des réponses, `MailboxAuth` | Tests | ✅ | +| 2.5 | Rotation des clés de mailbox (`my_next_identity` v1) et révocation de contact | Tests | ⬜ | + +## Phase 3 — `meow-server` (`meowsrv`) + +| Lot | Contenu | Fin | État | +|---|---|---|---| +| 3.1 | axum : `/v2/card`, `/v2/rpc`, `/healthz`, configuration TOML + variables d'env, `server.key` en 0600 | Le serveur démarre | ✅ | +| 3.2 | `MemoryStore` : post, pull, long-poll (`Notify`), invitations (shortcode, mot de passe, 3 essais, TTL) | Tests d'intégration en mémoire | ✅ | +| 3.3 | Vérification de `MailboxAuth` (fenêtre de temps, signature, anti-rejeu) | Tests : rejet d'un pull volé ou rejoué | ✅ | +| 3.4 | `RedisStore` (même trait), sélectionné par `storage = "redis://..."` | Tests avec `redis-server` local (ignorés si absent) | ✅ | +| 3.5 | Limites : taille de corps, nombre de dépôts par requête, quota par mailbox, rate limiting par IP | Tests | 🟡 taille de corps et nombre de dépôts faits | +| 3.6 | Packaging : Dockerfile multi-stage, unité systemd, deb/rpm (`cargo-deb`, `cargo-generate-rpm`) | Image < 30 Mo | ⬜ | +| 3.7 | Statistiques agrégées `/v2/stats` (sans métadonnées par utilisateur) | | ⬜ | +| 3.8 | **Livraison au moins une fois** : aujourd'hui `Pull` *vide* la mailbox (comme en v1), donc un message est perdu si le client tombe entre la réponse et la sauvegarde. Il faut un pull qui renvoie des ids, puis un `Ack { ids }` au pull suivant pour supprimer, avec déduplication côté client par id de message | Test : coupure réseau simulée sans perte | ⬜ **prioritaire** | +| 3.9 | Chiffrer l'offre publiée sur le serveur avec une clé placée dans le fragment de l'URL (`…/inv/#`) : le serveur ne verrait plus le nom ni le message de l'initiateur | Test | ⬜ | + +## Phase 4 — `meow-store` (persistance client) + +| Lot | Contenu | Fin | État | +|---|---|---|---| +| 4.0 | *Provisoire* : fichier d'identité chiffré unique (`*.mwid2`) dans `meow-client`, avec écriture atomique et verrou exclusif | La CLI fonctionne | ✅ | +| 4.1 | Schéma SQLite (identité, serveurs, contacts, sessions DR, messages, fichiers, file d'envoi) + migrations | Tests | ⬜ | +| 4.2 | Chiffrement applicatif des colonnes (AAD `table‖id`), changement de mot de passe | Tests | ⬜ | +| 4.3 | Contacts cachés : emplacements de taille fixe, déverrouillage par mot de passe secondaire | Tests d'indiscernabilité de taille | ⬜ | +| 4.4 | Pagination de l'historique, recherche, aperçus de fichiers | Tests | ⬜ | +| 4.5 | Bascule de `meow-client` du fichier `.mwid2` vers `meow-store` | e2e vert | ⬜ | + +## Phase 5 — `meow-client` (façade asynchrone) + +| Lot | Contenu | Fin | État | +|---|---|---|---| +| 5.1 | Transport HTTP (`reqwest`, rustls), ajout de serveur avec épinglage de la carte | | ✅ | +| 5.2 | Invitation par fichier et par serveur (shortcode et mot de passe) | e2e | ✅ | +| 5.3 | Envoi : dépôt sur tous les serveurs de pull du contact, repli en cas d'échec | e2e | ✅ | +| 5.4 | Réception : un pull par serveur regroupant toutes les mailbox, long-poll, traitement, événements | e2e | ✅ | +| 5.5 | File d'envoi persistante avec retries et backoff, envoi hors ligne | Tests | ⬜ | +| 5.6 | Accusés de réception et de lecture chiffrés (dans le ratchet) | e2e | ⬜ | +| 5.7 | Fichiers : découpage en morceaux, reprise, déduplication, limite de taille | e2e (`send-file`) | 🟡 envoi en un seul morceau | +| 5.8 | Trafic leurre : mailbox fictives dans les pulls, ordre aléatoire, padding des requêtes | Tests | ⬜ | +| 5.9 | Stream d'événements (`tokio::broadcast`) et tâche de synchronisation en arrière-plan | | ⬜ | + +## Phase 6 — `meow-cli` (`meow`) + +| Lot | Contenu | Fin | État | +|---|---|---|---| +| 6.1 | `identity create/show`, `server add/list/remove`, `contact list/show` | | ✅ | +| 6.2 | `invitation create/check/answer/accept/finalize` (fichiers) | e2e | ✅ | +| 6.3 | `server-invitation create/get` | e2e | ✅ | +| 6.4 | `send`, `send-file`, `sync` (commande par défaut), `longpoll` | e2e | ✅ | +| 6.5 | `tests/e2e.sh` : parité avec `meowcli/test.sh` | Script vert | ✅ | +| 6.6 | Sortie `--json` pour l'automatisation, et import d'identité v1 (pseudo et serveurs) | | ⬜ | + +## Phase 7 — `meow-ffi` + intégration Flutter + +| Lot | Contenu | Fin | État | +|---|---|---|---| +| 7.1 | Crate `meow-ffi` (cdylib) avec `flutter_rust_bridge` v2, API miroir de `meow-client` | Génération Dart OK | ⬜ | +| 7.2 | Build Android (`cargo-ndk` arm64-v8a, armeabi-v7a, x86_64) et Linux, script `deploy.sh` | `libmeow_ffi.so` chargé par bastet | ⬜ | +| 7.3 | Adaptateur Dart dans bastet (`lib/meow2/`), remplacement écran par écran de `meowwrapper.dart` | Chat fonctionnel sur Linux | ⬜ | +| 7.4 | Arrière-plan Android : WorkManager + `client.sync()` | Notifications | ⬜ | +| 7.5 | Suppression de `meowjsonlib` et de `meowwrapper.dart` | | ⬜ | + +Correspondance des 63 exports actuels de `meowjsonlib` → API v2 : voir l'annexe A. + +## Phase 8 — Fonctionnalités avancées + +| Lot | Contenu | État | +|---|---|---| +| 8.1 | Chiffrement des en-têtes DR (variante « header encryption » de Signal) | ⬜ | +| 8.2 | Matriochka (multi-saut) : `Forward { next_server, sealed }`, délais aléatoires | ⬜ | +| 8.3 | Multi-appareils (mailbox d'appareil, synchronisation chiffrée) | ⬜ | +| 8.4 | Push WebSocket (`/v2/ws`) en plus du long-poll | ⬜ | +| 8.5 | Visio : émission de jetons LiveKit côté serveur (`VideoRoomRequest`) | ⬜ | +| 8.6 | Groupes (fan-out par paire, puis évaluation de MLS / `openmls`) | ⬜ | +| 8.7 | Portage de `peer_secure` (SAS) : canal Rust + vérification de l'empreinte `transcript` | ⬜ | +| 8.8 | Liste de serveurs connus, échange de cartes, fédération | ⬜ | + +## Phase 9 — Durcissement et livraison + +| Lot | Contenu | État | +|---|---|---| +| 9.1 | Fuzzing continu (décodeurs proto, `open_sealed`, `ratchet_decrypt`, RPC serveur) | ⬜ | +| 9.2 | Mémoire verrouillée pour la clé maîtresse (`memsec`), `zeroize` audité | ⬜ | +| 9.3 | Revue de sécurité externe du protocole v2 (document de spécification formelle) | ⬜ | +| 9.4 | Benchmarks (`criterion`) : v1 Go vs v2 Rust (chiffrement, débit serveur) | ⬜ | +| 9.5 | Builds reproductibles, SBOM, `cargo-audit` / `cargo-deny` en CI | ⬜ | + +## Phase 10 — Migration + +| Lot | Contenu | État | +|---|---|---| +| 10.1 | Déploiement d'un `meowsrv` v2 en parallèle du v1 (port distinct) | ⬜ | +| 10.2 | Import v1 → v2 : pseudo, serveurs, historique des messages (lecture Badger/SQLite v1 via un petit outil Go d'export JSON) | ⬜ | +| 10.3 | Ré-invitation assistée des contacts v1 (message v1 « je passe en v2 » contenant une Offer v2) | ⬜ | +| 10.4 | Arrêt de la v1 | ⬜ | + +--- + +## Annexe A — Correspondance meowjsonlib → API v2 + +| meowjsonlib (v1) | v2 (`meow-client` / FFI) | +|---|---| +| `InitConfig`, `LoadConfig`, `SetConfig`, `SetMemPass`, `GetStoragePath` | `MeowClient::open(path, password)` / `MeowClient::create(...)` | +| `IdentityCreate`, `LoadIdentity`, `GetIdentity` | `MeowClient::create`, `client.identity()` | +| `*Avatar*` | `client.identity().set_avatar(bytes)` (phase 4.4) | +| `MessageServerCard*`, `MessageServerRemove`, `MessageServerSetBackup` | `client.servers().add/list/remove/update` | +| `ContactsList`, `ContactGet`, `ContactUpdate`, `ContactRemove`, `ContactNameExists` | `client.contacts().list/get/update/remove/find_by_name` | +| `InvitationFile*`, `InvitationMessage*`, `InvitationCheck` | `client.invitations().create/answer/accept/finalize/inspect` (octets indépendants du transport) | +| `InvitationServer*` (8 fonctions) | `client.invitations().publish(offer, opts)` / `fetch(url)` : 2 appels | +| `PollServer`, `LongPollAllServerJobs`, `SaveCheckJobs`, `ConsumeInboxFile` | `client.sync(wait)` + `client.subscribe()` (plus de fichiers inbox) | +| `CreateUserMessageAndSendJob`, `ProcessSendQueues`, `ProcessSentMessages`, `CreateAndStoreUserMessage`, `SendMessage` | `client.messages().send(contact, Outgoing{…})` (la file d'envoi est interne) | +| `LoadMessagesHistory`, `GetMessagePreview`, `GetFilePreview`, `MarkMessageProcessed` | `client.messages().history(contact, page)`, `.mark_read(id)` | +| `Test*`, `TestDb`, `ActivateRemoteLogger` | supprimés | + +## Annexe B — Points v1 à ne pas oublier + +* Repérés pendant l'analyse, à corriger dans le dépôt Go tant que la v1 tourne : + * `meowsrv/config/meowsrv.json` versionne la clé privée du serveur **et** `api_key`/`api_secret` LiveKit. **Ces secrets sont à changer.** + * `meowsrv` envoie ses logs en dur à `https://log.redroom.link/loki`. + * Les pulls ne sont pas authentifiés (n'importe qui peut vider une mailbox dont il connaît la clé). + * Le suivi de livraison serveur est cassé (`dvyrq:` vs `msg:`). + * Le TTL des invitations est faux (millisecondes au lieu de secondes ; `mwiv:` n'expire jamais). diff --git a/crates/meow-cli/Cargo.toml b/crates/meow-cli/Cargo.toml new file mode 100644 index 0000000..bbb357f --- /dev/null +++ b/crates/meow-cli/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "meow-cli" +description = "Meow v2 command line client" +version.workspace = true +edition.workspace = true +license.workspace = true + +[[bin]] +name = "meow" +path = "src/main.rs" + +[dependencies] +meow-client = { path = "../meow-client" } +meow-crypto = { path = "../meow-crypto" } +clap = { version = "4", features = ["derive", "env"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros"] } +anyhow = "1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } + +[lints] +workspace = true diff --git a/crates/meow-cli/src/main.rs b/crates/meow-cli/src/main.rs new file mode 100644 index 0000000..ac55a0c --- /dev/null +++ b/crates/meow-cli/src/main.rs @@ -0,0 +1,469 @@ +//! `meow`: command line client for the Meow v2 protocol. +//! +//! Without a sub-command, `meow` synchronises (checks every server once). +//! Results go to stdout; diagnostics go to stderr. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use anyhow::{bail, Context, Result}; +use clap::{Args, Parser, Subcommand}; +use meow_client::{Content, Event, MeowClient, DEFAULT_INVITATION_TTL}; +use meow_crypto::password::KdfParams; + +#[derive(Parser)] +#[command(name = "meow", version, about = "Meow v2 secure messaging CLI")] +struct Cli { + /// Identity file. + #[arg(short, long, env = "MEOW_IDENTITY", global = true)] + identity: Option, + /// Password protecting the identity file. + #[arg(short, long, env = "MEOW_PASSWORD", hide_env_values = true, global = true)] + password: Option, + /// Use very weak key derivation (tests only!). + #[arg(long, env = "MEOW_INSECURE_FAST_KDF", hide = true, global = true)] + insecure_fast_kdf: bool, + /// Where received files are written. + #[arg(long, env = "MEOW_DOWNLOADS", default_value = "downloads", global = true)] + downloads: PathBuf, + /// More logs on stderr (repeat for more). + #[arg(short, long, action = clap::ArgAction::Count, global = true)] + verbose: u8, + #[command(subcommand)] + command: Option, +} + +#[derive(Subcommand)] +enum Cmd { + /// Manage the identity. + #[command(subcommand)] + Identity(IdentityCmd), + /// Manage message servers. + #[command(subcommand)] + Server(ServerCmd), + /// Manage contacts. + #[command(subcommand)] + Contact(ContactCmd), + /// Invitation through files (4 steps). + #[command(subcommand)] + Invitation(InvitationCmd), + /// Invitation through a server shortcode. + #[command(subcommand, name = "server-invitation")] + ServerInvitation(ServerInvitationCmd), + /// Send a text message. + Send { + contact: String, + #[arg(required = true, num_args = 1..)] + text: Vec, + }, + /// Send a file. + #[command(name = "send-file")] + SendFile { contact: String, file: PathBuf }, + /// Check every server once (default command). + Sync { + /// Long-poll for up to this many seconds. + #[arg(short, long, default_value_t = 0)] + wait: u64, + }, + /// Wait for messages continuously. + Longpoll { + #[arg(short, long, default_value_t = 30)] + wait: u64, + /// Exit after the first batch of events (or the first timeout). + #[arg(short, long)] + exit: bool, + }, + /// Show the conversation with a contact. + History { contact: String }, +} + +#[derive(Subcommand)] +enum IdentityCmd { + /// Create a new identity file. + Create { + nickname: String, + #[arg(long)] + force: bool, + }, + /// Show the identity summary. + Show, +} + +#[derive(Subcommand)] +enum ServerCmd { + /// Add a server by URL (its card is fetched and pinned). + Add { + url: String, + }, + List, + Remove { + server: String, + }, +} + +#[derive(Subcommand)] +enum ContactCmd { + List, + Show { name: String }, + Remove { name: String }, +} + +#[derive(Args)] +struct ServerSel { + /// Comma-separated server URLs or names (default: all my servers). + #[arg(short, long, value_delimiter = ',')] + servers: Vec, +} + +#[derive(Subcommand)] +enum InvitationCmd { + /// Step 1: create an invitation file for . + Create { + contact: String, + #[command(flatten)] + sel: ServerSel, + #[arg(short, long, default_value = "")] + message: String, + #[arg(short, long)] + out: Option, + }, + /// Show what an invitation file contains. + Check { file: PathBuf }, + /// Step 2: answer an invitation file. + Answer { + file: PathBuf, + #[command(flatten)] + sel: ServerSel, + /// Local name for the contact (default: the name they gave). + #[arg(short, long)] + name: Option, + #[arg(short, long)] + out: Option, + }, + /// Step 3: accept an answer file, produce the confirmation file. + Accept { + file: PathBuf, + #[arg(short, long)] + out: Option, + }, + /// Step 4: finalize with the confirmation file (sends the ack over the network). + Finalize { file: PathBuf }, +} + +#[derive(Subcommand)] +enum ServerInvitationCmd { + /// Publish an invitation on a server; prints its URL on stdout. + Create { + contact: String, + #[command(flatten)] + sel: ServerSel, + #[arg(short, long, default_value = "")] + message: String, + /// Password the invitee must give (transmit it out of band). + #[arg(long, default_value = "")] + invitation_password: String, + }, + /// Fetch and answer a published invitation. + Get { + url: String, + #[command(flatten)] + sel: ServerSel, + #[arg(short, long)] + name: Option, + #[arg(long, default_value = "")] + invitation_password: String, + }, +} + +fn default_identity() -> PathBuf { + std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_default() + .join(".meow2") + .join("default.mwid2") +} + +struct Ctx { + identity: PathBuf, + password: String, + kdf: KdfParams, + downloads: PathBuf, +} + +impl Ctx { + async fn open(&self) -> Result { + MeowClient::open(&self.identity, &self.password, self.kdf) + .await + .with_context(|| format!("cannot open identity {}", self.identity.display())) + } +} + +#[tokio::main] +async fn main() { + if let Err(e) = run().await { + eprintln!("error: {e:#}"); + std::process::exit(1); + } +} + +async fn run() -> Result<()> { + let cli = Cli::parse(); + let level = match cli.verbose { + 0 => "warn", + 1 => "info", + _ => "debug", + }; + tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| level.into())) + .with_writer(std::io::stderr) + .init(); + let Some(password) = cli.password else { + bail!("a password is required: use --password or the MEOW_PASSWORD environment variable"); + }; + let ctx = Ctx { + identity: cli.identity.unwrap_or_else(default_identity), + password, + kdf: if cli.insecure_fast_kdf { + KdfParams::INSECURE_TEST + } else { + KdfParams::DEFAULT + }, + downloads: cli.downloads, + }; + + match cli.command.unwrap_or(Cmd::Sync { wait: 0 }) { + Cmd::Identity(IdentityCmd::Create { nickname, force }) => { + if let Some(dir) = ctx.identity.parent().filter(|d| !d.as_os_str().is_empty()) { + std::fs::create_dir_all(dir)?; + } + MeowClient::create(&ctx.identity, &nickname, &ctx.password, ctx.kdf, force).await?; + println!("identity {nickname} created in {}", ctx.identity.display()); + } + Cmd::Identity(IdentityCmd::Show) => { + let c = ctx.open().await?; + println!("nickname: {}", c.nickname()); + println!("servers: {}", c.servers().len()); + println!("contacts: {}", c.contacts().len()); + } + Cmd::Server(ServerCmd::Add { url }) => { + let mut c = ctx.open().await?; + let s = c.add_server(&url).await?; + println!("added {} ({}) key {}", s.url, s.name, s.sign_key.fingerprint()); + } + Cmd::Server(ServerCmd::List) => { + let c = ctx.open().await?; + for s in c.servers() { + println!("{}\t{}\t{}", s.url, s.name, s.sign_key.fingerprint()); + } + } + Cmd::Server(ServerCmd::Remove { server }) => { + ctx.open().await?.remove_server(&server).await?; + println!("removed {server}"); + } + Cmd::Contact(ContactCmd::List) => { + let c = ctx.open().await?; + for k in c.contacts() { + println!("{}\t{:?}", k.name, k.state); + } + } + Cmd::Contact(ContactCmd::Show { name }) => { + let c = ctx.open().await?; + let k = c.contact(&name)?; + println!("name: {}", k.name); + println!("presented as: {}", k.my_name); + println!("state: {:?}", k.state); + println!("id: {}", k.id); + if let Some(p) = &k.peer { + println!("their name: {}", p.name); + println!( + "their servers: {}", + p.pull_servers + .iter() + .map(|s| s.url.as_str()) + .collect::>() + .join(", ") + ); + } + println!( + "my servers: {}", + k.my_pull_servers + .iter() + .map(|s| s.url.as_str()) + .collect::>() + .join(", ") + ); + if let Some(sn) = k.safety_number() { + println!("safety number: {sn}"); + } + } + Cmd::Contact(ContactCmd::Remove { name }) => { + ctx.open().await?.remove_contact(&name).await?; + println!("removed {name}"); + } + Cmd::Invitation(cmd) => invitation(&ctx, cmd).await?, + Cmd::ServerInvitation(ServerInvitationCmd::Create { + contact, + sel, + message, + invitation_password, + }) => { + let mut c = ctx.open().await?; + let url = c + .publish_invitation( + &contact, + &sel.servers, + &message, + &invitation_password, + DEFAULT_INVITATION_TTL, + ) + .await?; + println!("{url}"); + } + Cmd::ServerInvitation(ServerInvitationCmd::Get { + url, + sel, + name, + invitation_password, + }) => { + let mut c = ctx.open().await?; + let who = c + .accept_published_invitation(&url, &invitation_password, name.as_deref(), &sel.servers) + .await?; + println!("answered invitation from {who}"); + } + Cmd::Send { contact, text } => { + let r = ctx.open().await?.send_text(&contact, &text.join(" ")).await?; + println!("sent to {contact} ({} server(s))", r.delivered_to); + } + Cmd::SendFile { contact, file } => { + let r = ctx.open().await?.send_file(&contact, &file).await?; + println!("sent {} to {contact} ({} server(s))", file.display(), r.delivered_to); + } + Cmd::Sync { wait } => { + let mut c = ctx.open().await?; + let ev = c.sync(Duration::from_secs(wait)).await?; + print_events(&ctx, &ev)?; + } + Cmd::Longpoll { wait, exit } => { + let mut c = ctx.open().await?; + loop { + let ev = c.sync(Duration::from_secs(wait)).await?; + print_events(&ctx, &ev)?; + if exit { + break; + } + } + } + Cmd::History { contact } => { + let c = ctx.open().await?; + for h in c.history(&contact)? { + let who = if h.outbound { + c.nickname().to_string() + } else { + contact.clone() + }; + match &h.content { + Content::Text(t) => println!("[{who}] {t}"), + Content::File { name, size } => println!("[{who}] "), + } + } + } + } + Ok(()) +} + +fn stem(p: &Path) -> String { + p.file_stem() + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_default() +} + +async fn invitation(ctx: &Ctx, cmd: InvitationCmd) -> Result<()> { + match cmd { + InvitationCmd::Create { + contact, + sel, + message, + out, + } => { + let mut c = ctx.open().await?; + let offer = c + .create_invitation(&contact, &sel.servers, &message, DEFAULT_INVITATION_TTL) + .await?; + let out = out.unwrap_or_else(|| PathBuf::from(format!("{}-{contact}.mwiv2", c.nickname()))); + std::fs::write(&out, offer)?; + println!("{}", out.display()); + } + InvitationCmd::Check { file } => { + let c = ctx.open().await?; + let info = c.inspect_invitation(&std::fs::read(&file)?)?; + println!("from: {}", info.initiator_name); + println!("message: {}", info.message); + println!("expires at: {}", info.expires_at); + println!( + "servers: {}", + info.answer_servers + .iter() + .map(|s| s.url.as_str()) + .collect::>() + .join(", ") + ); + } + InvitationCmd::Answer { file, sel, name, out } => { + let mut c = ctx.open().await?; + let offer = std::fs::read(&file)?; + let initiator = c.inspect_invitation(&offer)?.initiator_name; + let answer = c.answer_invitation(&offer, name.as_deref(), &sel.servers).await?; + let out = out.unwrap_or_else(|| PathBuf::from(format!("{}-{initiator}.mwiv2", c.nickname()))); + std::fs::write(&out, answer)?; + println!("{}", out.display()); + } + InvitationCmd::Accept { file, out } => { + let mut c = ctx.open().await?; + let confirm = c.accept_answer(&std::fs::read(&file)?).await?; + let out = out.unwrap_or_else(|| { + // bob accepting "alice-bob.mwiv2" writes "bob-alice-step3.mwiv2" + let s = stem(&file); + let other = s.split('-').next().unwrap_or("contact").to_string(); + PathBuf::from(format!("{}-{other}-step3.mwiv2", c.nickname())) + }); + std::fs::write(&out, confirm)?; + println!("{}", out.display()); + } + InvitationCmd::Finalize { file } => { + let mut c = ctx.open().await?; + let name = c.finalize_invitation(&std::fs::read(&file)?).await?; + println!("contact {name} is active"); + } + } + Ok(()) +} + +fn safe_name(name: &str) -> String { + let base = Path::new(name) + .file_name() + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_default(); + if base.is_empty() || base.starts_with('.') { + "received.bin".into() + } else { + base + } +} + +fn print_events(ctx: &Ctx, events: &[Event]) -> Result<()> { + for e in events { + match e { + Event::Message { contact, text, .. } => println!("[{contact}] {text}"), + Event::File { contact, name, data } => { + std::fs::create_dir_all(&ctx.downloads)?; + let path = ctx.downloads.join(safe_name(name)); + std::fs::write(&path, data)?; + println!("[{contact}] file saved to {}", path.display()); + } + Event::InvitationAccepted { contact } => println!("invitation accepted by {contact}, confirmation sent"), + Event::ContactActivated { contact } => println!("contact {contact} is active"), + } + } + Ok(()) +} diff --git a/crates/meow-client/Cargo.toml b/crates/meow-client/Cargo.toml new file mode 100644 index 0000000..617286b --- /dev/null +++ b/crates/meow-client/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "meow-client" +description = "Meow v2 high-level async client API" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +meow-core = { path = "../meow-core" } +meow-proto = { path = "../meow-proto" } +meow-crypto = { path = "../meow-crypto" } +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] } +tokio = { version = "1", features = ["fs", "time", "macros"] } +futures-util = "0.3" +serde = { version = "1", features = ["derive"] } +postcard = { version = "1", default-features = false, features = ["alloc"] } +thiserror = "2" +tracing = "0.1" + +[dev-dependencies] +meow-server = { path = "../meow-server" } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net"] } + +[lints] +workspace = true diff --git a/crates/meow-client/src/lib.rs b/crates/meow-client/src/lib.rs new file mode 100644 index 0000000..65dccfd --- /dev/null +++ b/crates/meow-client/src/lib.rs @@ -0,0 +1,698 @@ +//! High-level async client API for Meow v2. +//! +//! [`MeowClient`] owns one identity (profile) and exposes servers, contacts, +//! invitations, messaging and synchronisation. It is the API mirrored by the CLI +//! and, later, by the Flutter FFI layer (`meow-ffi`). +//! +//! Invariant: any ratchet/contact state change is **persisted before** the +//! resulting bytes leave the device, so a crash can never make us reuse a key. + +#![forbid(unsafe_code)] +#![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::expect_used))] + +pub mod profile; +pub mod transport; + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use futures_util::future::join_all; +use meow_core::contact::{Contact, ContactState}; +use meow_core::invitation::{self, OfferInfo}; +use meow_core::server::{canonical_url, ServerInfo}; +use meow_core::{messaging, rpc}; +use meow_crypto::password::KdfParams; +use meow_crypto::{SignPublic, SigningKeyPair}; +use meow_proto::v2::{self, request::Body as Req, response::Body as Resp}; +use meow_proto::Message; + +pub use meow_core::contact::ContactState as State; +pub use profile::{Content, HistoryEntry}; + +/// Maximum file size sent in a single message (chunking: roadmap 5.7). +pub const MAX_FILE_BYTES: usize = 4 * 1024 * 1024; +/// Default invitation lifetime. +pub const DEFAULT_INVITATION_TTL: u64 = 7 * 86_400; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("wrong password or corrupted identity file")] + BadPassword, + #[error("corrupted identity file: {0}")] + Corrupted(String), + #[error("i/o: {0}")] + Io(#[from] std::io::Error), + #[error("network: {0}")] + Network(String), + #[error(transparent)] + Protocol(#[from] meow_core::Error), + #[error("crypto: {0}")] + Crypto(#[from] meow_crypto::CryptoError), + #[error("unknown server: {0}")] + UnknownServer(String), + #[error("server {0} changed its keys: refusing (remove and re-add it if this is expected)")] + ServerKeyChanged(String), + #[error("unknown contact: {0}")] + UnknownContact(String), + #[error("a contact named {0:?} already exists")] + NameTaken(String), + #[error("{0}")] + Invalid(String), + #[error("identity {0} is in use by another process")] + Locked(String), +} + +pub type Result = std::result::Result; + +pub(crate) fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +/// Something that happened during [`MeowClient::sync`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Event { + /// Initiator side: the invitee answered a server-published invitation; the + /// confirmation has been sent automatically. + InvitationAccepted { contact: String }, + /// The handshake is complete on this side. + ContactActivated { contact: String }, + Message { + contact: String, + id: Vec, + text: String, + sent_at_ms: u64, + }, + File { + contact: String, + name: String, + data: Vec, + }, +} + +/// Outcome of a send. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SendReport { + pub message_id: Vec, + /// Number of servers that accepted the deposit. + pub delivered_to: usize, +} + +/// One identity, with its servers, contacts and history. +pub struct MeowClient { + path: PathBuf, + password: String, + kdf: KdfParams, + profile: profile::Profile, + transport: transport::Transport, + /// Exclusive OS lock on `.lock`, held for the client's lifetime: + /// two processes saving the same ratchet state would roll sessions back. + _lock: std::fs::File, +} + +fn lock_identity(path: &Path) -> Result { + let mut lock_path = path.as_os_str().to_owned(); + lock_path.push(".lock"); + let f = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(PathBuf::from(lock_path))?; + match f.try_lock() { + Ok(()) => Ok(f), + Err(std::fs::TryLockError::WouldBlock) => Err(Error::Locked(path.display().to_string())), + Err(std::fs::TryLockError::Error(e)) => Err(Error::Io(e)), + } +} + +impl MeowClient { + // ───────────────────────── lifecycle ───────────────────────── + + /// Create a new identity file. Fails if it exists, unless `overwrite`. + pub async fn create(path: &Path, nickname: &str, password: &str, kdf: KdfParams, overwrite: bool) -> Result { + if !overwrite && path.exists() { + return Err(Error::Invalid(format!( + "{} already exists (use --force)", + path.display() + ))); + } + let c = Self { + path: path.to_path_buf(), + password: password.to_string(), + kdf, + profile: profile::Profile::new(nickname), + transport: transport::Transport::new()?, + _lock: lock_identity(path)?, + }; + c.save().await?; + Ok(c) + } + + /// Open an existing identity file. `kdf` is used for subsequent saves. + pub async fn open(path: &Path, password: &str, kdf: KdfParams) -> Result { + Ok(Self { + path: path.to_path_buf(), + password: password.to_string(), + kdf, + _lock: lock_identity(path)?, + profile: profile::Profile::load(path, password).await?, + transport: transport::Transport::new()?, + }) + } + + pub async fn save(&self) -> Result<()> { + self.profile.save(&self.path, &self.password, self.kdf).await + } + + pub fn nickname(&self) -> &str { + &self.profile.nickname + } + + // ───────────────────────── servers ───────────────────────── + + /// Add a server: fetch its card, verify it and pin its keys (TOFU). + pub async fn add_server(&mut self, url: &str) -> Result { + let info = self.transport.fetch_card(url).await?; + if canonical_url(url) != info.url { + tracing::warn!("server announces {} (contacted as {url})", info.url); + } + if let Some(known) = self + .profile + .servers + .iter() + .find(|s| s.url == info.url || s.sign_key == info.sign_key) + { + if !known.same_keys(&info) { + return Err(Error::ServerKeyChanged(info.url)); + } + return Ok(known.clone()); + } + self.profile.servers.push(info.clone()); + self.save().await?; + Ok(info) + } + + pub fn servers(&self) -> &[ServerInfo] { + &self.profile.servers + } + + pub async fn remove_server(&mut self, url_or_name: &str) -> Result<()> { + let u = canonical_url(url_or_name); + let before = self.profile.servers.len(); + self.profile.servers.retain(|s| s.url != u && s.name != url_or_name); + if self.profile.servers.len() == before { + return Err(Error::UnknownServer(url_or_name.to_string())); + } + self.save().await + } + + /// Resolve URLs to known servers; an empty list means "all my servers". + fn resolve_servers(&self, urls: &[String]) -> Result> { + if urls.is_empty() { + if self.profile.servers.is_empty() { + return Err(Error::Invalid("no server configured: add one first".into())); + } + return Ok(self.profile.servers.clone()); + } + urls.iter() + .map(|u| { + let cu = canonical_url(u); + self.profile + .servers + .iter() + .find(|s| s.url == cu || s.name == *u) + .cloned() + .ok_or_else(|| Error::UnknownServer(u.clone())) + }) + .collect() + } + + // ───────────────────────── contacts ───────────────────────── + + pub fn contacts(&self) -> &[Contact] { + &self.profile.contacts + } + + pub fn contact(&self, name: &str) -> Result<&Contact> { + self.profile + .contacts + .iter() + .find(|c| c.name == name) + .ok_or_else(|| Error::UnknownContact(name.to_string())) + } + + fn contact_index(&self, name: &str) -> Result { + self.profile + .contacts + .iter() + .position(|c| c.name == name) + .ok_or_else(|| Error::UnknownContact(name.to_string())) + } + + fn ensure_free_name(&self, name: &str) -> Result<()> { + if self.profile.contacts.iter().any(|c| c.name == name) { + return Err(Error::NameTaken(name.to_string())); + } + Ok(()) + } + + pub async fn remove_contact(&mut self, name: &str) -> Result<()> { + let i = self.contact_index(name)?; + let c = self.profile.contacts.remove(i); + self.profile.history.retain(|h| h.contact != c.id); + self.save().await + } + + pub fn history(&self, name: &str) -> Result> { + let id = &self.contact(name)?.id; + Ok(self.profile.history.iter().filter(|h| &h.contact == id).collect()) + } + + // ───────────────────────── invitations ───────────────────────── + + /// Step 1: create an invitation for `contact_name`. Returns the encoded offer. + pub async fn create_invitation( + &mut self, + contact_name: &str, + server_urls: &[String], + message: &str, + ttl: u64, + ) -> Result> { + self.ensure_free_name(contact_name)?; + let servers = self.resolve_servers(server_urls)?; + let offer = invitation::create_offer(contact_name, &self.profile.nickname, servers, message, now(), ttl)?; + self.profile.contacts.push(offer.contact); + self.save().await?; + Ok(offer.offer_bytes) + } + + pub fn inspect_invitation(&self, offer_bytes: &[u8]) -> Result { + Ok(invitation::inspect_offer(offer_bytes, now())?) + } + + /// Step 2: answer an offer. Returns the encoded answer (file flow). + pub async fn answer_invitation( + &mut self, + offer_bytes: &[u8], + contact_name: Option<&str>, + server_urls: &[String], + ) -> Result> { + let info = self.inspect_invitation(offer_bytes)?; + let name = contact_name.unwrap_or(&info.initiator_name).to_string(); + self.ensure_free_name(&name)?; + if self + .profile + .contacts + .iter() + .any(|c| c.invitation_id == info.invitation_id) + { + return Err(Error::Invalid("this invitation was already answered".into())); + } + let servers = self.resolve_servers(server_urls)?; + let (contact, answer) = invitation::answer(offer_bytes, &name, &self.profile.nickname, servers, now())?; + self.profile.contacts.push(contact); + self.save().await?; + Ok(answer.encode_to_vec()) + } + + fn by_invitation(&mut self, id: &[u8]) -> Result<&mut Contact> { + self.profile + .contacts + .iter_mut() + .find(|c| c.invitation_id.as_slice() == id) + .ok_or_else(|| Error::Invalid("no pending invitation matches".into())) + } + + /// Step 3 (file flow): process an answer, returns the encoded confirmation. + pub async fn accept_answer(&mut self, answer_bytes: &[u8]) -> Result> { + let msg = v2::InvitationMessage::decode(answer_bytes).map_err(meow_core::Error::from)?; + let contact = self.by_invitation(&msg.invitation_id)?; + let confirm = invitation::accept(contact, &msg, now())?; + self.save().await?; + Ok(confirm.encode_to_vec()) + } + + /// Step 4 (file flow): process a confirmation and send the ack through the network. + pub async fn finalize_invitation(&mut self, confirm_bytes: &[u8]) -> Result { + let msg = v2::InvitationMessage::decode(confirm_bytes).map_err(meow_core::Error::from)?; + let contact = self.by_invitation(&msg.invitation_id)?; + let ack = invitation::finalize(contact, &msg)?; + let deposit = messaging::deposit_for(contact, &ack)?; + let servers = contact + .peer + .as_ref() + .map(|p| p.pull_servers.clone()) + .unwrap_or_default(); + let name = contact.name.clone(); + self.save().await?; + self.deliver(&servers, vec![deposit]).await?; + Ok(name) + } + + /// Step 1 through a server: publish the offer and return its URL + /// (`/inv/`). + pub async fn publish_invitation( + &mut self, + contact_name: &str, + server_urls: &[String], + message: &str, + password: &str, + ttl: u64, + ) -> Result { + let offer = self.create_invitation(contact_name, server_urls, message, ttl).await?; + let server = self.resolve_servers(server_urls)?.remove(0); + let resp = self + .transport + .call( + &server, + Req::InvPublish(v2::InvitationPublish { + payload: offer, + ttl_seconds: ttl.min(u32::MAX as u64) as u32, + shortcode_len: 10, + password: password.to_string(), + }), + Duration::ZERO, + ) + .await?; + match resp { + Resp::InvPublished(p) => Ok(format!("{}/inv/{}", server.url, p.shortcode)), + _ => Err(Error::Network("unexpected response".into())), + } + } + + /// Step 2 through a server: fetch an offer by URL, answer it and post the answer + /// in the initiator's answer mailbox. Returns the initiator's name. + pub async fn accept_published_invitation( + &mut self, + url: &str, + password: &str, + contact_name: Option<&str>, + server_urls: &[String], + ) -> Result { + let (base, code) = url + .rsplit_once("/inv/") + .ok_or_else(|| Error::Invalid("invitation URL must look like /inv/".into()))?; + let server = self.transport.fetch_card(base).await?; + let resp = self + .transport + .call( + &server, + Req::InvFetch(v2::InvitationFetch { + shortcode: code.to_string(), + password: password.to_string(), + }), + Duration::ZERO, + ) + .await?; + let Resp::InvFetched(f) = resp else { + return Err(Error::Network("unexpected response".into())); + }; + let info = self.inspect_invitation(&f.payload)?; + let answer_bytes = self.answer_invitation(&f.payload, contact_name, server_urls).await?; + let answer = v2::InvitationMessage::decode(answer_bytes.as_slice()).map_err(meow_core::Error::from)?; + self.deliver(&info.answer_servers, vec![invitation::answer_deposit(&info, &answer)]) + .await?; + Ok(info.initiator_name) + } + + // ───────────────────────── messaging ───────────────────────── + + pub async fn send_text(&mut self, contact_name: &str, text: &str) -> Result { + let msg = messaging::text(text, now_ms()); + self.send(contact_name, msg, Content::Text(text.to_string())).await + } + + pub async fn send_file(&mut self, contact_name: &str, path: &Path) -> Result { + let data = tokio::fs::read(path).await?; + if data.len() > MAX_FILE_BYTES { + return Err(Error::Invalid(format!("file larger than {MAX_FILE_BYTES} bytes"))); + } + let name = path + .file_name() + .map(|n| n.to_string_lossy().to_string()) + .ok_or_else(|| Error::Invalid("bad file name".into()))?; + let size = data.len() as u64; + let body = v2::user_message::Body::File(v2::FileBody { + filename: name.clone(), + size, + chunk: 0, + chunks: 1, + data, + mime: String::new(), + }); + self.send( + contact_name, + messaging::new_message(body, now_ms()), + Content::File { name, size }, + ) + .await + } + + async fn send(&mut self, contact_name: &str, msg: v2::UserMessage, content: Content) -> Result { + let i = self.contact_index(contact_name)?; + let contact = &mut self.profile.contacts[i]; + let env = messaging::encrypt(contact, &msg)?; + let deposit = messaging::deposit_for(contact, &env)?; + let servers = contact + .peer + .as_ref() + .map(|p| p.pull_servers.clone()) + .unwrap_or_default(); + self.profile.history.push(HistoryEntry { + id: msg.id.clone(), + contact: contact.id.clone(), + outbound: true, + sent_at_ms: msg.sent_at_ms, + received_at: now(), + content, + }); + self.save().await?; + let delivered_to = self.deliver(&servers, vec![deposit]).await?; + Ok(SendReport { + message_id: msg.id, + delivered_to, + }) + } + + /// Post deposits to every server; succeeds if at least one accepted them. + async fn deliver(&self, servers: &[ServerInfo], deposits: Vec) -> Result { + if servers.is_empty() { + return Err(Error::Invalid("contact has no server".into())); + } + let calls = servers.iter().map(|s| { + self.transport.call( + s, + Req::Post(v2::Post { + deposits: deposits.clone(), + }), + Duration::ZERO, + ) + }); + let mut ok = 0; + let mut last_err = None; + for (s, r) in servers.iter().zip(join_all(calls).await) { + match r { + Ok(Resp::PostAck(_)) => ok += 1, + Ok(_) => last_err = Some(Error::Network(format!("{}: unexpected response", s.url))), + Err(e) => { + tracing::warn!("deposit on {} failed: {e}", s.url); + last_err = Some(e); + } + } + } + match (ok, last_err) { + (0, Some(e)) => Err(e), + (n, _) => Ok(n), + } + } + + // ───────────────────────── sync ───────────────────────── + + /// Pull every mailbox on every server (one request per server), process what + /// arrived and return the resulting events. With `wait > 0` the servers hold the + /// request until something arrives or the delay expires (long-poll). + pub async fn sync(&mut self, wait: Duration) -> Result> { + // server (by signing key) → (server, mailbox keys) + let mut jobs: BTreeMap)> = BTreeMap::new(); + for c in &self.profile.contacts { + for (kp, servers) in c.mailboxes() { + for s in servers { + jobs.entry(s.sign_key) + .or_insert_with(|| (s.clone(), Vec::new())) + .1 + .push(kp.clone()); + } + } + } + if jobs.is_empty() { + return Ok(Vec::new()); + } + let wait_s = wait.as_secs().min(u32::MAX as u64) as u32; + let calls = jobs.values().map(|(server, kps)| { + let rid = meow_crypto::random_bytes::<16>().to_vec(); + let ts = now(); + let auths = kps.iter().map(|kp| rpc::mailbox_auth(kp, server, &rid, ts)).collect(); + let req = v2::Request { + request_id: rid, + timestamp: ts, + body: Some(Req::Pull(v2::Pull { + auths, + wait_seconds: wait_s, + })), + }; + self.transport.call_request(server, req, wait) + }); + let results = join_all(calls).await; + + let mut stored = Vec::new(); + let mut failures = 0; + let mut last_err = None; + for ((server, _), r) in jobs.values().zip(results) { + match r { + Ok(Resp::PullResult(p)) => stored.extend(p.messages), + Ok(_) => failures += 1, + Err(e) => { + tracing::warn!("pull on {} failed: {e}", server.url); + failures += 1; + last_err = Some(e); + } + } + } + if failures == jobs.len() { + return Err(last_err.unwrap_or_else(|| Error::Network("all servers failed".into()))); + } + self.process(stored).await + } + + async fn process(&mut self, stored: Vec) -> Result> { + // Handshake messages first (step 2 before step 3), then ratchet messages by arrival. + let mut envs: Vec<(u32, u64, Vec, v2::PeerEnvelope)> = stored + .into_iter() + .filter_map(|m| { + let env = v2::PeerEnvelope::decode(m.payload.as_slice()).ok()?; + let rank = match &env.body { + Some(v2::peer_envelope::Body::Invitation(i)) => i.step, + _ => 10, + }; + Some((rank, m.received_at, m.mailbox, env)) + }) + .collect(); + envs.sort_by_key(|(rank, at, _, _)| (*rank, *at)); + + let mut events = Vec::new(); + let mut outgoing: Vec<(Vec, v2::Deposit)> = Vec::new(); + for (_, received_at, mailbox, env) in envs { + let Some(i) = self.profile.contacts.iter().position(|c| { + c.mailboxes() + .iter() + .any(|(kp, _)| kp.public().as_bytes().as_slice() == mailbox.as_slice()) + }) else { + tracing::debug!("message for an unknown mailbox"); + continue; + }; + let contact = &mut self.profile.contacts[i]; + match env.body { + Some(v2::peer_envelope::Body::Invitation(inv)) if inv.step == 2 => { + match invitation::accept(contact, &inv, now()) { + Ok(confirm) => { + let servers = contact + .peer + .as_ref() + .map(|p| p.pull_servers.clone()) + .unwrap_or_default(); + outgoing.push((servers, invitation::confirm_deposit(contact, &confirm)?)); + events.push(Event::InvitationAccepted { + contact: contact.name.clone(), + }); + } + Err(e) => tracing::debug!("ignoring answer: {e}"), + } + } + Some(v2::peer_envelope::Body::Invitation(inv)) if inv.step == 3 => { + match invitation::finalize(contact, &inv) { + Ok(ack) => { + let servers = contact + .peer + .as_ref() + .map(|p| p.pull_servers.clone()) + .unwrap_or_default(); + outgoing.push((servers, messaging::deposit_for(contact, &ack)?)); + events.push(Event::ContactActivated { + contact: contact.name.clone(), + }); + } + Err(e) => tracing::debug!("ignoring confirmation: {e}"), + } + } + Some(v2::peer_envelope::Body::Ratchet(rm)) => { + let was = contact.state; + let msg = match messaging::decrypt(contact, &rm) { + Ok(m) => m, + // Typically the same deposit received from a second server. + Err(e) => { + tracing::debug!("dropping undecryptable message: {e}"); + continue; + } + }; + let name = contact.name.clone(); + let cid = contact.id.clone(); + if was != ContactState::Active && contact.state == ContactState::Active { + events.push(Event::ContactActivated { contact: name.clone() }); + } + let mut record = |content| { + self.profile.history.push(HistoryEntry { + id: msg.id.clone(), + contact: cid.clone(), + outbound: false, + sent_at_ms: msg.sent_at_ms, + received_at, + content, + }) + }; + match &msg.body { + Some(v2::user_message::Body::Text(t)) => { + record(Content::Text(t.text.clone())); + events.push(Event::Message { + contact: name, + id: msg.id.clone(), + text: t.text.clone(), + sent_at_ms: msg.sent_at_ms, + }); + } + Some(v2::user_message::Body::File(f)) => { + record(Content::File { + name: f.filename.clone(), + size: f.size, + }); + events.push(Event::File { + contact: name, + name: f.filename.clone(), + data: f.data.clone(), + }); + } + _ => {} + } + } + _ => tracing::debug!("ignoring unsupported envelope"), + } + } + // Persist before anything leaves the device. + self.save().await?; + for (servers, deposit) in outgoing { + if let Err(e) = self.deliver(&servers, vec![deposit]).await { + tracing::warn!("could not deliver handshake message: {e}"); + } + } + Ok(events) + } +} diff --git a/crates/meow-client/src/profile.rs b/crates/meow-client/src/profile.rs new file mode 100644 index 0000000..45a6040 --- /dev/null +++ b/crates/meow-client/src/profile.rs @@ -0,0 +1,75 @@ +//! Provisional persistence: one encrypted file per identity (`*.mwid2`). +//! +//! Replaced by the SQLite store of `meow-store` in roadmap phase 4. The whole +//! profile is serialised with postcard and encrypted with Argon2id + +//! XChaCha20-Poly1305 ([`meow_crypto::password`]). + +use std::path::Path; + +use meow_core::contact::{Contact, ContactId}; +use meow_core::server::ServerInfo; +use meow_crypto::password::{self, KdfParams}; +use serde::{Deserialize, Serialize}; + +use crate::{Error, Result}; + +const FORMAT_VERSION: u32 = 1; + +/// One entry of a conversation history. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct HistoryEntry { + pub id: Vec, + pub contact: ContactId, + pub outbound: bool, + pub sent_at_ms: u64, + pub received_at: u64, + pub content: Content, +} + +/// Displayable content of a message. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub enum Content { + Text(String), + File { name: String, size: u64 }, +} + +#[derive(Clone, Serialize, Deserialize)] +pub struct Profile { + pub format: u32, + pub nickname: String, + pub servers: Vec, + pub contacts: Vec, + pub history: Vec, +} + +impl Profile { + pub fn new(nickname: &str) -> Self { + Self { + format: FORMAT_VERSION, + nickname: nickname.to_string(), + servers: vec![], + contacts: vec![], + history: vec![], + } + } + + pub async fn load(path: &Path, password: &str) -> Result { + let blob = tokio::fs::read(path).await?; + let plain = password::decrypt(password.as_bytes(), &blob).map_err(|_| Error::BadPassword)?; + let p: Profile = postcard::from_bytes(&plain).map_err(|e| Error::Corrupted(e.to_string()))?; + if p.format != FORMAT_VERSION { + return Err(Error::Corrupted(format!("unsupported profile format {}", p.format))); + } + Ok(p) + } + + /// Atomic save (write to a temporary file then rename). + pub async fn save(&self, path: &Path, password: &str, kdf: KdfParams) -> Result<()> { + let plain = postcard::to_allocvec(self).map_err(|e| Error::Corrupted(e.to_string()))?; + let blob = password::encrypt(password.as_bytes(), &plain, kdf)?; + let tmp = path.with_extension("tmp"); + tokio::fs::write(&tmp, blob).await?; + tokio::fs::rename(&tmp, path).await?; + Ok(()) + } +} diff --git a/crates/meow-client/src/transport.rs b/crates/meow-client/src/transport.rs new file mode 100644 index 0000000..43b7eb6 --- /dev/null +++ b/crates/meow-client/src/transport.rs @@ -0,0 +1,71 @@ +//! HTTP transport to meow servers. + +use std::time::Duration; + +use meow_core::rpc; +use meow_core::server::{canonical_url, ServerInfo}; +use meow_proto::v2::{request::Body as Req, response::Body as Resp}; + +use crate::{now, Error, Result}; + +#[derive(Clone)] +pub struct Transport { + http: reqwest::Client, +} + +impl Transport { + pub fn new() -> Result { + let http = reqwest::Client::builder() + .connect_timeout(Duration::from_secs(10)) + .user_agent("meow/2") + .build() + .map_err(|e| Error::Network(e.to_string()))?; + Ok(Self { http }) + } + + /// Download and verify a server card. + pub async fn fetch_card(&self, url: &str) -> Result { + let url = canonical_url(url); + let resp = self + .http + .get(format!("{url}/v2/card")) + .timeout(Duration::from_secs(20)) + .send() + .await + .map_err(|e| Error::Network(e.to_string()))? + .error_for_status() + .map_err(|e| Error::Network(e.to_string()))?; + let bytes = resp.bytes().await.map_err(|e| Error::Network(e.to_string()))?; + Ok(ServerInfo::from_bytes(&bytes)?) + } + + /// One sealed RPC. `wait` extends the HTTP timeout for long-polls. + pub async fn call(&self, server: &ServerInfo, body: Req, wait: Duration) -> Result { + let req = rpc::new_request(body, now()); + self.call_request(server, req, wait).await + } + + /// Same as [`Transport::call`] with a prepared request (needed when the body + /// must be bound to the request id, as for pulls). + pub async fn call_request( + &self, + server: &ServerInfo, + req: meow_proto::v2::Request, + wait: Duration, + ) -> Result { + let (wire, pending) = rpc::seal_request(server, &req)?; + let resp = self + .http + .post(format!("{}/v2/rpc", server.url)) + .header("content-type", "application/x-protobuf") + .timeout(wait + Duration::from_secs(30)) + .body(wire) + .send() + .await + .map_err(|e| Error::Network(e.to_string()))? + .error_for_status() + .map_err(|e| Error::Network(e.to_string()))?; + let bytes = resp.bytes().await.map_err(|e| Error::Network(e.to_string()))?; + Ok(rpc::open_response(&pending, &bytes)?) + } +} diff --git a/crates/meow-client/tests/flow.rs b/crates/meow-client/tests/flow.rs new file mode 100644 index 0000000..8611f4b --- /dev/null +++ b/crates/meow-client/tests/flow.rs @@ -0,0 +1,182 @@ +//! End-to-end in-process test: two real HTTP servers (memory store) and three clients. + +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use meow_client::{Event, MeowClient, State}; +use meow_crypto::password::KdfParams; +use meow_server::store::MemoryStore; +use meow_server::{encode_card, AppState, Limits}; +use tokio::sync::broadcast; + +async fn spawn_server() -> String { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let keys = meow_core::server::ServerKeys::generate(); + let (notify, _) = broadcast::channel(1024); + let state = Arc::new(AppState { + card: encode_card(&keys, &url, "test", ""), + keys, + store: Arc::new(MemoryStore::new(notify.clone(), 1000)), + notify, + limits: Limits::default(), + }); + tokio::spawn(meow_server::serve(listener, state)); + url +} + +fn tmpdir() -> PathBuf { + let d = std::env::temp_dir().join(format!("meow-test-{}", rand_suffix())); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn rand_suffix() -> String { + meow_crypto::random_bytes::<8>() + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +async fn client(dir: &std::path::Path, name: &str, servers: &[String]) -> MeowClient { + let mut c = MeowClient::create( + &dir.join(format!("{name}.mwid2")), + name, + "pw", + KdfParams::INSECURE_TEST, + false, + ) + .await + .unwrap(); + for s in servers { + c.add_server(s).await.unwrap(); + } + c +} + +fn texts(events: &[Event]) -> Vec { + events + .iter() + .filter_map(|e| match e { + Event::Message { text, .. } => Some(text.clone()), + _ => None, + }) + .collect() +} + +#[tokio::test(flavor = "multi_thread")] +async fn file_and_server_invitations_then_messaging() { + let s1 = spawn_server().await; + let s2 = spawn_server().await; + let servers = vec![s1.clone(), s2.clone()]; + let dir = tmpdir(); + let mut bob = client(&dir, "bob", &servers).await; + let mut alice = client(&dir, "alice", &servers).await; + let mut remote = client(&dir, "remote", &servers).await; + + // ── file invitation ── + let offer = bob.create_invitation("alice", &[], "hello alice", 3600).await.unwrap(); + assert_eq!(alice.inspect_invitation(&offer).unwrap().initiator_name, "bob"); + let answer = alice.answer_invitation(&offer, None, &[]).await.unwrap(); + let confirm = bob.accept_answer(&answer).await.unwrap(); + assert_eq!(bob.contact("alice").unwrap().state, State::ConfirmSent); + bob.send_text("alice", "sent before finalize").await.unwrap(); + alice.finalize_invitation(&confirm).await.unwrap(); + assert_eq!(alice.contact("bob").unwrap().state, State::Active); + + let ev = bob.sync(Duration::ZERO).await.unwrap(); + assert!(ev.contains(&Event::ContactActivated { + contact: "alice".into() + })); + assert_eq!(bob.contact("alice").unwrap().state, State::Active); + + // ── messaging, delivered on both servers but processed once ── + bob.send_text("alice", "hello").await.unwrap(); + let r = bob.send_text("alice", "again").await.unwrap(); + assert_eq!(r.delivered_to, 2); + let ev = alice.sync(Duration::ZERO).await.unwrap(); + assert_eq!(texts(&ev), vec!["sent before finalize", "hello", "again"]); + assert!(alice.sync(Duration::ZERO).await.unwrap().is_empty()); + + alice.send_text("bob", "hi bob").await.unwrap(); + assert_eq!(texts(&bob.sync(Duration::ZERO).await.unwrap()), vec!["hi bob"]); + + // ── file ── + let f = dir.join("note.txt"); + std::fs::write(&f, b"file content").unwrap(); + bob.send_file("alice", &f).await.unwrap(); + let ev = alice.sync(Duration::ZERO).await.unwrap(); + assert!(ev.contains(&Event::File { + contact: "bob".into(), + name: "note.txt".into(), + data: b"file content".to_vec() + })); + + // ── server invitation ── + let url = bob + .publish_invitation("remote", &[], "via server", "secret", 3600) + .await + .unwrap(); + assert!(remote + .accept_published_invitation(&url, "wrong", None, &[]) + .await + .is_err()); + let who = remote + .accept_published_invitation(&url, "secret", None, &[]) + .await + .unwrap(); + assert_eq!(who, "bob"); + let ev = bob.sync(Duration::ZERO).await.unwrap(); + assert_eq!( + ev, + vec![Event::InvitationAccepted { + contact: "remote".into() + }] + ); + let ev = remote.sync(Duration::ZERO).await.unwrap(); + assert_eq!(ev, vec![Event::ContactActivated { contact: "bob".into() }]); + let ev = bob.sync(Duration::ZERO).await.unwrap(); + assert_eq!( + ev, + vec![Event::ContactActivated { + contact: "remote".into() + }] + ); + + // ── long poll ── + let path = dir.join("alice.mwid2"); + drop(alice); + let waiter = tokio::spawn(async move { + let mut alice = MeowClient::open(&path, "pw", KdfParams::INSECURE_TEST).await.unwrap(); + let start = std::time::Instant::now(); + let ev = alice.sync(Duration::from_secs(20)).await.unwrap(); + (texts(&ev), start.elapsed()) + }); + tokio::time::sleep(Duration::from_millis(500)).await; + bob.send_text("alice", "wake up").await.unwrap(); + let (got, elapsed) = waiter.await.unwrap(); + assert_eq!(got, vec!["wake up"]); + assert!(elapsed < Duration::from_secs(10), "long poll took {elapsed:?}"); + + // ── one process at a time per identity ── + assert!(matches!( + MeowClient::open(&dir.join("bob.mwid2"), "pw", KdfParams::INSECURE_TEST).await, + Err(meow_client::Error::Locked(_)) + )); + drop(bob); + + // ── persistence & wrong password ── + assert!( + MeowClient::open(&dir.join("bob.mwid2"), "nope", KdfParams::INSECURE_TEST) + .await + .is_err() + ); + let bob2 = MeowClient::open(&dir.join("bob.mwid2"), "pw", KdfParams::INSECURE_TEST) + .await + .unwrap(); + assert_eq!(bob2.contacts().len(), 2); + assert_eq!(bob2.history("alice").unwrap().len(), 6); // 5 sent + "hi bob" + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/meow-core/Cargo.toml b/crates/meow-core/Cargo.toml new file mode 100644 index 0000000..b6769e4 --- /dev/null +++ b/crates/meow-core/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "meow-core" +description = "Meow v2 protocol logic (no I/O): cards, invitations, messaging, server requests" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +meow-proto = { path = "../meow-proto" } +meow-crypto = { path = "../meow-crypto" } +prost = "0.14" +serde = { version = "1", features = ["derive"] } +thiserror = "2" + +[lints] +workspace = true diff --git a/crates/meow-core/src/contact.rs b/crates/meow-core/src/contact.rs new file mode 100644 index 0000000..15706b2 --- /dev/null +++ b/crates/meow-core/src/contact.rs @@ -0,0 +1,197 @@ +//! Contacts: per-relationship keys, peer public material and state. + +use meow_crypto::{ratchet::Session, DhKeyPair, DhPublic, SignPublic, SigningKeyPair}; +use meow_proto::{v2, PROTOCOL_VERSION}; +use serde::{Deserialize, Serialize}; + +use crate::server::ServerInfo; +use crate::{proto_err, Error, Result}; + +/// Random contact identifier (16 bytes, hex encoded). +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct ContactId(pub String); + +impl ContactId { + pub fn random() -> Self { + Self(crate::hex(&meow_crypto::random_bytes::<16>())) + } +} + +impl std::fmt::Display for ContactId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +/// My own key material for one relationship. Never shared between contacts. +#[derive(Clone, Serialize, Deserialize)] +pub struct OwnKeys { + pub identity: SigningKeyPair, + pub dh: DhKeyPair, + pub mailbox: SigningKeyPair, + pub ratchet: DhKeyPair, +} + +impl OwnKeys { + pub fn generate() -> Self { + Self { + identity: SigningKeyPair::generate(), + dh: DhKeyPair::generate(), + mailbox: SigningKeyPair::generate(), + ratchet: DhKeyPair::generate(), + } + } + + /// The card I give to this contact. + pub fn card(&self, my_name: &str, pull_servers: &[ServerInfo]) -> v2::ContactCard { + v2::ContactCard { + version: PROTOCOL_VERSION, + name: my_name.to_string(), + identity_key: self.identity.public().to_vec(), + dh_key: self.dh.public().to_vec(), + mailbox: self.mailbox.public().to_vec(), + ratchet_key: self.ratchet.public().to_vec(), + pull_servers: pull_servers.iter().map(ServerInfo::to_card).collect(), + } + } +} + +/// Public material received from a contact. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PeerCard { + pub name: String, + pub identity: SignPublic, + pub dh: DhPublic, + pub mailbox: SignPublic, + pub ratchet: DhPublic, + pub pull_servers: Vec, +} + +impl PeerCard { + pub fn from_proto(c: &v2::ContactCard) -> Result { + if c.version != PROTOCOL_VERSION { + return Err(proto_err("unsupported contact card version")); + } + let pull_servers = c + .pull_servers + .iter() + .map(ServerInfo::from_card) + .collect::>>()?; + if pull_servers.is_empty() { + return Err(proto_err("contact card has no pull server")); + } + Ok(Self { + name: c.name.clone(), + identity: SignPublic::from_slice(&c.identity_key)?, + dh: DhPublic::from_slice(&c.dh_key)?, + mailbox: SignPublic::from_slice(&c.mailbox)?, + ratchet: DhPublic::from_slice(&c.ratchet_key)?, + pull_servers, + }) + } +} + +/// Secrets kept by the initiator between steps 1 and 3. +#[derive(Clone, Serialize, Deserialize)] +pub struct OfferSecrets { + pub offer_dh: DhKeyPair, + pub answer_mailbox: SigningKeyPair, + /// Exact encoded offer, hashed into the transcript. + pub offer_bytes: Vec, + pub expires_at: u64, +} + +/// Lifecycle of a contact. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ContactState { + /// Initiator, step 1 done: waiting for the invitee's answer. + OfferSent, + /// Invitee, step 2 done: waiting for the initiator's confirmation. + AnswerSent, + /// Initiator, step 3 done: can send; waiting for the invitee's ack. + ConfirmSent, + /// Handshake complete on this side. + Active, +} + +/// A contact (one relationship). +#[derive(Clone, Serialize, Deserialize)] +pub struct Contact { + pub id: ContactId, + /// Local name for this contact. + pub name: String, + /// Name I present to this contact. + pub my_name: String, + pub state: ContactState, + pub invitation_id: [u8; 16], + pub invitation_message: String, + /// Initiator only, until step 3. + pub offer: Option, + /// My keys (created at step 2 for the invitee, step 3 for the initiator). + pub keys: Option, + /// Servers where I poll my mailbox for this contact. + pub my_pull_servers: Vec, + pub peer: Option, + /// Serialised Double Ratchet session. + pub session: Option>, + /// Invitee only, between steps 2 and 4: hash of the received offer. + pub offer_hash: Option<[u8; 32]>, + /// Invitee only, between steps 2 and 4: the exact card sent in the answer. + pub sent_card: Option>, + /// Final handshake transcript hash, usable as a safety number. + pub transcript: Option<[u8; 32]>, + pub created_at: u64, +} + +impl Contact { + pub fn can_send(&self) -> bool { + matches!(self.state, ContactState::ConfirmSent | ContactState::Active) && self.session.is_some() + } + + pub(crate) fn load_session(&self) -> Result { + let bytes = self.session.as_ref().ok_or(Error::State("no ratchet session"))?; + Ok(Session::from_bytes(bytes)?) + } + + pub(crate) fn keys(&self) -> Result<&OwnKeys> { + self.keys.as_ref().ok_or(Error::State("contact keys not created yet")) + } + + pub(crate) fn peer(&self) -> Result<&PeerCard> { + self.peer.as_ref().ok_or(Error::State("peer card unknown")) + } + + /// The mailbox I currently poll for this contact, with the key that proves ownership. + pub fn my_mailbox(&self) -> Option<&SigningKeyPair> { + match (&self.keys, &self.offer) { + (Some(k), _) => Some(&k.mailbox), + (None, Some(o)) => Some(&o.answer_mailbox), + _ => None, + } + } + + /// Mailboxes to poll, with the servers to poll them on. + /// + /// While an offer is pending, the initiator also keeps polling the answer mailbox. + pub fn mailboxes(&self) -> Vec<(&SigningKeyPair, &[ServerInfo])> { + let mut v = Vec::new(); + if let Some(k) = &self.keys { + v.push((&k.mailbox, self.my_pull_servers.as_slice())); + } + if let Some(o) = &self.offer { + v.push((&o.answer_mailbox, self.my_pull_servers.as_slice())); + } + v + } + + /// Short human-comparable safety number derived from the handshake transcript. + pub fn safety_number(&self) -> Option { + self.transcript.map(|t| { + t[..10] + .chunks(2) + .map(|c| format!("{:05}", u16::from_be_bytes([c[0], c[1]]))) + .collect::>() + .join(" ") + }) + } +} diff --git a/crates/meow-core/src/invitation.rs b/crates/meow-core/src/invitation.rs new file mode 100644 index 0000000..7346e90 --- /dev/null +++ b/crates/meow-core/src/invitation.rs @@ -0,0 +1,386 @@ +//! Four-step invitation handshake (see ARCHITECTURE.md §3.3). +//! +//! The functions here only transform data; how the bytes travel (file, QR code, +//! server shortcode, mailbox, BLE...) is up to the caller. +//! +//! | step | who | function | produces | +//! |------|-----------|----------------|-------------------------------------------| +//! | 1 | initiator | [`create_offer`] | `InvitationOffer` | +//! | 2 | invitee | [`answer`] | `InvitationMessage` (step 2, sealed) | +//! | 3 | initiator | [`accept`] | `InvitationMessage` (step 3, sealed) | +//! | 4 | invitee | [`finalize`] | `PeerEnvelope` (ratchet `HandshakeAck`) | +//! +//! The initiator becomes `Active` when it decrypts the step-4 ack +//! ([`crate::messaging::decrypt`]). + +use meow_crypto::ratchet::Session; +use meow_crypto::seal::{self, SealedBox}; +use meow_crypto::{kdf, sha256, DhKeyPair, DhPublic, SignPublic, SigningKeyPair}; +use meow_proto::{v2, Message, PROTOCOL_VERSION}; + +use crate::contact::{Contact, ContactId, ContactState, OfferSecrets, OwnKeys, PeerCard}; +use crate::messaging; +use crate::server::ServerInfo; +use crate::{proto_err, Error, Result}; + +const CTX_ANSWER: &str = "invite/answer"; +const CTX_CONFIRM: &str = "invite/confirm"; + +fn offer_hash(offer_bytes: &[u8]) -> [u8; 32] { + sha256(&[b"meow/v2/invite/offer", offer_bytes]) +} + +fn answer_transcript(offer_hash: &[u8; 32], invitee_card: &[u8]) -> [u8; 32] { + sha256(&[b"meow/v2/invite/answer", offer_hash, invitee_card]) +} + +fn confirm_transcript(offer_hash: &[u8; 32], invitee_card: &[u8], initiator_card: &[u8], eph: &DhPublic) -> [u8; 32] { + sha256(&[ + b"meow/v2/invite/confirm", + offer_hash, + invitee_card, + initiator_card, + eph.as_bytes(), + ]) +} + +fn shared_key(dh1: &[u8; 32], dh2: &[u8; 32], dh3: &[u8; 32], transcript: &[u8; 32]) -> Result<[u8; 32]> { + let ikm = [dh1.as_slice(), dh2, dh3].concat(); + Ok(kdf::derive(&ikm, transcript, "invite/x3dh")?) +} + +fn to_sealed(b: SealedBox) -> v2::Sealed { + v2::Sealed { + version: PROTOCOL_VERSION, + ephemeral_key: b.ephemeral.to_vec(), + ciphertext: b.ciphertext, + } +} + +fn from_sealed(s: &v2::Sealed) -> Result { + Ok(SealedBox { + ephemeral: DhPublic::from_slice(&s.ephemeral_key)?, + ciphertext: s.ciphertext.clone(), + }) +} + +fn invitation_id(b: &[u8]) -> Result<[u8; 16]> { + b.try_into().map_err(|_| proto_err("bad invitation id")) +} + +// ───────────────────────────── Step 1 ───────────────────────────── + +/// Result of step 1: the pending contact (to store) and the encoded offer (to transmit). +pub struct NewOffer { + pub contact: Contact, + pub offer_bytes: Vec, +} + +/// Step 1 (initiator): create an offer. +/// +/// `my_pull_servers` are the servers where the answer may be posted and where I will +/// later receive messages from this contact. +pub fn create_offer( + contact_name: &str, + my_name: &str, + my_pull_servers: Vec, + message: &str, + now: u64, + ttl_seconds: u64, +) -> Result { + if my_pull_servers.is_empty() { + return Err(proto_err("at least one server is required")); + } + let id: [u8; 16] = meow_crypto::random_bytes(); + let offer_dh = DhKeyPair::generate(); + let answer_mailbox = SigningKeyPair::generate(); + let expires_at = now + ttl_seconds; + let offer = v2::InvitationOffer { + version: PROTOCOL_VERSION, + invitation_id: id.to_vec(), + initiator_name: my_name.to_string(), + offer_dh_key: offer_dh.public().to_vec(), + answer_mailbox: answer_mailbox.public().to_vec(), + answer_servers: my_pull_servers.iter().map(ServerInfo::to_card).collect(), + message: message.to_string(), + expires_at, + }; + let offer_bytes = offer.encode_to_vec(); + let contact = Contact { + id: ContactId::random(), + name: contact_name.to_string(), + my_name: my_name.to_string(), + state: ContactState::OfferSent, + invitation_id: id, + invitation_message: message.to_string(), + offer: Some(OfferSecrets { + offer_dh, + answer_mailbox, + offer_bytes: offer_bytes.clone(), + expires_at, + }), + keys: None, + my_pull_servers, + peer: None, + session: None, + offer_hash: None, + sent_card: None, + transcript: None, + created_at: now, + }; + Ok(NewOffer { contact, offer_bytes }) +} + +/// Decoded, validated view of an offer, e.g. for "invitation check". +#[derive(Debug, Clone)] +pub struct OfferInfo { + pub invitation_id: [u8; 16], + pub initiator_name: String, + pub message: String, + pub expires_at: u64, + pub answer_servers: Vec, + pub answer_mailbox: SignPublic, +} + +/// Parse and validate an offer. +pub fn inspect_offer(offer_bytes: &[u8], now: u64) -> Result { + let o = v2::InvitationOffer::decode(offer_bytes)?; + if o.version != PROTOCOL_VERSION { + return Err(proto_err("unsupported invitation version")); + } + if o.expires_at < now { + return Err(Error::Expired); + } + DhPublic::from_slice(&o.offer_dh_key)?; + Ok(OfferInfo { + invitation_id: invitation_id(&o.invitation_id)?, + initiator_name: o.initiator_name, + message: o.message, + expires_at: o.expires_at, + answer_servers: o + .answer_servers + .iter() + .map(ServerInfo::from_card) + .collect::>()?, + answer_mailbox: SignPublic::from_slice(&o.answer_mailbox)?, + }) +} + +// ───────────────────────────── Step 2 ───────────────────────────── + +/// Step 2 (invitee): answer an offer. Returns the pending contact and the answer. +pub fn answer( + offer_bytes: &[u8], + contact_name: &str, + my_name: &str, + my_pull_servers: Vec, + now: u64, +) -> Result<(Contact, v2::InvitationMessage)> { + if my_pull_servers.is_empty() { + return Err(proto_err("at least one server is required")); + } + inspect_offer(offer_bytes, now)?; + let offer = v2::InvitationOffer::decode(offer_bytes)?; + let id = invitation_id(&offer.invitation_id)?; + let oh = offer_hash(offer_bytes); + let keys = OwnKeys::generate(); + let card = keys.card(my_name, &my_pull_servers); + let card_bytes = card.encode_to_vec(); + let signature = keys.identity.sign(&answer_transcript(&oh, &card_bytes)).to_vec(); + let body = v2::InvitationAnswerBody { + invitation_id: id.to_vec(), + invitee: Some(card), + signature, + }; + let (sealed, _) = seal::seal( + &DhPublic::from_slice(&offer.offer_dh_key)?, + CTX_ANSWER, + &body.encode_to_vec(), + )?; + let msg = v2::InvitationMessage { + version: PROTOCOL_VERSION, + step: 2, + invitation_id: id.to_vec(), + sealed: Some(to_sealed(sealed)), + }; + let contact = Contact { + id: ContactId::random(), + name: contact_name.to_string(), + my_name: my_name.to_string(), + state: ContactState::AnswerSent, + invitation_id: id, + invitation_message: offer.message, + offer: None, + keys: Some(keys), + my_pull_servers, + peer: None, + session: None, + offer_hash: Some(oh), + sent_card: Some(card_bytes), + transcript: None, + created_at: now, + }; + Ok((contact, msg)) +} + +// ───────────────────────────── Step 3 ───────────────────────────── + +/// Step 3 (initiator): process the answer, create my keys and the confirmation. +/// +/// After this call the contact can already send messages (`ConfirmSent`). +pub fn accept(contact: &mut Contact, msg: &v2::InvitationMessage, now: u64) -> Result { + if contact.state != ContactState::OfferSent { + return Err(Error::State("contact is not waiting for an answer")); + } + if msg.step != 2 || msg.invitation_id != contact.invitation_id { + return Err(proto_err("not an answer to this invitation")); + } + let offer = contact.offer.as_ref().ok_or(Error::State("offer secrets missing"))?; + if offer.expires_at < now { + return Err(Error::Expired); + } + let sealed = from_sealed(msg.sealed.as_ref().ok_or_else(|| proto_err("missing sealed body"))?)?; + let (pt, _) = seal::open(&offer.offer_dh, CTX_ANSWER, &sealed)?; + let body = v2::InvitationAnswerBody::decode(pt.as_slice())?; + if body.invitation_id != contact.invitation_id { + return Err(proto_err("invitation id mismatch")); + } + let invitee_card = body.invitee.ok_or_else(|| proto_err("missing invitee card"))?; + let invitee_bytes = invitee_card.encode_to_vec(); + let peer = PeerCard::from_proto(&invitee_card)?; + let oh = offer_hash(&offer.offer_bytes); + peer.identity + .verify(&answer_transcript(&oh, &invitee_bytes), &body.signature)?; + + let keys = OwnKeys::generate(); + let my_card = keys.card(&contact.my_name, &contact.my_pull_servers); + let my_card_bytes = my_card.encode_to_vec(); + let eph = DhKeyPair::generate(); + let th = confirm_transcript(&oh, &invitee_bytes, &my_card_bytes, &eph.public()); + let sk = shared_key( + keys.dh.dh(&peer.dh)?.as_bytes(), + eph.dh(&peer.dh)?.as_bytes(), + eph.dh(&peer.ratchet)?.as_bytes(), + &th, + )?; + let mut session = Session::init_sender(sk, peer.ratchet)?; + let ack = messaging::new_message( + v2::user_message::Body::HandshakeAck(v2::HandshakeAck { + invitation_id: contact.invitation_id.to_vec(), + }), + now * 1000, + ); + let first = messaging::seal_with( + &mut session, + &ack, + &messaging::ad(&keys.identity.public(), &peer.identity), + )?; + let confirm = v2::InvitationConfirmBody { + invitation_id: contact.invitation_id.to_vec(), + initiator: Some(my_card), + ephemeral_key: eph.public().to_vec(), + signature: keys.identity.sign(&th).to_vec(), + first_message: Some(first), + }; + let (sealed, _) = seal::seal(&peer.dh, CTX_CONFIRM, &confirm.encode_to_vec())?; + + if contact.name.is_empty() { + contact.name = peer.name.clone(); + } + contact.keys = Some(keys); + contact.peer = Some(peer); + contact.session = Some(session.to_bytes()); + contact.offer = None; + contact.transcript = Some(th); + contact.state = ContactState::ConfirmSent; + Ok(v2::InvitationMessage { + version: PROTOCOL_VERSION, + step: 3, + invitation_id: contact.invitation_id.to_vec(), + sealed: Some(to_sealed(sealed)), + }) +} + +// ───────────────────────────── Step 4 ───────────────────────────── + +/// Step 4 (invitee): verify the confirmation, activate the contact and build the ack +/// (a ratchet message to deposit in the initiator's mailbox). +pub fn finalize(contact: &mut Contact, msg: &v2::InvitationMessage) -> Result { + if contact.state != ContactState::AnswerSent { + return Err(Error::State("contact is not waiting for a confirmation")); + } + if msg.step != 3 || msg.invitation_id != contact.invitation_id { + return Err(proto_err("not a confirmation for this invitation")); + } + let keys = contact.keys()?.clone(); + let sealed = from_sealed(msg.sealed.as_ref().ok_or_else(|| proto_err("missing sealed body"))?)?; + let (pt, _) = seal::open(&keys.dh, CTX_CONFIRM, &sealed)?; + let body = v2::InvitationConfirmBody::decode(pt.as_slice())?; + if body.invitation_id != contact.invitation_id { + return Err(proto_err("invitation id mismatch")); + } + let initiator_card = body.initiator.ok_or_else(|| proto_err("missing initiator card"))?; + let peer = PeerCard::from_proto(&initiator_card)?; + let eph = DhPublic::from_slice(&body.ephemeral_key)?; + let oh = contact.offer_hash.ok_or(Error::State("offer hash missing"))?; + let sent_card = contact.sent_card.as_ref().ok_or(Error::State("sent card missing"))?; + let th = confirm_transcript(&oh, sent_card, &initiator_card.encode_to_vec(), &eph); + peer.identity.verify(&th, &body.signature)?; + + let sk = shared_key( + keys.dh.dh(&peer.dh)?.as_bytes(), + keys.dh.dh(&eph)?.as_bytes(), + keys.ratchet.dh(&eph)?.as_bytes(), + &th, + )?; + let mut session = Session::init_receiver(sk, keys.ratchet.clone()); + let first = body.first_message.ok_or_else(|| proto_err("missing first message"))?; + let hello = messaging::open_with( + &mut session, + &first, + &messaging::ad(&peer.identity, &keys.identity.public()), + )?; + match hello.body { + Some(v2::user_message::Body::HandshakeAck(a)) if a.invitation_id == contact.invitation_id => {} + _ => return Err(proto_err("unexpected first message")), + } + + if contact.name.is_empty() { + contact.name = peer.name.clone(); + } + contact.peer = Some(peer); + contact.session = Some(session.to_bytes()); + contact.offer_hash = None; + contact.sent_card = None; + contact.transcript = Some(th); + contact.state = ContactState::Active; + + let ack = messaging::new_message( + v2::user_message::Body::HandshakeAck(v2::HandshakeAck { + invitation_id: contact.invitation_id.to_vec(), + }), + hello.sent_at_ms, + ); + messaging::encrypt(contact, &ack) +} + +/// Wrap a step-2 answer for deposit into the offer's answer mailbox. +pub fn answer_deposit(offer: &OfferInfo, answer: &v2::InvitationMessage) -> v2::Deposit { + let env = v2::PeerEnvelope { + version: PROTOCOL_VERSION, + body: Some(v2::peer_envelope::Body::Invitation(answer.clone())), + }; + v2::Deposit { + mailbox: offer.answer_mailbox.to_vec(), + payload: env.encode_to_vec(), + } +} + +/// Wrap a step-3 confirmation for deposit into the invitee's mailbox. +pub fn confirm_deposit(contact: &Contact, confirm: &v2::InvitationMessage) -> Result { + let env = v2::PeerEnvelope { + version: PROTOCOL_VERSION, + body: Some(v2::peer_envelope::Body::Invitation(confirm.clone())), + }; + messaging::deposit_for(contact, &env) +} diff --git a/crates/meow-core/src/lib.rs b/crates/meow-core/src/lib.rs new file mode 100644 index 0000000..7008df2 --- /dev/null +++ b/crates/meow-core/src/lib.rs @@ -0,0 +1,59 @@ +//! Meow v2 protocol logic. +//! +//! This crate performs **no I/O**: no network, no disk, no implicit clock (the current +//! time is always passed as a parameter). It is shared by the server, the CLI and the +//! mobile FFI layer, and is fully deterministic to test. +//! +//! * [`server`]: server cards, server key material; +//! * [`contact`]: per-contact keys and state; +//! * [`invitation`]: the 4-step invitation handshake; +//! * [`messaging`]: user messages ↔ Double Ratchet envelopes; +//! * [`rpc`]: sealed client ↔ server requests and mailbox authentication. + +#![forbid(unsafe_code)] +#![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::expect_used))] + +pub mod contact; +pub mod invitation; +pub mod messaging; +pub mod rpc; +pub mod server; + +pub use meow_crypto as crypto; +pub use meow_proto::v2 as proto; + +/// Errors of the protocol layer. +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("crypto: {0}")] + Crypto(#[from] meow_crypto::CryptoError), + #[error("decode: {0}")] + Decode(#[from] prost::DecodeError), + #[error("protocol: {0}")] + Protocol(String), + #[error("invalid state: {0}")] + State(&'static str), + #[error("expired")] + Expired, +} + +pub type Result = std::result::Result; + +pub(crate) fn proto_err(msg: impl Into) -> Error { + Error::Protocol(msg.into()) +} + +pub(crate) fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +/// Parse a lower/upper-case hex string. +pub fn from_hex(s: &str) -> Option> { + if !s.len().is_multiple_of(2) { + return None; + } + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()) + .collect() +} diff --git a/crates/meow-core/src/messaging.rs b/crates/meow-core/src/messaging.rs new file mode 100644 index 0000000..a0d2852 --- /dev/null +++ b/crates/meow-core/src/messaging.rs @@ -0,0 +1,99 @@ +//! User messages ↔ Double Ratchet envelopes. +//! +//! ```text +//! UserMessage → protobuf → pad → DR encrypt (ad = label ‖ sender id ‖ receiver id) → RatchetMessage +//! ``` +//! There is no signature: authenticity comes from the ratchet, which keeps messages deniable. + +use meow_crypto::ratchet::{Header, Session}; +use meow_crypto::{pad, DhPublic, SignPublic}; +use meow_proto::{v2, Message, PROTOCOL_VERSION}; + +use crate::contact::{Contact, ContactState}; +use crate::{proto_err, Error, Result}; + +const AD_LABEL: &[u8] = b"meow/v2/msg"; + +pub(crate) fn ad(sender: &SignPublic, receiver: &SignPublic) -> Vec { + [AD_LABEL, sender.as_bytes(), receiver.as_bytes()].concat() +} + +/// Build a user message with a fresh random id. +pub fn new_message(body: v2::user_message::Body, now_ms: u64) -> v2::UserMessage { + v2::UserMessage { + id: meow_crypto::random_bytes::<16>().to_vec(), + sent_at_ms: now_ms, + body: Some(body), + reply_to: Vec::new(), + } +} + +pub fn text(text: &str, now_ms: u64) -> v2::UserMessage { + new_message( + v2::user_message::Body::Text(v2::TextBody { text: text.to_string() }), + now_ms, + ) +} + +pub(crate) fn seal_with(session: &mut Session, msg: &v2::UserMessage, ad: &[u8]) -> Result { + let padded = pad::pad(&msg.encode_to_vec()); + let (h, ciphertext) = session.encrypt(&padded, ad)?; + Ok(v2::RatchetMessage { + header: Some(v2::RatchetHeader { + dh_key: h.dh.to_vec(), + previous_count: h.pn, + message_number: h.n, + }), + ciphertext, + }) +} + +pub(crate) fn open_with(session: &mut Session, rm: &v2::RatchetMessage, ad: &[u8]) -> Result { + let h = rm.header.as_ref().ok_or_else(|| proto_err("missing ratchet header"))?; + let header = Header { + dh: DhPublic::from_slice(&h.dh_key)?, + pn: h.previous_count, + n: h.message_number, + }; + let padded = session.decrypt(&header, &rm.ciphertext, ad)?; + Ok(v2::UserMessage::decode(pad::unpad(&padded)?)?) +} + +/// Encrypt a message for `contact`; updates the stored session. +pub fn encrypt(contact: &mut Contact, msg: &v2::UserMessage) -> Result { + if !contact.can_send() { + return Err(Error::State("contact cannot receive messages yet")); + } + let ad = ad(&contact.keys()?.identity.public(), &contact.peer()?.identity); + let mut session = contact.load_session()?; + let rm = seal_with(&mut session, msg, &ad)?; + contact.session = Some(session.to_bytes()); + Ok(v2::PeerEnvelope { + version: PROTOCOL_VERSION, + body: Some(v2::peer_envelope::Body::Ratchet(rm)), + }) +} + +/// Decrypt a ratchet message from `contact`; updates the stored session. +/// +/// A `HandshakeAck` received by the initiator completes the invitation (state → Active). +pub fn decrypt(contact: &mut Contact, rm: &v2::RatchetMessage) -> Result { + let ad = ad(&contact.peer()?.identity, &contact.keys()?.identity.public()); + let mut session = contact.load_session()?; + let msg = open_with(&mut session, rm, &ad)?; + contact.session = Some(session.to_bytes()); + if let Some(v2::user_message::Body::HandshakeAck(ack)) = &msg.body { + if ack.invitation_id == contact.invitation_id && contact.state == ContactState::ConfirmSent { + contact.state = ContactState::Active; + } + } + Ok(msg) +} + +/// Wrap an envelope into a deposit for the contact's mailbox. +pub fn deposit_for(contact: &Contact, env: &v2::PeerEnvelope) -> Result { + Ok(v2::Deposit { + mailbox: contact.peer()?.mailbox.to_vec(), + payload: env.encode_to_vec(), + }) +} diff --git a/crates/meow-core/src/rpc.rs b/crates/meow-core/src/rpc.rs new file mode 100644 index 0000000..01ff24a --- /dev/null +++ b/crates/meow-core/src/rpc.rs @@ -0,0 +1,189 @@ +//! Sealed client ↔ server requests and mailbox authentication. +//! +//! Requests are sealed to the server's X25519 key; the response is encrypted with the +//! key derived alongside (`k_resp`). The client is therefore anonymous to the server. +//! Pulling a mailbox requires a signature with the mailbox private key, bound to the +//! server, the request id and a timestamp. + +use meow_crypto::aead::{self, Key}; +use meow_crypto::seal::{self, SealedBox}; +use meow_crypto::{DhPublic, SignPublic, SigningKeyPair}; +use meow_proto::{v2, Message, PROTOCOL_VERSION}; + +use crate::server::{ServerInfo, ServerKeys}; +use crate::{proto_err, Error, Result}; + +const CTX_REQUEST: &str = "rpc/request"; +const AAD_RESPONSE: &[u8] = b"meow/v2/rpc/response"; +const PULL_LABEL: &[u8] = b"meow/v2/pull"; + +/// Maximum accepted clock skew for mailbox authentications, in seconds. +pub const AUTH_WINDOW_SECS: u64 = 300; + +/// Client-side state needed to read the response of a sealed request. +pub struct PendingCall { + key: Key, + request_id: Vec, +} + +/// Build a request with a fresh random id. +pub fn new_request(body: v2::request::Body, now: u64) -> v2::Request { + v2::Request { + request_id: meow_crypto::random_bytes::<16>().to_vec(), + timestamp: now, + body: Some(body), + } +} + +/// Client: seal a request for `server`. +pub fn seal_request(server: &ServerInfo, req: &v2::Request) -> Result<(Vec, PendingCall)> { + let (sealed, key) = seal::seal(&server.dh_key, CTX_REQUEST, &req.encode_to_vec())?; + let wire = v2::SealedRequest { + version: PROTOCOL_VERSION, + ephemeral_key: sealed.ephemeral.to_vec(), + ciphertext: sealed.ciphertext, + }; + Ok(( + wire.encode_to_vec(), + PendingCall { + key, + request_id: req.request_id.clone(), + }, + )) +} + +/// Client: decrypt and check a response. Server-side errors become [`Error::Protocol`]. +pub fn open_response(call: &PendingCall, bytes: &[u8]) -> Result { + let wire = v2::SealedResponse::decode(bytes)?; + let pt = aead::decrypt(&call.key, &wire.ciphertext, AAD_RESPONSE)?; + let resp = v2::Response::decode(pt.as_slice())?; + if resp.request_id != call.request_id { + return Err(proto_err("response does not match request")); + } + match resp.body { + Some(v2::response::Body::Error(e)) => Err(proto_err(format!( + "server error {:?}: {}", + v2::error::Code::try_from(e.code).unwrap_or(v2::error::Code::Unspecified), + e.message + ))), + Some(b) => Ok(b), + None => Err(proto_err("empty response")), + } +} + +/// Server: open a sealed request. Returns the request and the response key. +pub fn open_request(keys: &ServerKeys, bytes: &[u8]) -> Result<(v2::Request, Key)> { + let wire = v2::SealedRequest::decode(bytes)?; + if wire.version != PROTOCOL_VERSION { + return Err(proto_err("unsupported request version")); + } + let sealed = SealedBox { + ephemeral: DhPublic::from_slice(&wire.ephemeral_key)?, + ciphertext: wire.ciphertext, + }; + let (pt, key) = seal::open(&keys.dh, CTX_REQUEST, &sealed)?; + Ok((v2::Request::decode(pt.as_slice())?, key)) +} + +/// Server: encrypt a response with the key returned by [`open_request`]. +pub fn seal_response(key: &Key, resp: &v2::Response) -> Vec { + v2::SealedResponse { + version: PROTOCOL_VERSION, + ciphertext: aead::encrypt(key, &resp.encode_to_vec(), AAD_RESPONSE), + } + .encode_to_vec() +} + +fn pull_message(server_sign: &SignPublic, mailbox: &SignPublic, ts: u64, request_id: &[u8]) -> Vec { + [ + PULL_LABEL, + server_sign.as_bytes(), + mailbox.as_bytes(), + &ts.to_be_bytes(), + request_id, + ] + .concat() +} + +/// Client: prove ownership of a mailbox for one pull request. +pub fn mailbox_auth(mailbox: &SigningKeyPair, server: &ServerInfo, request_id: &[u8], now: u64) -> v2::MailboxAuth { + let pk = mailbox.public(); + v2::MailboxAuth { + mailbox: pk.to_vec(), + timestamp: now, + signature: mailbox + .sign(&pull_message(&server.sign_key, &pk, now, request_id)) + .to_vec(), + } +} + +/// Server: verify a mailbox authentication. Replay protection on `request_id` is the +/// caller's job (it needs shared state). +pub fn verify_mailbox_auth( + server_sign: &SignPublic, + request_id: &[u8], + auth: &v2::MailboxAuth, + now: u64, +) -> Result { + let mailbox = SignPublic::from_slice(&auth.mailbox)?; + if auth.timestamp.abs_diff(now) > AUTH_WINDOW_SECS { + return Err(Error::Expired); + } + mailbox.verify( + &pull_message(server_sign, &mailbox, auth.timestamp, request_id), + &auth.signature, + )?; + Ok(mailbox) +} + +/// Server helper: build an error response. +pub fn error_response(request_id: Vec, code: v2::error::Code, message: &str) -> v2::Response { + v2::Response { + request_id, + body: Some(v2::response::Body::Error(v2::Error { + code: code as i32, + message: message.to_string(), + })), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn request_response_roundtrip() { + let keys = ServerKeys::generate(); + let info = ServerInfo::from_card(&keys.card("http://s", "s", "", 1)).unwrap(); + let req = new_request(v2::request::Body::Ping(v2::Ping {}), 10); + let (wire, call) = seal_request(&info, &req).unwrap(); + let (got, key) = open_request(&keys, &wire).unwrap(); + assert_eq!(got, req); + let resp = v2::Response { + request_id: got.request_id.clone(), + body: Some(v2::response::Body::Pong(v2::Pong { server_time: 11 })), + }; + let body = open_response(&call, &seal_response(&key, &resp)).unwrap(); + assert_eq!(body, v2::response::Body::Pong(v2::Pong { server_time: 11 })); + // a response for another request is rejected + let other = v2::Response { + request_id: vec![0; 16], + ..resp + }; + assert!(open_response(&call, &seal_response(&key, &other)).is_err()); + } + + #[test] + fn mailbox_auth_checks() { + let keys = ServerKeys::generate(); + let info = ServerInfo::from_card(&keys.card("http://s", "s", "", 1)).unwrap(); + let mb = SigningKeyPair::generate(); + let auth = mailbox_auth(&mb, &info, b"rid", 1000); + let sp = keys.sign.public(); + assert_eq!(verify_mailbox_auth(&sp, b"rid", &auth, 1100).unwrap(), mb.public()); + assert!(verify_mailbox_auth(&sp, b"other", &auth, 1100).is_err()); + assert!(verify_mailbox_auth(&sp, b"rid", &auth, 1000 + AUTH_WINDOW_SECS + 1).is_err()); + let other_server = ServerKeys::generate().sign.public(); + assert!(verify_mailbox_auth(&other_server, b"rid", &auth, 1000).is_err()); + } +} diff --git a/crates/meow-core/src/server.rs b/crates/meow-core/src/server.rs new file mode 100644 index 0000000..2551318 --- /dev/null +++ b/crates/meow-core/src/server.rs @@ -0,0 +1,121 @@ +//! Server cards and server key material. + +use meow_crypto::{DhKeyPair, DhPublic, SignPublic, SigningKeyPair}; +use meow_proto::{v2, Message, PROTOCOL_VERSION}; +use serde::{Deserialize, Serialize}; + +use crate::{proto_err, Result}; + +/// Normalise a server URL (no trailing slash). +pub fn canonical_url(url: &str) -> String { + url.trim().trim_end_matches('/').to_string() +} + +/// A verified server card, as known by clients. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServerInfo { + pub url: String, + pub name: String, + pub description: String, + pub sign_key: SignPublic, + pub dh_key: DhPublic, + pub issued_at: u64, + pub signature: Vec, +} + +fn signed_bytes(card: &v2::ServerCard) -> Vec { + let mut c = card.clone(); + c.signature.clear(); + [b"meow/v2/server-card".as_slice(), &c.encode_to_vec()].concat() +} + +impl ServerInfo { + /// Parse and verify a self-signed card. + pub fn from_card(card: &v2::ServerCard) -> Result { + if card.version != PROTOCOL_VERSION { + return Err(proto_err("unsupported server card version")); + } + let sign_key = SignPublic::from_slice(&card.sign_key)?; + sign_key.verify(&signed_bytes(card), &card.signature)?; + Ok(Self { + url: canonical_url(&card.url), + name: card.name.clone(), + description: card.description.clone(), + sign_key, + dh_key: DhPublic::from_slice(&card.dh_key)?, + issued_at: card.issued_at, + signature: card.signature.clone(), + }) + } + + pub fn from_bytes(b: &[u8]) -> Result { + Self::from_card(&v2::ServerCard::decode(b)?) + } + + pub fn to_card(&self) -> v2::ServerCard { + v2::ServerCard { + version: PROTOCOL_VERSION, + name: self.name.clone(), + description: self.description.clone(), + url: self.url.clone(), + sign_key: self.sign_key.to_vec(), + dh_key: self.dh_key.to_vec(), + issued_at: self.issued_at, + signature: self.signature.clone(), + } + } + + /// Same server keys (used to detect key changes when re-fetching a card). + pub fn same_keys(&self, other: &ServerInfo) -> bool { + self.sign_key == other.sign_key && self.dh_key == other.dh_key + } +} + +/// Private key material of a server. +#[derive(Clone, Serialize, Deserialize)] +pub struct ServerKeys { + pub sign: SigningKeyPair, + pub dh: DhKeyPair, +} + +impl ServerKeys { + pub fn generate() -> Self { + Self { + sign: SigningKeyPair::generate(), + dh: DhKeyPair::generate(), + } + } + + /// Build the self-signed card for this server. + pub fn card(&self, url: &str, name: &str, description: &str, now: u64) -> v2::ServerCard { + let mut card = v2::ServerCard { + version: PROTOCOL_VERSION, + name: name.to_string(), + description: description.to_string(), + url: canonical_url(url), + sign_key: self.sign.public().to_vec(), + dh_key: self.dh.public().to_vec(), + issued_at: now, + signature: Vec::new(), + }; + card.signature = self.sign.sign(&signed_bytes(&card)).to_vec(); + card + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn card_roundtrip_and_tamper() { + let keys = ServerKeys::generate(); + let card = keys.card("http://localhost:8080/", "srv", "desc", 42); + let info = ServerInfo::from_card(&card).unwrap(); + assert_eq!(info.url, "http://localhost:8080"); + assert_eq!(info.to_card(), card); + let mut bad = card.clone(); + bad.url = "http://evil".into(); + assert!(ServerInfo::from_card(&bad).is_err()); + } +} diff --git a/crates/meow-core/tests/handshake.rs b/crates/meow-core/tests/handshake.rs new file mode 100644 index 0000000..be84ce0 --- /dev/null +++ b/crates/meow-core/tests/handshake.rs @@ -0,0 +1,121 @@ +//! Full protocol flow without any I/O: invitation then bidirectional messaging. + +use meow_core::contact::ContactState; +use meow_core::proto::{peer_envelope, user_message}; +use meow_core::server::{ServerInfo, ServerKeys}; +use meow_core::{invitation, messaging}; + +fn server() -> ServerInfo { + ServerInfo::from_card(&ServerKeys::generate().card("http://localhost:8080", "s", "", 1)).unwrap() +} + +fn ratchet(env: &meow_core::proto::PeerEnvelope) -> &meow_core::proto::RatchetMessage { + match env.body.as_ref().unwrap() { + peer_envelope::Body::Ratchet(r) => r, + _ => panic!("not a ratchet message"), + } +} + +fn text_of(m: &meow_core::proto::UserMessage) -> &str { + match m.body.as_ref().unwrap() { + user_message::Body::Text(t) => &t.text, + _ => panic!("not text"), + } +} + +#[test] +fn full_invitation_and_messaging() { + let now = 1_000_000; + let srv = server(); + + // 1. bob invites alice + let offer = invitation::create_offer("alice", "bob", vec![srv.clone()], "hi!", now, 3600).unwrap(); + let mut bob_side = offer.contact; + assert_eq!(bob_side.state, ContactState::OfferSent); + let info = invitation::inspect_offer(&offer.offer_bytes, now).unwrap(); + assert_eq!(info.initiator_name, "bob"); + assert_eq!(info.message, "hi!"); + + // 2. alice answers + let (mut alice_side, answer) = + invitation::answer(&offer.offer_bytes, "bob", "alice", vec![srv.clone()], now).unwrap(); + assert_eq!(alice_side.state, ContactState::AnswerSent); + assert!(!alice_side.can_send()); + + // 3. bob accepts: he can send right away + let confirm = invitation::accept(&mut bob_side, &answer, now).unwrap(); + assert_eq!(bob_side.state, ContactState::ConfirmSent); + let early = messaging::encrypt(&mut bob_side, &messaging::text("early bird", 1)).unwrap(); + + // 4. alice finalizes and produces the ack + let ack = invitation::finalize(&mut alice_side, &confirm).unwrap(); + assert_eq!(alice_side.state, ContactState::Active); + assert_eq!(alice_side.transcript, bob_side.transcript); + assert_eq!(alice_side.safety_number(), bob_side.safety_number()); + + // the early message is readable after finalisation + let m = messaging::decrypt(&mut alice_side, ratchet(&early)).unwrap(); + assert_eq!(text_of(&m), "early bird"); + + // bob gets the ack → active + messaging::decrypt(&mut bob_side, ratchet(&ack)).unwrap(); + assert_eq!(bob_side.state, ContactState::Active); + + // conversation + for i in 0..3 { + let e = messaging::encrypt(&mut alice_side, &messaging::text(&format!("a{i}"), 2)).unwrap(); + assert_eq!( + text_of(&messaging::decrypt(&mut bob_side, ratchet(&e)).unwrap()), + format!("a{i}") + ); + let e = messaging::encrypt(&mut bob_side, &messaging::text(&format!("b{i}"), 3)).unwrap(); + assert_eq!( + text_of(&messaging::decrypt(&mut alice_side, ratchet(&e)).unwrap()), + format!("b{i}") + ); + } + + // deposits target the peer's mailbox + let d = messaging::deposit_for(&bob_side, &early).unwrap(); + assert_eq!(d.mailbox, alice_side.keys.as_ref().unwrap().mailbox.public().to_vec()); +} + +#[test] +fn tampered_answer_is_rejected() { + let now = 10; + let srv = server(); + let offer = invitation::create_offer("alice", "bob", vec![srv.clone()], "", now, 60).unwrap(); + let mut bob_side = offer.contact; + let (_, mut answer) = invitation::answer(&offer.offer_bytes, "bob", "alice", vec![srv.clone()], now).unwrap(); + let sealed = answer.sealed.as_mut().unwrap(); + let n = sealed.ciphertext.len(); + sealed.ciphertext[n - 1] ^= 1; + assert!(invitation::accept(&mut bob_side, &answer, now).is_err()); + assert_eq!(bob_side.state, ContactState::OfferSent); +} + +#[test] +fn confirm_for_another_invitee_is_rejected() { + let now = 10; + let srv = server(); + let offer = invitation::create_offer("alice", "bob", vec![srv.clone()], "", now, 60).unwrap(); + let mut bob_side = offer.contact; + let (mut alice_side, answer) = + invitation::answer(&offer.offer_bytes, "bob", "alice", vec![srv.clone()], now).unwrap(); + // mallory answers the same offer too; bob accepts mallory's answer + let (_, mallory_answer) = invitation::answer(&offer.offer_bytes, "bob", "mallory", vec![srv.clone()], now).unwrap(); + let confirm = invitation::accept(&mut bob_side, &mallory_answer, now).unwrap(); + // the confirm is sealed to mallory: alice cannot use it + assert!(invitation::finalize(&mut alice_side, &confirm).is_err()); + assert_eq!(alice_side.state, ContactState::AnswerSent); + // and bob cannot accept twice + assert!(invitation::accept(&mut bob_side, &answer, now).is_err()); +} + +#[test] +fn expired_offer() { + let srv = server(); + let offer = invitation::create_offer("alice", "bob", vec![srv.clone()], "", 100, 10).unwrap(); + assert!(invitation::inspect_offer(&offer.offer_bytes, 111).is_err()); + assert!(invitation::answer(&offer.offer_bytes, "bob", "alice", vec![srv], 111).is_err()); +} diff --git a/crates/meow-crypto/Cargo.toml b/crates/meow-crypto/Cargo.toml new file mode 100644 index 0000000..01c33e3 --- /dev/null +++ b/crates/meow-crypto/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "meow-crypto" +description = "Meow v2 cryptographic primitives: keys, sealed boxes, Double Ratchet, at-rest encryption" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +ed25519-dalek = { version = "2.1", features = ["rand_core", "zeroize"] } +x25519-dalek = { version = "2.0", features = ["static_secrets", "zeroize"] } +chacha20poly1305 = "0.10" +hkdf = "0.12" +hmac = "0.12" +sha2 = "0.10" +argon2 = "0.5" +rand_core = { version = "0.6", features = ["getrandom"] } +zeroize = { version = "1", features = ["derive"] } +subtle = "2" +thiserror = "2" +serde = { version = "1", features = ["derive"] } +postcard = { version = "1", default-features = false, features = ["alloc"] } + +[lints] +workspace = true diff --git a/crates/meow-crypto/src/aead.rs b/crates/meow-crypto/src/aead.rs new file mode 100644 index 0000000..cf661f9 --- /dev/null +++ b/crates/meow-crypto/src/aead.rs @@ -0,0 +1,75 @@ +//! XChaCha20-Poly1305 with random nonces. Output format: `nonce (24) || ciphertext+tag`. + +use chacha20poly1305::aead::{Aead, KeyInit, Payload}; +use chacha20poly1305::{XChaCha20Poly1305, XNonce}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +use crate::{CryptoError, Result}; + +pub const NONCE_LEN: usize = 24; +pub const TAG_LEN: usize = 16; +pub const OVERHEAD: usize = NONCE_LEN + TAG_LEN; + +/// 256-bit symmetric key. +#[derive(Clone, Zeroize, ZeroizeOnDrop, PartialEq, Eq)] +pub struct Key(pub [u8; 32]); + +impl Key { + pub fn generate() -> Self { + Key(crate::random_bytes()) + } +} + +impl std::fmt::Debug for Key { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Key(..)") + } +} + +pub fn encrypt(key: &Key, plaintext: &[u8], aad: &[u8]) -> Vec { + let cipher = XChaCha20Poly1305::new((&key.0).into()); + let nonce: [u8; NONCE_LEN] = crate::random_bytes(); + // Encryption with a valid key and in-memory buffers cannot fail. + let ct = cipher + .encrypt(XNonce::from_slice(&nonce), Payload { msg: plaintext, aad }) + .unwrap_or_default(); + let mut out = Vec::with_capacity(NONCE_LEN + ct.len()); + out.extend_from_slice(&nonce); + out.extend_from_slice(&ct); + out +} + +pub fn decrypt(key: &Key, data: &[u8], aad: &[u8]) -> Result> { + if data.len() < OVERHEAD { + return Err(CryptoError::Decrypt); + } + let (nonce, ct) = data.split_at(NONCE_LEN); + XChaCha20Poly1305::new((&key.0).into()) + .decrypt(XNonce::from_slice(nonce), Payload { msg: ct, aad }) + .map_err(|_| CryptoError::Decrypt) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn roundtrip_and_tamper() { + let k = Key::generate(); + let ct = encrypt(&k, b"secret", b"ad"); + assert_eq!(decrypt(&k, &ct, b"ad").unwrap(), b"secret"); + assert!(decrypt(&k, &ct, b"AD").is_err()); + let mut bad = ct.clone(); + let last = bad.len() - 1; + bad[last] ^= 1; + assert!(decrypt(&k, &bad, b"ad").is_err()); + assert!(decrypt(&Key::generate(), &ct, b"ad").is_err()); + assert!(decrypt(&k, &ct[..10], b"ad").is_err()); + } + + #[test] + fn nonces_are_random() { + let k = Key::generate(); + assert_ne!(encrypt(&k, b"x", b""), encrypt(&k, b"x", b"")); + } +} diff --git a/crates/meow-crypto/src/kdf.rs b/crates/meow-crypto/src/kdf.rs new file mode 100644 index 0000000..510e06b --- /dev/null +++ b/crates/meow-crypto/src/kdf.rs @@ -0,0 +1,43 @@ +//! HKDF-SHA256 with mandatory domain-separation labels. +//! +//! Every label is prefixed with `meow/v2/` so that keys derived for one purpose can +//! never collide with keys derived for another one. + +use hkdf::Hkdf; +use hmac::{Hmac, Mac}; +use sha2::Sha256; + +use crate::{CryptoError, Result}; + +pub const LABEL_PREFIX: &str = "meow/v2/"; + +/// Derive `N` bytes from `ikm` with an optional salt and a purpose label. +pub fn derive(ikm: &[u8], salt: &[u8], label: &str) -> Result<[u8; N]> { + let hk = Hkdf::::new(Some(salt), ikm); + let mut out = [0u8; N]; + let info = [LABEL_PREFIX.as_bytes(), label.as_bytes()].concat(); + hk.expand(&info, &mut out).map_err(|_| CryptoError::Kdf)?; + Ok(out) +} + +/// HMAC-SHA256. +pub fn hmac(key: &[u8], data: &[u8]) -> [u8; 32] { + // HMAC accepts keys of any length: `new_from_slice` cannot fail. + let mut m = as Mac>::new_from_slice(key).unwrap_or_else(|_| unreachable!()); + m.update(data); + m.finalize().into_bytes().into() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn labels_separate_domains() { + let a: [u8; 32] = derive(b"ikm", b"salt", "a").unwrap(); + let b: [u8; 32] = derive(b"ikm", b"salt", "b").unwrap(); + assert_ne!(a, b); + let a2: [u8; 32] = derive(b"ikm", b"salt", "a").unwrap(); + assert_eq!(a, a2); + } +} diff --git a/crates/meow-crypto/src/keys.rs b/crates/meow-crypto/src/keys.rs new file mode 100644 index 0000000..64a12f8 --- /dev/null +++ b/crates/meow-crypto/src/keys.rs @@ -0,0 +1,188 @@ +//! Strongly typed key material. + +use std::fmt; + +use ed25519_dalek::Signer; +use serde::{Deserialize, Serialize}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +use crate::{CryptoError, Result}; + +/// Ed25519 signature (64 bytes). +pub type Signature = [u8; 64]; + +macro_rules! public_key_type { + ($name:ident, $doc:literal) => { + #[doc = $doc] + #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] + pub struct $name(pub [u8; 32]); + + impl $name { + pub fn from_slice(b: &[u8]) -> Result { + let arr: [u8; 32] = b.try_into().map_err(|_| CryptoError::BadKey)?; + Ok(Self(arr)) + } + pub fn as_bytes(&self) -> &[u8; 32] { + &self.0 + } + pub fn to_vec(&self) -> Vec { + self.0.to_vec() + } + /// Lower-case hex, for logs/filenames (never for secrets). + pub fn to_hex(&self) -> String { + hex(&self.0) + } + /// Short fingerprint for UI display. + pub fn fingerprint(&self) -> String { + hex(&crate::sha256(&[&self.0])[..8]) + } + } + + impl fmt::Debug for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, concat!(stringify!($name), "({})"), &self.to_hex()[..16]) + } + } + }; +} + +public_key_type!(SignPublic, "Ed25519 public key. Also used as a mailbox identifier."); +public_key_type!(DhPublic, "X25519 public key."); + +pub(crate) fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +impl SignPublic { + pub fn verify(&self, msg: &[u8], sig: &[u8]) -> Result<()> { + let vk = ed25519_dalek::VerifyingKey::from_bytes(&self.0).map_err(|_| CryptoError::BadKey)?; + let sig: [u8; 64] = sig.try_into().map_err(|_| CryptoError::BadSignature)?; + vk.verify_strict(msg, &ed25519_dalek::Signature::from_bytes(&sig)) + .map_err(|_| CryptoError::BadSignature) + } +} + +/// Ed25519 key pair. +#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)] +pub struct SigningKeyPair { + secret: [u8; 32], +} + +impl SigningKeyPair { + pub fn generate() -> Self { + Self { + secret: crate::random_bytes(), + } + } + pub fn from_secret(secret: [u8; 32]) -> Self { + Self { secret } + } + pub fn secret_bytes(&self) -> &[u8; 32] { + &self.secret + } + fn inner(&self) -> ed25519_dalek::SigningKey { + ed25519_dalek::SigningKey::from_bytes(&self.secret) + } + pub fn public(&self) -> SignPublic { + SignPublic(self.inner().verifying_key().to_bytes()) + } + pub fn sign(&self, msg: &[u8]) -> Signature { + self.inner().sign(msg).to_bytes() + } +} + +impl fmt::Debug for SigningKeyPair { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "SigningKeyPair({:?})", self.public()) + } +} + +/// X25519 key pair. +#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)] +pub struct DhKeyPair { + secret: [u8; 32], +} + +impl DhKeyPair { + pub fn generate() -> Self { + Self { + secret: crate::random_bytes(), + } + } + pub fn from_secret(secret: [u8; 32]) -> Self { + Self { secret } + } + pub fn secret_bytes(&self) -> &[u8; 32] { + &self.secret + } + fn inner(&self) -> x25519_dalek::StaticSecret { + x25519_dalek::StaticSecret::from(self.secret) + } + pub fn public(&self) -> DhPublic { + DhPublic(x25519_dalek::PublicKey::from(&self.inner()).to_bytes()) + } + /// X25519. Rejects all-zero shared secrets (low-order peer keys). + pub fn dh(&self, peer: &DhPublic) -> Result { + let s = self.inner().diffie_hellman(&x25519_dalek::PublicKey::from(peer.0)); + if !s.was_contributory() { + return Err(CryptoError::BadKey); + } + Ok(SharedSecret(s.to_bytes())) + } +} + +impl fmt::Debug for DhKeyPair { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "DhKeyPair({:?})", self.public()) + } +} + +/// Raw X25519 output. Never use directly as a key: feed it to a KDF. +#[derive(Zeroize, ZeroizeOnDrop)] +pub struct SharedSecret(pub(crate) [u8; 32]); + +impl SharedSecret { + pub fn as_bytes(&self) -> &[u8; 32] { + &self.0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sign_verify() { + let kp = SigningKeyPair::generate(); + let sig = kp.sign(b"hello"); + assert!(kp.public().verify(b"hello", &sig).is_ok()); + assert_eq!(kp.public().verify(b"hellO", &sig), Err(CryptoError::BadSignature)); + let other = SigningKeyPair::generate(); + assert!(other.public().verify(b"hello", &sig).is_err()); + } + + #[test] + fn dh_agreement() { + let a = DhKeyPair::generate(); + let b = DhKeyPair::generate(); + assert_eq!( + a.dh(&b.public()).unwrap().as_bytes(), + b.dh(&a.public()).unwrap().as_bytes() + ); + } + + #[test] + fn dh_rejects_low_order() { + let a = DhKeyPair::generate(); + assert!(a.dh(&DhPublic([0u8; 32])).is_err()); + } + + #[test] + fn roundtrip_secret() { + let kp = SigningKeyPair::generate(); + let kp2 = SigningKeyPair::from_secret(*kp.secret_bytes()); + assert_eq!(kp.public(), kp2.public()); + let d = DhKeyPair::generate(); + assert_eq!(d.public(), DhKeyPair::from_secret(*d.secret_bytes()).public()); + } +} diff --git a/crates/meow-crypto/src/lib.rs b/crates/meow-crypto/src/lib.rs new file mode 100644 index 0000000..0440826 --- /dev/null +++ b/crates/meow-crypto/src/lib.rs @@ -0,0 +1,64 @@ +//! Meow v2 cryptographic primitives. +//! +//! * [`keys`]: Ed25519 signing keys and X25519 Diffie-Hellman keys with strong types; +//! * [`aead`]: XChaCha20-Poly1305 with random 24-byte nonces; +//! * [`kdf`]: HKDF-SHA256 with domain-separation labels; +//! * [`seal`]: ECIES-style sealed boxes with a derived response key; +//! * [`password`]: Argon2id based at-rest encryption; +//! * [`ratchet`]: Double Ratchet (Signal specification); +//! * [`pad`]: length-hiding padding. +//! +//! Every secret type zeroizes its memory on drop. + +#![forbid(unsafe_code)] +#![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::expect_used))] + +pub mod aead; +pub mod kdf; +pub mod keys; +pub mod pad; +pub mod password; +pub mod ratchet; +pub mod seal; + +pub use keys::{DhKeyPair, DhPublic, SignPublic, Signature, SigningKeyPair}; + +/// Errors raised by this crate. Messages are intentionally vague to avoid oracles. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum CryptoError { + #[error("decryption failed")] + Decrypt, + #[error("invalid signature")] + BadSignature, + #[error("invalid key material")] + BadKey, + #[error("malformed data")] + Malformed, + #[error("too many skipped messages")] + TooManySkipped, + #[error("ratchet session not ready to send")] + NotReady, + #[error("key derivation failed")] + Kdf, +} + +pub type Result = std::result::Result; + +/// Fill a fixed-size array with OS randomness. +pub fn random_bytes() -> [u8; N] { + use rand_core::RngCore; + let mut b = [0u8; N]; + rand_core::OsRng.fill_bytes(&mut b); + b +} + +/// SHA-256 helper. +pub fn sha256(parts: &[&[u8]]) -> [u8; 32] { + use sha2::Digest; + let mut h = sha2::Sha256::new(); + for p in parts { + h.update((p.len() as u64).to_be_bytes()); + h.update(p); + } + h.finalize().into() +} diff --git a/crates/meow-crypto/src/pad.rs b/crates/meow-crypto/src/pad.rs new file mode 100644 index 0000000..ac8c608 --- /dev/null +++ b/crates/meow-crypto/src/pad.rs @@ -0,0 +1,51 @@ +//! Length-hiding padding: `len (u32 BE) ‖ data ‖ zeros`, rounded up to a bucket size. +//! +//! Buckets: 256 B, 1 KiB, 4 KiB, 16 KiB, 64 KiB, then multiples of 64 KiB. + +use crate::{CryptoError, Result}; + +const BUCKETS: [usize; 5] = [256, 1024, 4096, 16 * 1024, 64 * 1024]; +const STEP: usize = 64 * 1024; + +fn bucket(n: usize) -> usize { + BUCKETS + .iter() + .copied() + .find(|b| *b >= n) + .unwrap_or_else(|| n.div_ceil(STEP) * STEP) +} + +pub fn pad(data: &[u8]) -> Vec { + let total = bucket(data.len() + 4); + let mut out = Vec::with_capacity(total); + out.extend_from_slice(&(data.len() as u32).to_be_bytes()); + out.extend_from_slice(data); + out.resize(total, 0); + out +} + +pub fn unpad(padded: &[u8]) -> Result<&[u8]> { + if padded.len() < 4 { + return Err(CryptoError::Malformed); + } + let n = u32::from_be_bytes([padded[0], padded[1], padded[2], padded[3]]) as usize; + padded.get(4..4 + n).ok_or(CryptoError::Malformed) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn buckets() { + assert_eq!(pad(b"").len(), 256); + assert_eq!(pad(&[1u8; 252]).len(), 256); + assert_eq!(pad(&[1u8; 253]).len(), 1024); + assert_eq!(pad(&[1u8; 70_000]).len(), 2 * STEP); + for n in [0, 1, 252, 253, 5000, 70_000] { + let d = vec![7u8; n]; + assert_eq!(unpad(&pad(&d)).unwrap(), &d[..]); + } + assert!(unpad(&[0, 0, 1, 0]).is_err()); + } +} diff --git a/crates/meow-crypto/src/password.rs b/crates/meow-crypto/src/password.rs new file mode 100644 index 0000000..6e314e3 --- /dev/null +++ b/crates/meow-crypto/src/password.rs @@ -0,0 +1,106 @@ +//! Password-based at-rest encryption (Argon2id + XChaCha20-Poly1305). +//! +//! Blob format: +//! ```text +//! "MEOWPW" (6) ‖ version (1) ‖ m_cost KiB (u32 BE) ‖ t_cost (u32 BE) ‖ p_cost (u32 BE) +//! ‖ salt (16) ‖ nonce ‖ ciphertext+tag +//! ``` +//! The header is authenticated as AEAD associated data. + +use argon2::{Algorithm, Argon2, Params, Version}; + +use crate::aead::{self, Key}; +use crate::{CryptoError, Result}; + +const MAGIC: &[u8; 6] = b"MEOWPW"; +const VERSION: u8 = 1; +const HEADER_LEN: usize = 6 + 1 + 12 + 16; + +/// Argon2id cost parameters. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct KdfParams { + pub m_cost_kib: u32, + pub t_cost: u32, + pub p_cost: u32, +} + +impl KdfParams { + /// Interactive default: 64 MiB, 3 passes. + pub const DEFAULT: Self = Self { + m_cost_kib: 64 * 1024, + t_cost: 3, + p_cost: 1, + }; + /// Very cheap parameters, for tests only. + pub const INSECURE_TEST: Self = Self { + m_cost_kib: 64, + t_cost: 1, + p_cost: 1, + }; +} + +/// Derive a key from a password with Argon2id. +pub fn derive_key(password: &[u8], salt: &[u8; 16], p: KdfParams) -> Result { + let params = Params::new(p.m_cost_kib, p.t_cost, p.p_cost, Some(32)).map_err(|_| CryptoError::Kdf)?; + let mut out = [0u8; 32]; + Argon2::new(Algorithm::Argon2id, Version::V0x13, params) + .hash_password_into(password, salt, &mut out) + .map_err(|_| CryptoError::Kdf)?; + Ok(Key(out)) +} + +/// Encrypt `plaintext` under `password`. +pub fn encrypt(password: &[u8], plaintext: &[u8], p: KdfParams) -> Result> { + let salt: [u8; 16] = crate::random_bytes(); + let key = derive_key(password, &salt, p)?; + let mut header = Vec::with_capacity(HEADER_LEN); + header.extend_from_slice(MAGIC); + header.push(VERSION); + header.extend_from_slice(&p.m_cost_kib.to_be_bytes()); + header.extend_from_slice(&p.t_cost.to_be_bytes()); + header.extend_from_slice(&p.p_cost.to_be_bytes()); + header.extend_from_slice(&salt); + let ct = aead::encrypt(&key, plaintext, &header); + Ok([header, ct].concat()) +} + +/// Decrypt a blob produced by [`encrypt`]. +pub fn decrypt(password: &[u8], blob: &[u8]) -> Result> { + if blob.len() < HEADER_LEN || &blob[..6] != MAGIC || blob[6] != VERSION { + return Err(CryptoError::Malformed); + } + let be = |i: usize| u32::from_be_bytes([blob[i], blob[i + 1], blob[i + 2], blob[i + 3]]); + let p = KdfParams { + m_cost_kib: be(7), + t_cost: be(11), + p_cost: be(15), + }; + // Refuse absurd parameters coming from a tampered file (DoS). + if p.m_cost_kib > 4 * 1024 * 1024 || p.t_cost > 64 || p.p_cost > 16 { + return Err(CryptoError::Malformed); + } + let mut salt = [0u8; 16]; + salt.copy_from_slice(&blob[19..35]); + let key = derive_key(password, &salt, p)?; + aead::decrypt(&key, &blob[HEADER_LEN..], &blob[..HEADER_LEN]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn roundtrip() { + let blob = encrypt(b"pw", b"data", KdfParams::INSECURE_TEST).unwrap(); + assert_eq!(decrypt(b"pw", &blob).unwrap(), b"data"); + assert_eq!(decrypt(b"bad", &blob), Err(CryptoError::Decrypt)); + } + + #[test] + fn header_is_authenticated() { + let mut blob = encrypt(b"pw", b"data", KdfParams::INSECURE_TEST).unwrap(); + blob[20] ^= 1; // salt + assert!(decrypt(b"pw", &blob).is_err()); + assert_eq!(decrypt(b"pw", b"junk"), Err(CryptoError::Malformed)); + } +} diff --git a/crates/meow-crypto/src/ratchet.rs b/crates/meow-crypto/src/ratchet.rs new file mode 100644 index 0000000..6cf98bd --- /dev/null +++ b/crates/meow-crypto/src/ratchet.rs @@ -0,0 +1,333 @@ +//! Double Ratchet, following the Signal specification +//! (). +//! +//! * `KDF_RK(rk, dh)` = HKDF-SHA256(salt = rk, ikm = dh, "ratchet/rk") → (rk', ck) +//! * `KDF_CK(ck)` = (HMAC(ck, 0x02), HMAC(ck, 0x01)) → (ck', mk) +//! * `ENCRYPT(mk, pt, ad ‖ header)` = XChaCha20-Poly1305 (random nonce) +//! +//! Decryption is transactional: the state is only updated when authentication +//! succeeds, so forged or replayed messages cannot desynchronise a session. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +use crate::aead::{self, Key}; +use crate::keys::{DhKeyPair, DhPublic}; +use crate::{kdf, CryptoError, Result}; + +/// Maximum number of message keys skipped within one receiving chain. +pub const MAX_SKIP: u32 = 1000; +/// Maximum number of skipped message keys kept overall (oldest are dropped). +pub const MAX_STORED_SKIPPED: usize = 2000; + +/// Clear-text ratchet header. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Header { + pub dh: DhPublic, + /// Number of messages in the previous sending chain. + pub pn: u32, + /// Message number in the current sending chain. + pub n: u32, +} + +impl Header { + fn encode(&self) -> [u8; 40] { + let mut out = [0u8; 40]; + out[..32].copy_from_slice(&self.dh.0); + out[32..36].copy_from_slice(&self.pn.to_be_bytes()); + out[36..].copy_from_slice(&self.n.to_be_bytes()); + out + } +} + +#[derive(Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)] +struct SkippedKey { + dh: [u8; 32], + n: u32, + order: u64, + mk: [u8; 32], +} + +/// Double Ratchet session state. Serialisable with [`Session::to_bytes`]. +#[derive(Clone, Serialize, Deserialize)] +pub struct Session { + dhs: DhKeyPair, + dhr: Option, + rk: [u8; 32], + cks: Option<[u8; 32]>, + ckr: Option<[u8; 32]>, + ns: u32, + nr: u32, + pn: u32, + skipped: BTreeMap<([u8; 32], u32), SkippedKey>, + skip_counter: u64, +} + +impl Drop for Session { + fn drop(&mut self) { + self.rk.zeroize(); + if let Some(c) = self.cks.as_mut() { + c.zeroize(); + } + if let Some(c) = self.ckr.as_mut() { + c.zeroize(); + } + } +} + +fn kdf_rk(rk: &[u8; 32], dh: &[u8; 32]) -> Result<([u8; 32], [u8; 32])> { + let okm: [u8; 64] = kdf::derive(dh, rk, "ratchet/rk")?; + let mut new_rk = [0u8; 32]; + let mut ck = [0u8; 32]; + new_rk.copy_from_slice(&okm[..32]); + ck.copy_from_slice(&okm[32..]); + Ok((new_rk, ck)) +} + +fn kdf_ck(ck: &[u8; 32]) -> ([u8; 32], [u8; 32]) { + (kdf::hmac(ck, &[0x02]), kdf::hmac(ck, &[0x01])) +} + +fn full_ad(ad: &[u8], h: &Header) -> Vec { + [ad, &h.encode()].concat() +} + +impl Session { + /// Initialise the party that sends first (the invitation initiator), + /// knowing the peer's initial ratchet public key. + pub fn init_sender(shared_key: [u8; 32], peer_ratchet: DhPublic) -> Result { + let dhs = DhKeyPair::generate(); + let dh = dhs.dh(&peer_ratchet)?; + let (rk, cks) = kdf_rk(&shared_key, dh.as_bytes())?; + Ok(Self { + dhs, + dhr: Some(peer_ratchet), + rk, + cks: Some(cks), + ckr: None, + ns: 0, + nr: 0, + pn: 0, + skipped: BTreeMap::new(), + skip_counter: 0, + }) + } + + /// Initialise the party that receives first, owning the initial ratchet key pair. + pub fn init_receiver(shared_key: [u8; 32], own_ratchet: DhKeyPair) -> Self { + Self { + dhs: own_ratchet, + dhr: None, + rk: shared_key, + cks: None, + ckr: None, + ns: 0, + nr: 0, + pn: 0, + skipped: BTreeMap::new(), + skip_counter: 0, + } + } + + /// Whether this side can already send (the receiver must first receive one message). + pub fn can_send(&self) -> bool { + self.cks.is_some() + } + + pub fn encrypt(&mut self, plaintext: &[u8], ad: &[u8]) -> Result<(Header, Vec)> { + let ck = self.cks.ok_or(CryptoError::NotReady)?; + let (next_ck, mk) = kdf_ck(&ck); + self.cks = Some(next_ck); + let header = Header { + dh: self.dhs.public(), + pn: self.pn, + n: self.ns, + }; + self.ns += 1; + let ct = aead::encrypt(&Key(mk), plaintext, &full_ad(ad, &header)); + Ok((header, ct)) + } + + pub fn decrypt(&mut self, header: &Header, ciphertext: &[u8], ad: &[u8]) -> Result> { + // Skipped message? + if let Some(sk) = self.skipped.get(&(header.dh.0, header.n)) { + let pt = aead::decrypt(&Key(sk.mk), ciphertext, &full_ad(ad, header))?; + self.skipped.remove(&(header.dh.0, header.n)); + return Ok(pt); + } + // Work on a copy: commit only on success. + let mut next = self.clone(); + if Some(header.dh) != next.dhr { + next.skip_until(header.pn)?; + next.dh_ratchet(header)?; + } + next.skip_until(header.n)?; + let ck = next.ckr.ok_or(CryptoError::Decrypt)?; + let (next_ck, mk) = kdf_ck(&ck); + next.ckr = Some(next_ck); + next.nr += 1; + let pt = aead::decrypt(&Key(mk), ciphertext, &full_ad(ad, header))?; + *self = next; + Ok(pt) + } + + fn skip_until(&mut self, until: u32) -> Result<()> { + let Some(mut ck) = self.ckr else { return Ok(()) }; + if until < self.nr { + return Ok(()); + } + if until - self.nr > MAX_SKIP { + return Err(CryptoError::TooManySkipped); + } + let dhr = self.dhr.ok_or(CryptoError::Decrypt)?; + while self.nr < until { + let (next_ck, mk) = kdf_ck(&ck); + ck = next_ck; + self.skip_counter += 1; + self.skipped.insert( + (dhr.0, self.nr), + SkippedKey { + dh: dhr.0, + n: self.nr, + order: self.skip_counter, + mk, + }, + ); + self.nr += 1; + } + self.ckr = Some(ck); + while self.skipped.len() > MAX_STORED_SKIPPED { + let oldest = self + .skipped + .iter() + .min_by_key(|(_, v)| v.order) + .map(|(k, _)| *k) + .ok_or(CryptoError::Decrypt)?; + self.skipped.remove(&oldest); + } + Ok(()) + } + + fn dh_ratchet(&mut self, header: &Header) -> Result<()> { + self.pn = self.ns; + self.ns = 0; + self.nr = 0; + self.dhr = Some(header.dh); + let dh = self.dhs.dh(&header.dh)?; + let (rk, ckr) = kdf_rk(&self.rk, dh.as_bytes())?; + self.rk = rk; + self.ckr = Some(ckr); + self.dhs = DhKeyPair::generate(); + let dh = self.dhs.dh(&header.dh)?; + let (rk, cks) = kdf_rk(&self.rk, dh.as_bytes())?; + self.rk = rk; + self.cks = Some(cks); + Ok(()) + } + + /// Serialise the full state (contains secrets: encrypt before storing!). + pub fn to_bytes(&self) -> Vec { + postcard::to_allocvec(self).unwrap_or_default() + } + + pub fn from_bytes(b: &[u8]) -> Result { + postcard::from_bytes(b).map_err(|_| CryptoError::Malformed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pair() -> (Session, Session) { + let sk: [u8; 32] = crate::random_bytes(); + let bob_ratchet = DhKeyPair::generate(); + let alice = Session::init_sender(sk, bob_ratchet.public()).unwrap(); + let bob = Session::init_receiver(sk, bob_ratchet); + (alice, bob) + } + + #[test] + fn ping_pong() { + let (mut a, mut b) = pair(); + assert!(!b.can_send()); + for i in 0..5 { + let m = format!("a->b {i}"); + let (h, c) = a.encrypt(m.as_bytes(), b"ad").unwrap(); + assert_eq!(b.decrypt(&h, &c, b"ad").unwrap(), m.as_bytes()); + let m = format!("b->a {i}"); + let (h, c) = b.encrypt(m.as_bytes(), b"ad").unwrap(); + assert_eq!(a.decrypt(&h, &c, b"ad").unwrap(), m.as_bytes()); + } + } + + #[test] + fn out_of_order_and_replay() { + let (mut a, mut b) = pair(); + let msgs: Vec<_> = (0..4).map(|i| a.encrypt(&[i], b"").unwrap()).collect(); + assert_eq!(b.decrypt(&msgs[3].0, &msgs[3].1, b"").unwrap(), [3]); + assert_eq!(b.decrypt(&msgs[0].0, &msgs[0].1, b"").unwrap(), [0]); + assert_eq!(b.decrypt(&msgs[2].0, &msgs[2].1, b"").unwrap(), [2]); + // replay + assert!(b.decrypt(&msgs[0].0, &msgs[0].1, b"").is_err()); + assert_eq!(b.decrypt(&msgs[1].0, &msgs[1].1, b"").unwrap(), [1]); + // new chain after reply, old chain messages still decryptable + let late = a.encrypt(b"late", b"").unwrap(); + let (h, c) = b.encrypt(b"reply", b"").unwrap(); + a.decrypt(&h, &c, b"").unwrap(); + let (h2, c2) = a.encrypt(b"new chain", b"").unwrap(); + assert_eq!(b.decrypt(&h2, &c2, b"").unwrap(), b"new chain"); + assert_eq!(b.decrypt(&late.0, &late.1, b"").unwrap(), b"late"); + } + + #[test] + fn forgery_does_not_corrupt_state() { + let (mut a, mut b) = pair(); + let (h, mut c) = a.encrypt(b"x", b"").unwrap(); + let good = c.clone(); + let last = c.len() - 1; + c[last] ^= 1; + assert!(b.decrypt(&h, &c, b"").is_err()); + // forged header with a random DH key + let fake = Header { + dh: DhKeyPair::generate().public(), + pn: 0, + n: 0, + }; + assert!(b.decrypt(&fake, &good, b"").is_err()); + assert_eq!(b.decrypt(&h, &good, b"").unwrap(), b"x"); + } + + #[test] + fn wrong_ad_fails() { + let (mut a, mut b) = pair(); + let (h, c) = a.encrypt(b"x", b"ad1").unwrap(); + assert!(b.decrypt(&h, &c, b"ad2").is_err()); + } + + #[test] + fn too_many_skipped() { + let (mut a, mut b) = pair(); + let mut h = a.encrypt(b"", b"").unwrap().0; + h.n = MAX_SKIP + 5; + assert_eq!( + b.decrypt(&h, b"whatever-ciphertext-long-enough-for-aead", b""), + Err(CryptoError::TooManySkipped) + ); + } + + #[test] + fn persist_and_restore() { + let (mut a, mut b) = pair(); + let (h, c) = a.encrypt(b"1", b"").unwrap(); + b.decrypt(&h, &c, b"").unwrap(); + let mut a2 = Session::from_bytes(&a.to_bytes()).unwrap(); + let mut b2 = Session::from_bytes(&b.to_bytes()).unwrap(); + let (h, c) = b2.encrypt(b"2", b"").unwrap(); + assert_eq!(a2.decrypt(&h, &c, b"").unwrap(), b"2"); + let (h, c) = a2.encrypt(b"3", b"").unwrap(); + assert_eq!(b2.decrypt(&h, &c, b"").unwrap(), b"3"); + } +} diff --git a/crates/meow-crypto/src/seal.rs b/crates/meow-crypto/src/seal.rs new file mode 100644 index 0000000..fa6a481 --- /dev/null +++ b/crates/meow-crypto/src/seal.rs @@ -0,0 +1,79 @@ +//! Sealed boxes (ECIES: X25519 + HKDF-SHA256 + XChaCha20-Poly1305). +//! +//! ```text +//! eph ← fresh X25519 +//! shared = DH(eph, recipient) +//! k_req ‖ k_resp = HKDF(shared, salt = eph_pk ‖ recipient_pk, "seal/" ‖ context) +//! ciphertext = AEAD(k_req, plaintext, aad = context) +//! ``` +//! +//! `k_resp` lets the recipient answer the (anonymous) sender without knowing who it is. + +use crate::aead::{self, Key}; +use crate::keys::{DhKeyPair, DhPublic}; +use crate::{kdf, Result}; + +/// A sealed message as transported. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SealedBox { + pub ephemeral: DhPublic, + pub ciphertext: Vec, +} + +fn keys(shared: &[u8; 32], eph: &DhPublic, recipient: &DhPublic, context: &str) -> Result<(Key, Key)> { + let salt = [eph.0.as_slice(), recipient.0.as_slice()].concat(); + let okm: [u8; 64] = kdf::derive(shared, &salt, &format!("seal/{context}"))?; + let mut req = [0u8; 32]; + let mut resp = [0u8; 32]; + req.copy_from_slice(&okm[..32]); + resp.copy_from_slice(&okm[32..]); + Ok((Key(req), Key(resp))) +} + +/// Seal `plaintext` for `recipient`. Returns the box and the key that will protect the reply. +pub fn seal(recipient: &DhPublic, context: &str, plaintext: &[u8]) -> Result<(SealedBox, Key)> { + let eph = DhKeyPair::generate(); + let eph_pub = eph.public(); + let shared = eph.dh(recipient)?; + let (k_req, k_resp) = keys(shared.as_bytes(), &eph_pub, recipient, context)?; + let ciphertext = aead::encrypt(&k_req, plaintext, context.as_bytes()); + Ok(( + SealedBox { + ephemeral: eph_pub, + ciphertext, + }, + k_resp, + )) +} + +/// Open a sealed box with the recipient key pair. Returns the plaintext and the reply key. +pub fn open(recipient: &DhKeyPair, context: &str, sealed: &SealedBox) -> Result<(Vec, Key)> { + let shared = recipient.dh(&sealed.ephemeral)?; + let (k_req, k_resp) = keys(shared.as_bytes(), &sealed.ephemeral, &recipient.public(), context)?; + let pt = aead::decrypt(&k_req, &sealed.ciphertext, context.as_bytes())?; + Ok((pt, k_resp)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn seal_open_with_reply() { + let server = DhKeyPair::generate(); + let (sealed, k_client) = seal(&server.public(), "rpc", b"request").unwrap(); + let (pt, k_server) = open(&server, "rpc", &sealed).unwrap(); + assert_eq!(pt, b"request"); + assert_eq!(k_client, k_server); + let reply = aead::encrypt(&k_server, b"response", b""); + assert_eq!(aead::decrypt(&k_client, &reply, b"").unwrap(), b"response"); + } + + #[test] + fn wrong_context_or_key_fails() { + let server = DhKeyPair::generate(); + let (sealed, _) = seal(&server.public(), "rpc", b"x").unwrap(); + assert!(open(&server, "other", &sealed).is_err()); + assert!(open(&DhKeyPair::generate(), "rpc", &sealed).is_err()); + } +} diff --git a/crates/meow-proto/Cargo.toml b/crates/meow-proto/Cargo.toml new file mode 100644 index 0000000..09879c6 --- /dev/null +++ b/crates/meow-proto/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "meow-proto" +description = "Meow protocol v2 wire types (generated from proto/meow.proto)" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +prost = "0.14" + +[build-dependencies] +prost-build = "0.14" +protox = "0.9" + +[lints] +workspace = true diff --git a/crates/meow-proto/build.rs b/crates/meow-proto/build.rs new file mode 100644 index 0000000..8ba30d7 --- /dev/null +++ b/crates/meow-proto/build.rs @@ -0,0 +1,9 @@ +//! Compiles `proto/meow.proto` with protox (pure Rust): no `protoc` required. +fn main() -> Result<(), Box> { + let proto_dir = "../../proto"; + let file = format!("{proto_dir}/meow.proto"); + println!("cargo:rerun-if-changed={file}"); + let fds = protox::compile([file], [proto_dir])?; + prost_build::Config::new().compile_fds(fds)?; + Ok(()) +} diff --git a/crates/meow-proto/src/lib.rs b/crates/meow-proto/src/lib.rs new file mode 100644 index 0000000..8abcd8f --- /dev/null +++ b/crates/meow-proto/src/lib.rs @@ -0,0 +1,27 @@ +//! Meow protocol v2 wire types. +//! +//! Generated from `rust/proto/meow.proto`. This crate contains no logic besides +//! small encoding helpers; protocol semantics live in `meow-core`. + +#![forbid(unsafe_code)] +#![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::expect_used))] + +#[allow(clippy::all, missing_docs)] +pub mod v2 { + include!(concat!(env!("OUT_DIR"), "/meow.v2.rs")); +} + +pub use prost::Message; + +/// Current protocol version carried in every top-level wire object. +pub const PROTOCOL_VERSION: u32 = 2; + +/// Decode helper returning a uniform error type. +pub fn decode(bytes: &[u8]) -> Result { + M::decode(bytes) +} + +/// Encode helper. +pub fn encode(msg: &M) -> Vec { + msg.encode_to_vec() +} diff --git a/crates/meow-server/Cargo.toml b/crates/meow-server/Cargo.toml new file mode 100644 index 0000000..08969af --- /dev/null +++ b/crates/meow-server/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "meow-server" +description = "Meow v2 relay server (meowsrv)" +version.workspace = true +edition.workspace = true +license.workspace = true + +[[bin]] +name = "meowsrv" +path = "src/main.rs" + +[dependencies] +meow-core = { path = "../meow-core" } +meow-proto = { path = "../meow-proto" } +meow-crypto = { path = "../meow-crypto" } +axum = "0.8" +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "sync", "signal"] } +async-trait = "0.1" +redis = { version = "0.32", default-features = false, features = ["aio", "tokio-comp"] } +futures-util = "0.3" +clap = { version = "4", features = ["derive", "env"] } +serde = { version = "1", features = ["derive"] } +toml = "0.9" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +thiserror = "2" +anyhow = "1" +subtle = "2" + +[dev-dependencies] +reqwest = { version = "0.12", default-features = false } + +[lints] +workspace = true diff --git a/crates/meow-server/src/config.rs b/crates/meow-server/src/config.rs new file mode 100644 index 0000000..f675832 --- /dev/null +++ b/crates/meow-server/src/config.rs @@ -0,0 +1,139 @@ +//! Server configuration: command line > environment (`MEOWSRV_*`) > TOML file > defaults. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use clap::Parser; +use meow_core::server::ServerKeys; +use meow_crypto::{DhKeyPair, SigningKeyPair}; +use serde::Deserialize; + +#[derive(Parser, Debug, Default)] +#[command(name = "meowsrv", version, about = "Meow v2 relay server")] +pub struct Args { + /// TOML configuration file. + #[arg(short, long, env = "MEOWSRV_CONFIG")] + pub config: Option, + /// Listen address, e.g. 0.0.0.0:8080. + #[arg(long, env = "MEOWSRV_LISTEN")] + pub listen: Option, + /// Public URL announced in the server card (defaults to http://). + #[arg(long, env = "MEOWSRV_PUBLIC_URL")] + pub public_url: Option, + #[arg(long, env = "MEOWSRV_NAME")] + pub name: Option, + #[arg(long, env = "MEOWSRV_DESCRIPTION")] + pub description: Option, + /// `memory` or a Redis URL (`redis://host:6379/0`). + #[arg(long, env = "MEOWSRV_STORAGE")] + pub storage: Option, + /// Private key file, created with mode 0600 if missing. + #[arg(long, env = "MEOWSRV_KEY_FILE")] + pub key_file: Option, + /// Days a message is kept in a mailbox (Redis backend). + #[arg(long, env = "MEOWSRV_MAILBOX_TTL_DAYS")] + pub mailbox_ttl_days: Option, + /// Log filter (tracing EnvFilter syntax), e.g. `info` or `meow_server=debug`. + #[arg(long, env = "MEOWSRV_LOG")] + pub log: Option, +} + +#[derive(Deserialize, Debug, Default)] +#[serde(deny_unknown_fields)] +struct FileConfig { + listen: Option, + public_url: Option, + name: Option, + description: Option, + storage: Option, + key_file: Option, + mailbox_ttl_days: Option, + log: Option, +} + +/// Resolved configuration. +#[derive(Debug, Clone)] +pub struct Config { + pub listen: String, + pub public_url: String, + pub name: String, + pub description: String, + pub storage: String, + pub key_file: PathBuf, + pub mailbox_ttl: Duration, + pub log: String, +} + +impl Config { + pub fn resolve(args: Args) -> anyhow::Result { + let file: FileConfig = match &args.config { + Some(p) => toml::from_str(&std::fs::read_to_string(p)?)?, + None => FileConfig::default(), + }; + let listen = args.listen.or(file.listen).unwrap_or_else(|| "127.0.0.1:8080".into()); + let public_url = args + .public_url + .or(file.public_url) + .unwrap_or_else(|| format!("http://{listen}")); + Ok(Self { + public_url, + listen, + name: args.name.or(file.name).unwrap_or_else(|| "meow server".into()), + description: args.description.or(file.description).unwrap_or_default(), + storage: args.storage.or(file.storage).unwrap_or_else(|| "memory".into()), + key_file: args.key_file.or(file.key_file).unwrap_or_else(|| "server.key".into()), + mailbox_ttl: Duration::from_secs(86_400 * args.mailbox_ttl_days.or(file.mailbox_ttl_days).unwrap_or(30)), + log: args.log.or(file.log).unwrap_or_else(|| "info".into()), + }) + } +} + +/// Load the server keys, or generate them (file mode 0600) on first start. +/// +/// Format: one line of hex, `sign_secret (32) ‖ dh_secret (32)`. +pub fn load_or_create_keys(path: &Path) -> anyhow::Result { + if path.exists() { + let s = std::fs::read_to_string(path)?; + let b = meow_core::from_hex(s.trim()).ok_or_else(|| anyhow::anyhow!("key file is not hex"))?; + anyhow::ensure!(b.len() == 64, "key file must contain 64 bytes"); + let mut sign = [0u8; 32]; + let mut dh = [0u8; 32]; + sign.copy_from_slice(&b[..32]); + dh.copy_from_slice(&b[32..]); + return Ok(ServerKeys { + sign: SigningKeyPair::from_secret(sign), + dh: DhKeyPair::from_secret(dh), + }); + } + let keys = ServerKeys::generate(); + let hex: String = keys + .sign + .secret_bytes() + .iter() + .chain(keys.dh.secret_bytes()) + .map(|x| format!("{x:02x}")) + .collect(); + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { + std::fs::create_dir_all(dir)?; + } + write_private(path, hex.as_bytes())?; + tracing::warn!("generated new server keys in {}", path.display()); + Ok(keys) +} + +#[cfg(unix)] +fn write_private(path: &Path, data: &[u8]) -> std::io::Result<()> { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path)?; + f.write_all(data) +} + +#[cfg(not(unix))] +fn write_private(path: &Path, data: &[u8]) -> std::io::Result<()> { + std::fs::write(path, data) +} diff --git a/crates/meow-server/src/lib.rs b/crates/meow-server/src/lib.rs new file mode 100644 index 0000000..327a04c --- /dev/null +++ b/crates/meow-server/src/lib.rs @@ -0,0 +1,233 @@ +//! Meow v2 relay server. +//! +//! Routes: +//! * `GET /v2/card` – self-signed `ServerCard` (protobuf); +//! * `POST /v2/rpc` – `SealedRequest` → `SealedResponse`; +//! * `GET /healthz`. +//! +//! The server never sees message contents nor who talks to whom: deposits are +//! anonymous, and pulls are authorised by a signature of the mailbox key. + +#![forbid(unsafe_code)] +#![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::expect_used))] + +pub mod config; +pub mod store; + +use std::collections::HashSet; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use axum::body::Bytes; +use axum::extract::{DefaultBodyLimit, State}; +use axum::http::{header, StatusCode}; +use axum::response::IntoResponse; +use axum::routing::{get, post}; +use axum::Router; +use meow_core::rpc; +use meow_core::server::ServerKeys; +use meow_proto::v2::{self, error::Code, request::Body as Req, response::Body as Resp}; +use meow_proto::Message; +use tokio::sync::broadcast; + +use crate::store::{Mailbox, ServerStore, StoreError}; + +/// Operational limits. +#[derive(Clone, Debug)] +pub struct Limits { + pub max_body_bytes: usize, + pub max_deposits: usize, + pub max_payload_bytes: usize, + pub max_mailboxes_per_pull: usize, + pub max_wait: Duration, + pub max_invitation_ttl: Duration, + pub replay_ttl: Duration, +} + +impl Default for Limits { + fn default() -> Self { + Self { + max_body_bytes: 16 * 1024 * 1024, + max_deposits: 128, + max_payload_bytes: 8 * 1024 * 1024, + max_mailboxes_per_pull: 512, + max_wait: Duration::from_secs(120), + max_invitation_ttl: Duration::from_secs(7 * 86_400), + replay_ttl: Duration::from_secs(2 * rpc::AUTH_WINDOW_SECS), + } + } +} + +/// Shared state of a running server. +pub struct AppState { + pub keys: ServerKeys, + pub card: Vec, + pub store: Arc, + pub notify: broadcast::Sender, + pub limits: Limits, +} + +pub fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// Build the HTTP router. +pub fn router(state: Arc) -> Router { + let limit = state.limits.max_body_bytes; + Router::new() + .route("/v2/card", get(card)) + .route("/v2/rpc", post(rpc_handler)) + .route("/healthz", get(|| async { "ok" })) + .layer(DefaultBodyLimit::max(limit)) + .with_state(state) +} + +async fn card(State(st): State>) -> impl IntoResponse { + ([(header::CONTENT_TYPE, "application/x-protobuf")], st.card.clone()) +} + +async fn rpc_handler(State(st): State>, body: Bytes) -> impl IntoResponse { + let (req, key) = match rpc::open_request(&st.keys, &body) { + Ok(x) => x, + Err(_) => return (StatusCode::BAD_REQUEST, Vec::new()), + }; + let rid = req.request_id.clone(); + let resp = match handle(&st, req).await { + Ok(body) => v2::Response { + request_id: rid, + body: Some(body), + }, + Err((code, msg)) => { + tracing::debug!(?code, msg, "request rejected"); + rpc::error_response(rid, code, msg) + } + }; + (StatusCode::OK, rpc::seal_response(&key, &resp)) +} + +type HResult = Result; + +fn store_err(e: StoreError) -> (Code, &'static str) { + match e { + StoreError::NotFound => (Code::NotFound, "not found"), + StoreError::Unauthorized => (Code::Unauthorized, "bad password"), + StoreError::Locked => (Code::Unauthorized, "invitation destroyed after too many attempts"), + StoreError::Backend(e) => { + tracing::error!("store error: {e}"); + (Code::Internal, "storage error") + } + } +} + +async fn handle(st: &AppState, req: v2::Request) -> HResult { + let now = now(); + if req.request_id.len() != 16 { + return Err((Code::BadRequest, "bad request id")); + } + if req.timestamp.abs_diff(now) > rpc::AUTH_WINDOW_SECS { + return Err((Code::Expired, "request timestamp out of window")); + } + if !st + .store + .mark_request(&req.request_id, st.limits.replay_ttl) + .await + .map_err(store_err)? + { + return Err((Code::Unauthorized, "replayed request")); + } + match req.body.ok_or((Code::BadRequest, "empty request"))? { + Req::Ping(_) => Ok(Resp::Pong(v2::Pong { server_time: now })), + Req::Post(p) => post_messages(st, p, now).await, + Req::Pull(p) => pull(st, &req.request_id, p, now).await, + Req::InvPublish(p) => { + if p.payload.len() > 64 * 1024 { + return Err((Code::TooLarge, "invitation too large")); + } + let ttl = Duration::from_secs(p.ttl_seconds.max(60) as u64).min(st.limits.max_invitation_ttl); + let len = (p.shortcode_len as usize).clamp(6, 64); + let code = st + .store + .put_invitation(p.payload, &p.password, ttl, len) + .await + .map_err(store_err)?; + Ok(Resp::InvPublished(v2::InvitationPublished { + shortcode: code, + expires_at: now + ttl.as_secs(), + })) + } + Req::InvFetch(f) => { + let payload = st + .store + .get_invitation(&f.shortcode, &f.password) + .await + .map_err(store_err)?; + Ok(Resp::InvFetched(v2::InvitationFetched { payload })) + } + } +} + +async fn post_messages(st: &AppState, p: v2::Post, now: u64) -> HResult { + if p.deposits.is_empty() || p.deposits.len() > st.limits.max_deposits { + return Err((Code::BadRequest, "bad number of deposits")); + } + let mut accepted = 0u32; + for d in p.deposits { + let mb: Mailbox = d + .mailbox + .as_slice() + .try_into() + .map_err(|_| (Code::BadRequest, "bad mailbox"))?; + if d.payload.len() > st.limits.max_payload_bytes { + return Err((Code::TooLarge, "payload too large")); + } + st.store.post(mb, d.payload, now).await.map_err(store_err)?; + accepted += 1; + } + Ok(Resp::PostAck(v2::PostAck { accepted })) +} + +async fn pull(st: &AppState, request_id: &[u8], p: v2::Pull, now: u64) -> HResult { + if p.auths.is_empty() || p.auths.len() > st.limits.max_mailboxes_per_pull { + return Err((Code::BadRequest, "bad number of mailboxes")); + } + let sign = st.keys.sign.public(); + let mut mailboxes = Vec::with_capacity(p.auths.len()); + for a in &p.auths { + let mb = rpc::verify_mailbox_auth(&sign, request_id, a, now) + .map_err(|_| (Code::Unauthorized, "bad mailbox auth"))?; + mailboxes.push(mb.0); + } + // Subscribe before draining, so a deposit landing in between is not missed. + let mut rx = st.notify.subscribe(); + let mut messages = st.store.drain(&mailboxes).await.map_err(store_err)?; + let wait = Duration::from_secs(p.wait_seconds as u64).min(st.limits.max_wait); + if messages.is_empty() && !wait.is_zero() { + let wanted: HashSet = mailboxes.iter().copied().collect(); + let _ = tokio::time::timeout(wait, async { + loop { + match rx.recv().await { + Ok(mb) if wanted.contains(&mb) => break, + Ok(_) => continue, + // Lagged: we may have missed ours, check anyway. Closed: stop. + Err(_) => break, + } + } + }) + .await; + messages = st.store.drain(&mailboxes).await.map_err(store_err)?; + } + Ok(Resp::PullResult(v2::PullResult { messages })) +} + +/// Serve on an already bound listener until the future is dropped. +pub async fn serve(listener: tokio::net::TcpListener, state: Arc) -> std::io::Result<()> { + axum::serve(listener, router(state)).await +} + +/// Encode the card for `GET /v2/card`. +pub fn encode_card(keys: &ServerKeys, url: &str, name: &str, description: &str) -> Vec { + keys.card(url, name, description, now()).encode_to_vec() +} diff --git a/crates/meow-server/src/main.rs b/crates/meow-server/src/main.rs new file mode 100644 index 0000000..3e9c2c1 --- /dev/null +++ b/crates/meow-server/src/main.rs @@ -0,0 +1,50 @@ +//! `meowsrv`: Meow v2 relay server. + +use std::sync::Arc; + +use clap::Parser; +use meow_server::config::{load_or_create_keys, Args, Config}; +use meow_server::store::{MemoryStore, RedisStore, ServerStore}; +use meow_server::{encode_card, router, AppState, Limits}; +use tokio::sync::broadcast; + +const MAX_PER_MAILBOX: usize = 10_000; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let cfg = Config::resolve(Args::parse())?; + tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::new(&cfg.log)) + .init(); + + let keys = load_or_create_keys(&cfg.key_file)?; + let (notify, _) = broadcast::channel(4096); + let store: Arc = if cfg.storage == "memory" { + tracing::warn!("using in-memory storage: messages are lost on restart"); + Arc::new(MemoryStore::new(notify.clone(), MAX_PER_MAILBOX)) + } else { + Arc::new(RedisStore::connect(&cfg.storage, notify.clone(), cfg.mailbox_ttl, MAX_PER_MAILBOX).await?) + }; + let card = encode_card(&keys, &cfg.public_url, &cfg.name, &cfg.description); + tracing::info!( + url = %cfg.public_url, + sign_key = %keys.sign.public().fingerprint(), + "server identity" + ); + let state = Arc::new(AppState { + keys, + card, + store, + notify, + limits: Limits::default(), + }); + + let listener = tokio::net::TcpListener::bind(&cfg.listen).await?; + tracing::info!("listening on {}", cfg.listen); + axum::serve(listener, router(state)) + .with_graceful_shutdown(async { + let _ = tokio::signal::ctrl_c().await; + }) + .await?; + Ok(()) +} diff --git a/crates/meow-server/src/store.rs b/crates/meow-server/src/store.rs new file mode 100644 index 0000000..dd88bad --- /dev/null +++ b/crates/meow-server/src/store.rs @@ -0,0 +1,456 @@ +//! Server storage abstraction with an in-memory and a Redis backend. +//! +//! New-message notifications go through a `broadcast` channel owned by the app +//! state: the memory store publishes to it directly; the Redis store publishes on a +//! Redis channel and a single background task per server instance forwards those +//! events (so several `meowsrv` instances can share one Redis). + +use std::collections::{HashMap, VecDeque}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use async_trait::async_trait; +use meow_proto::{v2, Message}; +use subtle::ConstantTimeEq; +use tokio::sync::broadcast; + +pub type Mailbox = [u8; 32]; + +#[derive(Debug, thiserror::Error)] +pub enum StoreError { + #[error("not found")] + NotFound, + #[error("unauthorized")] + Unauthorized, + #[error("invitation destroyed after too many failed attempts")] + Locked, + #[error("backend: {0}")] + Backend(String), +} + +impl From for StoreError { + fn from(e: redis::RedisError) -> Self { + StoreError::Backend(e.to_string()) + } +} + +pub type StoreResult = Result; + +/// Maximum failed password attempts before an invitation is destroyed. +pub const MAX_INVITATION_ATTEMPTS: i64 = 3; + +#[async_trait] +pub trait ServerStore: Send + Sync { + /// Append a payload to a mailbox and notify waiters. + async fn post(&self, mailbox: Mailbox, payload: Vec, now: u64) -> StoreResult<()>; + /// Atomically take every message of the given mailboxes. + async fn drain(&self, mailboxes: &[Mailbox]) -> StoreResult>; + /// Record a request id; returns `false` if it was already seen (replay). + async fn mark_request(&self, request_id: &[u8], ttl: Duration) -> StoreResult; + /// Store an invitation under a fresh shortcode. + async fn put_invitation( + &self, + payload: Vec, + password: &str, + ttl: Duration, + code_len: usize, + ) -> StoreResult; + /// Fetch an invitation, enforcing the password and the attempt limit. + async fn get_invitation(&self, code: &str, password: &str) -> StoreResult>; +} + +pub fn random_shortcode(len: usize) -> String { + const ALPHABET: &[u8] = b"abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + // Rejection sampling for an unbiased draw. + let limit = 256 - (256 % ALPHABET.len()); + let mut out = String::with_capacity(len); + while out.len() < len { + for b in meow_crypto::random_bytes::<32>() { + if (b as usize) < limit && out.len() < len { + out.push(ALPHABET[b as usize % ALPHABET.len()] as char); + } + } + } + out +} + +fn password_ok(expected: &str, given: &str) -> bool { + expected.as_bytes().ct_eq(given.as_bytes()).into() +} + +// ───────────────────────────── Memory ───────────────────────────── + +struct MemInvitation { + payload: Vec, + password: String, + failures: i64, + expires: Instant, +} + +#[derive(Default)] +struct MemInner { + mailboxes: HashMap>, + requests: HashMap, Instant>, + invitations: HashMap, +} + +/// In-memory store, for development and tests. Data is lost on restart. +pub struct MemoryStore { + inner: Mutex, + notify: broadcast::Sender, + max_per_mailbox: usize, +} + +impl MemoryStore { + pub fn new(notify: broadcast::Sender, max_per_mailbox: usize) -> Self { + Self { + inner: Mutex::new(MemInner::default()), + notify, + max_per_mailbox, + } + } + + fn lock(&self) -> StoreResult> { + self.inner + .lock() + .map_err(|_| StoreError::Backend("poisoned lock".into())) + } +} + +#[async_trait] +impl ServerStore for MemoryStore { + async fn post(&self, mailbox: Mailbox, payload: Vec, now: u64) -> StoreResult<()> { + { + let mut g = self.lock()?; + let q = g.mailboxes.entry(mailbox).or_default(); + q.push_back(v2::StoredMessage { + mailbox: mailbox.to_vec(), + payload, + received_at: now, + }); + while q.len() > self.max_per_mailbox { + q.pop_front(); + } + } + let _ = self.notify.send(mailbox); + Ok(()) + } + + async fn drain(&self, mailboxes: &[Mailbox]) -> StoreResult> { + let mut g = self.lock()?; + Ok(mailboxes + .iter() + .filter_map(|m| g.mailboxes.remove(m)) + .flatten() + .collect()) + } + + async fn mark_request(&self, request_id: &[u8], ttl: Duration) -> StoreResult { + let mut g = self.lock()?; + let now = Instant::now(); + g.requests.retain(|_, exp| *exp > now); + Ok(g.requests.insert(request_id.to_vec(), now + ttl).is_none()) + } + + async fn put_invitation( + &self, + payload: Vec, + password: &str, + ttl: Duration, + code_len: usize, + ) -> StoreResult { + let mut g = self.lock()?; + let now = Instant::now(); + g.invitations.retain(|_, i| i.expires > now); + let code = loop { + let c = random_shortcode(code_len); + if !g.invitations.contains_key(&c) { + break c; + } + }; + g.invitations.insert( + code.clone(), + MemInvitation { + payload, + password: password.to_string(), + failures: 0, + expires: now + ttl, + }, + ); + Ok(code) + } + + async fn get_invitation(&self, code: &str, password: &str) -> StoreResult> { + let mut g = self.lock()?; + let now = Instant::now(); + let inv = match g.invitations.get_mut(code) { + Some(i) if i.expires > now => i, + _ => return Err(StoreError::NotFound), + }; + if !inv.password.is_empty() && !password_ok(&inv.password, password) { + inv.failures += 1; + if inv.failures >= MAX_INVITATION_ATTEMPTS { + g.invitations.remove(code); + return Err(StoreError::Locked); + } + return Err(StoreError::Unauthorized); + } + inv.failures = 0; + Ok(inv.payload.clone()) + } +} + +// ───────────────────────────── Redis ───────────────────────────── + +/// Redis channel used to fan out new-message notifications between instances. +pub const NOTIFY_CHANNEL: &str = "meow:v2:new"; + +/// Redis-backed store. +/// +/// Keys: `meow:v2:mb:{hex}` (list of encoded `StoredMessage`), `meow:v2:rq:{hex}` +/// (replay cache), `meow:v2:inv:{code}`, `meow:v2:invpw:{code}`, `meow:v2:invfa:{code}`. +pub struct RedisStore { + conn: redis::aio::MultiplexedConnection, + mailbox_ttl: Duration, + max_per_mailbox: usize, +} + +fn hexs(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +impl RedisStore { + /// Connect and start the notification forwarder. + pub async fn connect( + url: &str, + notify: broadcast::Sender, + mailbox_ttl: Duration, + max_per_mailbox: usize, + ) -> StoreResult { + let client = redis::Client::open(url)?; + let conn = client.get_multiplexed_async_connection().await?; + let mut pubsub = client.get_async_pubsub().await?; + pubsub.subscribe(NOTIFY_CHANNEL).await?; + tokio::spawn(async move { + use futures_util::StreamExt; + let mut stream = pubsub.on_message(); + while let Some(msg) = stream.next().await { + if let Ok(mb) = ::try_from(msg.get_payload_bytes()) { + let _ = notify.send(mb); + } + } + tracing::error!("redis notification stream closed"); + }); + Ok(Self { + conn, + mailbox_ttl, + max_per_mailbox, + }) + } +} + +#[async_trait] +impl ServerStore for RedisStore { + async fn post(&self, mailbox: Mailbox, payload: Vec, now: u64) -> StoreResult<()> { + let key = format!("meow:v2:mb:{}", hexs(&mailbox)); + let item = v2::StoredMessage { + mailbox: mailbox.to_vec(), + payload, + received_at: now, + } + .encode_to_vec(); + let mut c = self.conn.clone(); + let max = self.max_per_mailbox as isize; + let _: () = redis::pipe() + .atomic() + .rpush(&key, item) + .ignore() + .ltrim(&key, -max, -1) + .ignore() + .expire(&key, self.mailbox_ttl.as_secs() as i64) + .ignore() + .publish(NOTIFY_CHANNEL, mailbox.as_slice()) + .ignore() + .query_async(&mut c) + .await?; + Ok(()) + } + + async fn drain(&self, mailboxes: &[Mailbox]) -> StoreResult> { + let mut out = Vec::new(); + let mut c = self.conn.clone(); + for mb in mailboxes { + let key = format!("meow:v2:mb:{}", hexs(mb)); + let (items, _): (Vec>, i64) = redis::pipe() + .atomic() + .lrange(&key, 0, -1) + .del(&key) + .query_async(&mut c) + .await?; + for it in items { + match v2::StoredMessage::decode(it.as_slice()) { + Ok(m) => out.push(m), + Err(e) => tracing::warn!("dropping corrupted stored message: {e}"), + } + } + } + Ok(out) + } + + async fn mark_request(&self, request_id: &[u8], ttl: Duration) -> StoreResult { + let mut c = self.conn.clone(); + let r: Option = redis::cmd("SET") + .arg(format!("meow:v2:rq:{}", hexs(request_id))) + .arg(1) + .arg("NX") + .arg("EX") + .arg(ttl.as_secs()) + .query_async(&mut c) + .await?; + Ok(r.is_some()) + } + + async fn put_invitation( + &self, + payload: Vec, + password: &str, + ttl: Duration, + code_len: usize, + ) -> StoreResult { + let mut c = self.conn.clone(); + loop { + let code = random_shortcode(code_len); + let ok: Option = redis::cmd("SET") + .arg(format!("meow:v2:inv:{code}")) + .arg(payload.as_slice()) + .arg("NX") + .arg("EX") + .arg(ttl.as_secs()) + .query_async(&mut c) + .await?; + if ok.is_some() { + if !password.is_empty() { + let _: () = redis::cmd("SET") + .arg(format!("meow:v2:invpw:{code}")) + .arg(password) + .arg("EX") + .arg(ttl.as_secs()) + .query_async(&mut c) + .await?; + } + return Ok(code); + } + } + } + + async fn get_invitation(&self, code: &str, password: &str) -> StoreResult> { + let mut c = self.conn.clone(); + let inv_key = format!("meow:v2:inv:{code}"); + let pw_key = format!("meow:v2:invpw:{code}"); + let fa_key = format!("meow:v2:invfa:{code}"); + let (payload, expected): (Option>, Option) = + redis::pipe().get(&inv_key).get(&pw_key).query_async(&mut c).await?; + let payload = payload.ok_or(StoreError::NotFound)?; + if let Some(expected) = expected { + if !password_ok(&expected, password) { + let (n, _): (i64, i64) = redis::pipe() + .atomic() + .incr(&fa_key, 1) + .expire(&fa_key, 86_400) + .query_async(&mut c) + .await?; + if n >= MAX_INVITATION_ATTEMPTS { + let _: () = redis::pipe() + .del(&inv_key) + .del(&pw_key) + .del(&fa_key) + .query_async(&mut c) + .await?; + return Err(StoreError::Locked); + } + return Err(StoreError::Unauthorized); + } + let _: () = redis::cmd("DEL").arg(&fa_key).query_async(&mut c).await?; + } + Ok(payload) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shortcodes() { + let c = random_shortcode(8); + assert_eq!(c.len(), 8); + assert!(c.chars().all(|x| x.is_ascii_alphanumeric())); + assert_ne!(random_shortcode(16), random_shortcode(16)); + } + + async fn exercise(store: &dyn ServerStore, rx: &mut broadcast::Receiver) { + let mb = meow_crypto::random_bytes::<32>(); + store.post(mb, b"one".to_vec(), 1).await.unwrap(); + store.post(mb, b"two".to_vec(), 2).await.unwrap(); + assert_eq!(rx.recv().await.unwrap(), mb); + let got = store.drain(&[mb]).await.unwrap(); + assert_eq!( + got.iter().map(|m| m.payload.clone()).collect::>(), + vec![b"one".to_vec(), b"two".to_vec()] + ); + assert!(store.drain(&[mb]).await.unwrap().is_empty()); + + let rid = meow_crypto::random_bytes::<16>(); + assert!(store.mark_request(&rid, Duration::from_secs(60)).await.unwrap()); + assert!(!store.mark_request(&rid, Duration::from_secs(60)).await.unwrap()); + + let code = store + .put_invitation(b"inv".to_vec(), "pw", Duration::from_secs(60), 10) + .await + .unwrap(); + assert_eq!(store.get_invitation(&code, "pw").await.unwrap(), b"inv"); + assert!(matches!( + store.get_invitation(&code, "x").await, + Err(StoreError::Unauthorized) + )); + assert!(matches!( + store.get_invitation(&code, "x").await, + Err(StoreError::Unauthorized) + )); + assert!(matches!( + store.get_invitation(&code, "x").await, + Err(StoreError::Locked) + )); + assert!(matches!( + store.get_invitation(&code, "pw").await, + Err(StoreError::NotFound) + )); + + let open = store + .put_invitation(b"open".to_vec(), "", Duration::from_secs(60), 6) + .await + .unwrap(); + assert_eq!(store.get_invitation(&open, "anything").await.unwrap(), b"open"); + } + + #[tokio::test] + async fn memory_store() { + let (tx, mut rx) = broadcast::channel(16); + let store = MemoryStore::new(tx, 100); + exercise(&store, &mut rx).await; + } + + /// Runs only when `MEOW_TEST_REDIS` is set (e.g. `redis://127.0.0.1:6379/15`). + #[tokio::test] + async fn redis_store() { + let Ok(url) = std::env::var("MEOW_TEST_REDIS") else { + eprintln!("MEOW_TEST_REDIS not set: skipping"); + return; + }; + let (tx, mut rx) = broadcast::channel(16); + let store = RedisStore::connect(&url, tx, Duration::from_secs(60), 100) + .await + .unwrap(); + exercise(&store, &mut rx).await; + } +} diff --git a/proto/meow.proto b/proto/meow.proto new file mode 100644 index 0000000..36ff50a --- /dev/null +++ b/proto/meow.proto @@ -0,0 +1,224 @@ +// Meow protocol v2. +// +// Conventions: +// * all keys are raw 32-byte values (Ed25519 / X25519), never base64 inside protobuf; +// * timestamps are unix seconds (uint64) unless suffixed with _ms; +// * every top-level wire object carries a `version` so it can evolve without ambiguity. +// +// See rust/ARCHITECTURE.md for the cryptographic constructions referenced here. +syntax = "proto3"; +package meow.v2; + +// ───────────────────────────── Cards ───────────────────────────── + +// Self-signed description of a server, served at GET /v2/card. +message ServerCard { + uint32 version = 1; + string name = 2; + string description = 3; + string url = 4; // canonical base URL (http[s]://host[:port]) + bytes sign_key = 5; // Ed25519 public key + bytes dh_key = 6; // X25519 public key, recipient of sealed requests + uint64 issued_at = 7; + bytes signature = 8; // Ed25519 over the card encoded with signature = empty +} + +// Per-contact public material exchanged during an invitation. +message ContactCard { + uint32 version = 1; + string name = 2; // nickname I want this contact to see + bytes identity_key = 3; // Ed25519 + bytes dh_key = 4; // X25519 static key for this relationship + bytes mailbox = 5; // Ed25519 public key = mailbox where I read messages from you + bytes ratchet_key = 6; // X25519 initial ratchet public key + repeated ServerCard pull_servers = 7; // where I poll my mailbox +} + +// ─────────────────────────── Invitation ────────────────────────── + +// Step 1 (initiator → invitee). Transported by file, QR code, server shortcode, BLE... +message InvitationOffer { + uint32 version = 1; + bytes invitation_id = 2; // 16 random bytes + string initiator_name = 3; + bytes offer_dh_key = 4; // X25519 temporary key: the Answer is sealed to it + bytes answer_mailbox = 5; // Ed25519 temporary key: mailbox where the Answer may be posted + repeated ServerCard answer_servers = 6; + string message = 7; + uint64 expires_at = 8; +} + +// Step 2 content (sealed to offer_dh_key). +message InvitationAnswerBody { + bytes invitation_id = 1; + ContactCard invitee = 2; + bytes signature = 3; // invitee.identity_key over transcript(offer, invitee) +} + +// Step 3 content (sealed to invitee.dh_key). +message InvitationConfirmBody { + bytes invitation_id = 1; + ContactCard initiator = 2; + bytes ephemeral_key = 3; // X25519 public key used in the X3DH-like agreement + bytes signature = 4; // initiator.identity_key over transcript(offer, invitee, initiator, ephemeral) + RatchetMessage first_message = 5; // first Double Ratchet message (HandshakeAck): bootstraps the invitee's sending chain +} + +// A sealed-box blob: ECIES X25519 + HKDF-SHA256 + XChaCha20-Poly1305. +message Sealed { + uint32 version = 1; + bytes ephemeral_key = 2; + bytes ciphertext = 3; // nonce (24) || aead ciphertext +} + +// Invitation steps 2 and 3 as transported (file or mailbox). +message InvitationMessage { + uint32 version = 1; + uint32 step = 2; // 2 = answer, 3 = confirm + bytes invitation_id = 3; // clear, so the receiver can find the pending invitation + Sealed sealed = 4; +} + +// ─────────────────────────── Peer layer ────────────────────────── + +message RatchetHeader { + bytes dh_key = 1; // X25519 current ratchet public key + uint32 previous_count = 2; // PN + uint32 message_number = 3; // N +} + +// What sits in a mailbox. +message PeerEnvelope { + uint32 version = 1; + oneof body { + RatchetMessage ratchet = 2; + InvitationMessage invitation = 3; // step 2 posted to the offer's answer mailbox + } +} + +message RatchetMessage { + RatchetHeader header = 1; + bytes ciphertext = 2; // nonce || aead(padded UserMessage) +} + +// Plaintext of a RatchetMessage (after unpadding). +message UserMessage { + bytes id = 1; // 16 random bytes + uint64 sent_at_ms = 2; + oneof body { + TextBody text = 10; + FileBody file = 11; + Receipt receipt = 12; + HandshakeAck handshake_ack = 13; // invitation step 4 + bytes app_data = 14; + } + bytes reply_to = 3; +} + +message TextBody { string text = 1; } + +message FileBody { + string filename = 1; + uint64 size = 2; + uint32 chunk = 3; + uint32 chunks = 4; + bytes data = 5; + string mime = 6; +} + +message Receipt { + enum Kind { KIND_UNSPECIFIED = 0; DELIVERED = 1; READ = 2; } + Kind kind = 1; + repeated bytes message_ids = 2; +} + +message HandshakeAck { bytes invitation_id = 1; } + +// ─────────────────────────── Client ↔ server ───────────────────── + +// Body of POST /v2/rpc. +message SealedRequest { + uint32 version = 1; + bytes ephemeral_key = 2; + bytes ciphertext = 3; // nonce || aead(Request), key = k_req +} + +// Response body of POST /v2/rpc. +message SealedResponse { + uint32 version = 1; + bytes ciphertext = 2; // nonce || aead(Response), key = k_resp +} + +message Request { + bytes request_id = 1; // 16 random bytes, anti-replay + uint64 timestamp = 2; + oneof body { + Ping ping = 10; + Post post = 11; + Pull pull = 12; + InvitationPublish inv_publish = 13; + InvitationFetch inv_fetch = 14; + } +} + +message Response { + bytes request_id = 1; + oneof body { + Error error = 10; + Pong pong = 11; + PostAck post_ack = 12; + PullResult pull_result = 13; + InvitationPublished inv_published = 14; + InvitationFetched inv_fetched = 15; + } +} + +message Error { + enum Code { + CODE_UNSPECIFIED = 0; + BAD_REQUEST = 1; + UNAUTHORIZED = 2; + NOT_FOUND = 3; + TOO_LARGE = 4; + RATE_LIMITED = 5; + INTERNAL = 6; + EXPIRED = 7; + } + Code code = 1; + string message = 2; +} + +message Ping {} +message Pong { uint64 server_time = 1; } + +message Deposit { + bytes mailbox = 1; // Ed25519 public key + bytes payload = 2; // encoded PeerEnvelope +} +message Post { repeated Deposit deposits = 1; } +message PostAck { uint32 accepted = 1; } + +message MailboxAuth { + bytes mailbox = 1; + uint64 timestamp = 2; + bytes signature = 3; // see ARCHITECTURE.md §3.5 +} +message Pull { repeated MailboxAuth auths = 1; uint32 wait_seconds = 2; } + +message StoredMessage { + bytes mailbox = 1; + bytes payload = 2; + uint64 received_at = 3; +} +message PullResult { repeated StoredMessage messages = 1; } + +message InvitationPublish { + bytes payload = 1; // encoded InvitationOffer + uint32 ttl_seconds = 2; + uint32 shortcode_len = 3; + string password = 4; +} +message InvitationPublished { string shortcode = 1; uint64 expires_at = 2; } + +message InvitationFetch { string shortcode = 1; string password = 2; } +message InvitationFetched { bytes payload = 1; } diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..7530651 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +max_width = 120 diff --git a/scripts/check.sh b/scripts/check.sh new file mode 100755 index 0000000..a034084 --- /dev/null +++ b/scripts/check.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# Format check + lints + unit/integration tests. Run before every commit. +# Set MEOW_TEST_REDIS=redis://127.0.0.1:6379/15 to include the Redis store test. +set -euo pipefail +cd "$(dirname "$0")/.." +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace diff --git a/tests/e2e.sh b/tests/e2e.sh new file mode 100755 index 0000000..0719611 --- /dev/null +++ b/tests/e2e.sh @@ -0,0 +1,172 @@ +#!/usr/bin/env bash +# End-to-end test of the Meow v2 Rust stack (meowsrv + meow CLI). +# Rust equivalent of meowcli/test.sh, with output assertions. +# +# Usage: +# tests/e2e.sh # two servers, in-memory storage +# E2E_STORAGE=redis://127.0.0.1:6379/15 tests/e2e.sh # Redis backend (db 15 is used) +# E2E_RELEASE=1 tests/e2e.sh # release build +# E2E_KEEP=1 tests/e2e.sh # keep tests/work for inspection +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +WORK="$ROOT/tests/work" +PORT1="${E2E_PORT1:-18080}" +PORT2="${E2E_PORT2:-18081}" +S1="http://127.0.0.1:$PORT1" +S2="http://127.0.0.1:$PORT2" +STORAGE="${E2E_STORAGE:-memory}" + +green() { printf '\033[32m%s\033[0m\n' "$*"; } +red() { printf '\033[31m%s\033[0m\n' "$*"; } +step() { green "## $*"; } + +PIDS=() +cleanup() { + for p in "${PIDS[@]:-}"; do [ -n "$p" ] && kill "$p" 2>/dev/null || true; done + wait 2>/dev/null || true + [ "${E2E_KEEP:-0}" = 1 ] || rm -rf "$WORK" +} +trap cleanup EXIT +trap 'red "FAILED at line $LINENO"' ERR + +# ── build ── +step "BUILD" +PROFILE=debug +if [ "${E2E_RELEASE:-0}" = 1 ]; then + (cd "$ROOT" && cargo build --release --bin meow --bin meowsrv); PROFILE=release +else + (cd "$ROOT" && cargo build --bin meow --bin meowsrv) +fi +MEOW_BIN="$ROOT/target/$PROFILE/meow" +SRV_BIN="$ROOT/target/$PROFILE/meowsrv" + +rm -rf "$WORK" && mkdir -p "$WORK" && cd "$WORK" + +# ── servers ── +step "SERVERS ($STORAGE)" +start_server() { # port name + MEOWSRV_LOG=warn "$SRV_BIN" --listen "127.0.0.1:$1" --name "$2" \ + --storage "$STORAGE" --key-file "$WORK/$2.key" >"$WORK/$2.log" 2>&1 & + PIDS+=($!) +} +start_server "$PORT1" srv1 +start_server "$PORT2" srv2 +for url in "$S1" "$S2"; do + for _ in $(seq 50); do curl -fs "$url/healthz" >/dev/null 2>&1 && break; sleep 0.1; done + curl -fs "$url/healthz" >/dev/null || { red "server $url did not start"; cat "$WORK"/*.log; exit 1; } +done + +export MEOW_PASSWORD="e2e-password" +export MEOW_INSECURE_FAST_KDF=true # weak KDF: tests only +meow() { local id="$1"; shift; "$MEOW_BIN" -i "$WORK/$id.mwid2" --downloads "$WORK/dl-$id" "$@"; } + +# expect : run, show output, check it contains needle +expect() { + local desc="$1" needle="$2"; shift 2 + local out + out="$("$@")" + [ -n "$out" ] && printf '%s\n' "$out" | sed 's/^/ /' + if ! grep -qF -- "$needle" <<<"$out"; then + red "expected '$needle' ($desc)"; exit 1 + fi +} + +# ── identities ── +step "IDENTITIES" +for who in bob alice remote; do meow "$who" identity create "$who" --force; done +expect "wrong password rejected" "cannot open identity" \ + bash -c "'$MEOW_BIN' -i '$WORK/bob.mwid2' -p wrong identity show 2>&1 || true" + +step "SERVER ADD" +for who in bob alice remote; do + meow "$who" server add "$S1" >/dev/null + meow "$who" server add "$S2" >/dev/null +done +expect "bob has 2 servers" "srv2" meow bob server list + +# ── file invitation ── +step "FILE INVITATION (4 steps)" +expect "step 1" "bob-alice.mwiv2" meow bob invitation create alice --servers "$S1,$S2" --message "hello alice" +expect "check" "hello alice" meow alice invitation check bob-alice.mwiv2 +expect "step 2" "alice-bob.mwiv2" meow alice invitation answer bob-alice.mwiv2 --servers "$S1,$S2" +expect "alice pending" "AnswerSent" meow alice contact list +expect "step 3" "bob-alice-step3.mwiv2" meow bob invitation accept alice-bob.mwiv2 +expect "bob can already send" "sent to alice" meow bob send alice "sent before finalize" +expect "step 4" "contact bob is active" meow alice invitation finalize bob-alice-step3.mwiv2 +expect "bob receives the ack" "contact alice is active" meow bob +expect "bob: alice active" "Active" meow bob contact list +SN_BOB="$(meow bob contact show alice | grep 'safety number')" +SN_ALICE="$(meow alice contact show bob | grep 'safety number')" +[ "$SN_BOB" = "$SN_ALICE" ] || { red "safety numbers differ"; exit 1; } +echo " $SN_BOB (identical on both sides)" + +# ── messaging ── +step "MESSAGING" +expect "early message delivered" "[bob] sent before finalize" meow alice +meow bob send alice hello >/dev/null +expect "receive" "[bob] hello" meow alice +[ -z "$(meow alice)" ] || { red "unexpected extra messages"; exit 1; } +printf 'meow meow\n' >meow01.ascii +head -c 200000 /dev/urandom >blob.bin +meow bob send-file alice meow01.ascii >/dev/null +expect "text file" "file saved to" meow alice +cmp meow01.ascii "$WORK/dl-alice/meow01.ascii" +meow bob send-file alice blob.bin >/dev/null +expect "binary file" "blob.bin" meow alice +cmp blob.bin "$WORK/dl-alice/blob.bin" +meow bob send alice msg1 >/dev/null; meow bob send alice msg2 >/dev/null; meow bob send alice msg3 >/dev/null +OUT="$(meow alice)"; printf '%s\n' "$OUT" | sed 's/^/ /' +[ "$(grep -c '^\[bob\] msg' <<<"$OUT")" = 3 ] || { red "expected 3 messages"; exit 1; } +expect "reply" "sent to bob" meow alice send bob "hi bob" +expect "bob reads reply" "[alice] hi bob" meow bob + +# ── server invitation ── +step "SERVER INVITATION (4 steps)" +URL="$(meow bob server-invitation create remote --servers "$S1,$S2" --message "via server" --invitation-password s3cret)" +echo " invitation URL: $URL" +expect "wrong invitation password" "bad password" \ + bash -c "'$MEOW_BIN' -i '$WORK/remote.mwid2' server-invitation get '$URL' --invitation-password nope 2>&1 || true" +expect "step 2" "answered invitation from bob" meow remote server-invitation get "$URL" --invitation-password s3cret +expect "step 3 (auto)" "invitation accepted by remote" meow bob +expect "step 4 (auto)" "contact bob is active" meow remote +expect "ack" "contact remote is active" meow bob +meow remote send bob "hello from remote" >/dev/null +expect "remote -> bob" "[remote] hello from remote" meow bob + +# ── long poll ── +step "LONG POLL" +meow alice longpoll --wait 20 --exit >"$WORK/lp1.out" & +LP=$! +sleep 1 +meow bob send alice "longpoll?" >/dev/null +START=$(date +%s) +wait "$LP" +ELAPSED=$(( $(date +%s) - START )) +sed 's/^/ /' "$WORK/lp1.out" +grep -qF "[bob] longpoll?" "$WORK/lp1.out" || { red "long poll did not get the message"; exit 1; } +[ "$ELAPSED" -lt 10 ] || { red "long poll took ${ELAPSED}s"; exit 1; } + +step "LONG POLL (offline messages)" +for i in 1 2 3; do meow bob send alice "longpoll$i?" >/dev/null; done +OUT="$(meow alice longpoll --wait 5 --exit)"; printf '%s\n' "$OUT" | sed 's/^/ /' +[ "$(grep -c 'longpoll[123]?' <<<"$OUT")" = 3 ] || { red "expected 3 offline messages"; exit 1; } + +step "MIXED" +meow bob send alice "ba1?" >/dev/null +meow alice send bob "ab1?" >/dev/null +meow bob send alice "ba2?" >/dev/null +meow alice send bob "ab2?" >/dev/null +expect "alice" "[bob] ba2?" meow alice longpoll --wait 5 --exit +expect "bob" "[alice] ab2?" meow bob longpoll --wait 5 --exit + +# ── resilience: one server down ── +step "ONE SERVER DOWN" +kill "${PIDS[1]}"; wait "${PIDS[1]}" 2>/dev/null || true; PIDS[1]="" +expect "send with one server down" "(1 server(s))" meow bob send alice "still here" +expect "receive with one server down" "[bob] still here" meow alice 2>/dev/null + +step "HISTORY" +expect "history" "[alice] hi bob" meow bob history alice + +green "ALL E2E TESTS PASSED"