rework basically everything
This commit is contained in:
1 parent
2bd81a66a4
commit
a1e5daba59
12 files changed
+450
-157
No files matched your search
Generated
+2
@@ -1374,6 +1374,8 @@ dependencies = [
|
||||
"gpui-kit",
|
||||
"gpui-omarchy",
|
||||
"is-terminal",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
@@ -17,6 +17,8 @@ getrandom = { version = "0.4.3", features = ["sys_rng"] }
|
||||
gpui-kit = "0.7.0"
|
||||
gpui-omarchy = "0.2.1"
|
||||
is-terminal = "0.4.17"
|
||||
serde = "1.0.229"
|
||||
serde_json = "1.0.154"
|
||||
thiserror = "2.0.21"
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
mod passphrase_input;
|
||||
|
||||
pub use passphrase_input::{PassphraseInput, PassphraseInputEvent};
|
||||
@@ -0,0 +1,97 @@
|
||||
use gpui_kit::assets::IconName;
|
||||
use gpui_kit::base::input::{InputEvent, InputState};
|
||||
use gpui_kit::{
|
||||
App, AppContext, Context, Entity, EventEmitter, IntoElement, Render, SharedString, Styled,
|
||||
Subscription, Window,
|
||||
};
|
||||
use gpui_omarchy::{ButtonVariant, icon_button, input};
|
||||
|
||||
|
||||
/// A masked passphrase field with a show/hide toggle.
|
||||
///
|
||||
/// The `show` flag is passed in from outside so that it can be shared
|
||||
/// (e.g. passphrase and confirm-passphrase inputs should share it).
|
||||
pub struct PassphraseInput {
|
||||
state: Entity<InputState>,
|
||||
show: Entity<bool>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
pub enum PassphraseInputEvent {
|
||||
/// The user pressed Enter in the field.
|
||||
Submit,
|
||||
/// The field's text changed.
|
||||
Change,
|
||||
/// The field lost focus.
|
||||
Blur,
|
||||
}
|
||||
|
||||
impl EventEmitter<PassphraseInputEvent> for PassphraseInput {}
|
||||
|
||||
impl PassphraseInput {
|
||||
pub fn new(show: Entity<bool>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let masked = !*show.read(cx);
|
||||
let state = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.masked(masked)
|
||||
.placeholder("correct horse battery staple")
|
||||
});
|
||||
|
||||
// keep this field's masking in sync with the shared flag
|
||||
let sync_mask = cx.observe_in(&show, window, |this, show, window, cx| {
|
||||
let masked = !*show.read(cx);
|
||||
this.state.update(cx, |state, cx| state.set_masked(masked, window, cx));
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
// re-emit the subset of input events that consumers care about
|
||||
let forward = cx.subscribe(&state, |_, _, event: &InputEvent, cx| {
|
||||
let event = match event {
|
||||
InputEvent::PressEnter { .. } => PassphraseInputEvent::Submit,
|
||||
InputEvent::Change => PassphraseInputEvent::Change,
|
||||
InputEvent::Blur => PassphraseInputEvent::Blur,
|
||||
InputEvent::Focus => return,
|
||||
};
|
||||
cx.emit(event);
|
||||
});
|
||||
|
||||
Self {
|
||||
state,
|
||||
show,
|
||||
_subscriptions: vec![sync_mask, forward],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value(&self, cx: &App) -> SharedString {
|
||||
self.state.read(cx).value()
|
||||
}
|
||||
|
||||
pub fn focus(&self, window: &mut Window, cx: &mut App) {
|
||||
self.state.update(cx, |state, cx| state.focus(window, cx));
|
||||
}
|
||||
|
||||
fn toggle_show(&mut self, cx: &mut Context<Self>) {
|
||||
self.show.update(cx, |show, cx| {
|
||||
*show = !*show;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for PassphraseInput {
|
||||
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let (icon, label) = if *self.show.read(cx) {
|
||||
(IconName::EyeOff, "Hide passphrase")
|
||||
}
|
||||
else {
|
||||
(IconName::Eye, "Show passphrase")
|
||||
};
|
||||
|
||||
input("passphrase", &self.state, window, cx)
|
||||
.w_full()
|
||||
.suffix(
|
||||
icon_button("toggle-show", icon, label, ButtonVariant::Secondary, cx)
|
||||
.on_click(cx.listener(|this, _, _, cx| this.toggle_show(cx))),
|
||||
)
|
||||
}
|
||||
}
|
||||
+65
-11
@@ -1,36 +1,90 @@
|
||||
use std::fs::File;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use gpui_kit::Global;
|
||||
use is_terminal::IsTerminal;
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
use crate::error::CreddyError;
|
||||
|
||||
|
||||
/// Config that doesn't need to or can't be stored in the encrypted db
|
||||
/// (such as settings that must be known at startup, before unlock).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct PublicConfig {
|
||||
db_salt: [u8; 32],
|
||||
}
|
||||
|
||||
impl PublicConfig {
|
||||
/// Construct a PublicConfig with default values, in case there is nothing saved on disk
|
||||
fn default() -> PublicConfig {
|
||||
let mut db_salt = [0u8; 32];
|
||||
getrandom::fill(&mut db_salt);
|
||||
PublicConfig { db_salt }
|
||||
}
|
||||
|
||||
/// Load non-sensitive config from disk.
|
||||
fn load() -> Result<PublicConfig, CreddyError> {
|
||||
let public_path = config_path()?.join("public_config.json");
|
||||
if public_path.exists() {
|
||||
let f = File::open(public_path)?;
|
||||
serde_json::from_reader(f).map_err(|e| CreddyError::ConfigDecode(e))
|
||||
}
|
||||
else {
|
||||
Ok(PublicConfig::default())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AppConfig {
|
||||
pub db_path: PathBuf,
|
||||
pub db_salt: [u8; 32],
|
||||
}
|
||||
|
||||
impl AppConfig {
|
||||
pub fn default() -> Result<AppConfig, CreddyError> {
|
||||
/// Load config from disk, using defaults for non-public values.
|
||||
pub fn load() -> Result<AppConfig, CreddyError> {
|
||||
let public_config = PublicConfig::load()?;
|
||||
Ok(AppConfig {
|
||||
db_path: default_db_path()?,
|
||||
db_path: db_path()?,
|
||||
db_salt: public_config.db_salt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Global for AppConfig {}
|
||||
|
||||
pub fn default_db_path() -> Result<PathBuf, CreddyError> {
|
||||
let mut path = dirs::data_dir()
|
||||
.ok_or(CreddyError::DataDirNotFound)?;
|
||||
path.push("creddy");
|
||||
|
||||
std::fs::create_dir_all(&path)?;
|
||||
if cfg!(debug_assertions) && std::io::stdout().is_terminal() {
|
||||
path.push("creddy.dev.duckdb");
|
||||
pub fn config_path() -> Result<PathBuf, CreddyError> {
|
||||
dirs::data_dir()
|
||||
.map(|d| d.join("creddy"))
|
||||
.ok_or(CreddyError::DataDirNotFound)
|
||||
}
|
||||
|
||||
|
||||
pub fn db_path() -> Result<PathBuf, CreddyError> {
|
||||
let dir = config_path()?;
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
|
||||
let path = if cfg!(debug_assertions) && std::io::stdout().is_terminal() {
|
||||
dir.join("creddy.dev.duckdb")
|
||||
}
|
||||
else {
|
||||
path.push("creddy.duckdb");
|
||||
}
|
||||
dir.join("creddy.duckdb")
|
||||
};
|
||||
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_public_default() {
|
||||
let conf = PublicConfig::default();
|
||||
assert!(conf.db_salt.len() == 32);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::sync::Mutex;
|
||||
use argon2::{Algorithm, Argon2, Version, Error as Argon2Error, ParamsBuilder};
|
||||
use base64ct::{Base64, Encoding};
|
||||
use duckdb::{
|
||||
Connection,
|
||||
@@ -5,27 +7,61 @@ use duckdb::{
|
||||
Error,
|
||||
};
|
||||
|
||||
use crate::config::{self, AppConfig};
|
||||
use crate::error::CreddyError;
|
||||
use crate::config::AppConfig;
|
||||
|
||||
|
||||
struct Db {
|
||||
connection: Connection,
|
||||
// tests take forever with production parameters, so we turn them down in dev
|
||||
#[cfg(not(debug_assertions))]
|
||||
const MEM_COST: u32 = 128 * 1024;
|
||||
#[cfg(not(debug_assertions))]
|
||||
const TIME_COST: u32 = 8;
|
||||
#[cfg(not(debug_assertions))]
|
||||
const PARALLELISM_COST: u32 = 4;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
const MEM_COST: u32 = 48 * 1024;
|
||||
#[cfg(debug_assertions)]
|
||||
const TIME_COST: u32 = 1;
|
||||
#[cfg(debug_assertions)]
|
||||
const PARALLELISM_COST: u32 = 1;
|
||||
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Db {
|
||||
connection: Mutex<Connection>,
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub fn connect(config: &AppConfig, key: &[u8; 32]) -> Result<Self, Error> {
|
||||
// DuckDB docks say to use base64 for the key, so that's what we'll do
|
||||
let mut b64_key = [0u8; 44]; // 32 bytes take up 44 chars of base64
|
||||
let key_str = Base64::encode(key, &mut b64_key).expect("Wrong-sized input buffer"); // should never happen
|
||||
pub fn connect(config: &AppConfig, passphrase: &str) -> Result<Self, CreddyError> {
|
||||
let path = config.db_path.to_string_lossy();
|
||||
let key = Db::derive_key(passphrase, &config.db_salt)?;
|
||||
|
||||
let conn = Connection::open_in_memory()?;
|
||||
// hard-code the path for now, until we get proper config set up
|
||||
conn.execute(
|
||||
"ATTACH ? AS creddy (ENCRYPTION_KEY ?);",
|
||||
params![config.db_path.to_string_lossy(), key_str],
|
||||
params![path, key],
|
||||
)?;
|
||||
conn.execute("USE creddy;", [])?;
|
||||
Ok(Self{ connection: conn })
|
||||
Ok(Self{ connection: Mutex::new(conn) })
|
||||
}
|
||||
|
||||
/// Hash the given passphrase/salt with argon2, then encode to base64 for DuckDB
|
||||
fn derive_key(passphrase: &str, salt: &[u8; 32]) -> Result<String, Argon2Error> {
|
||||
let params = ParamsBuilder::new()
|
||||
.m_cost(MEM_COST)
|
||||
.t_cost(TIME_COST)
|
||||
.p_cost(PARALLELISM_COST)
|
||||
.build()
|
||||
.unwrap(); // only errors if the given params are invalid
|
||||
|
||||
let hasher = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
|
||||
|
||||
let mut key = [0; 32]; // todo: replace this with a `zeroize` or `secrecy` type
|
||||
hasher.hash_password_into(passphrase.as_bytes(), salt, &mut key)?;
|
||||
|
||||
Ok(Base64::encode_string(&key))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,14 +70,21 @@ impl Db {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const TEST_PASSPHRASE: &'static str = "correct horse battery staple";
|
||||
const TEST_SALT: [u8; 32] = [0; 32];
|
||||
// the result of hashing TEST_PASSPHRASE with TEST_SALT and encoding to Base64
|
||||
const TEST_KEY: &'static str = "CPLL6XQdzFMlhx1yOKX461hvsDOSD27a8AwEo4jyV7Q=";
|
||||
|
||||
#[test]
|
||||
fn test_connect_new() {
|
||||
let data_dir = tempfile::tempdir().unwrap();
|
||||
let db_path = data_dir.path().join("creddy.test.db");
|
||||
|
||||
let config = AppConfig { db_path: db_path.clone() };
|
||||
let key = [0u8; 32];
|
||||
let res = Db::connect(&config, &key);
|
||||
let config = AppConfig {
|
||||
db_path: db_path.clone(),
|
||||
db_salt: [0u8; 32],
|
||||
};
|
||||
let res = Db::connect(&config, TEST_PASSPHRASE);
|
||||
assert!(res.is_ok());
|
||||
|
||||
// confirm that db is in fact encrypted
|
||||
@@ -53,23 +96,44 @@ mod tests {
|
||||
Err(e) => panic!("Unexpected error type: {e:?}"),
|
||||
Ok(_) => panic!("Should not be able to open newly-created database without encryption key"),
|
||||
};
|
||||
|
||||
// confirm that using a different passphrase won't work
|
||||
let res = Db::connect(&config, "not the correct passphrase");
|
||||
match res {
|
||||
Err(CreddyError::Db(Error::DuckDBFailure(error, Some(desc)))) => {
|
||||
assert!(error.code == duckdb::ErrorCode::Unknown);
|
||||
assert!(error.extended_code == 1);
|
||||
assert!(desc.contains("Wrong encryption key"));
|
||||
},
|
||||
Err(e) => panic!("Unexpected error type: {e:?}"),
|
||||
Ok(_) => panic!("Should not be able to open database with a different passphrase"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connect_existing() {
|
||||
let data_dir = tempfile::tempdir().unwrap();
|
||||
let db_path = data_dir.path().join("creddy.test.db");
|
||||
let key = [0u8; 32];
|
||||
let key_str = Base64::encode_string(&key);
|
||||
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
conn.execute(
|
||||
"ATTACH ? AS creddy (ENCRYPTION_KEY ?);",
|
||||
params![&db_path.to_string_lossy(), &key_str],
|
||||
params![&db_path.to_string_lossy(), TEST_KEY],
|
||||
).unwrap();
|
||||
|
||||
let config = AppConfig { db_path: db_path };
|
||||
let res = Db::connect(&config, &key);
|
||||
let config = AppConfig {
|
||||
db_path,
|
||||
db_salt: [0u8; 32],
|
||||
};
|
||||
let res = Db::connect(&config, TEST_PASSPHRASE);
|
||||
assert!(res.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derive_key() {
|
||||
match Db::derive_key(TEST_PASSPHRASE, &TEST_SALT) {
|
||||
Ok(key) => assert!(key == "CPLL6XQdzFMlhx1yOKX461hvsDOSD27a8AwEo4jyV7Q="),
|
||||
Err(e) => panic!("Error deriving key: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,16 @@ use thiserror::Error;
|
||||
pub enum CreddyError {
|
||||
#[error("Couldn't determine location for app state")]
|
||||
DataDirNotFound,
|
||||
|
||||
#[error("Error from database: {0}")]
|
||||
Db(#[from] duckdb::Error),
|
||||
|
||||
#[error("I/O error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
|
||||
#[error("Unable to load saved configuration: {0}")]
|
||||
ConfigDecode(#[from] serde_json::Error),
|
||||
|
||||
#[error("Unable to hash password: {0}")]
|
||||
PasswordHash(#[from] argon2::Error),
|
||||
}
|
||||
+44
-25
@@ -1,48 +1,67 @@
|
||||
use gpui_kit::{
|
||||
AppContext, Context, Entity, IntoElement, ParentElement, Render, Styled, Window, WindowOptions,
|
||||
AppContext, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div,
|
||||
};
|
||||
use gpui_omarchy::{ActiveTheme, ButtonVariant, button, focus_scope, panel};
|
||||
use gpui_omarchy::ActiveTheme;
|
||||
|
||||
mod components;
|
||||
mod config;
|
||||
mod db;
|
||||
mod error;
|
||||
mod screens;
|
||||
mod session;
|
||||
|
||||
use config::AppConfig;
|
||||
use session::AppSession;
|
||||
use screens::WelcomeScreen;
|
||||
use screens::{HomeScreen, WelcomeScreen};
|
||||
|
||||
enum AppScreen {
|
||||
Welcome(Entity<WelcomeScreen>),
|
||||
}
|
||||
|
||||
struct CreddyApp {
|
||||
session: Entity<AppSession>,
|
||||
screen: AppScreen,
|
||||
}
|
||||
struct CreddyApp {}
|
||||
|
||||
impl Render for CreddyApp {
|
||||
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
||||
match &self.screen {
|
||||
AppScreen::Welcome(s) => s.clone().into_any_element(),
|
||||
}
|
||||
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let session = cx.global::<AppSession>();
|
||||
let screen = match session {
|
||||
AppSession::Empty => window
|
||||
.use_keyed_state("welcome", cx, |window, cx| {
|
||||
WelcomeScreen::new(window, cx)
|
||||
})
|
||||
.into_any_element(),
|
||||
// todo: unlock screen
|
||||
AppSession::Locked => div().child("Creddy is locked").into_any_element(),
|
||||
AppSession::Unlocked { .. } => window
|
||||
.use_keyed_state("home", cx, |_, _| HomeScreen {})
|
||||
.into_any_element(),
|
||||
};
|
||||
|
||||
let theme = cx.omarchy();
|
||||
div()
|
||||
.size_full()
|
||||
.bg(theme.background)
|
||||
.text_color(theme.foreground)
|
||||
.font_family(theme.font.clone())
|
||||
.child(screen)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// todo: replace this with proper error handling
|
||||
let app_config = AppConfig::load().expect("failed to load config");
|
||||
let app_session = AppSession::load(&app_config);
|
||||
dbg!(&app_session);
|
||||
|
||||
// Icons are read through the asset source, so register the bundle.
|
||||
gpui_kit::application()
|
||||
.with_assets(gpui_kit::assets::Assets)
|
||||
.run(|cx| {
|
||||
gpui_omarchy::init(cx);
|
||||
let session = cx.new(|_| AppSession::Empty);
|
||||
cx.open_window(WindowOptions::default(), |window, cx| {
|
||||
let screen = AppScreen::Welcome(
|
||||
cx.new(|cx| WelcomeScreen::new(session.clone(), window, cx)),
|
||||
);
|
||||
cx.new(|_| CreddyApp { session, screen })
|
||||
})
|
||||
.run(|app| {
|
||||
gpui_omarchy::init(app);
|
||||
app.set_global(app_config);
|
||||
app.set_global(app_session);
|
||||
// refresh_windows() forces everything to re-render, which is kind of a nuclear solution,
|
||||
// but these values aren't expected to change very frequently, so it shouldn't be a problem
|
||||
app.observe_global::<AppConfig>(|app| app.refresh_windows()).detach();
|
||||
app.observe_global::<AppSession>(|app| app.refresh_windows()).detach();
|
||||
|
||||
app.open_window(WindowOptions::default(), |_, cx| cx.new(|_| CreddyApp {}))
|
||||
.expect("open window");
|
||||
cx.activate(true);
|
||||
app.activate(true);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use gpui_kit::{div, Render, Window, Context, IntoElement, Styled, ParentElement};
|
||||
|
||||
pub struct HomeScreen {}
|
||||
|
||||
impl Render for HomeScreen {
|
||||
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
||||
div()
|
||||
.flex()
|
||||
.justify_center()
|
||||
.items_center()
|
||||
.child("Creddy is unlocked")
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
mod home;
|
||||
mod welcome;
|
||||
|
||||
pub use home::HomeScreen;
|
||||
pub use welcome::WelcomeScreen;
|
||||
+105
-57
@@ -1,18 +1,22 @@
|
||||
use gpui_kit::base::input::{InputEvent, InputState};
|
||||
use gpui_kit::{
|
||||
AppContext, Context, Entity, IntoElement, ParentElement, Render, SharedString, Styled,
|
||||
Subscription, Task, Window, div, rems,
|
||||
AppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString,
|
||||
Styled, Subscription, Task,Window, div, rems,
|
||||
};
|
||||
use gpui_omarchy::{ActiveTheme, ButtonVariant, Status, alert, button, focus_scope, input, panel};
|
||||
use gpui_omarchy::{ActiveTheme, ButtonVariant, Status, alert, button, focus_scope};
|
||||
|
||||
use crate::components::{PassphraseInput, PassphraseInputEvent};
|
||||
use crate::config::AppConfig;
|
||||
use crate::db::Db;
|
||||
use crate::session::AppSession;
|
||||
|
||||
|
||||
const MISMATCH: &str = "Passphrases do not match.";
|
||||
|
||||
|
||||
/// First-run screen: choose a passphrase, derive the key, and unlock the session.
|
||||
pub struct WelcomeScreen {
|
||||
session: Entity<AppSession>,
|
||||
passphrase: Entity<InputState>,
|
||||
confirm: Entity<InputState>,
|
||||
passphrase: Entity<PassphraseInput>,
|
||||
confirm: Entity<PassphraseInput>,
|
||||
error: Option<SharedString>,
|
||||
/// Set while the KDF is running; dropping it cancels the task.
|
||||
pending: Option<Task<()>>,
|
||||
@@ -20,33 +24,37 @@ pub struct WelcomeScreen {
|
||||
}
|
||||
|
||||
impl WelcomeScreen {
|
||||
pub fn new(session: Entity<AppSession>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let passphrase = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.masked(true)
|
||||
.placeholder("Passphrase")
|
||||
});
|
||||
let confirm = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.masked(true)
|
||||
.placeholder("Confirm passphrase")
|
||||
});
|
||||
passphrase.update(cx, |state, cx| state.focus(window, cx));
|
||||
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let show = cx.new(|_| false);
|
||||
let passphrase = cx.new(|cx| PassphraseInput::new(show.clone(), window, cx));
|
||||
let confirm = cx.new(|cx| PassphraseInput::new(show, window, cx));
|
||||
passphrase.update(cx, |input, cx| input.focus(window, cx));
|
||||
|
||||
// Enter in either field submits
|
||||
let _subscriptions = [&passphrase, &confirm]
|
||||
.into_iter()
|
||||
.map(|field| {
|
||||
cx.subscribe_in(field, window, |this, _, event, window, cx| {
|
||||
if let InputEvent::PressEnter { .. } = event {
|
||||
this.submit(window, cx);
|
||||
let mut _subscriptions = Vec::new();
|
||||
for input in [&passphrase, &confirm] {
|
||||
_subscriptions.push(cx.subscribe_in(input, window, |this, _, event, window, cx| {
|
||||
match event {
|
||||
PassphraseInputEvent::Submit => this.submit(window, cx),
|
||||
// typing only dismisses the mismatch error, never raises it
|
||||
PassphraseInputEvent::Change if this.passphrases_match(cx) => {
|
||||
this.error = None;
|
||||
cx.notify();
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
_ => (),
|
||||
}
|
||||
}));
|
||||
}
|
||||
// leaving the confirm field is what raises the mismatch error
|
||||
_subscriptions.push(cx.subscribe_in(&confirm, window, |this, _, event, _, cx| {
|
||||
if let PassphraseInputEvent::Blur = event
|
||||
&& !this.passphrases_match(cx)
|
||||
{
|
||||
this.error = Some(MISMATCH.into());
|
||||
cx.notify();
|
||||
}
|
||||
}));
|
||||
|
||||
Self {
|
||||
session,
|
||||
passphrase,
|
||||
confirm,
|
||||
error: None,
|
||||
@@ -55,44 +63,42 @@ impl WelcomeScreen {
|
||||
}
|
||||
}
|
||||
|
||||
fn passphrases_match(&self, cx: &Context<Self>) -> bool {
|
||||
self.passphrase.read(cx).value(cx) == self.confirm.read(cx).value(cx)
|
||||
}
|
||||
|
||||
fn submit(&mut self, _: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.pending.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let passphrase = self.passphrase.read(cx).value();
|
||||
let confirm = self.confirm.read(cx).value();
|
||||
if passphrase.is_empty() {
|
||||
self.error = Some("Passphrase cannot be empty.".into());
|
||||
let passphrase = self.passphrase.read(cx).value(cx);
|
||||
if !self.passphrases_match(cx) {
|
||||
self.error = Some(MISMATCH.into());
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
if passphrase != confirm {
|
||||
self.error = Some("Passphrases do not match.".into());
|
||||
if passphrase.is_empty() {
|
||||
self.error = Some("Passphrase is empty.".into());
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
|
||||
let config = cx.global::<AppConfig>().clone();
|
||||
self.error = None;
|
||||
// todo: persist the salt (and KDF params) so the database can be unlocked again later
|
||||
self.pending = Some(cx.spawn(async move |this, cx| {
|
||||
// argon2 is deliberately slow, so keep it off the UI thread
|
||||
let result = cx
|
||||
.background_spawn(async move {
|
||||
let salt = AppSession::salt().map_err(|e| e.to_string())?;
|
||||
AppSession::new(&passphrase, &salt).map_err(|e| e.to_string())
|
||||
Db::connect(&config, passphrase.as_str())
|
||||
})
|
||||
.await;
|
||||
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
this.pending = None;
|
||||
match result {
|
||||
Ok(unlocked) => {
|
||||
this.session.update(cx, |session, cx| {
|
||||
*session = unlocked;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
Ok(db) => cx.set_global(AppSession::Unlocked(db)),
|
||||
Err(e) => this.error = Some(format!("Failed to derive key: {e}").into()),
|
||||
}
|
||||
cx.notify();
|
||||
@@ -103,27 +109,69 @@ impl WelcomeScreen {
|
||||
}
|
||||
|
||||
impl Render for WelcomeScreen {
|
||||
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let busy = self.pending.is_some();
|
||||
let label = if busy { "Creating…" } else { "Get started" };
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let t = cx.omarchy();
|
||||
let field = |label: &'static str, input: &Entity<PassphraseInput>| {
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(rems(0.25))
|
||||
.child(div().text_size(rems(0.875)).child(label))
|
||||
.child(input.clone())
|
||||
};
|
||||
|
||||
focus_scope("welcome")
|
||||
.size_full()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.bg(cx.omarchy().background)
|
||||
.items_center()
|
||||
.bg(t.background)
|
||||
.text_color(t.foreground)
|
||||
.font_family(t.font.clone())
|
||||
.child(
|
||||
panel("Welcome to Creddy", cx)
|
||||
.w(rems(24.))
|
||||
.child(div().child("Choose a passphrase to encrypt your credentials."))
|
||||
.child(input("passphrase", &self.passphrase, window, cx))
|
||||
.child(input("confirm", &self.confirm, window, cx))
|
||||
div()
|
||||
.w_full()
|
||||
.max_w(rems(32.))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(rems(2.))
|
||||
.child(
|
||||
div()
|
||||
.text_center()
|
||||
.text_size(rems(1.5))
|
||||
.font_weight(FontWeight::BOLD)
|
||||
.child("Welcome to Creddy!"),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(rems(1.))
|
||||
.child("Create a passphrase to get started.")
|
||||
.child(
|
||||
"Please note that if you forget your passphrase, there is no way \
|
||||
to recover your stored credentials. You will have to start over \
|
||||
with a new passphrase.",
|
||||
),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.w_full()
|
||||
.max_w(rems(24.))
|
||||
.mx_auto()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(rems(1.))
|
||||
.children(self.error.clone().map(|e| alert(e, Status::Error, cx)))
|
||||
.child(field("Passphrase", &self.passphrase))
|
||||
.child(field("Re-enter passphrase", &self.confirm))
|
||||
.child(
|
||||
button("get-started", label, ButtonVariant::Primary, cx)
|
||||
.disabled(busy)
|
||||
.on_click(cx.listener(|this, _, window, cx| this.submit(window, cx))),
|
||||
button("submit", "Submit", ButtonVariant::Primary, cx)
|
||||
.disabled(self.pending.is_some())
|
||||
.on_click(cx.listener(|this, _, window, cx| {
|
||||
this.submit(window, cx)
|
||||
})),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
+28
-47
@@ -1,62 +1,43 @@
|
||||
use argon2::{Algorithm, Argon2, ParamsBuilder, Result as Argon2Result, Version};
|
||||
use gpui_kit::Global;
|
||||
use crate::config::AppConfig;
|
||||
use crate::error::CreddyError;
|
||||
use crate::db::Db;
|
||||
|
||||
// tests take forever with production parameters, so we turn them down in dev
|
||||
#[cfg(not(debug_assertions))]
|
||||
const MEM_COST: u32 = 128 * 1024;
|
||||
#[cfg(not(debug_assertions))]
|
||||
const TIME_COST: u32 = 8;
|
||||
#[cfg(not(debug_assertions))]
|
||||
const PARALLELISM_COST: u32 = 4;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
const MEM_COST: u32 = 48 * 1024;
|
||||
#[cfg(debug_assertions)]
|
||||
const TIME_COST: u32 = 1;
|
||||
#[cfg(debug_assertions)]
|
||||
const PARALLELISM_COST: u32 = 1;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Debug)]
|
||||
pub enum AppSession {
|
||||
Empty,
|
||||
Locked,
|
||||
Unlocked { key: [u8; 32] },
|
||||
Unlocked(Db),
|
||||
}
|
||||
|
||||
impl AppSession {
|
||||
pub fn new(passphrase: &str, salt: &[u8]) -> Argon2Result<Self> {
|
||||
let params = ParamsBuilder::new()
|
||||
.m_cost(MEM_COST)
|
||||
.t_cost(TIME_COST)
|
||||
.p_cost(PARALLELISM_COST)
|
||||
.build()
|
||||
.unwrap(); // only errors if the given params are invalid
|
||||
|
||||
let hasher = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
|
||||
|
||||
let mut key = [0; 32]; // todo: replace this with a `zeroize` or `secrecy` type
|
||||
hasher.hash_password_into(passphrase.as_bytes(), &salt, &mut key)?;
|
||||
Ok(Self::Unlocked { key })
|
||||
}
|
||||
|
||||
pub fn salt() -> Result<[u8; 32], getrandom::Error> {
|
||||
let mut salt = [0; 32];
|
||||
getrandom::fill(&mut salt)?;
|
||||
Ok(salt)
|
||||
pub fn load(config: &AppConfig) -> AppSession {
|
||||
if config.db_path.exists() {
|
||||
AppSession::Locked
|
||||
} else {
|
||||
AppSession::Empty
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unlock(&mut self, passphrase: &str) -> Result<AppSession, CreddyError> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl Global for AppSession {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new() {
|
||||
let passphrase = "correct horse battery staple";
|
||||
let salt = AppSession::salt().expect("salt generation failed.");
|
||||
let session = AppSession::new(passphrase, &salt).expect("password KDF failed.");
|
||||
match session {
|
||||
AppSession::Unlocked { .. } => (),
|
||||
_ => panic!("AppSession::new() should return an unlocked session"),
|
||||
}
|
||||
}
|
||||
// #[test]
|
||||
// fn test_new() {
|
||||
// let passphrase = "correct horse battery staple";
|
||||
// let salt = AppSession::salt().expect("salt generation failed.");
|
||||
// let session = AppSession::new(passphrase, &salt).expect("password KDF failed.");
|
||||
// match session {
|
||||
// AppSession::Unlocked { .. } => (),
|
||||
// _ => panic!("AppSession::new() should return an unlocked session"),
|
||||
// }
|
||||
// }
|
||||
}
|
||||
Reference in new issue
Block a user