handshakes

This commit is contained in:
DecDuck
2024-10-08 18:08:52 +11:00
parent ae4c65b7ab
commit 4bb33c8223
9 changed files with 285 additions and 43 deletions

View File

@ -3,11 +3,12 @@ use std::{
sync::Mutex,
};
use log::info;
use serde::{Deserialize, Serialize};
use tauri::{App, AppHandle, Emitter, Error, EventLoopMessage, Wry};
use tauri::{App, AppHandle, Emitter, Error, EventLoopMessage, Manager, Wry};
use url::Url;
use crate::{AppStatus, User, DB};
use crate::{data::DatabaseCerts, AppState, AppStatus, User, DB};
#[derive(Serialize)]
struct InitiateRequestBody {
@ -15,11 +16,78 @@ struct InitiateRequestBody {
platform: String,
}
pub async fn recieve_handshake(app: AppHandle, path: String) {
// Tell the app we're connecting
app.emit("auth/connecting", ()).unwrap();
#[derive(Serialize)]
struct HandshakeRequestBody {
clientId: String,
token: String,
}
// TODO
#[derive(Deserialize)]
struct HandshakeResponse {
private: String,
public: String,
certificate: String,
id: String,
}
macro_rules! unwrap_or_return {
( $e:expr, $app:expr ) => {
match $e {
Ok(x) => x,
Err(_) => {
$app.emit("auth/failed", ()).unwrap();
return;
}
}
};
}
pub fn recieve_handshake(app: AppHandle, path: String) {
// Tell the app we're processing
app.emit("auth/processing", ()).unwrap();
let path_chunks: Vec<&str> = path.split("/").collect();
if path_chunks.len() != 3 {
app.emit("auth/failed", ()).unwrap();
return;
}
let base_url = {
let handle = DB.borrow_data().unwrap();
Url::parse(handle.base_url.as_str()).unwrap()
};
let client_id = path_chunks.get(1).unwrap();
let token = path_chunks.get(2).unwrap();
let body = HandshakeRequestBody {
clientId: client_id.to_string(),
token: token.to_string(),
};
let endpoint = unwrap_or_return!(base_url.join("/api/v1/client/handshake"), app);
let client = reqwest::blocking::Client::new();
let response = unwrap_or_return!(client.post(endpoint).json(&body).send(), app);
info!("server responded with {}", response.status());
let response_struct = unwrap_or_return!(response.json::<HandshakeResponse>(), app);
{
let mut handle = DB.borrow_data_mut().unwrap();
handle.certs = Some(DatabaseCerts {
private: response_struct.private,
public: response_struct.public,
cert: response_struct.certificate,
});
drop(handle);
DB.save().unwrap();
}
{
let app_state = app.state::<Mutex<AppState>>();
let mut app_state_handle = app_state.lock().unwrap();
app_state_handle.status = AppStatus::SignedIn;
}
app.emit("auth/finished", ()).unwrap();
}
#[tauri::command]
@ -48,6 +116,7 @@ pub async fn auth_initiate<'a>() -> Result<(), String> {
let redir_url = response.text().await.unwrap();
let complete_redir_url = base_url.join(&redir_url).unwrap();
info!("opening web browser to continue authentication");
webbrowser::open(&complete_redir_url.to_string()).unwrap();
return Ok(());
@ -59,12 +128,11 @@ pub fn setup() -> Result<(AppStatus, Option<User>), Error> {
// If we have certs, exit for now
if data.certs.is_some() {
// TODO: check if it's still valid, and fetch user information
info!("have existing certs, assuming logged in...");
return Ok((AppStatus::SignedInNeedsReauth, None));
}
drop(data);
auth_initiate();
return Ok((AppStatus::SignedOut, None));
}

View File

@ -4,15 +4,17 @@ mod remote;
mod unpacker;
use std::{
io,
sync::{LazyLock, Mutex},
task, thread,
};
use auth::{auth_initiate, recieve_handshake};
use data::DatabaseInterface;
use futures::executor;
use log::info;
use remote::use_remote;
use serde::Serialize;
use structured_logger::{json::new_writer, Builder};
use tauri_plugin_deep_link::DeepLinkExt;
#[derive(Clone, Copy, Serialize)]
@ -40,6 +42,10 @@ fn fetch_state<'a>(state: tauri::State<'_, Mutex<AppState>>) -> Result<AppState,
}
fn setup<'a>() -> AppState {
Builder::with_level("info")
.with_target_writer("*", new_writer(io::stdout()))
.init();
let is_set_up = data::is_set_up();
if !is_set_up {
return AppState {
@ -60,14 +66,14 @@ pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(|| data::setup());
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let state = setup();
info!("Initialized drop client");
let mut builder = tauri::Builder::default();
#[cfg(desktop)]
{
builder = builder.plugin(tauri_plugin_single_instance::init(|_app, argv, _cwd| {
println!("a new app instance was opened with {argv:?} and the deep link event was already triggered");
// when defining deep link schemes at runtime, you must also check `argv` here
// when defining deep link schemes at runtime, you must also check `argv` here
}));
}
@ -85,20 +91,17 @@ pub fn run() {
{
use tauri_plugin_deep_link::DeepLinkExt;
app.deep_link().register_all()?;
info!("registered all pre-defined deep links");
}
let handle = app.handle().clone();
app.deep_link().on_open_url(move |event| {
info!("handling drop:// url");
let binding = event.urls();
let url = binding.get(0).unwrap();
match url.host_str().unwrap() {
"handshake" => {
executor::block_on(recieve_handshake(
handle.clone(),
url.path().to_string(),
));
}
"handshake" => recieve_handshake(handle.clone(), url.path().to_string()),
_ => (),
}
});

View File

@ -3,6 +3,7 @@ use std::{
sync::Mutex,
};
use log::{info, warn};
use serde::Deserialize;
use url::Url;
@ -32,7 +33,7 @@ pub async fn use_remote<'a>(
url: String,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<(), String> {
println!("connecting to url {}", url);
info!("connecting to url {}", url);
let base_url = unwrap_or_return!(Url::parse(&url));
// Test Drop url
@ -42,6 +43,7 @@ pub async fn use_remote<'a>(
let result = response.json::<DropHealthcheck>().await.unwrap();
if result.appName != "Drop" {
warn!("user entered drop endpoint that connected, but wasn't identified as Drop");
return Err("Not a valid Drop endpoint".to_string());
}