bg check ajustments

This commit is contained in:
yves committed 2026-11-21 11:02:02 +01:00
1 parent 7eed94d82c
commit 923f4e397e
14 files changed
+649 -46

No files matched your search

+48
View File
@@ -336,6 +336,49 @@ let mut events = client.subscribe(); // Strea
lance `flutter test test/meow_ffi_test.dart` (deux identités, un vrai serveur, tout passe lance `flutter test test/meow_ffi_test.dart` (deux identités, un vrai serveur, tout passe
par les événements). par les événements).
### 5.5 Invitation en présentiel (application)
* Transports : `lan_connect` (Wi-Fi local, partout) et `ble_connect` (Bluetooth LE, mobile),
derrière l'interface `PeerTransport` de `peer_secure`.
* Canal : session `peer_secure`. Les deux côtés s'engagent sur leur clé éphémère avant de la
révéler. Ils dérivent un code SAS de 6 chiffres, que les deux personnes comparent : avec
l'engagement, un attaquant au milieu a une chance sur 10⁶. Les données sont chiffrées et
authentifiées (ChaCha20-Poly1305). Rien n'est écrit sur disque (`EphemeralTrustStore`).
* Sur ce canal passent l'offre, la réponse et la confirmation de l'invitation v2 (§3.3).
L'acquittement final part par les serveurs, mis en file si on est hors ligne.
L'initiateur peut écrire tout de suite.
* Le numéro de sécurité v2 (fiche du contact) reste une seconde vérification possible.
### 5.6 Veille en arrière-plan et notifications
Le travail de fond **relève et notifie, sans jamais déchiffrer**, comme dans la v1, mais sans
tampon local :
* **Fichier de veille** (`identity.watch`) : pour chaque mailbox de l'**espace principal**, le
serveur et la clé de mailbox qui signe les pulls, et rien d'autre. Pas de nom, pas de clé
de ratchet. Il est complété par des mailbox leurres jusqu'à un palier (8, 16, 32…) puis
mélangé, et réécrit quand les mailbox changent. Il est chiffré par une **clé de l'appareil** :
sous Android, une clé aléatoire enveloppée par une clé AES du Keystore (plugin local
`bastet_keystore`) ; ailleurs, une clé en mémoire, puisque la veille ne tourne qu'avec
l'application ouverte. Les espaces cachés n'y figurent **jamais**.
* **`watch_check`** (Rust, sans mot de passe ni base) : un pull **sans ack**, avec
`MailboxAuth.after` = dernier id vu, d'où le long-poll seulement sur les messages *nouveaux*.
Les curseurs sont dans un petit fichier chiffré. La fonction renvoie le nombre de nouveaux
messages. Rien n'est stocké : les messages restent sur les serveurs jusqu'au traitement
normal par l'application ouverte (§3.6).
* **Qui vérifie** : l'application verrouillée mais lancée (long-poll, toutes plateformes) ;
sous Android, application fermée, WorkManager toutes les 15 min environ, ou un service de
premier plan avec long-poll (« notifications instantanées », notification permanente).
Quand l'identité est ouverte et l'application en arrière-plan, ses propres événements
déclenchent la notification.
* **Notification neutre** : « Nouveaux messages », sans expéditeur ni texte, et masquée sur
l'écran de verrouillage d'Android (`VISIBILITY_SECRET`).
* **Limites** : quelqu'un qui possède le fichier *et* la clé (appareil déverrouillé) peut faire
des pulls, et même acquitter (donc effacer) les messages en attente, sans pouvoir les lire.
Il voit aussi la date des vérifications.
* Serveur : `MailboxAuth.after` (champ 5, filtre de lecture non signé) ; ids croissants dans
le temps (mémoire : horodatés ; Redis : ids de stream, lecture par `XRANGE (id`, Redis ≥ 6.2).
--- ---
## 6. Stockage client (`meow-store`) ## 6. Stockage client (`meow-store`)
@@ -444,6 +487,11 @@ révèle la longueur des conversations.
d'invitation prennent `space: Option<mot de passe>`, et l'espace principal n'est alors jamais d'invitation prennent `space: Option<mot de passe>`, et l'espace principal n'est alors jamais
écrit. Les étapes suivantes demandent que cet espace soit déverrouillé. Un contact créé dans écrit. Les étapes suivantes demandent que cet espace soit déverrouillé. Un contact créé dans
l'espace principal puis caché laisse ses anciens blocs effacés puis recyclés. l'espace principal puis caché laisse ses anciens blocs effacés puis recyclés.
* Application : le mot de passe principal ouvre l'identité. « Ouvrir un espace » (liste des
conversations, réglages) essaie un autre mot de passe ; les contacts de l'espace restent
visibles jusqu'au verrouillage. Ces actions sont présentes pour tout le monde, et une réponse
neutre est donnée quand rien ne s'ouvre. La fiche contact permet de cacher ou de révéler un
contact. Le verrouillage, manuel ou automatique en arrière-plan, referme tout ce qui est ouvert.
* CLI : `-u/--unlock <mot de passe>` (répétable), `contact hide <nom> --space-password …`, * CLI : `-u/--unlock <mot de passe>` (répétable), `contact hide <nom> --space-password …`,
`contact reveal`, `identity password --new-password …`, `--space-password` sur les `contact reveal`, `identity password --new-password …`, `--space-password` sur les
commandes d'invitation. Un mot de passe qui n'ouvre rien est commandes d'invitation. Un mot de passe qui n'ouvre rien est
Generated
+2
View File
@@ -1396,7 +1396,9 @@ dependencies = [
"meow-proto", "meow-proto",
"meow-server", "meow-server",
"meow-store", "meow-store",
"postcard",
"reqwest", "reqwest",
"serde",
"thiserror", "thiserror",
"tokio", "tokio",
"tracing", "tracing",
+7 -4
View File
@@ -17,13 +17,16 @@ Pour reprendre le travail : lire ce fichier, prendre le premier lot ⬜ dont les
1. ~~**3.8** livraison au moins une fois~~ ✅ 1. ~~**3.8** livraison au moins une fois~~ ✅
2. ~~**4.5** brancher `meow-store` dans le client et la CLI~~ ✅ 2. ~~**4.5** brancher `meow-store` dans le client et la CLI~~ ✅
3. ~~5.5, 5.6, 5.9, 5.10~~ ✅ 3. ~~5.5, 5.6, 5.9, 5.10~~ ✅
4. ~~7.1 → 7.5~~ ✅, puis **7.5b** (présentiel), **7.6 → 7.8** (espaces cachés, Android en arrière-plan, retrait de la v1). 4. ~~7.1 → 7.7~~ ✅, puis **7.8** (retrait de la v1).
5. Le reste (phases 8–10) selon les priorités. 5. Le reste (phases 8–10) selon les priorités.
### Journal ### Journal
| Date | Lots | Notes | | Date | Lots | Notes |
|---|---|---| |---|---|---|
| 2026-11-21 | 7.7 | Proto : `MailboxAuth.after` ; ids horodatés dans le stockage mémoire. Rust : module `watch` (`enable_watch`, `disable_watch`, `watch_check`) ; FFI `watchCheck`. App : `lib/core/background.dart`, plugin local `packages/bastet_keystore` (Java, Android Keystore, pour éviter un second plugin Kotlin), `workmanager`, `flutter_foreground_task`, `flutter_local_notifications` **22** (la 23 exige le SDK 37, pas encore supporté par AGP 9.1), désugarisation activée. Choix validés : aucune notification pour les espaces cachés ; WorkManager par défaut, mode instantané en option. Linux : pas de `flutter_secure_storage` (`libsecret` absent), clé en mémoire. Avertissement KGP : `bluetooth_low_energy_android`, `workmanager_android`. |
| 2026-11-21 | 7.6 | `SessionNotifier.unlockSpace`, `lib/ui/spaces.dart` (dialogues « ouvrir un espace » et « cacher un contact »), actions dans la liste des conversations, les réglages et la fiche contact. Choix : le mot de passe principal reste nécessaire pour ouvrir l'identité, et les actions « espace » sont visibles pour tous (le déni porte sur l'existence des espaces de *cet* utilisateur, pas sur la fonction). Verrouillage automatique (`autoLockProvider`, `AppLifecycleListener` : mise en pause sur mobile, fenêtre masquée sur bureau, pas la simple perte de focus). **Corrigé avant qu'il n'existe** : verrouiller laissait une conversation ou un dialogue ouvert au-dessus de l'écran de déverrouillage, d'où la fermeture de toutes les routes. 10 tests Flutter, test d'intégration étendu. |
| 2026-11-21 | 7.5b | `peer_secure` corrigé (dépôt séparé) : **3 failles** ; (1) le SAS sans engagement permettait à un attaquant au milieu d'essayer des clés jusqu'à faire coïncider les codes (environ 10⁶ essais), d'où un engagement SHA-256 avant révélation ; (2) données applicatives en clair et non authentifiées, désormais ChaCha20-Poly1305 avec une clé par sens et des compteurs, types inconnus rejetés ; (3) identité et pairs stockés en clair, désormais `TrustStore` en mémoire par défaut. S'y ajoutent un `dispose()` qui bloquait (fermeture d'un contrôleur à abonnement unique jamais écouté) et des tests (4). App : `NearbyInvitation` (logique testée avec deux vraies identités et un vrai serveur), `NearbyScreen`, permissions Android (dont `INTERNET`, absente du manifeste principal depuis le 7.3, ce qui aurait cassé les versions de release). Avertissement Gradle : `bluetooth_low_energy_android` utilise encore le plugin Kotlin (KGP). |
| 2026-11-21 | 7.5 | Rust : `accept_invitation` (offre reçue par n'importe quel canal ; contact et réponse enregistrés **dans la même sauvegarde**, ce qui corrige une fenêtre où un plantage laissait un contact bloqué), `accept_published_invitation` s'appuie dessus ; FFI `acceptInvitation`. Flutter : feuille « Ajouter un contact », lien et mot de passe (12 caractères, environ 68 bits), QR code (`qr_flutter`) + copie et fichier `.bastet`, « Rejoindre » (`mobile_scanner` sur mobile, coller, fichier), option espace caché, fermeture auto quand le contact accepte. Format texte `bastet://invite/<base64url>` (offre de 278 octets avec un serveur). Test d'intégration : lien (Bob), QR (Carol), rejoindre (Dave). **`peer_secure` audité** : voir annexe B ; présentiel reporté au 7.5b. | | 2026-11-21 | 7.5 | Rust : `accept_invitation` (offre reçue par n'importe quel canal ; contact et réponse enregistrés **dans la même sauvegarde**, ce qui corrige une fenêtre où un plantage laissait un contact bloqué), `accept_published_invitation` s'appuie dessus ; FFI `acceptInvitation`. Flutter : feuille « Ajouter un contact », lien et mot de passe (12 caractères, environ 68 bits), QR code (`qr_flutter`) + copie et fichier `.bastet`, « Rejoindre » (`mobile_scanner` sur mobile, coller, fichier), option espace caché, fermeture auto quand le contact accepte. Format texte `bastet://invite/<base64url>` (offre de 278 octets avec un serveur). Test d'intégration : lien (Bob), QR (Carol), rejoindre (Dave). **`peer_secure` audité** : voir annexe B ; présentiel reporté au 7.5b. |
| 2026-11-21 | 7.4 | Identifiant d'application `im.bastet.bastet` (Android et Linux). Rust : `conversation_summary` (dernier message et non-lus, comptés à rebours par segments) et `Meow::conversations()` triées par activité. Flutter : flux d'événements unique par session, `conversationsProvider` (rafraîchi par les événements, avec anti-rebond) et `chatProvider` (famille par contact : segments, fusion du dernier segment, accusés appliqués sur place). Écrans de liste et de conversation, fiche contact, `file_picker` 13. Test d'intégration : Bob (identité FFI) accepte une invitation, écrit ; l'application affiche, répond depuis le champ de saisie ; Bob reçoit la réponse et l'accusé de lecture. Corrigés en route : le raccourci Entrée lisait un état périmé ; les SnackBars couvraient le champ de saisie sur bureau (largeur limitée sur grand écran). Formateur Dart à 120 colonnes. | | 2026-11-21 | 7.4 | Identifiant d'application `im.bastet.bastet` (Android et Linux). Rust : `conversation_summary` (dernier message et non-lus, comptés à rebours par segments) et `Meow::conversations()` triées par activité. Flutter : flux d'événements unique par session, `conversationsProvider` (rafraîchi par les événements, avec anti-rebond) et `chatProvider` (famille par contact : segments, fusion du dernier segment, accusés appliqués sur place). Écrans de liste et de conversation, fiche contact, `file_picker` 13. Test d'intégration : Bob (identité FFI) accepte une invitation, écrit ; l'application affiche, répond depuis le champ de saisie ; Bob reçoit la réponse et l'accusé de lecture. Corrigés en route : le raccourci Entrée lisait un état périmé ; les SnackBars couvraient le champ de saisie sur bureau (largeur limitée sur grand écran). Formateur Dart à 120 colonnes. |
| 2026-11-21 | 7.3 | Nouvelle application `../bastet` : Riverpod 3, session, thème sable conçu pour Material 3 (palette dérivée de Papyrus, contrastes vérifiés par test), écrans d'accueil, de déverrouillage, des conversations, des réglages et des serveurs, adaptatifs (bureau : panneau de marque et rail ; mobile : barre du bas). i18n en/fr (ARB). Sans `google_fonts` (fuite vers Google). Outil de captures `tool/screenshots_test.dart`. Test d'intégration réel sur Linux (création, serveur, verrouillage, mauvais mot de passe, déverrouillage). Corrigés en route : tailles de police perdues dans le thème (géométrie typographique absente), focus après une erreur de déverrouillage. Vérifié aussi sur l'émulateur Android. | | 2026-11-21 | 7.3 | Nouvelle application `../bastet` : Riverpod 3, session, thème sable conçu pour Material 3 (palette dérivée de Papyrus, contrastes vérifiés par test), écrans d'accueil, de déverrouillage, des conversations, des réglages et des serveurs, adaptatifs (bureau : panneau de marque et rail ; mobile : barre du bas). i18n en/fr (ARB). Sans `google_fonts` (fuite vers Google). Outil de captures `tool/screenshots_test.dart`. Test d'intégration réel sur Linux (création, serveur, verrouillage, mauvais mot de passe, déverrouillage). Corrigés en route : tailles de police perdues dans le thème (géométrie typographique absente), focus après une erreur de déverrouillage. Vérifié aussi sur l'émulateur Android. |
@@ -137,9 +140,9 @@ conversation est un widget maison, léger. On réutilise de la v1 :
| 7.3 | Squelette de l'application : Riverpod, session (welcome → unlock → home), **thème sable clair/sombre** (contrastes WCAG testés), navigation adaptative (rail / barre), écrans création d'identité, déverrouillage, conversations (état vide), réglages (apparence, accusés, mot de passe, verrouillage), serveurs ; i18n en/fr ; icônes v1 | Lancement Linux et Android, test d'intégration réel | ✅ | | 7.3 | Squelette de l'application : Riverpod, session (welcome → unlock → home), **thème sable clair/sombre** (contrastes WCAG testés), navigation adaptative (rail / barre), écrans création d'identité, déverrouillage, conversations (état vide), réglages (apparence, accusés, mot de passe, verrouillage), serveurs ; i18n en/fr ; icônes v1 | Lancement Linux et Android, test d'intégration réel | ✅ |
| 7.4 | Liste des conversations (dernier message, non-lus, statuts, invitations en attente, contacts cachés) + **écran de conversation maison** : liste inversée chargée segment par segment, bulles groupées, séparateurs de jours, statuts (✓, ✓✓, lu), fichiers (envoi en octets, enregistrement), Entrée pour envoyer, lu à l'ouverture, fiche contact (numéro de sécurité, suppression). Maître-détail sur grand écran | Échange réel testé de bout en bout (test d'intégration) | ✅ | | 7.4 | Liste des conversations (dernier message, non-lus, statuts, invitations en attente, contacts cachés) + **écran de conversation maison** : liste inversée chargée segment par segment, bulles groupées, séparateurs de jours, statuts (✓, ✓✓, lu), fichiers (envoi en octets, enregistrement), Entrée pour envoyer, lu à l'ouverture, fiche contact (numéro de sécurité, suppression). Maître-détail sur grand écran | Échange réel testé de bout en bout (test d'intégration) | ✅ |
| 7.5 | Invitations dans l'UI : **lien serveur + mot de passe** (généré), **QR code / texte / fichier en un seul transfert** (`accept_invitation` : seule l'offre circule hors réseau, la réponse passe par les serveurs), écran « J'ai reçu une invitation » (coller, scanner sur mobile, ouvrir un fichier, y compris un fichier de la CLI ; aperçu avant acceptation), option « garder dans un espace caché » | Test d'intégration réel des trois parcours | ✅ | | 7.5 | Invitations dans l'UI : **lien serveur + mot de passe** (généré), **QR code / texte / fichier en un seul transfert** (`accept_invitation` : seule l'offre circule hors réseau, la réponse passe par les serveurs), écran « J'ai reçu une invitation » (coller, scanner sur mobile, ouvrir un fichier, y compris un fichier de la CLI ; aperçu avant acceptation), option « garder dans un espace caché » | Test d'intégration réel des trois parcours | ✅ |
| 7.5b | **En présentiel (BLE / Wi-Fi local)** : réutiliser seulement les *transports* de `ble_connect` / `lan_connect` ; les 3 messages de l'invitation v2 passent sur le canal, puis les deux personnes comparent le **numéro de sécurité v2** (qui couvre la transcription signée, donc les octets réellement échangés). Pas de la couche session de `peer_secure` (voir annexe B) | e2e manuel entre deux appareils | ⬜ (décision à confirmer) | | 7.5b | **En présentiel (Wi-Fi local / Bluetooth)** : `peer_secure` corrigé (engagement avant révélation des clés, données chiffrées et authentifiées, stockage de confiance en mémoire par défaut), code SAS de 6 chiffres à comparer, puis les 3 messages de l'invitation v2 sur le canal chiffré ; l'acquittement final passe par les serveurs. Bluetooth sur mobile, Wi-Fi local partout | Tests `peer_secure` (4), test du protocole (2), test d'intégration UI | ✅ (essai réel entre deux appareils à faire) |
| 7.6 | Espaces cachés dans l'UI (cacher/révéler, inviter dans un espace caché, aucune trace visuelle sans déverrouillage), réglages (accusés, mot de passe) | | ⬜ | | 7.6 | Espaces cachés dans l'UI : « Ouvrir un espace » (conversations, réglages ; réponse neutre si rien ne s'ouvre), cacher et révéler un contact depuis sa fiche, inviter dans un espace caché (7.5) ; verrouillage automatique en arrière-plan (immédiat, 1 min, 5 min ou jamais) ; au verrouillage, fermeture de tout ce qui est ouvert au-dessus | Test d'intégration : cacher, verrouiller, absent, ouvrir, présent | ✅ |
| 7.7 | Android : synchronisation en arrière-plan (service ou WorkManager) et notifications **sans le texte des messages** | Notifications | ⬜ | | 7.7 | Veille en arrière-plan sans mot de passe (fichier de veille de l'espace principal, chiffré par une clé de l'appareil, avec leurres ; pull sans ack avec curseur `after`) ; WorkManager (15 min) et service instantané au choix ; veille dans l'application verrouillée ; notifications neutres | Test Rust, test d'intégration Linux (notification verrouillée, contact caché ignoré, message intact), test Android sur émulateur (Keystore, WorkManager, notification) | ✅ (service instantané non essayé sur un vrai appareil) |
| 7.8 | Retrait de `meowjsonlib`, `meowwrapper.dart` et `bastet_v1` | | ⬜ | | 7.8 | Retrait de `meowjsonlib`, `meowwrapper.dart` et `bastet_v1` | | ⬜ |
## Phase 8 — Fonctionnalités avancées ## Phase 8 — Fonctionnalités avancées
+2
View File
@@ -13,6 +13,8 @@ meow-store = { path = "../meow-store" }
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] } reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
tokio = { version = "1", features = ["fs", "time", "macros", "sync", "rt"] } tokio = { version = "1", features = ["fs", "time", "macros", "sync", "rt"] }
futures-util = "0.3" futures-util = "0.3"
serde = { version = "1", features = ["derive"] }
postcard = { version = "1", default-features = false, features = ["alloc"] }
thiserror = "2" thiserror = "2"
tracing = "0.1" tracing = "0.1"
+11
View File
@@ -20,6 +20,7 @@
pub mod background; pub mod background;
pub mod outbox; pub mod outbox;
pub mod transport; pub mod transport;
pub mod watch;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::path::Path; use std::path::Path;
@@ -43,6 +44,7 @@ pub use meow_core::server::ServerInfo;
pub use meow_proto::PROTOCOL_VERSION; pub use meow_proto::PROTOCOL_VERSION;
pub use meow_store::{Content, HistoryEntry, HistoryPage, PendingAck, Settings, Status}; pub use meow_store::{Content, HistoryEntry, HistoryPage, PendingAck, Settings, Status};
pub use outbox::{PendingSend, RetryPolicy}; pub use outbox::{PendingSend, RetryPolicy};
pub use watch::watch_check;
/// Maximum file size sent in a single message (chunking: roadmap 5.7). /// Maximum file size sent in a single message (chunking: roadmap 5.7).
pub const MAX_FILE_BYTES: usize = 4 * 1024 * 1024; pub const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
@@ -233,6 +235,8 @@ pub struct MeowClient {
/// Bumped at every save: the background task restarts its wait when the state /// Bumped at every save: the background task restarts its wait when the state
/// changed under it (new contact to poll, unlocked space, queued message). /// changed under it (new contact to poll, unlocked space, queued message).
changes: tokio::sync::watch::Sender<u64>, changes: tokio::sync::watch::Sender<u64>,
/// Background watch file (lot 7.7), when enabled.
watch: Option<watch::WatchConfig>,
} }
type Mailboxes = Vec<(SigningKeyPair, Vec<ServerInfo>)>; type Mailboxes = Vec<(SigningKeyPair, Vec<ServerInfo>)>;
@@ -270,6 +274,7 @@ impl MeowClient {
pending_events: Vec::new(), pending_events: Vec::new(),
events: tokio::sync::broadcast::channel(EVENT_BUFFER).0, events: tokio::sync::broadcast::channel(EVENT_BUFFER).0,
changes: tokio::sync::watch::channel(0).0, changes: tokio::sync::watch::channel(0).0,
watch: None,
}) })
} }
@@ -288,7 +293,13 @@ impl MeowClient {
let batch = std::mem::take(&mut sp.batch); let batch = std::mem::take(&mut sp.batch);
lock(&self.store)?.save(sp.id, &sp.state, batch)?; lock(&self.store)?.save(sp.id, &sp.state, batch)?;
sp.dirty = false; sp.dirty = false;
let main = sp.id == SpaceId::MAIN;
self.changes.send_modify(|v| *v = v.wrapping_add(1)); self.changes.send_modify(|v| *v = v.wrapping_add(1));
if main {
if let Err(e) = self.refresh_watch() {
tracing::warn!("cannot update the watch file: {e}");
}
}
Ok(()) Ok(())
} }
+5
View File
@@ -56,6 +56,11 @@ impl RetryPolicy {
} }
} }
/// Uniform random index in `0..n` (n > 0); the tiny modulo bias does not matter here.
pub(crate) fn rand_below(n: usize) -> usize {
(u64::from_le_bytes(meow_crypto::random_bytes::<8>()) % n as u64) as usize
}
/// A queued deposit, as shown to the user. /// A queued deposit, as shown to the user.
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingSend { pub struct PendingSend {
+279
View File
@@ -0,0 +1,279 @@
//! Background watching (roadmap lot 7.7).
//!
//! While the identity is open, the client keeps a small **watch file** up to date: for
//! each mailbox of the *main* space, the server to pull it from and the mailbox key that
//! signs pulls. Nothing else: no names, no ratchet keys, no history. Hidden spaces are
//! never included (their activity would betray them).
//!
//! A background task (Android WorkManager / foreground service, or the app while locked)
//! calls [`watch_check`] **without the password**: it *peeks* (pull without
//! acknowledgement, only messages after the last one seen) and returns how many new
//! messages are waiting. Nothing is stored locally: the messages stay on the servers
//! until the app, opened and unlocked, processes and acknowledges them normally.
//!
//! The file is encrypted with a device key held by the platform (Android Keystore,
//! desktop keyring), not by the password; it is padded with decoy mailboxes to a fixed
//! bucket so that it does not reveal the number of contacts.
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::time::Duration;
use futures_util::future::join_all;
use meow_core::rpc;
use meow_core::server::ServerInfo;
use meow_crypto::aead::{self, Key};
use meow_crypto::{SignPublic, SigningKeyPair};
use meow_proto::v2::{self, request::Body as Req, response::Body as Resp};
use serde::{Deserialize, Serialize};
use crate::{now, transport::Transport, Error, MeowClient, Result};
const PROFILE_AAD: &[u8] = b"meow/v2/watch-profile";
const CURSOR_AAD: &[u8] = b"meow/v2/watch-cursors";
#[derive(Serialize, Deserialize)]
struct WatchMailbox {
server: ServerInfo,
key: SigningKeyPair,
}
#[derive(Serialize, Deserialize, Default)]
struct WatchProfile {
mailboxes: Vec<WatchMailbox>,
}
/// Last message id seen per (server, mailbox).
#[derive(Serialize, Deserialize, Default)]
struct Cursors(BTreeMap<String, Vec<u8>>);
fn cursor_key(server: &SignPublic, mailbox: &SignPublic) -> String {
format!("{}/{}", server.to_hex(), mailbox.to_hex())
}
/// Smallest bucket (8, 16, 32…) holding `n` entries.
fn bucket(n: usize) -> usize {
n.max(1).next_power_of_two().max(8)
}
fn seal<T: Serialize>(key: &Key, aad: &[u8], v: &T) -> Result<Vec<u8>> {
let plain = postcard::to_allocvec(v).map_err(|e| Error::Invalid(e.to_string()))?;
Ok(aead::encrypt(key, &plain, aad))
}
fn open<T: for<'de> Deserialize<'de>>(key: &Key, aad: &[u8], data: &[u8]) -> Result<T> {
let plain = aead::decrypt(key, data, aad)?;
postcard::from_bytes(&plain).map_err(|e| Error::Invalid(format!("watch file: {e}")))
}
/// Atomic write, owner-only permissions.
fn write_private(path: &Path, data: &[u8]) -> Result<()> {
let tmp = path.with_extension("tmp");
{
use std::io::Write;
let mut o = std::fs::OpenOptions::new();
o.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
o.mode(0o600);
}
let mut f = o.open(&tmp)?;
f.write_all(data)?;
f.sync_all()?;
}
std::fs::rename(&tmp, path)?;
Ok(())
}
fn cursor_path(watch: &Path) -> PathBuf {
let mut p = watch.as_os_str().to_owned();
p.push(".cursors");
PathBuf::from(p)
}
/// Where the watch file goes and its device key.
pub(crate) struct WatchConfig {
path: PathBuf,
key: Key,
/// Hash of the real mailboxes last written (decoys excluded), to skip rewrites.
written: Option<[u8; 32]>,
}
impl MeowClient {
/// Keep the watch file at `path` up to date, encrypted with `key` (32 bytes, held
/// by the platform's key store). Written now and whenever the main space's
/// mailboxes change.
pub fn enable_watch(&mut self, path: &Path, key: [u8; 32]) -> Result<()> {
self.watch = Some(WatchConfig {
path: path.to_path_buf(),
key: Key(key),
written: None,
});
self.refresh_watch()
}
/// Stop maintaining the watch file and delete it (and its cursors).
pub fn disable_watch(&mut self) -> Result<()> {
if let Some(w) = self.watch.take() {
for p in [w.path.clone(), cursor_path(&w.path)] {
if p.exists() {
std::fs::remove_file(p)?;
}
}
}
Ok(())
}
/// Rewrite the watch file if the main space's mailboxes changed.
pub(crate) fn refresh_watch(&mut self) -> Result<()> {
let Some(w) = self.watch.as_ref() else {
return Ok(());
};
// Main space only: hidden spaces must stay invisible.
let mut real: Vec<WatchMailbox> = Vec::new();
for (kp, servers) in self.space_mailboxes(0) {
for s in servers {
real.push(WatchMailbox {
server: s,
key: kp.clone(),
});
}
}
let fingerprint: Vec<u8> = real
.iter()
.flat_map(|m| {
[
m.server.sign_key.as_bytes().to_vec(),
m.key.public().as_bytes().to_vec(),
]
.concat()
})
.collect();
let hash = meow_crypto::sha256(&[&fingerprint]);
if w.written == Some(hash) && w.path.exists() {
return Ok(());
}
// Decoys on the user's servers, up to the bucket size, then shuffled.
let servers = self.main().servers.clone();
let target = bucket(real.len());
let mut all = real;
if !servers.is_empty() {
while all.len() < target {
let s = servers[crate::outbox::rand_below(servers.len())].clone();
all.push(WatchMailbox {
server: s,
key: SigningKeyPair::generate(),
});
}
}
for i in (1..all.len()).rev() {
all.swap(i, crate::outbox::rand_below(i + 1));
}
let data = seal(&w.key, PROFILE_AAD, &WatchProfile { mailboxes: all })?;
write_private(&w.path, &data)?;
if let Some(w) = self.watch.as_mut() {
w.written = Some(hash);
}
Ok(())
}
}
/// Peek for new messages with the watch file, without the password. Waits up to
/// `wait` (long-poll) when nothing is new. Returns the number of new messages (a
/// message deposited on two servers counts twice). Never acknowledges anything.
pub async fn watch_check(path: &Path, key: [u8; 32], wait: Duration) -> Result<usize> {
let key = Key(key);
let profile: WatchProfile = open(&key, PROFILE_AAD, &std::fs::read(path)?)?;
let cpath = cursor_path(path);
let mut cursors: Cursors = match std::fs::read(&cpath) {
Ok(d) => open(&key, CURSOR_AAD, &d).unwrap_or_default(),
Err(_) => Cursors::default(),
};
// One pull per server.
let mut by_server: BTreeMap<SignPublic, (ServerInfo, Vec<SigningKeyPair>)> = BTreeMap::new();
for m in profile.mailboxes {
by_server
.entry(m.server.sign_key)
.or_insert_with(|| (m.server.clone(), Vec::new()))
.1
.push(m.key);
}
let transport = Transport::new()?;
let wait_s = wait.as_secs().min(u32::MAX as u64) as u32;
let calls = by_server.values().map(|(server, keys)| {
let rid = meow_crypto::random_bytes::<16>().to_vec();
let ts = now();
let auths = keys
.iter()
.map(|kp| {
let mut a = rpc::mailbox_auth(kp, server, &rid, Vec::new(), ts);
a.after = cursors
.0
.get(&cursor_key(&server.sign_key, &kp.public()))
.cloned()
.unwrap_or_default();
a
})
.collect();
let req = v2::Request {
request_id: rid,
timestamp: ts,
body: Some(Req::Pull(v2::Pull {
auths,
wait_seconds: wait_s,
})),
};
transport.call_request(server, req, wait)
});
let results = join_all(calls).await;
let mut new = 0;
let mut ok = 0;
let mut last_err = None;
let mut latest: HashMap<String, Vec<u8>> = HashMap::new();
for ((server, _), r) in by_server.values().zip(results) {
match r {
Ok(Resp::PullResult(p)) => {
ok += 1;
new += p.messages.len();
// Oldest first: the last one per mailbox is the new cursor.
for m in p.messages {
if let Ok(mb) = SignPublic::from_slice(&m.mailbox) {
latest.insert(cursor_key(&server.sign_key, &mb), m.id);
}
}
}
Ok(_) => {}
Err(e) => {
tracing::debug!("watch: {} unreachable: {e}", server.url);
last_err = Some(e);
}
}
}
if ok == 0 {
if let Some(e) = last_err {
return Err(e);
}
}
if !latest.is_empty() {
cursors.0.extend(latest);
write_private(&cpath, &seal(&key, CURSOR_AAD, &cursors)?)?;
}
Ok(new)
}
#[cfg(test)]
mod tests {
use super::bucket;
#[test]
fn buckets() {
assert_eq!(bucket(0), 8);
assert_eq!(bucket(3), 8);
assert_eq!(bucket(8), 8);
assert_eq!(bucket(9), 16);
assert_eq!(bucket(40), 64);
}
}
+69 -1
View File
@@ -226,7 +226,7 @@ impl meow_server::store::ServerStore for FlakyStore {
} }
async fn fetch( async fn fetch(
&self, &self,
mbs: &[[u8; 32]], mbs: &[([u8; 32], Vec<u8>)],
limit: usize, limit: usize,
) -> meow_server::store::StoreResult<Vec<meow_proto::v2::StoredMessage>> { ) -> meow_server::store::StoreResult<Vec<meow_proto::v2::StoredMessage>> {
self.inner.fetch(mbs, limit).await self.inner.fetch(mbs, limit).await
@@ -849,3 +849,71 @@ async fn one_shot_invitation_completes_through_servers() {
); );
let _ = std::fs::remove_dir_all(&dir); let _ = std::fs::remove_dir_all(&dir);
} }
// ───────────── background watch (roadmap lot 7.7) ─────────────
#[tokio::test(flavor = "multi_thread")]
async fn background_watch_peeks_without_consuming() {
let url = spawn_server().await;
let servers = vec![url.clone()];
let dir = tmpdir();
let mut alice = client(&dir, "alice", &servers).await;
let mut bob = client(&dir, "bob", &servers).await;
let mut carol = client(&dir, "carol", &servers).await;
connect(&mut alice, &mut bob, "bob").await;
connect(&mut alice, &mut carol, "carol").await;
alice.hide_contact("carol", "carol-secret").await.unwrap();
bob.sync(Duration::ZERO).await.unwrap();
carol.sync(Duration::ZERO).await.unwrap();
alice.sync(Duration::ZERO).await.unwrap();
let path = dir.join("alice.watch");
let key = [7u8; 32];
alice.enable_watch(&path, key).unwrap();
// Encrypted, and padded: neither the servers nor the number of contacts show.
let raw = std::fs::read(&path).unwrap();
assert!(!raw.windows(9).any(|w| w == b"127.0.0.1"));
assert!(
meow_client::watch_check(&path, [8u8; 32], Duration::ZERO)
.await
.is_err(),
"wrong key"
);
// Baseline (whatever was pending), then nothing new.
meow_client::watch_check(&path, key, Duration::ZERO).await.unwrap();
assert_eq!(meow_client::watch_check(&path, key, Duration::ZERO).await.unwrap(), 0);
// A new message is counted once, and not consumed.
bob.send_text("alice", "ping").await.unwrap();
assert_eq!(meow_client::watch_check(&path, key, Duration::ZERO).await.unwrap(), 1);
assert_eq!(meow_client::watch_check(&path, key, Duration::ZERO).await.unwrap(), 0);
// Hidden contacts are never watched.
carol.send_text("alice", "from the hidden side").await.unwrap();
assert_eq!(meow_client::watch_check(&path, key, Duration::ZERO).await.unwrap(), 0);
// The app still gets everything (nothing was acknowledged by the watcher).
let got = texts(&alice.sync(Duration::ZERO).await.unwrap());
assert!(got.contains(&"ping".to_string()) && got.contains(&"from the hidden side".to_string()));
// Long-poll: wakes up as soon as something arrives.
let p = path.clone();
let waiter = tokio::spawn(async move {
let start = std::time::Instant::now();
(
meow_client::watch_check(&p, key, Duration::from_secs(20))
.await
.unwrap(),
start.elapsed(),
)
});
tokio::time::sleep(Duration::from_millis(500)).await;
bob.send_text("alice", "wake").await.unwrap();
let (n, elapsed) = waiter.await.unwrap();
assert_eq!(n, 1);
assert!(elapsed < Duration::from_secs(10), "{elapsed:?}");
alice.disable_watch().unwrap();
assert!(!path.exists());
let _ = std::fs::remove_dir_all(&dir);
}
+2
View File
@@ -132,6 +132,8 @@ pub fn mailbox_auth(
timestamp: now, timestamp: now,
signature, signature,
acks, acks,
// A read filter set by watchers (`after`); not part of the signature.
after: Vec::new(),
} }
} }
+32
View File
@@ -51,6 +51,24 @@ pub fn core_version() -> String {
) )
} }
fn key32(key: &[u8]) -> Result<[u8; 32]> {
key.try_into().map_err(|_| anyhow!("the watch key must be 32 bytes"))
}
/// Background check (lot 7.7), **without the password**: peek with the watch file for
/// messages that arrived since the last check, waiting up to `wait_seconds`. Returns
/// how many are new. Nothing is acknowledged nor stored: the app gets the messages
/// when it is opened.
pub async fn watch_check(path: String, key: Vec<u8>, wait_seconds: u32) -> Result<u32> {
let key = key32(&key)?;
run(async move {
let n =
meow_client::watch_check(path.as_ref(), key, std::time::Duration::from_secs(wait_seconds as u64)).await?;
Ok(n as u32)
})
.await
}
/// Called once by the generated Dart `RustLib.init()`. /// Called once by the generated Dart `RustLib.init()`.
#[frb(init)] #[frb(init)]
pub fn init_app() { pub fn init_app() {
@@ -412,6 +430,20 @@ impl Meow {
}) })
} }
// ── background watch ──
/// Keep the watch file at `path` up to date (main space only), encrypted with
/// `key` (32 bytes from the platform key store).
pub async fn enable_watch(&self, path: String, key: Vec<u8>) -> Result<()> {
let key = key32(&key)?;
with_client!(self, |c| Ok(c.enable_watch(path.as_ref(), key)?))
}
/// Stop maintaining the watch file and delete it.
pub async fn disable_watch(&self) -> Result<()> {
with_client!(self, |c| Ok(c.disable_watch()?))
}
// ── hidden spaces ── // ── hidden spaces ──
/// Try a password on the hidden spaces; `true` if one opened (its contacts appear). /// Try a password on the hidden spaces; `true` if one opened (its contacts appear).
+151 -24
View File
@@ -40,7 +40,7 @@ flutter_rust_bridge::frb_generated_boilerplate!(
default_rust_auto_opaque = RustAutoOpaqueMoi, default_rust_auto_opaque = RustAutoOpaqueMoi,
); );
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.13.0"; pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.13.0";
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -1405833860; pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 1969878811;
// Section: executor // Section: executor
@@ -580,6 +580,97 @@ fn wire__crate__api__meow__Meow_create_invitation_impl(
}, },
) )
} }
fn wire__crate__api__meow__Meow_disable_watch_impl(
port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
rust_vec_len_: i32,
data_len_: i32,
) {
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
flutter_rust_bridge::for_generated::TaskInfo {
debug_name: "Meow_disable_watch",
port: Some(port_),
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
},
move || {
let message = unsafe {
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(ptr_, rust_vec_len_, data_len_)
};
let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message);
let api_that = <RustOpaqueMoi<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<Meow>>>::sse_decode(
&mut deserializer,
);
deserializer.end();
move |context| async move {
transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>(
(move || async move {
let mut api_that_guard = None;
let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![
flutter_rust_bridge::for_generated::LockableOrderInfo::new(&api_that, 0, false),
]);
for i in decode_indices_ {
match i {
0 => api_that_guard = Some(api_that.lockable_decode_async_ref().await),
_ => unreachable!(),
}
}
let api_that_guard = api_that_guard.unwrap();
let output_ok = crate::api::meow::Meow::disable_watch(&*api_that_guard).await?;
std::result::Result::Ok(output_ok)
})()
.await,
)
}
},
)
}
fn wire__crate__api__meow__Meow_enable_watch_impl(
port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
rust_vec_len_: i32,
data_len_: i32,
) {
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
flutter_rust_bridge::for_generated::TaskInfo {
debug_name: "Meow_enable_watch",
port: Some(port_),
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
},
move || {
let message = unsafe {
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(ptr_, rust_vec_len_, data_len_)
};
let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message);
let api_that = <RustOpaqueMoi<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<Meow>>>::sse_decode(
&mut deserializer,
);
let api_path = <String>::sse_decode(&mut deserializer);
let api_key = <Vec<u8>>::sse_decode(&mut deserializer);
deserializer.end();
move |context| async move {
transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>(
(move || async move {
let mut api_that_guard = None;
let decode_indices_ = flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![
flutter_rust_bridge::for_generated::LockableOrderInfo::new(&api_that, 0, false),
]);
for i in decode_indices_ {
match i {
0 => api_that_guard = Some(api_that.lockable_decode_async_ref().await),
_ => unreachable!(),
}
}
let api_that_guard = api_that_guard.unwrap();
let output_ok =
crate::api::meow::Meow::enable_watch(&*api_that_guard, api_path, api_key).await?;
std::result::Result::Ok(output_ok)
})()
.await,
)
}
},
)
}
fn wire__crate__api__meow__Meow_events_impl( fn wire__crate__api__meow__Meow_events_impl(
port_: flutter_rust_bridge::for_generated::MessagePort, port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
@@ -1588,6 +1679,39 @@ fn wire__crate__api__meow__init_app_impl(
}, },
) )
} }
fn wire__crate__api__meow__watch_check_impl(
port_: flutter_rust_bridge::for_generated::MessagePort,
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
rust_vec_len_: i32,
data_len_: i32,
) {
FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::<flutter_rust_bridge::for_generated::SseCodec, _, _, _>(
flutter_rust_bridge::for_generated::TaskInfo {
debug_name: "watch_check",
port: Some(port_),
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
},
move || {
let message = unsafe {
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(ptr_, rust_vec_len_, data_len_)
};
let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message);
let api_path = <String>::sse_decode(&mut deserializer);
let api_key = <Vec<u8>>::sse_decode(&mut deserializer);
let api_wait_seconds = <u32>::sse_decode(&mut deserializer);
deserializer.end();
move |context| async move {
transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>(
(move || async move {
let output_ok = crate::api::meow::watch_check(api_path, api_key, api_wait_seconds).await?;
std::result::Result::Ok(output_ok)
})()
.await,
)
}
},
)
}
// Section: related_funcs // Section: related_funcs
@@ -2096,28 +2220,31 @@ fn pde_ffi_dispatcher_primary_impl(
9 => wire__crate__api__meow__Meow_conversations_impl(port, ptr, rust_vec_len, data_len), 9 => wire__crate__api__meow__Meow_conversations_impl(port, ptr, rust_vec_len, data_len),
10 => wire__crate__api__meow__Meow_create_impl(port, ptr, rust_vec_len, data_len), 10 => wire__crate__api__meow__Meow_create_impl(port, ptr, rust_vec_len, data_len),
11 => wire__crate__api__meow__Meow_create_invitation_impl(port, ptr, rust_vec_len, data_len), 11 => wire__crate__api__meow__Meow_create_invitation_impl(port, ptr, rust_vec_len, data_len),
12 => wire__crate__api__meow__Meow_events_impl(port, ptr, rust_vec_len, data_len), 12 => wire__crate__api__meow__Meow_disable_watch_impl(port, ptr, rust_vec_len, data_len),
13 => wire__crate__api__meow__Meow_file_impl(port, ptr, rust_vec_len, data_len), 13 => wire__crate__api__meow__Meow_enable_watch_impl(port, ptr, rust_vec_len, data_len),
14 => wire__crate__api__meow__Meow_finalize_invitation_impl(port, ptr, rust_vec_len, data_len), 14 => wire__crate__api__meow__Meow_events_impl(port, ptr, rust_vec_len, data_len),
15 => wire__crate__api__meow__Meow_flush_outbox_impl(port, ptr, rust_vec_len, data_len), 15 => wire__crate__api__meow__Meow_file_impl(port, ptr, rust_vec_len, data_len),
16 => wire__crate__api__meow__Meow_hide_contact_impl(port, ptr, rust_vec_len, data_len), 16 => wire__crate__api__meow__Meow_finalize_invitation_impl(port, ptr, rust_vec_len, data_len),
17 => wire__crate__api__meow__Meow_history_impl(port, ptr, rust_vec_len, data_len), 17 => wire__crate__api__meow__Meow_flush_outbox_impl(port, ptr, rust_vec_len, data_len),
18 => wire__crate__api__meow__Meow_inspect_invitation_impl(port, ptr, rust_vec_len, data_len), 18 => wire__crate__api__meow__Meow_hide_contact_impl(port, ptr, rust_vec_len, data_len),
19 => wire__crate__api__meow__Meow_mark_read_impl(port, ptr, rust_vec_len, data_len), 19 => wire__crate__api__meow__Meow_history_impl(port, ptr, rust_vec_len, data_len),
20 => wire__crate__api__meow__Meow_nickname_impl(port, ptr, rust_vec_len, data_len), 20 => wire__crate__api__meow__Meow_inspect_invitation_impl(port, ptr, rust_vec_len, data_len),
21 => wire__crate__api__meow__Meow_open_impl(port, ptr, rust_vec_len, data_len), 21 => wire__crate__api__meow__Meow_mark_read_impl(port, ptr, rust_vec_len, data_len),
22 => wire__crate__api__meow__Meow_pending_sends_impl(port, ptr, rust_vec_len, data_len), 22 => wire__crate__api__meow__Meow_nickname_impl(port, ptr, rust_vec_len, data_len),
23 => wire__crate__api__meow__Meow_publish_invitation_impl(port, ptr, rust_vec_len, data_len), 23 => wire__crate__api__meow__Meow_open_impl(port, ptr, rust_vec_len, data_len),
24 => wire__crate__api__meow__Meow_remove_contact_impl(port, ptr, rust_vec_len, data_len), 24 => wire__crate__api__meow__Meow_pending_sends_impl(port, ptr, rust_vec_len, data_len),
25 => wire__crate__api__meow__Meow_remove_server_impl(port, ptr, rust_vec_len, data_len), 25 => wire__crate__api__meow__Meow_publish_invitation_impl(port, ptr, rust_vec_len, data_len),
26 => wire__crate__api__meow__Meow_reveal_contact_impl(port, ptr, rust_vec_len, data_len), 26 => wire__crate__api__meow__Meow_remove_contact_impl(port, ptr, rust_vec_len, data_len),
27 => wire__crate__api__meow__Meow_send_file_impl(port, ptr, rust_vec_len, data_len), 27 => wire__crate__api__meow__Meow_remove_server_impl(port, ptr, rust_vec_len, data_len),
28 => wire__crate__api__meow__Meow_send_text_impl(port, ptr, rust_vec_len, data_len), 28 => wire__crate__api__meow__Meow_reveal_contact_impl(port, ptr, rust_vec_len, data_len),
29 => wire__crate__api__meow__Meow_servers_impl(port, ptr, rust_vec_len, data_len), 29 => wire__crate__api__meow__Meow_send_file_impl(port, ptr, rust_vec_len, data_len),
30 => wire__crate__api__meow__Meow_set_settings_impl(port, ptr, rust_vec_len, data_len), 30 => wire__crate__api__meow__Meow_send_text_impl(port, ptr, rust_vec_len, data_len),
31 => wire__crate__api__meow__Meow_settings_impl(port, ptr, rust_vec_len, data_len), 31 => wire__crate__api__meow__Meow_servers_impl(port, ptr, rust_vec_len, data_len),
32 => wire__crate__api__meow__Meow_unlock_impl(port, ptr, rust_vec_len, data_len), 32 => wire__crate__api__meow__Meow_set_settings_impl(port, ptr, rust_vec_len, data_len),
34 => wire__crate__api__meow__init_app_impl(port, ptr, rust_vec_len, data_len), 33 => wire__crate__api__meow__Meow_settings_impl(port, ptr, rust_vec_len, data_len),
34 => wire__crate__api__meow__Meow_unlock_impl(port, ptr, rust_vec_len, data_len),
36 => wire__crate__api__meow__init_app_impl(port, ptr, rust_vec_len, data_len),
37 => wire__crate__api__meow__watch_check_impl(port, ptr, rust_vec_len, data_len),
_ => unreachable!(), _ => unreachable!(),
} }
} }
@@ -2130,7 +2257,7 @@ fn pde_ffi_dispatcher_sync_impl(
) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse {
// Codec=Pde (Serialization + dispatch), see doc to use other codecs // Codec=Pde (Serialization + dispatch), see doc to use other codecs
match func_id { match func_id {
33 => wire__crate__api__meow__core_version_impl(ptr, rust_vec_len, data_len), 35 => wire__crate__api__meow__core_version_impl(ptr, rust_vec_len, data_len),
_ => unreachable!(), _ => unreachable!(),
} }
} }
+8 -3
View File
@@ -205,13 +205,18 @@ async fn pull(st: &AppState, request_id: &[u8], p: v2::Pull, now: u64) -> HResul
let sign = st.keys.sign.public(); let sign = st.keys.sign.public();
let mut mailboxes = Vec::with_capacity(p.auths.len()); let mut mailboxes = Vec::with_capacity(p.auths.len());
for a in &p.auths { for a in &p.auths {
if a.acks.len() > st.limits.max_acks || a.acks.iter().any(|id| id.len() > 64) { if a.acks.len() > st.limits.max_acks || a.acks.iter().any(|id| id.len() > 64) || a.after.len() > 64 {
return Err((Code::BadRequest, "bad acks")); return Err((Code::BadRequest, "bad acks"));
} }
let mb = rpc::verify_mailbox_auth(&sign, request_id, a, now) let mb = rpc::verify_mailbox_auth(&sign, request_id, a, now)
.map_err(|_| (Code::Unauthorized, "bad mailbox auth"))?; .map_err(|_| (Code::Unauthorized, "bad mailbox auth"))?;
mailboxes.push(mb.0); mailboxes.push(mb.0);
} }
let cursors: Vec<(Mailbox, Vec<u8>)> = mailboxes
.iter()
.zip(&p.auths)
.map(|(m, a)| (*m, a.after.clone()))
.collect();
// Acknowledged messages were persisted by the client: delete them first. // Acknowledged messages were persisted by the client: delete them first.
for (mb, a) in mailboxes.iter().zip(&p.auths) { for (mb, a) in mailboxes.iter().zip(&p.auths) {
if !a.acks.is_empty() { if !a.acks.is_empty() {
@@ -221,7 +226,7 @@ async fn pull(st: &AppState, request_id: &[u8], p: v2::Pull, now: u64) -> HResul
// Subscribe before reading, so a deposit landing in between is not missed. // Subscribe before reading, so a deposit landing in between is not missed.
let mut rx = st.notify.subscribe(); let mut rx = st.notify.subscribe();
let limit = st.limits.max_pull_messages; let limit = st.limits.max_pull_messages;
let mut messages = st.store.fetch(&mailboxes, limit + 1).await.map_err(store_err)?; let mut messages = st.store.fetch(&cursors, limit + 1).await.map_err(store_err)?;
let wait = Duration::from_secs(p.wait_seconds as u64).min(st.limits.max_wait); let wait = Duration::from_secs(p.wait_seconds as u64).min(st.limits.max_wait);
if messages.is_empty() && !wait.is_zero() { if messages.is_empty() && !wait.is_zero() {
let wanted: HashSet<Mailbox> = mailboxes.iter().copied().collect(); let wanted: HashSet<Mailbox> = mailboxes.iter().copied().collect();
@@ -236,7 +241,7 @@ async fn pull(st: &AppState, request_id: &[u8], p: v2::Pull, now: u64) -> HResul
} }
}) })
.await; .await;
messages = st.store.fetch(&mailboxes, limit + 1).await.map_err(store_err)?; messages = st.store.fetch(&cursors, limit + 1).await.map_err(store_err)?;
} }
// Honour the count and size budgets; always return at least one message. // Honour the count and size budgets; always return at least one message.
let mut more = messages.len() > limit; let mut more = messages.len() > limit;
+29 -14
View File
@@ -44,8 +44,10 @@ pub trait ServerStore: Send + Sync {
/// Append a payload to a mailbox (under a fresh id) and notify waiters. /// Append a payload to a mailbox (under a fresh id) and notify waiters.
async fn post(&self, mailbox: Mailbox, payload: Vec<u8>, now: u64) -> StoreResult<()>; async fn post(&self, mailbox: Mailbox, payload: Vec<u8>, now: u64) -> StoreResult<()>;
/// Read, oldest first and **without removing them**, at most `limit` messages of the /// Read, oldest first and **without removing them**, at most `limit` messages of the
/// given mailboxes. Messages stay until acknowledged with [`ServerStore::ack`]. /// given mailboxes, each with an optional cursor: only messages stored after the
async fn fetch(&self, mailboxes: &[Mailbox], limit: usize) -> StoreResult<Vec<v2::StoredMessage>>; /// message whose id it is (empty: from the start). Messages stay until acknowledged
/// with [`ServerStore::ack`]. Ids grow over time within a mailbox.
async fn fetch(&self, mailboxes: &[(Mailbox, Vec<u8>)], limit: usize) -> StoreResult<Vec<v2::StoredMessage>>;
/// Delete the given messages of a mailbox. Unknown ids are ignored (idempotent). /// Delete the given messages of a mailbox. Unknown ids are ignored (idempotent).
async fn ack(&self, mailbox: Mailbox, ids: &[Vec<u8>]) -> StoreResult<()>; async fn ack(&self, mailbox: Mailbox, ids: &[Vec<u8>]) -> StoreResult<()>;
/// Record a request id; returns `false` if it was already seen (replay). /// Record a request id; returns `false` if it was already seen (replay).
@@ -131,7 +133,11 @@ impl ServerStore for MemoryStore {
async fn post(&self, mailbox: Mailbox, payload: Vec<u8>, now: u64) -> StoreResult<()> { async fn post(&self, mailbox: Mailbox, payload: Vec<u8>, now: u64) -> StoreResult<()> {
{ {
let mut g = self.lock()?; let mut g = self.lock()?;
g.next_id += 1; // Time-based so that ids keep growing across restarts (watchers keep cursors).
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as u64);
g.next_id = (now_ms << 16).max(g.next_id + 1);
let id = g.next_id.to_be_bytes().to_vec(); let id = g.next_id.to_be_bytes().to_vec();
let q = g.mailboxes.entry(mailbox).or_default(); let q = g.mailboxes.entry(mailbox).or_default();
q.push_back(v2::StoredMessage { q.push_back(v2::StoredMessage {
@@ -148,12 +154,12 @@ impl ServerStore for MemoryStore {
Ok(()) Ok(())
} }
async fn fetch(&self, mailboxes: &[Mailbox], limit: usize) -> StoreResult<Vec<v2::StoredMessage>> { async fn fetch(&self, mailboxes: &[(Mailbox, Vec<u8>)], limit: usize) -> StoreResult<Vec<v2::StoredMessage>> {
let g = self.lock()?; let g = self.lock()?;
Ok(mailboxes Ok(mailboxes
.iter() .iter()
.filter_map(|m| g.mailboxes.get(m)) .filter_map(|(m, after)| g.mailboxes.get(m).map(|q| (q, after)))
.flatten() .flat_map(|(q, after)| q.iter().filter(move |msg| after.is_empty() || msg.id > *after))
.take(limit) .take(limit)
.cloned() .cloned()
.collect()) .collect())
@@ -322,18 +328,23 @@ impl ServerStore for RedisStore {
Ok(()) Ok(())
} }
async fn fetch(&self, mailboxes: &[Mailbox], limit: usize) -> StoreResult<Vec<v2::StoredMessage>> { async fn fetch(&self, mailboxes: &[(Mailbox, Vec<u8>)], limit: usize) -> StoreResult<Vec<v2::StoredMessage>> {
let mut out = Vec::new(); let mut out = Vec::new();
let mut c = self.conn.clone(); let mut c = self.conn.clone();
for mb in mailboxes { for (mb, after) in mailboxes {
let left = limit.saturating_sub(out.len()); let left = limit.saturating_sub(out.len());
if left == 0 { if left == 0 {
break; break;
} }
let key = mailbox_key(mb); let key = mailbox_key(mb);
// Exclusive start "(<id>" (Redis ≥ 6.2); an invalid cursor reads from the start.
let start = match std::str::from_utf8(after) {
Ok(a) if is_stream_id(a) => format!("({a}"),
_ => "-".to_string(),
};
let entries: Vec<(String, Vec<Vec<u8>>)> = redis::cmd("XRANGE") let entries: Vec<(String, Vec<Vec<u8>>)> = redis::cmd("XRANGE")
.arg(&key) .arg(&key)
.arg("-") .arg(start)
.arg("+") .arg("+")
.arg("COUNT") .arg("COUNT")
.arg(left) .arg(left)
@@ -484,13 +495,17 @@ mod tests {
store.post(mb, b"three".to_vec(), 3).await.unwrap(); store.post(mb, b"three".to_vec(), 3).await.unwrap();
assert_eq!(rx.recv().await.unwrap(), mb); assert_eq!(rx.recv().await.unwrap(), mb);
let payloads = |v: &[v2::StoredMessage]| v.iter().map(|m| m.payload.clone()).collect::<Vec<_>>(); let payloads = |v: &[v2::StoredMessage]| v.iter().map(|m| m.payload.clone()).collect::<Vec<_>>();
let got = store.fetch(&[mb], 10).await.unwrap(); let got = store.fetch(&[(mb, vec![])], 10).await.unwrap();
assert_eq!( assert_eq!(
payloads(&got), payloads(&got),
vec![b"one".to_vec(), b"two".to_vec(), b"three".to_vec()] vec![b"one".to_vec(), b"two".to_vec(), b"three".to_vec()]
); );
// A cursor only returns what came after it.
let after_first = store.fetch(&[(mb, got[0].id.clone())], 10).await.unwrap();
assert_eq!(payloads(&after_first), vec![b"two".to_vec(), b"three".to_vec()]);
assert!(store.fetch(&[(mb, got[2].id.clone())], 10).await.unwrap().is_empty());
// Not acknowledged: delivered again. The limit is honoured. // Not acknowledged: delivered again. The limit is honoured.
let again = store.fetch(&[mb], 2).await.unwrap(); let again = store.fetch(&[(mb, vec![])], 2).await.unwrap();
assert_eq!(payloads(&again), vec![b"one".to_vec(), b"two".to_vec()]); assert_eq!(payloads(&again), vec![b"one".to_vec(), b"two".to_vec()]);
assert_eq!(again[0].id, got[0].id); assert_eq!(again[0].id, got[0].id);
assert_ne!(got[0].id, got[1].id); assert_ne!(got[0].id, got[1].id);
@@ -500,15 +515,15 @@ mod tests {
.await .await
.unwrap(); .unwrap();
assert_eq!( assert_eq!(
payloads(&store.fetch(&[mb], 10).await.unwrap()), payloads(&store.fetch(&[(mb, vec![])], 10).await.unwrap()),
vec![b"three".to_vec()] vec![b"three".to_vec()]
); );
// Acks are scoped to their mailbox. // Acks are scoped to their mailbox.
let other = meow_crypto::random_bytes::<32>(); let other = meow_crypto::random_bytes::<32>();
store.ack(other, &[got[2].id.clone()]).await.unwrap(); store.ack(other, &[got[2].id.clone()]).await.unwrap();
assert_eq!(store.fetch(&[mb], 10).await.unwrap().len(), 1); assert_eq!(store.fetch(&[(mb, vec![])], 10).await.unwrap().len(), 1);
store.ack(mb, &[got[2].id.clone()]).await.unwrap(); store.ack(mb, &[got[2].id.clone()]).await.unwrap();
assert!(store.fetch(&[mb], 10).await.unwrap().is_empty()); assert!(store.fetch(&[(mb, vec![])], 10).await.unwrap().is_empty());
let rid = meow_crypto::random_bytes::<16>(); 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());
+4
View File
@@ -205,6 +205,10 @@ message MailboxAuth {
// Ids of messages of this mailbox, received by an earlier pull and now safely // Ids of messages of this mailbox, received by an earlier pull and now safely
// persisted by the client: the server deletes them before answering. // persisted by the client: the server deletes them before answering.
repeated bytes acks = 4; repeated bytes acks = 4;
// Only return messages of this mailbox stored after the message with this id (ids
// grow over time). Used by background watchers, which never acknowledge: they peek
// and long-poll for *new* messages while earlier ones wait for the app.
bytes after = 5;
} }
message Pull { repeated MailboxAuth auths = 1; uint32 wait_seconds = 2; } message Pull { repeated MailboxAuth auths = 1; uint32 wait_seconds = 2; }