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
Bound an untrusted work factor, and make quality checkable in one command
Yashwanth Kamireddic6fa6f96078b
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjsnew file mode 100644index 0000000..a3ea16d--- /dev/null+++ b/.uiverify/a11y.mjs@@ -0,0 +1,83 @@+// Accessibility audit with axe-core — the same engine Lighthouse and Deque use.+// Every auth screen, in both themes, at WCAG 2.1 AA.+import { chromium } from "playwright";+import AxeBuilder from "@axe-core/playwright";++const SERVICES = ["account","archivews","calendar","ckdatabasews","cksharews","contacts",+ "contactsweb","developerapi","docws","drivews","findme","geows","iwmb","iworkexportws",+ "iworkthumbnailws","keyvalue","mail","mcc","mccgateway","mpp","notes","photos",+ "photosupload","premiummailsettings","push","reminders","settings","sharedlibrary",+ "sharedstreams","ubiquity","uploadimagews"];++function installStub({ screen, services, twoFactor }) {+ window.__TAURI_INTERNALS__ = {+ transformCallback: (cb) => cb,+ invoke: async (cmd) => {+ switch (cmd) {+ case "auth_status":+ return { hasStoredSession: screen === "library", signedIn: screen === "library" };+ case "auth_resume": return screen === "library";+ case "auth_sign_in": return screen === "code" ? "needs_two_factor" : "complete";+ case "auth_two_factor_options": return twoFactor;+ case "account_services": return services;+ default: return null;+ }+ },+ };+}++const TWO_FACTOR = { trustedDeviceCount: 0, phones: [{ id: 1, maskedNumber: "+91 ••••• ••318" }], tooManyCodesSent: false };++const screens = [+ { name: "sign-in", screen: "signin" },+ { name: "code", screen: "code", act: async (p) => {+ await p.fill('input[aria-label="Apple ID"]', "[email protected]");+ await p.fill('input[aria-label="Password"]', "secret");+ await p.click('button[type="submit"]');+ await p.waitForSelector(".code");+ } },+ { name: "library", screen: "library", act: async (p) => {+ await p.waitForSelector(".sidebar .nav-item");+ await p.click(".nav-toggle"); // audit the expanded state too+ } },+];++const browser = await chromium.launch();+let total = 0;++for (const theme of ["light", "dark"]) {+ for (const { name, screen, act } of screens) {+ const ctx = await browser.newContext({+ viewport: { width: 1040, height: 800 },+ colorScheme: theme,+ });+ await ctx.addInitScript(installStub, { screen, services: SERVICES, twoFactor: TWO_FACTOR });+ const page = await ctx.newPage();+ await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+ if (act) await act(page);+ await page.waitForTimeout(400);++ const { violations } = await new AxeBuilder({ page })+ .withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"])+ .analyze();++ total += violations.length;+ const label = `${name} (${theme})`.padEnd(18);+ if (violations.length === 0) {+ console.log(`${label} clean`);+ } else {+ console.log(`${label} ${violations.length} violation(s)`);+ for (const v of violations) {+ console.log(` [${v.impact}] ${v.id} — ${v.help}`);+ for (const node of v.nodes.slice(0, 3)) {+ console.log(` ${node.html.slice(0, 110)}`);+ }+ }+ }+ await ctx.close();+ }+}++await browser.close();+console.log(total === 0 ? "\nPASS no WCAG 2.1 AA violations" : `\nFAIL ${total} violation(s)`);+process.exitCode = total === 0 ? 0 : 1;diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjsnew file mode 100644index 0000000..e7dc081--- /dev/null+++ b/.uiverify/keyboard.mjs@@ -0,0 +1,120 @@+// Keyboard-only operability. axe cannot judge focus flow, and this is what a keyboard or+// screen-reader user actually experiences.+import { chromium } from "playwright";++const SERVICES = ["calendar","contacts","reminders","notes","photos","drivews","mail",+ "findme","sharedlibrary","sharedstreams","account","push","mpp","geows"];++function installStub({ screen, services, twoFactor }) {+ window.__TAURI_INTERNALS__ = {+ transformCallback: (cb) => cb,+ invoke: async (cmd) => {+ switch (cmd) {+ case "auth_status":+ return { hasStoredSession: screen === "library", signedIn: screen === "library" };+ case "auth_resume": return screen === "library";+ case "auth_sign_in": return screen === "code" ? "needs_two_factor" : "complete";+ case "auth_two_factor_options": return twoFactor;+ case "account_services": return services;+ default: return null;+ }+ },+ };+}+const TWO_FACTOR = { trustedDeviceCount: 2, phones: [], tooManyCodesSent: false };++const browser = await chromium.launch();+const checks = [];+const check = (name, ok, detail = "") => checks.push({ name, ok, detail });++async function open(screen) {+ const ctx = await browser.newContext({ viewport: { width: 1040, height: 800 } });+ await ctx.addInitScript(installStub, { screen, services: SERVICES, twoFactor: TWO_FACTOR });+ const page = await ctx.newPage();+ await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+ await page.waitForTimeout(300);+ return { ctx, page };+}++const focused = (page) =>+ page.evaluate(() => {+ const el = document.activeElement;+ if (!el) return "none";+ return el.getAttribute("aria-label") || el.textContent?.trim().slice(0, 24) || el.tagName;+ });++// --- sign-in: every control reachable, in a sensible order ---+{+ const { ctx, page } = await open("signin");+ const seen = [];+ for (let i = 0; i < 4; i++) {+ await page.keyboard.press("Tab");+ seen.push(await focused(page));+ }+ check("sign-in reaches Apple ID, Password, Sign in by Tab",+ seen.includes("Apple ID") && seen.includes("Password") && seen.some((s) => /Sign in/.test(s)),+ seen.join(" → "));++ // A visible focus ring is the whole point of keyboard focus.+ await page.focus('input[aria-label="Apple ID"]');+ const ring = await page.evaluate(() => {+ const g = document.querySelector(".field-group");+ return g ? getComputedStyle(g).boxShadow : "";+ });+ check("focused field shows a visible ring", ring.includes("rgb"), ring.slice(0, 48));+ await ctx.close();+}++// --- code: one tab stop, not six ---+{+ const { ctx, page } = await open("code");+ await page.fill('input[aria-label="Apple ID"]', "[email protected]");+ await page.fill('input[aria-label="Password"]', "secret");+ await page.click('button[type="submit"]');+ await page.waitForSelector(".code");++ check("code field takes focus automatically", (await focused(page)) === "Digit 1");++ const stops = await page.evaluate(+ () => document.querySelectorAll('.code input[tabindex="0"]').length+ );+ check("six boxes are ONE tab stop, not six", stops === 1, `${stops} tabbable`);++ // Typing advances; the whole code submits without touching a mouse.+ await page.keyboard.type("4812");+ check("typing advances between boxes", (await focused(page)) === "Digit 5");+ await ctx.close();+}++// --- library: arrow keys, single tab stop ---+{+ const { ctx, page } = await open("library");+ await page.waitForSelector(".sidebar .nav-item");++ const stops = await page.evaluate(+ () => document.querySelectorAll('.sidebar .nav-item[tabindex="0"]').length+ );+ check("sidebar is ONE tab stop", stops === 1, `${stops} tabbable`);++ await page.focus('.nav-item[aria-current="true"]');+ const before = await focused(page);+ await page.keyboard.press("ArrowDown");+ const after = await focused(page);+ check("ArrowDown moves down the sidebar", before !== after, `${before} → ${after}`);++ await page.keyboard.press("End");+ const end = await focused(page);+ await page.keyboard.press("Home");+ const home = await focused(page);+ check("Home/End jump to the ends", end !== home, `End=${end} Home=${home}`);+ await ctx.close();+}++await browser.close();+let failed = 0;+for (const c of checks) {+ if (!c.ok) failed++;+ console.log(`${c.ok ? "PASS" : "FAIL"} ${c.name}${c.detail ? ` [${c.detail}]` : ""}`);+}+console.log(failed === 0 ? "\nPASS keyboard-only operation works" : `\nFAIL ${failed} check(s)`);+process.exitCode = failed === 0 ? 0 : 1;diff --git a/check.sh b/check.shnew file mode 100755index 0000000..a4e1eb1--- /dev/null+++ b/check.sh@@ -0,0 +1,33 @@+#!/usr/bin/env bash+# Everything that has to be true before a change is worth keeping.+# One command, so "is it broken?" is answerable rather than a matter of trust.+set -uo pipefail+cd "$(dirname "$0")"+export PATH="$HOME/.cargo/bin:$PATH"++fail=0+step() {+ printf '\n\033[1m── %s ──\033[0m\n' "$1"; shift+ if "$@"; then printf '\033[32mok\033[0m\n'; else printf '\033[31mFAILED\033[0m\n'; fail=1; fi+}++step "rust format" cargo fmt --all -- --check+step "rust lint" cargo clippy --workspace --all-targets -- -D warnings+step "rust tests" cargo test --workspace --quiet+step "typescript" npx tsc --noEmit+step "frontend build" npm run build++# The browser checks need the built bundle served.+npx vite preview --port 4173 --strictPort >/tmp/quince-preview.log 2>&1 &+preview=$!+trap 'kill $preview 2>/dev/null' EXIT+for _ in $(seq 20); do curl -sf -o /dev/null http://localhost:4173/ && break; sleep 0.5; done++step "ui renders" node .uiverify/shots.mjs+step "nav behaviour" node .uiverify/assert.mjs+step "accessibility" node .uiverify/a11y.mjs+step "keyboard only" node .uiverify/keyboard.mjs++printf '\n'+if [ "$fail" -eq 0 ]; then printf '\033[32mAll checks passed.\033[0m\n'; else printf '\033[31mSome checks failed.\033[0m\n'; fi+exit "$fail"diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex 1f41209..0f3f4d9 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -75,6 +75,11 @@ impl Endpoints {/// iCloud web's first-party OAuth widget key. Not a secret — it is public in the web client.const WIDGET_KEY: &str = "d39ba9916b7251055b22c7f910e2ea796ee65e98b2ddecea8f5dde8d9d1a815d";+/// Bounds on Apple's PBKDF2 iteration count. Apple uses roughly 20k; anything far outside+/// this is either a corrupted response or something trying to make us burn CPU.+const MIN_PBKDF2_ITERATIONS: u32 = 1_000;+const MAX_PBKDF2_ITERATIONS: u32 = 1_000_000;+const UA: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 \(KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36";@@ -96,8 +101,10 @@ pub enum Error {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 — \- repeated attempts risk a temporary lock")]+ #[error(+ "Apple is rate-limiting this account. Wait a few minutes before trying again — \+ repeated attempts risk a temporary lock"+ )]RateLimited,#[error("couldn't use the system keyring: {0}")]Keyring(String),@@ -132,11 +139,17 @@ fn apple_error(context: &str, status: StatusCode, body: &str) -> Error {return Error::RateLimited;}if !message.is_empty() {- return Error::Protocol(format!("{context}: {message} (Apple code {code}, HTTP {status})"));+ return Error::Protocol(format!(+ "{context}: {message} (Apple code {code}, HTTP {status})"+ ));}}}- let snippet: String = body.chars().take(220).collect::<String>().replace('\n', " ");+ let snippet: String = body+ .chars()+ .take(220)+ .collect::<String>()+ .replace('\n', " ");Error::Protocol(format!("{context}: HTTP {status} {snippet}"))}@@ -254,7 +267,10 @@ impl Client {if let Ok(v) = HeaderValue::from_str(&format!("{}/", endpoints.home)) {defaults.insert("referer", v);}- defaults.insert("accept-language", HeaderValue::from_static("en-US,en;q=0.9"));+ defaults.insert(+ "accept-language",+ HeaderValue::from_static("en-US,en;q=0.9"),+ );let http = HttpClient::builder().cookie_provider(Arc::clone(&jar))@@ -262,7 +278,13 @@ impl Client {.default_headers(defaults).build()?;- Ok(Self { http, jar, store, session, endpoints })+ Ok(Self {+ http,+ jar,+ store,+ session,+ endpoints,+ })}pub fn session(&self) -> &Session {@@ -278,7 +300,11 @@ impl Client {fn capture(&mut self, response: &Response) {for (header, field) in CAPTURED_HEADERS {- if let Some(v) = response.headers().get(*header).and_then(|v| v.to_str().ok()) {+ if let Some(v) = response+ .headers()+ .get(*header)+ .and_then(|v| v.to_str().ok())+ {self.session.set(*field, v.to_string());}}@@ -437,7 +463,9 @@ impl Client {if let Some(until) = self.session.retry_after {let now = unix_now();if now < until {- return Err(Error::CoolingDown { seconds: until - now });+ return Err(Error::CoolingDown {+ seconds: until - now,+ });}}@@ -478,7 +506,8 @@ impl Client {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")))+ B64.decode(raw)+ .map_err(|_| Error::Protocol(format!("`{key}` wasn't valid base64")))};let salt = decode("salt")?;let b_pub = decode("b")?;@@ -486,10 +515,19 @@ impl Client {.as_str().ok_or_else(|| Error::Protocol("sign-in response had no `c`".into()))?.to_string();- let iterations = init["iteration"]- .as_u64()- .ok_or_else(|| Error::Protocol("sign-in response had no `iteration`".into()))?- as u32;+ 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}")))?;@@ -497,7 +535,9 @@ impl Client {// --- /signin/complete: submit the proof ---let proof = client.process_challenge(password, protocol, &salt, &b_pub, iterations)- .ok_or_else(|| Error::Protocol("Apple's sign-in challenge failed its safety check".into()))?;+ .ok_or_else(|| {+ Error::Protocol("Apple's sign-in challenge failed its safety check".into())+ })?;let mut body = json!({"accountName": apple_id,@@ -535,9 +575,9 @@ impl Client {Ok(SignInOutcome::Complete)}StatusCode::UNAUTHORIZED => Err(Error::BadCredentials),- StatusCode::PRECONDITION_FAILED => {- Err(Error::UnsupportedAccount("two-factor auth isn't switched on".into()))- }+ StatusCode::PRECONDITION_FAILED => Err(Error::UnsupportedAccount(+ "two-factor auth isn't switched on".into(),+ )),s => Err(apple_error("finishing sign-in", s, &text)),}}@@ -549,7 +589,12 @@ impl Client {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(&self.endpoints.auth).headers(headers).send().await?;+ let r = self+ .http+ .get(&self.endpoints.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);@@ -575,7 +620,9 @@ impl Client {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),+ too_many_codes_sent: v["securityCode"]["tooManyCodesSent"]+ .as_bool()+ .unwrap_or(false),})}@@ -585,14 +632,19 @@ impl Client {headers.insert("accept", HeaderValue::from_static("application/json"));let r = self.http- .put(format!("{}/verify/trusteddevice/securitycode", self.endpoints.auth))+ .put(format!(+ "{}/verify/trusteddevice/securitycode",+ self.endpoints.auth+ )).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})")));+ return Err(Error::Protocol(format!(+ "couldn't resend the code ({status})"+ )));}Ok(())}@@ -611,7 +663,9 @@ impl Client {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})")));+ return Err(Error::Protocol(format!(+ "couldn't send the text ({status})"+ )));}Ok(())}@@ -663,7 +717,10 @@ impl Client {headers.insert("accept", HeaderValue::from_static("application/json"));let r = self.http- .post(format!("{}/verify/trusteddevice/securitycode", self.endpoints.auth))+ .post(format!(+ "{}/verify/trusteddevice/securitycode",+ self.endpoints.auth+ )).headers(headers).body(json!({ "securityCode": { "code": code } }).to_string()).send()@@ -699,7 +756,12 @@ impl Client {/// `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();- let r = self.http.get(format!("{}/2sv/trust", self.endpoints.auth)).headers(headers).send().await?;+ let r = self+ .http+ .get(format!("{}/2sv/trust", self.endpoints.auth))+ .headers(headers)+ .send()+ .await?;self.capture(&r);let status = r.status();let body = r.text().await.unwrap_or_default();@@ -731,7 +793,9 @@ impl Client {let status = r.status();let text = r.text().await.unwrap_or_default();if !status.is_success() {- return Err(Error::Protocol(format!("couldn't open the account ({status})")));+ return Err(Error::Protocol(format!(+ "couldn't open the account ({status})"+ )));}Ok(serde_json::from_str(&text)?)}@@ -751,7 +815,6 @@ impl Client {}}-#[cfg(test)]mod tests {use super::*;@@ -776,7 +839,12 @@ mod tests {#[test]fn session_headers_are_forwarded_when_present() {- let h = base_oauth_headers("auth-test", HOME_T, Some("scnt-value"), Some("session-value"));+ let h = base_oauth_headers(+ "auth-test",+ HOME_T,+ Some("scnt-value"),+ Some("session-value"),+ );assert_eq!(h.get("scnt").unwrap(), "scnt-value");assert_eq!(h.get("x-apple-id-session-id").unwrap(), "session-value");}@@ -784,11 +852,22 @@ mod tests {/// Sign-in must not advertise a session that does not exist yet.#[test]fn init_headers_omit_challenge_state() {- let stale = base_oauth_headers("auth-test", HOME_T, Some("stale-scnt"), Some("stale-session"));- assert!(stale.get("scnt").is_some(), "sanity: the helper does forward them");+ let stale = base_oauth_headers(+ "auth-test",+ HOME_T,+ Some("stale-scnt"),+ Some("stale-session"),+ );+ assert!(+ stale.get("scnt").is_some(),+ "sanity: the helper does forward them"+ );let init = with_srp_origin(base_oauth_headers("auth-test", HOME_T, None, None), ROOT_T);- assert!(init.get("scnt").is_none(), "/signin/init must not send scnt");+ assert!(+ init.get("scnt").is_none(),+ "/signin/init must not send scnt"+ );assert!(init.get("x-apple-id-session-id").is_none(),"/signin/init must not send a session id"@@ -806,12 +885,17 @@ mod tests {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");+ 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."}]}"#;+ let wrong =+ r#"{"serviceErrors":[{"code":"-21669","message":"Incorrect verification code."}]}"#;assert!(matches!(apple_error("x", StatusCode::CONFLICT, wrong),Error::BadCodediff --git a/crates/quince-auth/src/session.rs b/crates/quince-auth/src/session.rsindex 75371dc..d073e2d 100644--- a/crates/quince-auth/src/session.rs+++ b/crates/quince-auth/src/session.rs@@ -135,7 +135,10 @@ impl Store {/// Production: secrets in the OS keyring.pub fn keyring(state_dir: &Path) -> std::io::Result<Self> {std::fs::create_dir_all(state_dir)?;- Ok(Self { cookie_path: state_dir.join("cookies.json"), backend: Backend::Keyring })+ Ok(Self {+ cookie_path: state_dir.join("cookies.json"),+ backend: Backend::Keyring,+ })}/// Tests only: secrets in a file under `state_dir`. Never use for real accounts —diff --git a/crates/quince-auth/src/srp.rs b/crates/quince-auth/src/srp.rsindex a015fab..9b099af 100644--- a/crates/quince-auth/src/srp.rs+++ b/crates/quince-auth/src/srp.rs@@ -110,7 +110,11 @@ impl Client {let n = n();let a = BigUint::from_bytes_be(a_bytes);let a_pub = BigUint::from(G).modpow(&a, &n);- Self { username: username.to_string(), a, a_pub }+ Self {+ username: username.to_string(),+ a,+ a_pub,+ }}/// Start with a fresh random private key. Production use.@@ -184,14 +188,7 @@ impl Client {h_n_xor_g[i] = h_n[i] ^ h_g[i];}let h_i = sha256(&[self.username.as_bytes()]);- let m1 = sha256(&[- &h_n_xor_g,- &h_i,- salt,- &be(&self.a_pub),- &be(&b_pub),- &key,- ]);+ let m1 = sha256(&[&h_n_xor_g, &h_i, salt, &be(&self.a_pub), &be(&b_pub), &key]);// M2 = H(A || M1 || K)let m2 = sha256(&[&be(&self.a_pub), &m1, &key]);@@ -211,7 +208,10 @@ mod tests {}fn hex(s: &str) -> Vec<u8> {- (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect()+ (0..s.len())+ .step_by(2)+ .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())+ .collect()}/// Every value must match srp==1.0.22 — the library icloudpd pins — on inputs where@@ -230,12 +230,18 @@ mod tests {let salt = hex(case["salt_hex"].as_str().unwrap());let derived = derive_key(password, proto, &salt, iterations);- assert_eq!(hex_lower(&derived), case["derived_key"].as_str().unwrap(),- "{name}: derived key");+ assert_eq!(+ hex_lower(&derived),+ case["derived_key"].as_str().unwrap(),+ "{name}: derived key"+ );let client = Client::with_private_key(username, &a);- assert_eq!(hex_lower(&client.a_public_bytes()), case["A"].as_str().unwrap(),- "{name}: public key A");+ assert_eq!(+ hex_lower(&client.a_public_bytes()),+ case["A"].as_str().unwrap(),+ "{name}: public key A"+ );let p = client.process_challenge(password, proto, &salt, &b_pub, iterations)@@ -253,10 +259,15 @@ mod tests {let v = vectors();let case = &v["leading_zero_salt"];let salt = hex(case["salt_hex"].as_str().unwrap());- assert_eq!(salt[0], 0x00, "this vector only means something with a leading zero salt");-- let client = Client::with_private_key(v["username"].as_str().unwrap(),- &hex(v["a_hex"].as_str().unwrap()));+ assert_eq!(+ salt[0], 0x00,+ "this vector only means something with a leading zero salt"+ );++ let client = Client::with_private_key(+ v["username"].as_str().unwrap(),+ &hex(v["a_hex"].as_str().unwrap()),+ );let p = client.process_challenge(v["password"].as_str().unwrap(),@@ -267,9 +278,16 @@ mod tests {).expect("challenge is valid");- assert_eq!(hex_lower(&p.m1), case["M1"].as_str().unwrap(), "spec-correct M1");- assert_ne!(hex_lower(&p.m1), case["ctsrp_buggy_M1"].as_str().unwrap(),- "must not reproduce the reference implementation's BIGNUM salt bug");+ assert_eq!(+ hex_lower(&p.m1),+ case["M1"].as_str().unwrap(),+ "spec-correct M1"+ );+ assert_ne!(+ hex_lower(&p.m1),+ case["ctsrp_buggy_M1"].as_str().unwrap(),+ "must not reproduce the reference implementation's BIGNUM salt bug"+ );}#[test]@@ -277,6 +295,8 @@ mod tests {let client = Client::with_private_key("[email protected]", &[7u8; 32]);// B == N => B % N == 0 => SRP-6a safety check must reject.let b = hex(N_HEX);- assert!(client.process_challenge("pw", Protocol::S2k, b"salt", &b, 1000).is_none());+ assert!(client+ .process_challenge("pw", Protocol::S2k, b"salt", &b, 1000)+ .is_none());}}diff --git a/crates/quince-auth/tests/auth_flow.rs b/crates/quince-auth/tests/auth_flow.rsindex dcca5a4..0a53aac 100644--- a/crates/quince-auth/tests/auth_flow.rs+++ b/crates/quince-auth/tests/auth_flow.rs@@ -96,7 +96,9 @@ fn client_for(server: &MockServer, dir: &std::path::Path) -> Client {}fn requests_to<'a>(reqs: &'a [Request], suffix: &str) -> Vec<&'a Request> {- reqs.iter().filter(|r| r.url.path().ends_with(suffix)).collect()+ reqs.iter()+ .filter(|r| r.url.path().ends_with(suffix))+ .collect()}#[tokio::test]@@ -114,7 +116,10 @@ async fn two_factor_sign_in_stores_the_trust_token() {let dir = tempfile::tempdir().unwrap();let mut client = client_for(&server, dir.path());- let outcome = client.sign_in("[email protected]", "hunter2").await.unwrap();+ let outcome = client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();assert_eq!(outcome, SignInOutcome::NeedsTwoFactor);client.submit_two_factor("123456").await.unwrap();@@ -130,7 +135,10 @@ async fn two_factor_sign_in_stores_the_trust_token() {// A fresh client over the same store must resume without a password.let reloaded = client_for(&server, dir.path());- assert!(reloaded.has_stored_session(), "the trust token must outlive the process");+ assert!(+ reloaded.has_stored_session(),+ "the trust token must outlive the process"+ );}/// The regression: an abandoned attempt left `scnt` behind, and replaying it into a new@@ -145,11 +153,17 @@ async fn sign_in_never_replays_a_previous_challenge() {let mut client = client_for(&server, dir.path());// First attempt: abandoned after Apple asks for a code, leaving scnt/session id stored.- client.sign_in("[email protected]", "hunter2").await.unwrap();+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();assert_eq!(client.session().scnt.as_deref(), Some("scnt-from-init"));// Second attempt from the same session must start clean.- client.sign_in("[email protected]", "hunter2").await.unwrap();+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();let reqs = server.received_requests().await.unwrap();let inits = requests_to(&reqs, "/signin/init");@@ -181,23 +195,38 @@ async fn idmsa_origin_is_used_only_for_sign_in() {let dir = tempfile::tempdir().unwrap();let mut client = client_for(&server, dir.path());- client.sign_in("[email protected]", "hunter2").await.unwrap();+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();client.submit_two_factor("123456").await.unwrap();let reqs = server.received_requests().await.unwrap();let origin_of = |r: &Request| {- r.headers.get("origin").and_then(|v| v.to_str().ok()).unwrap_or("<none>").to_string()+ r.headers+ .get("origin")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("<none>")+ .to_string()};for suffix in ["/signin/init", "/signin/complete"] {let found = requests_to(&reqs, suffix);assert!(!found.is_empty(), "no request reached {suffix}");for r in found {- assert_eq!(origin_of(r), SRP_ORIGIN, "{suffix} must use the idmsa origin");+ assert_eq!(+ origin_of(r),+ SRP_ORIGIN,+ "{suffix} must use the idmsa origin"+ );}}- for suffix in ["/verify/trusteddevice/securitycode", "/2sv/trust", "/accountLogin"] {+ for suffix in [+ "/verify/trusteddevice/securitycode",+ "/2sv/trust",+ "/accountLogin",+ ] {let found = requests_to(&reqs, suffix);assert!(!found.is_empty(), "no request reached {suffix}");for r in found {@@ -225,7 +254,10 @@ async fn a_wrong_code_is_reported_as_a_wrong_code() {let dir = tempfile::tempdir().unwrap();let mut client = client_for(&server, dir.path());- client.sign_in("[email protected]", "hunter2").await.unwrap();+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();let err = client.submit_two_factor("000000").await.unwrap_err();assert!(@@ -252,13 +284,19 @@ async fn a_409_that_still_completes_is_treated_as_success() {let dir = tempfile::tempdir().unwrap();let mut client = client_for(&server, dir.path());- client.sign_in("[email protected]", "hunter2").await.unwrap();+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();client.submit_two_factor("123456").await.expect("the session became usable, so the code was accepted");- assert_eq!(client.session().trust_token.as_deref(), Some("trust-token-xyz"));+ assert_eq!(+ client.session().trust_token.as_deref(),+ Some("trust-token-xyz")+ );}#[tokio::test]@@ -269,7 +307,10 @@ async fn throttling_is_named_so_the_fix_is_to_wait() {let dir = tempfile::tempdir().unwrap();let mut client = client_for(&server, dir.path());- let err = client.sign_in("[email protected]", "hunter2").await.unwrap_err();+ let err = client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap_err();assert!(matches!(err, quince_auth::Error::RateLimited),"throttling must be distinguishable from a real failure: {err}"@@ -292,16 +333,27 @@ async fn a_rejected_session_falls_back_cleanly() {{// Seed a stored session that Apple will reject.let mut seed = client_for(&server, dir.path());- seed.sign_in("[email protected]", "hunter2").await.unwrap();+ seed.sign_in("[email protected]", "hunter2")+ .await+ .unwrap();}let mut client = client_for(&server, dir.path());assert!(client.has_stored_session());- assert!(!client.resume().await.unwrap(), "a 421 means the session is dead");- assert!(client.session().scnt.is_none(), "a dead session must not keep its challenge state");+ assert!(+ !client.resume().await.unwrap(),+ "a 421 means the session is dead"+ );+ assert!(+ client.session().scnt.is_none(),+ "a dead session must not keep its challenge state"+ );// And signing in again still works.- let outcome = client.sign_in("[email protected]", "hunter2").await.unwrap();+ let outcome = client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();assert_eq!(outcome, SignInOutcome::NeedsTwoFactor);}@@ -315,7 +367,10 @@ async fn a_cooldown_survives_a_restart_and_spares_apple() {let dir = tempfile::tempdir().unwrap();{let mut client = client_for(&server, dir.path());- let err = client.sign_in("[email protected]", "hunter2").await.unwrap_err();+ let err = client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap_err();assert!(matches!(err, quince_auth::Error::RateLimited));}@@ -323,14 +378,20 @@ async fn a_cooldown_survives_a_restart_and_spares_apple() {// 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();+ 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");+ 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@@ -343,7 +404,10 @@ async fn a_successful_sign_in_clears_the_backoff() {let dir = tempfile::tempdir().unwrap();let mut client = client_for(&server, dir.path());- client.sign_in("[email protected]", "hunter2").await.unwrap();+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();assert_eq!(client.session().consecutive_failures, 0);assert!(client.session().retry_after.is_none());@@ -365,7 +429,10 @@ async fn signing_out_forgets_everything() {let dir = tempfile::tempdir().unwrap();{let mut client = client_for(&server, dir.path());- client.sign_in("[email protected]", "hunter2").await.unwrap();+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();client.submit_two_factor("123456").await.unwrap();assert!(client.session().trust_token.is_some());@@ -376,7 +443,10 @@ async fn signing_out_forgets_everything() {// And nothing survives into a fresh client over the same directory.let reopened = client_for(&server, dir.path());- assert!(!reopened.has_stored_session(), "sign-out must clear the stored session");+ assert!(+ !reopened.has_stored_session(),+ "sign-out must clear the stored session"+ );assert!(reopened.session().trust_token.is_none());assert!(reopened.session().webservices.is_none());}@@ -390,7 +460,10 @@ async fn signing_out_clears_a_cooldown() {let dir = tempfile::tempdir().unwrap();let mut client = client_for(&server, dir.path());- client.sign_in("[email protected]", "hunter2").await.unwrap_err();+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap_err();assert!(client.session().retry_after.is_some());client.sign_out().unwrap();@@ -399,3 +472,35 @@ async fn signing_out_clears_a_cooldown() {"a fresh start must not inherit the previous account's backoff");}++/// Apple's iteration count drives PBKDF2, arrives over the network, and is therefore+/// untrusted input controlling how much work we do. An implausible value must be refused+/// rather than truncated into a cast or left to burn CPU.+#[tokio::test]+async fn an_implausible_work_factor_is_refused() {+ for absurd in [u64::from(u32::MAX) + 1, 5_000_000_000, 3] {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/signin/init"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "salt": b64(&[0x77; 16]),+ "b": b64(&[0x5e; 256]),+ "c": "challenge-c",+ "iteration": absurd,+ "protocol": "s2k",+ })))+ .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::Protocol(_)),+ "iteration={absurd} should be rejected, got {err}"+ );+ }+}diff --git a/package-lock.json b/package-lock.jsonindex acfd555..b744f9b 100644--- a/package-lock.json+++ b/package-lock.json@@ -13,15 +13,30 @@"react-dom": "^18.3.1"},"devDependencies": {+ "@axe-core/playwright": "^4.13.0","@tauri-apps/cli": "^2","@types/react": "^18.3.12","@types/react-dom": "^18.3.1","@vitejs/plugin-react": "^4.3.4",+ "axe-core": "^4.13.0","playwright": "^1.63.0","typescript": "^5.7.2","vite": "^6.0.7"}},+ "node_modules/@axe-core/playwright": {+ "version": "4.13.0",+ "resolved": "https://registry.npmjs.org/@axe-core/playwright/-/playwright-4.13.0.tgz",+ "integrity": "sha512-6YLx+kxXu5GJceG4ozFg+33a2EMTdjYwWGloJ3sb9Kta5pp+ZNS53uxGVog5JetIY8s++P5UrtX+cri+u0VAVg==",+ "dev": true,+ "license": "MPL-2.0",+ "dependencies": {+ "axe-core": "~4.13.0"+ },+ "peerDependencies": {+ "playwright-core": ">= 1.0.0"+ }+ },"node_modules/@babel/code-frame": {"version": "7.29.7","resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",@@ -1555,6 +1570,16 @@"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"}},+ "node_modules/axe-core": {+ "version": "4.13.0",+ "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.13.0.tgz",+ "integrity": "sha512-UzGt8zg7Ny8djbYMhxl2zuEevVa7r2gJjYY5Lwr1xM7+XU2nd6CkIWFTVcCIbAP63vSz71NaVyyuSk9lHKcy0A==",+ "dev": true,+ "license": "MPL-2.0",+ "engines": {+ "node": ">=4"+ }+ },"node_modules/baseline-browser-mapping": {"version": "2.11.22","resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.22.tgz",diff --git a/package.json b/package.jsonindex fd97542..8b48eb7 100644--- a/package.json+++ b/package.json@@ -15,10 +15,12 @@"react-dom": "^18.3.1"},"devDependencies": {+ "@axe-core/playwright": "^4.13.0","@tauri-apps/cli": "^2","@types/react": "^18.3.12","@types/react-dom": "^18.3.1","@vitejs/plugin-react": "^4.3.4",+ "axe-core": "^4.13.0","playwright": "^1.63.0","typescript": "^5.7.2","vite": "^6.0.7"diff --git a/probe/src/main.rs b/probe/src/main.rsindex f4aec53..e3a1160 100644--- a/probe/src/main.rs+++ b/probe/src/main.rs@@ -39,9 +39,17 @@ impl Outcome {fn line(&self) -> String {format!("{} {:<30} {:>4} {}",- if self.ok { "\x1b[32mPASS\x1b[0m" } else { "\x1b[31mFAIL\x1b[0m" },+ if self.ok {+ "\x1b[32mPASS\x1b[0m"+ } else {+ "\x1b[31mFAIL\x1b[0m"+ },self.label,- if self.status == 0 { "—".into() } else { self.status.to_string() },+ if self.status == 0 {+ "—".into()+ } else {+ self.status.to_string()+ },self.detail)}@@ -50,8 +58,18 @@ impl Outcome {/// Describe a response without dumping anyone's personal data.fn summarise(v: &Value) -> String {let mut parts = Vec::new();- for key in ["Collections", "collections", "Reminders", "contacts", "Events", "events",- "records", "zones", "items", "devices"] {+ for key in [+ "Collections",+ "collections",+ "Reminders",+ "contacts",+ "Events",+ "events",+ "records",+ "zones",+ "items",+ "devices",+ ] {if let Some(a) = v.get(key).and_then(|x| x.as_array()) {parts.push(format!("{key}={}", a.len()));}@@ -66,21 +84,24 @@ fn summarise(v: &Value) -> String {parts.join(" ")}-async fn probe_post(- client: &Client,- label: &'static str,- url: String,- body: Value,-) -> Outcome {+async fn probe_post(client: &Client, label: &'static str, url: String, body: Value) -> Outcome {let session = client.session();let q: Vec<(String, String)> = vec![("clientBuildNumber".into(), "2523Project28".into()),("clientMasteringNumber".into(), "2523B28".into()),- ("clientId".into(), session.client_id.clone().unwrap_or_default()),+ (+ "clientId".into(),+ session.client_id.clone().unwrap_or_default(),+ ),("dsid".into(), session.dsid.clone().unwrap_or_default()),];match client.http().post(&url).query(&q).json(&body).send().await {- Err(e) => Outcome { label, ok: false, status: 0, detail: format!("transport: {e}") },+ Err(e) => Outcome {+ label,+ ok: false,+ status: 0,+ detail: format!("transport: {e}"),+ },Ok(r) => {let status = r.status();let text = r.text().await.unwrap_or_default();@@ -98,9 +119,18 @@ async fn probe_post(}(Some(v), true) => summarise(v),(_, true) => format!("{} bytes", text.len()),- _ => text.chars().take(160).collect::<String>().replace('\n', " "),+ _ => text+ .chars()+ .take(160)+ .collect::<String>()+ .replace('\n', " "),};- Outcome { label, ok: status.is_success(), status: status.as_u16(), detail }+ Outcome {+ label,+ ok: status.is_success(),+ status: status.as_u16(),+ detail,+ }}}}@@ -115,7 +145,10 @@ async fn probe_get(let mut q: Vec<(String, String)> = vec![("clientBuildNumber".into(), "2523Project28".into()),("clientMasteringNumber".into(), "2523B28".into()),- ("clientId".into(), session.client_id.clone().unwrap_or_default()),+ (+ "clientId".into(),+ session.client_id.clone().unwrap_or_default(),+ ),];if let Some(d) = &session.dsid {q.push(("dsid".into(), d.clone()));@@ -125,7 +158,12 @@ async fn probe_get(}match client.http().get(&url).query(&q).send().await {- Err(e) => Outcome { label, ok: false, status: 0, detail: format!("transport: {e}") },+ Err(e) => Outcome {+ label,+ ok: false,+ status: 0,+ detail: format!("transport: {e}"),+ },Ok(r) => {let status = r.status();let body = r.text().await.unwrap_or_default();@@ -137,18 +175,29 @@ async fn probe_get(_ if status.as_u16() == 450 => {"needs a fresh sign-in (a resumed session isn't accepted here)".to_string()}- _ => body.chars().take(160).collect::<String>().replace('\n', " "),+ _ => body+ .chars()+ .take(160)+ .collect::<String>()+ .replace('\n', " "),};- Outcome { label, ok: status.is_success(), status: status.as_u16(), detail }+ Outcome {+ label,+ ok: status.is_success(),+ status: status.as_u16(),+ detail,+ }}}}fn state_dir() -> PathBuf {- std::env::var("QUINCE_STATE").map(PathBuf::from).unwrap_or_else(|_| {- PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| ".".into()))- .join(".local/share/quince-probe")- })+ std::env::var("QUINCE_STATE")+ .map(PathBuf::from)+ .unwrap_or_else(|_| {+ PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| ".".into()))+ .join(".local/share/quince-probe")+ })}#[tokio::main]@@ -159,7 +208,10 @@ async fn main() -> Result<()> {let mut client = Client::new(&dir)?;println!("\n\x1b[1mQuince Phase 0 probe\x1b[0m");- println!("state: {} (secrets live in the system keyring)\n", dir.display());+ println!(+ "state: {} (secrets live in the system keyring)\n",+ dir.display()+ );if fresh {client.sign_out().ok();@@ -184,7 +236,10 @@ async fn main() -> Result<()> {if !resumed && code_only {println!("Resuming the pending two-factor challenge (no new sign-in)…\n");let opts = client.two_factor_options().await?;- println!(" trusted devices Apple pushed to : {}", opts.trusted_device_count);+ println!(+ " trusted devices Apple pushed to : {}",+ opts.trusted_device_count+ );for (i, ph) in opts.phones.iter().enumerate() {println!(" [{}] {}", i + 1, ph.masked_number);}@@ -227,7 +282,9 @@ async fn main() -> Result<()> {);}if opts.too_many_codes_sent {- println!(" \x1b[33mApple is rate-limiting new codes. Wait a few minutes.\x1b[0m");+ 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);@@ -235,10 +292,14 @@ async fn main() -> Result<()> {println!("\n Nothing arrived? Two things to know:");println!(" • The code is only created once you tap Allow on the iPhone prompt.");println!(" No prompt means no code was ever generated — waiting won't help.");- println!(" • iOS 18/26 hides \"Get Verification Code\" while the phone is ONLINE.");+ println!(+ " • iOS 18/26 hides \"Get Verification Code\" while the phone is ONLINE."+ );println!(" Turn on Airplane Mode, then Settings → your name → Sign-In &");println!(" Security. A popup offers the code while offline.");- println!("\n Type the 6-digit code, or `r` to push again, or `1`/`2`… to text it.");+ 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 {@@ -257,7 +318,10 @@ async fn main() -> Result<()> {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);+ println!(+ " texted {} — enter the code when it lands",+ phone.masked_number+ );continue;}}@@ -272,7 +336,9 @@ async fn main() -> Result<()> {};match result {Ok(()) => {- println!(" \x1b[32mcode accepted, trust token stored in the keyring\x1b[0m");+ println!(+ " \x1b[32mcode accepted, trust token stored in the keyring\x1b[0m"+ );break;}Err(e) => println!(" {e}"),@@ -285,9 +351,15 @@ async fn main() -> Result<()> {// ---- 3. account facts -------------------------------------------------------let session = client.session();println!("\n\x1b[1m── Account ──\x1b[0m");- println!(" dsid : {}", session.dsid.clone().unwrap_or("—".into()));+ println!(+ " dsid : {}",+ session.dsid.clone().unwrap_or("—".into())+ );println!(" trust token : {}", redact(session.trust_token.as_ref()));- println!(" session token : {}", redact(session.session_token.as_ref()));+ println!(+ " session token : {}",+ redact(session.session_token.as_ref())+ );println!("\n\x1b[1m── Services Apple advertises for this account ──\x1b[0m");if let Some(ws) = session.webservices.as_ref().and_then(|w| w.as_object()) {@@ -304,41 +376,113 @@ async fn main() -> Result<()> {// ---- 4. one session, every service ------------------------------------------println!("\n\x1b[1m── Reachability: one sign-in, every service ──\x1b[0m");let mut results = Vec::new();- let cal_range: &[(&str, &str)] =- &[("startDate", "2026-09-01"), ("endDate", "2026-09-30"), ("lang", "en-us"), ("usertz", "UTC")];+ let cal_range: &[(&str, &str)] = &[+ ("startDate", "2026-09-01"),+ ("endDate", "2026-09-30"),+ ("lang", "en-us"),+ ("usertz", "UTC"),+ ];if let Some(u) = session.service_url("calendar") {- results.push(probe_get(&client, "Calendar /ca/startup", format!("{u}/ca/startup"), cal_range).await);- results.push(probe_get(&client, "Calendar /ca/events", format!("{u}/ca/events"), cal_range).await);+ results.push(+ probe_get(+ &client,+ "Calendar /ca/startup",+ format!("{u}/ca/startup"),+ cal_range,+ )+ .await,+ );+ results.push(+ probe_get(+ &client,+ "Calendar /ca/events",+ format!("{u}/ca/events"),+ cal_range,+ )+ .await,+ );}if let Some(u) = session.service_url("contacts") {- results.push(probe_get(&client, "Contacts /co/startup", format!("{u}/co/startup"),- &[("clientVersion", "2.1"), ("locale", "en_US"), ("order", "last,first")]).await);+ results.push(+ probe_get(+ &client,+ "Contacts /co/startup",+ format!("{u}/co/startup"),+ &[+ ("clientVersion", "2.1"),+ ("locale", "en_US"),+ ("order", "last,first"),+ ],+ )+ .await,+ );}if let Some(u) = session.service_url("reminders") {- results.push(probe_get(&client, "Reminders /rd/startup", format!("{u}/rd/startup"),- &[("clientVersion", "4.0"), ("lang", "en-us"), ("usertz", "UTC")]).await);+ results.push(+ probe_get(+ &client,+ "Reminders /rd/startup",+ format!("{u}/rd/startup"),+ &[+ ("clientVersion", "4.0"),+ ("lang", "en-us"),+ ("usertz", "UTC"),+ ],+ )+ .await,+ );}if let Some(u) = session.service_url("drivews") {- results.push(probe_post(&client, "Drive item details",- format!("{u}/retrieveItemDetailsInFolders"),- serde_json::json!([{- "drivewsid": "FOLDER::com.apple.CloudDocs::root",- "partialData": false,- }])).await);+ results.push(+ probe_post(+ &client,+ "Drive item details",+ format!("{u}/retrieveItemDetailsInFolders"),+ serde_json::json!([{+ "drivewsid": "FOLDER::com.apple.CloudDocs::root",+ "partialData": false,+ }]),+ )+ .await,+ );}if let Some(u) = session.service_url("findme") {- results.push(probe_get(&client, "Find My initClient",- format!("{u}/fmipservice/client/web/initClient"), &[]).await);+ results.push(+ probe_get(+ &client,+ "Find My initClient",+ format!("{u}/fmipservice/client/web/initClient"),+ &[],+ )+ .await,+ );}// CloudKit zone lists double as the Advanced Data Protection tell: with ADP on,// these return nothing readable because Apple's servers hold no keys.if let Some(u) = session.service_url("ckdatabasews") {- let ck: &[(&str, &str)] = &[("ckjsBuildVersion", "17DProjectDev77"), ("ckjsVersion", "2.6.1")];- results.push(probe_get(&client, "Photos CloudKit zones",- format!("{u}/database/1/com.apple.photos.cloud/production/private/zones/list"), ck).await);- results.push(probe_get(&client, "Notes CloudKit zones",- format!("{u}/database/1/com.apple.notes/production/private/zones/list"), ck).await);+ let ck: &[(&str, &str)] = &[+ ("ckjsBuildVersion", "17DProjectDev77"),+ ("ckjsVersion", "2.6.1"),+ ];+ results.push(+ probe_get(+ &client,+ "Photos CloudKit zones",+ format!("{u}/database/1/com.apple.photos.cloud/production/private/zones/list"),+ ck,+ )+ .await,+ );+ results.push(+ probe_get(+ &client,+ "Notes CloudKit zones",+ format!("{u}/database/1/com.apple.notes/production/private/zones/list"),+ ck,+ )+ .await,+ );}for r in &results {@@ -348,8 +492,14 @@ async fn main() -> Result<()> {// ---- 5. verdict -------------------------------------------------------------let passed = results.iter().filter(|r| r.ok).count();println!("\n\x1b[1m── Verdict ──\x1b[0m");- println!(" services reachable from one sign-in : {passed}/{}", results.len());- println!(" trust token stored : {}", session.trust_token.is_some());+ println!(+ " services reachable from one sign-in : {passed}/{}",+ results.len()+ );+ println!(+ " trust token stored : {}",+ session.trust_token.is_some()+ );println!(" resumed with no password or 2FA : {resumed}");if !resumed {println!(@@ -364,8 +514,13 @@ async fn main() -> Result<()> {session.trust_token.is_some(), results.len()));for r in &results {- md.push_str(&format!("- `{}` — **{}** ({}) {}\n",- r.label.trim(), if r.ok { "PASS" } else { "FAIL" }, r.status, r.detail));+ md.push_str(&format!(+ "- `{}` — **{}** ({}) {}\n",+ r.label.trim(),+ if r.ok { "PASS" } else { "FAIL" },+ r.status,+ r.detail+ ));}std::fs::write(dir.join("findings.md"), md)?;println!("\n findings: {}\n", dir.join("findings.md").display());diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 8d1ff84..f35bf93 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -84,7 +84,10 @@ async fn auth_sign_in(#[tauri::command]async fn auth_submit_code(code: String, auth: State<'_, Auth>) -> UiResult<()> {let mut client = auth.client.lock().await;- client.submit_two_factor(&code).await.map_err(|e| e.to_string())+ client+ .submit_two_factor(&code)+ .await+ .map_err(|e| e.to_string())}/// Where Apple can send a code, and whether it already pushed one.@@ -108,13 +111,12 @@ async fn auth_send_sms(phone_id: u64, auth: State<'_, Auth>) -> UiResult<()> {}#[tauri::command]-async fn auth_submit_sms_code(- phone_id: u64,- code: String,- auth: State<'_, Auth>,-) -> UiResult<()> {+async fn auth_submit_sms_code(phone_id: u64, code: String, auth: State<'_, Auth>) -> UiResult<()> {let mut client = auth.client.lock().await;- client.submit_sms_code(phone_id, &code).await.map_err(|e| e.to_string())+ client+ .submit_sms_code(phone_id, &code)+ .await+ .map_err(|e| e.to_string())}#[tauri::command]@@ -155,12 +157,11 @@ fn spawn_heartbeat(client: Arc<Mutex<Client>>) {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(_) => {}+ // 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 a dead one.+ // A transient error is not proof of that, so only a clean `false` ends the loop.+ if matches!(guard.heartbeat().await, Ok(false)) {+ break;}}});@@ -169,9 +170,12 @@ fn spawn_heartbeat(client: Arc<Mutex<Client>>) {fn main() {tauri::Builder::default().setup(|app| {- let dir = state_dir(&app.handle());+ let dir = state_dir(app.handle());let client = Arc::new(Mutex::new(Client::new(&dir)?));- app.manage(Auth { client: Arc::clone(&client), signing_in: AtomicBool::new(false) });+ app.manage(Auth {+ client: Arc::clone(&client),+ signing_in: AtomicBool::new(false),+ });spawn_heartbeat(client);Ok(())})diff --git a/src/components/CodeInput.tsx b/src/components/CodeInput.tsxindex 1eefe87..83d61a7 100644--- a/src/components/CodeInput.tsx+++ b/src/components/CodeInput.tsx@@ -24,6 +24,8 @@ export function CodeInput({}, []);const digits = value.padEnd(6, " ").slice(0, 6).split("");+ // The box Tab should land on: the first empty one, or the last if the code is complete.+ const activeIndex = Math.min(digits.findIndex((d) => !d.trim()) === -1 ? 5 : digits.findIndex((d) => !d.trim()), 5);function setAt(index: number, digit: string) {const next = digits.map((d, i) => (i === index ? digit : d)).join("").trimEnd();@@ -77,6 +79,7 @@ export function CodeInput({onChange={(e) => handleChange(i, e.target.value)}onKeyDown={(e) => handleKeyDown(i, e)}onFocus={(e) => e.target.select()}+ tabIndex={i === activeIndex ? 0 : -1}inputMode="numeric"autoComplete={i === 0 ? "one-time-code" : "off"}maxLength={6}diff --git a/src/screens/Library.tsx b/src/screens/Library.tsxindex 65aa39d..4c0d343 100644--- a/src/screens/Library.tsx+++ b/src/screens/Library.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { api, messageOf } from "../lib/ipc";const NAMES: Record<string, string> = {@@ -79,16 +79,42 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {// Everything else is infrastructure — real, but not something anyone navigates to.const rest = services.filter((k) => !PRIMARY.includes(k));- const item = (key: string) => (- <button- key={key}- className="nav-item"- aria-current={selected === key}- onClick={() => setSelected(key)}- >- <span>{NAMES[key] ?? key}</span>- </button>- );+ // Native sidebars move with the arrow keys and occupy a single tab stop. Without this a+ // keyboard user has to Tab through every row to reach the content.+ const rows = useRef<(HTMLButtonElement | null)[]>([]);+ const order = showAll ? [...primary, ...rest] : primary;++ function onKeyDown(e: React.KeyboardEvent, index: number) {+ const move = (to: number) => {+ e.preventDefault();+ const clamped = Math.max(0, Math.min(to, order.length - 1));+ rows.current[clamped]?.focus();+ setSelected(order[clamped]);+ };+ if (e.key === "ArrowDown") move(index + 1);+ else if (e.key === "ArrowUp") move(index - 1);+ else if (e.key === "Home") move(0);+ else if (e.key === "End") move(order.length - 1);+ }++ const item = (key: string) => {+ const index = order.indexOf(key);+ return (+ <button+ key={key}+ ref={(el) => {+ rows.current[index] = el;+ }}+ className="nav-item"+ aria-current={selected === key}+ tabIndex={selected === key ? 0 : -1}+ onKeyDown={(e) => onKeyDown(e, index)}+ onClick={() => setSelected(key)}+ >+ <span>{NAMES[key] ?? key}</span>+ </button>+ );+ };return (<div className="library enter-library">