//! Cotton Secrets' sharing, decided (assets/design/keys/DECISIONS.md "Sharing"//! and S1 to S5). PURE: keys, facts and a clock in; words-free decisions out.//! The phone module seals, asks its object and says the words.//!//! **A share is two boxes**, each a `p1:` box sealed by the giver's phone to//! the holder's sharing key (`seal::share::seal_to_person`)://! - the **card** (the name, kind and site: enough for the holder's list),//! bound to [`card_context`];//! - the **value** (the secret's payload), bound to [`value_context`] at a//! version, so an older value can never be replayed as the new one.//!//! The holder's object hands the value out only when the holder reveals or//! copies, and counts each fetch. So "opened" is what the server saw, not//! what the holder's app chose to report (S5).//!//! **The check (S1).** A person's sharing key is one key for all their phones,//! derived from their data key. Two people check each other once: the same six//! words on both phones ([`check_words`]), or one scans the other's code//! ([`check_code`], [`read_code`]). The key is pinned at the check; a key that//! differs later pauses every share to them until they are checked again.use chrono::{DateTime, Duration, Utc};use serde::{Deserialize, Serialize};use sha2::{Digest, Sha256};usesuper::generator::EFF_LARGE;usecrate::vault::SecretPayload;/// The domain the check words are hashed under.const CHECK_INFO: &[u8] = b"cotton-secrets-check-v1";/// A scanned code's prefix and version.const CODE_PREFIX: &str = "cotton-check:1:";/// How many words a check says.pubconst CHECK_WORDS: usize = 6;/// What a card box carries: what the holder's list shows, nothing more.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructShareCard {pub name: String,pub kind: String, #[serde(default, skip_serializing_if = "Option::is_none")]pub site: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub username: Option<String>,/// The giver's own name for themselves, as their phone knows it. #[serde(default, skip_serializing_if = "Option::is_none")]pub from_name: Option<String>,pub may: May,/// RFC 3339; `None` until the giver takes it back. #[serde(default, skip_serializing_if = "Option::is_none")]pub until: Option<String>,/// The fields the giver's secret holds (`password`, `notes`, …), so the person it is shared with sees only those/// named (launch-ios's walk, 25 Nov 2026: an invented login showed Notes, One-time code and Other websites sealed,/// all empty). `None` on a card from before it: every field of the kind, as then. #[serde(default, skip_serializing_if = "Option::is_none")]pub fields: Option<Vec<String>>,}/// The fields a payload holds a value in, by their payload names, in the kind's own order.pubfn filled(payload: &crate::vault::SecretPayload) -> Vec<String> {let value = serde_json::to_value(payload).unwrap_or_default();letSome(kind) = value.get("kind").and_then(|k| k.as_str()).and_then(crate::vault::SecretKind::parse) else { returnVec::new() }; kind.spec() .fields .iter() .filter(|field| value.get(field.name).and_then(|v| v.as_str()).is_some_and(|v| !v.trim().is_empty())) .map(|field| field.name.to_string()) .collect()}/// What a value box carries: the payload, at a version.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructShareValue {pub version: u32,pub payload: SecretPayload,}/// What a holder may do. Two levels, kept small (DECISIONS.md question 3).#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]#[serde(rename_all = "snake_case")]pubenumMay {/// Read it in Secrets; copy off. #[default]See,/// Read it and copy it.Copy,}implMay {pubfn parse(text: &str) -> Option<May> {match text {"see" => Some(May::See),"copy" => Some(May::Copy), _ => None, } }pubconstfn as_str(self) -> &'static str {matchself {May::See => "see",May::Copy => "copy", } }}/// The card's context: `secret-card:<share>`.pubfn card_context(share: &str) -> String { format!("secret-card:{share}")}/// The value's context: `secret-value:<share>:<version>`.pubfn value_context(share: &str, version: u32) -> String { format!("secret-value:{share}:{version}")}/// An ask's context: `secret-ask:<ask>`.pubfn ask_context(ask: &str) -> String { format!("secret-ask:{ask}")}/// Whether a kind may be shared at all. A passkey signs in; it is never shown/// or sent (DECISIONS.md "Kinds").pubfn shareable(kind: &str) -> bool { kind != "passkey"}// ── until ──────────────────────────────────────────────────────────────/// The expiry choices a share offers, in their order; `week` is the default/// for a share and `day` for the answer to an ask (DECISIONS.md question 4).pubconst UNTIL_CHOICES: [&str; 4] = ["day", "week", "month", "taken"];/// When a share chosen as `choice` at `now` ends: `None` for "until I take it/// back". A date (`YYYY-MM-DD`) ends at the end of that day, UTC. Refused/// (`None` inside `Err`) for anything else, or a date already past.pubfn until_of(choice: &str, now: DateTime<Utc>) -> Result<Option<DateTime<Utc>>, ()> {match choice {"day" => Ok(Some(now + Duration::days(1))),"week" => Ok(Some(now + Duration::days(7))),"month" => Ok(Some(now + Duration::days(30))),"taken" => Ok(None), date => {let day = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").map_err(|_| ())?;let end = day.and_hms_opt(23, 59, 59).ok_or(())?.and_utc();if end <= now {returnErr(()); }Ok(Some(end)) } }}// ── a holder's standing ────────────────────────────────────────────────/// What a giver knows of one share, from its own record and its object.#[derive(Debug, Clone, Default, PartialEq, Eq)]pubstructFacts {/// When the holder's object received it (never: `None`).pub delivered_at: Option<DateTime<Utc>>,/// Value fetches the holder's object counted.pub opens: u32,pub last_open: Option<DateTime<Utc>>,pub until: Option<DateTime<Utc>>,pub taken_back_at: Option<DateTime<Utc>>,/// When the giver last changed the secret's value.pub changed_at: Option<DateTime<Utc>>,}/// Where one share stands.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pubenumStanding {/// Live: they hold it.Holds,/// Ended or taken back before anything of it was seen: nothing to do.Ended,/// Ended or taken back after the value left the server, and the secret/// not changed since: it is only safe once it is changed.StillKnown,/// Ended or taken back after it was seen, and changed since: done.Changed,}implFacts {/// When the share stopped: taken back, or its expiry passed.pubfn ended_at(&self, now: DateTime<Utc>) -> Option<DateTime<Utc>> {match (self.taken_back_at, self.until.filter(|until| *until <= now)) { (Some(taken), Some(until)) => Some(taken.min(until)), (taken, until) => taken.or(until), } }/// Whether anything of the value may be known to the holder. Only a fetch/// the server counted makes it known (S5): a card alone says no value.pubfn seen(&self) -> bool {self.opens > 0 }pubfn standing(&self, now: DateTime<Utc>) -> Standing {letSome(ended) = self.ended_at(now) else { returnStanding::Holds };if !self.seen() {returnStanding::Ended; }matchself.changed_at {Some(changed) if changed >= ended => Standing::Changed, _ => Standing::StillKnown, } }}/// What a take back may honestly say before it happens (S5).#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pubenumBefore {/// The holder's object never received it: no change needed.NeverReceived,/// Received, never opened: the value never left the holder's object./// Still advised for a developer secret, because the giver cannot see the/// holder's object itself.Received,/// Opened this many times: change it after.Opened(u32),}pubfn before_take(facts: &Facts) -> Before {match (facts.delivered_at, facts.opens) { (None, _) => Before::NeverReceived, (Some(_), 0) => Before::Received, (Some(_), n) => Before::Opened(n), }}// ── the check (S1) ─────────────────────────────────────────────────────/// One person's side of a check: their number and their sharing key's public half.#[derive(Debug, Clone, PartialEq, Eq)]pubstructSide<'a> {pub number: &'a str,pub key: &'a [u8; 32],}/// The six words both phones show. The same on both sides, whoever asks:/// the two sides are sorted by number before they are hashed.pubfn check_words(a: &Side<'_>, b: &Side<'_>) -> [String; CHECK_WORDS] {let (first, second) = if a.number <= b.number { (a, b) } else { (b, a) };letmut hash = Sha256::new(); hash.update(CHECK_INFO);for side in [first, second] { hash.update((side.number.len() as u32).to_be_bytes()); hash.update(side.number.as_bytes()); hash.update(side.key); }let digest = hash.finalize();let words: Vec<&str> = EFF_LARGE.lines().collect(); std::array::from_fn(|i| {let n = u32::from(u16::from_be_bytes([digest[i * 3], digest[i * 3 + 1]])) << 8 | u32::from(digest[i * 3 + 2]); words[(n as usize) % words.len()].to_string() })}/// What one phone shows as a QR code: its number and its sharing key.pubfn check_code(me: &Side<'_>) -> String { format!("{CODE_PREFIX}{}:{}", me.number, crate::seal::share::key_text(me.key))}/// A scanned code, read: the number and the key it names. `None` for/// anything that is not a check code.pubfn read_code(code: &str) -> Option<(String, [u8; 32])> {let rest = code.trim().strip_prefix(CODE_PREFIX)?;let (number, key) = rest.rsplit_once(':')?;if !number.starts_with('+') || number.len() < 4 {returnNone; }Some((number.to_string(), crate::seal::share::key_from_text(key)?))}/// A short, stable print of a key, for a pinned key's record.pubfn key_print(key: &[u8; 32]) -> String {let digest = Sha256::digest(key); digest[..8].iter().map(|byte| format!("{byte:02x}")).collect()}// ── where to change it ─────────────────────────────────────────────────/// A provider whose key page a "change it" step opens.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructProvider {pub name: &'static str,/// Where a person changes or rolls the key.pub url: &'static str,}/// Providers known by a token's prefix or the secret's site, in the order/// they are tried. Invented values never reach here: only a kind, a site and/// a token's first characters.const PROVIDERS: &[(&[&str], &[&str], Provider)] = &[ (&["sk_live_", "sk_test_", "rk_live_", "rk_test_", "pk_live_", "pk_test_"], &["stripe.com"], Provider { name: "Stripe", url: "https://dashboard.stripe.com/apikeys" }), (&["AKIA", "ASIA"], &["aws.amazon.com", "amazonaws.com"], Provider { name: "AWS", url: "https://console.aws.amazon.com/iam/home#/security_credentials" }), (&["ghp_", "gho_", "ghs_", "github_pat_"], &["github.com"], Provider { name: "GitHub", url: "https://github.com/settings/tokens" }), (&["AIza"], &["console.cloud.google.com", "cloud.google.com"], Provider { name: "Google Cloud", url: "https://console.cloud.google.com/apis/credentials" }), (&[], &["firebase.google.com", "console.firebase.google.com"], Provider { name: "Firebase", url: "https://console.firebase.google.com/" }), (&[], &["play.google.com"], Provider { name: "Play Console", url: "https://play.google.com/console" }), (&[], &["appstoreconnect.apple.com", "developer.apple.com"], Provider { name: "App Store Connect", url: "https://appstoreconnect.apple.com/access/integrations/api" }), (&["xoxb-", "xoxp-"], &["slack.com", "api.slack.com"], Provider { name: "Slack", url: "https://api.slack.com/apps" }), (&["sk-ant-"], &["console.anthropic.com"], Provider { name: "Anthropic", url: "https://console.anthropic.com/settings/keys" }),];/// Where a secret is changed: a known provider by its token's prefix or its/// site, else the site itself (`https://<site>`), else nothing.pubfn change_at(site: Option<&str>, token_start: Option<&str>) -> Option<(String, Option<String>)> {let site = site.map(|site| site.trim().trim_start_matches("https://").trim_start_matches("http://").trim_end_matches('/').to_lowercase()).filter(|site| !site.is_empty());for (prefixes, sites, provider) in PROVIDERS {let by_prefix = token_start.is_some_and(|start| prefixes.iter().any(|prefix| start.starts_with(prefix)));let by_site = site.as_deref().is_some_and(|site| sites.iter().any(|known| site == *known || site.ends_with(&format!(".{known}"))));if by_prefix || by_site {returnSome((provider.name.to_string(), Some(provider.url.to_string()))); } } site.map(|site| (site.clone(), Some(format!("https://{site}"))))}#[cfg(test)]#[path = "share_tests.rs"]mod tests;