use std::fmt;
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Mime(String);
impl Mime {
pub fn new(value: impl Into<String>) -> Self {
Mime(value.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn is_text(&self) -> bool {
let m = self.0.to_ascii_lowercase();
m.starts_with("text/") || m == "utf8_string" || m == "string"
}
pub fn is_image(&self) -> bool {
self.0.to_ascii_lowercase().starts_with("image/")
}
}
impl fmt::Display for Mime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for Mime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Mime({})", self.0)
}
}
pub const PASSWORD_HINT: &str = "x-kde-passwordManagerHint";
pub const PASSWORD_HINT_SECRET: &str = "secret";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Sensitivity {
Recordable,
Secret,
}
impl Sensitivity {
pub fn classify(mimes: &[Mime], hint_value: Option<&str>) -> Sensitivity {
let advertises_hint = mimes.iter().any(|m| m.as_str() == PASSWORD_HINT);
if !advertises_hint {
return Sensitivity::Recordable;
}
match hint_value {
Some(value) if value.trim().eq_ignore_ascii_case(PASSWORD_HINT_SECRET) => {
Sensitivity::Secret
}
None => Sensitivity::Secret,
Some(_) => Sensitivity::Recordable,
}
}
pub fn is_secret(self) -> bool {
matches!(self, Sensitivity::Secret)
}
}
#[derive(Clone, PartialEq, Eq)]
pub enum Content {
Text(String),
Image {
bytes: Vec<u8>,
mime: Mime,
},
}
impl Content {
pub fn is_empty(&self) -> bool {
match self {
Content::Text(text) => text.trim().is_empty(),
Content::Image { bytes, .. } => bytes.is_empty(),
}
}
pub fn size(&self) -> usize {
match self {
Content::Text(text) => text.len(),
Content::Image { bytes, .. } => bytes.len(),
}
}
pub fn preview(&self, max_chars: usize) -> String {
match self {
Content::Image { bytes, mime } => {
format!("Image · {} · {}", mime, human_size(bytes.len()))
}
Content::Text(text) => {
let collapsed = text.split_whitespace().collect::<Vec<_>>().join(" ");
if collapsed.chars().count() <= max_chars {
return collapsed;
}
let cut: String = collapsed
.chars()
.take(max_chars.saturating_sub(1))
.collect();
format!("{cut}\u{2026}")
}
}
}
}
impl fmt::Debug for Content {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Content::Text(text) => {
write!(f, "Text({:?})", hyprforge_secret::chars(text.chars().count()))
}
Content::Image { bytes, mime } => {
write!(f, "Image({mime}, {:?})", hyprforge_secret::bytes(bytes.len()))
}
}
}
}
fn human_size(bytes: usize) -> String {
const KB: usize = 1024;
const MB: usize = KB * 1024;
match bytes {
b if b >= MB => format!("{:.1} MB", b as f64 / MB as f64),
b if b >= KB => format!("{:.0} KB", b as f64 / KB as f64),
b => format!("{b} B"),
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct Entry {
pub id: EntryId,
pub content: Content,
pub copied_at: u64,
pub pinned: bool,
}
impl fmt::Debug for Entry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Entry")
.field("id", &self.id)
.field("content", &self.content)
.field("pinned", &self.pinned)
.finish()
}
}
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct EntryId(String);
impl EntryId {
pub fn from_raw(id: impl Into<String>) -> Self {
EntryId(id.into())
}
pub fn of(content: &Content) -> Self {
let mut hasher = blake3::Hasher::new();
match content {
Content::Text(text) => {
hasher.update(b"text\0");
hasher.update(text.as_bytes());
}
Content::Image { bytes, mime } => {
hasher.update(b"image\0");
hasher.update(mime.as_str().as_bytes());
hasher.update(b"\0");
hasher.update(bytes);
}
}
EntryId(hasher.finalize().to_hex().to_string())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for EntryId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "EntryId({}…)", &self.0[..8.min(self.0.len())])
}
}
#[cfg(test)]
mod tests {
use super::*;
fn mimes(list: &[&str]) -> Vec<Mime> {
list.iter().map(|m| Mime::new(*m)).collect()
}
#[test]
fn an_offer_a_password_manager_marked_secret_is_never_recordable() {
let offer = mimes(&["text/plain", PASSWORD_HINT]);
assert_eq!(
Sensitivity::classify(&offer, Some("secret")),
Sensitivity::Secret
);
}
#[test]
fn an_unreadable_hint_is_treated_as_secret_rather_than_assumed_safe() {
let offer = mimes(&["text/plain", PASSWORD_HINT]);
assert_eq!(Sensitivity::classify(&offer, None), Sensitivity::Secret);
}
#[test]
fn the_hint_being_present_is_not_itself_the_signal_its_value_is() {
let offer = mimes(&["text/plain", PASSWORD_HINT]);
assert_eq!(
Sensitivity::classify(&offer, Some("not-secret")),
Sensitivity::Recordable
);
}
#[test]
fn an_ordinary_offer_with_no_hint_is_recordable() {
assert_eq!(
Sensitivity::classify(&mimes(&["text/plain", "text/html"]), None),
Sensitivity::Recordable
);
}
#[test]
fn an_entry_never_renders_its_own_content() {
let secret = "correct-horse-battery-staple";
let entry = Entry {
id: EntryId::of(&Content::Text(secret.to_string())),
content: Content::Text(secret.to_string()),
copied_at: 0,
pinned: false,
};
let rendered = format!("{entry:?}");
assert!(!rendered.contains(secret), "leaked: {rendered}");
assert!(
rendered.contains(&format!("{} chars", secret.chars().count())),
"expected a redacted count, got {rendered}"
);
}
#[test]
fn the_same_content_copied_twice_has_the_same_id() {
let a = Content::Text("hello".to_string());
let b = Content::Text("hello".to_string());
assert_eq!(EntryId::of(&a), EntryId::of(&b));
assert_ne!(EntryId::of(&a), EntryId::of(&Content::Text("other".into())));
}
#[test]
fn text_and_an_image_with_the_same_bytes_are_different_entries() {
let text = Content::Text("hello".to_string());
let image = Content::Image {
bytes: b"hello".to_vec(),
mime: Mime::new("image/png"),
};
assert_ne!(EntryId::of(&text), EntryId::of(&image));
}
#[test]
fn a_preview_is_one_line_and_never_splits_a_character() {
let text = Content::Text("line one\n\n line two\tline three".to_string());
assert_eq!(text.preview(80), "line one line two line three");
let emoji = Content::Text("🎉".repeat(50));
let preview = emoji.preview(10);
assert_eq!(preview.chars().count(), 10);
assert!(preview.ends_with('\u{2026}'));
}
#[test]
fn an_image_preview_says_what_it_is_rather_than_showing_bytes() {
let image = Content::Image {
bytes: vec![0; 2048],
mime: Mime::new("image/png"),
};
let preview = image.preview(80);
assert!(preview.contains("image/png"));
assert!(preview.contains("2 KB"));
}
#[test]
fn a_mime_knows_whether_it_is_text_or_an_image() {
assert!(Mime::new("text/plain;charset=utf-8").is_text());
assert!(Mime::new("UTF8_STRING").is_text());
assert!(Mime::new("image/png").is_image());
assert!(!Mime::new("image/png").is_text());
}
#[test]
fn a_blank_copy_is_empty_even_when_it_has_bytes() {
assert!(Content::Text(" \n\t ".to_string()).is_empty());
assert!(!Content::Text("x".to_string()).is_empty());
}
}