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
Recover when no two-factor code arrives
Yashwanth Kamireddi919839398d89
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex 91b5b0f..fad2068 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -56,6 +56,26 @@ pub enum Error {type Result<T> = std::result::Result<T, Error>;+/// A phone Apple will text a code to, when no trusted device responds.+#[derive(Debug, Clone, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct TrustedPhone {+ pub id: u64,+ /// Already masked by Apple, e.g. "+91 ••••• ••123".+ pub masked_number: String,+}++/// Where Apple is willing to send a code. Read after a `NeedsTwoFactor` outcome.+#[derive(Debug, Clone, Default, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct TwoFactorOptions {+ /// Devices Apple pushed the code to. Zero means nothing will arrive on its own.+ pub trusted_device_count: u64,+ pub phones: Vec<TrustedPhone>,+ /// Apple refuses further sends for a while.+ pub too_many_codes_sent: bool,+}+/// What `sign_in` decided.#[derive(Debug, PartialEq, Eq)]pub enum SignInOutcome {@@ -330,6 +350,113 @@ impl Client {}}+ /// Where Apple can send a code, and whether it already pushed one.+ ///+ /// Worth reading whenever a code doesn't arrive: a `trusted_device_count` of zero means+ /// no push was ever sent and SMS is the only route.+ pub async fn two_factor_options(&mut self) -> Result<TwoFactorOptions> {+ let mut headers = self.auth_headers();+ headers.insert("accept", HeaderValue::from_static("application/json"));+ let r = self.http.get(AUTH).headers(headers).send().await?;+ self.capture(&r);+ let text = r.text().await.unwrap_or_default();+ let v: Value = serde_json::from_str(&text).unwrap_or(Value::Null);++ let phones = v["trustedPhoneNumbers"]+ .as_array()+ .map(|arr| {+ arr.iter()+ .filter_map(|p| {+ Some(TrustedPhone {+ id: p["id"].as_u64()?,+ masked_number: p["numberWithDialCode"]+ .as_str()+ .or_else(|| p["obfuscatedNumber"].as_str())+ .unwrap_or("(hidden)")+ .to_string(),+ })+ })+ .collect()+ })+ .unwrap_or_default();++ Ok(TwoFactorOptions {+ trusted_device_count: v["trustedDeviceCount"].as_u64().unwrap_or(0),+ phones,+ too_many_codes_sent: v["securityCode"]["tooManyCodesSent"].as_bool().unwrap_or(false),+ })+ }++ /// Ask Apple to push the code to trusted devices again.+ pub async fn resend_to_devices(&mut self) -> Result<()> {+ let mut headers = self.auth_headers();+ headers.insert("accept", HeaderValue::from_static("application/json"));+ let r = self+ .http+ .put(format!("{AUTH}/verify/trusteddevice"))+ .headers(headers)+ .send()+ .await?;+ self.capture(&r);+ let status = r.status();+ if !status.is_success() && status != StatusCode::NO_CONTENT {+ return Err(Error::Protocol(format!("couldn't resend the code ({status})")));+ }+ Ok(())+ }++ /// Text the code to one of the trusted phone numbers.+ pub async fn send_sms(&mut self, phone_id: u64) -> Result<()> {+ let mut headers = self.auth_headers();+ headers.insert("accept", HeaderValue::from_static("application/json"));+ let r = self+ .http+ .put(format!("{AUTH}/verify/phone"))+ .headers(headers)+ .body(json!({ "phoneNumber": { "id": phone_id }, "mode": "sms" }).to_string())+ .send()+ .await?;+ self.capture(&r);+ let status = r.status();+ if !status.is_success() && status != StatusCode::NO_CONTENT {+ return Err(Error::Protocol(format!("couldn't send the text ({status})")));+ }+ Ok(())+ }++ /// Submit a code that arrived by SMS. Trusted-device codes use `submit_two_factor`.+ pub async fn submit_sms_code(&mut self, phone_id: u64, code: &str) -> Result<()> {+ let mut headers = self.auth_headers();+ headers.insert("accept", HeaderValue::from_static("application/json"));+ let r = self+ .http+ .post(format!("{AUTH}/verify/phone/securitycode"))+ .headers(headers)+ .body(+ json!({+ "phoneNumber": { "id": phone_id },+ "securityCode": { "code": code },+ "mode": "sms",+ })+ .to_string(),+ )+ .send()+ .await?;+ self.capture(&r);+ let status = r.status();+ if !status.is_success() && status != StatusCode::NO_CONTENT {+ return Err(match status {+ StatusCode::BAD_REQUEST | StatusCode::PRECONDITION_FAILED => Error::BadCode,+ s => Error::Protocol(format!("code check failed ({s})")),+ });+ }+ self.trust().await?;+ let data = self.account_login().await?;+ self.absorb(&data);+ self.persist()?;+ Ok(())+ }+/// Submit the six-digit code, then ask Apple to trust this install.pub async fn submit_two_factor(&mut self, code: &str) -> Result<()> {let mut headers = self.auth_headers();diff --git a/probe/src/main.rs b/probe/src/main.rsindex 5d9f242..89b793b 100644--- a/probe/src/main.rs+++ b/probe/src/main.rs@@ -146,10 +146,66 @@ async fn main() -> Result<()> {match client.sign_in(&apple_id, &password).await? {SignInOutcome::Complete => println!(" signed in; Apple already trusted this install"),SignInOutcome::NeedsTwoFactor => {- println!(" Apple sent a six-digit code to your devices.");- let code = prompt(" Code: ")?;- client.submit_two_factor(&code).await?;- println!(" \x1b[32mcode accepted, trust token stored in the keyring\x1b[0m");+ let opts = client.two_factor_options().await?;+ println!();+ if opts.trusted_device_count > 0 {+ println!(+ " Apple pushed a code to {} trusted device(s).",+ opts.trusted_device_count+ );+ } else {+ println!(+ " \x1b[33mApple reports NO trusted devices, so no code was pushed.\x1b[0m"+ );+ }+ if opts.too_many_codes_sent {+ println!(" \x1b[33mApple is rate-limiting new codes. Wait a few minutes.\x1b[0m");+ }+ for (i, p) in opts.phones.iter().enumerate() {+ println!(" [{}] text it to {}", i + 1, p.masked_number);+ }+ println!("\n If nothing arrived, on your iPhone open");+ println!(" Settings → your name → Sign-In & Security → Get Verification Code.");+ println!("\n Type the 6-digit code, or `r` to push again, or `1`/`2`… to text it.");++ let mut sms_phone: Option<u64> = None;+ loop {+ let answer = prompt(" Code: ")?;+ let trimmed = answer.trim().to_string();++ if trimmed.eq_ignore_ascii_case("r") {+ client.resend_to_devices().await?;+ println!(" pushed again — check your devices");+ continue;+ }+ if let Ok(choice) = trimmed.parse::<usize>() {+ // A 1-2 digit entry that indexes a phone means "text me"; a 6-digit+ // entry is the code itself.+ if trimmed.len() <= 2 && choice >= 1 && choice <= opts.phones.len() {+ let phone = &opts.phones[choice - 1];+ client.send_sms(phone.id).await?;+ sms_phone = Some(phone.id);+ println!(" texted {} — enter the code when it lands", phone.masked_number);+ continue;+ }+ }+ if trimmed.len() != 6 || !trimmed.chars().all(|c| c.is_ascii_digit()) {+ println!(" that isn't a 6-digit code — try again");+ continue;+ }++ let result = match sms_phone {+ Some(id) => client.submit_sms_code(id, &trimmed).await,+ None => client.submit_two_factor(&trimmed).await,+ };+ match result {+ Ok(()) => {+ println!(" \x1b[32mcode accepted, trust token stored in the keyring\x1b[0m");+ break;+ }+ Err(e) => println!(" {e}"),+ }+ }}}}