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
Protect the account from impatient clicking, and keep the session warm
Yashwanth Kamireddi789e40feef12
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex 9e9992c..1f41209 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -19,7 +19,7 @@ use reqwest::{Client as HttpClient, Response, StatusCode};use reqwest_cookie_store::CookieStoreMutex;use serde_json::{json, Value};pub use session::Store;-use session::{Session, CAPTURED_HEADERS};+use session::{backoff_seconds, unix_now, Session, CAPTURED_HEADERS};use std::path::Path;use std::sync::Arc;@@ -92,6 +92,8 @@ pub enum Error {Network(#[from] reqwest::Error),#[error("Apple sent back something unexpected: {0}")]Protocol(String),+ #[error("too many attempts just now — try again in {seconds}s")]+ CoolingDown { seconds: u64 },#[error("this needs a fresh sign-in — Apple won't accept a resumed session for it")]ReauthRequired,#[error("Apple is rate-limiting this account. Wait a few minutes before trying again — \@@ -405,6 +407,40 @@ impl Client {/// The password is never sent to Apple — SRP proves knowledge of it without transmitting/// it. Apple retired the old cleartext endpoint; it now answers 503.pub async fn sign_in(&mut self, apple_id: &str, password: &str) -> Result<SignInOutcome> {+ let outcome = self.sign_in_inner(apple_id, password).await;+ match &outcome {+ // Reaching the two-factor step means the password was accepted: not a failure.+ Ok(_) => {+ self.session.consecutive_failures = 0;+ self.session.retry_after = None;+ }+ Err(Error::CoolingDown { .. }) => {}+ Err(e) => {+ self.session.consecutive_failures =+ self.session.consecutive_failures.saturating_add(1);+ // Apple saying "slow down" outranks our own schedule.+ let wait = if matches!(e, Error::RateLimited) {+ backoff_seconds(u32::MAX)+ } else {+ backoff_seconds(self.session.consecutive_failures)+ };+ self.session.retry_after = (wait > 0).then(|| unix_now() + wait);+ }+ }+ let _ = self.persist();+ outcome+ }++ async fn sign_in_inner(&mut self, apple_id: &str, password: &str) -> Result<SignInOutcome> {+ // Refuse before touching Apple. Hammering sign-in is what gets an account+ // temporarily locked, and an impatient user clicking twice should not risk that.+ if let Some(until) = self.session.retry_after {+ let now = unix_now();+ if now < until {+ return Err(Error::CoolingDown { seconds: until - now });+ }+ }+// Start clean. An interrupted previous attempt would otherwise announce a// half-finished session and Apple would reject this one as a conflict.self.clear_challenge_state();@@ -760,6 +796,19 @@ mod tests {assert_eq!(init.get("origin").unwrap(), ROOT_T);}+ /// The first retry should be nearly free; repeated failures must back off hard, because+ /// the penalty for hammering Apple is a temporary account lock.+ #[test]+ fn backoff_grows_and_is_capped() {+ use crate::session::backoff_seconds;+ assert_eq!(backoff_seconds(0), 0, "a first attempt must not be delayed");+ let steps: Vec<u64> = (1..=6).map(backoff_seconds).collect();+ for pair in steps.windows(2) {+ assert!(pair[1] >= pair[0], "backoff must never shrink: {steps:?}");+ }+ assert_eq!(backoff_seconds(u32::MAX), backoff_seconds(5), "and it must be bounded");+ }+#[test]fn apple_errors_are_classified() {let wrong = r#"{"serviceErrors":[{"code":"-21669","message":"Incorrect verification code."}]}"#;diff --git a/crates/quince-auth/src/session.rs b/crates/quince-auth/src/session.rsindex a6eaad1..75371dc 100644--- a/crates/quince-auth/src/session.rs+++ b/crates/quince-auth/src/session.rs@@ -46,6 +46,38 @@ pub struct Session {/// Apple's per-account service URL map, from `accountLogin`.pub webservices: Option<serde_json::Value>,pub dsid: Option<String>,++ /// Failed sign-ins in a row. Drives the local backoff.+ #[serde(default)]+ pub consecutive_failures: u32,+ /// Unix seconds before which we refuse to contact Apple again.+ ///+ /// Persisted deliberately: a cooldown that resets when the app restarts is no cooldown+ /// at all, and repeated attempts are what get accounts temporarily locked.+ #[serde(default)]+ pub retry_after: Option<u64>,+}++/// Seconds to wait after `failures` consecutive failed sign-ins.+///+/// Apple rate-limits, and the penalty for ignoring it is a temporary account lock — so the+/// first retry is nearly free and the ceiling is deliberately high.+pub fn backoff_seconds(failures: u32) -> u64 {+ match failures {+ 0 => 0,+ 1 => 5,+ 2 => 15,+ 3 => 60,+ 4 => 180,+ _ => 600,+ }+}++pub fn unix_now() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0)}impl Session {diff --git a/crates/quince-auth/tests/auth_flow.rs b/crates/quince-auth/tests/auth_flow.rsindex 3e9a5f2..e1b74b2 100644--- a/crates/quince-auth/tests/auth_flow.rs+++ b/crates/quince-auth/tests/auth_flow.rs@@ -304,3 +304,47 @@ async fn a_rejected_session_falls_back_cleanly() {let outcome = client.sign_in("[email protected]", "hunter2").await.unwrap();assert_eq!(outcome, SignInOutcome::NeedsTwoFactor);}++/// A cooldown that resets on restart is no cooldown. After a failure the next attempt must+/// be refused locally, without another request reaching Apple.+#[tokio::test]+async fn a_cooldown_survives_a_restart_and_spares_apple() {+ let server = MockServer::start().await;+ mount_init(&server, 429).await; // Apple says slow down++ let dir = tempfile::tempdir().unwrap();+ {+ let mut client = client_for(&server, dir.path());+ let err = client.sign_in("[email protected]", "hunter2").await.unwrap_err();+ assert!(matches!(err, quince_auth::Error::RateLimited));+ }++ let before = server.received_requests().await.unwrap().len();++ // A brand-new client, as if the app had been restarted.+ let mut restarted = client_for(&server, dir.path());+ let err = restarted.sign_in("[email protected]", "hunter2").await.unwrap_err();+ match err {+ quince_auth::Error::CoolingDown { seconds } => assert!(seconds > 0),+ other => panic!("expected a cooldown after a restart, got {other}"),+ }++ let after = server.received_requests().await.unwrap().len();+ assert_eq!(before, after, "the cooldown must be enforced without contacting Apple");+}++/// Reaching the two-factor step means the password was accepted, so it must clear any+/// backoff rather than count as another failure.+#[tokio::test]+async fn a_successful_sign_in_clears_the_backoff() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 409).await;++ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());+ client.sign_in("[email protected]", "hunter2").await.unwrap();++ assert_eq!(client.session().consecutive_failures, 0);+ assert!(client.session().retry_after.is_none());+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex ee1dfb4..115cd35 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -4,10 +4,12 @@use quince_auth::{Client, SignInOutcome, TwoFactorOptions};use serde::Serialize;use std::path::PathBuf;+use std::sync::Arc;+use std::time::Duration;use tauri::{Manager, State};use tokio::sync::Mutex;-struct Auth(Mutex<Client>);+struct Auth(Arc<Mutex<Client>>);#[derive(Serialize)]#[serde(rename_all = "camelCase")]@@ -116,12 +118,39 @@ async fn account_services(auth: State<'_, Auth>) -> UiResult<Vec<String>> {.unwrap_or_default())}+/// Keep the session warm.+///+/// Apple resets auth cookies after a long idle gap, so a session left untouched can die well+/// before its nominal life. Roughly hourly contact is what keeps it alive in practice; 45+/// minutes leaves margin without being chatty enough to look like polling.+fn spawn_heartbeat(client: Arc<Mutex<Client>>) {+ tauri::async_runtime::spawn(async move {+ const INTERVAL: Duration = Duration::from_secs(45 * 60);+ loop {+ tokio::time::sleep(INTERVAL).await;+ let mut guard = client.lock().await;+ // Only meaningful once signed in; before that there is nothing to keep warm.+ if guard.session().webservices.is_none() {+ continue;+ }+ match guard.heartbeat().await {+ Ok(true) => {}+ // A lapsed session is expected roughly every two months. The UI discovers it+ // on next use and asks for a code; nothing to do here but stop pinging.+ Ok(false) => break,+ Err(_) => {}+ }+ }+ });+}+fn main() {tauri::Builder::default().setup(|app| {let dir = state_dir(&app.handle());- let client = Client::new(&dir)?;- app.manage(Auth(Mutex::new(client)));+ let client = Arc::new(Mutex::new(Client::new(&dir)?));+ app.manage(Auth(Arc::clone(&client)));+ spawn_heartbeat(client);Ok(())}).invoke_handler(tauri::generate_handler![