reorganisation, cleanup and new nonce protocol

This commit is contained in:
DecDuck
2024-10-12 17:34:47 +11:00
parent ac66b20591
commit e828bca2a5
19 changed files with 429 additions and 60 deletions

View File

@ -1,10 +1,11 @@
use std::{
borrow::{Borrow, BorrowMut},
env,
fmt::format,
sync::Mutex,
};
use log::info;
use log::{info, warn};
use openssl::{
ec::EcKey,
hash::MessageDigest,
@ -12,11 +13,11 @@ use openssl::{
sign::{self, Signer},
};
use serde::{Deserialize, Serialize};
use tauri::{App, AppHandle, Emitter, Error, EventLoopMessage, Manager, Wry};
use tauri::{http::response, App, AppHandle, Emitter, EventLoopMessage, Manager, Wry};
use url::Url;
use uuid::Uuid;
use crate::{data::DatabaseAuth, AppState, AppStatus, User, DB};
use crate::{db::DatabaseAuth, AppState, AppStatus, User, DB};
#[derive(Serialize)]
struct InitiateRequestBody {
@ -49,7 +50,7 @@ macro_rules! unwrap_or_return {
};
}
pub fn sign_nonce(private_key: String, nonce: String) -> Result<String, Error> {
pub fn sign_nonce(private_key: String, nonce: String) -> Result<String, ()> {
let client_private_key = EcKey::private_key_from_pem(private_key.as_bytes()).unwrap();
let pkey_private_key = PKey::from_ec_key(client_private_key).unwrap();
@ -74,7 +75,7 @@ pub fn generate_authorization_header() -> String {
return format!("Nonce {} {} {}", certs.clientId, nonce, signature);
}
pub fn fetch_user() -> Result<User, Error> {
pub fn fetch_user() -> Result<User, ()> {
let base_url = {
let handle = DB.borrow_data().unwrap();
Url::parse(&handle.base_url).unwrap()
@ -90,6 +91,11 @@ pub fn fetch_user() -> Result<User, Error> {
.send()
.unwrap();
if response.status() != 200 {
warn!("Failed to fetch user: {}", response.status());
return Err(());
}
let user = response.json::<User>().unwrap();
return Ok(user);
@ -138,11 +144,10 @@ pub fn recieve_handshake(app: AppHandle, path: String) {
let app_state = app.state::<Mutex<AppState>>();
let mut app_state_handle = app_state.lock().unwrap();
app_state_handle.status = AppStatus::SignedIn;
app_state_handle.user = Some(fetch_user().unwrap());
}
app.emit("auth/finished", ()).unwrap();
fetch_user().unwrap();
}
#[tauri::command]
@ -152,12 +157,10 @@ pub async fn auth_initiate<'a>() -> Result<(), String> {
Url::parse(&db_lock.base_url.clone()).unwrap()
};
let current_os_info = os_info::get();
let endpoint = base_url.join("/api/v1/client/auth/initiate").unwrap();
let body = InitiateRequestBody {
name: format!("Drop Desktop Client"),
platform: current_os_info.os_type().to_string(),
platform: env::consts::OS.to_string(),
};
let client = reqwest::Client::new();
@ -168,6 +171,10 @@ pub async fn auth_initiate<'a>() -> Result<(), String> {
.await
.unwrap();
if response.status() != 200 {
return Err("Failed to create redirect URL. Please try again later.".to_string());
}
let redir_url = response.text().await.unwrap();
let complete_redir_url = base_url.join(&redir_url).unwrap();
@ -177,7 +184,7 @@ pub async fn auth_initiate<'a>() -> Result<(), String> {
return Ok(());
}
pub fn setup() -> Result<(AppStatus, Option<User>), Error> {
pub fn setup() -> Result<(AppStatus, Option<User>), ()> {
let data = DB.borrow_data().unwrap();
// If we have certs, exit for now
@ -186,7 +193,7 @@ pub fn setup() -> Result<(AppStatus, Option<User>), Error> {
if user_result.is_err() {
return Ok((AppStatus::SignedInNeedsReauth, None));
}
return Ok((AppStatus::SignedIn, Some(user_result.unwrap())))
return Ok((AppStatus::SignedIn, Some(user_result.unwrap())));
}
drop(data);

View File

@ -1,4 +1,8 @@
use std::fs;
use std::{
fs::{self, create_dir_all},
path::PathBuf,
sync::LazyLock,
};
use directories::BaseDirs;
use rustbreak::{deser::Bincode, PathDatabase};
@ -13,20 +17,37 @@ pub struct DatabaseAuth {
pub clientId: String,
}
#[derive(serde::Serialize, Clone, Deserialize)]
pub struct DatabaseApps {
pub apps_base_dir: String,
}
#[derive(serde::Serialize, Clone, Deserialize)]
pub struct Database {
pub auth: Option<DatabaseAuth>,
pub base_url: String,
pub downloads: DatabaseApps,
}
pub type DatabaseInterface =
rustbreak::Database<Database, rustbreak::backend::PathBackend, Bincode>;
pub static DATA_ROOT_DIR: LazyLock<PathBuf> =
LazyLock::new(|| BaseDirs::new().unwrap().data_dir().join("drop"));
pub fn setup() -> DatabaseInterface {
let db_path = BaseDirs::new().unwrap().data_dir().join("drop");
let db_path = DATA_ROOT_DIR.join("drop.db");
let apps_base_dir = DATA_ROOT_DIR.join("apps");
create_dir_all(DATA_ROOT_DIR.clone()).unwrap();
create_dir_all(apps_base_dir.clone()).unwrap();
let default = Database {
auth: None,
base_url: "".to_string(),
downloads: DatabaseApps {
apps_base_dir: apps_base_dir.to_str().unwrap().to_string(),
},
};
let db = match fs::exists(db_path.clone()).unwrap() {
true => PathDatabase::load_from_path(db_path).expect("Database loading failed"),

View File

@ -1,5 +1,5 @@
mod auth;
mod data;
mod db;
mod remote;
mod unpacker;
@ -10,7 +10,7 @@ use std::{
};
use auth::{auth_initiate, recieve_handshake};
use data::DatabaseInterface;
use db::{DatabaseInterface, DATA_ROOT_DIR};
use log::info;
use remote::{gen_drop_url, use_remote};
use serde::{Deserialize, Serialize};
@ -52,7 +52,7 @@ fn setup<'a>() -> AppState {
.with_target_writer("*", new_writer(io::stdout()))
.init();
let is_set_up = data::is_set_up();
let is_set_up = db::is_set_up();
if !is_set_up {
return AppState {
status: AppStatus::NotConfigured,
@ -67,14 +67,14 @@ fn setup<'a>() -> AppState {
};
}
pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(|| data::setup());
pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(|| db::setup());
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let state = setup();
info!("Initialized drop client");
let mut builder = tauri::Builder::default();
let mut builder = tauri::Builder::default().plugin(tauri_plugin_dialog::init());
#[cfg(desktop)]
{
@ -103,6 +103,19 @@ pub fn run() {
let handle = app.handle().clone();
let main_window = tauri::WebviewWindowBuilder::new(
&handle,
"main", // BTW this is not the name of the window, just the label. Keep this 'main', there are permissions & configs that depend on it
tauri::WebviewUrl::App("index.html".into()),
)
.title("Drop Desktop App")
.min_inner_size(900.0, 900.0)
.inner_size(1536.0, 864.0)
.decorations(false)
.data_directory(DATA_ROOT_DIR.join(".webview"))
.build()
.unwrap();
app.deep_link().on_open_url(move |event| {
info!("handling drop:// url");
let binding = event.urls();
@ -112,6 +125,7 @@ pub fn run() {
_ => (),
}
});
Ok(())
})
.run(tauri::generate_context!())