diff --git a/apps-baosec/vault2/locales/i18n.json b/apps-baosec/vault2/locales/i18n.json index 30d4b846d..74a0547a4 100644 --- a/apps-baosec/vault2/locales/i18n.json +++ b/apps-baosec/vault2/locales/i18n.json @@ -504,10 +504,10 @@ "zh": "选择字体" }, "vault.u2f.appinfo.authcount": { - "en": "Usage count: ", - "en-tts": "Usage count: ", - "fr": "Nombre d’usages: ", - "ja": "使用回数: ", + "en": "Uses: ", + "en-tts": "Uses: ", + "fr": "Usages : ", + "ja": "使用数: ", "zh": "使用次数: " }, "vault.u2f.appinfo.days_ago": { diff --git a/apps-baosec/vault2/src/actions.rs b/apps-baosec/vault2/src/actions.rs index af86feed0..5c684c388 100644 --- a/apps-baosec/vault2/src/actions.rs +++ b/apps-baosec/vault2/src/actions.rs @@ -1,7 +1,7 @@ use core::convert::TryFrom; use std::cell::RefCell; use std::io::ErrorKind; -use std::io::{Read, Write}; +use std::io::Write; use std::sync::{ Arc, Mutex, atomic::{AtomicBool, Ordering}, @@ -17,7 +17,6 @@ use num_traits::*; use passwords::PasswordGenerator; use pddb::BasisRetentionPolicy; use ux_api::widgets::TextEntryPayload; -use vault2::env::xous::U2F_APP_DICT; use vault2::{ AppInfo, VAULT_ALLOC_HINT, VAULT_PASSWORD_DICT, VAULT_TOTP_DICT, atime_to_str, basis_change, deserialize_app_info, serialize_app_info, utc_now, @@ -506,7 +505,7 @@ impl ActionManager { /// This is mainly used by the autotype routine to ensure that the single entry that /// was autotyped has an updated atime in the UX; otherwise routines should update /// the cache directly. - pub(crate) fn update_db_entry(&mut self, entry: SelectedEntry) { + pub(crate) fn update_db_entry(&mut self, entry: &SelectedEntry) { match entry.mode { VaultMode::Password => { let choice = storage::ContentKind::Password; @@ -530,109 +529,12 @@ impl ActionManager { }; } - pub(crate) fn menu_edit(&mut self, entry: SelectedEntry) { + pub(crate) fn menu_edit(&mut self, entry: &SelectedEntry) { let choice = match entry.mode { - VaultMode::Password => Some(storage::ContentKind::Password), - VaultMode::Totp => Some(storage::ContentKind::TOTP), + VaultMode::Password => storage::ContentKind::Password, + VaultMode::Totp => storage::ContentKind::TOTP, }; - if choice.is_none() { - let dict = U2F_APP_DICT; - // at the moment only U2F records are supported for editing. The FIDO2 stuff is done with a - // different record storage format that's a bit funkier to edit. - let maybe_update = match self.pddb.borrow().get( - dict, - &entry.key_guid, - None, - false, - false, - None, - Some(basis_change), - ) { - Ok(mut record) => { - // resolve the basis of the key, so that we are editing it "in place" - let attr = record.attributes().expect("couldn't get key attributes"); - let mut data = Vec::::new(); - let maybe_update = match record.read_to_end(&mut data) { - Ok(_len) => { - if let Some(mut ai) = deserialize_app_info(data) { - let edit_data = if ai.notes != t!("vault.notes", locales::LANG) { - self.modals - .alert_builder(t!("vault.edit_dialog", locales::LANG)) - .field_placeholder_persist(Some(ai.name), Some(password_validator)) - .field_placeholder_persist(Some(ai.notes), Some(password_validator)) - .field_placeholder_persist(Some(hex::encode(ai.id)), None) - .build() - .expect("modals error in edit") - } else { - self.modals - .alert_builder(t!("vault.edit_dialog", locales::LANG)) - .field_placeholder_persist(Some(ai.name), Some(password_validator)) - .field(Some(ai.notes), Some(password_validator)) - .field_placeholder_persist(Some(hex::encode(ai.id)), None) - .build() - .expect("modals error in edit") - }; - ai.name = edit_data.content()[0].content.as_str().to_string(); - ai.notes = edit_data.content()[1].content.as_str().to_string(); - ai.atime = 0; - ai - } else { - self.report_err( - t!("vault.error.record_error", locales::LANG), - None::, - ); - return; - } - } - Err(e) => { - self.report_err(t!("vault.error.internal_error", locales::LANG), Some(e)); - return; - } - }; - Some((maybe_update, attr.basis)) - } - Err(e) => { - match e.kind() { - std::io::ErrorKind::NotFound => { - self.report_err(t!("vault.error.fido2", locales::LANG), None::) - } - _ => self.report_err(t!("vault.error.internal_error", locales::LANG), Some(e)), - } - return; - } - }; - if let Some((update, basis)) = maybe_update { - self.pddb.borrow().delete_key(dict, entry.key_guid.as_str(), Some(&basis)).unwrap_or_else( - |e| self.report_err(t!("vault.error.internal_error", locales::LANG), Some(e)), - ); - match self.pddb.borrow().get( - dict, - entry.key_guid.as_str(), - Some(&basis), - false, - true, - Some(VAULT_ALLOC_HINT), - Some(basis_change), - ) { - Ok(mut record) => { - let ser = serialize_app_info(&update); - record.write(&ser).unwrap_or_else(|e| { - self.report_err(t!("vault.error.internal_error", locales::LANG), Some(e)); - 0 - }); - // update the item cache so it appears on the screen - let li = make_u2f_item_from_record(entry.key_guid.as_str(), update); - self.item_lists.lock().unwrap().insert_unique(self.mode_cache, li); - } - Err(e) => self.report_err(t!("vault.error.internal_error", locales::LANG), Some(e)), - } - } - self.pddb.borrow().sync().ok(); - return; - } - - let choice = choice.unwrap(); let key_guid = entry.key_guid.as_str(); let mut storage = self.storage.borrow_mut(); @@ -648,7 +550,7 @@ impl ActionManager { let edit_data = if pw.notes != t!("vault.notes", locales::LANG) { self.modals - .alert_builder(t!("vault.edit_dialog", locales::LANG)) + .alert_builder("") .field_placeholder_persist(Some(pw.name), Some(password_validator)) .field_placeholder_persist(Some(pw.secret), Some(password_validator)) .field_placeholder_persist(Some(pw.notes), Some(password_validator)) @@ -663,7 +565,7 @@ impl ActionManager { .expect("modals error in edit") } else { self.modals - .alert_builder(t!("vault.edit_dialog", locales::LANG)) + .alert_builder("") .field_placeholder_persist(Some(pw.name), Some(password_validator)) .field_placeholder_persist(Some(pw.secret), Some(password_validator)) .field(Some(pw.notes), Some(password_validator)) @@ -727,7 +629,7 @@ impl ActionManager { // display previous data for edit let edit_data = if pw.notes != t!("vault.notes", locales::LANG) { self.modals - .alert_builder(t!("vault.edit_dialog", locales::LANG)) + .alert_builder("") .field_placeholder_persist(Some(pw.description), Some(password_validator)) .field_placeholder_persist(Some(pw.username), Some(password_validator)) .field_placeholder_persist(Some(pw.password), Some(password_validator)) @@ -738,7 +640,7 @@ impl ActionManager { } else { // note is placeholder text, treat it as such self.modals - .alert_builder(t!("vault.edit_dialog", locales::LANG)) + .alert_builder("") .field_placeholder_persist(Some(pw.description), Some(password_validator)) .field_placeholder_persist(Some(pw.username), Some(password_validator)) .field_placeholder_persist(Some(pw.password), Some(password_validator)) @@ -961,6 +863,7 @@ impl ActionManager { log::debug!("heap usage A: {}", heap_usage()); match self.mode_cache { VaultMode::Password => { + use std::fmt::Write; self.modals .dynamic_notification(Some(t!("vault.reloading_database", locales::LANG)), None) .ok(); @@ -971,7 +874,7 @@ impl ActionManager { let mut oom_keys = 0; // allocate a re-usable temporary buffers, to avoid triggering allocs let mut pw_rec = PasswordRecord::alloc(); - let mut extra = String::with_capacity(256); + let mut extra = String::with_capacity(16); let mut desc = String::with_capacity(256); let mut lookup_key = ListKey::reserved(); let mut il = self.item_lists.lock().unwrap(); @@ -990,17 +893,10 @@ impl ActionManager { lookup_key.reset_from_parts(&desc, &key.name); if let Some(prev_entry) = il.get(self.mode_cache, &lookup_key) { - prev_entry.dirty = true; if prev_entry.atime != pw_rec.atime || prev_entry.count != pw_rec.count { - // this is expensive, so don't run it unless we have to - let human_time = atime_to_str(pw_rec.atime); - // note this code is duplicated in make_pw_item_from_record() - extra.push_str(&human_time); - extra.push_str("; "); - extra.push_str(t!("vault.u2f.appinfo.authcount", locales::LANG)); - extra.push_str(&pw_rec.count.to_string()); + write!(extra, "[{}]", pw_rec.count).ok(); prev_entry.extra.clear(); prev_entry.extra.push_str(&extra); } @@ -1014,18 +910,11 @@ impl ActionManager { prev_entry.guid.push_str(&key.name); } } else { - let human_time = atime_to_str(pw_rec.atime); - - extra.push_str(&human_time); - extra.push_str("; "); - extra.push_str(t!("vault.u2f.appinfo.authcount", locales::LANG)); - extra.push_str(&pw_rec.count.to_string()); - + write!(extra, "[{}]", pw_rec.count).ok(); let li = ListItem::new( desc.to_string(), /* these allocs will be slow, but we do it * only once on boot */ - extra.to_string(), - true, + extra.to_owned(), key.name, pw_rec.atime, pw_rec.count, @@ -1555,22 +1444,11 @@ pub(crate) fn heap_usage() -> usize { } } -fn make_pw_name(description: &str, _username: &str, dest: &mut String) { +fn make_pw_name(description: &str, username: &str, dest: &mut String) { dest.clear(); dest.push_str(description); - // dest.push_str("/"); - // dest.push_str(username); -} - -fn make_u2f_item_from_record(guid: &str, ai: AppInfo) -> ListItem { - let extra = format!( - "{}; {}{}", - atime_to_str(ai.atime), - t!("vault.u2f.appinfo.authcount", locales::LANG), - ai.count, - ); - let desc: String = format!("{} (U2F)", ai.name); - ListItem::new(desc, extra, true, guid.to_owned(), ai.count, ai.atime) + dest.push_str("/"); + dest.push_str(username); } fn make_totp_item_from_record(guid: &str, totp: TotpRecord) -> ListItem { @@ -1583,7 +1461,7 @@ fn make_totp_item_from_record(guid: &str, totp: TotpRecord) -> ListItem { if totp.is_hotp { "HOTP" } else { "TOTP" } ); let desc = format!("{}", totp.name); - ListItem::new(desc, extra, true, guid.to_owned(), 0, 0) + ListItem::new(desc, extra, guid.to_owned(), 0, 0) } fn make_pw_item_from_record(guid: &str, pw: PasswordRecord) -> ListItem { // create the list item from the updated entry @@ -1598,7 +1476,6 @@ fn make_pw_item_from_record(guid: &str, pw: PasswordRecord) -> ListItem { ListItem::new( desc.to_string(), // these allocs will be slow, but we do it only once on boot extra.to_string(), - true, guid.to_string(), pw.atime, pw.count, diff --git a/apps-baosec/vault2/src/itemcache.rs b/apps-baosec/vault2/src/itemcache.rs index feb1278a3..5c2c641f2 100644 --- a/apps-baosec/vault2/src/itemcache.rs +++ b/apps-baosec/vault2/src/itemcache.rs @@ -2,8 +2,7 @@ use core::num::NonZeroUsize; use std::cmp::Ordering; use std::ops::Range; -use crate::ux::NavDir; -use crate::{SelectedEntry, VaultMode}; +use crate::VaultMode; pub struct ListKey { pub name: String, @@ -58,13 +57,11 @@ impl PartialEq for ListKey { /// Display list for items. "name" is the key by which the list is sorted. /// "extra" is more information about the item, which should not be part of the sort. -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct ListItem { name: String, sortable_name: String, pub extra: String, - /// used by drawing routines to optimize refresh time - pub dirty: bool, /// this is the name of the key used to refer to the item pub guid: String, /// stash a copy so we can compare to the DB record and avoid re-generating the atime/count string if it @@ -105,9 +102,9 @@ impl PartialEq for ListItem { impl Eq for ListItem {} impl ListItem { - pub fn new(name: String, extra: String, dirty: bool, guid: String, atime: u64, count: u64) -> Self { + pub fn new(name: String, extra: String, guid: String, atime: u64, count: u64) -> Self { let sortable_name = name.to_lowercase(); - Self { name, sortable_name, extra, dirty, guid, atime, count } + Self { name, sortable_name, extra, guid, atime, count } } /// This is made available for edit/delete routines to generate the key without having to @@ -136,7 +133,6 @@ pub struct FilteredListView { // on the heap to copy data. list: Vec, sorted: bool, - selection_index: usize, items_per_screen: NonZeroUsize, filter_range: Option>, } @@ -146,7 +142,6 @@ impl FilteredListView { Self { list: Vec::new(), sorted: false, - selection_index: 0, items_per_screen: NonZeroUsize::new(1).unwrap(), filter_range: None, } @@ -165,16 +160,10 @@ impl FilteredListView { log::debug!("filter clear"); self.list.clear(); self.sorted = false; - self.selection_index = 0; self.filter_range = None; } pub fn set_items_per_screen(&mut self, ips: usize) { - if ips != self.items_per_screen.get() { - for item in self.list.iter_mut() { - item.dirty = true; - } - } self.items_per_screen = NonZeroUsize::new(ips).unwrap_or(NonZeroUsize::new(1).unwrap()); } @@ -266,31 +255,9 @@ impl FilteredListView { } } } - //ts[4] = tt.elapsed_ms(); - if let Some(r) = &self.filter_range { - if self.selection_index >= r.len() { - self.selection_index = 0; - } - } - self.mark_filtered_as_dirty(); - //ts[5] = tt.elapsed_ms(); - //for(index, &elapsed) in ts[1..].iter().enumerate() { - // log::info!("{}: {}", index + 1, elapsed.saturating_sub(ts[0])); - //} } - fn mark_filtered_as_dirty(&mut self) { - if let Some(r) = self.filter_range.clone() { - for i in self.list[r].iter_mut() { - i.dirty = true; - } - } - } - - pub fn filter_reset(&mut self) { - self.filter_range = Some(0..self.list.len()); - self.mark_filtered_as_dirty(); - } + pub fn filter_reset(&mut self) { self.filter_range = Some(0..self.list.len()); } pub fn filter_len(&self) -> usize { if let Some(r) = &self.filter_range { @@ -302,134 +269,9 @@ impl FilteredListView { } } - pub fn mark_all_dirty(&mut self) { - for item in self.list.iter_mut() { - item.dirty = true; - } - } - - fn mark_filtered_selection_as_dirty(&mut self, index: usize) { - let index = index + self.filter_start(); - if index < self.list.len() { - self.list[index].dirty = true; - } - } - - fn mark_filtered_screen_as_dirty(&mut self, index: usize) { - let index = index + self.filter_start(); - let page = index / self.items_per_screen.get(); - let listlen = self.list.len(); - for item in self.list[((page as usize) * self.items_per_screen.get()).min(listlen) - ..((1 + page as usize) * self.items_per_screen.get()).min(listlen)] - .iter_mut() - { - item.dirty = true; - } - } - fn filter_start(&self) -> usize { self.filter_range.clone().unwrap_or(0..0).start } - pub fn get_page(&self) -> usize { self.selection_index / self.items_per_screen.get() } - - pub fn selected_index(&self) -> usize { self.selection_index % self.items_per_screen.get() } - - pub fn selected_page(&mut self) -> &mut [ListItem] { - let filterlen = self.filter_len(); - let page = self.get_page(); - let filtered_range = &mut self.list[self.filter_range.clone().unwrap_or(0..0)]; - &mut filtered_range[(page * self.items_per_screen.get()).min(filterlen) - ..((1 + page) * self.items_per_screen.get()).min(filterlen)] - } - pub fn full_list(&mut self) -> &mut [ListItem] { &mut self.list[..] } - - pub fn nav(&mut self, dir: NavDir) { - log::debug!("index bef: {}, filter: {:?}", self.selection_index, self.filter_range); - match dir { - NavDir::Up => { - if self.selection_index > 0 { - let starting_page = self.get_page(); - self.mark_filtered_selection_as_dirty(self.selection_index); - self.selection_index -= 1; - self.mark_filtered_selection_as_dirty(self.selection_index); - if starting_page != self.get_page() { - self.mark_filtered_screen_as_dirty(self.selection_index); - } - } - } - NavDir::Down => { - if self.selection_index < self.filter_len() { - let starting_page = self.get_page(); - self.mark_filtered_selection_as_dirty(self.selection_index); - self.selection_index += 1; - self.mark_filtered_selection_as_dirty(self.selection_index); - if starting_page != self.get_page() { - self.mark_filtered_screen_as_dirty(self.selection_index); - } - } - } - NavDir::PageUp => { - if self.selection_index > self.items_per_screen.get() { - self.mark_filtered_screen_as_dirty(self.selection_index); - self.selection_index -= self.items_per_screen.get(); - self.mark_filtered_screen_as_dirty(self.selection_index); - } else { - self.mark_filtered_selection_as_dirty(self.selection_index); - self.selection_index = 0; - self.mark_filtered_selection_as_dirty(self.selection_index); - } - } - NavDir::PageDown => { - if self.selection_index < self.filter_len() - self.items_per_screen.get() { - self.mark_filtered_screen_as_dirty(self.selection_index); - self.selection_index += self.items_per_screen.get(); - self.mark_filtered_screen_as_dirty(self.selection_index); - } else { - self.mark_filtered_selection_as_dirty(self.selection_index); - self.selection_index = self.filter_len() - 1; - self.mark_filtered_selection_as_dirty(self.selection_index); - } - } - } - log::debug!("index after: {}", self.selection_index); - } - - pub fn selected_guid(&self) -> String { - self.list[self.selection_index + self.filter_start()].guid.to_owned() - } - - pub fn selected_extra(&self) -> String { - self.list[self.selection_index + self.filter_start()].extra.to_owned() - } - - pub fn selected_update_extra(&mut self, extra: String) { - let start = self.filter_start(); - self.list[self.selection_index + start].extra = extra - } - - pub fn selected_update_atime(&mut self, atime: u64) { - let start = self.filter_start(); - self.list[self.selection_index + start].atime = atime - } - - pub fn selected_entry(&self, mode: VaultMode) -> Option { - if let Some(r) = self.filter_range.clone() { - log::debug!("filter range: {:?}", r); - log::debug!("selection index: {}", self.selection_index); - log::debug!("filter start: {}", self.filter_start()); - if r.contains(&(self.selection_index + self.filter_start())) { - Some(SelectedEntry { - key_guid: String::from(&self.list[self.selection_index + self.filter_start()].guid), - description: String::from(&self.list[self.selection_index + self.filter_start()].name), - mode, - }) - } else { - None - } - } else { - None - } - } } pub struct ItemLists { totp: FilteredListView, @@ -478,11 +320,6 @@ impl ItemLists { self.pw.set_items_per_screen(ips as usize); } - pub fn mark_all_dirty(&mut self) { - self.totp.mark_all_dirty(); - self.pw.mark_all_dirty(); - } - pub fn clear_filter(&mut self) {} pub fn clear(&mut self, list_type: VaultMode) { self.li_mut(list_type).clear(); } @@ -502,30 +339,6 @@ impl ItemLists { pub fn filter_len(&self, list_type: VaultMode) -> usize { self.li(list_type).filter_len() } - pub fn nav(&mut self, list_type: VaultMode, dir: NavDir) { self.li_mut(list_type).nav(dir); } - - pub fn selected_index(&self, list_type: VaultMode) -> usize { self.li(list_type).selected_index() } - - pub fn selected_guid(&self, list_type: VaultMode) -> String { self.li(list_type).selected_guid() } - - pub fn selected_extra(&self, list_type: VaultMode) -> String { self.li(list_type).selected_extra() } - - pub fn selected_update_extra(&mut self, list_type: VaultMode, extra: String) { - self.li_mut(list_type).selected_update_extra(extra) - } - - pub fn selected_update_atime(&mut self, list_type: VaultMode, atime: u64) { - self.li_mut(list_type).selected_update_atime(atime) - } - - pub fn selected_entry(&self, list_type: VaultMode) -> Option { - self.li(list_type).selected_entry(list_type) - } - - pub fn selected_page(&mut self, list_type: VaultMode) -> &mut [ListItem] { - self.li_mut(list_type).selected_page() - } - pub fn full_list(&mut self, list_type: VaultMode) -> &mut [ListItem] { self.li_mut(list_type).full_list() } diff --git a/apps-baosec/vault2/src/main.rs b/apps-baosec/vault2/src/main.rs index 2458d9df2..4059fa290 100644 --- a/apps-baosec/vault2/src/main.rs +++ b/apps-baosec/vault2/src/main.rs @@ -8,6 +8,7 @@ mod storage; mod submenu; mod totp; pub mod vault_api; +use ux_api::service::gfx::Gfx; pub use vault_api::*; mod vendor_commands; @@ -34,10 +35,6 @@ use crate::vendor_commands::VendorSession; /* Dev status & notes -- -Nov 12 2025: - -`cargo xtask baosec-emu` will launch the emulated UI. - UI interaction planning. Main mode of interaction is QR code scanning. This should be accessible with a single button. Thus: @@ -59,6 +56,17 @@ we *could*, possibly, if we really needed menu hierarchies, repurpose a left/rig a hierarchy nav function. -> But can we keep the menu shallow? + +Architectural notes -- + +Data is long-term stored in the PDDB. Each of the three modes have their own dictionary +(OpenSK/FIDO2, passwords, totp). + +The data is read into an `ItemList`, which is a RAM-based structure that caches all the PDDB data for +fast sorting, searching etc. `ItemList` is where meta-operations like search & sort happen. + +For rendering the data is then copied into a UI element, such as a `ScrollableList`, based on +the currently active mode. */ pub(crate) const SERVER_NAME_VAULT2: &str = "_Vault2_"; @@ -78,7 +86,7 @@ pub struct SelectedEntry { fn main() -> ! { log_server::init_wait().unwrap(); - log::set_max_level(log::LevelFilter::Debug); + log::set_max_level(log::LevelFilter::Info); log::info!("Vault2 PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); @@ -106,9 +114,10 @@ fn main() -> ! { crate::totp::pumper(mode.clone(), pump_sid, conn, allow_totp_rendering.clone()); let pump_conn = xous::connect(pump_sid).unwrap(); - // respond to keyboard events - let kbd = bao1x_api::keyboard::Keyboard::new(&xns).unwrap(); - kbd.register_listener(SERVER_NAME_VAULT2, VaultOp::KeyPress.to_u32().unwrap() as usize); + // respond to keyboard events - register with the `Gfx` subsystem, so we're getting keypresses + // filtered by the modals interface + let gfx = Gfx::new(&xns).unwrap(); + gfx.register_listener(SERVER_NAME_VAULT2, VaultOp::KeyPress.to_u32().unwrap() as usize); // spawn the actions server. This is responsible for grooming the UX elements. It // has to be in its own thread because it uses blocking modal calls that would cause @@ -147,7 +156,8 @@ fn main() -> ! { unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let entry = buffer.to_original::().unwrap(); manager.activate(); - manager.menu_edit(entry); // this is responsible for updating the item cache + manager.menu_edit(&entry); // this is responsible for updating the item cache + manager.update_db_entry(&entry); manager.deactivate(); } Some(ActionOp::MenuUnlockBasis) => { @@ -175,7 +185,7 @@ fn main() -> ! { unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let entry = buffer.to_original::().unwrap(); manager.activate(); - manager.update_db_entry(entry); + manager.update_db_entry(&entry); manager.deactivate(); } Some(ActionOp::UpdateMode) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { @@ -339,7 +349,7 @@ fn main() -> ! { xous::Message::new_blocking_scalar(ActionOp::ReloadDb.to_usize().unwrap(), 0, 0, 0, 0), ) .ok(); - vault_ui.refresh_totp(); + vault_ui.refresh_draw_list(); // kickstart the pumper xous::send_message(pump_conn, xous::Message::new_scalar(PumpOp::Pump.to_usize().unwrap(), 0, 0, 0, 0)) @@ -358,13 +368,13 @@ fn main() -> ! { xous::Message::new_blocking_scalar(ActionOp::ReloadDb.to_usize().unwrap(), 0, 0, 0, 0), ) .ok(); - vault_ui.refresh_totp(); + vault_ui.refresh_draw_list(); vault_ui.redraw(); } Some(VaultOp::MenuDone) => { menu_active = false; // update the TOTP codes, in case there were changes - vault_ui.refresh_totp(); + vault_ui.refresh_draw_list(); allow_totp_rendering.store(true, Ordering::SeqCst); vault_ui.redraw(); } @@ -376,7 +386,7 @@ fn main() -> ! { xous::Message::new_blocking_scalar(ActionOp::ReloadDb.to_usize().unwrap(), 0, 0, 0, 0), ) .ok(); - vault_ui.refresh_totp(); + vault_ui.refresh_draw_list(); allow_totp_rendering.store(true, Ordering::SeqCst); xous::send_message( pump_conn, @@ -386,7 +396,10 @@ fn main() -> ! { vault_ui.redraw(); } Some(VaultOp::MenuPwMode) => { - *mode.lock().unwrap() = VaultMode::Password; + { + // lock needs to go out of scope so we don't hang the later ops + *mode.lock().unwrap() = VaultMode::Password; + } allow_totp_rendering.store(false, Ordering::SeqCst); // reload DB on mode switch xous::send_message( @@ -417,11 +430,11 @@ fn main() -> ! { vault_ui.redraw(); } '←' => { - vault_ui.nav(NavDir::PageUp); + vault_ui.nav(NavDir::Autotype); vault_ui.redraw(); } '→' => { - vault_ui.nav(NavDir::PageDown); + vault_ui.nav(NavDir::Reserved); vault_ui.redraw(); } '🔥' => { @@ -453,7 +466,7 @@ fn main() -> ! { ) .ok(); if *mode.lock().unwrap() == VaultMode::Totp { - vault_ui.refresh_totp(); + vault_ui.refresh_draw_list(); } vault_ui.redraw(); } @@ -467,16 +480,16 @@ fn main() -> ! { // stage 1 happens here because the filtered list and selection entry are in the responsive UX // section. log::debug!("selecting entry for edit"); + // this will block redraws + allow_totp_rendering.store(false, Ordering::SeqCst); if let Some(entry) = vault_ui.selected_entry() { let buf = Buffer::into_buf(entry).expect("IPC error"); - buf.send(actions_conn, ActionOp::MenuEditStage2.to_u32().unwrap()) + buf.lend(actions_conn, ActionOp::MenuEditStage2.to_u32().unwrap()) .expect("messaging error"); } else { - // this will block redraws - allow_totp_rendering.store(false, Ordering::SeqCst); modals.show_notification(t!("vault.error.nothing_selected", locales::LANG), None).ok(); - allow_totp_rendering.store(true, Ordering::SeqCst); } + allow_totp_rendering.store(true, Ordering::SeqCst); } Some(VaultOp::MenuChangeFont) => { for item in FONT_LIST { diff --git a/apps-baosec/vault2/src/submenu.rs b/apps-baosec/vault2/src/submenu.rs index 0db4ece67..219afe2bc 100644 --- a/apps-baosec/vault2/src/submenu.rs +++ b/apps-baosec/vault2/src/submenu.rs @@ -37,13 +37,6 @@ pub fn create_submenu(vault_conn: xous::CID, actions_conn: xous::CID, menu_mgr: action_payload: MenuPayload::Scalar([0, 0, 0, 0]), close_on_select: true, }); - menu_items.push(MenuItem { - name: String::from(t!("vault.menu_change_font", locales::LANG)), - action_conn: Some(vault_conn), - action_opcode: VaultOp::MenuChangeFont.to_u32().unwrap(), - action_payload: MenuPayload::Scalar([0, 0, 0, 0]), - close_on_select: true, - }); #[cfg(feature = "vault-testing")] menu_items.push(MenuItem { name: String::from("Generate test vectors"), @@ -53,9 +46,9 @@ pub fn create_submenu(vault_conn: xous::CID, actions_conn: xous::CID, menu_mgr: close_on_select: true, }); menu_items.push(MenuItem { - name: String::from(t!("prefs.autotype_rate", locales::LANG)), + name: String::from(t!("vault.menu_change_font", locales::LANG)), action_conn: Some(vault_conn), - action_opcode: VaultOp::MenuAutotypeRate.to_u32().unwrap(), + action_opcode: VaultOp::MenuChangeFont.to_u32().unwrap(), action_payload: MenuPayload::Scalar([0, 0, 0, 0]), close_on_select: true, }); diff --git a/apps-baosec/vault2/src/ux.rs b/apps-baosec/vault2/src/ux.rs index 58434cf9d..ae18e7eb1 100644 --- a/apps-baosec/vault2/src/ux.rs +++ b/apps-baosec/vault2/src/ux.rs @@ -12,6 +12,11 @@ use xous::CID; use crate::storage::{ContentKind, Manager}; use crate::*; +const FAST_SCROLL_DELAY_MS: u64 = 1300; +const KEYUP_DELAY_MS: u64 = 100; +/// How many elements to skip through on fast scroll +const PAGE_INCREMENT: usize = 6; + pub const DEFAULT_FONT: GlyphStyle = GlyphStyle::Regular; pub const FONT_LIST: [&'static str; 6] = ["regular", "tall", "mono", "bold", "large", "small"]; pub fn name_to_style(name: &str) -> Option { @@ -44,8 +49,8 @@ const VAULT_CONFIG_KEY_FONT: &'static str = "fontstyle"; pub enum NavDir { Up, Down, - PageUp, - PageDown, + Autotype, + Reserved, } /// Centralizes tunable UI parameters for TOTP @@ -73,7 +78,7 @@ impl TotpLayout { pub struct VaultUi { main_cid: CID, gfx: Gfx, - totp_list: ScrollableList, + display_list: ScrollableList, item_lists: Arc>, mode: Arc>, @@ -87,6 +92,9 @@ pub struct VaultUi { storage_manager: Manager, usb_dev: usb_bao1x::UsbHid, + last_key_time: u64, + start_hold_time: u64, + tt: ticktimer_server::Ticktimer, } impl VaultUi { @@ -104,6 +112,8 @@ impl VaultUi { .style(TotpLayout::list_font()); totp_list.set_autoflush(false); + let tt = ticktimer_server::Ticktimer::new().unwrap(); + let now = tt.elapsed_ms(); let gfx = Gfx::new(&xns).unwrap(); let style = DEFAULT_FONT; let glyph_height = gfx.glyph_height_hint(style).unwrap() as isize; @@ -111,7 +121,7 @@ impl VaultUi { Self { main_cid: cid, gfx, - totp_list, + display_list: totp_list, item_lists, mode, totp_code: None, @@ -121,21 +131,34 @@ impl VaultUi { style, storage_manager: Manager::new(xns), usb_dev: usb_bao1x::UsbHid::new(), + tt, + last_key_time: now, + start_hold_time: now, } } - pub(crate) fn refresh_totp(&mut self) { - let mut locked_lists = self.item_lists.lock().unwrap(); - let full_list = locked_lists.full_list(VaultMode::Totp); - self.totp_list.clear(); + pub(crate) fn refresh_draw_list(&mut self) { + let mode = { (*self.mode.lock().unwrap()).clone() }; + + let mut locked_lists = if let Ok(g) = self.item_lists.try_lock() { + g + } else { + log::warn!("Couldn't get lock in refresh_draw_list; aborting the refresh"); + return; + }; + let full_list = locked_lists.full_list(mode); + self.display_list.clear(); for item in full_list { - self.totp_list.add_item(0, &item.name()); + self.display_list.add_item(0, &item.name()); } } pub(crate) fn update_selected_totp_code(&mut self) -> Option { - if self.totp_list.len() > 0 { - let selected = self.totp_list.get_selected(); + if *self.mode.lock().unwrap() != VaultMode::Totp { + return None; + } + if self.display_list.len() > 0 { + let selected = self.display_list.get_selected(); let mut locked_lists = self.item_lists.lock().unwrap(); let full_list = locked_lists.full_list(VaultMode::Totp); if let Some(selected_item) = full_list.iter().find(|item| item.name() == selected) { @@ -157,16 +180,38 @@ impl VaultUi { } } + pub(crate) fn get_selected_item(&self) -> Option { + let mode = *self.mode.lock().unwrap(); + if self.display_list.len() > 0 { + let selected = self.display_list.get_selected(); + let mut locked_lists = self.item_lists.lock().unwrap(); + let full_list = locked_lists.full_list(mode); + full_list.iter().find(|&item| item.name() == selected).cloned() + } else { + None + } + } + + pub(crate) fn selected_entry(&self) -> Option { + let mode = *self.mode.lock().unwrap(); + if let Some(li) = self.get_selected_item() { + let name = li.name().to_owned(); + Some(SelectedEntry { key_guid: li.guid, description: name, mode }) + } else { + None + } + } + pub(crate) fn basis_change(&mut self) { self.item_lists.lock().unwrap().clear_all(); - self.totp_list.clear(); + self.display_list.clear(); } pub(crate) fn store_glyph_style(&mut self, style: GlyphStyle) { self.pddb .borrow() .delete_key(VAULT_CONFIG_DICT, VAULT_CONFIG_KEY_FONT, Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS)) - .expect("couldn't delete previous setting"); + .ok(); match self.pddb.borrow().get( VAULT_CONFIG_DICT, @@ -215,7 +260,7 @@ impl VaultUi { GlyphStyle::Regular } }; - self.totp_list.style(style); + self.display_list.style(style); let glyph_height = self.gfx.glyph_height_hint(style).unwrap(); self.item_height = glyph_height as isize + 2; // +2 because of the border width self.item_lists.lock().unwrap().set_items_per_screen( @@ -253,7 +298,7 @@ impl VaultUi { tv.style = TotpLayout::totp_font(); tv.draw_border = false; - if self.totp_code.is_none() && self.totp_list.len() > 0 { + if self.totp_code.is_none() && self.display_list.len() > 0 { // this handles initial population of the field self.update_selected_totp_code(); } @@ -269,7 +314,7 @@ impl VaultUi { self.gfx.draw_textview(&mut tv).expect("couldn't draw text"); // list of codes to pick from - self.totp_list.draw(TotpLayout::timer_box().br().y); + self.display_list.draw(TotpLayout::timer_box().br().y); // draw the timer element let mut object_list = ObjectList::new(); @@ -300,36 +345,6 @@ impl VaultUi { self.gfx.draw_object_list(object_list).unwrap(); } VaultMode::Password => { - /* - Password UI -- - - Home menu: - - > Search by QR code - > Search by text entry - > Enter new by QR code - > Enter new by text entry - - Prefix entered: - - --------------------- - | Selected Domain | - | Selected Username | - --------------------- - > Domain short 1 - > Domain short 2 - > Domain short 3 - > Domain short 4 - > search prefix < - - - Scrolling down to search prefix and hitting home brings up keyboard UI - - Left-right would page through prefixed entries - - Up down would page through just the current page of entries (allowing selection of search prefix region) - - Selecting search prefix brings up the alphabetic entry UI - - Pressing in on scroll button raises a new menu for "autotype password" + "delete passsword" + "edit password" options - - Pressing on circle middle button just does autotype - - */ let screensize = self.gfx.screen_size().unwrap(); // handle empty database case if self.item_lists.lock().unwrap().filter_len(VaultMode::Password) == 0 { @@ -343,67 +358,37 @@ impl VaultUi { ); box_text.draw_border = false; box_text.clear_area = true; + box_text.invert = true; box_text.style = self.style; write!(box_text, "{}", t!("vault.no_items", locales::LANG)).ok(); self.gfx.draw_textview(&mut box_text).expect("couldn't post empty notification"); self.gfx.flush().ok(); return; } + + // ---- draw the top "detail info" about the selected password ---- let mut insert_at = 0; - if let Some(entry) = self.item_lists.lock().unwrap().selected_entry(VaultMode::Password) { + if let Some(entry) = self.get_selected_item() { log::debug!("rendering entry {:?}", entry); // draw more data about the selected item - let guid = entry.key_guid.as_str(); - let pw: storage::PasswordRecord = - match self.storage_manager.get_record(&ContentKind::Password, guid) { - Ok(record) => record, - Err(error) => { - log::error!("internal error rendering password: {:?}", error); - self.gfx.flush().ok(); - return; - } - }; let mut box_text = TextView::new( Gid::dummy(), - TextBounds::CenteredBot(Rectangle::new( + TextBounds::CenteredTop(Rectangle::new( Point::new(0, insert_at), - Point::new(screensize.x, insert_at + self.item_height), + Point::new(screensize.x, insert_at + self.item_height * 3), )), ); - insert_at += self.item_height; box_text.draw_border = false; box_text.clear_area = false; box_text.ellipsis = true; box_text.style = self.style; box_text.invert = true; // line 1 - write!(box_text, "{}", &pw.description).ok(); + write!(box_text, "{} {}", &entry.name(), &entry.extra).ok(); self.gfx.draw_textview(&mut box_text).unwrap(); - // line 2 - box_text.bounds_hint = TextBounds::CenteredBot(Rectangle::new( - Point::new(0, insert_at), - Point::new(screensize.x, insert_at + self.item_height), - )); - insert_at += self.item_height; - box_text.clear_str(); - write!(box_text, "{}", &pw.username).ok(); - self.gfx.draw_textview(&mut box_text).ok(); - // draw a rectangle around the top area - self.gfx - .draw_rectangle(Rectangle::new_coords_with_style( - 0, - 0, - screensize.x, - self.item_height * 2, - DrawStyle { - fill_color: None, - stroke_color: Some(PixelColor::Light), - stroke_width: 2, - }, - )) - .ok(); + insert_at += box_text.bounds_computed.unwrap().height() as isize; } else { - // draw a rectangle around the top area + // draw just the empty rectangle around the top area if nothing is selected self.gfx .draw_rectangle(Rectangle::new_coords_with_style( 0, @@ -420,78 +405,66 @@ impl VaultUi { log::error!("Couldn't retrieve password info to render top area"); insert_at = self.item_height * 2; }; - // ---- draw list body area ---- - let selected = self.item_lists.lock().unwrap().selected_index(VaultMode::Password); - let mut guarded_list = self.item_lists.lock().unwrap(); - let current_page = guarded_list.selected_page(VaultMode::Password); - log::debug!("current_page len {}", current_page.len()); - for (index, item) in current_page.iter_mut().enumerate() { - if insert_at - 1 > screensize.y - self.item_height { - // -1 because of the overlapping border - break; - } - log::debug!("drawing {}", item.name()); - let mut box_text = TextView::new( - Gid::dummy(), - TextBounds::BoundingBox(Rectangle::new( - Point::new(0, insert_at), - Point::new(screensize.x, insert_at + self.item_height), - )), - ); - box_text.draw_border = false; - box_text.rounded_border = None; - box_text.clear_area = false; - box_text.style = self.style; - box_text.ellipsis = true; - if index == selected { - box_text.invert = false; - } else { - box_text.invert = true; - } - write!(box_text, "{}", item.name()).ok(); - // do a dry run to get the final bounding box - box_text.set_dry_run(true); - self.gfx.draw_textview(&mut box_text).expect("couldn't post list item"); - if index == selected { - let mut r = box_text.bounds_computed.unwrap(); - r.style = DrawStyle { - fill_color: Some(PixelColor::Light), - stroke_color: None, - stroke_width: 0, - }; - self.gfx.draw_rectangle(r).ok(); - } - // now draw for reals - box_text.set_dry_run(false); - self.gfx.draw_textview(&mut box_text).expect("couldn't post list item"); - - insert_at += self.item_height; - } + self.display_list.draw(insert_at); } } self.gfx.flush().ok(); } + /// Returns `true` if in longpress state. Only call this once per key hit input. + pub(crate) fn manage_longpress(&mut self) -> bool { + let now = self.tt.elapsed_ms(); + if now - self.last_key_time > KEYUP_DELAY_MS { + self.start_hold_time = now; + } + self.last_key_time = now; + now - self.start_hold_time > FAST_SCROLL_DELAY_MS + } + pub(crate) fn nav(&mut self, dir: NavDir) { let mode_at_entry = (*self.mode.lock().unwrap()).clone(); match mode_at_entry { VaultMode::Password => { - self.item_lists.lock().unwrap().nav((*self.mode.lock().unwrap()).clone(), dir); + let increment = if self.manage_longpress() { PAGE_INCREMENT } else { 1 }; + match dir { + NavDir::Up => { + for _ in 0..increment { + self.display_list.key_action('↑'); + } + } + NavDir::Down => { + for _ in 0..increment { + self.display_list.key_action('↓'); + } + } + NavDir::Autotype => { + if let Some(item) = self.get_selected_item() { + // print any errors within this function as a panic at this line + self.handle_autotype(item.guid, false).unwrap(); + } + } + NavDir::Reserved => { + // tbd + } + } } VaultMode::Totp => { match dir { NavDir::Up => { - self.totp_list.key_action('↑'); + self.display_list.key_action('↑'); } NavDir::Down => { - self.totp_list.key_action('↓'); + self.display_list.key_action('↓'); } - _ => { + NavDir::Autotype => { if let Some(code) = self.update_selected_totp_code() { // ignore USB errors while sending code self.usb_dev.send_str(&code).ok(); } } + NavDir::Reserved => { + // tbd + } } self.totp_code = None; } @@ -502,8 +475,50 @@ impl VaultUi { self.item_lists.lock().unwrap().filter(self.mode.lock().unwrap().clone(), criteria); } - pub(crate) fn selected_entry(&self) -> Option { - let mode = (*self.mode.lock().unwrap()).clone(); - self.item_lists.lock().unwrap().selected_entry(mode) + pub(crate) fn handle_autotype(&mut self, guid: String, type_username: bool) -> Result<(), String> { + // we re-fetch the entry for autotype, because the PDDB could have unmounted a basis. + let atime = utc_now().timestamp() as u64; + let pddb_binding = self.pddb.borrow(); + + let mut record = pddb_binding + .get(vault2::VAULT_PASSWORD_DICT, &guid, None, false, false, None, Some(vault2::basis_change)) + .map_err(|e| format!("couldn't access key {}: {:?}", guid, e))?; + let mut data = Vec::::new(); + record.read_to_end(&mut data).map_err(|_| format!("Couldn't access key {}", guid))?; + let mut pw = crate::storage::PasswordRecord::try_from(data) + .map_err(|_| format!("Couldn't deserialize {}", guid))?; + let to_type = if type_username { &pw.username } else { &pw.password }; + self.usb_dev.send_str(to_type).ok(); // ignore USB errors + pw.count += 1; + pw.atime = atime; + + // this get determines which basis the key is in + let app_data = pddb_binding + .get(vault2::VAULT_PASSWORD_DICT, &guid, None, true, true, Some(256), Some(vault2::basis_change)) + .map_err(|e| format!("error updating key atime: {:?}", e))?; + let basis = app_data.attributes().map_err(|_| "couldn't get attributes")?.basis; + + // delete the old key + pddb_binding + .delete_key(vault2::VAULT_PASSWORD_DICT, &guid, Some(&basis)) + .map_err(|_| "Couldn't delete previous pw entry")?; + + // write the new key in + let mut record = pddb_binding + .get( + vault2::VAULT_PASSWORD_DICT, + &guid, + Some(&basis), + false, + true, + Some(vault2::VAULT_ALLOC_HINT), + Some(vault2::basis_change), + ) + .map_err(|e| format!("couldn't update key {}: {:?}", guid, e))?; + let ser: Vec = crate::storage::PasswordRecord::into(pw); + record.write(&ser).map_err(|e| format!("couldn't update key {}: {:?}", guid, e))?; + + self.pddb.borrow().sync().ok(); + Ok(()) } }