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: Apple's escrow step, its repair step, security keys, and HTTPS only
Yashwanth Kamireddica1cd23f6b45
diff --git a/.uiverify/security-key.mjs b/.uiverify/security-key.mjsnew file mode 100644index 0000000..a53d971--- /dev/null+++ b/.uiverify/security-key.mjs@@ -0,0 +1,42 @@+// An Apple Account that signs in with a security key gets no code — Apple asks for the key,+// which Skykeep can't use yet. The code screen says so plainly, with a way back, instead of six+// empty boxes waiting for a code that never comes (icloudpd#583, #1423).+import { engine } from "./engine.mjs";+import { SERVICES, installStub } from "./stub.mjs";+const URL = process.env.BASE ?? process.env.URL ?? "http://localhost:4173";+const b = await engine.launch();+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++async function codeScreen(twoFactor) {+ const ctx = await b.newContext({ viewport: { width: 1100, height: 800 } });+ await ctx.addInitScript(installStub, { screen: "code", services: SERVICES, twoFactor });+ const page = await ctx.newPage();+ await page.goto(URL, { waitUntil: "networkidle" });+ await page.fill('input[aria-label="Apple Account"]', "[email protected]");+ await page.fill('input[aria-label="Password"]', "not-a-real-password");+ await page.click('button[type="submit"]');+ await page.waitForTimeout(500);+ return { ctx, page };+}++{+ const { ctx, page } = await codeScreen({ trustedDeviceCount: 0, phones: [], tooManyCodesSent: false, securityKey: true });+ ok(await page.getByRole("heading", { name: "This account uses a security key" }).isVisible(), "a security-key account is told so");+ ok((await page.locator(".lede").innerText()).includes("can't sign in with security keys yet"), "plainly, and truly");+ ok(!(await page.locator('[aria-label="Digit 1"]').count()), "no code boxes to wait at");+ await page.getByRole("button", { name: "Use a different Apple Account" }).click();+ await page.waitForTimeout(200);+ ok(await page.locator('input[aria-label="Password"]').isVisible(), "and the way back is there");+ await ctx.close();+}++{+ const { ctx, page } = await codeScreen({ trustedDeviceCount: 1, phones: [], tooManyCodesSent: false });+ ok(await page.locator('[aria-label="Digit 1"]').isVisible(), "an account with codes gets the code screen as before");+ await ctx.close();+}++await b.close();+if (failures) { console.log(`${failures} failed`); process.exit(1); }+console.log("all passed");diff --git a/check.sh b/check.shindex 5627b1a..92fe272 100755--- a/check.sh+++ b/check.sh@@ -171,6 +171,7 @@ step "lapse reason" node .uiverify/lapse-reason.mjsstep "device approval" node .uiverify/device-approval.mjsstep "code only when asked" node .uiverify/code-lapse.mjsstep "new iCloud terms" node .uiverify/icloud-terms.mjs+step "security keys" node .uiverify/security-key.mjsstep "webkit: approval" env ENGINE=webkit node .uiverify/device-approval.mjsstep "calendar undo" node .uiverify/calendar-undo.mjsdiff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex cd02061..3a5658a 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -104,6 +104,9 @@ pub enum Error {NoTrustToken,#[error("this account signs in a way Skykeep can't handle yet ({0})")]UnsupportedAccount(String),+ /// Apple wants something finished on the account before it signs in anywhere new.+ #[error("Apple needs one more step on your Apple Account first. Sign in at account.apple.com, finish what it asks, then sign in here again.")]+ RepairNeeded,/// Said without the address, which carries account and client ids.#[error("couldn't reach Apple: {}", if .0.is_timeout() { "it took too long to answer" } else if .0.is_connect() { "check your connection" } else { "the connection dropped" })]Network(#[from] reqwest::Error),@@ -344,6 +347,21 @@ pub struct TwoFactorOptions {pub phones: Vec<TrustedPhone>,/// Apple refuses further sends for a while.pub too_many_codes_sent: bool,+ /// The account signs in with security keys (FIDO): Apple offers a WebAuthn challenge+ /// (`fsaChallenge`) in place of a code (icloudpd#583, #1423). Skykeep cannot answer one yet,+ /// so the code screen says so rather than waiting for a code that will not come.+ pub security_key: bool,+}++/// Whether Apple's two-factor answer offers a security-key challenge: `fsaChallenge` with its+/// `challenge`, `keyHandles` and `rpId`, as icloudpd reads it.+fn offers_security_key(v: &Value) -> bool {+ let c = &v["fsaChallenge"];+ c.is_object()+ && ["challenge", "keyHandles", "rpId"].iter().all(|k| {+ let x = &c[*k];+ !x.is_null() && x.as_str() != Some("") && x.as_array().is_none_or(|a| !a.is_empty())+ })}/// What `sign_in` decided.@@ -355,6 +373,65 @@ pub enum SignInOutcome {NeedsTwoFactor,}+/// Apple's SRP challenge, from `/signin/init` or `/escrow/init`.+struct Challenge {+ salt: Vec<u8>,+ b_pub: Vec<u8>,+ c: String,+ iterations: u32,+ protocol: srp::Protocol,+}++impl Challenge {+ fn of(init: &Value) -> Result<Self> {+ let decode = |key: &str| -> Result<Vec<u8>> {+ let raw = init[key]+ .as_str()+ .ok_or_else(|| Error::Protocol(format!("sign-in response had no `{key}`")))?;+ B64.decode(raw)+ .map_err(|_| Error::Protocol(format!("`{key}` wasn't valid base64")))+ };+ let salt = decode("salt")?;+ let b_pub = decode("b")?;+ let c = init["c"]+ .as_str()+ .ok_or_else(|| Error::Protocol("sign-in response had no `c`".into()))?+ .to_string();+ let iterations = {+ let raw = init["iteration"]+ .as_u64()+ .ok_or_else(|| Error::Protocol("sign-in response had no `iteration`".into()))?;+ u32::try_from(raw)+ .ok()+ .filter(|n| (MIN_PBKDF2_ITERATIONS..=MAX_PBKDF2_ITERATIONS).contains(n))+ .ok_or_else(|| {+ Error::Protocol(format!(+ "Apple asked for an implausible {raw} key-derivation rounds"+ ))+ })?+ };+ let protocol_name = init["protocol"].as_str().unwrap_or("s2k");+ let protocol = srp::Protocol::parse(protocol_name)+ .ok_or_else(|| Error::UnsupportedAccount(format!("SRP protocol {protocol_name}")))?;+ Ok(Self {+ salt,+ b_pub,+ c,+ iterations,+ protocol,+ })+ }+}++/// Whether Apple wants its escrow step: `X-Apple-EDP` or `X-Apple-PDP` on a 409 (icloud-photos-+/// sync#1124, rclone#10048). Since iOS 26.4 Apple asks for it after an accepted code, and when+/// a sign-in presents a trust token it accepts — and until it is done it does not honour the+/// trust token, so every later sign-in looks as if it needs a code again.+fn wants_escrow(response: &Response) -> bool {+ let h = response.headers();+ h.contains_key("x-apple-edp") || h.contains_key("x-apple-pdp")+}+/// Whether a sign-in that Apple wants a code for asks Apple to send it now.#[derive(Clone, Copy, Debug, PartialEq, Eq)]enum Code {@@ -1006,7 +1083,8 @@ impl Client {| Error::Keyring(_)| Error::Io(_)| Error::Json(_)- | Error::TermsPending,+ | Error::TermsPending+ | Error::RepairNeeded,) => {}Err(e) => {self.session.consecutive_failures =@@ -1080,36 +1158,13 @@ impl Client {return Err(apple_error("starting sign-in", status, &text));}let init: Value = serde_json::from_str(&text)?;-- let decode = |key: &str| -> Result<Vec<u8>> {- let raw = init[key]- .as_str()- .ok_or_else(|| Error::Protocol(format!("sign-in response had no `{key}`")))?;- B64.decode(raw)- .map_err(|_| Error::Protocol(format!("`{key}` wasn't valid base64")))- };- let salt = decode("salt")?;- let b_pub = decode("b")?;- let c = init["c"]- .as_str()- .ok_or_else(|| Error::Protocol("sign-in response had no `c`".into()))?- .to_string();- let iterations = {- let raw = init["iteration"]- .as_u64()- .ok_or_else(|| Error::Protocol("sign-in response had no `iteration`".into()))?;- u32::try_from(raw)- .ok()- .filter(|n| (MIN_PBKDF2_ITERATIONS..=MAX_PBKDF2_ITERATIONS).contains(n))- .ok_or_else(|| {- Error::Protocol(format!(- "Apple asked for an implausible {raw} key-derivation rounds"- ))- })?- };- let protocol_name = init["protocol"].as_str().unwrap_or("s2k");- let protocol = srp::Protocol::parse(protocol_name)- .ok_or_else(|| Error::UnsupportedAccount(format!("SRP protocol {protocol_name}")))?;+ let Challenge {+ salt,+ b_pub,+ c,+ iterations,+ protocol,+ } = Challenge::of(&init)?;// --- /signin/complete: submit the proof ---let proof = client@@ -1141,6 +1196,7 @@ impl Client {.await?;self.capture(&r);let status = r.status();+ let escrow = wants_escrow(&r);// This step's own reply: its serviceErrors say why Apple refused (a locked account,// a wrong password). The challenge from /signin/init is not the reason and is never shown.let text = if status.is_success() || status == StatusCode::CONFLICT {@@ -1150,6 +1206,15 @@ impl Client {};match status {+ // Apple accepted this computer's trust token and wants its escrow step, not a code:+ // read as "a code", every lapse asked for one — about daily.+ StatusCode::CONFLICT if escrow && self.session.trust_token.is_some() => {+ self.complete_escrow(password).await?;+ let data = self.account_login().await?;+ self.absorb(&data);+ self.keep();+ Ok(SignInOutcome::Complete)+ }StatusCode::CONFLICT => {self.keep();// Ask for the code — when the person has just typed their password. Apple used@@ -1175,9 +1240,16 @@ impl Client {Ok(SignInOutcome::Complete)}StatusCode::UNAUTHORIZED => Err(refused_password("finishing sign-in", status, &text)),- StatusCode::PRECONDITION_FAILED => Err(Error::UnsupportedAccount(- "two-factor auth isn't switched on".into(),- )),+ // "Precondition failed": Apple wants a step on the account finished first (seen right+ // after new iCloud terms, and on accounts without two-factor). icloudpd answers it+ // with an empty `POST repair/complete` and carries on; so does this.+ StatusCode::PRECONDITION_FAILED => {+ self.repair_complete().await?;+ let data = self.account_login().await?;+ self.absorb(&data);+ self.keep();+ Ok(SignInOutcome::Complete)+ }s => Err(apple_error("finishing sign-in", s, &text)),}}@@ -1220,6 +1292,7 @@ impl Client {trusted_device_count: counted.unwrap_or(u64::from(has_devices)),phones,too_many_codes_sent: too_many,+ security_key: places.iter().any(|p| offers_security_key(p)),})}@@ -1309,8 +1382,13 @@ impl Client {.await?;self.capture(&r);let status = r.status();+ let escrow = wants_escrow(&r);+ // A correct code on an account with steps waiting (right after new iCloud terms, say)+ // is answered 412 with a repair session token, not 200 (pyicloud#466): accepted.+ let repair = status == StatusCode::PRECONDITION_FAILED+ && r.headers().contains_key("x-apple-repair-session-token");let body = r.text().await.unwrap_or_default();- if !status.is_success() && status != StatusCode::NO_CONTENT {+ if !status.is_success() && status != StatusCode::NO_CONTENT && !repair {let err = apple_error("checking that texted code", status, &body);if matches!(err, Error::BadCode) {return Err(err);@@ -1323,6 +1401,7 @@ impl Client {}return Err(err);}+ self.escrow_if_asked(escrow).await?;self.trust().await?;let data = self.account_login().await?;self.absorb(&data);@@ -1346,6 +1425,7 @@ impl Client {.await?;self.capture(&r);let status = r.status();+ let escrow = wants_escrow(&r);let body = r.text().await.unwrap_or_default();// Since iOS 26.4 a correct code is answered 409 with `securityCode.valid: true`.let accepted = status == StatusCode::CONFLICT@@ -1371,6 +1451,7 @@ impl Client {return Err(err);}+ self.escrow_if_asked(escrow).await?;self.trust().await?;let data = self.account_login().await?;self.absorb(&data);@@ -1378,6 +1459,116 @@ impl Client {Ok(())}+ /// Apple's escrow step: the SRP password proof again, with an empty account name, sending+ /// the session key with it — `POST escrow/init` `{a, accountName: "", protocols}`, then+ /// `POST escrow/complete` `{m1, m2, c, k}` (icloud-photos-sync#1124, rclone#10048). Apple+ /// issues a new session token for it, taken with the other headers.+ async fn complete_escrow(&mut self, password: &str) -> Result<()> {+ let client = srp::Client::new("");+ let r = self+ .http+ .post(format!("{}/escrow/init", self.endpoints.auth))+ .headers(self.srp_headers())+ .body(+ json!({+ "a": B64.encode(client.a_public_bytes()),+ "accountName": "",+ "protocols": ["s2k", "s2k_fo"],+ })+ .to_string(),+ )+ .send()+ .await?;+ self.capture(&r);+ let status = r.status();+ let text = r.text().await.unwrap_or_default();+ if !status.is_success() {+ return Err(apple_error(+ "confirming your password with Apple",+ status,+ &text,+ ));+ }+ let challenge = Challenge::of(&serde_json::from_str(&text)?)?;+ let proof = client+ .process_challenge(+ password,+ challenge.protocol,+ &challenge.salt,+ &challenge.b_pub,+ challenge.iterations,+ )+ .ok_or_else(|| {+ Error::Protocol("Apple's sign-in challenge failed its safety check".into())+ })?;+ let r = self+ .http+ .post(format!("{}/escrow/complete", self.endpoints.auth))+ .headers(self.srp_headers())+ .body(+ json!({+ "m1": B64.encode(proof.m1),+ "m2": B64.encode(proof.m2),+ "c": challenge.c,+ "k": B64.encode(proof.key),+ })+ .to_string(),+ )+ .send()+ .await?;+ self.capture(&r);+ let status = r.status();+ if !status.is_success() && status != StatusCode::NO_CONTENT {+ let text = r.text().await.unwrap_or_default();+ return Err(apple_error(+ "confirming your password with Apple",+ status,+ &text,+ ));+ }+ quiet!("quince: Apple's escrow step is done");+ Ok(())+ }++ /// `POST repair/complete` with `{}`, as icloudpd sends it when `/signin/complete` answers+ /// 412. Refused, the account needs the person at account.apple.com.+ async fn repair_complete(&mut self) -> Result<()> {+ let r = self+ .http+ .post(format!("{}/repair/complete", self.endpoints.auth))+ .headers(self.auth_headers())+ .body("{}")+ .send()+ .await?;+ self.capture(&r);+ let status = r.status();+ if status.is_success() || status == StatusCode::NO_CONTENT {+ return Ok(());+ }+ if let Some(e) = transient(status) {+ return Err(e);+ }+ Err(Error::RepairNeeded)+ }++ /// The password for the escrow step after a code: the one just typed, or the one kept.+ fn password_for_escrow(&self) -> Option<String> {+ self.pending+ .as_ref()+ .map(|(_, p)| p.clone())+ .or_else(|| self.session.password.clone())+ }++ /// After an accepted code: Apple's escrow step when the answer asks for it, before the+ /// trust token is asked for — without it Apple does not honour that token next time.+ async fn escrow_if_asked(&mut self, asked: bool) -> Result<()> {+ if !asked {+ return Ok(());+ }+ let password = self.password_for_escrow().ok_or(Error::ReauthRequired)?;+ self.complete_escrow(&password).await+ }+/// `GET /2sv/trust` — yields the trust token. Without it, sign-in wouldn't outlive the process.async fn trust(&mut self) -> Result<()> {let headers = self.auth_headers();@@ -1744,7 +1935,13 @@ fn url_apples(url: &reqwest::Url, loopback: bool) -> bool {.parse::<std::net::IpAddr>(){Ok(ip) => loopback && ip.is_loopback(),- Err(_) => apple_host(host, loopback),+ // Apple's hosts over TLS only. Plain HTTP to one — an address in Apple's data, or a+ // redirect down to it — would carry the session's cookies where anyone on the network+ // can read them (pyicloud#356, #401). This computer, in tests, is the one exception.+ Err(_) => {+ let secure = matches!(url.scheme(), "https" | "wss");+ (secure || (loopback && host == "localhost")) && apple_host(host, loopback)+ }}}diff --git a/crates/quince-auth/src/srp.rs b/crates/quince-auth/src/srp.rsindex 888a351..4cfb13f 100644--- a/crates/quince-auth/src/srp.rs+++ b/crates/quince-auth/src/srp.rs@@ -102,6 +102,8 @@ pub struct Client {pub struct Proof {pub m1: [u8; 32],pub m2: [u8; 32],+ /// The shared session key `K = H(PAD(S))`. Apple's escrow step sends it with its proof.+ pub key: [u8; 32],}impl Client {@@ -200,7 +202,7 @@ impl Client {// M2 = H(A || M1 || K)let m2 = sha256(&[&a_padded, &m1, &key]);- Some(Proof { m1, m2 })+ Some(Proof { m1, m2, key })}}@@ -332,7 +334,7 @@ mod tests {let a = pad(&be(&c.a_pub), w);let m1 = sha256(&[&x_or, &h_i, salt, &a, &pad(b, w), &key]);let m2 = sha256(&[&a, &m1, &key]);- Proof { m1, m2 }+ Proof { m1, m2, key }}#[test]@@ -380,3 +382,60 @@ mod tests {assert_eq!(got.m2, want.m2);}}++#[cfg(test)]+mod escrow_tests {+ use super::*;++ /// Apple's escrow step is the same exchange with an empty account name (icloud-photos-sync+ /// #1124, rclone#10048): its M1 differs from the sign-in's, only by `H(I)`, and its session+ /// key is the same for the same `a`, `B`, salt and password.+ #[test]+ fn an_empty_account_name_changes_the_proof_not_the_key() {+ let a = [0x42u8; 32];+ let salt = [0x77u8; 16];+ let mut b = vec![0u8; 256];+ b[255] = 0x05;+ b[0] = 0x3c;+ let signed = Client::with_private_key("[email protected]", &a)+ .process_challenge("hunter2", Protocol::S2k, &salt, &b, 1000)+ .unwrap();+ let escrow = Client::with_private_key("", &a)+ .process_challenge("hunter2", Protocol::S2k, &salt, &b, 1000)+ .unwrap();+ assert_ne!(signed.m1, escrow.m1);+ assert_eq!(signed.key, escrow.key);+ let c = Client::with_private_key("", &a);+ let reference = tests_reference(&c, &salt, &b);+ assert_eq!(escrow.m1, reference.0);+ assert_eq!(escrow.m2, reference.1);+ assert_eq!(escrow.key, reference.2);+ }++ /// The proof for an empty account name, by the textbook formulas.+ fn tests_reference(c: &Client, salt: &[u8], b: &[u8]) -> ([u8; 32], [u8; 32], [u8; 32]) {+ let n = n();+ let w = be(&n).len();+ let g = BigUint::from(G);+ let b_pub = BigUint::from_bytes_be(b);+ let k = BigUint::from_bytes_be(&sha256(&[&pad(&be(&n), w), &pad(&be(&g), w)]));+ let u = BigUint::from_bytes_be(&sha256(&[&pad(&be(&c.a_pub), w), &pad(b, w)]));+ let derived = derive_key("hunter2", Protocol::S2k, salt, 1000);+ let x = BigUint::from_bytes_be(&sha256(&[salt, &sha256(&[b":", &derived])]));+ let v = g.modpow(&x, &n);+ let base = (&b_pub + &n * &k - (&k * &v) % &n) % &n;+ let s = base.modpow(&(&c.a + &u * &x), &n);+ let key = sha256(&[&pad(&be(&s), w)]);+ let h_n = sha256(&[&be(&n)]);+ let h_g = sha256(&[&pad(&be(&g), w)]);+ let mut x_or = [0u8; 32];+ for i in 0..32 {+ x_or[i] = h_n[i] ^ h_g[i];+ }+ let h_i = sha256(&[b""]);+ let a = pad(&be(&c.a_pub), w);+ let m1 = sha256(&[&x_or, &h_i, salt, &a, &pad(b, w), &key]);+ let m2 = sha256(&[&a, &m1, &key]);+ (m1, m2, key)+ }+}diff --git a/crates/quince-auth/tests/apple_only.rs b/crates/quince-auth/tests/apple_only.rsindex 9228f93..91d19c0 100644--- a/crates/quince-auth/tests/apple_only.rs+++ b/crates/quince-auth/tests/apple_only.rs@@ -31,6 +31,31 @@ fn only_apples_hosts_count_as_apples() {}}+/// Apple's own hosts, but over plain HTTP: refused before anything leaves the machine, so the+/// session's cookies never cross the network in the clear (pyicloud#356, #401) — an address in+/// Apple's data, or a redirect down to HTTP, included.+#[tokio::test(flavor = "multi_thread")]+async fn apples_hosts_over_plain_http_are_refused() {+ let client = quince_auth::apple_only().build().unwrap();+ for url in [+ "http://setup.icloud.com/setup/ws/1/validate",+ "http://p45-contactsws.icloud.com/co/startup",+ "http://idmsa.apple.com/appleauth/auth",+ "http://cvws.icloud-content.com/B/abc",+ ] {+ let err = client+ .get(url)+ .send()+ .await+ .expect_err("plain HTTP to Apple");+ let said = format!("{err:?}");+ assert!(+ said.contains("Apple's client reaches only Apple"),+ "{url}: refused before connecting: {said}"+ );+ }+}+#[tokio::test(flavor = "multi_thread")]async fn a_client_refuses_anything_but_apple_before_connecting() {let client = quince_auth::apple_only().build().unwrap();diff --git a/crates/quince-auth/tests/auth_flow.rs b/crates/quince-auth/tests/auth_flow.rsindex a064528..3398619 100644--- a/crates/quince-auth/tests/auth_flow.rs+++ b/crates/quince-auth/tests/auth_flow.rs@@ -1620,3 +1620,319 @@ async fn sign_in_is_not_held_up_by_a_cooldown_from_a_clock_that_ran_ahead() {1);}++/// `/escrow/init` answering a well-formed challenge, and `/escrow/complete` a new session token.+async fn mount_escrow(server: &MockServer) {+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/escrow/init"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "salt": b64(&[0x31; 16]),+ "b": b64(&[0x6a; 256]),+ "c": "escrow-c",+ "iteration": 20173,+ "protocol": "s2k",+ })))+ .mount(server)+ .await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/escrow/complete"))+ .respond_with(+ ResponseTemplate::new(200)+ .insert_header("X-Apple-Session-Token", "session-token-escrow")+ .set_body_json(json!({})),+ )+ .mount(server)+ .await;+}++/// The daily code: a computer Apple already trusts signs in again, and Apple answers 409 with+/// `X-Apple-EDP` — "trust token accepted, now the escrow step" (rclone#10048,+/// icloud-photos-sync#1124). Read as "a code", every lapse asked for one. Now: the escrow step,+/// then the account — no code, nothing pushed to the phone.+#[tokio::test]+async fn a_trusted_sign_in_that_asks_for_escrow_needs_no_code() {+ let dir = tempfile::tempdir().unwrap();+ signed_in(dir.path()).await;++ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/signin/complete"))+ .respond_with(+ ResponseTemplate::new(409)+ .insert_header("X-Apple-EDP", "1")+ .insert_header("X-Apple-Session-Token", "session-token-abc")+ .set_body_json(json!({})),+ )+ .mount(&server)+ .await;+ mount_escrow(&server).await;+ mount_trust_and_login(&server).await;++ let mut client = client_for(&server, dir.path());+ assert_eq!(+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap(),+ SignInOutcome::Complete+ );+ let reqs = server.received_requests().await.unwrap();+ assert_eq!(code_pushes(&reqs), 0, "no code asked for");+ let init = requests_to(&reqs, "/escrow/init");+ assert_eq!(init.len(), 1);+ let body: serde_json::Value = serde_json::from_slice(&init[0].body).unwrap();+ assert_eq!(+ body["accountName"], "",+ "the escrow proof is made with an empty account name"+ );+ assert_eq!(body["protocols"], json!(["s2k", "s2k_fo"]));+ let complete = requests_to(&reqs, "/escrow/complete");+ assert_eq!(complete.len(), 1);+ let body: serde_json::Value = serde_json::from_slice(&complete[0].body).unwrap();+ assert_eq!(body["c"], "escrow-c", "the challenge is echoed");+ for key in ["m1", "m2", "k"] {+ let v = body[key].as_str().unwrap_or_default();+ assert_eq!(+ base64::Engine::decode(&base64::engine::general_purpose::STANDARD, v)+ .map(|b| b.len())+ .unwrap_or(0),+ 32,+ "{key} is a 32-byte value"+ );+ }+ assert!(+ requests_to(&reqs, "/setup/ws/1/accountLogin").len() == 1,+ "and the account is opened"+ );+}++/// Without a trust token a 409 is a code, escrow header or not: a first sign-in never skips it.+#[tokio::test]+async fn a_first_sign_in_that_mentions_escrow_still_asks_for_a_code() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/signin/complete"))+ .respond_with(+ ResponseTemplate::new(409)+ .insert_header("X-Apple-EDP", "1")+ .set_body_json(json!({})),+ )+ .mount(&server)+ .await;+ Mock::given(method("PUT"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(ResponseTemplate::new(202))+ .mount(&server)+ .await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());+ assert_eq!(+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap(),+ SignInOutcome::NeedsTwoFactor+ );+ assert!(requests_to(&server.received_requests().await.unwrap(), "/escrow/init").is_empty());+}++/// An accepted code whose answer asks for escrow: the escrow step comes before the trust+/// token is asked for — without it Apple does not honour that token next time.+#[tokio::test]+async fn an_accepted_code_that_asks_for_escrow_completes_it_before_trust() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 409).await;+ Mock::given(method("PUT"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(ResponseTemplate::new(202))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(+ ResponseTemplate::new(409)+ .insert_header("X-Apple-PDP", "1")+ .insert_header("X-Apple-Session-Token", "session-token-code")+ .set_body_json(json!({ "securityCode": { "valid": true } })),+ )+ .mount(&server)+ .await;+ mount_escrow(&server).await;+ mount_trust_and_login(&server).await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();+ client.submit_two_factor("123456").await.unwrap();+ let reqs = server.received_requests().await.unwrap();+ let order: Vec<&str> = reqs+ .iter()+ .map(|r| r.url.path())+ .filter(|p| p.ends_with("/escrow/complete") || p.ends_with("/2sv/trust"))+ .collect();+ assert_eq!(+ order,+ [+ "/appleauth/auth/escrow/complete",+ "/appleauth/auth/2sv/trust"+ ],+ "escrow first, then trust"+ );+ assert_eq!(+ client.session().trust_token.as_deref(),+ Some("trust-token-xyz")+ );+}++/// `/signin/complete` answering 412: Apple's repair step, as icloudpd takes it, then the account+/// — not "two-factor auth isn't switched on".+#[tokio::test]+async fn a_412_at_sign_in_is_repaired_and_carries_on() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 412).await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/repair/complete"))+ .respond_with(ResponseTemplate::new(204))+ .mount(&server)+ .await;+ mount_trust_and_login(&server).await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());+ assert_eq!(+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap(),+ SignInOutcome::Complete+ );+ let reqs = server.received_requests().await.unwrap();+ let repair = requests_to(&reqs, "/repair/complete");+ assert_eq!(repair.len(), 1);+ assert_eq!(repair[0].body, b"{}");+}++/// A repair Apple refuses is said as what to do — at account.apple.com — and is not counted as+/// a wrong password.+#[tokio::test]+async fn a_repair_apple_refuses_says_where_to_finish_it() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 412).await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/repair/complete"))+ .respond_with(ResponseTemplate::new(400).set_body_json(json!({})))+ .mount(&server)+ .await;+ 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::RepairNeeded), "{err:?}");+ assert!(err.to_string().contains("account.apple.com"));+ assert_eq!(client.session().consecutive_failures, 0);+}++/// A texted code answered 412 with a repair session token was accepted (pyicloud#466): the+/// sign-in finishes, never "That code didn't match".+#[tokio::test]+async fn a_texted_code_answered_412_with_a_repair_token_is_accepted() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 409).await;+ Mock::given(method("PUT"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(ResponseTemplate::new(202))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/verify/phone/securitycode"))+ .respond_with(+ ResponseTemplate::new(412)+ .insert_header("X-Apple-Repair-Session-Token", "repair-token")+ .insert_header("X-Apple-Session-Token", "session-token-sms")+ .set_body_json(json!({})),+ )+ .mount(&server)+ .await;+ mount_trust_and_login(&server).await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();+ client.submit_sms_code(1, "123456").await.unwrap();+ assert_eq!(+ client.session().trust_token.as_deref(),+ Some("trust-token-xyz")+ );+}++/// An account that signs in with security keys is told so, not left at a code screen.+#[tokio::test]+async fn an_account_with_security_keys_is_recognised() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/appleauth/auth"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "trustedDeviceCount": 0,+ "fsaChallenge": { "challenge": "Y2hhbGxlbmdl", "keyHandles": ["aGFuZGxl"], "rpId": "apple.com" },+ "keyNames": ["Key"]+ })))+ .mount(&server)+ .await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());+ assert!(client.two_factor_options().await.unwrap().security_key);++ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/appleauth/auth"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "trustedDeviceCount": 1, "fsaChallenge": { "challenge": "", "keyHandles": [] }+ })))+ .mount(&server)+ .await;+ let mut client = client_for(&server, dir.path());+ assert!(+ !client.two_factor_options().await.unwrap().security_key,+ "an empty challenge is no security key"+ );+}++/// An account Apple answers with no services at all (seen with a beta of iOS on it,+/// icloudpd#1361): signed in, nothing to read, nothing crashes.+#[tokio::test]+async fn an_account_with_no_services_signs_in_and_offers_none() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 200).await;+ Mock::given(method("POST"))+ .and(path("/setup/ws/1/accountLogin"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "dsInfo": { "dsid": "1234567890", "hasUnreleasedOS": true },+ "webservices": {},+ "configBag": { "urls": {} }+ })))+ .mount(&server)+ .await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());+ assert_eq!(+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap(),+ SignInOutcome::Complete+ );+ assert!(client.session().service_url("ckdatabasews").is_none());+ assert!(client.data_access_missing().is_empty());+}diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 7a326fb..3c6d0fc 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -30,6 +30,8 @@ export type TwoFactorOptions = {trustedDeviceCount: number;phones: TrustedPhone[];tooManyCodesSent: boolean;+ /** The account signs in with a security key, which Skykeep can't use yet. */+ securityKey?: boolean;};/** How one service's refresh ended. */diff --git a/src/screens/CodeEntry.tsx b/src/screens/CodeEntry.tsxindex 7ec9621..9bd19b6 100644--- a/src/screens/CodeEntry.tsx+++ b/src/screens/CodeEntry.tsx@@ -96,6 +96,26 @@ export function CodeEntry({}}+ // An account that signs in with a security key gets no code: Apple asks for the key. Said+ // plainly, rather than a code screen waiting for something that never comes.+ if (options?.securityKey) {+ return (+ <div className="sheet enter-sheet">+ <Mark className="mark" />+ <h1>This account uses a security key</h1>+ <p className="lede">+ Your Apple Account signs in with a security key. Skykeep can't sign in with security keys yet, so it+ can't finish signing in to this account.+ </p>+ <div className="sheet-foot">+ <button className="link" type="button" onClick={onCancel}>+ Use a different Apple Account+ </button>+ </div>+ </div>+ );+ }+return (<div className="sheet enter-sheet" aria-busy={verifying}><Mark className="mark" />