diff --git a/Cargo.lock b/Cargo.lock index 71286a267..0913a5810 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1969,6 +1969,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "getrandom" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.13.3+wasi-0.2.2", + "windows-targets 0.52.6", +] + [[package]] name = "ghash" version = "0.5.1" @@ -4196,6 +4208,7 @@ dependencies = [ "radicle-types", "serde", "serde_json", + "ssh-key", "tauri", "tauri-build", "tauri-plugin-clipboard-manager", @@ -4206,6 +4219,7 @@ dependencies = [ "thiserror 1.0.69", "tokio", "ts-rs", + "zeroize", ] [[package]] @@ -4224,6 +4238,9 @@ dependencies = [ "serde", "serde_json", "sqlite", + "ssh-key", + "tauri-plugin-clipboard-manager", + "tauri-plugin-fs", "tempfile", "thiserror 1.0.69", "tree-sitter-bash", @@ -5517,9 +5534,9 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "tar" -version = "0.4.43" +version = "0.4.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c65998313f8e17d0d553d28f91a0df93e4dbbbf770279c7bc21ca0f09ea1a1f6" +checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a" dependencies = [ "filetime", "libc", @@ -5875,12 +5892,13 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.14.0" +version = "3.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cce251fcbc87fac86a866eeb0d6c2d536fc16d06f184bb61aeae11aa4cee0c" +checksum = "22e5a0acb1f3f55f65cc4a866c361b2fb2a0ff6366785ae6fbb5f85df07ba230" dependencies = [ "cfg-if", "fastrand", + "getrandom 0.3.1", "once_cell", "rustix", "windows-sys 0.59.0", @@ -6756,6 +6774,15 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +[[package]] +name = "wasi" +version = "0.13.3+wasi-0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2" +dependencies = [ + "wit-bindgen-rt", +] + [[package]] name = "wasm-bindgen" version = "0.2.99" @@ -7391,6 +7418,15 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "wit-bindgen-rt" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" +dependencies = [ + "bitflags 2.6.0", +] + [[package]] name = "write16" version = "1.0.0" @@ -7642,6 +7678,9 @@ name = "zeroize" version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" +dependencies = [ + "serde", +] [[package]] name = "zerovec" diff --git a/crates/radicle-tauri/Cargo.toml b/crates/radicle-tauri/Cargo.toml index 912678f9e..13e40405c 100644 --- a/crates/radicle-tauri/Cargo.toml +++ b/crates/radicle-tauri/Cargo.toml @@ -32,6 +32,8 @@ tauri-plugin-window-state = { version = "2.2.1" } thiserror = { version = "1.0.64" } tokio = { version = "1.40.0", features = ["time"] } ts-rs = { version = "10.0.0", features = ["serde-json-impl", "no-serde-warnings"] } +ssh-key = { version = "0.6.3" } +zeroize = { version = "1.8.1", features = ["serde"] } [features] # by default Tauri runs in production mode diff --git a/crates/radicle-tauri/src/commands.rs b/crates/radicle-tauri/src/commands.rs index 600925679..c8005304d 100644 --- a/crates/radicle-tauri/src/commands.rs +++ b/crates/radicle-tauri/src/commands.rs @@ -2,7 +2,7 @@ pub mod auth; pub mod cob; pub mod diff; pub mod inbox; -pub mod init; pub mod profile; pub mod repo; +pub mod startup; pub mod thread; diff --git a/crates/radicle-tauri/src/commands/auth.rs b/crates/radicle-tauri/src/commands/auth.rs index 3ff3a9569..3209abf22 100644 --- a/crates/radicle-tauri/src/commands/auth.rs +++ b/crates/radicle-tauri/src/commands/auth.rs @@ -1,9 +1,84 @@ +use std::str::FromStr; + +use radicle::crypto::ssh::{self, Passphrase}; +use radicle::node::Alias; +use radicle::profile::env; use radicle_types::error::Error; -use radicle_types::traits::auth::Auth; use crate::AppState; #[tauri::command] -pub(crate) fn authenticate(ctx: tauri::State) -> Result<(), Error> { - ctx.authenticate().map_err(Error::from) +pub fn authenticate( + ctx: tauri::State, + passphrase: Option, +) -> Result<(), Error> { + let profile = &ctx.profile; + if !profile.keystore.is_encrypted()? { + return Ok(()); + } + match ssh::agent::Agent::connect() { + Ok(mut agent) => { + if agent.request_identities()?.contains(&profile.public_key) { + return Ok(()); + } + + match passphrase { + Some(passphrase) => { + profile.keystore.secret_key(Some(passphrase.clone()))?; + register(&mut agent, profile, passphrase) + } + None => Err(Error::Crypto( + radicle::crypto::ssh::keystore::Error::PassphraseMissing, + )), + } + } + Err(e) if e.is_not_running() => Err(Error::AgentNotRunning)?, + Err(e) => Err(e)?, + } +} + +#[tauri::command] +pub(crate) fn init(alias: String, passphrase: Passphrase) -> Result<(), Error> { + let home = radicle::profile::home()?; + let alias = Alias::from_str(&alias)?; + + if passphrase.is_empty() { + return Err(Error::Crypto( + radicle::crypto::ssh::keystore::Error::PassphraseMissing, + )); + } + let profile = radicle::Profile::init(home, alias, Some(passphrase.clone()), env::seed())?; + match ssh::agent::Agent::connect() { + Ok(mut agent) => register(&mut agent, &profile, passphrase.clone())?, + Err(e) if e.is_not_running() => return Err(Error::AgentNotRunning), + Err(e) => Err(e)?, + } + + Ok(()) +} + +pub fn register( + agent: &mut ssh::agent::Agent, + profile: &radicle::Profile, + passphrase: ssh::Passphrase, +) -> Result<(), Error> { + let secret = profile + .keystore + .secret_key(Some(passphrase)) + .map_err(|e| { + if e.is_crypto_err() { + Error::Crypto(radicle::crypto::ssh::keystore::Error::Ssh( + ssh_key::Error::Crypto, + )) + } else { + e.into() + } + })? + .ok_or(Error::Crypto(radicle::crypto::ssh::keystore::Error::Ssh( + ssh_key::Error::Crypto, + )))?; + + agent.register(&secret)?; + + Ok(()) } diff --git a/crates/radicle-tauri/src/commands/cob.rs b/crates/radicle-tauri/src/commands/cob.rs index dcc2fae25..e9b54c7cf 100644 --- a/crates/radicle-tauri/src/commands/cob.rs +++ b/crates/radicle-tauri/src/commands/cob.rs @@ -1,7 +1,5 @@ use std::path::PathBuf; -use anyhow::{Context, Result}; - use radicle::git; use radicle::identity; use radicle_types as types; @@ -44,8 +42,7 @@ pub async fn save_embed_by_clipboard( let content = app_handle .clipboard() .read_image() - .map(|i| i.rgba().to_vec()) - .context("Not able to read the image from the clipboard")?; + .map(|i| i.rgba().to_vec())?; ctx.save_embed_by_bytes(rid, name, content) } @@ -68,16 +65,15 @@ pub async fn save_embed_to_disk( oid: git::Oid, name: String, ) -> Result<(), Error> { - let path = app_handle + let Some(path) = app_handle .dialog() .file() .set_file_name(name) .blocking_save_file() - .context("no path defined")?; - - let path = path - .into_path() - .context("Not able to convert into PathBuf")?; + else { + return Err(Error::SaveEmbedError); + }; + let path = path.into_path()?; ctx.save_embed_to_disk(rid, oid, path) } diff --git a/crates/radicle-tauri/src/commands/repo.rs b/crates/radicle-tauri/src/commands/repo.rs index 054037b3d..433c085c9 100644 --- a/crates/radicle-tauri/src/commands/repo.rs +++ b/crates/radicle-tauri/src/commands/repo.rs @@ -1,6 +1,13 @@ -use radicle::git; -use radicle::identity::RepoId; +use std::collections::BTreeSet; +use std::str::FromStr; +use radicle::git; +use radicle::identity::project::ProjectName; +use radicle::identity::{doc, Project, RepoId, Visibility}; +use radicle::rad::InitError; +use radicle::storage::git::Repository; +use radicle::storage::refs::branch_of; +use radicle::storage::{SignRepository, WriteRepository}; use radicle_types as types; use radicle_types::error::Error; use radicle_types::traits::repo::{Repo, Show}; @@ -47,3 +54,69 @@ pub async fn list_commits( ) -> Result, Error> { ctx.list_commits(rid, base, head) } + +#[tauri::command] +pub(crate) async fn create_repo( + ctx: tauri::State<'_, AppState>, + name: String, + description: String, +) -> Result<(), Error> { + let profile = &ctx.profile; + let storage = &profile.storage; + let signer = ctx.profile.signer()?; + let config = radicle::git::raw::Config::open_default()?; + // SAFETY: "master" is always a valid RefString + let default_branch = git::RefString::try_from( + config + .get_string("init.defaultBranch") + .unwrap_or("master".to_owned()), + ) + .unwrap(); + + let name = ProjectName::from_str(&name)?; + if description.len() > doc::MAX_STRING_LENGTH { + return Err(Error::ProjectError( + radicle::identity::project::ProjectError::Description("Cannot exceed 255 characters."), + )); + } + + let visibility = Visibility::Private { + allow: BTreeSet::default(), + }; + + let proj = Project::new(name, description, default_branch.clone()).map_err(|errs| { + InitError::ProjectPayload( + errs.into_iter() + .map(|err| err.to_string()) + .collect::>() + .join(", "), + ) + })?; + let doc = radicle::identity::Doc::initial(proj, profile.public_key.into(), visibility); + let (project, identity) = Repository::init(&doc, &storage, &signer)?; + + let tree_id = { + let mut index = project.backend.index()?; + + index.write_tree() + }?; + let sig = project.backend.signature()?; + let tree = project.backend.find_tree(tree_id)?; + + project.set_remote_identity_root_to(signer.public_key(), identity)?; + project.set_identity_head_to(identity)?; + + let base = project + .backend + .commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])?; + + let ns_head = branch_of(&ctx.profile.public_key, &default_branch); + project + .backend + .reference(ns_head.as_str(), base, false, "Created namespace ref")?; + + project.set_head()?; + project.sign_refs(&signer)?; + + Ok(()) +} diff --git a/crates/radicle-tauri/src/commands/init.rs b/crates/radicle-tauri/src/commands/startup.rs similarity index 74% rename from crates/radicle-tauri/src/commands/init.rs rename to crates/radicle-tauri/src/commands/startup.rs index 3fd14d353..22bdc96ea 100644 --- a/crates/radicle-tauri/src/commands/init.rs +++ b/crates/radicle-tauri/src/commands/startup.rs @@ -14,6 +14,8 @@ use radicle_types::{domain, AppState}; #[tauri::command] pub(crate) fn startup(app: AppHandle) -> Result { let profile = radicle::Profile::load()?; + let repositories = profile.storage.repositories()?; + let public_key = profile.public_key; let inbox_db = radicle_types::outbound::sqlite::Sqlite::reader( profile.node().join(NOTIFICATIONS_DB_FILE), @@ -24,43 +26,25 @@ pub(crate) fn startup(app: AppHandle) -> Result { let inbox_service = domain::inbox::service::Service::new(inbox_db); let patch_service = domain::patch::service::Service::new(cob_db); + let node_handle = app.app_handle().clone(); + let sync_handle = app.app_handle().clone(); + let events_handle = app.app_handle().clone(); + + let node = Node::new(profile.socket()); + let node_status = node.clone(); + + let mut node_seeds = node.clone(); + app.manage(inbox_service); app.manage(patch_service); - let state = AppState { profile }; - app.manage(state.clone()); - - Ok(state.config()) -} - -#[tauri::command] -pub(crate) fn node_status_events(app: AppHandle, ctx: tauri::State) -> Result<(), Error> { - let app_handle = app.clone(); - - let node = Node::new(ctx.profile.socket()); - let node_status = node.clone(); - tauri::async_runtime::spawn(async move { loop { - let _ = app_handle.emit("node_running", node_status.is_running()); + let _ = node_handle.emit("node_running", node_status.is_running()); tokio::time::sleep(std::time::Duration::from_secs(2)).await; } }); - Ok(()) -} - -#[tauri::command] -pub(crate) fn repo_sync_events(app: AppHandle, ctx: tauri::State) -> Result<(), Error> { - let profile = &ctx.profile; - let repositories = profile.storage.repositories()?; - - let app_handle = app.clone(); - let public_key = profile.public_key; - - let node = Node::new(profile.socket()); - let mut node_seeds = node.clone(); - tauri::async_runtime::spawn(async move { loop { let mut sync_status = @@ -81,34 +65,29 @@ pub(crate) fn repo_sync_events(app: AppHandle, ctx: tauri::State) -> R } } } - let _ = app_handle.emit("sync_status", sync_status); + let _ = sync_handle.emit("sync_status", sync_status); tokio::time::sleep(std::time::Duration::from_secs(10)).await; } }); - Ok(()) -} - -#[tauri::command] -pub(crate) fn node_events(app: AppHandle, ctx: tauri::State) -> Result<(), Error> { - let app_handle = app.clone(); - let node = Node::new(ctx.profile.socket()); - tauri::async_runtime::spawn(async move { loop { if node.is_running() { - log::debug!("node: spawned node event subscription."); + log::info!("node: spawned node event subscription."); while let Ok(events) = node.subscribe(std::time::Duration::MAX) { for event in events.into_iter().flatten() { - let _ = app_handle.emit("event", event); + let _ = events_handle.emit("event", event); } } - log::debug!("node: event subscription loop has exited."); + log::info!("node: event subscription loop has exited."); } tokio::time::sleep(std::time::Duration::from_secs(2)).await; } }); - Ok(()) + let state = AppState { profile }; + app.manage(state.clone()); + + Ok(state.config()) } diff --git a/crates/radicle-tauri/src/lib.rs b/crates/radicle-tauri/src/lib.rs index 53540942c..bc735741a 100644 --- a/crates/radicle-tauri/src/lib.rs +++ b/crates/radicle-tauri/src/lib.rs @@ -2,7 +2,7 @@ mod commands; use radicle_types::AppState; -use commands::{auth, cob, diff, inbox, init, profile, repo, thread}; +use commands::{auth, cob, diff, inbox, profile, repo, startup, thread}; #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { @@ -22,42 +22,43 @@ pub fn run() { .plugin(tauri_plugin_clipboard_manager::init()) .plugin(tauri_plugin_window_state::Builder::default().build()) .invoke_handler(tauri::generate_handler![ - init::startup, - init::node_status_events, - init::repo_sync_events, - init::node_events, auth::authenticate, - repo::repo_count, - repo::list_repos, - repo::repo_by_id, - repo::diff_stats, - repo::list_commits, - diff::get_diff, - inbox::list_notifications, - inbox::count_notifications_by_repo, - inbox::clear_notifications, + auth::init, cob::get_embed, - cob::save_embed_to_disk, - cob::save_embed_by_path, - cob::save_embed_by_clipboard, - cob::save_embed_by_bytes, cob::issue::activity_by_issue, - cob::issue::list_issues, - cob::issue::issue_by_id, cob::issue::comment_threads_by_issue_id, cob::issue::create_issue, cob::issue::edit_issue, + cob::issue::issue_by_id, + cob::issue::list_issues, cob::patch::activity_by_patch, + cob::patch::edit_patch, cob::patch::list_patches, cob::patch::patch_by_id, cob::patch::edit_patch, cob::patch::review_by_patch_and_revision_and_id, cob::patch::revisions_by_patch, cob::patch::revision_by_patch_and_id, + cob::patch::revisions_by_patch, + cob::save_embed_by_bytes, + cob::save_embed_by_clipboard, + cob::save_embed_by_path, + cob::save_embed_to_disk, + diff::get_diff, + inbox::clear_notifications, + inbox::count_notifications_by_repo, + inbox::list_notifications, + profile::alias, + profile::config, + repo::create_repo, + repo::diff_stats, + repo::list_commits, + repo::list_repos, + repo::repo_by_id, + repo::repo_count, + startup::startup, thread::create_issue_comment, thread::create_patch_comment, - profile::config, - profile::alias, ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/crates/radicle-types/Cargo.toml b/crates/radicle-types/Cargo.toml index e906562ee..88f3598fb 100644 --- a/crates/radicle-types/Cargo.toml +++ b/crates/radicle-types/Cargo.toml @@ -16,6 +16,9 @@ radicle-surf = { version = "0.22.1", features = ["serde"] } serde = { version = "1.0.210", features = ["derive"] } serde_json = { version = "1.0.132" } sqlite = { version = "0.32.0", features = ["bundled"] } +ssh-key = { version = "0.6.3" } +tauri-plugin-clipboard-manager = { version = "2.2.1" } +tauri-plugin-fs = { version = "2.2.0" } tempfile = { version = "3.14.0" } thiserror = { version = "1.0.65" } tree-sitter-bash = { version = "0.23.3" } diff --git a/crates/radicle-types/bindings/error/ErrorWrapper.ts b/crates/radicle-types/bindings/error/ErrorWrapper.ts new file mode 100644 index 000000000..c7c4c34ac --- /dev/null +++ b/crates/radicle-types/bindings/error/ErrorWrapper.ts @@ -0,0 +1,3 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ErrorWrapper = { code: string; message?: string }; diff --git a/crates/radicle-types/src/error.rs b/crates/radicle-types/src/error.rs index 62053ccd8..842de9747 100644 --- a/crates/radicle-types/src/error.rs +++ b/crates/radicle-types/src/error.rs @@ -9,7 +9,35 @@ use crate::cobs::stream; pub enum Error { /// Profile error. #[error(transparent)] - Profile(#[from] radicle::profile::Error), + ProfileError(#[from] radicle::profile::Error), + + /// Missing SSH Agent error. + #[error("ssh agent not running")] + AgentNotRunning, + + /// Embeds error. + #[error("not able to save embed")] + SaveEmbedError, + + /// Init Error error. + #[error(transparent)] + InitError(#[from] radicle::rad::InitError), + + /// Alias error. + #[error(transparent)] + AliasError(#[from] radicle::node::AliasError), + + /// Tauri Plugin Clipboard error. + #[error(transparent)] + TauriPluginClipboard(#[from] tauri_plugin_clipboard_manager::Error), + + /// Tauri Plugin Fs error. + #[error(transparent)] + TauriPluginFs(#[from] tauri_plugin_fs::Error), + + /// Project error. + #[error(transparent)] + ProjectError(#[from] radicle::identity::project::ProjectError), /// List notification error. #[error(transparent)] @@ -25,10 +53,6 @@ pub enum Error { #[error(transparent)] CobStore(#[from] radicle::cob::store::Error), - /// Anyhow error. - #[error(transparent)] - Anyhow(#[from] anyhow::Error), - /// Io error. #[error(transparent)] Io(#[from] std::io::Error), @@ -109,45 +133,60 @@ pub enum Error { #[error(transparent)] Node(#[from] radicle::node::Error), - /// An error with a hint. - #[error("{err} {hint}")] - WithHint { - err: anyhow::Error, - hint: &'static str, - }, - /// Serde JSON error. #[error(transparent)] SerdeJSON(#[from] serde_json::error::Error), } -#[derive(Serialize)] -struct ErrorWrapperWithHint { - err: String, - hint: String, +impl Error { + #[must_use] + pub const fn code(&self) -> &'static str { + match self { + Error::ProjectError(radicle::identity::project::ProjectError::Name(_)) => { + "ProjectError.InvalidName" + } + Error::ProjectError(radicle::identity::project::ProjectError::Description(_)) => { + "ProjectError.InvalidDescription" + } + Error::Crypto(radicle::crypto::ssh::keystore::Error::Ssh(ssh_key::Error::Crypto)) + | Error::Crypto(radicle::crypto::ssh::keystore::Error::PassphraseMissing) => { + "PassphraseError.InvalidPassphrase" + } + Error::AliasError(radicle::node::AliasError::Empty) => "AliasError.EmptyAlias", + Error::AliasError(radicle::node::AliasError::MaxBytesExceeded) => { + "AliasError.TooLongAlias" + } + Error::ProfileError(radicle::profile::Error::NotFound(_)) => { + "IdentityError.MissingProfile" + } + Error::AliasError(radicle::node::AliasError::InvalidCharacter) => { + "AliasError.InvalidAlias" + } + _ => "UnknownError", + } + } } -#[derive(Serialize)] -struct ErrorWrapper { - err: String, +#[derive(Serialize, ts_rs::TS, Debug)] +#[ts(export)] +#[ts(export_to = "error/")] +pub struct ErrorWrapper { + code: String, + #[ts(optional)] + message: Option, } -impl Serialize for Error { +impl serde::Serialize for Error { fn serialize(&self, serializer: S) -> Result where S: serde::ser::Serializer, { - match self { - Error::WithHint { err, hint } => ErrorWrapperWithHint { - err: err.to_string(), - hint: hint.to_string(), - } - .serialize(serializer), - err => ErrorWrapper { - err: err.to_string(), - } - .serialize(serializer), - } + use serde::ser::SerializeStruct; + + let mut state = serializer.serialize_struct("ErrorWrapper", 2)?; + state.serialize_field("code", &self.code().to_string())?; + state.serialize_field("message", &self.to_string())?; + state.end() } } @@ -164,14 +203,27 @@ impl IntoResponse for Error { #[cfg(test)] #[allow(clippy::unwrap_used)] mod test { - use super::Error; - use anyhow::anyhow; + use crate::error::Error; #[test] - fn serialize_errors() { - assert_eq!(serde_json::to_string(&Error::WithHint { - err: anyhow!("Not able to find your keys in the ssh agent"), - hint: "Make sure to run rad auth in your terminal to add your keys to the ssh-agent.", - }).unwrap(),"{\"err\":\"Not able to find your keys in the ssh agent\",\"hint\":\"Make sure to run rad auth in your terminal to add your keys to the ssh-agent.\"}"); + fn serialize_nested_errors() { + let serialized = serde_json::to_string(&Error::Crypto( + radicle::crypto::ssh::keystore::Error::Ssh(ssh_key::Error::Crypto), + )) + .unwrap(); + assert_eq!( + serialized, + "{\"code\":\"PassphraseError.InvalidPassphrase\",\"message\":\"ssh keygen: cryptographic error\"}" + ); + } + + #[test] + fn serialize_unknown_errors() { + let serialized = + serde_json::to_string(&Error::Issue(radicle::issue::Error::MissingIdentity)).unwrap(); + assert_eq!( + serialized, + "{\"code\":\"UnknownError\",\"message\":\"identity document missing\"}" + ); } } diff --git a/crates/radicle-types/src/lib.rs b/crates/radicle-types/src/lib.rs index 9e7c6aba4..e455cd822 100644 --- a/crates/radicle-types/src/lib.rs +++ b/crates/radicle-types/src/lib.rs @@ -1,4 +1,3 @@ -use traits::auth::Auth; use traits::cobs::Cobs; use traits::issue::{Issues, IssuesMut}; use traits::patch::{Patches, PatchesMut}; @@ -22,7 +21,6 @@ pub struct AppState { pub profile: radicle::Profile, } -impl Auth for AppState {} impl Repo for AppState {} impl Thread for AppState {} impl Cobs for AppState {} diff --git a/crates/radicle-types/src/repo.rs b/crates/radicle-types/src/repo.rs index 59ac1cc9a..f35681012 100644 --- a/crates/radicle-types/src/repo.rs +++ b/crates/radicle-types/src/repo.rs @@ -100,7 +100,7 @@ impl TryFrom for ProjectPayloadData { type Error = error::Error; fn try_from(value: identity::doc::Payload) -> Result { - serde_json::from_value::((*value).clone()).map_err(error::Error::from) + serde_json::from_value::((*value).clone()).map_err(Into::into) } } diff --git a/crates/radicle-types/src/traits.rs b/crates/radicle-types/src/traits.rs index 674ae27d2..10b756603 100644 --- a/crates/radicle-types/src/traits.rs +++ b/crates/radicle-types/src/traits.rs @@ -2,7 +2,6 @@ use radicle::node::{AliasStore, NodeId}; use crate::config::Config; -pub mod auth; pub mod cobs; pub mod issue; pub mod patch; diff --git a/crates/radicle-types/src/traits/auth.rs b/crates/radicle-types/src/traits/auth.rs deleted file mode 100644 index 74135137e..000000000 --- a/crates/radicle-types/src/traits/auth.rs +++ /dev/null @@ -1,31 +0,0 @@ -use anyhow::anyhow; - -use radicle::crypto::ssh; - -use crate::error::Error; - -use super::Profile; - -pub trait Auth: Profile { - fn authenticate(&self) -> Result<(), Error> { - let profile = &self.profile(); - - if !profile.keystore.is_encrypted()? { - return Ok(()); - } - match ssh::agent::Agent::connect() { - Ok(mut agent) => { - if agent.request_identities()?.contains(&profile.public_key) { - Ok(()) - } else { - Err(Error::WithHint { - err: anyhow!("Not able to find your keys in the ssh agent"), - hint: "Make sure to run rad auth in your terminal to add your keys to the ssh-agent.", - })? - } - } - Err(e) if e.is_not_running() => Err(Error::WithHint { err: anyhow!("SSH Agent is not running"), hint: "For now we require the user to have an ssh agent running, since we don't have passphrase inputs yet." })?, - Err(e) => Err(e)?, - } - } -} diff --git a/crates/test-http-api/src/api.rs b/crates/test-http-api/src/api.rs index 223a0c5c3..fcfa14e06 100644 --- a/crates/test-http-api/src/api.rs +++ b/crates/test-http-api/src/api.rs @@ -23,7 +23,6 @@ use radicle_types::domain::patch::service::Service; use radicle_types::domain::patch::traits::PatchService; use radicle_types::error::Error; use radicle_types::outbound::sqlite::Sqlite; -use radicle_types::traits::auth::Auth; use radicle_types::traits::cobs::Cobs; use radicle_types::traits::issue::{Issues, IssuesMut}; use radicle_types::traits::patch::{Patches, PatchesMut}; @@ -37,7 +36,6 @@ pub struct Context { patches: Arc>, } -impl Auth for Context {} impl Repo for Context {} impl Cobs for Context {} impl Thread for Context {} @@ -107,9 +105,7 @@ async fn config_handler(State(ctx): State) -> impl IntoResponse { Ok::<_, Error>(Json(config)) } -async fn auth_handler(State(ctx): State) -> impl IntoResponse { - ctx.authenticate()?; - +async fn auth_handler() -> impl IntoResponse { Ok::<_, Error>(Json(())) } diff --git a/public/index.css b/public/index.css index 981574a3e..be8155414 100644 --- a/public/index.css +++ b/public/index.css @@ -76,6 +76,16 @@ body { flex-shrink: 0; } +.global-link { + color: var(--color-foreground-default); + text-decoration: none; +} +.global-link:hover { + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 2px; +} + :root { --elevation-low: 0 0 48px 0 #000000ee; } diff --git a/src/App.svelte b/src/App.svelte index ad0e9db95..807ffa443 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -1,78 +1,60 @@ {#if $activeRouteStore.resource === "booting"} + {#if startup.error?.code === "IdentityError.MissingProfile"} + + {:else if startup.error?.code === "PassphraseError.InvalidPassphrase" && profile} + {/if} {:else if $activeRouteStore.resource === "home"} diff --git a/src/components/Icon.svelte b/src/components/Icon.svelte index 072c7494e..02eed409b 100644 --- a/src/components/Icon.svelte +++ b/src/components/Icon.svelte @@ -37,6 +37,7 @@ | "face" | "file" | "home" + | "info" | "inbox" | "issue" | "issue-closed" @@ -583,6 +584,21 @@ + {:else if name === "info"} + + + + + + + + + + + + + + {:else if name === "issue"} diff --git a/src/components/IssueTimeline.svelte b/src/components/IssueTimeline.svelte index 6b329da21..819bf3780 100644 --- a/src/components/IssueTimeline.svelte +++ b/src/components/IssueTimeline.svelte @@ -72,15 +72,6 @@ + +
+ + +
Unlock keys
+
Your passphrase is needed to unlock your keys.
+
+
+ +
+
Alias
+
+ {profile.alias} +
+
+
+ +
+
DID
+
+ {truncateDid(profile.did)} +
+
+
+
+
+
Passphrase
+ { + error = undefined; + }} + placeholder="Enter passphrase to unlock your keys" + type="password" + bind:value={passphrase} /> + {#if error?.code === "PassphraseError.InvalidPassphrase"} +
+ + Not able to decrypt keys with provided passphrase. +
+ {/if} +
+ +
+
diff --git a/src/views/booting/CreateIdentity.svelte b/src/views/booting/CreateIdentity.svelte new file mode 100644 index 000000000..7f5e09829 --- /dev/null +++ b/src/views/booting/CreateIdentity.svelte @@ -0,0 +1,218 @@ + + + + +
+ + +
Log in to Radicle Desktop
+
+ Create a Radicle identity in order to use the app. +
+ +
+
+
Alias (required)
+ { + errors.alias = []; + if (alias.length > 0) { + validateInput("alias"); + } + }} + placeholder="Enter desired alias" + type="text" + bind:value={alias}> + {#if errors.alias.some(e => e.code.startsWith("AliasError"))} + {#each errors.alias as error} +
+ + {#if error.code === "AliasError.EmptyAlias"} + Alias cannot be empty. + {:else if error.code === "AliasError.TooLongAlias"} + Alias is too long, make it less than 32 characters. + {:else if error.code === "AliasError.InvalidAlias"} + Alias cannot contain whitespace. + {/if} +
+ {/each} + {:else} +
+ Max 32 characters, no whitespace. +
+ {/if} +
+
+
+
Passphrase (required)
+ { + errors.passphrase = []; + notMatchingPassphrases = false; + if (passphrase.length > 0) { + validateInput("passphrase"); + } + }} + placeholder="Enter passphrase to protect your keys" + type="password" + bind:value={passphrase}> + {#if errors.passphrase.some(e => e.code.startsWith("PassphraseError"))} + {#each errors.passphrase as error} +
+ + {#if error.code === "PassphraseError.InvalidPassphrase"} + Passphrase cannot be empty. + {:else} + {error.message} + {/if} +
+ {/each} + {/if} +
+
+ { + errors.passphrase = []; + notMatchingPassphrases = false; + validatePassphraseRepeat(); + }} + placeholder="Repeat passphrase" + type="password" + bind:value={passphraseRepeat}> + {#if notMatchingPassphrases} +
+ Passphrases don't match +
+ {/if} +
+
+ +
+
diff --git a/src/views/home/Onboarding.svelte b/src/views/home/Onboarding.svelte new file mode 100644 index 000000000..07312a65b --- /dev/null +++ b/src/views/home/Onboarding.svelte @@ -0,0 +1,226 @@ + + + + +{#snippet tabSnippet(name: typeof tab, content: string)} + { + tab = name; + }}> + {content} + +{/snippet} + +
+ You don't have any repositories in your Radicle storage yet. To get started, + try one of the options below. +
+ + {@render tabSnippet("create", "Create a new repo")} + {@render tabSnippet("init", "Initialize existing repo")} + + + + {#if tab === "create"} +
+
+
Create a new repo initialized with Radicle.
+ +
+
+
Repository name (required)
+ { + errors.repoName = []; + validateInput("name"); + }} + placeholder="Name of your repo" /> + {#if errors.repoName.length > 0} + {#each errors.repoName as error} + {#if error.code === "ProjectError.InvalidName" && repoName.length > 0} +
+ + + Only alphanumeric characters, '-', '_' and '.' are + allowed. + +
+ {/if} + {/each} + {/if} +
+ +
+
Description
+