From 0769bfad28607a2b344a2c0f7d1a79b029401df2 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 8 May 2025 14:00:00 -0400 Subject: [PATCH] sora logout handler --- .../src/commands/command_response_wrapper.rs | 99 +++++++++++++++++++ crates/desktop/artcraft/src/commands/mod.rs | 1 + .../desktop/artcraft/src/commands/sora/mod.rs | 1 + .../src/commands/sora/sora_logout_command.rs | 35 +++++++ crates/desktop/artcraft/src/lib.rs | 2 + .../src/state/sora/sora_credential_manager.rs | 35 +++++++ .../sora_login_window/sora_login_thread.rs | 7 +- 7 files changed, 174 insertions(+), 6 deletions(-) create mode 100644 crates/desktop/artcraft/src/commands/command_response_wrapper.rs create mode 100644 crates/desktop/artcraft/src/commands/sora/sora_logout_command.rs diff --git a/crates/desktop/artcraft/src/commands/command_response_wrapper.rs b/crates/desktop/artcraft/src/commands/command_response_wrapper.rs new file mode 100644 index 0000000000..a3207900f4 --- /dev/null +++ b/crates/desktop/artcraft/src/commands/command_response_wrapper.rs @@ -0,0 +1,99 @@ +use serde::Serialize; +use std::error::Error; +use std::str::FromStr; + +/// Easy to use Result type. +pub type CommandResult = Result, CommandErrorResponseWrapper>; + +/// Statuses for successful commands. +#[derive(Serialize, Clone, Debug)] +#[serde(rename_all = "snake_case")] +pub enum CommandSuccessStatus { + Success, // 200 +} + +/// Statuses for errorful commands. +#[derive(Serialize, Clone, Debug)] +#[serde(rename_all = "snake_case")] +pub enum CommandErrorStatus { + BadRequest, // 400 + Unauthorized, // 401 + ServerError, // 500 +} + +#[derive(Serialize, Debug)] +pub struct CommandSuccessResponseWrapper { + /// Both "success" and "error" types have a `status` field for the frontend. + pub status: CommandSuccessStatus, + + #[serde(skip_serializing_if = "Option::is_none")] + pub payload: Option, +} + +#[derive(Serialize, Debug)] +pub struct CommandErrorResponseWrapper { + /// Both "success" and "error" types have a `status` field for the frontend. + pub status: CommandErrorStatus, + + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + + +impl CommandSuccessResponseWrapper<()> { + pub fn empty() -> Self { + CommandSuccessResponseWrapper { + status: CommandSuccessStatus::Success, + payload: None, + } + } +} + +/// NB: This is a hack because of `()` (a.k.a. the "unit" type) and `Serialize` trait coherence and overlap. +/// We cannot currently implement a trait for `()` and generic `Serialize` because `()` itself implements +/// `Serialize`. Rust's `"specialization"`, which would let us account for this, is an unstable, nightly-only +/// feature. So instead we manually mark all types other than `()` with `SerializeMarker` as a hack to +/// distinguish the two. +trait SerializeMarker : Serialize {} + +// NB: () is Serialize! So we can't broadly implement just `T: Serialize`. +impl From<()> for CommandSuccessResponseWrapper<()> { + fn from(_: ()) -> Self { + CommandSuccessResponseWrapper { + status: CommandSuccessStatus::Success, + payload: None, + } + } +} + +/// NB: Note the `"+ SerializeMarker"` bound here. This is a hack to distinguish between `()` and other types +/// for which we will manually mark as `SerializeMarker`. +impl From for CommandSuccessResponseWrapper where T: Serialize + SerializeMarker { + fn from(val: T) -> Self { + CommandSuccessResponseWrapper { + status: CommandSuccessStatus::Success, + payload: Some(val), + } + } +} + +impl From<&str> for CommandErrorResponseWrapper { + fn from(value: &str) -> Self { + CommandErrorResponseWrapper { + status: CommandErrorStatus::BadRequest, // NB: Default to 500 error. + error: Some(value.to_string()), + } + } +} + +#[cfg(test)] +mod tests { + + #[test] + fn test_empty_tuple_serialize() { + let response = super::CommandSuccessResponseWrapper::<()>::from(()); + let serialized = serde_json::to_string(&response).unwrap(); + // NB: This tests that the blanket "Serialize" impl doesn't produce a "null payload" field. + assert_eq!(serialized, r#"{"status":"success"}"#); + } +} diff --git a/crates/desktop/artcraft/src/commands/mod.rs b/crates/desktop/artcraft/src/commands/mod.rs index a83adf2f50..549119c5dc 100644 --- a/crates/desktop/artcraft/src/commands/mod.rs +++ b/crates/desktop/artcraft/src/commands/mod.rs @@ -1,4 +1,5 @@ pub mod app_preferences; +pub mod command_response_wrapper; pub mod flip_image; pub mod platform_info_command; pub mod sora; diff --git a/crates/desktop/artcraft/src/commands/sora/mod.rs b/crates/desktop/artcraft/src/commands/sora/mod.rs index 3a85a45beb..5a1e942fbe 100644 --- a/crates/desktop/artcraft/src/commands/sora/mod.rs +++ b/crates/desktop/artcraft/src/commands/sora/mod.rs @@ -2,3 +2,4 @@ pub mod check_sora_session_command; pub mod open_sora_login_command; pub mod sora_image_generation_command; pub mod sora_image_remix_command; +pub mod sora_logout_command; diff --git a/crates/desktop/artcraft/src/commands/sora/sora_logout_command.rs b/crates/desktop/artcraft/src/commands/sora/sora_logout_command.rs new file mode 100644 index 0000000000..1c87366fd1 --- /dev/null +++ b/crates/desktop/artcraft/src/commands/sora/sora_logout_command.rs @@ -0,0 +1,35 @@ +use crate::commands::app_preferences::get_app_preferences_command::AppPreferencesPayload; +use crate::commands::command_response_wrapper::{CommandResult, CommandSuccessResponseWrapper}; +use crate::state::app_preferences::app_preferences_manager::AppPreferencesManager; +use crate::state::data_dir::app_data_root::AppDataRoot; +use crate::state::sora::sora_credential_manager::SoraCredentialManager; +use crate::windows::sora_login_window::open_sora_login_window::open_sora_login_window; +use errors::{AnyhowError, AnyhowResult}; +use log::{error, info}; +use once_cell::sync::Lazy; +use openai_sora_client::creds::sora_credential_set::SoraCredentialSet; +use openai_sora_client::recipes::maybe_upgrade_or_renew_session::maybe_upgrade_or_renew_session; +use openai_sora_client::requests::list_media::list_media::list_media; +use serde_derive::Serialize; +use std::fmt::format; +use tauri::{AppHandle, State}; + +#[tauri::command] +pub async fn sora_logout_command( + sora_creds_manager: State<'_, SoraCredentialManager>, +) -> CommandResult<(), String> { + info!("sora_logout_command called"); + + if let Err(err) = sora_creds_manager.purge_credentials_from_disk() { + error!("Error purging credentials from disk: {:?}", err); + return Err("error purging credentials from disk".into()); + } + + if let Err(err) = sora_creds_manager.clear_credentials() { + error!("Error clearing credentials from memory: {:?}", err); + return Err("error clearing credentials from memory".into()); + } + + Ok(().into()) +} + diff --git a/crates/desktop/artcraft/src/lib.rs b/crates/desktop/artcraft/src/lib.rs index a1de6336d1..37b96ba016 100644 --- a/crates/desktop/artcraft/src/lib.rs +++ b/crates/desktop/artcraft/src/lib.rs @@ -15,6 +15,7 @@ use crate::commands::sora::check_sora_session_command::check_sora_session_comman use crate::commands::sora::open_sora_login_command::open_sora_login_command; use crate::commands::sora::sora_image_generation_command::sora_image_generation_command; use crate::commands::sora::sora_image_remix_command::sora_image_remix_command; +use crate::commands::sora::sora_logout_command::sora_logout_command; use crate::state::app_preferences::app_preferences_manager::load_app_preferences_or_default; use crate::state::data_dir::app_data_root::AppDataRoot; use crate::state::main_window_size::MainWindowSize; @@ -127,6 +128,7 @@ pub fn run() { platform_info_command, sora_image_generation_command, sora_image_remix_command, + sora_logout_command, update_app_preferences_command, ]) .run(tauri::generate_context!("tauri.conf.json")) diff --git a/crates/desktop/artcraft/src/state/sora/sora_credential_manager.rs b/crates/desktop/artcraft/src/state/sora/sora_credential_manager.rs index c82b1d6de3..e69f277753 100644 --- a/crates/desktop/artcraft/src/state/sora/sora_credential_manager.rs +++ b/crates/desktop/artcraft/src/state/sora/sora_credential_manager.rs @@ -1,3 +1,4 @@ +use std::{fs, io}; use crate::state::data_dir::app_data_root::AppDataRoot; use crate::state::sora::read_sora_credentials_from_disk::read_sora_credentials_from_disk; use crate::state::sora::sora_credential_holder::SoraCredentialHolder; @@ -9,6 +10,7 @@ use openai_sora_client::creds::sora_sentinel::SoraSentinel; use openai_sora_client::requests::sentinel_refresh::generate::token::generate_token; use std::fs::OpenOptions; use std::io::Write; +use std::path::Path; use openai_sora_client::creds::sora_cookies::SoraCookies; use openai_sora_client::creds::sora_jwt_bearer_token::SoraJwtBearerToken; @@ -45,6 +47,31 @@ impl SoraCredentialManager { Ok(()) } + /// This is meant to be infallible. + pub fn purge_credentials_from_disk(&self) -> Result<(), io::Error> { + let creds_dir = self.app_data_root.credentials_dir(); + + remove_file_if_exists(creds_dir.get_sora_cookie_file_path())?; + remove_file_if_exists(creds_dir.get_sora_bearer_token_file_path())?; + remove_file_if_exists(creds_dir.get_sora_sentinel_file_path())?; + + Ok(()) + } + + /// This is meant to be infallible. + pub fn try_purge_credentials_from_disk(&self) { + let creds_dir = self.app_data_root.credentials_dir(); + if let Err(err) = fs::remove_file(creds_dir.get_sora_cookie_file_path()) { + error!("Failed to remove cookie file: {:?}", err); + } + if let Err(err) = fs::remove_file(creds_dir.get_sora_bearer_token_file_path()) { + error!("Failed to remove bearer token file: {:?}", err); + } + if let Err(err) = fs::remove_file(creds_dir.get_sora_sentinel_file_path()) { + error!("Failed to remove sentinel file: {:?}", err); + } + } + pub fn get_credentials(&self) -> AnyhowResult> { self.holder.get_credentials() } @@ -155,3 +182,11 @@ fn persist_sentinel_to_disk(sentinel: &SoraSentinel, app_data_root: &AppDataRoot Ok(()) } + +fn remove_file_if_exists>(path: P) -> Result<(), io::Error> { + let p = path.as_ref(); + if p.exists() && p.is_file() { + fs::remove_file(p)?; + } + Ok(()) +} diff --git a/crates/desktop/artcraft/src/windows/sora_login_window/sora_login_thread.rs b/crates/desktop/artcraft/src/windows/sora_login_window/sora_login_thread.rs index 4538f3ee0b..06cc0145a0 100644 --- a/crates/desktop/artcraft/src/windows/sora_login_window/sora_login_thread.rs +++ b/crates/desktop/artcraft/src/windows/sora_login_window/sora_login_thread.rs @@ -132,12 +132,7 @@ async fn check_login_window( // TODO(bt): Race conditions ahead. sora_credential_manager.clear_credentials()?; - - let creds_dir = app_data_root.credentials_dir(); - - let _r = fs::remove_file(creds_dir.get_sora_cookie_file_path()); - let _r = fs::remove_file(creds_dir.get_sora_bearer_token_file_path()); - let _r = fs::remove_file(creds_dir.get_sora_sentinel_file_path()); + sora_credential_manager.try_purge_credentials_from_disk(); sora_credential_manager.set_credentials(&new_credentials)?; sora_credential_manager.persist_all_to_disk()?;