//! Typed items and their templates (docs/FORMAT.md, "Item types and their fields"). use crate::secret::SecretString; use serde::{Deserialize, Serialize}; use std::fmt; /// Previous values kept per item, oldest dropped first. pub const HISTORY_LIMIT: usize = 20; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum ItemType { WebLogin, ApiCredential, LocalApp, Wifi, SecureNote, Card, /// A signing or SSH key pair (docs/FACTORS.md, "The key-pair item type"). KeyPair, } impl ItemType { pub const ALL: [ItemType; 7] = [ ItemType::WebLogin, ItemType::ApiCredential, ItemType::LocalApp, ItemType::Wifi, ItemType::SecureNote, ItemType::Card, ItemType::KeyPair, ]; pub fn label(self) -> &'static str { match self { ItemType::WebLogin => "Web login", ItemType::ApiCredential => "API credential", ItemType::LocalApp => "Local app credential", ItemType::Wifi => "Wi-Fi", ItemType::SecureNote => "Secure note", ItemType::Card => "Card", ItemType::KeyPair => "Key pair", } } /// The template: field names in display order, and whether each is secret. pub fn template(self) -> &'static [(&'static str, bool)] { match self { ItemType::WebLogin => &[ ("username", false), ("password", true), ("url", false), ("totp", true), ("autotype-match", false), ("autotype-sequence", false), ], ItemType::ApiCredential => { &[("service", false), ("key-id", false), ("secret", true), ("endpoint", false), ("expires", false)] } ItemType::LocalApp => &[("target", false), ("username", false), ("password", true)], ItemType::Wifi => &[("ssid", false), ("password", true), ("security", false), ("hidden", false)], ItemType::SecureNote => &[], ItemType::Card => { &[("cardholder", false), ("number", true), ("expiry", false), ("cvv", true), ("pin", true)] } ItemType::KeyPair => &[ ("algorithm", false), ("public-key", false), ("public-pem", false), ("private-key", true), ("private-openssh", true), ("fingerprint", false), ("comment", false), ], } } } #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Field { pub name: String, pub value: SecretString, #[serde(default)] pub secret: bool, } impl Field { pub fn text(name: &str, value: &str) -> Self { Self { name: name.into(), value: value.into(), secret: false } } pub fn secret(name: &str, value: &str) -> Self { Self { name: name.into(), value: value.into(), secret: true } } } impl fmt::Debug for Field { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Field").field("name", &self.name).field("secret", &self.secret).finish_non_exhaustive() } } #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct HistoryEntry { pub field: String, pub value: SecretString, pub changed: i64, } impl fmt::Debug for HistoryEntry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("HistoryEntry") .field("field", &self.field) .field("changed", &self.changed) .finish_non_exhaustive() } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Item { pub id: String, #[serde(rename = "type")] pub kind: ItemType, pub title: String, #[serde(default)] pub fields: Vec, #[serde(default)] pub tags: Vec, #[serde(default)] pub notes: SecretString, pub created: i64, pub modified: i64, #[serde(default)] pub history: Vec, } impl Item { /// A new item with every template field present and empty. `now` is Unix milliseconds. pub fn new(kind: ItemType, title: &str, now: i64) -> Self { Item { id: new_id(), kind, title: title.into(), fields: kind .template() .iter() .map(|&(name, secret)| Field { name: name.into(), value: SecretString::default(), secret }) .collect(), tags: Vec::new(), notes: SecretString::default(), created: now, modified: now, history: Vec::new(), } } /// The first field called `name`. pub fn field(&self, name: &str) -> Option<&Field> { self.fields.iter().find(|f| f.name == name) } /// Sets the first field called `name` (adding it if missing, secret if the template says so). /// A changed secret field keeps its previous non-empty value in `history`. pub fn set(&mut self, name: &str, value: &str, now: i64) { let template_secret = self.kind.template().iter().any(|&(n, s)| n == name && s); match self.fields.iter_mut().find(|f| f.name == name) { Some(f) if f.value.expose() == value => return, Some(f) => { let old = std::mem::replace(&mut f.value, value.into()); if f.secret && !old.is_empty() { self.history.push(HistoryEntry { field: name.into(), value: old, changed: now }); let excess = self.history.len().saturating_sub(HISTORY_LIMIT); self.history.drain(..excess); } } None => self.fields.push(Field { name: name.into(), value: value.into(), secret: template_secret }), } self.modified = now; } /// Appends a field, e.g. a second `url`. pub fn add_field(&mut self, field: Field) { self.fields.push(field); } } /// 128 random bits as 32 hex digits. pub fn new_id() -> String { let mut b = [0u8; 16]; crate::crypto::fill_random(&mut b); b.iter().map(|x| format!("{x:02x}")).collect() } /// Now, in Unix milliseconds. pub fn now_ms() -> i64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0) }