From 09046854db073a724822652bc9a512b8ba99451d Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 23 Jun 2022 01:32:06 +0800 Subject: [PATCH] add password edit/delete functions --- apps/vault/locales/i18n.json | 74 +++++++- apps/vault/src/actions.rs | 318 ++++++++++++++++++++++++++++++--- apps/vault/src/ctap/mod.rs | 2 + apps/vault/src/ctap/storage.rs | 2 +- apps/vault/src/main.rs | 70 +++++++- apps/vault/src/submenu.rs | 8 +- apps/vault/src/ux/fido.rs | 20 ++- apps/vault/src/ux/framework.rs | 66 ++++++- 8 files changed, 512 insertions(+), 48 deletions(-) diff --git a/apps/vault/locales/i18n.json b/apps/vault/locales/i18n.json index a3db00f14..7986250a1 100644 --- a/apps/vault/locales/i18n.json +++ b/apps/vault/locales/i18n.json @@ -1,4 +1,70 @@ { + "vault.edit_dialog": { + "en": "Make your changes and press enter.\nUse the d-pad to navigate entries.", + "ja": "変更を加えてEnterキーを押します。 D-PADを使用してエントリをナビゲートします。", + "zh": "进行更改并按 Enter。 使用 D-PAD 导航条目。", + "en-tts": "Make your changes and press enter.\nUse the d-pad to navigate entries." + }, + "vault.notes": { + "en": "Notes", + "ja": "ノート", + "zh": "笔录", + "en-tts": "Notes" + }, + "vault.autotyping": { + "en": "Autotyping...", + "ja": "今すぐ自動入力...", + "zh": "现在自动输入...", + "en-tts": "Autotyping..." + }, + "vault.error.usb_error": { + "en": "USB error. Check connection to host.", + "ja": "USBエラー。 ホストへの接続を確認してください。", + "zh": "USB错误。 检查与主机的连接。", + "en-tts": "USB error. Check connection to host." + }, + "vault.error.record_error": { + "en": "Corrupt database entry.", + "ja": "破損したデータベースエントリ", + "zh": "损坏的数据库条目.", + "en-tts": "Corrupt database entry." + }, + "vault.error.not_found": { + "en": "Entry not found.", + "ja": "エントリが見つかりません.", + "zh": "找不到条目.", + "en-tts": "Entry not found." + }, + "vault.error.fido2": { + "en": "Can't edit FIDO2 tokens.", + "ja": "FIDO2トークンを編集できません。", + "zh": "无法编辑 FIDO2 令牌。", + "en-tts": "Can't edit FIDO2 tokens." + }, + "vault.error.internal_error": { + "en": "Internal error.", + "ja": "内部エラー.", + "zh": "内部错误.", + "en-tts": "Internal error." + }, + "vault.error.nothing_selected": { + "en": "Nothing selected.", + "ja": "何も選択されていません.", + "zh": "未选择任何内容.", + "en-tts": "Nothing selected." + }, + "vault.delete.confirm": { + "en": "Confirm entry deletion: ", + "ja": "エントリの削除を確認する: ", + "zh": "确认条目删除: ", + "en-tts": "Confirm entry deletion: " + }, + "vault.completed": { + "en": "Operation completed.", + "ja": "操作が完了しました.", + "zh": "操作完成.", + "en-tts": "Operation completed." + }, "vault.yes": { "en": "Yes", "ja": "はい", @@ -168,10 +234,10 @@ "en-tts": "App name: " }, "vault.u2f.appinfo.last_authtime": { - "en": "Last authorized: ", - "ja": "最後に承認された:", - "zh": "最后授权:", - "en-tts": "Last authorized: " + "en": "Last accessed: ", + "ja": "最後にアクセスした:", + "zh": "最后访问:", + "en-tts": "Last accessed: " }, "vault.u2f.appinfo.seconds_ago": { "en": "secs ago", diff --git a/apps/vault/src/actions.rs b/apps/vault/src/actions.rs index 19a5e64ac..c785f24ec 100644 --- a/apps/vault/src/actions.rs +++ b/apps/vault/src/actions.rs @@ -3,6 +3,7 @@ use gam::TextEntryPayload; use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}; use num_traits::*; use xous::{SID, msg_blocking_scalar_unpack, Message, send_message}; +use xous_ipc::Buffer; use locales::t; use std::io::{Write, Read}; use passwords::PasswordGenerator; @@ -11,32 +12,32 @@ use std::time::{SystemTime, UNIX_EPOCH}; use std::cell::RefCell; use crate::ux::ListItem; -use crate::VaultMode; +use crate::{VaultMode, SelectedEntry}; -const VAULT_PASSWORD_DICT: &'static str = "vault.passwords"; +pub(crate) const VAULT_PASSWORD_DICT: &'static str = "vault.passwords"; /// bytes to reserve for a key entry. Making this slightly larger saves on some churn as stuff gets updated const VAULT_ALLOC_HINT: usize = 256; const VAULT_PASSWORD_REC_VERSION: u32 = 1; /// time allowed between dialog box swaps for background operations to redraw const SWAP_DELAY_MS: usize = 300; -struct PasswordRecord { - version: u32, - description: String, - username: String, - password: String, - ctime: u64, - atime: u64, - count: u64, +pub(crate) struct PasswordRecord { + pub version: u32, + pub description: String, + pub username: String, + pub password: String, + pub notes: String, + pub ctime: u64, + pub atime: u64, + pub count: u64, } #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub(crate) enum ActionOp { /// Menu items - MenuAutotype, MenuAddnew, - MenuEdit, - MenuDelete, + MenuEditStage2, + MenuDeleteStage2, MenuClose, /// Internal ops UpdateMode, @@ -60,19 +61,24 @@ pub(crate) fn start_actions_thread( Some(ActionOp::MenuAddnew) => { manager.activate(); manager.menu_addnew(); + // this is necessary so the next redraw shows the newly added entry + manager.retrieve_db(); manager.deactivate(); }, - Some(ActionOp::MenuAutotype) => { + Some(ActionOp::MenuDeleteStage2) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let entry = buffer.to_original::().unwrap(); manager.activate(); + manager.menu_delete(entry); + manager.retrieve_db(); manager.deactivate(); }, - Some(ActionOp::MenuDelete) => { - manager.activate(); - manager.deactivate(); - - }, - Some(ActionOp::MenuEdit) => { + Some(ActionOp::MenuEditStage2) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let entry = buffer.to_original::().unwrap(); manager.activate(); + manager.menu_edit(entry); + manager.retrieve_db(); manager.deactivate(); }, Some(ActionOp::MenuClose) => { @@ -283,6 +289,7 @@ impl ActionManager { description, username, password, + notes: t!("vault.notes", xous::LANG).to_string(), ctime: utc_now().timestamp() as u64, atime: 0, count: 0, @@ -297,16 +304,268 @@ impl ActionManager { Some(VAULT_ALLOC_HINT), Some(crate::basis_change) ) { Ok(mut data) => { - data.write(&ser).expect("couldn't store password record"); + match data.write(&ser) { + Ok(_) => {} + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e + ), None).ok(); + } + } + } + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e + ), None).ok(); } - _ => log::error!("Error storing new password"), } self.pddb.borrow().sync().ok(); } _ => {} // not valid for these other modes } } - #[allow(dead_code)] + + pub(crate) fn menu_delete(&mut self, entry: SelectedEntry) { + if self.yes_no_approval(&format!("{}\n{}", t!("vault.delete.confirm", xous::LANG), entry.description)) { + let dict = match entry.mode { + VaultMode::Password => VAULT_PASSWORD_DICT, + VaultMode::Fido => crate::fido::U2F_APP_DICT, + VaultMode::Totp => unimplemented!(), + }; + match self.pddb.borrow().delete_key(dict, entry.key_name.as_str().unwrap_or("UTF8-error"), None) { + Ok(_) => { + self.modals.show_notification(t!("vault.completed", xous::LANG), None).ok(); + } + Err(e) => { + match e.kind() { + std::io::ErrorKind::NotFound => { + // handle special case of FIDO which is two dicts combined + if entry.mode == VaultMode::Fido { + // try the "other" dictionary + match self.pddb.borrow() + .delete_key( + crate::ctap::FIDO_CRED_DICT, + entry.key_name.as_str().unwrap_or("UTF8-error"), + None) { + Ok(_) => { + self.modals.show_notification(t!("vault.completed", xous::LANG), None).ok(); + return; + } + _ => {} + } + } + self.modals.show_notification(t!("vault.error.not_found", xous::LANG), None).ok(); + } + _ => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), + e + ), None).ok(); + } + } + } + } + } + } + + pub(crate) fn menu_edit(&mut self, entry: SelectedEntry) { + let dict = match entry.mode { + VaultMode::Password => VAULT_PASSWORD_DICT, + VaultMode::Fido => crate::fido::U2F_APP_DICT, + VaultMode::Totp => unimplemented!(), + }; + match entry.mode { + VaultMode::Password => { + let maybe_update = match self.pddb.borrow().get( + dict, entry.key_name.as_str().unwrap(), None, + false, false, None, Some(crate::basis_change) + ) { + Ok(mut record) => { + let mut data = Vec::::new(); + let maybe_update = match record.read_to_end(&mut data) { + Ok(_len) => { + if let Some(mut pw) = deserialize_password(data) { + let edit_data = self.modals + .alert_builder(t!("vault.edit_dialog", xous::LANG)) + .field(Some(pw.description), Some(name_validator)) + .field(Some(pw.username), Some(name_validator)) + .field(Some(pw.password), Some(name_validator)) + .field(Some(pw.notes), Some(name_validator)) + .build().expect("modals error in edit"); + pw.description = edit_data.content()[0].content.as_str().unwrap().to_string(); + pw.username = edit_data.content()[1].content.as_str().unwrap().to_string(); + pw.password = edit_data.content()[2].content.as_str().unwrap().to_string(); + pw.notes = edit_data.content()[3].content.as_str().unwrap().to_string(); + pw.atime = utc_now().timestamp() as u64; + Some(pw) + } else { + log::error!("couldn't deserialize {}", entry.key_name); + self.modals.show_notification(t!("vault.error.record_error", xous::LANG), None).ok(); + None + } + } + Err(e) => { + log::error!("couldn't access key {}: {:?}", entry.key_name, e); + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e), + None + ).ok(); + None + } + }; + maybe_update + } + Err(e) => { + match e.kind() { + std::io::ErrorKind::NotFound => { + self.modals.show_notification(t!("vault.error.not_found", xous::LANG), None).ok(); + } + _ => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), + e + ), None).ok(); + } + } + None + } + }; + if let Some(update) = maybe_update { + match self.pddb.borrow().delete_key(dict, entry.key_name.as_str().unwrap(), None) { + Ok(_) => {} + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), + e + ), None).ok(); + return; + } + } + match self.pddb.borrow().get( + dict, entry.key_name.as_str().unwrap(), None, + false, true, Some(VAULT_ALLOC_HINT), + Some(crate::basis_change) + ) { + Ok(mut record) => { + let ser = serialize_password(&update); + match record.write(&ser) { + Ok(_) => {} + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e + ), None).ok(); + } + } + } + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e + ), None).ok(); + return; + } + } + } + self.pddb.borrow().sync().ok(); + } + VaultMode::Fido => { + // 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_name.as_str().unwrap(), None, + false, false, None, Some(crate::basis_change) + ) { + Ok(mut record) => { + let mut data = Vec::::new(); + let maybe_update = match record.read_to_end(&mut data) { + Ok(_len) => { + if let Some(mut ai) = crate::fido::deserialize_app_info(data) { + let edit_data = self.modals + .alert_builder(t!("vault.edit_dialog", xous::LANG)) + .field(Some(ai.name), Some(name_validator)) + .field(Some(ai.notes), Some(name_validator)) + .field(Some(hex::encode(ai.id)), None) + .build().expect("modals error in edit"); + ai.name = edit_data.content()[0].content.as_str().unwrap().to_string(); + ai.notes = edit_data.content()[1].content.as_str().unwrap().to_string(); + ai.atime = utc_now().timestamp() as u64; + Some(ai) + } else { + log::error!("couldn't deserialize {}", entry.key_name); + self.modals.show_notification(t!("vault.error.record_error", xous::LANG), None).ok(); + None + } + } + Err(e) => { + log::error!("couldn't access key {}: {:?}", entry.key_name, e); + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e), + None + ).ok(); + None + } + }; + maybe_update + } + Err(e) => { + match e.kind() { + std::io::ErrorKind::NotFound => { + // most likely this is due to this being a FIDO2 token, which we can't edit + // there are no editable fields -- if we change them, it can break the authentication protocol. + self.modals.show_notification(t!("vault.error.fido2", xous::LANG), None).ok(); + } + _ => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), + e + ), None).ok(); + } + } + None + } + }; + if let Some(update) = maybe_update { + match self.pddb.borrow().delete_key(dict, entry.key_name.as_str().unwrap(), None) { + Ok(_) => {} + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), + e + ), None).ok(); + return; + } + } + match self.pddb.borrow().get( + dict, entry.key_name.as_str().unwrap(), None, + false, true, Some(VAULT_ALLOC_HINT), + Some(crate::basis_change) + ) { + Ok(mut record) => { + let ser = crate::fido::serialize_app_info(&update); + match record.write(&ser) { + Ok(_) => {} + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e + ), None).ok(); + } + } + } + Err(e) => { + self.modals.show_notification(&format!("{}\n{:?}", + t!("vault.error.internal_error", xous::LANG), e + ), None).ok(); + return; + } + } + } + self.pddb.borrow().sync().ok(); + } + VaultMode::Totp => { + unimplemented!() + } + } + } + fn yes_no_approval(&self, query: &str) -> bool { self.modals.add_list( vec![t!("vault.yes", xous::LANG), t!("vault.no", xous::LANG)] @@ -332,7 +591,8 @@ impl ActionManager { hex::encode(guid) } - // populates the display list with testing data + /// Populate the display list with data from the PDDB. Limited by total available RAM; probably + /// would stop working if you have over 500-1k records with the current heap limits. pub(crate) fn retrieve_db(&mut self) { self.mode_cache = { (*self.mode.lock().unwrap()).clone() @@ -419,7 +679,7 @@ impl ActionManager { } -fn name_validator(input: TextEntryPayload) -> Option> { +pub(crate) fn name_validator(input: TextEntryPayload) -> Option> { let proposed_name = input.as_str(); if proposed_name.contains('\n') { // the '\n' is reserved as the delimiter to end the name field Some(xous_ipc::String::<256>::from_str(t!("vault.illegal_char", xous::LANG))) @@ -440,24 +700,26 @@ fn length_validator(input: TextEntryPayload) -> Option> { } fn serialize_password<'a>(record: &PasswordRecord) -> Vec:: { - format!("{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}", + format!("{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}", "version", record.version, "description", record.description, "username", record.username, "password", record.password, + "notes", record.notes, "ctime", record.ctime, "atime", record.atime, "count", record.count, ).into_bytes() } -fn deserialize_password(data: Vec::) -> Option { +pub(crate) fn deserialize_password(data: Vec::) -> Option { if let Ok(desc_str) = String::from_utf8(data) { let mut pr = PasswordRecord { version: 0, description: String::new(), username: String::new(), password: String::new(), + notes: String::new(), ctime: 0, atime: 0, count: 0 @@ -465,7 +727,6 @@ fn deserialize_password(data: Vec::) -> Option { let lines = desc_str.split('\n'); for line in lines { if let Some((tag, data)) = line.split_once(':') { - log::info!("tag: {}, data: {}", tag, data); match tag { "version" => { if let Ok(ver) = u32::from_str_radix(data, 10) { @@ -477,6 +738,7 @@ fn deserialize_password(data: Vec::) -> Option { "description" => pr.description.push_str(data), "username" => pr.username.push_str(data), "password" => pr.password.push_str(data), + "notes" => pr.notes.push_str(data), "ctime" => { if let Ok(ctime) = u64::from_str_radix(data, 10) { pr.ctime = ctime; diff --git a/apps/vault/src/ctap/mod.rs b/apps/vault/src/ctap/mod.rs index 994237adb..9fe0d9f60 100644 --- a/apps/vault/src/ctap/mod.rs +++ b/apps/vault/src/ctap/mod.rs @@ -122,6 +122,8 @@ pub const ES256_CRED_PARAM: PublicKeyCredentialParameter = PublicKeyCredentialPa // - Some(CredentialProtectionPolicy::UserVerificationRequired) const DEFAULT_CRED_PROTECT: Option = None; +pub(crate) const FIDO_CRED_DICT: &'static str = "fido.cred"; + // This function is adapted from https://doc.rust-lang.org/nightly/src/core/str/mod.rs.html#2110 // (as of 2020-01-20) and truncates to "max" bytes, not breaking the encoding. // We change the return value, since we don't need the bool. diff --git a/apps/vault/src/ctap/storage.rs b/apps/vault/src/ctap/storage.rs index 4b8d6d6cb..2dceb54da 100644 --- a/apps/vault/src/ctap/storage.rs +++ b/apps/vault/src/ctap/storage.rs @@ -80,7 +80,7 @@ const _DEFAULT_MIN_PIN_LENGTH_RP_IDS: Vec = Vec::new(); const _MAX_RP_IDS_LENGTH: usize = 8; const FIDO_DICT: &'static str = "fido.cfg"; -const FIDO_CRED_DICT: &'static str = "fido.cred"; +use crate::ctap::FIDO_CRED_DICT; const FIDO_PERSISTENT_DICT: &'static str = "fido.persistent"; /// Wrapper for master keys. diff --git a/apps/vault/src/main.rs b/apps/vault/src/main.rs index 938fe9a51..f08ad260b 100644 --- a/apps/vault/src/main.rs +++ b/apps/vault/src/main.rs @@ -71,6 +71,13 @@ UI concept: Left/right arrow: moves up or down the list view in pages Enter: picks the selected list view Select: *alaways* raises system 'main menu' + + Organization: + - Main thread (vaultux object): "responsive" UI operations - must always be able to respond to redraw commands. + operates on lists of data shared between main & actions thread + - Actions thread (actions object): "blocking" UI operations - manages multi-sequence dialog queries, database access + - Fido thread: handles USB interactions. Can always pop up a dialog box, but it cannot override a dialog-in-progress. + - Icontray thread: a simple server that serves as a shim between the IME structure and this to create an icontray function */ #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] @@ -88,6 +95,9 @@ pub(crate) enum VaultOp { /// Partial menu MenuChangeFont, + MenuDeleteStage1, + MenuEditStage1, + MenuAutotype, /// PDDB basis change BasisChange, @@ -96,14 +106,22 @@ pub(crate) enum VaultOp { Quit, } -#[derive(Copy, Clone, PartialEq, Eq, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] enum VaultMode { Fido, Totp, Password, } +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +struct SelectedEntry { + key_name: xous_ipc::String::<256>, + description: xous_ipc::String::<256>, + mode: VaultMode, +} + static SELF_CONN: AtomicU32 = AtomicU32::new(0); +const ERR_TIMEOUT_MS: usize = 5000; fn main() -> ! { log_server::init_wait().unwrap(); @@ -200,6 +218,7 @@ fn main() -> ! { let mut allow_redraw = false; let modals = modals::Modals::new(&xns).unwrap(); + let tt = ticktimer_server::Ticktimer::new().unwrap(); loop { let msg = xous::receive_message(sid).unwrap(); let opcode: Option = FromPrimitive::from_usize(msg.body.id()); @@ -328,6 +347,55 @@ fn main() -> ! { } vaultux.update_mode(); } + Some(VaultOp::MenuAutotype) => { + modals.dynamic_notification(Some(t!("vault.autotyping", xous::LANG)), None).ok(); + match vaultux.autotype() { + Err(xous::Error::UseBeforeInit) => { // USB not plugged in + modals.dynamic_notification_update(Some(t!("vault.error.usb_error", xous::LANG)), None).ok(); + tt.sleep_ms(ERR_TIMEOUT_MS).unwrap(); + }, + Err(xous::Error::InvalidString) => { // deserialzation error + modals.dynamic_notification_update(Some(t!("vault.error.record_error", xous::LANG)), None).ok(); + tt.sleep_ms(ERR_TIMEOUT_MS).unwrap(); + }, + Err(xous::Error::ProcessNotFound) => { // key or dictionary not found + modals.dynamic_notification_update(Some(t!("vault.error.not_found", xous::LANG)), None).ok(); + tt.sleep_ms(ERR_TIMEOUT_MS).unwrap(); + }, + Err(xous::Error::InvalidPID) => { // nothing was selected + modals.dynamic_notification_update(Some(t!("vault.error.nothing_selected", xous::LANG)), None).ok(); + tt.sleep_ms(ERR_TIMEOUT_MS).unwrap(); + }, + Ok(_) => {}, + Err(e) => { // unknown error + modals.dynamic_notification(Some( + &format!("{}\n{:?}", t!("vault.error.internal_error", xous::LANG), e), + ), None).ok(); + tt.sleep_ms(ERR_TIMEOUT_MS).unwrap(); + } + } + modals.dynamic_notification_close().ok(); + } + Some(VaultOp::MenuDeleteStage1) => { + // stage 1 happens here because the filtered list and selection entry are in the responsive UX section. + if let Some(entry) = vaultux.selected_entry() { + let buf = Buffer::into_buf(entry).expect("IPC error"); + buf.send(actions_conn, ActionOp::MenuDeleteStage2.to_u32().unwrap()).expect("messaging error"); + } else { + // this will block redraws, but it's just one notification in a sequence so it's OK. + modals.show_notification(t!("vault.error.nothing_selected", xous::LANG), None).ok(); + } + } + Some(VaultOp::MenuEditStage1) => { + // stage 1 happens here because the filtered list and selection entry are in the responsive UX section. + if let Some(entry) = vaultux.selected_entry() { + let buf = Buffer::into_buf(entry).expect("IPC error"); + buf.send(actions_conn, ActionOp::MenuEditStage2.to_u32().unwrap()).expect("messaging error"); + } else { + // this will block redraws, but it's just one notification in a sequence so it's OK. + modals.show_notification(t!("vault.error.nothing_selected", xous::LANG), None).ok(); + } + } Some(VaultOp::Quit) => { log::error!("got Quit"); break; diff --git a/apps/vault/src/submenu.rs b/apps/vault/src/submenu.rs index 912084c01..6d6821587 100644 --- a/apps/vault/src/submenu.rs +++ b/apps/vault/src/submenu.rs @@ -10,15 +10,15 @@ pub fn create_submenu(vault_conn: xous::CID, actions_conn: xous::CID, menu_mgr: menu_items.push(MenuItem { name: xous_ipc::String::from_str(t!("vault.menu_edit", xous::LANG)), - action_conn: Some(actions_conn), - action_opcode: ActionOp::MenuEdit.to_u32().unwrap(), + action_conn: Some(vault_conn), + action_opcode: VaultOp::MenuEditStage1.to_u32().unwrap(), action_payload: MenuPayload::Scalar([0, 0, 0, 0]), close_on_select: true, }); menu_items.push(MenuItem { name: xous_ipc::String::from_str(t!("vault.menu_delete", xous::LANG)), - action_conn: Some(actions_conn), - action_opcode: ActionOp::MenuDelete.to_u32().unwrap(), + action_conn: Some(vault_conn), + action_opcode: VaultOp::MenuDeleteStage1.to_u32().unwrap(), action_payload: MenuPayload::Scalar([0, 0, 0, 0]), close_on_select: true, }); diff --git a/apps/vault/src/ux/fido.rs b/apps/vault/src/ux/fido.rs index 0379733ba..cedf1faef 100644 --- a/apps/vault/src/ux/fido.rs +++ b/apps/vault/src/ux/fido.rs @@ -443,6 +443,7 @@ pub(crate) fn start_fido_ux_thread() { Ok(name) => { let info = AppInfo { name: name.content()[0].content.to_string(), + notes: t!("vault.notes", xous::LANG).to_string(), id, ctime: utc_now().timestamp() as u64, atime: 0, @@ -493,18 +494,20 @@ pub(crate) fn start_fido_ux_thread() { /// hash: app hash in hex string, lowercase /// created: decimal number representing epoch of the creation date /// last auth: decimal number representing epoch of the last auth time -struct AppInfo { - name: String, - id: [u8; 32], - ctime: u64, - atime: u64, - count: u64, +pub(crate) struct AppInfo { + pub name: String, + pub id: [u8; 32], + pub notes: String, + pub ctime: u64, + pub atime: u64, + pub count: u64, } -fn deserialize_app_info(descriptor: Vec::) -> Option:: { +pub(crate) fn deserialize_app_info(descriptor: Vec::) -> Option:: { if let Ok(desc_str) = String::from_utf8(descriptor) { let mut appinfo = AppInfo { name: String::new(), + notes: String::new(), id: [0u8; 32], ctime: 0, atime: 0, @@ -517,6 +520,7 @@ fn deserialize_app_info(descriptor: Vec::) -> Option:: { "name" => { appinfo.name.push_str(data); } + "notes" => appinfo.notes.push_str(data), "id" => { if let Ok(id) = hex::decode(data) { appinfo.id.copy_from_slice(&id); @@ -563,7 +567,7 @@ fn deserialize_app_info(descriptor: Vec::) -> Option:: { } } -fn serialize_app_info<'a>(appinfo: &AppInfo) -> Vec:: { +pub(crate) fn serialize_app_info<'a>(appinfo: &AppInfo) -> Vec:: { format!("{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}", "name", appinfo.name, "id", hex::encode(appinfo.id), diff --git a/apps/vault/src/ux/framework.rs b/apps/vault/src/ux/framework.rs index bbd58dfa1..9c86d88d8 100644 --- a/apps/vault/src/ux/framework.rs +++ b/apps/vault/src/ux/framework.rs @@ -15,6 +15,7 @@ pub(crate) struct ListItem { pub(crate) name: String, pub(crate) extra: String, pub(crate) dirty: bool, + /// this is the name of the key used to refer to the item pub(crate) guid: String, } impl ListItem { @@ -83,6 +84,9 @@ pub(crate) struct VaultUx { menu_mgr: MenuMatic, main_conn: xous::CID, actions_conn: xous::CID, + + /// usb interface + usb_dev: usb_device_xous::UsbHid, } pub(crate) const DEFAULT_FONT: GlyphStyle = GlyphStyle::Regular; @@ -205,6 +209,7 @@ impl VaultUx { main_conn: xous::connect(sid).unwrap(), actions_conn, action_active, + usb_dev: usb_device_xous::UsbHid::new(), } } pub(crate) fn update_mode(&mut self) { @@ -257,8 +262,8 @@ impl VaultUx { self.menu_mgr.insert_item( MenuItem { name: xous_ipc::String::from_str(t!("vault.menu_autotype", xous::LANG)), - action_conn: Some(self.actions_conn), - action_opcode: ActionOp::MenuAutotype.to_u32().unwrap(), + action_conn: Some(self.main_conn), + action_opcode: VaultOp::MenuAutotype.to_u32().unwrap(), action_payload: MenuPayload::Scalar([0, 0, 0, 0]), close_on_select: true, }, @@ -570,4 +575,61 @@ impl VaultUx { } } } + + pub(crate) fn autotype(&mut self) -> Result<(), xous::Error> { + if self.selection_index >= self.filtered_list.len() { + return Err(xous::Error::InvalidPID); + } + let entry = &self.filtered_list[self.selection_index].guid; + // we re-fetch the entry for autotype, because the PDDB could have unmounted a basis. + match self.pddb.borrow().get( + crate::actions::VAULT_PASSWORD_DICT, + entry, + None, + false, false, None, + Some(crate::basis_change) + ) { + Ok(mut record) => { + let mut data = Vec::::new(); + match record.read_to_end(&mut data) { + Ok(_len) => { + if let Some(pw) = crate::actions::deserialize_password(data) { + match self.usb_dev.send_str(&pw.password) { + Ok(_) => Ok(()), + Err(e) => { + log::error!("couldn't autotype password: {:?}", e); + Err(xous::Error::UseBeforeInit) + } + } + } else { + log::error!("couldn't deserialize {}", entry); + Err(xous::Error::InvalidString) + } + } + Err(e) => { + log::error!("couldn't access key {}: {:?}", entry, e); + Err(xous::Error::ProcessNotFound) + }, + } + } + Err(e) => { + log::error!("couldn't access key {}: {:?}", entry, e); + Err(xous::Error::ProcessNotFound) + } + } + } + pub(crate) fn selected_entry(&self) -> Option { + if self.selection_index >= self.filtered_list.len() { + None + } else { + let entry = &self.filtered_list[self.selection_index]; + Some( + SelectedEntry { + key_name: xous_ipc::String::from_str(entry.guid.to_string()), + mode: (*self.mode.lock().unwrap()).clone(), + description: xous_ipc::String::from_str(entry.name.to_string()), + } + ) + } + } } \ No newline at end of file