diff --git a/crates/desktop/artcraft/src/utils/cookies/mod.rs b/crates/desktop/artcraft/src/utils/cookies/mod.rs deleted file mode 100644 index fc9a63ecd8..0000000000 --- a/crates/desktop/artcraft/src/utils/cookies/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod sora_webview_cookies; \ No newline at end of file diff --git a/crates/desktop/artcraft/src/utils/mod.rs b/crates/desktop/artcraft/src/utils/mod.rs index 02dbf73e50..c98cf6ab71 100644 --- a/crates/desktop/artcraft/src/utils/mod.rs +++ b/crates/desktop/artcraft/src/utils/mod.rs @@ -1,5 +1,4 @@ pub mod clear_all_webview_cookies; -pub mod cookies; pub mod get_url_file_extension; pub mod image; pub mod large_file_transfer; diff --git a/crates/desktop/artcraft/src/utils/cookies/sora_webview_cookies.rs b/crates/desktop/artcraft/src/windows/sora_login_window/extract_sora_webview_cookies.rs similarity index 82% rename from crates/desktop/artcraft/src/utils/cookies/sora_webview_cookies.rs rename to crates/desktop/artcraft/src/windows/sora_login_window/extract_sora_webview_cookies.rs index 6abf2a4082..2d9f9cc908 100644 --- a/crates/desktop/artcraft/src/utils/cookies/sora_webview_cookies.rs +++ b/crates/desktop/artcraft/src/windows/sora_login_window/extract_sora_webview_cookies.rs @@ -1,8 +1,8 @@ +use errors::AnyhowResult; use once_cell::sync::Lazy; use reqwest::Url; -use tauri::Webview; use tauri::webview::Cookie; -use errors::AnyhowResult; +use tauri::Webview; const CHAT_GPT_ROOT_COOKIE_URL_STR: &str = "https://chatgpt.com"; @@ -10,12 +10,7 @@ static CHAT_GPT_ROOT_COOKIE_URL: Lazy = Lazy::new(|| { Url::parse(CHAT_GPT_ROOT_COOKIE_URL_STR).expect("URL should parse") }); -pub fn get_all_chatgpt_cookies(webview: &Webview) -> AnyhowResult> { - let cookies = webview.cookies_for_url(CHAT_GPT_ROOT_COOKIE_URL.clone())?; - Ok(cookies) -} - -pub fn get_all_sora_cookies_as_string(webview: &Webview) -> AnyhowResult { +pub fn extract_sora_webview_cookies(webview: &Webview) -> AnyhowResult { // NB(bt): Cookies were originally on sora.com, but now they're located on // the sora.chatgpt.com / *.chatgpt.com domains. let cookies = get_all_chatgpt_cookies(webview)?; @@ -26,3 +21,8 @@ pub fn get_all_sora_cookies_as_string(webview: &Webview) -> AnyhowResult .join("; "); Ok(cookie_string) } + +fn get_all_chatgpt_cookies(webview: &Webview) -> AnyhowResult> { + let cookies = webview.cookies_for_url(CHAT_GPT_ROOT_COOKIE_URL.clone())?; + Ok(cookies) +} diff --git a/crates/desktop/artcraft/src/windows/sora_login_window/mod.rs b/crates/desktop/artcraft/src/windows/sora_login_window/mod.rs index 85aca611f1..0ff8648e3b 100644 --- a/crates/desktop/artcraft/src/windows/sora_login_window/mod.rs +++ b/crates/desktop/artcraft/src/windows/sora_login_window/mod.rs @@ -1,4 +1,5 @@ pub mod clear_browsing_on_test_domain; +pub mod extract_sora_webview_cookies; pub mod keep_on_login_domains; pub mod open_sora_login_window; pub mod sora_login_thread; 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 a78269ddbb..454a214794 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 @@ -1,8 +1,8 @@ use crate::state::data_dir::app_data_root::AppDataRoot; use crate::state::sora::sora_credential_holder::SoraCredentialHolder; use crate::state::sora::sora_credential_manager::SoraCredentialManager; -use crate::utils::cookies::sora_webview_cookies::get_all_sora_cookies_as_string; use crate::utils::sora::initialize_sora_jwt_bearer_token::initialize_sora_jwt_bearer_token; +use crate::windows::sora_login_window::extract_sora_webview_cookies::extract_sora_webview_cookies; use crate::windows::sora_login_window::open_sora_login_window::LOGIN_WINDOW_NAME; use anyhow::anyhow; use chrono::{DateTime, NaiveDateTime, TimeDelta}; @@ -41,87 +41,111 @@ pub async fn sora_login_thread( &sora_creds_manager, ).await; - if let Err(err) = result { - error!("Error checking login window: {:?}", err); + match result { + Err(err) => { + error!("Error checking login window: {:?}", err); + } + Ok(false) => {} // Continue iteration and try again... + Ok(true) => { + info!("Successfully saved cookies from login window. Closing."); + if let Err(err) = login_webview.close() { + error!("Error closing login window: {:?}", err); + } + return; + } } tokio::time::sleep(std::time::Duration::from_millis(2_000)).await; } } +/// Returns true if we can exit. async fn check_login_window( webview: &Webview, app_data_root: &AppDataRoot, sora_credential_manager: &SoraCredentialManager, -) -> AnyhowResult<()> { - //clear_browsing_data_on_test_domain(webview)?; - //keep_on_task(webview)?; - extract_cookies_to_file(webview, app_data_root, sora_credential_manager).await?; - Ok(()) -} +) -> AnyhowResult { + + /* Login flow looks like this: + + 1. Start: https://sora.chatgpt.com/ + 2. Login Start: https://chatgpt.com/auth/login?next=%2Fsora%2F [this is where we start] + 3. Login Continue: https://auth.openai.com/log-in + 4. SSO / Google Login (etc): https://accounts.google.com/v3/signin/challenge/pwd?[query] + 5. Done / Landing: https://sora.chatgpt.com/explore + */ + + /* + - Do not use credential manager until the end (we don't load old cookies!) + - Check if we're on the correct domain, if not exit? (or inverse, that we're not in login flow) + */ -// TODO(bt,2025-04-07): Heuristic to detect when logged in. Only write when logged in. -async fn extract_cookies_to_file( - webview: &Webview, - app_data_root: &AppDataRoot, - sora_credential_manager: &SoraCredentialManager, -) -> AnyhowResult<()> { - let new_cookies = get_all_sora_cookies_as_string(webview)?.trim().to_string(); + let hostname = get_hostname(webview)?; - if new_cookies.is_empty() { - return Ok(()); + info!("Sora login webview is at hostname `{}`.", hostname); + + let mut maybe_at_destination = false; + + match hostname.as_str() { + "sora.com" | // Old destination + "sora.chatgpt.com" // New destination + => { + maybe_at_destination = true; + } + // chatgpt.com/auth is also an auth domain + "auth.openai.com" | + "accounts.google.com" | + "accounts.youtube.com" | + "login.live.com" | + "appleid.apple.com" + => { + // NB: We're in auth flow. + return Ok(false) + } + _ => {}, // We just don't know... } - let session_cookie_presence = has_session_cookie(&new_cookies) + let webview_cookies = extract_sora_webview_cookies(webview)?.trim().to_string(); + + let session_cookie_presence = has_session_cookie(&webview_cookies) .unwrap_or_else(|err| { error!("Failed to check for session cookie: {:?}", err); SessionCookiePresence::MaybePresent }); - - info!("Session cookies are: {:?}", session_cookie_presence); - - let (should_write_cookies, should_upgrade_session) = match session_cookie_presence { - SessionCookiePresence::Present => (true, true), - SessionCookiePresence::MaybePresent => (true, false), - SessionCookiePresence::Absent => (false, false), - }; - - if !should_write_cookies { - return Ok(()); + + match session_cookie_presence { + SessionCookiePresence::Absent => { + info!("Session cookies are absent."); + return Ok(false); + } + _ => {}, } + let mut new_credentials = + SoraCredentialSet::initialize_with_just_cookies_str(&webview_cookies); + + let _upgraded = maybe_upgrade_or_renew_session(&mut new_credentials).await?; + // TODO(bt): Race conditions ahead. sora_credential_manager.clear_credentials()?; - let _r = fs::remove_file(app_data_root.get_sora_cookie_file_path()); - let _r = fs::remove_file(app_data_root.get_sora_bearer_token_file_path()); - let _r = fs::remove_file(app_data_root.get_sora_sentinel_file_path()); - - let mut new_credentials = - SoraCredentialSet::initialize_with_just_cookies_str(&new_cookies); - - if should_upgrade_session { - let _upgraded = maybe_upgrade_or_renew_session(&mut new_credentials).await?; - } + 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.set_credentials(&new_credentials)?; sora_credential_manager.persist_all_to_disk()?; - - Ok(()) + + Ok(true) } -pub fn read_sora_cookies_from_disk(app_data_root: &AppDataRoot) -> Option { - let cookie_file = app_data_root.get_sora_cookie_file_path(); - if !cookie_file.exists() { - return None; - } - - match read_to_string(cookie_file) { - Ok(contents) => Some(contents.trim().to_string()), - Err(err) => { - warn!("Failed to read cookie file: {:?}", err); - None - } - } +fn get_hostname(webview: &Webview) -> AnyhowResult { + let url = webview.url()?; + let url_hostname= url.host() + .ok_or(anyhow!("no host in url"))? + .to_string(); + Ok(url_hostname) } diff --git a/crates/lib/api_clients/openai_sora_client/src/recipes/maybe_upgrade_or_renew_session.rs b/crates/lib/api_clients/openai_sora_client/src/recipes/maybe_upgrade_or_renew_session.rs index 98b2f284f0..ea9fec866e 100644 --- a/crates/lib/api_clients/openai_sora_client/src/recipes/maybe_upgrade_or_renew_session.rs +++ b/crates/lib/api_clients/openai_sora_client/src/recipes/maybe_upgrade_or_renew_session.rs @@ -7,13 +7,14 @@ use chrono::{DateTime, TimeDelta, Utc}; use errors::AnyhowResult; use log::info; use std::ops::Sub; +use crate::sora_error::SoraError; const EXPIRATION_DEADLINE : TimeDelta = TimeDelta::hours(12); /// Call this at session startup to generate the tokens for the first time. /// Call this periodically to refresh the JWT as it nears its expiration date. /// This will not refresh the sentinel token once it's been generated - we can use other flows to accomplish that. -pub async fn maybe_upgrade_or_renew_session(sora_credentials: &mut SoraCredentialSet) -> AnyhowResult { +pub async fn maybe_upgrade_or_renew_session(sora_credentials: &mut SoraCredentialSet) -> Result { let mut refresh_jwt = !sora_credentials.jwt_bearer_token.is_some(); let refresh_sentinel = !sora_credentials.sora_sentinel.is_some();