Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Sign-in: offline is not signed out — a resume that cannot reach Apple keeps the session untouched (a fallback sign-in cleared the session token and saved it), counts no failed attempt, and the library opens on what it holds; a locked keyring is reported, not read as nothing stored; trust token + password are enough to resume
Yashwanth Kamireddi416ac2ddbc53
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex afab4fc..40c8e9a 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -243,6 +243,9 @@ pub struct Client {pending: Option<(String, String)>,/// A lapsed session tried to sign itself back in and Apple wants a code first.awaiting_code: bool,+ /// The keyring would not answer when this started — locked, or not up yet. Not the same+ /// as nothing stored: it is asked again before anything else happens.+ keyring_error: Option<String>,}impl Client {@@ -253,7 +256,10 @@ impl Client {/// Build a client against specific endpoints and a specific secret store.pub fn with(state_dir: &Path, endpoints: Endpoints, store: Store) -> Result<Self> {std::fs::create_dir_all(state_dir)?;- let session = store.load();+ let (session, keyring_error) = match store.try_load() {+ Ok(session) => (session, None),+ Err(e) => (session::Session::default(), Some(e.to_string())),+ };let jar = {let path = store.cookie_path();@@ -295,6 +301,7 @@ impl Client {endpoints,pending: None,awaiting_code: false,+ keyring_error,})}@@ -394,15 +401,29 @@ impl Client {/// product promises. `Ok(false)` means Apple rejected it and a full sign-in is needed;/// that is an expected outcome (roughly every 60 days), not a failure.pub async fn resume(&mut self) -> Result<bool> {+ // A keyring that would not answer at startup is asked again; still locked, that is+ // what is said — never "signed out", which led to a sign-in replacing what it holds.+ if self.keyring_error.is_some() {+ match self.store.try_load() {+ Ok(session) => {+ self.session = session;+ self.keyring_error = None;+ }+ Err(e) => return Err(e),+ }+ }if !self.session.is_resumable() {return Ok(false);}// Cheap path: the cookies are still good, so nothing needs re-establishing.- if let Ok(data) = self.validate().await {- self.absorb(&data);- self.persist()?;- return Ok(true);- }+ let validated = match self.validate().await {+ Ok(data) => {+ self.absorb(&data);+ self.persist()?;+ return Ok(true);+ }+ Err(e) => e,+ };// The cookies are missing or stale but the tokens are not. Apple's service endpoints// authenticate by cookie — without X-APPLE-WEBAUTH-USER they answer 421 — so trade@@ -410,10 +431,20 @@ impl Client {//// This is what makes staying signed in survive a lost cookie file, a copied install,// or cookies expiring before the trust token does.- if let Ok(data) = self.account_login().await {- self.absorb(&data);- self.persist()?;- return Ok(true);+ let logged_in = match self.account_login().await {+ Ok(data) => {+ self.absorb(&data);+ self.persist()?;+ return Ok(true);+ }+ Err(e) => e,+ };+ // Unreachable is not rejected. Offline — no network yet after login, or a resume+ // from sleep mid-reconnect — the session is left exactly as it is and the caller+ // told so; signing in again here cleared the session token, failed on the network,+ // and saved the cleared state, so every launch after showed the sign-in screen.+ if matches!(validated, Error::Network(_)) && matches!(logged_in, Error::Network(_)) {+ return Err(logged_in);}// The session token has lapsed too — Apple keeps one for days, not months. With the@@ -423,8 +454,15 @@ impl Client {if let (Some(apple_id), Some(password)) =(self.session.apple_id.clone(), self.session.password.clone()){+ let before = self.session.clone();match self.sign_in(&apple_id, &password).await {Ok(SignInOutcome::Complete) => return Ok(true),+ // Lost the network part way: what was kept is put back as it was.+ Err(Error::Network(e)) => {+ self.session = before;+ let _ = self.persist();+ return Err(Error::Network(e));+ }Ok(SignInOutcome::NeedsTwoFactor) => {self.awaiting_code = true;return Ok(false);@@ -506,7 +544,8 @@ impl Client {self.session.consecutive_failures = 0;self.session.retry_after = None;}- Err(Error::CoolingDown { .. }) => {}+ // Not reaching Apple is not a failed attempt: no cooldown for being offline.+ Err(Error::CoolingDown { .. } | Error::Network(_)) => {}Err(e) => {self.session.consecutive_failures =self.session.consecutive_failures.saturating_add(1);diff --git a/crates/quince-auth/src/session.rs b/crates/quince-auth/src/session.rsindex 6736389..03edd3a 100644--- a/crates/quince-auth/src/session.rs+++ b/crates/quince-auth/src/session.rs@@ -125,7 +125,10 @@ impl Session {/// True when there's enough stored state to try resuming without a password.pub fn is_resumable(&self) -> bool {- self.session_token.is_some()+ // A lapsed session token is not the end: with the trust token and the password kept,+ // a sign-in needs no code. Requiring the session token alone meant one failed+ // attempt that cleared it sent every later launch to the sign-in screen.+ self.session_token.is_some() || (self.trust_token.is_some() && self.password.is_some())}}@@ -257,17 +260,25 @@ impl Store {/// Load the stored session. A missing entry is normal (first run), not an error.pub fn load(&self) -> Session {+ self.try_load().unwrap_or_default()+ }++ /// [`Self::load`], telling "nothing stored" apart from "the keyring would not answer" —+ /// locked, or not started yet at login. Read as nothing stored, a locked keyring showed+ /// the sign-in screen, and signing in then replaced the entry and its trust token.+ pub fn try_load(&self) -> Result<Session, crate::Error> {let json = match &self.backend {Backend::Keyring(_) => match self.entry().and_then(|e| e.get_password()) {Ok(j) => j,- Err(_) => return Session::default(),+ Err(keyring::Error::NoEntry) => return Ok(Session::default()),+ Err(e) => return Err(crate::Error::Keyring(e.to_string())),},Backend::File(path) => match std::fs::read_to_string(path) {Ok(j) => j,- Err(_) => return Session::default(),+ Err(_) => return Ok(Session::default()),},};- serde_json::from_str(&json).unwrap_or_default()+ Ok(serde_json::from_str(&json).unwrap_or_default())}pub fn save(&self, session: &Session) -> Result<(), crate::Error> {diff --git a/crates/quince-auth/tests/auth_flow.rs b/crates/quince-auth/tests/auth_flow.rsindex 3597497..221c85c 100644--- a/crates/quince-auth/tests/auth_flow.rs+++ b/crates/quince-auth/tests/auth_flow.rs@@ -556,6 +556,67 @@ async fn resume_rebuilds_a_session_from_tokens_alone() {);}+/// Offline is not signed out. With the network down — the app opened before the network+/// came up, or a resume from sleep mid-reconnect — resuming says so and leaves the session+/// exactly as it was; the next launch, online, is still signed in, with no cooldown.+#[tokio::test]+async fn resuming_offline_keeps_the_session() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/setup/ws/1/validate"))+ .respond_with(ResponseTemplate::new(421).set_body_json(json!({ "error": 1 })))+ .mount(&server)+ .await;+ mount_init(&server, 200).await;+ mount_complete(&server, 409).await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(ResponseTemplate::new(204))+ .mount(&server)+ .await;+ mount_trust_and_login(&server).await;+ let dir = tempfile::tempdir().unwrap();+ {+ let mut first = client_for(&server, dir.path());+ first+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();+ first.submit_two_factor("123456").await.unwrap();+ }+ // Nothing listening: every request fails to connect.+ let nowhere = Endpoints {+ auth_root: SRP_ORIGIN.into(),+ home: WEB_ORIGIN.into(),+ auth: "http://127.0.0.1:9/appleauth/auth".into(),+ setup: "http://127.0.0.1:9/setup/ws/1".into(),+ };+ {+ let mut offline =+ Client::with(dir.path(), nowhere, Store::file(dir.path()).unwrap()).unwrap();+ assert!(offline.has_stored_session());+ let err = offline+ .resume()+ .await+ .expect_err("offline is said, not hidden");+ assert!(matches!(err, quince_auth::Error::Network(_)), "{err}");+ }+ let back = client_for(&server, dir.path());+ assert!(+ back.has_stored_session(),+ "still signed in after a launch with no network"+ );+ assert!(+ back.session().session_token.is_some(),+ "the session token was kept"+ );+ assert_eq!(+ back.session().consecutive_failures,+ 0,+ "and being offline is no failed attempt"+ );+}+/// A cooldown that a restart forgets is not a cooldown.////// It used to live only in the keyring, so on a machine with none — or one that is locked —diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 2fa0c39..1af82a3 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -184,7 +184,14 @@ async fn auth_status(auth: State<'_, Auth>) -> UiResult<Status> {#[tauri::command]async fn auth_resume(auth: State<'_, Auth>) -> UiResult<&'static str> {let mut client = auth.client.lock().await;- let resumed = client.resume().await.map_err(|e| e.to_string())?;+ let resumed = match client.resume().await {+ Ok(resumed) => resumed,+ // Offline with a session kept: the library opens on what it holds, as a local-first+ // app should, and the next refresh — on the timer, or when the network is back —+ // signs back in.+ Err(quince_auth::Error::Network(_)) if client.has_stored_session() => true,+ Err(e) => return Err(e.to_string()),+ };// Back in; or back in but for the code Apple wants before trusting this computer again;// or out, with nothing kept to sign in with.Ok(if resumed {