//! SHARED SETS (ruling R5, 15 Nov 2026): a calendar, a list or//! a group that several people read and write has its OWN key, wrapped to//! each member's sharing key ([`super::share`]).//!//! ```text//! set key (epoch e) = 32 random bytes, minted on a member's device//! member wrap = w1(member's share_pub, set key || "set\n" set_id "\n" e)//! row in the set = "g1:" e ":" b64url(nonce12 || AES-256-GCM(set key(e), body, aad))//! aad = "g1|" set_id "|" e "|" row_id//! ```//!//! - **Adding a member** wraps the CURRENT epoch's key for them. They read//! what is written from then on, and what was written before in that epoch//! (a person added to a list sees the list).//! - **Removing a member** mints a new key at epoch e+1, wrapped only to the//! members who remain. What is written after is sealed under it, so the//! removed member cannot open new rows. What they already held (the old//! epochs' keys and rows) stays with them: an honest limit, said plainly.//! - Every epoch's wraps are kept, so a member reads old rows with the key of//! the epoch the row names. A member's wrap names the set and the epoch it//! is for, so a wrap moved onto another set or epoch opens nothing.//!//! The object stores the wraps and the sealed rows as opaque text; it never//! holds a set key. Which shared sets exist is a kit's matter: this is the//! rule and its state, the seam a shared calendar or list builds on.use std::collections::BTreeMap;use aes_gcm::aead::{Aead, Payload};use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engineas _;use rand::RngCore;use serde::{Deserialize, Serialize};use zeroize::{Zeroizing, ZeroizeOnDrop};usesuper::{plain_field, SealError, NONCE_LEN};usecrate::vault::wrap::{unwrap, wrap};/// The prefix of a row sealed in a set.pubconst SET_ROW_PREFIX: &str = "g1:";/// One epoch's set key, wiped when it drops. Not `Clone`.#[derive(ZeroizeOnDrop)]pubstructSetKey([u8; 32]);implSetKey {pubfn mint() -> SetKey {letmut bytes = [0u8; 32]; rand::rngs::OsRng.fill_bytes(&mut bytes);SetKey(bytes) }pubfn from_bytes(bytes: [u8; 32]) -> SetKey {SetKey(bytes) }pubfn expose(&self) -> &[u8; 32] { &self.0 }}impl std::fmt::DebugforSetKey {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("SetKey(…)") }}/// A set's key state as the object keeps it: who is a member now, and each/// epoch's wraps by member. Opaque to the object; every value is a wrap or a/// public key.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructMembership {pub set_id: String,/// The epoch new rows are sealed under.pub epoch: u32,/// Members now: an id the kit names them by (a number's key, a person/// fingerprint) to their sharing key, base64url.pub members: BTreeMap<String, String>,/// Every epoch's wraps: epoch → member id → `w1:` wrap.pub wraps: BTreeMap<u32, BTreeMap<String, String>>,}fn wrap_plain(key: &SetKey, set_id: &str, epoch: u32) -> Zeroizing<Vec<u8>> {letmut out = Zeroizing::new(Vec::with_capacity(32 + 16 + set_id.len())); out.extend_from_slice(key.expose()); out.extend_from_slice(format!("set\n{set_id}\n{epoch}").as_bytes()); out}fn share_pub(text: &str) -> Result<[u8; 32], SealError> {super::share::key_from_text(text).ok_or_else(|| SealError::BadInput("a member's sharing key is 32 bytes, base64url".into()))}/// One epoch's key wrapped to one member's sharing key.pubfn wrap_set_key(member_pub: &[u8; 32], key: &SetKey, set_id: &str, epoch: u32) -> Result<String, SealError> { plain_field("set", set_id)?; wrap(member_pub, &wrap_plain(key, set_id, epoch)).ok_or_else(|| SealError::BadInput("a member's sharing key is not a usable X25519 key".into()))}/// A member's wrap opened with their sharing secret, refused unless it names this set and epoch.pubfn open_set_key(share_secret: &[u8; 32], wrapped: &str, set_id: &str, epoch: u32) -> Result<SetKey, SealError> {let plain = Zeroizing::new(unwrap(share_secret, wrapped).ok_or(SealError::DoesNotOpen)?);if plain.len() < 32 || plain[32..] != *format!("set\n{set_id}\n{epoch}").as_bytes() {returnErr(SealError::DoesNotOpen); }Ok(SetKey::from_bytes(plain[..32].try_into().map_err(|_| SealError::DoesNotOpen)?))}implMembership {/// A new set: a fresh key at epoch 1, wrapped to every founding member/// (the founder among them). The key is answered so the founder seals at once.pubfn found(set_id: &str, members: &BTreeMap<String, String>) -> Result<(Membership, SetKey), SealError> { plain_field("set", set_id)?;let key = SetKey::mint();letmut set = Membership { set_id: set_id.into(), epoch: 1, members: BTreeMap::new(), wraps: BTreeMap::new() };for (id, public) in members { set.wrap_for(&key, id, public)?; }Ok((set, key)) }fn wrap_for(&mutself, key: &SetKey, id: &str, public: &str) -> Result<(), SealError> {let wrapped = wrap_set_key(&share_pub(public)?, key, &self.set_id, self.epoch)?;self.wraps.entry(self.epoch).or_default().insert(id.into(), wrapped);self.members.insert(id.into(), public.into());Ok(()) }/// A member added by someone who holds the current key: it is wrapped for them.pubfn add(&mutself, current: &SetKey, id: &str, public: &str) -> Result<(), SealError> {self.wrap_for(current, id, public) }/// A member removed: a NEW key at the next epoch, wrapped to everyone who/// remains, answered so the remover seals what comes next under it.pubfn remove(&mutself, id: &str) -> Result<SetKey, SealError> {self.members.remove(id);self.epoch = self.epoch.checked_add(1).ok_or(SealError::Failed)?;let key = SetKey::mint();let remaining: Vec<(String, String)> = self.members.iter().map(|(k, v)| (k.clone(), v.clone())).collect();for (member, public) in remaining {self.wrap_for(&key, &member, &public)?; }Ok(key) }/// The key of `epoch`, opened by member `id` with their sharing secret.pubfn key_for(&self, id: &str, share_secret: &[u8; 32], epoch: u32) -> Result<SetKey, SealError> {let wrapped = self.wraps.get(&epoch).and_then(|w| w.get(id)).ok_or_else(|| SealError::KeyMissing(format!("set {} epoch {epoch}", self.set_id)))?; open_set_key(share_secret, wrapped, &self.set_id, epoch) }}fn row_aad(set_id: &str, epoch: u32, row_id: &str) -> Vec<u8> { format!("g1|{set_id}|{epoch}|{row_id}").into_bytes()}/// A row's body sealed in a set under the key of `epoch`.pubfn seal_in_set(key: &SetKey, set_id: &str, epoch: u32, row_id: &str, body: &[u8]) -> Result<String, SealError> {letmut nonce = [0u8; NONCE_LEN]; rand::rngs::OsRng.fill_bytes(&mut nonce); seal_in_set_with(&nonce, key, set_id, epoch, row_id, body)}/// [`seal_in_set`] with the nonce supplied.pubfn seal_in_set_with(nonce: &[u8; NONCE_LEN], key: &SetKey, set_id: &str, epoch: u32, row_id: &str, body: &[u8]) -> Result<String, SealError> { plain_field("set", set_id)?; plain_field("row", row_id)?;let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.expose()));let ct = cipher.encrypt(Nonce::from_slice(nonce), Payload { msg: body, aad: &row_aad(set_id, epoch, row_id) }).map_err(|_| SealError::Failed)?;letmut out = Vec::with_capacity(NONCE_LEN + ct.len()); out.extend_from_slice(nonce); out.extend_from_slice(&ct);Ok(format!("{SET_ROW_PREFIX}{epoch}:{}", URL_SAFE_NO_PAD.encode(out)))}/// The epoch a sealed set row names: which key opens it.pubfn epoch_of(sealed: &str) -> Result<u32, SealError> {let rest = sealed.strip_prefix(SET_ROW_PREFIX).ok_or(SealError::DoesNotOpen)?; rest.split_once(':').and_then(|(e, _)| e.parse().ok()).ok_or(SealError::DoesNotOpen)}/// A set row opened with the key of the epoch it names.pubfn open_in_set(key: &SetKey, set_id: &str, row_id: &str, sealed: &str) -> Result<Vec<u8>, SealError> {let epoch = epoch_of(sealed)?;let (_, b64) = sealed[SET_ROW_PREFIX.len()..].split_once(':').ok_or(SealError::DoesNotOpen)?;let body = URL_SAFE_NO_PAD.decode(b64).map_err(|_| SealError::DoesNotOpen)?;if body.len() < NONCE_LEN + 16 {returnErr(SealError::DoesNotOpen); }let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.expose())); cipher.decrypt(Nonce::from_slice(&body[..NONCE_LEN]), Payload { msg: &body[NONCE_LEN..], aad: &row_aad(set_id, epoch, row_id) }).map_err(|_| SealError::DoesNotOpen)}#[cfg(test)]#[path = "set_tests.rs"]mod tests;