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: say when Apple waits on new iCloud terms; diagnostics a person can turn on
Yashwanth Kamireddi92b2516941d5
diff --git a/.uiverify/icloud-terms.mjs b/.uiverify/icloud-terms.mjsnew file mode 100644index 0000000..9e2868a--- /dev/null+++ b/.uiverify/icloud-terms.mjs@@ -0,0 +1,67 @@+// Issue #5: Apple has new iCloud terms the person has not agreed to, and opens only part of a+// web session until they do — every service fails, Calendar and Contacts too. One calm page+// says what to do at icloud.com, with Try Again; agreed, it goes and the library is back.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const BASE = 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 open(setup) {+ const ctx = await b.newContext({ viewport: { width: 1180, height: 800 } });+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+ await ctx.addInitScript(setup);+ const page = await ctx.newPage();+ await page.goto(BASE, { waitUntil: "networkidle" });+ await page.waitForTimeout(400);+ return { ctx, page };+}++{+ const { ctx, page } = await open(() => { window.__termsNeeded = true; window.__termsAfterRefresh = true; });+ const heading = page.getByRole("heading", { name: "Agree to the new iCloud terms" });+ ok(await heading.isVisible(), "new terms waiting: the page says to agree to them");+ ok((await page.locator(".icloud-com-waiting").innerText()).includes("icloud.com"), "and where");+ await page.locator(".nav-item", { hasText: "Calendar" }).click();+ await page.waitForTimeout(200);+ ok(await heading.isVisible(), "Calendar too: every service waits on it");+ await page.getByRole("button", { name: "Try Again" }).click();+ await page.waitForTimeout(250);+ ok((await page.evaluate(() => window.__accountRefreshes)) === 1, "Try Again asks Apple for the account again");+ ok(await heading.isVisible(), "not agreed yet: the page stays");++ // Agreed at icloud.com, then Try Again.+ await page.evaluate(() => { window.__termsAfterRefresh = false; });+ await page.getByRole("button", { name: "Try Again" }).click();+ await page.waitForTimeout(300);+ ok(!(await heading.isVisible()), "agreed: the page goes");+ ok(await page.locator(".cx").first().isVisible(), "and the calendar is there");+ await ctx.close();+}++{+ const { ctx, page } = await open(() => { window.__termsNeeded = true; });+ await openScreen(page, "Notes").catch(() => {});+ // Agreed meanwhile; the next pass finds it and says so.+ await page.evaluate(() => { window.__termsNeeded = false; window.__emit?.("quince://synced", { services: [], asOf: null, tookMs: 0, changed: [] }); });+ await page.waitForTimeout(300);+ ok(!(await page.getByRole("heading", { name: "Agree to the new iCloud terms" }).isVisible()), "agreed elsewhere: the next pass clears it by itself");+ await ctx.close();+}++{+ const { ctx, page } = await open(() => { window.__repairNeeded = true; });+ ok(await page.getByRole("heading", { name: "Finish setting up iCloud" }).isVisible(), "an account Apple wants finished says so");+ await ctx.close();+}++{+ const { ctx, page } = await open(() => {});+ ok(!(await page.locator(".icloud-com-waiting").count()), "nothing waiting: nothing shown");+ await ctx.close();+}++await b.close();+if (failures) { console.log(`${failures} failed`); process.exit(1); }+console.log("all passed");diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex fd4e880..79e792a 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -1057,7 +1057,12 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note}case "alerts_shown": return window.__alertsShown ?? true;case "diagnostics_save": (window.__diagnostics = (window.__diagnostics ?? 0) + 1); return "/home/user/Downloads/Skykeep diagnostics 2026-10-18 20.00.txt";- case "account_info": return { name: "Asha Rao", email: "[email protected]", photoContact: window.__mePhoto ?? null, webAccessAllowed: window.__webAccess ?? true, dataProtection: false };+ case "account_info": return { name: "Asha Rao", email: "[email protected]", photoContact: window.__mePhoto ?? null, webAccessAllowed: window.__webAccess ?? true, dataProtection: false, termsUpdateNeeded: Boolean(window.__termsNeeded), repairNeeded: Boolean(window.__repairNeeded) };+ // Asking Apple for the account again: counted, and answering what the test set next.+ case "account_refresh":+ window.__accountRefreshes = (window.__accountRefreshes ?? 0) + 1;+ if (window.__termsAfterRefresh !== undefined) window.__termsNeeded = window.__termsAfterRefresh;+ return { name: "Asha Rao", email: "[email protected]", photoContact: null, webAccessAllowed: true, dataProtection: false, termsUpdateNeeded: Boolean(window.__termsNeeded), repairNeeded: Boolean(window.__repairNeeded) };// Advanced Data Protection's approval: nothing waits on one unless a test says so// (`window.__dataAccess`); asking again counts, and answers what the test set next.case "data_access_status": return window.__dataAccess ?? { state: "open", services: [], problem: null };diff --git a/README.md b/README.mdindex 40c857f..7743b0a 100644--- a/README.md+++ b/README.md@@ -354,6 +354,21 @@ Personal Apple Accounts. Managed Apple Accounts from a school or workplace aren'Any time. **Settings → Export Everything** saves your notes as Markdown, events as iCalendar, contacts as vCard, and your files as they are.</details>+<details>+<summary><b>Something fails only on my account. How do I send a log?</b></summary>++Quit Skykeep (from the tray too), then start it from a terminal with diagnostics turned on:++```sh+SKYKEEP_LOG=1 skykeep+# Flatpak: flatpak run --env=SKYKEEP_LOG=1 io.github.yashwanthkamireddi.Skykeep+```++On Windows, run `$env:SKYKEEP_LOG=1` in PowerShell, then start `skykeep.exe` from that same window.++Skykeep prints where it writes `diagnostics.log`, in its data folder (on Linux, usually `~/.local/share/io.github.yashwanthkamireddi.Skykeep/`). Sign in or sync, then attach the file to your issue. It lists which iCloud addresses Skykeep asked, Apple's answer codes, and the names of the cookies that were sent. It never contains cookie values, tokens, passwords, your name, your email or anything from your library, and Skykeep never uploads it. Start Skykeep normally again to turn diagnostics off.+</details>+## RoadmapWhat I'd like to add next:diff --git a/check.sh b/check.shindex 0396c0c..5627b1a 100755--- a/check.sh+++ b/check.sh@@ -170,6 +170,7 @@ step "sign-in keyring" node .uiverify/signin-keyring.mjsstep "lapse reason" node .uiverify/lapse-reason.mjsstep "device approval" node .uiverify/device-approval.mjsstep "code only when asked" node .uiverify/code-lapse.mjs+step "new iCloud terms" node .uiverify/icloud-terms.mjsstep "webkit: approval" env ENGINE=webkit node .uiverify/device-approval.mjsstep "calendar undo" node .uiverify/calendar-undo.mjsdiff --git a/crates/quince-auth/src/diag.rs b/crates/quince-auth/src/diag.rsnew file mode 100644index 0000000..c293e8f--- /dev/null+++ b/crates/quince-auth/src/diag.rs@@ -0,0 +1,298 @@+//! Diagnostics the person turns on, for a problem that only shows on their account.+//!+//! Off unless they ask (the app turns it on with `SKYKEEP_LOG=1`; see its `diagnostics`). On,+//! it says what Skykeep asked Apple and what came back — and nothing of the person's:+//!+//! * where: the host, and the path with every id-like part (record ids, GUIDs, numbers) put+//! as `…`; never the query, which carries the account's id and this install's;+//! * the status, and Apple's own error codes and reasons, each cut short, with anything that+//! could be an address or an id taken out;+//! * which cookies went with a request, and which an answer set — by name, with their domain,+//! path and whether they last — and whether the jar kept each one, and if not why. Never a+//! value: those are the session itself.+//!+//! No password, token, name, address, note or record is ever written. The log stays on this+//! computer; Skykeep sends nothing anywhere.++use reqwest::header::HeaderValue;+use reqwest_cookie_store::CookieStoreMutex;+use std::sync::{Arc, OnceLock};++/// Where a line goes. Set once by the app when the person turned diagnostics on.+pub type Sink = fn(&str);+static SINK: OnceLock<Sink> = OnceLock::new();++/// Turn diagnostics on. Once per run; later calls change nothing.+pub fn set_sink(sink: Sink) {+ let _ = SINK.set(sink);+}++/// Whether diagnostics are on.+#[must_use]+pub fn on() -> bool {+ SINK.get().is_some()+}++/// Tell one line, when diagnostics are on.+pub fn note(line: &str) {+ if let Some(sink) = SINK.get() {+ sink(line);+ }+}++/// A part of a path that names something of the person's rather than an endpoint: long, or+/// mostly digits, or shaped like an id.+fn id_like(part: &str) -> bool {+ let digits = part.chars().filter(char::is_ascii_digit).count();+ part.len() > 24+ || (digits >= 4 && digits * 2 >= part.len())+ || part.contains("::")+ || part.contains('@')+ || part.contains('%')+}++/// Host and path, the person's parts put as `…`, no query.+#[must_use]+pub fn place(url: &reqwest::Url) -> String {+ let path: Vec<&str> = url+ .path()+ .split('/')+ .map(|p| if id_like(p) { "…" } else { p })+ .collect();+ format!("{}{}", url.host_str().unwrap_or("?"), path.join("/"))+}++/// Apple's error codes and reasons out of an answer, safe to write: only the fields Apple uses+/// for them, each cut to 100 characters, and nothing that could be an address or an id.+#[must_use]+pub fn codes(body: &str) -> String {+ let Ok(v) = serde_json::from_str::<serde_json::Value>(body) else {+ return if body.trim().is_empty() {+ "(no body)".into()+ } else {+ "(not JSON)".into()+ };+ };+ let mut found = Vec::new();+ collect(&v, &mut found, 0);+ if found.is_empty() {+ "(no error codes)".into()+ } else {+ found.join(", ")+ }+}++const CODE_KEYS: [&str; 9] = [+ "serverErrorCode",+ "errorCode",+ "errorReason",+ "reason",+ "error",+ "code",+ "message",+ "status",+ "success",+];++fn collect(v: &serde_json::Value, out: &mut Vec<String>, depth: usize) {+ if depth > 4 || out.len() >= 12 {+ return;+ }+ match v {+ serde_json::Value::Object(map) => {+ for key in CODE_KEYS {+ if let Some(x) = map.get(key) {+ let text = match x {+ serde_json::Value::String(s) => clean(s),+ serde_json::Value::Number(n) => n.to_string(),+ serde_json::Value::Bool(b) => b.to_string(),+ _ => continue,+ };+ out.push(format!("{key}={text}"));+ }+ }+ for x in map.values() {+ if x.is_object() || x.is_array() {+ collect(x, out, depth + 1);+ }+ }+ }+ serde_json::Value::Array(items) => {+ for x in items.iter().take(4) {+ collect(x, out, depth + 1);+ }+ }+ _ => {}+ }+}++/// A reason Apple gave, cut short, with any word that could be an address or an id taken out.+fn clean(s: &str) -> String {+ let words: Vec<&str> = s+ .split_whitespace()+ .map(|w| if id_like(w) { "…" } else { w })+ .collect();+ let mut text = words.join(" ");+ if text.chars().count() > 100 {+ text = text.chars().take(100).collect::<String>() + "…";+ }+ format!("{text:?}")+}++/// One answer, told: where it came from and its status.+pub fn answer(url: &reqwest::Url, status: reqwest::StatusCode) {+ if on() {+ note(&format!("← {} {}", status.as_u16(), place(url)));+ }+}++/// Facts about an account answer that explain a session that will not work, never its data.+pub fn account(what: &str, data: &serde_json::Value) {+ if !on() {+ return;+ }+ let flag = |k: &str| {+ data.get(k)+ .or_else(|| data.pointer(&format!("/dsInfo/{k}")))+ .and_then(serde_json::Value::as_bool)+ .map_or("absent".to_string(), |b| b.to_string())+ };+ let services: Vec<&str> = data+ .get("webservices")+ .and_then(serde_json::Value::as_object)+ .map(|o| o.keys().map(String::as_str).collect())+ .unwrap_or_default();+ note(&format!(+ "{what}: termsUpdateNeeded={} isRepairNeeded={} hsaChallengeRequired={} hsaTrustedBrowser={} isWebAccessAllowed={} iCDPEnabled={} services={services:?}",+ flag("termsUpdateNeeded"),+ flag("isRepairNeeded"),+ flag("hsaChallengeRequired"),+ flag("hsaTrustedBrowser"),+ flag("isWebAccessAllowed"),+ flag("iCDPEnabled"),+ ));+}++/// The client's cookie jar, telling diagnostics which cookies go out and which come back — by+/// name only — and whether the jar kept each one it was handed.+pub struct Told(pub Arc<CookieStoreMutex>);++impl reqwest::cookie::CookieStore for Told {+ fn set_cookies(&self, headers: &mut dyn Iterator<Item = &HeaderValue>, url: &reqwest::Url) {+ if !on() {+ self.0.set_cookies(headers, url);+ return;+ }+ let headers: Vec<&HeaderValue> = headers.collect();+ let mut seen = Vec::new();+ for h in &headers {+ seen.push(describe(h, url));+ }+ note(&format!(" set by {}: {}", place(url), seen.join(" | ")));+ self.0.set_cookies(&mut headers.into_iter(), url);+ }++ fn cookies(&self, url: &reqwest::Url) -> Option<HeaderValue> {+ let sent = self.0.cookies(url);+ if on() {+ let names: Vec<String> = sent+ .as_ref()+ .and_then(|h| h.to_str().ok())+ .map(|s| {+ s.split("; ")+ .filter_map(|c| c.split('=').next())+ .map(str::to_string)+ .collect()+ })+ .unwrap_or_default();+ note(&format!("→ {} cookies {names:?}", place(url)));+ }+ sent+ }+}++/// One Set-Cookie, by name and attributes, and whether the jar would keep it — never its value.+fn describe(h: &HeaderValue, url: &reqwest::Url) -> String {+ let Ok(text) = h.to_str() else {+ return "(not text: dropped)".into();+ };+ let Ok(raw) = cookie_store::RawCookie::parse(text.to_string()) else {+ return "(unreadable: dropped)".into();+ };+ let lasts = if raw.max_age().is_some() || raw.expires().is_some_and(|e| e.is_datetime()) {+ "lasting"+ } else {+ "session"+ };+ let kept = match cookie_store::Cookie::try_from_raw_cookie(&raw, url) {+ Ok(c) if c.is_expired() => "deleted".to_string(),+ Ok(_) if raw.value().is_empty() => "empty".to_string(),+ Ok(_) => "kept".to_string(),+ Err(e) => format!("DROPPED: {e:?}"),+ };+ format!(+ "{} domain={} path={} {lasts} {kept}",+ raw.name(),+ raw.domain().unwrap_or("(host)"),+ raw.path().unwrap_or("(default)"),+ )+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn places_never_carry_the_query_or_an_id() {+ let u = reqwest::Url::parse(+ "https://p45-ckdatabasews.icloud.com/database/1/com.apple.notes/production/private/records/lookup?dsid=12345678901&clientId=auth-abc",+ )+ .unwrap();+ assert_eq!(+ place(&u),+ "p45-ckdatabasews.icloud.com/database/1/com.apple.notes/production/private/records/lookup"+ );+ let u = reqwest::Url::parse(+ "https://p45-calendarws.icloud.com/ca/events/home/4186A3B2-77C1-4E0A-9F00-5D0C1B2E3F44",+ )+ .unwrap();+ assert_eq!(place(&u), "p45-calendarws.icloud.com/ca/events/home/…");+ }++ #[test]+ fn only_apples_codes_are_written_never_its_data() {+ let body = r#"{ "uuid" : "f3321aa0-1111-2222-3333-444455556666", "serverErrorCode" : "AUTHENTICATION_FAILED", "reason" : "no auth method found" }"#;+ assert_eq!(+ codes(body),+ r#"serverErrorCode="AUTHENTICATION_FAILED", reason="no auth method found""#+ );+ assert_eq!(+ codes(r#"{"reason":"Missing X-APPLE-WEBAUTH-TOKEN cookie","error":1}"#),+ r#"reason="Missing X-APPLE-WEBAUTH-TOKEN cookie", error=1"#+ );+ // An address, an id, a name in a record: none of it.+ let personal = r#"{"reason":"no account for [email protected]","records":[{"recordName":"ABCDEF123456","fields":{"title":{"value":"Mum's birthday"}}}]}"#;+ let said = codes(personal);+ assert!(+ !said.contains("example.com") && !said.contains("ABCDEF") && !said.contains("birthday"),+ "{said}"+ );+ assert_eq!(codes("<html>Bad Gateway</html>"), "(not JSON)");+ }++ #[test]+ fn a_cookie_is_described_by_name_never_by_value() {+ let u = reqwest::Url::parse("https://setup.icloud.com/setup/ws/1/accountLogin").unwrap();+ let h = HeaderValue::from_static(+ "X-APPLE-WEBAUTH-TOKEN=\"v=2:t=SECRETSECRET\"; Path=/; Domain=.icloud.com; Secure; HttpOnly",+ );+ let said = describe(&h, &u);+ assert!(+ said.starts_with("X-APPLE-WEBAUTH-TOKEN domain=icloud.com path=/ session kept"),+ "{said}"+ );+ assert!(!said.contains("SECRET"));+ let wrong = HeaderValue::from_static("X=1; Domain=apple.com; Path=/");+ assert!(describe(&wrong, &u).contains("DROPPED: DomainMismatch"));+ }+}diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex 2d4c91c..426beca 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -21,6 +21,7 @@ macro_rules! quiet {};}+pub mod diag;pub mod pcs;pub mod releases;mod sealed;@@ -582,7 +583,9 @@ impl Client {// long as bytes arrive); idle connections are let go of before they can go stale; and// keep-alives notice a dead one.let http = apple_only()- .cookie_provider(Arc::clone(&jar))+ // The jar itself, telling diagnostics (when the person turned them on) which+ // cookies go out and come back, by name.+ .cookie_provider(Arc::new(diag::Told(Arc::clone(&jar)))).user_agent(UA).default_headers(defaults).connect_timeout(std::time::Duration::from_secs(15))@@ -665,6 +668,7 @@ impl Client {// ---- persistence ----------------------------------------------------------------fn capture(&mut self, response: &Response) {+ diag::answer(response.url(), response.status());for (header, field) in CAPTURED_HEADERS {if let Some(v) = response.headers()@@ -934,7 +938,9 @@ impl Client {return Err(transient(status).unwrap_or_else(|| Error::Protocol(format!("validate returned {status}"))));}- Ok(serde_json::from_str(&body).unwrap_or(Value::Null))+ let data = serde_json::from_str(&body).unwrap_or(Value::Null);+ diag::account("validate", &data);+ Ok(data)}/// Keep the session warm.@@ -1422,6 +1428,7 @@ impl Client {}));}let data: Value = serde_json::from_str(&text)?;+ diag::account("accountLogin", &data);// New iCloud terms not yet accepted: Apple answers 200 but opens the session only// part-way, without the web cookies every service needs (rclone/rclone#9919), so every// sync failed afterwards with nothing to say why. Only icloud.com or a device of the@@ -1478,6 +1485,34 @@ impl Client {{self.session.data_protection = Some(on);}+ // Read from every answer that carries them, so agreeing at icloud.com clears them at+ // the next `accountLogin` — the heartbeat's, or Try Again's.+ if let Some(needed) = data.get("termsUpdateNeeded").and_then(Value::as_bool) {+ if needed {+ quiet!("quince: Apple has iCloud terms waiting to be agreed to");+ }+ self.session.terms_update_needed = needed;+ }+ if let Some(needed) = data.get("isRepairNeeded").and_then(Value::as_bool) {+ self.session.repair_needed = needed;+ }+ }++ /// Ask Apple for the account again — after the person agreed to new iCloud terms at+ /// icloud.com, say: a fresh `accountLogin` opens the whole web session they were waiting on.+ pub async fn refresh_account(&mut self) -> Result<()> {+ let data = self.account_login().await?;+ self.absorb(&data);+ self.keep();+ Ok(())+ }++ /// Apple is keeping this session from the account's data until something is done at+ /// icloud.com: new terms agreed to, or the account finished. Nothing else can be read+ /// meanwhile, so nothing else is asked.+ #[must_use]+ pub fn waits_on_icloud_com(&self) -> bool {+ self.session.terms_update_needed || self.session.repair_needed}/// Query parameters every iCloud service endpoint expects alongside the session cookies.diff --git a/crates/quince-auth/src/pcs.rs b/crates/quince-auth/src/pcs.rsindex b91699f..e15b52e 100644--- a/crates/quince-auth/src/pcs.rs+++ b/crates/quince-auth/src/pcs.rs@@ -197,7 +197,9 @@ impl Client {/// holds no key for them, or the one it held ran out. Asks Apple nothing.#[must_use]pub fn data_access_missing(&self) -> Vec<&'static str> {- if self.session.web_access_allowed == Some(false) {+ // Web access off, or terms waiting at icloud.com: no key is released either way (Apple+ // answers requestPCS "Missing X-APPLE-WEBAUTH-TOKEN cookie"), so none is asked for.+ if self.session.web_access_allowed == Some(false) || self.waits_on_icloud_com() {return Vec::new();}if selfdiff --git a/crates/quince-auth/src/session.rs b/crates/quince-auth/src/session.rsindex e06f5f4..5bb9aaf 100644--- a/crates/quince-auth/src/session.rs+++ b/crates/quince-auth/src/session.rs@@ -117,6 +117,15 @@ pub struct Session {/// whose key cookie is not known by name; the rest are read from the cookies themselves.#[serde(default)]pub pcs_until: std::collections::BTreeMap<String, u64>,+ /// Apple has new iCloud terms the person has not agreed to (`termsUpdateNeeded`). Until+ /// they do, `accountLogin` opens only part of a web session — no `X-APPLE-WEBAUTH-TOKEN`+ /// — and every service, Calendar and Contacts too, answers "Missing X-APPLE-WEBAUTH-TOKEN+ /// cookie" or "no auth method found" (issue #5; rclone#9658).+ #[serde(default)]+ pub terms_update_needed: bool,+ /// Apple wants the account finished at icloud.com first (`isRepairNeeded`).+ #[serde(default)]+ pub repair_needed: bool,/// Failed sign-ins in a row. Drives the local backoff.#[serde(default)]diff --git a/crates/quince-auth/tests/apple_cookies.rs b/crates/quince-auth/tests/apple_cookies.rsnew file mode 100644index 0000000..3cd45cf--- /dev/null+++ b/crates/quince-auth/tests/apple_cookies.rs@@ -0,0 +1,109 @@+//! Apple's own Set-Cookie headers, with every attribute it sends, through the same jar the+//! client uses (issue #5: every service answered "Missing X-APPLE-WEBAUTH-TOKEN cookie" /+//! "no auth method found"). Each cookie `accountLogin` sets on setup.icloud.com must be kept and+//! sent to every service host Apple's map names, and to nothing outside icloud.com.++use reqwest::cookie::CookieStore as _;+use reqwest::header::HeaderValue;+use reqwest_cookie_store::CookieStoreMutex;++fn url(s: &str) -> reqwest::Url {+ reqwest::Url::parse(s).unwrap()+}++/// What `accountLogin` sets, shaped as Apple sends it: quoted values with `=` and `:`, both+/// `Expires` date forms browsers see from Apple, `Max-Age`, `SameSite=None`, newer attributes+/// (`Partitioned`, `Priority`), a domain with and without its leading dot, an empty "delete"+/// tombstone, and a token of the size Apple's are.+fn account_login_cookies() -> Vec<String> {+ let token = format!("\"v=2:t={}\"", "A".repeat(3500));+ vec![+ format!("X-APPLE-WEBAUTH-TOKEN={token}; Path=/; Domain=.icloud.com; Secure; HttpOnly"),+ "X-APPLE-WEBAUTH-USER=\"v=1:s=0:d=12345678901\"; Expires=Sat, 05-Dec-2026 10:00:00 GMT; Path=/; Domain=.icloud.com; Secure; HttpOnly".into(),+ "X-APPLE-DS-WEB-SESSION-TOKEN=\"AQEAAAAAAAAAAA==\"; Path=/; Domain=.icloud.com; Secure; HttpOnly; SameSite=None".into(),+ "X-APPLE-WEBAUTH-VALIDATE=\"v=1:t=AQAAAAAAAAAA\"; Path=/; Domain=icloud.com; Secure".into(),+ "X-APPLE-WEBAUTH-HSA-TRUST=\"8a7c0e3f2b1d\"; Max-Age=2592000; Expires=Thu, 03 Dec 2026 10:00:00 GMT; Path=/; Domain=.icloud.com; Secure; HttpOnly; Priority=High".into(),+ "X-APPLE-UNIQUE-CLIENT-ID=\"Ab12\"; Path=/; Domain=.icloud.com; Secure; Partitioned; SameSite=None".into(),+ "X-APPLE-WEBAUTH-HSA-LOGIN=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/; Domain=.icloud.com; Secure; HttpOnly".into(),+ ]+}++const KEPT: [&str; 6] = [+ "X-APPLE-WEBAUTH-TOKEN",+ "X-APPLE-WEBAUTH-USER",+ "X-APPLE-DS-WEB-SESSION-TOKEN",+ "X-APPLE-WEBAUTH-VALIDATE",+ "X-APPLE-WEBAUTH-HSA-TRUST",+ "X-APPLE-UNIQUE-CLIENT-ID",+];++fn names_sent(jar: &CookieStoreMutex, to: &str) -> Vec<String> {+ jar.cookies(&url(to))+ .map(|h| {+ h.to_str()+ .unwrap()+ .split("; ")+ .filter_map(|c| c.split('=').next())+ .map(str::to_string)+ .collect()+ })+ .unwrap_or_default()+}++#[test]+fn every_account_login_cookie_reaches_every_service_host() {+ let jar = CookieStoreMutex::default();+ let headers: Vec<HeaderValue> = account_login_cookies()+ .iter()+ .map(|c| HeaderValue::from_str(c).unwrap())+ .collect();+ jar.set_cookies(+ &mut headers.iter(),+ &url("https://setup.icloud.com/setup/ws/1/accountLogin?clientBuildNumber=1"),+ );+ for host in [+ "https://p123-contactsws.icloud.com/co/startup",+ "https://p45-ckdatabasews.icloud.com/database/1/com.apple.notes/production/private/changes/zone",+ "https://p45-calendarws.icloud.com/ca/startup",+ "https://p45-drivews.icloud.com/retrieveItemDetailsInFolders",+ "https://setup.icloud.com/setup/ws/1/validate",+ ] {+ let sent = names_sent(&jar, host);+ for name in KEPT {+ assert!(sent.iter().any(|n| n == name), "{name} not sent to {host}: {sent:?}");+ }+ assert!(+ !sent.iter().any(|n| n == "X-APPLE-WEBAUTH-HSA-LOGIN"),+ "a deleted cookie is not sent"+ );+ }+ assert!(+ names_sent(&jar, "https://example.com/").is_empty(),+ "never outside icloud.com"+ );+ assert!(+ names_sent(&jar, "http://p123-contactsws.icloud.com/co/startup").is_empty(),+ "never over plain HTTP"+ );+}++/// Several cookies in one header line (folded by a proxy) are not lost silently: each line Apple+/// sends is one cookie, and that is what this keeps.+#[test]+fn one_set_cookie_header_per_cookie_is_what_is_kept() {+ let jar = CookieStoreMutex::default();+ let headers = [+ HeaderValue::from_static(+ "X-APPLE-WEBAUTH-USER=\"v=1:s=0\"; Path=/; Domain=.icloud.com; Secure",+ ),+ HeaderValue::from_static(+ "X-APPLE-WEBAUTH-TOKEN=\"v=2:t=x\"; Path=/; Domain=.icloud.com; Secure",+ ),+ ];+ jar.set_cookies(+ &mut headers.iter(),+ &url("https://setup.icloud.com/setup/ws/1/accountLogin"),+ );+ let sent = names_sent(&jar, "https://p1-contactsws.icloud.com/co/startup");+ assert_eq!(sent.len(), 2, "{sent:?}");+}diff --git a/crates/quince-auth/tests/icloud_terms.rs b/crates/quince-auth/tests/icloud_terms.rsnew file mode 100644index 0000000..25c5467--- /dev/null+++ b/crates/quince-auth/tests/icloud_terms.rs@@ -0,0 +1,168 @@+//! Issue #5: sign-in works, then every service — Calendar and Contacts too — answers "Missing+//! X-APPLE-WEBAUTH-TOKEN cookie" or "no auth method found". With new iCloud terms waiting,+//! Apple's `accountLogin` says `termsUpdateNeeded` and opens only part of a web session+//! (rclone#9658). Said as that, nothing more asked of Apple meanwhile, and cleared by the next+//! `accountLogin` once the person has agreed at icloud.com.+//!+//! And diagnostics: on, they name each request's place, status and cookies — never a value.++use quince_auth::pcs::DataAccess;+use quince_auth::{Client, Endpoints, Store};+use serde_json::json;+use std::sync::Mutex;+use wiremock::matchers::{method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++fn b64(bytes: &[u8]) -> String {+ use base64::{engine::general_purpose::STANDARD as E, Engine};+ E.encode(bytes)+}++static LINES: Mutex<Vec<String>> = Mutex::new(Vec::new());+fn sink(line: &str) {+ LINES.lock().unwrap().push(line.to_string());+}++async fn mount_sign_in(server: &MockServer) {+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/signin/init"))+ .respond_with(+ ResponseTemplate::new(200)+ .append_header("set-cookie", "aasp=SECRET-AASP; Path=/; Secure; HttpOnly")+ .set_body_json(json!({+ "salt": b64(&[0x77; 16]), "b": b64(&[0x5e; 256]), "c": "challenge-c",+ "iteration": 20173, "protocol": "s2k",+ })),+ )+ .mount(server)+ .await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/signin/complete"))+ .respond_with(+ ResponseTemplate::new(200)+ .insert_header("X-Apple-Session-Token", "session-token-abc")+ .set_body_json(json!({})),+ )+ .mount(server)+ .await;+}++fn login(terms: bool) -> ResponseTemplate {+ let mut r = ResponseTemplate::new(200)+ .append_header(+ "set-cookie",+ "X-APPLE-WEBAUTH-USER=\"v=1:s=0:d=SECRET-USER\"; Path=/; Max-Age=2592000",+ )+ .append_header(+ "set-cookie",+ "X-APPLE-WEBAUTH-HSA-TRUST=\"SECRET-TRUST\"; Path=/; Max-Age=2592000",+ );+ if !terms {+ r = r.append_header(+ "set-cookie",+ "X-APPLE-WEBAUTH-TOKEN=\"v=2:t=SECRET-TOKEN\"; Path=/",+ );+ }+ r.set_body_json(json!({+ "dsInfo": { "dsid": "1234567890", "isWebAccessAllowed": true, "fullName": "Asha Rao",+ "primaryEmail": "[email protected]" },+ "iCDPEnabled": true,+ "termsUpdateNeeded": terms,+ "webservices": {+ "calendar": { "url": "https://p00-calendarws.test.invalid:443" },+ "ckdatabasews": { "url": "https://p00-ckdatabasews.test.invalid:443", "pcsRequired": true },+ "drivews": { "url": "https://p00-drivews.test.invalid:443", "pcsRequired": true }+ }+ }))+}++fn client_for(server: &MockServer, dir: &std::path::Path) -> Client {+ Client::with(dir, Endpoints::at(&server.uri()), Store::file(dir).unwrap()).unwrap()+}++#[tokio::test]+async fn new_terms_are_said_waited_on_and_cleared_once_agreed() {+ quince_auth::diag::set_sink(sink);+ let server = MockServer::start().await;+ mount_sign_in(&server).await;+ Mock::given(method("POST"))+ .and(path("/setup/ws/1/accountLogin"))+ .respond_with(login(true))+ .up_to_n_times(1)+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/setup/ws/1/accountLogin"))+ .respond_with(login(false))+ .mount(&server)+ .await;++ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();+ assert!(client.session().terms_update_needed, "Apple's flag is kept");+ assert!(client.waits_on_icloud_com());+ // Advanced Data Protection's keys are not asked for meanwhile: Apple would refuse them.+ assert!(client.data_access_missing().is_empty());+ assert_eq!(client.data_access(true).await.unwrap(), DataAccess::Open);+ let reqs = server.received_requests().await.unwrap();+ assert!(+ !reqs+ .iter()+ .any(|r| r.url.path().contains("requestWebAccessState")),+ "nothing asked of Apple about keys while the terms wait"+ );++ // Agreed at icloud.com, then Try Again.+ client.refresh_account().await.unwrap();+ assert!(+ !client.session().terms_update_needed,+ "cleared by the next accountLogin"+ );+ assert!(!client.waits_on_icloud_com());+ assert_eq!(+ client.data_access_missing(),+ ["notes", "reminders", "photos", "drive"]+ );+ // And remembered across a restart either way.+ drop(client);+ assert!(+ !client_for(&server, dir.path())+ .session()+ .terms_update_needed+ );++ // Diagnostics: places, statuses, flags and cookie names — no value, token, name or address.+ let lines = LINES.lock().unwrap().join("\n");+ assert!(lines.contains("termsUpdateNeeded=true"), "{lines}");+ assert!(lines.contains("termsUpdateNeeded=false"));+ assert!(+ lines.contains("← 200 127.0.0.1/setup/ws/1/accountLogin"),+ "{lines}"+ );+ assert!(+ lines.contains("X-APPLE-WEBAUTH-TOKEN domain=(host) path=/ session kept"),+ "{lines}"+ );+ assert!(+ lines.contains("→ 127.0.0.1/setup/ws/1/accountLogin cookies"),+ "{lines}"+ );+ for secret in [+ "SECRET",+ "hunter2",+ "session-token-abc",+ "Asha",+ "[email protected]",+ "1234567890",+ "[email protected]",+ ] {+ assert!(+ !lines.contains(secret),+ "{secret} written to diagnostics:\n{lines}"+ );+ }+}diff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rsindex b689f72..0596e4e 100644--- a/crates/quince-icloud/src/calendar.rs+++ b/crates/quince-icloud/src/calendar.rs@@ -299,7 +299,8 @@ fn now_seconds() -> i64 {/// {"ChangeSet":…}` — which says nothing to a person about what happened or what to do. The/// sentence says that; the path, status and body go to the log for whoever has to look.fn refusal(path: &str, status: reqwest::StatusCode, body: &str) -> Error {- let _ = (path, body);+ let _ = path;+ crate::told("calendar", status, body);quiet!("calendar: a request was refused ({status})");match status.as_u16() {409 | 412 => Error::Conflict,diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rsindex bf82d67..b565822 100644--- a/crates/quince-icloud/src/contacts.rs+++ b/crates/quince-icloud/src/contacts.rs@@ -820,6 +820,7 @@ async fn write(return Err(Error::Conflict);}if !status.is_success() {+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("contacts returned {status}: {}",text.chars().take(200).collect::<String>()@@ -1214,6 +1215,7 @@ async fn write_list(return Err(Error::Conflict);}if !status.is_success() {+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("contacts returned {status}: {}",text.chars().take(200).collect::<String>()@@ -1348,6 +1350,7 @@ async fn co_text(return Err(Error::Conflict);}if !status.is_success() {+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("contacts returned {status}: {}",text.chars().take(200).collect::<String>()@@ -1891,6 +1894,7 @@ async fn startup(return Err(Error::ReauthRequired);}if !status.is_success() {+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("/co/startup returned {status}: {}",text.chars().take(160).collect::<String>()diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rsindex 02217ab..6f4ad31 100644--- a/crates/quince-icloud/src/lib.rs+++ b/crates/quince-icloud/src/lib.rs@@ -100,8 +100,28 @@ pub fn locked_by_data_protection(body: &str) -> bool {|| (lower.contains("access_denied") && lower.contains("private db access disabled"))}+/// Where Apple's refusals are told when the person has turned diagnostics on (see the app's+/// `diagnostics`): what was asked (`context`), the status, and Apple's answer — which the sink+/// boils down to its error codes before anything is written. Unset, nothing is told.+pub type DiagnosticsSink = fn(context: &str, status: u16, body: &str);+static DIAGNOSTICS: std::sync::OnceLock<DiagnosticsSink> = std::sync::OnceLock::new();++/// Turn diagnostics on for this crate's requests. Once per run; later calls change nothing.+pub fn set_diagnostics(sink: DiagnosticsSink) {+ let _ = DIAGNOSTICS.set(sink);+}++pub(crate) fn told(context: &str, status: reqwest::StatusCode, body: &str) {+ if let Some(sink) = DIAGNOSTICS.get() {+ sink(context, status.as_u16(), body);+ }+}+/// [`Error::NeedsDeviceApproval`] for an answer [`locked_by_data_protection`] recognises.+/// Every refusal passes through here on its way to an error, so it is also where one is told+/// to diagnostics.pub(crate) fn approval_needed(status: reqwest::StatusCode, body: &str) -> Result<()> {+ told("refused", status, body);if locked_by_data_protection(body) {quiet!("icloud: waiting for Advanced Data Protection approval ({status})");return Err(Error::NeedsDeviceApproval);diff --git a/src-tauri/src/diagnostics.rs b/src-tauri/src/diagnostics.rsnew file mode 100644index 0000000..3da5a7f--- /dev/null+++ b/src-tauri/src/diagnostics.rs@@ -0,0 +1,117 @@+//! Diagnostics, for a problem that only shows on one person's account — in a release build too,+//! and only when they turn it on: start Skykeep with `SKYKEEP_LOG=1`.+//!+//! It writes `diagnostics.log` in Skykeep's data folder: each request's host and path (ids put+//! as `…`, never the query), each answer's status and Apple's error codes, which cookies went+//! and came back by name, whether the jar kept each, and the account flags that explain a+//! session that will not work (new terms waiting, web access off). Never a cookie's value, a+//! token, a password, a name, an address or anything from the library — see+//! `quince_auth::diag`, which every line passes through. Nothing is sent anywhere: the person+//! reads it, and attaches it to an issue if they choose.++use std::io::Write;+use std::path::{Path, PathBuf};+use std::sync::{Mutex, OnceLock};++/// The log's name in the data folder.+pub const FILE_NAME: &str = "diagnostics.log";++/// Past this, the log starts over: a run left on for days never fills the disk.+const MOST_BYTES: u64 = 4 * 1024 * 1024;++static LOG: OnceLock<Mutex<Log>> = OnceLock::new();++struct Log {+ path: PathBuf,+ file: Option<std::fs::File>,+}++/// Whether the person asked for diagnostics this run.+fn asked() -> bool {+ std::env::var("SKYKEEP_LOG").is_ok_and(|v| {+ let v = v.trim().to_ascii_lowercase();+ v == "1" || v == "true" || v == "yes" || v == "on"+ })+}++/// Turn diagnostics on for this run, when the person asked, writing into `dir`.+pub fn start(dir: &Path) {+ if !asked() {+ return;+ }+ let path = dir.join(FILE_NAME);+ if LOG+ .set(Mutex::new(Log {+ path: path.clone(),+ file: open(&path),+ }))+ .is_err()+ {+ return;+ }+ quince_auth::diag::set_sink(line);+ quince_icloud::set_diagnostics(refused);+ line(&format!(+ "diagnostics on: Skykeep {} on {} {}",+ env!("CARGO_PKG_VERSION"),+ std::env::consts::OS,+ std::env::consts::ARCH+ ));+ eprintln!("Skykeep diagnostics: {}", path.display());+}++fn open(path: &Path) -> Option<std::fs::File> {+ let mut options = std::fs::OpenOptions::new();+ options.create(true).append(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ // Readable by this user alone, like everything else in the data folder.+ options.mode(0o600);+ }+ options.open(path).ok()+}++/// Write one line, with the time.+fn line(text: &str) {+ let Some(log) = LOG.get() else { return };+ let mut log = log+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let too_big = log+ .file+ .as_ref()+ .and_then(|f| f.metadata().ok())+ .is_some_and(|m| m.len() > MOST_BYTES);+ if too_big {+ let _ = std::fs::write(&log.path, b"");+ log.file = open(&log.path);+ }+ let at = jiff::Timestamp::now()+ .round(jiff::Unit::Second)+ .unwrap_or_else(|_| jiff::Timestamp::now());+ if let Some(file) = log.file.as_mut() {+ let _ = writeln!(file, "{at} {text}");+ }+}++/// A refusal from one of the iCloud services: its status and Apple's codes, nothing more.+fn refused(context: &str, status: u16, body: &str) {+ line(&format!(+ " {context} {status}: {}",+ quince_auth::diag::codes(body)+ ));+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn it_is_off_unless_asked_for() {+ // The test runner never sets it; a build that logged unasked would write here.+ if std::env::var_os("SKYKEEP_LOG").is_none() {+ assert!(!asked());+ }+ }+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 4a94c53..6f2c2a2 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -20,6 +20,7 @@ mod contacts_cmds;mod contacts_merge;mod cpu;mod data_access;+mod diagnostics;mod drive_watch;mod export;mod grants;@@ -102,6 +103,9 @@ struct SessionFacts {email: Option<String>,web_access_allowed: Option<bool>,data_protection: Option<bool>,+ /// Apple has new iCloud terms, or wants the account finished, at icloud.com first.+ terms_update_needed: bool,+ repair_needed: bool,/// Signed in, but no keyring would keep the session: it lasts as long as Skykeep runs.unsaved: bool,}@@ -127,6 +131,8 @@ impl SessionFacts {email: s.account_email.clone().or_else(|| s.apple_id.clone()),web_access_allowed: s.web_access_allowed,data_protection: s.data_protection,+ terms_update_needed: s.terms_update_needed,+ repair_needed: s.repair_needed,unsaved: client.unsaved().is_some(),}}@@ -1361,6 +1367,12 @@ async fn keep_signed_in(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>) {}Ok(true) => {TOLD.store(false, std::sync::atomic::Ordering::Relaxed);+ // New iCloud terms waiting at icloud.com: asked again each pass, so the whole+ // session opens by itself once the person has agreed — one request every few+ // minutes, and only while they are waiting.+ if guard.waits_on_icloud_com() {+ let _ = guard.refresh_account().await;+ }// Keys that ran out while the approval still holds are attached again before the// pass needs them — never a prompt on the person's phone from here.drop(guard);@@ -2006,6 +2018,11 @@ struct AccountInfo {web_access_allowed: Option<bool>,/// Advanced Data Protection.data_protection: Option<bool>,+ /// Apple has new iCloud terms waiting to be agreed to at icloud.com; until then it opens+ /// only part of a web session and nothing can be read (issue #5).+ terms_update_needed: bool,+ /// Apple wants the account finished at icloud.com first.+ repair_needed: bool,/// The person's own card, when it has a photo: theirs to show as the account's picture,/// served like any contact's.photo_contact: Option<String>,@@ -2030,10 +2047,38 @@ async fn account_info(auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<email: s.email,web_access_allowed: s.web_access_allowed,data_protection: s.data_protection,+ terms_update_needed: s.terms_update_needed,+ repair_needed: s.repair_needed,photo_contact,})}+/// Ask Apple for the account again — the person agreed to new iCloud terms at icloud.com and+/// pressed Try Again — then read everything that was waiting on it.+#[tauri::command]+async fn account_refresh(+ app: tauri::AppHandle,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<AccountInfo> {+ let waiting = {+ let mut client = auth.client.lock().await;+ client.refresh_account().await.map_err(|e| e.to_string())?;+ *auth+ .known+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = SessionFacts::of(&client);+ client.waits_on_icloud_com()+ };+ if !waiting {+ let client = Arc::clone(&auth.client);+ let result = refresh::all(&client, &data.0).await;+ alerts::changed();+ app.emit(SYNCED, told(&result)).ok();+ }+ account_info(auth, data).await+}+/// Settings' switches, as the backend obeys them.#[derive(Serialize)]#[serde(rename_all = "camelCase")]@@ -6721,6 +6766,8 @@ fn main() {// Neither a lock nor its stand-in: never run beside another unseen.Err(why) => cannot_start(&dir, &why),}+ // Before anything reaches Apple, so a run with diagnostics on has all of it.+ diagnostics::start(&dir);let client = match Client::new(&dir) {Ok(client) => client,Err(quince_auth::Error::Io(e)) => cannot_start(&dir, &folder_problem(&e)),@@ -6882,6 +6929,7 @@ fn main() {.invoke_handler(tauri::generate_handler![data_access::data_access_status,data_access::data_access_ask,+ account_refresh,grants::pick_open,grants::pick_save,export::library_export_start,diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex a11cf35..7a326fb 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -450,6 +450,8 @@ export const api = {storageInfo: () => invoke<{ usedBytes: number; totalBytes: number }>("storage_info"),/** Who is signed in, as Apple names them. */accountInfo: () => invoke<AccountInfo>("account_info"),+ /** Ask Apple for the account again, after something was done at icloud.com. */+ accountRefresh: () => invoke<AccountInfo>("account_refresh"),/** Where an Advanced Data Protection approval stands. */dataAccess: () => invoke<DataAccess>("data_access_status"),/** Put the approval on the person's devices again, and follow it. */@@ -773,6 +775,10 @@ export type AccountInfo = {email: string | null;webAccessAllowed?: boolean | null;dataProtection?: boolean | null;+ /** Apple has new iCloud terms to agree to at icloud.com; until then nothing can be read. */+ termsUpdateNeeded?: boolean;+ /** Apple wants the account finished at icloud.com first. */+ repairNeeded?: boolean;photoContact?: string | null;};diff --git a/src/screens/Library.tsx b/src/screens/Library.tsxindex 04a4617..2e85139 100644--- a/src/screens/Library.tsx+++ b/src/screens/Library.tsx@@ -6,7 +6,7 @@ import { lazy, Suspense, useCallback, useEffect, useLayoutEffect, useRef, useStaimport { listen } from "@tauri-apps/api/event";import { invoke } from "@tauri-apps/api/core";import { PanelLeft } from "lucide-react";-import { api, DATA_ACCESS, messageOf, NEW_EVENT, OPEN_REMINDER, type DataAccess } from "../lib/ipc";+import { api, DATA_ACCESS, messageOf, NEW_EVENT, OPEN_REMINDER, SYNCED, type AccountInfo, type DataAccess } from "../lib/ipc";import { ApprovalNotice, ApprovalScreen, awaitsApproval } from "../components/DeviceApproval";import { SyncProvider, useSync } from "../lib/sync";import { AccountCard } from "../components/Account";@@ -289,9 +289,35 @@ export function Library({ onSignOut, onShown }: { onSignOut: (keep: boolean) =>return !was;});- useEffect(() => {- api.accountInfo().then((a) => setWebAccess(a?.webAccessAllowed ?? null), () => {});+ /**+ * Apple waiting on something at icloud.com — new iCloud terms to agree to, or the account to+ * finish — before it opens a whole web session: every service fails until then, Calendar and+ * Contacts too (issue #5). Read again after every pass, so it clears by itself once done.+ */+ const [atIcloud, setAtIcloud] = useState<"terms" | "repair" | null>(null);+ const takeAccount = useCallback((a: AccountInfo | null | undefined) => {+ setWebAccess(a?.webAccessAllowed ?? null);+ setAtIcloud(a?.termsUpdateNeeded ? "terms" : a?.repairNeeded ? "repair" : null);}, []);+ useEffect(() => {+ api.accountInfo().then(takeAccount, () => {});+ const off = listen(SYNCED, () => {+ api.accountInfo().then(takeAccount, () => {});+ });+ return () => {+ void off.then((f) => f());+ };+ }, [takeAccount]);+ const [checking, setChecking] = useState(false);+ const [checkError, setCheckError] = useState<string | null>(null);+ const checkAgain = () => {+ setChecking(true);+ setCheckError(null);+ api+ .accountRefresh()+ .then(takeAccount, (e) => setCheckError(messageOf(e)))+ .finally(() => setChecking(false));+ };/** Advanced Data Protection: which services wait on an approval on the person's devices. */const [access, setAccess] = useState<DataAccess | null>(null);@@ -384,7 +410,8 @@ export function Library({ onSignOut, onShown }: { onSignOut: (keep: boolean) =>const frontService = selected && selected !== "settings" ? serviceOf(selected) : null;const approval: "screen" | "notice" | null =frontService && access && awaitsApproval(access, frontService) ? (held[frontService] ? "notice" : "screen") : null;- const noScreen = Boolean(error) || (ready && (!selected || webAccess === false || approval === "screen"));+ const noScreen =+ Boolean(error) || (ready && (!selected || webAccess === false || approval === "screen" || atIcloud !== null));useEffect(() => {if (noScreen) drawn();}, [noScreen, drawn]);@@ -629,7 +656,28 @@ export function Library({ onSignOut, onShown }: { onSignOut: (keep: boolean) =>:has() across the whole content instead, WebKit checked it again on every changeanywhere inside — every tile's selection in a 20,000-photo grid. */}<main className="content" ref={content} data-screen={selected}>- {webAccess === false && selected !== "settings" ? (+ {atIcloud && webAccess !== false && selected !== "settings" ? (+ // Apple opens only part of a web session until this is done at icloud.com, and+ // every screen would fail its own way. One plain answer, with where to do it.+ <div className="web-access-off icloud-com-waiting" role="alert">+ <h1>{atIcloud === "terms" ? "Agree to the new iCloud terms" : "Finish setting up iCloud"}</h1>+ <p>+ {atIcloud === "terms"+ ? "Apple has updated the iCloud Terms and Conditions. Once you agree to them, your iCloud opens here."+ : "Apple needs one more step on your Apple Account before your iCloud opens here."}+ </p>+ <p>+ Sign in at <b>icloud.com</b> in your browser and follow what it asks+ {atIcloud === "terms" ? ", then agree to the terms" : ""}. Then click Try Again.+ </p>+ <p className="device-approval-status" role="status" aria-live="polite">+ <span>{checkError ?? (checking ? "Checking with Apple…" : "")}</span>+ </p>+ <button className="primary" onClick={checkAgain} disabled={checking}>+ Try Again+ </button>+ </div>+ ) : webAccess === false && selected !== "settings" ? (// Advanced Data Protection with web access off: every read would fail, and each// screen would say so its own way. One plain answer, with Apple's own switch.<div className="web-access-off" role="alert">