//! The Custos vault: one `.custos` file, Argon2id + XChaCha20-Poly1305, documented in docs/FORMAT.md //! (version 1) and docs/FACTORS.md (version 2: any two factors). //! //! ``` //! use custos_vault::{FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault}; //! let password = SecretString::from("Orbit7-Fable3-Quartz9-Lumen2"); //! let device_key = [7u8; 32]; // in the app: a key file only this Windows account can read //! # let kdf = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }; //! let mut vault = Vault::create_with( //! Unlock::Password(&password), "Master password", //! Unlock::Material(FactorKind::Device, &device_key), "This PC", kdf)?; //! vault.add(Item::new(ItemType::WebLogin, "GitHub", custos_vault::now_ms())); //! let bytes = vault.to_bytes()?; //! let back = Vault::open_with(&bytes, Unlock::Password(&password), Unlock::Material(FactorKind::Device, &device_key))?; //! assert_eq!(back.items().len(), 1); //! # Ok::<(), custos_vault::Error>(()) //! ``` mod crypto; mod device; mod format; pub mod identity; mod item; pub mod provision; mod recovery; mod save; mod secret; pub mod security; pub mod signing; pub mod team; pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms}; pub use recovery::RecoveryKey; pub use save::{CrashPoint, save_atomic, save_atomic_crashing}; pub use secret::{SecretBytes, SecretString}; pub use team::{ KnownTeam, NewSigner, NewTarget, Removal, RemovedMember, SignerView, TargetView, TeamAction, TeamAuditEntry, TeamMember, TeamView, }; use crypto::KEY_LEN; use format::{ FactorSlot, Header, ID_LEN, MAX_FACTORS, PairSlot, PasswordSlot, RawSlot, SALT_LEN, SLOT_FACTOR, SLOT_PAIR, SLOT_PASSWORD, SingleSlot, VERSION, VERSION_2, }; use serde::{Deserialize, Serialize}; use std::fmt; use std::path::Path; use zeroize::Zeroizing; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("not a Custos vault file")] NotAVault, #[error("vault format version {0} is not supported by this version of Custos")] UnsupportedVersion(u16), #[error("the vault file is malformed")] Malformed, #[error("the vault's key-derivation parameters are not supported")] UnsupportedKdf, #[error("wrong password")] WrongPassword, #[error("the vault file was changed or damaged after it was written")] Corrupted, #[error("this device's unlock key no longer opens the vault; use the master password")] DeviceKeyRejected, #[error("this vault opens with two different factors")] NeedTwoFactors, #[error("this factor does not open the vault")] FactorRejected, #[error("these two factors are kept on the same device; use one of them with another factor")] SameDevice, #[error("this is not a recovery key as Custos prints it: check each group of characters")] RecoveryKeyMistyped, #[error("this recovery key does not open this vault: it is another vault's, or an older one that was replaced")] WrongRecoveryKey, #[error("this vault has no recovery key")] NoRecoveryKey, #[error("a vault has at most 8 factors and one master password")] TooManyFactors, #[error("this vault has no Domi identity yet")] NoIdentity, #[error("this vault already has a Domi identity")] IdentityExists, #[error("the Domi identity signs only certificates that name it")] NotACert, #[error("those words are not the ones in the recovery phrase")] WrongWords, #[error("these are not the 24 words of a recovery phrase: check each word and their order")] NotAMnemonic, #[error("the Domi identity signs a revocation only for a key revoked in Custos, at the time it was revoked")] NotARevocation, #[error("the Domi identity did not certify this key")] UnknownKey, #[error("this vault already has {0} signing keys")] SigningExists(&'static str), /// Names the member that does not fit (docs/FORMAT.md), never its value. #[error("provision audit: {0}")] Provision(&'static str), /// Names the rule a security change breaks (docs/FORMAT.md, "The security member"), never a value. #[error("security: {0}")] Security(&'static str), #[error("signing keys: {0}")] Signing(String), /// A team vault operation was refused (docs/TEAM.md); names why, never a value. #[error("team: {0}")] Team(String), #[error("this is not a team vault")] NotATeam, #[error("this member key does not open this team vault: not a member, or removed")] NotAMember, #[error("this team vault is older than the one this member has seen, or another team's under the same id")] TeamRollback, #[error("{0}")] Io(#[from] std::io::Error), } /// Argon2id parameters, stored per vault (docs/FORMAT.md, "Limits"). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct KdfParams { pub m_cost_kib: u32, pub t_cost: u32, pub p_cost: u32, } impl KdfParams { /// 64 MiB, 20 passes, 1 lane: about 0.75 s per unlock on the dev machine (2026, release build; /// measure with `cargo run --release -p custos-vault --example kdf_timing`). pub const DEFAULT: KdfParams = KdfParams { m_cost_kib: 65_536, t_cost: 20, p_cost: 1 }; pub const MAX_M_COST_KIB: u32 = 2 * 1024 * 1024; pub const MAX_T_COST: u32 = 64; pub const MAX_P_COST: u32 = 16; /// Refuses parameters outside the limits before any Argon2 work. pub fn check(&self) -> Result<(), Error> { let ok = (1..=Self::MAX_P_COST).contains(&self.p_cost) && (1..=Self::MAX_T_COST).contains(&self.t_cost) && (8 * self.p_cost..=Self::MAX_M_COST_KIB).contains(&self.m_cost_kib); if ok { Ok(()) } else { Err(Error::UnsupportedKdf) } } } impl Default for KdfParams { fn default() -> Self { Self::DEFAULT } } /// What kind of secret a factor is (docs/FACTORS.md, "Factor KEKs"). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum FactorKind { /// The master password. Password, /// A key one device keeps (a DPAPI-protected key file, a key in the phone's storage). Device, /// A share the TOTP service releases after a valid code. Totp, /// A secret another paired device sends after you approve there. Approval, /// A WebAuthn PRF output (Face ID, Touch ID, Windows Hello passkey). Passkey, } impl FactorKind { fn code(self) -> u8 { match self { FactorKind::Password => 1, FactorKind::Device => 2, FactorKind::Totp => 3, FactorKind::Approval => 4, FactorKind::Passkey => 5, } } fn from_code(c: u8) -> Option { Some(match c { 1 => FactorKind::Password, 2 => FactorKind::Device, 3 => FactorKind::Totp, 4 => FactorKind::Approval, 5 => FactorKind::Passkey, _ => return None, }) } } /// One factor given to open a vault. `Debug` never prints the password or the material. #[derive(Clone, Copy)] pub enum Unlock<'a> { Password(&'a SecretString), /// Any other factor: its kind and 32..=64 bytes of material. Material(FactorKind, &'a [u8]), } impl Unlock<'_> { fn kind(&self) -> FactorKind { match self { Unlock::Password(_) => FactorKind::Password, Unlock::Material(k, _) => *k, } } /// Material for types 2..5 must be 32..=64 bytes, and a password is never passed as material. fn check(&self) -> Result<(), Error> { match self { Unlock::Password(_) => Ok(()), Unlock::Material(FactorKind::Password, _) => Err(Error::FactorRejected), Unlock::Material(_, m) if (32..=64).contains(&m.len()) => Ok(()), Unlock::Material(..) => Err(Error::FactorRejected), } } } impl fmt::Debug for Unlock<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Unlock::Password(_) => f.write_str("Password([redacted])"), Unlock::Material(k, _) => write!(f, "Material({k:?}, [redacted])"), } } } /// A factor of an unlocked vault, as the app lists it. Never carries the factor key. #[derive(Clone, Debug, PartialEq, Eq)] pub struct FactorInfo { /// 32 hex digits. pub id: String, pub kind: FactorKind, pub label: String, pub created: i64, } /// A factor as the body keeps it: its key `F` is what lets an unlocked vault add pairs. #[derive(Clone)] struct FactorRec { id: [u8; ID_LEN], kind: FactorKind, label: String, created: i64, key: Zeroizing<[u8; KEY_LEN]>, } #[derive(Serialize, Deserialize)] struct FactorJson { id: String, #[serde(rename = "type")] kind: FactorKind, label: String, created: i64, key: SecretString, } fn hex(b: &[u8]) -> String { b.iter().map(|x| format!("{x:02x}")).collect() } fn unhex(s: &str) -> Option<[u8; N]> { if s.len() != 2 * N { return None; } let mut out = [0u8; N]; for (i, o) in out.iter_mut().enumerate() { *o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?; } Some(out) } impl FactorRec { fn json(&self) -> FactorJson { FactorJson { id: hex(&self.id), kind: self.kind, label: self.label.clone(), created: self.created, key: SecretString::new(hex(self.key.as_ref())), } } fn from_json(j: &FactorJson) -> Option { Some(FactorRec { id: unhex(&j.id)?, kind: j.kind, label: j.label.clone(), created: j.created, key: Zeroizing::new(unhex(j.key.expose())?), }) } } const BODY_FORMAT: u32 = 1; const BODY_FORMAT_2: u32 = 2; const INFO_FACTOR: &[u8] = b"custos factor v2"; const INFO_PAIR: &[u8] = b"custos pair v2"; const INFO_SINGLE: &[u8] = b"custos single v2"; const INFO_RECOVERY: &[u8] = b"custos recovery v2"; #[derive(Deserialize)] struct Body { format: u32, items: Vec, #[serde(default)] factors: Vec, #[serde(default)] identity: Option, #[serde(default)] signing: Option, #[serde(default)] provision: Option, #[serde(default)] security: Option, /// `"team"` for a team vault (core 0.18.0, docs/TEAM.md). #[serde(default)] kind: Option, #[serde(default)] team: Option, /// A person's member key (core 0.18.0). #[serde(default)] member: Option, } /// What `to_bytes` serializes: borrows the items instead of cloning every secret. #[derive(Serialize)] struct BodyRef<'a> { format: u32, items: &'a [Item], #[serde(skip_serializing_if = "Vec::is_empty")] factors: Vec, #[serde(skip_serializing_if = "Option::is_none")] identity: Option, #[serde(skip_serializing_if = "Option::is_none")] signing: Option, #[serde(skip_serializing_if = "Option::is_none")] provision: Option, #[serde(skip_serializing_if = "Option::is_none")] security: Option, #[serde(skip_serializing_if = "Option::is_none")] kind: Option<&'static str>, #[serde(skip_serializing_if = "Option::is_none")] team: Option, #[serde(skip_serializing_if = "Option::is_none")] member: Option, } /// An unlocked vault: the vault key and the decrypted items, both wiped on drop. pub struct Vault { key: Zeroizing<[u8; KEY_LEN]>, version: u16, slots: Vec, items: Vec, /// Version 2 only. factors: Vec, /// Argon2 parameters for a password factor added later. kdf_new: KdfParams, /// The Domi identity's root key (docs/IDENTITY.md), never handed out. identity: Option, /// Signing keys and their audit log (docs/SIGNING.md); no key is ever handed out. signing: signing::Store, /// The Provisio audit (docs/FORMAT.md), oldest first. provision: Vec, /// The security level's Setup window, the checklist and their audit (docs/FORMAT.md). security: security::State, /// A team vault's own state (docs/TEAM.md); `None` for every other vault. team: Option, /// A person's member key and the teams it has opened (docs/TEAM.md); never in a team vault. member: Option, } impl fmt::Debug for Vault { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Vault") .field("version", &self.version) .field("items", &self.items.len()) .field("factors", &self.factors.len()) .field("identity", &self.identity.is_some()) .finish_non_exhaustive() } } fn password_slot(key: &[u8; KEY_LEN], password: &SecretString, kdf: KdfParams) -> Result { kdf.check()?; let mut salt = [0u8; SALT_LEN]; crypto::fill_random(&mut salt); let mut slot = PasswordSlot { kdf, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() }; let kek = crypto::derive_kek(password.expose().as_bytes(), &slot.salt, kdf)?; slot.wrapped = crypto::seal(&kek, &slot.nonce, key, &slot.aad()); Ok(slot) } /// The KEK a factor's material gives for one factor slot. fn factor_kek(u: &Unlock, salt: &[u8], kdf: Option) -> Result, Error> { match (u, kdf) { (Unlock::Password(p), Some(k)) => crypto::derive_kek(p.expose().as_bytes(), salt, k), (Unlock::Material(_, m), None) => Ok(crypto::hkdf(m, salt, INFO_FACTOR)), _ => Err(Error::FactorRejected), } } /// A new factor slot wrapping `key` (the factor key `F`) with `u`'s material. fn factor_slot(id: [u8; ID_LEN], key: &[u8; KEY_LEN], u: &Unlock, kdf: KdfParams) -> Result { u.check()?; let kdf = matches!(u, Unlock::Password(_)).then_some(kdf); if let Some(k) = kdf { k.check()?; } let mut salt = [0u8; SALT_LEN]; crypto::fill_random(&mut salt); let mut slot = FactorSlot { id, kind: u.kind().code(), kdf, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() }; let kek = factor_kek(u, &slot.salt, slot.kdf)?; slot.wrapped = crypto::seal(&kek, &slot.nonce, key, &slot.aad()); Ok(slot) } fn pair_kek(a: &FactorRec, b: &FactorRec) -> Zeroizing<[u8; KEY_LEN]> { let (x, y) = if a.id < b.id { (a, b) } else { (b, a) }; let mut ikm = Zeroizing::new([0u8; 2 * KEY_LEN]); ikm[..KEY_LEN].copy_from_slice(x.key.as_ref()); ikm[KEY_LEN..].copy_from_slice(y.key.as_ref()); let mut salt = [0u8; 2 * ID_LEN]; salt[..ID_LEN].copy_from_slice(&x.id); salt[ID_LEN..].copy_from_slice(&y.id); crypto::hkdf(ikm.as_ref(), &salt, INFO_PAIR) } fn pair_slot(vault_key: &[u8; KEY_LEN], a: &FactorRec, b: &FactorRec) -> PairSlot { let (x, y) = if a.id < b.id { (a.id, b.id) } else { (b.id, a.id) }; let mut slot = PairSlot { a: x, b: y, nonce: crypto::random_nonce(), wrapped: Vec::new() }; slot.wrapped = crypto::seal(&pair_kek(a, b), &slot.nonce, vault_key, &slot.aad()); slot } fn single_kek(f: &FactorRec) -> Zeroizing<[u8; KEY_LEN]> { crypto::hkdf(f.key.as_ref(), &f.id, INFO_SINGLE) } fn key32(k: Zeroizing>) -> Result, Error> { Ok(Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::Malformed)?)) } /// The first factor slot of `u`'s kind that `u` unwraps: its id and factor key. fn unwrap_factor(header: &Header, u: &Unlock) -> Result { u.check()?; for slot in header.factor_slots().into_iter().filter(|s| s.kind == u.kind().code()) { let kek = factor_kek(u, &slot.salt, slot.kdf)?; if let Some(k) = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()) { return Ok(FactorRec { id: slot.id, kind: u.kind(), label: String::new(), created: 0, key: key32(k)? }); } } Err(if matches!(u, Unlock::Password(_)) { Error::WrongPassword } else { Error::FactorRejected }) } impl Vault { /// An empty version-2 vault with `key` and no slots yet: a team vault writes its member slots itself. pub(crate) fn empty_v2(key: Zeroizing<[u8; KEY_LEN]>) -> Vault { Vault { key, version: VERSION_2, slots: Vec::new(), items: Vec::new(), factors: Vec::new(), kdf_new: KdfParams::DEFAULT, identity: None, signing: signing::Store::default(), provision: Vec::new(), security: security::State::default(), team: None, member: None, } } /// A new, empty version-1 vault with a fresh random vault key wrapped by `password`. pub fn create(password: &SecretString, kdf: KdfParams) -> Result { let key = crypto::random_key(); let slot = password_slot(&key, password, kdf)?; Ok(Vault { key, version: VERSION, slots: vec![slot.raw()], items: Vec::new(), factors: Vec::new(), kdf_new: kdf, identity: None, signing: signing::Store::default(), provision: Vec::new(), security: security::State::default(), team: None, member: None, }) } /// A new, empty version-2 vault that opens with these two factors together (docs/FACTORS.md). pub fn create_with(a: Unlock, label_a: &str, b: Unlock, label_b: &str, kdf: KdfParams) -> Result { if a.kind() == FactorKind::Password && b.kind() == FactorKind::Password { return Err(Error::NeedTwoFactors); } let mut v = Vault { key: crypto::random_key(), version: VERSION_2, slots: Vec::new(), items: Vec::new(), factors: Vec::new(), kdf_new: kdf, identity: None, signing: signing::Store::default(), provision: Vec::new(), security: security::State::default(), team: None, member: None, }; v.add_factor(a, label_a)?; v.add_factor(b, label_b)?; Ok(v) } /// A machine store: a separate vault that one device key opens alone, for a program that must /// open it unattended (the Claude Code store). Never for the user's own secrets. pub fn create_machine_store(material: &[u8], label: &str) -> Result { let u = Unlock::Material(FactorKind::Device, material); u.check()?; let key = crypto::random_key(); let mut id = [0u8; ID_LEN]; crypto::fill_random(&mut id); let rec = FactorRec { id, kind: FactorKind::Device, label: label.into(), created: now_ms(), key: crypto::random_key(), }; let fslot = factor_slot(id, &rec.key, &u, KdfParams::DEFAULT)?; let mut single = SingleSlot { id, nonce: crypto::random_nonce(), wrapped: Vec::new() }; single.wrapped = crypto::seal(&single_kek(&rec), &single.nonce, key.as_ref(), &single.aad()); Ok(Vault { key, version: VERSION_2, slots: vec![fslot.raw(), single.raw()], items: Vec::new(), factors: vec![rec], kdf_new: KdfParams::DEFAULT, identity: None, signing: signing::Store::default(), provision: Vec::new(), security: security::State::default(), team: None, member: None, }) } pub fn open_file(path: &Path, password: &SecretString) -> Result { Vault::open(&std::fs::read(path)?, password) } /// Unlocks a version-1 vault with its password. A version-2 vault needs [`Vault::open_with`]. /// Returns no data at all unless both the key slot and the body authenticate. pub fn open(bytes: &[u8], password: &SecretString) -> Result { let (header, body_at) = Header::parse(bytes)?; if header.version == VERSION_2 { return Err(Error::NeedTwoFactors); } let pw_slots: Vec = header .slots .iter() .filter(|s| s.kind == SLOT_PASSWORD) .map(|s| PasswordSlot::parse(&s.payload)) .collect::>()?; if pw_slots.is_empty() { return Err(Error::Malformed); } for slot in &pw_slots { let kek = crypto::derive_kek(password.expose().as_bytes(), &slot.salt, slot.kdf)?; if let Some(k) = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()) { let kdf = slot.kdf; let mut v = Vault::open_body(bytes, header, body_at, key32(k)?)?; v.kdf_new = kdf; return Ok(v); } } Err(Error::WrongPassword) } /// Unlocks a version-2 vault with two different factors, in any order (docs/FACTORS.md, "Opening"). pub fn open_with(bytes: &[u8], a: Unlock, b: Unlock) -> Result { let (header, body_at) = Header::parse(bytes)?; if header.version != VERSION_2 || header.is_machine_store() { return Err(Error::NeedTwoFactors); } // Refuse bad material before any Argon2 work. a.check()?; b.check()?; let fa = unwrap_factor(&header, &a)?; let fb = unwrap_factor(&header, &b)?; if fa.id == fb.id { return Err(Error::NeedTwoFactors); } let (x, y) = if fa.id < fb.id { (fa.id, fb.id) } else { (fb.id, fa.id) }; // Both factors opened, so a missing pair is one added apart from the other (one device). let slot = header.pair_slots().into_iter().find(|p| p.a == x && p.b == y).ok_or(Error::SameDevice)?; let k = crypto::open(&pair_kek(&fa, &fb), &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::Corrupted)?; Vault::open_body(bytes, header, body_at, key32(k)?) } /// Opens a machine store with its one device key. A user vault is never opened this way. pub fn open_machine_store(bytes: &[u8], material: &[u8]) -> Result { let (header, body_at) = Header::parse(bytes)?; if header.version != VERSION_2 || !header.is_machine_store() { return Err(Error::NeedTwoFactors); } let f = unwrap_factor(&header, &Unlock::Material(FactorKind::Device, material))?; let slot = header.single_slot().filter(|s| s.id == f.id).ok_or(Error::Corrupted)?; let k = crypto::open(&single_kek(&f), &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::Corrupted)?; Vault::open_body(bytes, header, body_at, key32(k)?) } /// The format version of a vault file (1 or 2), from its header alone. pub fn version_of(bytes: &[u8]) -> Result { Ok(Header::parse(bytes)?.0.version) } /// The kinds of factor a vault opens with, from its header alone: what the unlock screen offers. pub fn factor_kinds(bytes: &[u8]) -> Result, Error> { let (header, _) = Header::parse(bytes)?; if header.version == VERSION { return Ok(vec![FactorKind::Password]); } Ok(header.factor_slots().iter().filter_map(|s| FactorKind::from_code(s.kind)).collect()) } /// The factors a vault file has, from its header (no key needed): id (32 hex digits) and type. The app /// asks the TOTP service and paired devices for a factor by this id. pub fn factor_ids(bytes: &[u8]) -> Result, Error> { let (header, _) = Header::parse(bytes)?; if header.version == VERSION { return Ok(Vec::new()); } Ok(header.factor_slots().iter().filter_map(|s| Some((hex(&s.id), FactorKind::from_code(s.kind)?))).collect()) } pub fn is_machine_store(bytes: &[u8]) -> Result { Ok(Header::parse(bytes)?.0.is_machine_store()) } fn open_body(bytes: &[u8], header: Header, body_at: usize, key: Zeroizing<[u8; KEY_LEN]>) -> Result { let json = crypto::open(&key, &header.body_nonce, &bytes[body_at..], &bytes[..body_at]).ok_or(Error::Corrupted)?; let body: Body = serde_json::from_slice(&json).map_err(|_| Error::Corrupted)?; let want = if header.version == VERSION_2 { BODY_FORMAT_2 } else { BODY_FORMAT }; if body.format != want { return Err(Error::Corrupted); } let factors: Vec = body.factors.iter().map(FactorRec::from_json).collect::>().ok_or(Error::Corrupted)?; // Every factor slot in the header has its key in the body, and the other way round. if header.version == VERSION_2 { let mut in_header: Vec<_> = header.factor_slots().iter().map(|s| s.id).collect(); let mut in_body: Vec<_> = factors.iter().map(|f| f.id).collect(); in_header.sort(); in_body.sort(); if in_header != in_body { return Err(Error::Corrupted); } } let kdf_new = header.factor_slots().iter().find_map(|s| s.kdf).unwrap_or(KdfParams::DEFAULT); let identity = match &body.identity { Some(j) => Some(identity::Root::from_json(j).ok_or(Error::Corrupted)?), None => None, }; let signing = match body.signing { Some(j) => signing::Store::from_json(j).ok_or(Error::Corrupted)?, None => signing::Store::default(), }; let security = security::State::from_json(body.security).ok_or(Error::Corrupted)?; // A team vault (member slots) has a team body and nothing of a person's; every other vault has none. let team = match (header.is_team(), body.kind.as_deref(), body.team) { (true, Some("team"), Some(j)) => Some(team::TeamState::from_json(j).ok_or(Error::Corrupted)?), (false, None, None) => None, _ => return Err(Error::Corrupted), }; let member = match body.member { Some(_) if team.is_some() => return Err(Error::Corrupted), Some(j) => Some(team::MemberState::from_json(j).ok_or(Error::Corrupted)?), None => None, }; Ok(Vault { key, version: header.version, slots: header.slots, items: body.items, factors, kdf_new, identity, signing, provision: provision::from_json(body.provision), security, team, member, }) } /// Wraps the vault key for device unlock with key material only this device can produce (e.g. a /// Windows Hello signature). Version 1 only: a version-2 vault never opens with one secret. pub fn wrap_for_device(&self, material: &[u8]) -> Result, Error> { if self.version == VERSION_2 { return Err(Error::NeedTwoFactors); } Ok(device::wrap(&self.key, material)) } /// Unlocks with a device blob instead of the password (version 1). Fails with `DeviceKeyRejected` /// when the material is wrong or the blob was changed, and with `Corrupted` when it belongs to another vault. pub fn open_with_device(bytes: &[u8], blob: &[u8], material: &[u8]) -> Result { let (header, body_at) = Header::parse(bytes)?; if header.version == VERSION_2 { return Err(Error::NeedTwoFactors); } let key = device::unwrap(blob, material)?; Vault::open_body(bytes, header, body_at, key) } /// The encrypted file contents, with a fresh body nonce. pub fn to_bytes(&self) -> Result, Error> { let body_nonce = crypto::random_nonce(); let mut out = Header { version: self.version, slots: self.slots.clone(), body_nonce }.to_bytes(); let mut json = Zeroizing::new(Vec::with_capacity(4096 + 1024 * self.items.len())); let v2 = self.version == VERSION_2; let body = BodyRef { format: if v2 { BODY_FORMAT_2 } else { BODY_FORMAT }, items: &self.items, factors: self.factors.iter().map(FactorRec::json).collect(), identity: self.identity.as_ref().map(identity::Root::json), signing: self.signing.json(), provision: provision::json(&self.provision), security: self.security.json(), kind: self.team.is_some().then_some("team"), team: self.team.as_ref().map(team::TeamState::json), member: self.member.as_ref().map(team::MemberState::json), }; serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?; let sealed = crypto::seal(&self.key, &body_nonce, &json, &out); out.extend_from_slice(&sealed); Ok(out) } /// Encrypts and writes the vault atomically (see [`save_atomic`]). pub fn save(&self, path: &Path) -> Result<(), Error> { save_atomic(path, &self.to_bytes()?) } /// Changes the master password. Version 1: a new password slot. Version 2: the password factor's /// key is rewrapped, so its pairs keep working (also after a forgotten password: open with two /// other factors, then set a new one). The old password stops working at the next save. pub fn change_password(&mut self, new_password: &SecretString, kdf: KdfParams) -> Result<(), Error> { if self.version == VERSION { let slot = password_slot(&self.key, new_password, kdf)?; self.slots.retain(|s| s.kind != SLOT_PASSWORD); self.slots.insert(0, slot.raw()); self.kdf_new = kdf; return Ok(()); } if self.is_store() { return Err(Error::FactorRejected); } self.kdf_new = kdf; let Some(rec) = self.factors.iter().find(|f| f.kind == FactorKind::Password).cloned() else { self.add_factor(Unlock::Password(new_password), "Master password")?; return Ok(()); }; let slot = factor_slot(rec.id, &rec.key, &Unlock::Password(new_password), kdf)?; let at = self.factor_slot_index(&rec.id).ok_or(Error::Corrupted)?; self.slots[at] = slot.raw(); Ok(()) } /// A machine-key vault: one device factor opens it alone (a Claude Code store, or Custos's hands-off vault /// before it is taken over). pub fn opens_with_machine_key(&self) -> bool { self.is_store() } /// *Take over the vault* (Custos docs/12_hands_off.md, section 6): adds the master password as a factor paired /// with the device key, removes the PC-only access, and ticks the items that end unattended work. Returns the /// password factor's id. Only on a machine-key vault, once. The caller saves. pub fn take_over(&mut self, password: &SecretString, kdf: KdfParams, now: i64) -> Result { if !self.is_store() { return Err(Error::FactorRejected); } let slots = self.slots.clone(); let kdf_was = self.kdf_new; // Without its single slot the vault is an ordinary version-2 vault with one factor; the password pairs with it. self.slots.retain(|s| s.kind != format::SLOT_SINGLE); self.kdf_new = kdf; match self.add_factor(Unlock::Password(password), "Master password") { Ok(id) => { self.security_taken_over(now); Ok(id) } Err(e) => { self.slots = slots; self.kdf_new = kdf_was; Err(e) } } } // ---- the recovery key (docs/FACTORS.md, "The recovery key") ---- /// Which recovery key a vault file has (its id, 8 hex characters), from the header alone. pub fn recovery_id_of(bytes: &[u8]) -> Result, Error> { Ok(Header::parse(bytes)?.0.recovery_slot().map(|s| recovery::id_hex(&s.id))) } /// Which recovery key this vault has. pub fn recovery_id(&self) -> Option { self.slots .iter() .find(|s| s.kind == format::SLOT_RECOVERY) .and_then(|s| format::RecoverySlot::parse(&s.payload).ok()) .map(|s| recovery::id_hex(&s.id)) } fn recovery_put(&mut self) -> RecoveryKey { let mut id = [0u8; recovery::ID_LEN]; crypto::fill_random(&mut id); let material = crypto::random_key(); let mut salt = [0u8; SALT_LEN]; crypto::fill_random(&mut salt); let mut slot = format::RecoverySlot { id, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() }; let kek = crypto::hkdf(material.as_ref(), &slot.salt, INFO_RECOVERY); slot.wrapped = crypto::seal(&kek, &slot.nonce, self.key.as_ref(), &slot.aad()); self.slots.retain(|s| s.kind != format::SLOT_RECOVERY); self.slots.push(slot.raw()); recovery::encode(&id, &material) } /// Makes the vault's recovery key and returns it, once: it is in no file and no log, so what the caller does /// not show or print is lost. A key the vault already had stops working. Only a two-factor vault has one /// (not version 1, not a machine-key vault). The caller saves. pub fn recovery_create(&mut self, now: i64) -> Result { if self.version != VERSION_2 { return Err(Error::NeedTwoFactors); } if self.is_store() { return Err(Error::FactorRejected); } let key = self.recovery_put(); self.security.recovery_note(security::Action::RecoveryCreated, key.id(), now); Ok(key) } /// Removes the recovery key: from the next save on, only the factors open the vault. The caller saves. pub fn recovery_remove(&mut self, now: i64) -> Result<(), Error> { let id = self.recovery_id().ok_or(Error::NoRecoveryKey)?; self.slots.retain(|s| s.kind != format::SLOT_RECOVERY); self.security.recovery_note(security::Action::RecoveryRemoved, &id, now); Ok(()) } /// Opens a vault with its recovery key and, before handing it back, replaces what opened it until now: every /// factor is dropped, `new_password` and `second` (anything but a password) become its two factors, and the /// used recovery key is replaced by the new one returned here. The items and everything else stay. Nothing is /// written: the caller saves, and until it does the file is as it was. /// /// This is the only call that takes a recovery key, so the key is never an everyday unlock. pub fn recover( bytes: &[u8], key: &SecretString, new_password: &SecretString, kdf: KdfParams, second: Unlock, label: &str, now: i64, ) -> Result<(Vault, RecoveryKey), Error> { // What was typed is checked first: a typing mistake is not a wrong key. let (id, material) = recovery::decode(key)?; if second.kind() == FactorKind::Password { return Err(Error::NeedTwoFactors); } second.check()?; if new_password.expose().is_empty() { return Err(Error::WrongPassword); } kdf.check()?; let (header, body_at) = Header::parse(bytes)?; if header.version != VERSION_2 { return Err(Error::NoRecoveryKey); } let slot = header.recovery_slot().ok_or(Error::NoRecoveryKey)?; if slot.id != id { return Err(Error::WrongRecoveryKey); } let kek = crypto::hkdf(material.as_ref(), &slot.salt, INFO_RECOVERY); let k = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::WrongRecoveryKey)?; let mut v = Vault::open_body(bytes, header, body_at, key32(k)?)?; // Whoever held the old factors holds nothing of this vault from the next save on. v.slots.clear(); v.factors.clear(); v.kdf_new = kdf; v.add_factor(Unlock::Password(new_password), "Master password")?; v.add_factor(second, label)?; let new_key = v.recovery_put(); v.security.recovery_note(security::Action::Recovered, &recovery::id_hex(&id), now); Ok((v, new_key)) } fn is_store(&self) -> bool { self.slots.iter().any(|s| s.kind == format::SLOT_SINGLE) } fn factor_slot_index(&self, id: &[u8; ID_LEN]) -> Option { self.slots.iter().position(|s| s.kind == SLOT_FACTOR && s.payload.get(..ID_LEN) == Some(&id[..])) } /// Adds a factor to a version-2 vault: only the new factor's material is needed (docs/FACTORS.md). /// Returns its id. A second master password is refused; use [`Vault::change_password`]. pub fn add_factor(&mut self, u: Unlock, label: &str) -> Result { self.add_factor_apart(u, label, &[]) } /// Adds a factor that never pairs with the factors `apart` (ids of factors kept on the same device, such /// as a phone's passkey and its approval key): together they open nothing, so one device is never two /// factors. Returns its id. pub fn add_factor_apart(&mut self, u: Unlock, label: &str, apart: &[&str]) -> Result { let apart: Vec<[u8; ID_LEN]> = apart.iter().map(|a| unhex(a).ok_or(Error::FactorRejected)).collect::>()?; if apart.iter().any(|a| !self.factors.iter().any(|f| f.id == *a)) { return Err(Error::FactorRejected); } if self.version != VERSION_2 { return Err(Error::NeedTwoFactors); } if self.is_store() { return Err(Error::FactorRejected); } u.check()?; if self.factors.len() >= MAX_FACTORS || (u.kind() == FactorKind::Password && self.factors.iter().any(|f| f.kind == FactorKind::Password)) { return Err(Error::TooManyFactors); } let mut id = [0u8; ID_LEN]; crypto::fill_random(&mut id); let rec = FactorRec { id, kind: u.kind(), label: label.into(), created: now_ms(), key: crypto::random_key() }; let slot = factor_slot(id, &rec.key, &u, self.kdf_new)?; self.slots.push(slot.raw()); for other in self.factors.iter().filter(|f| !apart.contains(&f.id)) { self.slots.push(pair_slot(&self.key, &rec, other).raw()); } self.factors.push(rec); Ok(hex(&id)) } /// Removes a factor (a lost phone, an old PC) and every pair it is part of. A vault keeps at least two. pub fn remove_factor(&mut self, id: &str) -> Result<(), Error> { let id: [u8; ID_LEN] = unhex(id).ok_or(Error::FactorRejected)?; if !self.factors.iter().any(|f| f.id == id) { return Err(Error::FactorRejected); } if self.factors.len() <= 2 { return Err(Error::NeedTwoFactors); } self.factors.retain(|f| f.id != id); self.slots.retain(|s| match s.kind { SLOT_FACTOR => s.payload.get(..ID_LEN) != Some(&id[..]), SLOT_PAIR => s.payload.get(..ID_LEN) != Some(&id[..]) && s.payload.get(ID_LEN..2 * ID_LEN) != Some(&id[..]), _ => true, }); Ok(()) } /// Turns an unlocked version-1 vault into version 2 with its password and a second factor. /// The vault key and the items stay; from the next save on, the password alone opens nothing. pub fn upgrade_to_two_factors( &mut self, password: &SecretString, kdf: KdfParams, second: Unlock, label: &str, ) -> Result<(), Error> { if self.version != VERSION { return Err(Error::UnsupportedVersion(self.version)); } if second.kind() == FactorKind::Password { return Err(Error::NeedTwoFactors); } second.check()?; self.version = VERSION_2; self.slots.clear(); self.factors.clear(); self.kdf_new = kdf; self.add_factor(Unlock::Password(password), "Master password")?; self.add_factor(second, label)?; Ok(()) } /// The factors of a version-2 vault, oldest first. Empty for version 1. pub fn factors(&self) -> Vec { self.factors .iter() .map(|f| FactorInfo { id: hex(&f.id), kind: f.kind, label: f.label.clone(), created: f.created }) .collect() } /// 1 or 2. pub fn version(&self) -> u16 { self.version } /// Whether two unlocked vaults share a vault key (tests: a password change keeps the key). #[doc(hidden)] pub fn same_key_as(&self, other: &Vault) -> bool { self.key[..] == other.key[..] } /// The KDF parameters of the (first) password slot or password factor. pub fn kdf(&self) -> Option { self.slots.iter().find_map(|s| match s.kind { SLOT_PASSWORD => PasswordSlot::parse(&s.payload).ok().map(|p| p.kdf), SLOT_FACTOR => FactorSlot::parse(&s.payload).ok().and_then(|f| f.kdf), _ => None, }) } pub fn items(&self) -> &[Item] { &self.items } pub fn item(&self, id: &str) -> Option<&Item> { self.items.iter().find(|i| i.id == id) } pub fn item_mut(&mut self, id: &str) -> Option<&mut Item> { self.items.iter_mut().find(|i| i.id == id) } pub fn add(&mut self, item: Item) { self.items.push(item); } /// Replaces the item with the same id, or adds it. pub fn put(&mut self, item: Item) { match self.item_mut(&item.id) { Some(slot) => *slot = item, None => self.items.push(item), } } pub fn remove(&mut self, id: &str) -> Option { let i = self.items.iter().position(|it| it.id == id)?; Some(self.items.remove(i)) } // ---- the Domi identity (docs/IDENTITY.md); created with identity::Enrollment ---- /// The root public key, if this vault has a Domi identity. pub fn domi_root_public(&self) -> Option<[u8; 32]> { self.identity.as_ref().map(|r| r.public) } /// When the identity was created (Unix milliseconds). pub fn domi_created(&self) -> Option { self.identity.as_ref().map(|r| r.created) } /// Ed25519 with the root over `"tessera cert v1" ‖ tbs`. Refuses a `tbs` that does not start with /// `TSC1` and this root's public key ([`Error::NotACert`]): the root signs certificates and nothing else. pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error> { self.identity.as_ref().ok_or(Error::NoIdentity)?.sign_cert(tbs) } /// The certs this vault has signed, oldest first. pub fn domi_issued(&self) -> &[identity::Issued] { self.identity.as_ref().map(|r| r.issued.as_slice()).unwrap_or(&[]) } /// Records a cert this vault signed. The caller saves the vault. pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error> { self.identity.as_mut().ok_or(Error::NoIdentity)?.issued.push(issued); Ok(()) } /// The person revoked the key `subkey` (base64url): marks every cert of it. Returns the revocation time in /// effect, the earlier one if it was marked before. The caller saves the vault. pub fn domi_mark_revoked(&mut self, subkey: &str, revoked_at: u64) -> Result { self.identity.as_mut().ok_or(Error::NoIdentity)?.mark_revoked(subkey, revoked_at) } /// Ed25519 with the root over `"tessera revoke v1\0" ‖ tbs`, for a `tbs` that starts with `TRV1`, this /// root's public key, a key marked revoked and its `revoked_at` ([`Error::NotARevocation`] otherwise). pub fn domi_sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error> { self.identity.as_ref().ok_or(Error::NoIdentity)?.sign_revocation(tbs) } /// Keeps the signed statements (base64url `TRV1`) with every cert of `subkey`. The caller saves the vault. pub fn domi_record_revocation(&mut self, subkey: &str, statements: Vec) -> Result<(), Error> { self.identity.as_mut().ok_or(Error::NoIdentity)?.record_revocation(subkey, statements) } /// The backup secret of the app `app_id` (docs/IDENTITY.md): derived from the root, handed to that app /// only. The caller checks `app_id` (a-z, 0-9, `-`) and the app's right to it. pub fn domi_backup_secret(&self, app_id: &str) -> Result, Error> { Ok(self.identity.as_ref().ok_or(Error::NoIdentity)?.backup_secret(app_id)) } }