first commit

This commit is contained in:
yves committed 2026-11-20 21:47:33 +01:00
commit 6d3ea3e2a6
43 files changed
+8204

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
/target
*.mwid2
*.mwiv2
/tests/work
+247
View File
@@ -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<Event>
```
* 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`.
+23
View File
@@ -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.
Generated
+2614
View File
File diff suppressed because it is too large. Load diff
+24
View File
@@ -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
+52
View File
@@ -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"
```
+179
View File
@@ -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/<code>#<clé>`) : 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).
+21
View File
@@ -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
+469
View File
@@ -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<PathBuf>,
/// Password protecting the identity file.
#[arg(short, long, env = "MEOW_PASSWORD", hide_env_values = true, global = true)]
password: Option<String>,
/// 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<Cmd>,
}
#[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<String>,
},
/// 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<String>,
}
#[derive(Subcommand)]
enum InvitationCmd {
/// Step 1: create an invitation file for <contact>.
Create {
contact: String,
#[command(flatten)]
sel: ServerSel,
#[arg(short, long, default_value = "")]
message: String,
#[arg(short, long)]
out: Option<PathBuf>,
},
/// 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<String>,
#[arg(short, long)]
out: Option<PathBuf>,
},
/// Step 3: accept an answer file, produce the confirmation file.
Accept {
file: PathBuf,
#[arg(short, long)]
out: Option<PathBuf>,
},
/// 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<String>,
#[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> {
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::<Vec<_>>()
.join(", ")
);
}
println!(
"my servers: {}",
k.my_pull_servers
.iter()
.map(|s| s.url.as_str())
.collect::<Vec<_>>()
.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}] <file {name}, {size} bytes>"),
}
}
}
}
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::<Vec<_>>()
.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(())
}
+25
View File
@@ -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
+698
View File
@@ -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<T> = std::result::Result<T, Error>;
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<u8>,
text: String,
sent_at_ms: u64,
},
File {
contact: String,
name: String,
data: Vec<u8>,
},
}
/// Outcome of a send.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SendReport {
pub message_id: Vec<u8>,
/// 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 `<identity>.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<std::fs::File> {
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<Self> {
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<Self> {
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<ServerInfo> {
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<Vec<ServerInfo>> {
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<usize> {
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<Vec<&HistoryEntry>> {
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<Vec<u8>> {
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<OfferInfo> {
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<Vec<u8>> {
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<Vec<u8>> {
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<String> {
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
/// (`<server>/inv/<shortcode>`).
pub async fn publish_invitation(
&mut self,
contact_name: &str,
server_urls: &[String],
message: &str,
password: &str,
ttl: u64,
) -> Result<String> {
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<String> {
let (base, code) = url
.rsplit_once("/inv/")
.ok_or_else(|| Error::Invalid("invitation URL must look like <server>/inv/<code>".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<SendReport> {
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<SendReport> {
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<SendReport> {
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<v2::Deposit>) -> Result<usize> {
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<Vec<Event>> {
// server (by signing key) → (server, mailbox keys)
let mut jobs: BTreeMap<SignPublic, (ServerInfo, Vec<SigningKeyPair>)> = 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<v2::StoredMessage>) -> Result<Vec<Event>> {
// Handshake messages first (step 2 before step 3), then ratchet messages by arrival.
let mut envs: Vec<(u32, u64, Vec<u8>, 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<ServerInfo>, 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)
}
}
+75
View File
@@ -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<u8>,
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<ServerInfo>,
pub contacts: Vec<Contact>,
pub history: Vec<HistoryEntry>,
}
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<Self> {
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(())
}
}
+71
View File
@@ -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<Self> {
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<ServerInfo> {
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<Resp> {
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<Resp> {
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)?)
}
}
+182
View File
@@ -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<String> {
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);
}
+16
View File
@@ -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
+197
View File
@@ -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<ServerInfo>,
}
impl PeerCard {
pub fn from_proto(c: &v2::ContactCard) -> Result<Self> {
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::<Result<Vec<_>>>()?;
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<u8>,
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<OfferSecrets>,
/// My keys (created at step 2 for the invitee, step 3 for the initiator).
pub keys: Option<OwnKeys>,
/// Servers where I poll my mailbox for this contact.
pub my_pull_servers: Vec<ServerInfo>,
pub peer: Option<PeerCard>,
/// Serialised Double Ratchet session.
pub session: Option<Vec<u8>>,
/// 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<Vec<u8>>,
/// 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<Session> {
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<String> {
self.transcript.map(|t| {
t[..10]
.chunks(2)
.map(|c| format!("{:05}", u16::from_be_bytes([c[0], c[1]])))
.collect::<Vec<_>>()
.join(" ")
})
}
}
+386
View File
@@ -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<SealedBox> {
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<u8>,
}
/// 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<ServerInfo>,
message: &str,
now: u64,
ttl_seconds: u64,
) -> Result<NewOffer> {
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<ServerInfo>,
pub answer_mailbox: SignPublic,
}
/// Parse and validate an offer.
pub fn inspect_offer(offer_bytes: &[u8], now: u64) -> Result<OfferInfo> {
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::<Result<_>>()?,
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<ServerInfo>,
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<v2::InvitationMessage> {
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<v2::PeerEnvelope> {
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<v2::Deposit> {
let env = v2::PeerEnvelope {
version: PROTOCOL_VERSION,
body: Some(v2::peer_envelope::Body::Invitation(confirm.clone())),
};
messaging::deposit_for(contact, &env)
}
+59
View File
@@ -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<T> = std::result::Result<T, Error>;
pub(crate) fn proto_err(msg: impl Into<String>) -> 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<Vec<u8>> {
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()
}
+99
View File
@@ -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<u8> {
[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<v2::RatchetMessage> {
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<v2::UserMessage> {
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<v2::PeerEnvelope> {
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<v2::UserMessage> {
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<v2::Deposit> {
Ok(v2::Deposit {
mailbox: contact.peer()?.mailbox.to_vec(),
payload: env.encode_to_vec(),
})
}
+189
View File
@@ -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<u8>,
}
/// 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<u8>, 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<v2::response::Body> {
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<u8> {
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<u8> {
[
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<SignPublic> {
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<u8>, 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());
}
}
+121
View File
@@ -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<u8>,
}
fn signed_bytes(card: &v2::ServerCard) -> Vec<u8> {
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<Self> {
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> {
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());
}
}
+121
View File
@@ -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());
}
+24
View File
@@ -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
+75
View File
@@ -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<u8> {
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<Vec<u8>> {
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""));
}
}
+43
View File
@@ -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<const N: usize>(ikm: &[u8], salt: &[u8], label: &str) -> Result<[u8; N]> {
let hk = Hkdf::<Sha256>::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 = <Hmac<Sha256> 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);
}
}
+188
View File
@@ -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<Self> {
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<u8> {
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<SharedSecret> {
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());
}
}
+64
View File
@@ -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<T> = std::result::Result<T, CryptoError>;
/// Fill a fixed-size array with OS randomness.
pub fn random_bytes<const N: usize>() -> [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()
}
+51
View File
@@ -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<u8> {
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());
}
}
+106
View File
@@ -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<Key> {
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<Vec<u8>> {
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<Vec<u8>> {
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));
}
}
+333
View File
@@ -0,0 +1,333 @@
//! Double Ratchet, following the Signal specification
//! (<https://signal.org/docs/specifications/doubleratchet/>).
//!
//! * `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<DhPublic>,
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<u8> {
[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<Self> {
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<u8>)> {
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<Vec<u8>> {
// 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<u8> {
postcard::to_allocvec(self).unwrap_or_default()
}
pub fn from_bytes(b: &[u8]) -> Result<Self> {
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");
}
}
+79
View File
@@ -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<u8>,
}
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<u8>, 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());
}
}
+16
View File
@@ -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
+9
View File
@@ -0,0 +1,9 @@
//! Compiles `proto/meow.proto` with protox (pure Rust): no `protoc` required.
fn main() -> Result<(), Box<dyn std::error::Error>> {
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(())
}
+27
View File
@@ -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<M: Message + Default>(bytes: &[u8]) -> Result<M, prost::DecodeError> {
M::decode(bytes)
}
/// Encode helper.
pub fn encode<M: Message>(msg: &M) -> Vec<u8> {
msg.encode_to_vec()
}
+34
View File
@@ -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
+139
View File
@@ -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<PathBuf>,
/// Listen address, e.g. 0.0.0.0:8080.
#[arg(long, env = "MEOWSRV_LISTEN")]
pub listen: Option<String>,
/// Public URL announced in the server card (defaults to http://<listen>).
#[arg(long, env = "MEOWSRV_PUBLIC_URL")]
pub public_url: Option<String>,
#[arg(long, env = "MEOWSRV_NAME")]
pub name: Option<String>,
#[arg(long, env = "MEOWSRV_DESCRIPTION")]
pub description: Option<String>,
/// `memory` or a Redis URL (`redis://host:6379/0`).
#[arg(long, env = "MEOWSRV_STORAGE")]
pub storage: Option<String>,
/// Private key file, created with mode 0600 if missing.
#[arg(long, env = "MEOWSRV_KEY_FILE")]
pub key_file: Option<PathBuf>,
/// Days a message is kept in a mailbox (Redis backend).
#[arg(long, env = "MEOWSRV_MAILBOX_TTL_DAYS")]
pub mailbox_ttl_days: Option<u64>,
/// Log filter (tracing EnvFilter syntax), e.g. `info` or `meow_server=debug`.
#[arg(long, env = "MEOWSRV_LOG")]
pub log: Option<String>,
}
#[derive(Deserialize, Debug, Default)]
#[serde(deny_unknown_fields)]
struct FileConfig {
listen: Option<String>,
public_url: Option<String>,
name: Option<String>,
description: Option<String>,
storage: Option<String>,
key_file: Option<PathBuf>,
mailbox_ttl_days: Option<u64>,
log: Option<String>,
}
/// 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<Self> {
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<ServerKeys> {
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)
}
+233
View File
@@ -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<u8>,
pub store: Arc<dyn ServerStore>,
pub notify: broadcast::Sender<Mailbox>,
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<AppState>) -> 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<Arc<AppState>>) -> impl IntoResponse {
([(header::CONTENT_TYPE, "application/x-protobuf")], st.card.clone())
}
async fn rpc_handler(State(st): State<Arc<AppState>>, 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<Resp, (Code, &'static str)>;
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<Mailbox> = 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<AppState>) -> 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<u8> {
keys.card(url, name, description, now()).encode_to_vec()
}
+50
View File
@@ -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<dyn ServerStore> = 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(())
}
+456
View File
@@ -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<redis::RedisError> for StoreError {
fn from(e: redis::RedisError) -> Self {
StoreError::Backend(e.to_string())
}
}
pub type StoreResult<T> = Result<T, StoreError>;
/// 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<u8>, now: u64) -> StoreResult<()>;
/// Atomically take every message of the given mailboxes.
async fn drain(&self, mailboxes: &[Mailbox]) -> StoreResult<Vec<v2::StoredMessage>>;
/// Record a request id; returns `false` if it was already seen (replay).
async fn mark_request(&self, request_id: &[u8], ttl: Duration) -> StoreResult<bool>;
/// Store an invitation under a fresh shortcode.
async fn put_invitation(
&self,
payload: Vec<u8>,
password: &str,
ttl: Duration,
code_len: usize,
) -> StoreResult<String>;
/// Fetch an invitation, enforcing the password and the attempt limit.
async fn get_invitation(&self, code: &str, password: &str) -> StoreResult<Vec<u8>>;
}
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<u8>,
password: String,
failures: i64,
expires: Instant,
}
#[derive(Default)]
struct MemInner {
mailboxes: HashMap<Mailbox, VecDeque<v2::StoredMessage>>,
requests: HashMap<Vec<u8>, Instant>,
invitations: HashMap<String, MemInvitation>,
}
/// In-memory store, for development and tests. Data is lost on restart.
pub struct MemoryStore {
inner: Mutex<MemInner>,
notify: broadcast::Sender<Mailbox>,
max_per_mailbox: usize,
}
impl MemoryStore {
pub fn new(notify: broadcast::Sender<Mailbox>, max_per_mailbox: usize) -> Self {
Self {
inner: Mutex::new(MemInner::default()),
notify,
max_per_mailbox,
}
}
fn lock(&self) -> StoreResult<std::sync::MutexGuard<'_, MemInner>> {
self.inner
.lock()
.map_err(|_| StoreError::Backend("poisoned lock".into()))
}
}
#[async_trait]
impl ServerStore for MemoryStore {
async fn post(&self, mailbox: Mailbox, payload: Vec<u8>, 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<Vec<v2::StoredMessage>> {
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<bool> {
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<u8>,
password: &str,
ttl: Duration,
code_len: usize,
) -> StoreResult<String> {
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<Vec<u8>> {
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>,
mailbox_ttl: Duration,
max_per_mailbox: usize,
) -> StoreResult<Self> {
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) = <Mailbox>::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<u8>, 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<Vec<v2::StoredMessage>> {
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<Vec<u8>>, 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<bool> {
let mut c = self.conn.clone();
let r: Option<String> = 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<u8>,
password: &str,
ttl: Duration,
code_len: usize,
) -> StoreResult<String> {
let mut c = self.conn.clone();
loop {
let code = random_shortcode(code_len);
let ok: Option<String> = 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<Vec<u8>> {
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<Vec<u8>>, Option<String>) =
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<Mailbox>) {
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<_>>(),
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;
}
}
+224
View File
@@ -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; }
+1
View File
@@ -0,0 +1 @@
max_width = 120
+8
View File
@@ -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
Executable
+172
View File
@@ -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 <description> <needle> <command...>: 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"