433 lines · 20.1 KB · RustRaw
//! The Items screen, decided: chips, sections, search, paging and each row's//! picture, marks and quick acts. PURE: plain columns in, `ItemsAnswer` out —//! no file, no clock, no key. The phone module reads the rows (and the health//! marks, when the vault is open) and hands them here.//!//! Search is on the device and instant: every word typed must begin a word//! of the title, the site or the user name (accents and case folded), and a//! title that begins with the whole query ranks first. Nothing is matched by//! a substring in the middle of a word, so "ail" does not find "mail".use std::collections::HashMap;use serde_json::json;use unicode_normalization::UnicodeNormalization;use super::shapes::*;use crate::rules::shell_lines::LineSet;/// The kinds a filter may still name alone (an older screen's chip); the/// chips themselves are [`GROUPS`] since Cotton Secrets (25 Nov 2026).pub const CHIP_KINDS: &[&str] = &["login", "passkey", "code", "card", "note", "identity", "wifi", "address", "api_key", "document", "file"];/// The kinds the add menu offers, in its order.pub const ADD_KINDS: &[&str] = &["login", "note", "card", "code", "identity", "wifi", "address", "api_key", "file", "document"];/// Cotton Secrets' five groups, in the order the chips stand, and the kinds/// each holds (DECISIONS.md "Kinds"): a password, a passkey, a card, a note,/// a developer secret (a token or a key, or a whole file).pub const GROUPS: &[(&str, &[&str])] = &[ ("passwords", &["login", "wifi", "code", "document"]), ("passkeys", &["passkey"]), ("cards", &["card"]), ("notes", &["note", "identity", "address"]), ("developer", &["api_key", "file"]),];/// The group a row stands in. A login that also signs in with a passkey is a/// password; it counts under Passkeys as well (see [`in_group`]).pub fn group_of(kind: &str) -> &'static str { GROUPS.iter().find(|(_, kinds)| kinds.contains(&kind)).map(|(id, _)| *id).unwrap_or("passwords")}/// Whether `entry` is listed under the group `id`.pub fn in_group(entry: &Entry, id: &str) -> bool { group_of(&entry.kind) == id || (id == "passkeys" && entry.passkey)}/// Whether the developer face (the mono face, never wrapped mid-token) draws/// a row's second line.pub fn is_developer(kind: &str) -> bool { group_of(kind) == "developer"}/// One saved thing's plain columns: never a sealed value.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct Entry { pub id: String, /// A `secret` kind, or `passkey` for a passkey with no login of its own. pub kind: String, pub title: String, pub site: Option<String>, pub username: Option<String>, pub favourite: bool, /// RFC 3339, when it last filled or was copied. pub last_used: Option<String>, /// A login that also signs in with a passkey. pub passkey: bool, pub in_bin: bool, /// The row's second line when the phone could say more than the plain /// columns do: "Card ending 4821", a token's masked tail, "File · 18 /// lines". Worked out on the phone while the vault is open, never stored, /// never sent (DECISIONS.md S2: no server hint). pub second: Option<String>,}/// What the screen asked for.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct Ask { pub filter: String, pub q: String, pub after: Option<String>,}/// The vault set, read once per process./// The Secrets app's own words (`secrets`), where a screen's words have moved there from the vault set.pub fn secrets_lines() -> &'static LineSet { static LINES: std::sync::OnceLock<LineSet> = std::sync::OnceLock::new(); LINES.get_or_init(|| LineSet::shipped("secrets").expect("the kit ships the secrets line set"))}pub fn lines() -> &'static LineSet { static LINES: std::sync::OnceLock<LineSet> = std::sync::OnceLock::new(); LINES.get_or_init(|| LineSet::shipped("vault").expect("the kit ships the vault line set"))}/// One line of the vault set; a missing line is a kit bug the line test catches, said as its key.pub fn say(lines: &LineSet, line: &str, fills: &[(&str, &str)]) -> String { lines.say(line, fills).unwrap_or_else(|| line.to_string())}/// Text folded for search: decomposed, marks dropped, lower case.pub fn fold(text: &str) -> String { if !needs_fold(text) { return text.to_string(); } if text.is_ascii() { return text.to_ascii_lowercase(); } text.nfkd().filter(|c| !unicode_normalization::char::is_combining_mark(*c)).flat_map(char::to_lowercase).collect()}fn words(folded: &str) -> impl Iterator<Item = &str> { folded.split(|c: char| !c.is_alphanumeric()).filter(|word| !word.is_empty())}/// How well `entry` answers `query` (already folded and split): `None` for no/// match, else a rank, lower first: 0 the title begins with the whole query,/// 1 every word begins a title word, 2 a word needed the site or user name.pub fn rank(entry: &Entry, query: &str, terms: &[&str]) -> Option<u8> { rank_folded(&fold(&entry.title), entry, query, terms)}fn rank_folded(title: &str, entry: &Entry, query: &str, terms: &[&str]) -> Option<u8> { if title.starts_with(query) { return Some(0); } let site = entry.site.as_deref().map(fold).unwrap_or_default(); let user = entry.username.as_deref().map(fold).unwrap_or_default(); let mut rank = 1; for term in terms { if words(title).any(|word| word.starts_with(term)) { continue; } let elsewhere = words(&site).chain(words(&user)).any(|word| word.starts_with(term)) || site.starts_with(term) || user.starts_with(term); if !elsewhere { return None; } rank = 2; } Some(rank)}/// The initials a picture draws: the first letters of the first two words.pub fn initials(title: &str) -> String { let letters: String = title.split(|c: char| !c.is_alphanumeric()).filter(|word| !word.is_empty()).take(2).filter_map(|word| word.chars().next()).flat_map(char::to_uppercase).collect(); if letters.is_empty() { "?".to_string() } else { letters }}/// A stable tint for a title (FNV-1a), so a row keeps its colour across launches and devices.pub fn tint(title: &str) -> u32 { let mut hash: u32 = 0x811c_9dc5; for byte in fold(title).bytes() { hash ^= byte as u32; hash = hash.wrapping_mul(0x0100_0193); } hash % TINTS}/// Whether the fold changes this text at all: plain ASCII lower case needs none.fn needs_fold(text: &str) -> bool { !text.bytes().all(|b| b.is_ascii() && !b.is_ascii_uppercase())}pub fn picture(entry: &Entry) -> Picture { let symbol = match entry.kind.as_str() { "passkey" => None, "login" | "api_key" if entry.site.is_some() => None, kind => Some(kind.to_string()), }; Picture { initials: initials(&entry.title), tint: tint(&entry.title), symbol }}fn act(id: &str, label: String, method: &str, request: serde_json::Value) -> Act { Act { id: id.into(), label, method: method.into(), request, presence: false, confirm: None, tone: Tone::Neutral, symbol: None, input: None }}/// The marks a row wears, worded and toned.pub fn marks_of(lines: &LineSet, ids: &[String]) -> Vec<Mark> { ["breached", "weak", "reused", "old"] .iter() .filter(|id| ids.iter().any(|mark| mark == *id)) .map(|id| Mark { id: id.to_string(), label: say(lines, &format!("marks.{id}"), &[]), tone: if matches!(*id, "breached" | "weak") { Tone::Danger } else { Tone::Attention }, }) .collect()}fn row(lines: &LineSet, entry: &Entry, marks: &HashMap<String, Vec<String>>) -> ItemRow { let kind_word = say(lines, &format!("kinds.{}", entry.kind), &[]); let subtitle = entry.second.clone().or_else(|| entry.username.clone().filter(|user| !user.is_empty())).or_else(|| entry.site.clone()).unwrap_or(kind_word); let mut quick = Vec::new(); if entry.in_bin { quick.push(act("restore", say(lines, "item.restore", &[]), "vault.act", json!({"act": "restore", "id": entry.id}))); } else if entry.kind != "passkey" { if entry.username.as_deref().is_some_and(|user| !user.is_empty()) { let mut copy = act("copy_username", say(lines, "items.copy_username", &[]), "vault.field", json!({"id": entry.id, "field": "username"})); copy.symbol = Some("person".into()); quick.push(copy); } let primary = match entry.kind.as_str() { "login" | "wifi" | "document" => Some(("copy_password", "items.copy_password", "password")), "code" => Some(("copy_code", "items.copy_code", "code")), _ => None, }; if let Some((id, line, field)) = primary { let (method, request) = if field == "code" { ("vault.code", json!({"id": entry.id})) } else { ("vault.field", json!({"id": entry.id, "field": field})) }; let mut copy = act(id, say(lines, line, &[]), method, request); copy.presence = true; copy.symbol = Some(if field == "code" { "clock" } else { "key" }.into()); quick.push(copy); } let (line, on) = if entry.favourite { ("items.unfavourite", false) } else { ("items.favourite", true) }; let mut star = act(if on { "favourite" } else { "unfavourite" }, say(lines, line, &[]), "vault.act", json!({"act": if on { "favourite" } else { "unfavourite" }, "id": entry.id})); star.symbol = Some(if on { "star" } else { "star.slash" }.into()); quick.push(star); } ItemRow { id: entry.id.clone(), kind: entry.kind.clone(), group: group_of(&entry.kind).into(), mono: is_developer(&entry.kind) && entry.second.is_some(), title: entry.title.clone(), subtitle, picture: picture(entry), favourite: entry.favourite, marks: marks.get(&entry.id).map(|ids| marks_of(lines, ids)).unwrap_or_default(), badge: (entry.passkey && entry.kind == "login").then(|| say(lines, "items.passkey_badge", &[])), quick, }}/// The A–Z key a row sorts and pages by.fn sort_key(entry: &Entry) -> String { fold(&entry.title)}const CURSOR_SEP: char = '\u{1f}';fn cursor_of(rank: u8, sort: &str, id: &str) -> String { format!("{rank}{CURSOR_SEP}{sort}{CURSOR_SEP}{id}")}fn cursor_parts(cursor: &str) -> Option<(u8, String, String)> { let mut parts = cursor.splitn(3, CURSOR_SEP); Some((parts.next()?.parse().ok()?, parts.next()?.to_string(), parts.next()?.to_string()))}/// The Items screen for `ask`, over every entry kept (live and in the bin)./// `marks` names each entry's health marks by id; `open` says whether the vault is open here.pub fn items(entries: &[Entry], marks: &HashMap<String, Vec<String>>, ask: &Ask, open: bool) -> ItemsAnswer { let lines = lines(); let filter = match ask.filter.as_str() { "" => "all", other if other == "all" || other == "favourites" || other == "bin" || CHIP_KINDS.contains(&other) || GROUPS.iter().any(|(id, _)| *id == other) => other, _ => "all", }; let live: Vec<&Entry> = entries.iter().filter(|entry| !entry.in_bin).collect(); let binned = entries.len() - live.len(); let count = |pick: &dyn Fn(&Entry) -> bool| live.iter().filter(|entry| pick(entry)).count() as u32; let mut chips = vec![Chip { id: "all".into(), label: say(lines, "chips.all", &[]), count: live.len() as u32, on: filter == "all" }]; let favourites = count(&|entry| entry.favourite); if favourites > 0 || filter == "favourites" { chips.push(Chip { id: "favourites".into(), label: say(lines, "chips.favourites", &[]), count: favourites, on: filter == "favourites" }); } for (id, _) in GROUPS { let n = count(&|entry| in_group(entry, id)); if n > 0 || filter == *id { chips.push(Chip { id: id.to_string(), label: say(lines, &format!("chips.{id}"), &[]), count: n, on: filter == *id }); } } if filter == "bin" { chips.push(Chip { id: "bin".into(), label: say(lines, "chips.bin", &[]), count: binned as u32, on: true }); } let pool: Vec<&Entry> = match filter { "bin" => entries.iter().filter(|entry| entry.in_bin).collect(), "all" => live.clone(), "favourites" => live.iter().copied().filter(|entry| entry.favourite).collect(), "passkey" => live.iter().copied().filter(|entry| entry.kind == "passkey" || entry.passkey).collect(), group if GROUPS.iter().any(|(id, _)| *id == group) => live.iter().copied().filter(|entry| in_group(entry, group)).collect(), kind => live.iter().copied().filter(|entry| entry.kind == kind).collect(), }; let query = fold(ask.q.trim()); let terms: Vec<&str> = words(&query).collect(); let searching = !terms.is_empty(); let mut ordered: Vec<(u8, String, &Entry)> = pool .iter() .filter_map(|entry| { let key = sort_key(entry); let rank = if searching { rank_folded(&key, entry, &query, &terms)? } else { 0 }; Some((rank, key, *entry)) }) .collect(); ordered.sort_by(|a, b| (a.0, &a.1, &a.2.id).cmp(&(b.0, &b.1, &b.2.id))); let total = ordered.len() as u32; let after = ask.after.as_deref().and_then(cursor_parts); let start = match &after { Some((rank, key, id)) => ordered.partition_point(|(r, k, e)| (*r, k.as_str(), e.id.as_str()) <= (*rank, key.as_str(), id.as_str())), None => 0, }; let page: Vec<&(u8, String, &Entry)> = ordered[start..].iter().take(ITEMS_PAGE).collect(); let next = (start + page.len() < ordered.len()).then(|| page.last().map(|(rank, key, entry)| cursor_of(*rank, key, &entry.id))).flatten(); let mut sections = Vec::new(); let first_page = after.is_none(); if first_page && !searching && filter == "all" { let mut favs: Vec<&Entry> = live.iter().copied().filter(|entry| entry.favourite).collect(); favs.sort_by_key(|entry| (sort_key(entry), entry.id.clone())); if !favs.is_empty() { sections.push(Section { id: "favourites".into(), title: Some(say(secrets_lines(), "list.favourites", &[])), rows: favs.iter().map(|entry| row(lines, entry, marks)).collect() }); } let mut recent: Vec<&Entry> = live.iter().copied().filter(|entry| entry.last_used.is_some()).collect(); recent.sort_by(|a, b| b.last_used.cmp(&a.last_used).then_with(|| a.id.cmp(&b.id))); recent.truncate(RECENT_ROWS); if !recent.is_empty() { sections.push(Section { id: "recent".into(), title: Some(say(secrets_lines(), "list.recent", &[])), rows: recent.iter().map(|entry| row(lines, entry, marks)).collect() }); } } let (id, title) = match (searching, filter) { (true, _) => ("results", Some(say(lines, "items.results", &[("n", &total.to_string())]))), (false, "bin") => ("bin", Some(say(lines, "items.bin_note", &[]))), (false, "all") if !sections.is_empty() => ("all", Some(say(secrets_lines(), "list.all", &[]))), (false, _) => ("all", None), }; if !page.is_empty() { sections.push(Section { id: id.into(), title, rows: page.iter().map(|(_, _, entry)| row(lines, entry, marks)).collect() }); } let add_act = || act("add", say(lines, "items.add", &[]), "vault.edit", json!({"kind": "login"})); let empty = (total == 0).then(|| match (searching, filter) { (true, _) => Empty { title: say(lines, "items.no_results_title", &[]), body: say(lines, "items.no_results_body", &[]), act: None }, (false, "bin") => Empty { title: say(lines, "items.bin_title", &[]), body: say(lines, "items.bin_empty", &[]), act: None }, (false, "all") => Empty { title: say(lines, "items.empty_title", &[]), body: say(lines, "items.empty_body", &[]), act: Some(add_act()) }, (false, _) => Empty { title: say(lines, "items.empty_filter_title", &[]), body: say(lines, "items.empty_filter_body", &[]), act: None }, }); let bin = (binned > 0 && filter != "bin" && !searching).then(|| act("bin", say(lines, "items.bin_row", &[("n", &binned.to_string())]), "vault.items", json!({"filter": "bin"}))); let kinds = ADD_KINDS .iter() .map(|kind| { let mut pick = act(kind, say(lines, &format!("kinds.{kind}"), &[]), "vault.edit", json!({"kind": kind})); pick.symbol = Some(kind.to_string()); pick }) .collect(); ItemsAnswer { title: say(lines, if filter == "bin" { "items.bin_title" } else { "items.title" }, &[]), search_placeholder: say(lines, "items.search", &[]), q: ask.q.clone(), filter: filter.to_string(), chips, sections, next, total, empty, bin, add: AddMenu { label: say(lines, "items.add", &[]), kinds }, open, }}// ── the second line a phone works out while the vault is open ──────────/// The kinds whose second line comes from the sealed value, not the plain/// columns: a card's last four, a token's masked tail, a file's lines.pub const SECOND_KINDS: &[&str] = &["card", "api_key", "file"];/// A row's second line from its opened payload, or `None` when the plain/// columns already say enough. Never more of a value than a screen of the/// person's own phone shows next to it: a card's last four, a token's/// recognisable prefix and last four, a file's size in lines.pub fn second_line(lines: &LineSet, payload: &crate::vault::SecretPayload) -> Option<String> { use crate::vault::SecretPayload; match payload { SecretPayload::Card { number, .. } => { let digits: String = number.chars().filter(char::is_ascii_digit).collect(); (digits.len() >= 4).then(|| say(lines, "second.card", &[("last", &digits[digits.len() - 4..])])) } SecretPayload::ApiKey { key, .. } => masked_tail(key), SecretPayload::File { content, file_name, store_password, key_password, .. } => { let name = file_name.as_deref().filter(|name| !name.trim().is_empty()); let passwords = [store_password, key_password].iter().filter(|value| value.as_deref().is_some_and(|value| !value.is_empty())).count(); if passwords > 0 { let name = name.unwrap_or_else(|| "File"); return Some(if passwords == 1 { say(lines, "second.keystore_one", &[("name", name)]) } else { say(lines, "second.keystore", &[("name", name), ("n", &passwords.to_string())]) }); } let count = file_lines(content); let lines_word = match count { Some(1) => say(lines, "second.lines_one", &[]), Some(n) => say(lines, "second.lines_many", &[("n", &n.to_string())]), None => return name.map(str::to_string), }; Some(match name { Some(name) => say(lines, "second.file_named", &[("name", name), ("lines", &lines_word)]), None => say(lines, "second.file", &[("lines", &lines_word)]), }) } _ => None, }}/// `sk_test_…4f2a`: the token's own prefix (up to its last `_` or `-` in the/// first twelve characters, which providers use to say what a key is), an/// ellipsis, and the last four. A value of eight characters or fewer shows/// no character at all: there would be too little left hidden.pub fn masked_tail(value: &str) -> Option<String> { let chars: Vec<char> = value.trim().chars().collect(); if chars.len() <= 8 { return Some("••••".into()); } let head: String = chars.iter().take(12).collect(); let cut = head.rfind(['_', '-']).map(|at| head[..=at].chars().count()).filter(|n| *n < chars.len() - 4).unwrap_or(0); let prefix: String = chars[..cut].iter().collect(); let last: String = chars[chars.len() - 4..].iter().collect(); Some(format!("{prefix}…{last}"))}/// How many lines a file's text holds, or `None` for a file that is not text/// (a keystore, an image): base64 that does not decode, or bytes that are not/// UTF-8.pub fn file_lines(content: &str) -> Option<usize> { use base64::Engine as _; let bytes = base64::engine::general_purpose::STANDARD.decode(content.trim()).ok()?; let text = std::str::from_utf8(&bytes).ok()?; if text.is_empty() { return Some(0); } Some(text.lines().count())}