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
Advanced Data Protection: ask for each service's key on the person's devices
Yashwanth Kamireddi51a7d0b4f520
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 7bf7bc4..5b35057 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -123,7 +123,7 @@ jobs:# sign-out, and an instant write in each app.suites="csp a11y boundary signout notes-compose notes-instant reminders-add-donereminders-instant calendar-edits contacts-select drive-nav photos settings- search-everything updates"+ search-everything updates device-approval"failed=()for t in $suites; doif node ".uiverify/$t.mjs" >"$shots/$t.log" 2>&1; thendiff --git a/.uiverify/device-approval.mjs b/.uiverify/device-approval.mjsnew file mode 100644index 0000000..e263443--- /dev/null+++ b/.uiverify/device-approval.mjs@@ -0,0 +1,117 @@+// Advanced Data Protection (issue #4): Notes, Reminders, Photos and iCloud Drive open only once+// the person approves Skykeep on one of their devices. A screen with nothing on this computer+// yet is replaced by one calm page saying so, with Try Again; a screen that has its copy here+// keeps it, with one card at the foot. Calendar and Contacts are never held up. Once the+// approval lands, it all goes away by itself; with web access off, the existing page shows.+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++; };+const ALL = ["notes", "reminders", "photos", "drive"];+const HEADING = "Approve on your iPhone, iPad or Mac";++async function open(access, afterAsk) {+ const ctx = await b.newContext({ viewport: { width: 1180, height: 820 } });+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });+ await ctx.addInitScript(({ access, afterAsk }) => {+ window.__dataAccess = access;+ window.__dataAccessAfterAsk = afterAsk;+ }, { access, afterAsk });+ const page = await ctx.newPage();+ await page.goto(BASE, { waitUntil: "networkidle" });+ await page.waitForTimeout(300);+ return { ctx, page };+}+const say = (page, access) => page.evaluate((a) => window.__emit?.("quince://data-access", a), access);+const heading = (page) => page.getByRole("heading", { name: HEADING });++// iCloud Drive has nothing on this computer yet: the page stands in for it.+{+ const { ctx, page } = await open({ state: "waiting", services: ALL, problem: null });+ await openScreen(page, "Drive");+ await page.waitForTimeout(200);+ ok(await heading(page).isVisible(), "Drive, with nothing here yet, shows the approval page");+ const text = await page.locator(".device-approval").innerText();+ ok(text.includes("Advanced Data Protection, which keeps iCloud Drive end-to-end encrypted"), "it names the service and why");+ ok(text.includes("Waiting for your iPhone, iPad or Mac…"), "while it is on its way, it says it is waiting");+ ok(await page.locator(".device-approval .spinner").isVisible(), "with a spinner");+ ok(await page.getByRole("button", { name: "Try Again" }).isVisible(), "and Try Again");+ ok(!(await page.locator(".drive").first().isVisible()), "the empty Drive screen is not drawn beneath it");++ // Calendar and Contacts need no approval under Advanced Data Protection.+ await openScreen(page, "Calendar");+ await page.waitForTimeout(200);+ ok(!(await heading(page).isVisible()), "Calendar is never held up");+ ok(await page.locator(".cx").first().isVisible(), "and is drawn as usual");++ // Approved on the phone: the backend says so, and Drive opens by itself.+ await openScreen(page, "Drive");+ await say(page, { state: "open", services: [], problem: null });+ await page.waitForTimeout(250);+ ok(!(await heading(page).isVisible()), "once approved, the page goes away by itself");+ ok(await page.locator(".drive").first().isVisible(), "and Drive is drawn");+ await ctx.close();+}++// Notes already has its copy here: kept on screen, with one card at the foot.+{+ const { ctx, page } = await open({ state: "needed", services: ALL, problem: null }, { state: "waiting", services: ALL, problem: null });+ await openScreen(page, "Notes");+ await page.waitForTimeout(250);+ ok(!(await heading(page).isVisible()), "Notes with its copy here is not replaced");+ ok(await page.locator(".notes").first().isVisible(), "its notes stay readable");+ const card = page.locator(".device-approval-notice");+ ok(await card.isVisible(), "a card at the foot says what would bring it up to date");+ ok((await card.innerText()).includes("To bring Notes up to date, approve Skykeep on your iPhone, iPad or Mac."), "in plain words");+ await card.getByRole("button", { name: "Try Again" }).click();+ await page.waitForTimeout(200);+ ok((await page.evaluate(() => window.__dataAccessAsks)) === 1, "Try Again asks Apple once");+ ok((await card.innerText()).includes("Approve Skykeep on your iPhone, iPad or Mac to bring Notes up to date."), "and the card then says the request is on its way");+ ok(!(await card.getByRole("button", { name: "Try Again" }).isVisible()), "without a second button to press meanwhile");+ await ctx.close();+}++// Apple couldn't reach any of the person's devices; then, Try Again on the page.+{+ const { ctx, page } = await open({ state: "notSent", services: ["photos"], problem: null }, { state: "waiting", services: ["photos"], problem: null });+ await page.locator(".nav-item", { hasText: "Photos" }).click();+ await page.waitForTimeout(400);+ ok(await heading(page).isVisible(), "Photos shows the approval page");+ ok((await page.locator(".device-approval").innerText()).includes("Apple couldn’t reach your devices."), "and says Apple couldn't reach the devices");+ await page.getByRole("button", { name: "Try Again" }).click();+ await page.waitForTimeout(200);+ ok((await page.locator(".device-approval").innerText()).includes("Waiting for your iPhone, iPad or Mac…"), "Try Again puts it on its way");+ // A service not waiting on it opens as usual.+ await openScreen(page, "Notes");+ await page.waitForTimeout(200);+ ok(!(await page.locator(".device-approval-notice").isVisible()) && !(await heading(page).isVisible()), "Notes, not waiting on it, shows nothing extra");+ await ctx.close();+}++// "Access iCloud Data on the Web" turned off: the page that says how to turn it on.+{+ const { ctx, page } = await open({ state: "open", services: [], problem: null });+ await openScreen(page, "Notes");+ await say(page, { state: "webAccessOff", services: [], problem: null });+ await page.waitForTimeout(250);+ ok(await page.getByRole("heading", { name: "Your iCloud data is kept off the web" }).isVisible(), "web access off shows the page with Apple's switch");+ ok(!(await heading(page).isVisible()), "not the approval page");+ await ctx.close();+}++// The page is reachable by keyboard and reads as a status for a screen reader.+{+ const { ctx, page } = await open({ state: "needed", services: ALL, problem: null });+ await page.locator(".nav-item", { hasText: "Drive" }).click();+ await page.waitForTimeout(300);+ ok((await page.locator(".device-approval [role=status]").count()) === 1, "where it stands is announced politely");+ await page.getByRole("button", { name: "Try Again" }).focus();+ ok(await page.evaluate(() => document.activeElement?.textContent === "Try Again"), "Try Again takes focus");+ 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 e907735..cad255a 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -1058,6 +1058,13 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notecase "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 };+ // 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 };+ case "data_access_ask":+ window.__dataAccessAsks = (window.__dataAccessAsks ?? 0) + 1;+ window.__dataAccess = window.__dataAccessAfterAsk ?? window.__dataAccess;+ return window.__dataAccess ?? { state: "open", services: [], problem: null };case "settings_get": return { reminderAlerts: true, eventAlerts: true, ...(window.__settings ?? {}) };case "settings_set":if (window.__settingsFail) throw "Couldn't save that setting.";diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 99538be..479bc9f 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -68,4 +68,5 @@ once opened is kept mounted and inert while another is in front, so coming back| What is stored | `crates/quince-core/src/schema.rs`, then the service's file there || How a write behaves offline | `src-tauri/src/outbox.rs` || When syncing happens | `src-tauri/src/push.rs`, `refresh.rs` |+| Advanced Data Protection approvals | `crates/quince-auth/src/pcs.rs`, `src-tauri/src/data_access.rs` || A screen | `src/screens/`, its types in `src/lib/ipc.ts`, its suite in `.uiverify/` |diff --git a/README.md b/README.mdindex febdff9..40c857f 100644--- a/README.md+++ b/README.md@@ -315,7 +315,7 @@ Skykeep signs in the way icloud.com does, with Apple's own two-factor, and syncs<details><summary><b>I use Advanced Data Protection. Will it work?</b></summary>-Yes, with **Access iCloud Data on the Web** turned on: on your iPhone, Settings → your name → iCloud. Skykeep tells you when it's needed.+Yes, with **Access iCloud Data on the Web** turned on: on your iPhone, Settings → your name → iCloud. Skykeep tells you when it's needed. Calendar and Contacts open right away. For Notes, Reminders, Photos and iCloud Drive, approve Skykeep on your iPhone, iPad or Mac when it asks, just as you would for icloud.com. Apple's approval lasts about an hour at a time.</details><details>diff --git a/SECURITY.md b/SECURITY.mdindex 4277181..5b28033 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -131,6 +131,21 @@ With Advanced Data Protection on and "Access iCloud Data on the Web" off, Applelet any app outside your devices read your iCloud data, Skykeep included. Skykeep says soplainly and shows the switch; it does not work around it.+With "Access iCloud Data on the Web" on, Skykeep uses Apple's own approval, the one+icloud.com uses (`crates/quince-auth/src/pcs.rs`). Calendar and Contacts work as usual. For+Notes, Reminders, Photos and iCloud Drive, Skykeep asks Apple to put an approval request on+your trusted iPhone, iPad or Mac. It asks when you sign in or open a window, at most once+each time access runs out, or when you press Try Again, and never from a background sync.+Once you approve, Apple's servers have that device send each service's key to this session.+The keys arrive as `X-APPLE-WEBAUTH-PCS-*` cookies and are kept in Skykeep's sealed cookie+jar with the rest of the session. Apple limits an approval to about an hour. While it lasts,+Skykeep collects a key that ran out again without asking you. After that, it asks you to+approve again.++Skykeep never sees your device keys. It never approves anything for you, and it never turns+Advanced Data Protection or any other Apple setting on or off. Health data and passwords in+iCloud Keychain are outside what Apple lets the web reach at all.+## Reporting a vulnerabilityPlease use GitHub's private vulnerability reporting on this repository (Security →diff --git a/check.sh b/check.shindex 166dc99..fc9dc79 100755--- a/check.sh+++ b/check.sh@@ -168,6 +168,8 @@ step "webkit: occasions" env ENGINE=webkit node .uiverify/occasions.mjsstep "webkit: drive nav" env ENGINE=webkit node .uiverify/drive-nav.mjsstep "sign-in keyring" node .uiverify/signin-keyring.mjsstep "lapse reason" node .uiverify/lapse-reason.mjs+step "device approval" node .uiverify/device-approval.mjs+step "webkit: approval" env ENGINE=webkit node .uiverify/device-approval.mjsstep "calendar undo" node .uiverify/calendar-undo.mjsprintf '\n'diff --git a/crates/quince-auth/Cargo.toml b/crates/quince-auth/Cargo.tomlindex 3a1f326..a5fdb8c 100644--- a/crates/quince-auth/Cargo.toml+++ b/crates/quince-auth/Cargo.toml@@ -23,7 +23,7 @@ reqwest_cookie_store = "0.8"cookie_store = { version = "0.21", features = ["serde_json"] }thiserror = "2"# Looking up Apple's hosts for the client's own resolver (AppleOnly).-tokio = { workspace = true, features = ["net"] }+tokio = { workspace = true, features = ["net", "time"] }# The updater's client (releases.rs), locked like Apple's: the reqwest the Tauri updater plugin# is built on, with no TLS of its own — the plugin's (rustls on ring) is the one compiled.reqwest_releases = { package = "reqwest", version = "0.13", default-features = false, features = ["rustls-no-provider"] }diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex 8931982..97541b6 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -21,6 +21,7 @@ macro_rules! quiet {};}+pub mod pcs;pub mod releases;mod sealed;pub mod session;@@ -424,6 +425,8 @@ pub struct Client {/// The trusted phones Apple last listed, so a code is sent to and checked for each number/// the way that number takes one.phones: Vec<TrustedPhone>,+ /// What this run knows of Advanced Data Protection approvals (see [`pcs`]).+ pcs: pcs::Pcs,}/// What became of the cookies kept on disk when the client started.@@ -574,6 +577,7 @@ impl Client {persisted: std::sync::Mutex::new(Persisted::default()),cookies,phones: Vec::new(),+ pcs: pcs::Pcs::default(),})}@@ -726,6 +730,7 @@ impl Client {/// Forget this account entirely.pub fn sign_out(&mut self) -> Result<()> {self.session = Session::default();+ self.data_access_forget();if let Ok(mut jar) = self.jar.lock() {jar.clear();}@@ -998,6 +1003,8 @@ impl Client {// Start clean. An interrupted previous attempt would otherwise announce a// half-finished session and Apple would reject this one as a conflict.self.clear_challenge_state();+ // A new web session: its encrypted services' keys are its own to ask for.+ self.data_access_forget();let client = srp::Client::new(apple_id);diff --git a/crates/quince-auth/src/pcs.rs b/crates/quince-auth/src/pcs.rsnew file mode 100644index 0000000..b91699f--- /dev/null+++ b/crates/quince-auth/src/pcs.rs@@ -0,0 +1,535 @@+//! Advanced Data Protection: asking Apple to let this session read end-to-end encrypted data.+//!+//! With Advanced Data Protection on (Apple's iCloud Data Protection, `iCDPEnabled`) and+//! "Access iCloud Data on the Web" allowed, a web session reaches Calendar and Contacts as+//! usual, but Notes, Reminders, Photos and iCloud Drive only with a per-service key Apple+//! releases as a `X-APPLE-WEBAUTH-PCS-*` cookie. Apple releases it only after the person+//! approves the session on one of their trusted devices, and for an hour at a time+//! (support.apple.com/guide/security/sec973254c5f). Without it, iCloud Drive answers+//! `423 Missing PCS cookies from the request` and CloudKit `403 ACCESS_DENIED, private db+//! access disabled for this account` — issue #4.+//!+//! Three `POST`s to the setup service do it, as icloud.com does them (foxt/icloud.js#4,+//! rclone's `iclouddrive` backend, icloudpy#214, timlaing/pyicloud):+//!+//! * `requestWebAccessState`, empty — `isWebAccessAllowed`, `isICDRSDisabled` (recovery off:+//! ADP is in effect), `isDeviceConsentedForPCS`, `deviceConsentForPCSExpiry` (epoch ms).+//! * `enableDeviceConsentForPCS`, empty — puts the approval on the person's devices;+//! `isDeviceConsentNotificationSent` says whether Apple could.+//! * `requestPCS`, `{"appName", "derivedFromUserAction"}` — once approved, attaches the+//! service's cookies: `status: "success"` with "Cookies attached." or "Cookies already+//! present."; `status: "failure"` with "Requested the device to upload cookies." or+//! "Cookies not available yet on server." while the device is still sending the key.+//! `derivedFromUserAction` is true on the first ask only: repeating it notifies again.+//!+//! Nothing here waits for the person. [`Client::data_access`] takes one step and says where+//! it got to; whoever holds the client releases it between steps and follows+//! [`APPROVAL_SCHEDULE`] with [`follow`], so a sign-in, a sync or a sign-out is never held+//! up behind someone reaching for their phone.++use crate::{Client, Error, Result};+use reqwest::StatusCode;+use serde_json::{json, Value};+use std::collections::HashSet;+use std::time::Duration;++/// One service Advanced Data Protection keeps end-to-end encrypted, and how Apple names it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Protected {+ /// The app's own name for the service, as the sync reports name it.+ pub service: &'static str,+ /// Where Apple's service map lists it.+ pub webservice: &'static str,+ /// What `requestPCS` calls it — not the webservice key. A wrong one answers `success` and+ /// sets nothing, so where the cookies are known the answer is checked against them.+ pub app_name: &'static str,+ /// The cookies `requestPCS` sets for it, where the references have recorded them.+ pub cookies: &'static [&'static str],+}++/// Every service Skykeep reads that Advanced Data Protection covers. Calendar and Contacts are+/// not in it: Apple keeps their keys for itself under ADP, so they need no approval.+///+/// The app names are icloud.com's own: `photos` and `iclouddrive` (rclone, icloudpy#214, with+/// the cookies each sets), `notes3` and `reminders` (timlaing/pyicloud, which records no+/// cookie names for them).+pub const PROTECTED: [Protected; 4] = [+ Protected {+ service: "notes",+ webservice: "ckdatabasews",+ app_name: "notes3",+ cookies: &[],+ },+ Protected {+ service: "reminders",+ webservice: "ckdatabasews",+ app_name: "reminders",+ cookies: &[],+ },+ Protected {+ service: "photos",+ webservice: "ckdatabasews",+ app_name: "photos",+ cookies: &["X-APPLE-WEBAUTH-PCS-Photos", "X-APPLE-WEBAUTH-PCS-Sharing"],+ },+ Protected {+ service: "drive",+ webservice: "drivews",+ app_name: "iclouddrive",+ cookies: &["X-APPLE-WEBAUTH-PCS-Documents"],+ },+];++/// The protected service behind one of the app's names.+#[must_use]+pub fn protected(service: &str) -> Option<&'static Protected> {+ PROTECTED.iter().find(|p| p.service == service)+}++/// Where letting this session read end-to-end encrypted data has got to.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub enum DataAccess {+ /// Nothing waits on an approval: the account has no Advanced Data Protection, or every+ /// service it covers already has its key here.+ Open,+ /// The approval is on the person's devices, or approved and the keys on their way.+ /// Asked again after a wait ([`APPROVAL_SCHEDULE`]).+ Waiting,+ /// An approval is needed and none is on its way: asking was left to the person (a+ /// background pass never puts a prompt on their phone), or an earlier one ran out.+ Needed,+ /// Apple could not put the approval on any of the person's devices.+ NotSent,+ /// "Access iCloud Data on the Web" is off: no approval opens anything until it is on.+ WebAccessOff,+}++/// What `requestPCS` answers while the device is still uploading the key: not yet, not no.+const PENDING: [&str; 2] = [+ "Requested the device to upload cookies.",+ "Cookies not available yet on server.",+];++/// The web session cookie `requestPCS` stands on; without a live one Apple answers 500.+const WEB_AUTH_COOKIE: &str = "X-APPLE-WEBAUTH-TOKEN";++/// How long a key is taken to last when Apple gave no time for it: Apple's own hour.+const KEY_HOUR: u64 = 60 * 60;++/// An approval asked for within this long is not asked for again: a second push to the+/// person's phone while they reach for it is noise, and pushes count toward Apple's limits.+const ASK_AGAIN_AFTER: u64 = 2 * 60;++/// How long an approval put on the person's devices is waited for: [`APPROVAL_SCHEDULE`]'s+/// five minutes, and a little over for the requests themselves.+const APPROVAL_WINDOW: u64 = 6 * 60;++/// How long to wait before each step while an approval is on its way, then stop: every 5+/// seconds for the first minute (as icloudpy and pyicloud poll), every 10 for four more (as+/// rclone does), five minutes in all (rclone's bound) — 36 requests at most, never hammering.+/// After that the person is asked to try again.+pub const APPROVAL_SCHEDULE: fn(u32) -> Option<Duration> = |step| match step {+ 0..=11 => Some(Duration::from_secs(5)),+ 12..=35 => Some(Duration::from_secs(10)),+ _ => None,+};++/// Follow an approval from [`DataAccess::Waiting`] to where it lands: `step` is asked again+/// after each of `schedule`'s waits — the caller takes and releases the client inside it —+/// and the first answer that is not `Waiting` is the outcome. Run out, it is+/// [`DataAccess::Needed`]: the person is asked to try again rather than waited on for ever.+pub async fn follow<F, Fut>(+ schedule: fn(u32) -> Option<Duration>,+ mut step: F,+) -> Result<DataAccess>+where+ F: FnMut() -> Fut,+ Fut: std::future::Future<Output = Result<DataAccess>>,+{+ let mut n = 0;+ while let Some(wait) = schedule(n) {+ n += 1;+ if !wait.is_zero() {+ tokio::time::sleep(wait).await;+ }+ match step().await? {+ DataAccess::Waiting => {}+ other => return Ok(other),+ }+ }+ Ok(DataAccess::Needed)+}++/// What this run of the app knows about approvals, beside what the session keeps.+#[derive(Debug, Default)]+pub(crate) struct Pcs {+ /// Apple said recovery is on — Advanced Data Protection is not in effect — until then+ /// (unix seconds): not asked again every pass.+ open_until: Option<u64>,+ /// When an approval was last put on the person's devices.+ asked_at: Option<u64>,+ /// Services already asked for with `derivedFromUserAction`, so the ones after are not+ /// another notification. Forgotten once the key is here.+ announced: HashSet<&'static str>,+ /// Services Apple refused for want of their key even though one was held — it ran out,+ /// or Apple let it go: asked for again whatever the cookies say.+ stale: HashSet<&'static str>,+ /// A service was refused for want of its key on an account that never said it had+ /// Advanced Data Protection: it does, so every covered service is treated as protected.+ seen_locked: bool,+}++/// One answer from the setup service: its status and JSON body.+struct Answer {+ status: StatusCode,+ body: Value,+}++impl Answer {+ fn flag(&self, key: &str) -> Option<bool> {+ self.body.get(key).and_then(Value::as_bool)+ }+}++impl Client {+ /// The services Advanced Data Protection covers that this session cannot read yet: it+ /// 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) {+ return Vec::new();+ }+ if self+ .pcs+ .open_until+ .is_some_and(|until| until > crate::unix_now())+ {+ return Vec::new();+ }+ self.protected_here()+ .filter(|p| !self.holds_key(p))+ .map(|p| p.service)+ .collect()+ }++ /// Apple refused `service` for want of its key (see `quince_icloud::Error::+ /// NeedsDeviceApproval`): the next [`Self::data_access`] asks for it again, whatever the+ /// cookies held say.+ pub fn data_access_lapsed(&mut self, service: &str) {+ let Some(p) = protected(service) else { return };+ self.pcs.seen_locked = true;+ self.pcs.open_until = None;+ self.pcs.stale.insert(p.service);+ self.session.pcs_until.remove(p.app_name);+ }++ /// Forget every approval, for a sign-out or a new sign-in: the keys belong to the web+ /// session they were released to, so a new one asks for its own, whatever cookies the+ /// old one left in the jar.+ pub(crate) fn data_access_forget(&mut self) {+ self.pcs = Pcs {+ stale: PROTECTED.iter().map(|p| p.service).collect(),+ ..Pcs::default()+ };+ self.session.pcs_until.clear();+ }++ /// The protected services Apple offers this account and says it guards: by Advanced Data+ /// Protection being on, by the service map's `pcsRequired`, or by a refusal seen here.+ fn protected_here(&self) -> impl Iterator<Item = &'static Protected> + '_ {+ let adp = self.session.data_protection == Some(true) || self.pcs.seen_locked;+ PROTECTED.iter().filter(move |p| {+ let Some(ws) = self+ .session+ .webservices+ .as_ref()+ .and_then(|w| w.get(p.webservice))+ else {+ return false;+ };+ adp || ws.get("pcsRequired").and_then(Value::as_bool) == Some(true)+ })+ }++ /// Whether this session holds a key for `p` that has not run out.+ fn holds_key(&self, p: &Protected) -> bool {+ if self.pcs.stale.contains(p.service) {+ return false;+ }+ let now = crate::unix_now();+ let recorded = self+ .session+ .pcs_until+ .get(p.app_name)+ .is_some_and(|until| *until > now);+ if p.cookies.is_empty() {+ return recorded;+ }+ let jar = self+ .jar+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let held: HashSet<&str> = jar.iter_unexpired().map(|c| c.name()).collect();+ p.cookies.iter().all(|name| held.contains(name))+ }++ /// When the keys just attached run out: the earliest PCS cookie's expiry, else the+ /// approval's, else Apple's hour from now.+ fn keys_until(&self, consent_until: Option<u64>) -> u64 {+ let now = crate::unix_now();+ let jar = self+ .jar+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ jar.iter_unexpired()+ .filter(|c| c.name().starts_with("X-APPLE-WEBAUTH-PCS-"))+ .filter_map(|c| match c.expires {+ cookie_store::CookieExpiration::AtUtc(t) => u64::try_from(t.unix_timestamp()).ok(),+ cookie_store::CookieExpiration::SessionEnd => None,+ })+ .min()+ .or(consent_until)+ .filter(|t| *t > now)+ .unwrap_or(now + KEY_HOUR)+ }++ /// One `POST` to the setup service. Apple's words stay out of every error: what it says+ /// about an account's keys is the account's.+ async fn setup_post(&mut self, endpoint: &str, body: Option<Value>) -> Result<Answer> {+ let mut request = self+ .http+ .post(format!("{}/{endpoint}", self.endpoints.setup))+ .query(&self.service_params());+ request = match body {+ Some(body) => request+ .header("content-type", "application/json")+ .body(body.to_string()),+ None => request.body(""),+ };+ let response = request.send().await?;+ self.capture(&response);+ let status = response.status();+ let text = response.text().await.unwrap_or_default();+ let body = serde_json::from_str(&text).unwrap_or(Value::Null);+ quiet!("quince: {endpoint} answered {status}");+ match status.as_u16() {+ 401 | 421 | 450 => Err(Error::ReauthRequired),+ // "Not now": Apple busy, or asking for fewer requests. The caller waits.+ 429 | 502 | 503 | 504 => Err(Error::Unavailable(status.as_u16())),+ _ => Ok(Answer { status, body }),+ }+ }++ /// Take one step toward reading this account's end-to-end encrypted services, and say+ /// where it got to. Asks Apple nothing when nothing is missing.+ ///+ /// `ask` lets this put the approval on the person's devices when it is needed — for a+ /// sign-in, a window opening, or the person asking. A background pass does not: a prompt+ /// on their phone every hour, unasked, is not something to do to anyone.+ pub async fn data_access(&mut self, ask: bool) -> Result<DataAccess> {+ if self.session.web_access_allowed == Some(false) {+ return Ok(DataAccess::WebAccessOff);+ }+ let missing: Vec<&'static Protected> = self+ .data_access_missing()+ .into_iter()+ .filter_map(protected)+ .collect();+ if missing.is_empty() {+ return Ok(DataAccess::Open);+ }+ let state = self.setup_post("requestWebAccessState", None).await?;+ if !state.status.is_success() {+ return Err(Error::Protocol(format!(+ "Apple didn't say whether this session may read your encrypted data (HTTP {})",+ state.status+ )));+ }+ if state.flag("isWebAccessAllowed") == Some(false) {+ self.session.web_access_allowed = Some(false);+ self.keep();+ return Ok(DataAccess::WebAccessOff);+ }+ // An account that said it has Advanced Data Protection, or was refused for want of a+ // key, and an answer with no word of recovery either way: not something to read as+ // "nothing to approve", which would leave its services failing without saying why.+ let said_adp = self.session.data_protection == Some(true) || self.pcs.seen_locked;+ if said_adp && state.flag("isICDRSDisabled").is_none() {+ return Err(Error::Protocol(format!(+ "Apple didn't say whether this session may read your encrypted data (HTTP {})",+ state.status+ )));+ }+ if state.flag("isICDRSDisabled") != Some(true) {+ // Recovery is on, so Apple holds the keys itself: no approval opens anything more.+ self.pcs.open_until = Some(crate::unix_now() + KEY_HOUR);+ return Ok(DataAccess::Open);+ }+ let consent_until = state+ .body+ .get("deviceConsentForPCSExpiry")+ .and_then(Value::as_u64)+ .map(|ms| ms / 1000)+ .filter(|s| *s > 0);++ if state.flag("isDeviceConsentedForPCS") != Some(true) {+ let now = crate::unix_now();+ let since_asked = self.pcs.asked_at.map(|at| now.saturating_sub(at));+ let ask_now = ask && since_asked.is_none_or(|s| s >= ASK_AGAIN_AFTER);+ if !ask_now {+ // One already on the person's devices is waited for, as long as the schedule+ // runs; after that it is theirs to ask for again.+ return Ok(match since_asked {+ Some(s) if s < APPROVAL_WINDOW => DataAccess::Waiting,+ _ => DataAccess::Needed,+ });+ }+ let sent = self.setup_post("enableDeviceConsentForPCS", None).await?;+ if sent.flag("isWebAccessAllowed") == Some(false) {+ self.session.web_access_allowed = Some(false);+ self.keep();+ return Ok(DataAccess::WebAccessOff);+ }+ if sent.flag("isDeviceConsentNotificationSent") != Some(true) {+ return Ok(DataAccess::NotSent);+ }+ self.pcs.asked_at = Some(now);+ // A new approval: each service's first ask may say so again.+ self.pcs.announced.clear();+ return Ok(DataAccess::Waiting);+ }++ // Approved: ask for each missing service's key.+ self.pcs.asked_at = None;+ let mut waiting = false;+ for p in missing {+ let first = self.pcs.announced.insert(p.service);+ let answer = self+ .setup_post(+ "requestPCS",+ Some(json!({ "appName": p.app_name, "derivedFromUserAction": first })),+ )+ .await?;+ let message = answer+ .body+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or("");+ if answer.flag("isWebAccessAllowed") == Some(false) {+ self.session.web_access_allowed = Some(false);+ self.keep();+ return Ok(DataAccess::WebAccessOff);+ }+ // Recovery on after all (Apple's "User has not disabled iCloud DRS"): no key needed.+ if answer.status.as_u16() == 412 || message.contains("iCloud DRS") {+ self.pcs.open_until = Some(crate::unix_now() + KEY_HOUR);+ return Ok(DataAccess::Open);+ }+ if answer.status.as_u16() == 500 && message.contains(WEB_AUTH_COOKIE) {+ return Err(Error::ReauthRequired);+ }+ if answer.status.is_success()+ && answer.body.get("status").and_then(Value::as_str) == Some("success")+ {+ if !self.cookies_arrived(p) {+ return Err(Error::Protocol(format!(+ "Apple said the {} key was attached, but none arrived",+ p.service+ )));+ }+ let until = self.keys_until(consent_until);+ self.session.pcs_until.insert(p.app_name.to_string(), until);+ self.pcs.stale.remove(p.service);+ self.pcs.announced.remove(p.service);+ continue;+ }+ if PENDING.contains(&message) {+ waiting = true;+ continue;+ }+ return Err(Error::Protocol(format!(+ "Apple didn't release the {} key (HTTP {})",+ p.service, answer.status+ )));+ }+ // The cookies the answers set are in the jar: kept, sealed, for the next start.+ self.keep();+ Ok(if waiting {+ DataAccess::Waiting+ } else {+ DataAccess::Open+ })+ }++ /// Whether the cookies `requestPCS` is known to set for `p` are here now.+ fn cookies_arrived(&self, p: &Protected) -> bool {+ if p.cookies.is_empty() {+ return true;+ }+ let jar = self+ .jar+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let held: HashSet<&str> = jar.iter_unexpired().map(|c| c.name()).collect();+ p.cookies.iter().all(|name| held.contains(name))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_wait_is_bounded_and_never_hammers() {+ let waits: Vec<Duration> = (0..).map_while(APPROVAL_SCHEDULE).collect();+ assert_eq!(waits.len(), 36, "36 asks at most");+ let total: u64 = waits.iter().map(Duration::as_secs).sum();+ assert_eq!(total, 5 * 60, "five minutes in all, as rclone allows");+ assert!(+ waits.iter().all(|w| w.as_secs() >= 5),+ "never faster than every 5 seconds"+ );+ }++ #[test]+ fn every_protected_service_has_its_app_name() {+ let names: Vec<&str> = PROTECTED.iter().map(|p| p.app_name).collect();+ assert_eq!(names, ["notes3", "reminders", "photos", "iclouddrive"]);+ assert!(protected("calendar").is_none() && protected("contacts").is_none());+ }++ #[tokio::test]+ async fn following_stops_at_the_first_answer_that_is_not_waiting() {+ let mut asked = 0;+ let got = follow(+ |n| (n < 10).then_some(Duration::ZERO),+ || {+ asked += 1;+ let now = asked;+ async move {+ Ok(if now < 3 {+ DataAccess::Waiting+ } else {+ DataAccess::Open+ })+ }+ },+ )+ .await+ .unwrap();+ assert_eq!((got, asked), (DataAccess::Open, 3));++ let ran_out = follow(+ |n| (n < 4).then_some(Duration::ZERO),+ || async { Ok(DataAccess::Waiting) },+ )+ .await+ .unwrap();+ assert_eq!(+ ran_out,+ DataAccess::Needed,+ "run out, the person is asked to try again"+ );+ }+}diff --git a/crates/quince-auth/src/session.rs b/crates/quince-auth/src/session.rsindex e1f4daa..e06f5f4 100644--- a/crates/quince-auth/src/session.rs+++ b/crates/quince-auth/src/session.rs@@ -112,6 +112,11 @@ pub struct Session {/// Advanced Data Protection, which Apple calls iCloud Data Protection (`iCDPEnabled`).#[serde(default)]pub data_protection: Option<bool>,+ /// Under Advanced Data Protection, until when (unix seconds) each service's key — by its+ /// `requestPCS` name — was released to this session (see `pcs`). Kept for the services+ /// 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>,/// Failed sign-ins in a row. Drives the local backoff.#[serde(default)]diff --git a/crates/quince-auth/tests/data_protection.rs b/crates/quince-auth/tests/data_protection.rsnew file mode 100644index 0000000..b01721d--- /dev/null+++ b/crates/quince-auth/tests/data_protection.rs@@ -0,0 +1,819 @@+//! Advanced Data Protection (issue #4) against a mock Apple: every account shape the approval+//! flow meets, so what it asks of Apple — and what it never asks — is pinned in CI rather than+//! found on someone's account.+//!+//! The conversation is icloud.com's own, as foxt/icloud.js#4, rclone's iclouddrive backend,+//! icloudpy#214 and timlaing/pyicloud record it: `requestWebAccessState`, then+//! `enableDeviceConsentForPCS` while no approval is given, then `requestPCS` per service.++use quince_auth::pcs::{follow, DataAccess};+use quince_auth::{Client, Endpoints, Error, Store};+use serde_json::{json, Value};+use std::time::Duration;+use wiremock::matchers::{body_partial_json, method, path};+use wiremock::{Mock, MockServer, Request, ResponseTemplate};++const STATE: &str = "/setup/ws/1/requestWebAccessState";+const CONSENT: &str = "/setup/ws/1/enableDeviceConsentForPCS";+const PCS: &str = "/setup/ws/1/requestPCS";++fn b64(bytes: &[u8]) -> String {+ use base64::{engine::general_purpose::STANDARD as E, Engine};+ E.encode(bytes)+}++/// The account as `accountLogin` describes it.+#[derive(Clone, Copy)]+struct Shape {+ /// `iCDPEnabled`.+ adp: Option<bool>,+ /// `dsInfo.isWebAccessAllowed`.+ web_access: Option<bool>,+ /// `pcsRequired` on the encrypted services.+ pcs_required: bool,+ /// Apple offers iCloud Drive to the account at all.+ drive: bool,+}++const ADP: Shape = Shape {+ adp: Some(true),+ web_access: Some(true),+ pcs_required: true,+ drive: true,+};+const STANDARD: Shape = Shape {+ adp: None,+ web_access: None,+ pcs_required: false,+ drive: true,+};++fn login_body(shape: Shape) -> Value {+ let mut ws = json!({+ "calendar": { "url": "https://p00-calendarws.test.invalid:443", "status": "active" },+ "contacts": { "url": "https://p00-contactsws.test.invalid:443", "status": "active" },+ "ckdatabasews": { "url": "https://p00-ckdatabasews.test.invalid:443", "status": "active",+ "pcsRequired": shape.pcs_required },+ });+ if shape.drive {+ ws["drivews"] = json!({ "url": "https://p00-drivews.test.invalid:443", "status": "active",+ "pcsRequired": shape.pcs_required });+ }+ let mut ds = json!({ "dsid": "1234567890" });+ if let Some(w) = shape.web_access {+ ds["isWebAccessAllowed"] = json!(w);+ }+ let mut body = json!({ "dsInfo": ds, "webservices": ws });+ if let Some(a) = shape.adp {+ body["iCDPEnabled"] = json!(a);+ }+ body+}++/// Signed in to an account of `shape`, with a code from a trusted device — or, `sms`, with+/// one texted to a phone: how the code came makes no difference to what follows.+async fn signed_in(server: &MockServer, dir: &std::path::Path, shape: Shape, sms: bool) -> Client {+ 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": 20173, "protocol": "s2k",+ })))+ .mount(server)+ .await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/signin/complete"))+ .respond_with(+ ResponseTemplate::new(409)+ .insert_header("X-Apple-Session-Token", "session-token-abc")+ .insert_header("X-Apple-ID-Account-Country", "IND")+ .set_body_json(json!({})),+ )+ .mount(server)+ .await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(ResponseTemplate::new(204))+ .mount(server)+ .await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/verify/phone/securitycode"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))+ .mount(server)+ .await;+ Mock::given(method("GET"))+ .and(path("/appleauth/auth/2sv/trust"))+ .respond_with(+ ResponseTemplate::new(204)+ .insert_header("X-Apple-TwoSV-Trust-Token", "trust-token-xyz")+ .insert_header("X-Apple-Session-Token", "session-token-def"),+ )+ .mount(server)+ .await;+ Mock::given(method("POST"))+ .and(path("/setup/ws/1/accountLogin"))+ .respond_with(+ ResponseTemplate::new(200)+ .append_header(+ "set-cookie",+ "X-APPLE-WEBAUTH-TOKEN=web-token; Path=/; Max-Age=86400",+ )+ .set_body_json(login_body(shape)),+ )+ .mount(server)+ .await;++ let base = server.uri();+ let endpoints = Endpoints {+ auth_root: base.clone(),+ home: base.clone(),+ auth: format!("{base}/appleauth/auth"),+ setup: format!("{base}/setup/ws/1"),+ };+ let mut client = Client::with(dir, endpoints, Store::file(dir).unwrap()).unwrap();+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();+ if sms {+ client.submit_sms_code(1, "123456").await.unwrap();+ } else {+ client.submit_two_factor("123456").await.unwrap();+ }+ client+}++fn state(consented: bool, expiry_ms: u64) -> ResponseTemplate {+ ResponseTemplate::new(200).set_body_json(json!({+ "dsid": 1234567890, "isWebAccessAllowed": true, "isDeviceConsentedForPCS": consented,+ "isICDRSDisabled": true, "deviceConsentForPCSExpiry": expiry_ms,+ }))+}++fn in_an_hour_ms() -> u64 {+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_millis();+ u64::try_from(now).unwrap() + 3_600_000+}++/// `requestPCS` attaching a service's keys, with the cookies icloud.com is given for it.+async fn mount_keys(server: &MockServer, max_age: u32) {+ let attached = |cookies: &[&str]| {+ let mut r = ResponseTemplate::new(200).set_body_json(json!({+ "isWebAccessAllowed": true, "isDeviceConsentedForPCS": true, "isICDRSDisabled": true,+ "message": "Cookies attached.", "status": "success",+ }));+ for c in cookies {+ r = r.append_header(+ "set-cookie",+ format!("{c}=key; Path=/; Max-Age={max_age}").as_str(),+ );+ }+ r+ };+ for (app, cookies) in [+ (+ "photos",+ vec!["X-APPLE-WEBAUTH-PCS-Photos", "X-APPLE-WEBAUTH-PCS-Sharing"],+ ),+ ("iclouddrive", vec!["X-APPLE-WEBAUTH-PCS-Documents"]),+ ("notes3", vec!["X-APPLE-WEBAUTH-PCS-Notes"]),+ ("reminders", vec![]),+ ] {+ Mock::given(method("POST"))+ .and(path(PCS))+ .and(body_partial_json(json!({ "appName": app })))+ .respond_with(attached(&cookies))+ .mount(server)+ .await;+ }+}++fn to<'a>(reqs: &'a [Request], p: &str) -> Vec<&'a Request> {+ reqs.iter().filter(|r| r.url.path() == p).collect()+}++async fn asked(server: &MockServer, p: &str) -> usize {+ to(&server.received_requests().await.unwrap(), p).len()+}++fn app_names(reqs: &[&Request]) -> Vec<String> {+ reqs.iter()+ .map(|r| {+ let v: Value = serde_json::from_slice(&r.body).unwrap();+ v["appName"].as_str().unwrap().to_string()+ })+ .collect()+}++/// Waits of nothing, a few times: `follow` without the clock.+fn quick(n: u32) -> Option<Duration> {+ (n < 8).then_some(Duration::ZERO)+}++/// Without Advanced Data Protection nothing changes: no approval, and not one request more.+#[tokio::test]+async fn an_account_without_advanced_data_protection_is_never_asked_anything() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), STANDARD, false).await;+ assert!(client.data_access_missing().is_empty());+ assert_eq!(client.data_access(true).await.unwrap(), DataAccess::Open);+ for p in [STATE, CONSENT, PCS] {+ assert_eq!(asked(&server, p).await, 0, "{p} is never asked");+ }+}++/// `pcsRequired` alone does not prove Advanced Data Protection (icloudpy#214): Apple is asked+/// once, says recovery is on, and is not asked again every pass.+#[tokio::test]+async fn pcs_required_with_recovery_on_asks_once_and_needs_nothing() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let shape = Shape { adp: None, ..ADP };+ let mut client = signed_in(&server, dir.path(), shape, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "dsid": 1234567890, "isWebAccessAllowed": true+ })))+ .mount(&server)+ .await;+ assert_eq!(client.data_access(true).await.unwrap(), DataAccess::Open);+ assert_eq!(client.data_access(true).await.unwrap(), DataAccess::Open);+ assert_eq!(+ asked(&server, STATE).await,+ 1,+ "asked once, then remembered"+ );+ assert_eq!(+ asked(&server, CONSENT).await,+ 0,+ "no prompt on anyone's phone"+ );+ assert!(client.data_access_missing().is_empty());+}++/// Advanced Data Protection with web access off: the existing page, and nothing asked.+#[tokio::test]+async fn web_access_off_at_sign_in_is_said_without_asking() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let shape = Shape {+ web_access: Some(false),+ ..ADP+ };+ let mut client = signed_in(&server, dir.path(), shape, false).await;+ assert_eq!(+ client.data_access(true).await.unwrap(),+ DataAccess::WebAccessOff+ );+ assert_eq!(asked(&server, STATE).await, 0);+}++/// Turned off since sign-in: Apple's state says so, and the session remembers it.+#[tokio::test]+async fn web_access_turned_off_since_is_read_from_apple() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "isWebAccessAllowed": false, "isICDRSDisabled": true+ })))+ .mount(&server)+ .await;+ assert_eq!(+ client.data_access(true).await.unwrap(),+ DataAccess::WebAccessOff+ );+ assert_eq!(client.session().web_access_allowed, Some(false));+ assert_eq!(asked(&server, CONSENT).await, 0);+}++/// Approved already (within the hour): each service's key is asked for by icloud.com's name+/// for it, once, and held; nothing is put on the person's phone.+#[tokio::test]+async fn an_approval_already_given_attaches_every_key_silently() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ assert_eq!(+ client.data_access_missing(),+ ["notes", "reminders", "photos", "drive"],+ "every covered service waits on its key"+ );+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(true, in_an_hour_ms()))+ .mount(&server)+ .await;+ mount_keys(&server, 3600).await;++ assert_eq!(client.data_access(false).await.unwrap(), DataAccess::Open);+ let reqs = server.received_requests().await.unwrap();+ let pcs = to(&reqs, PCS);+ assert_eq!(+ app_names(&pcs),+ ["notes3", "reminders", "photos", "iclouddrive"]+ );+ for r in &pcs {+ let v: Value = serde_json::from_slice(&r.body).unwrap();+ assert_eq!(+ v["derivedFromUserAction"],+ json!(true),+ "the first ask for each says so"+ );+ assert!(+ r.url+ .query_pairs()+ .any(|(k, v)| k == "dsid" && v == "1234567890"),+ "with the account's dsid, as icloud.com sends it"+ );+ }+ assert_eq!(to(&reqs, CONSENT).len(), 0, "already approved: no prompt");+ assert!(client.data_access_missing().is_empty(), "every key is held");++ // Held: the next pass asks Apple nothing.+ assert_eq!(client.data_access(true).await.unwrap(), DataAccess::Open);+ assert_eq!(asked(&server, STATE).await, 1);++ // And kept for the next start, sealed with the cookies and the session.+ drop(client);+ let base = server.uri();+ let again = Client::with(+ dir.path(),+ Endpoints::at(&base),+ Store::file(dir.path()).unwrap(),+ )+ .unwrap();+ assert!(+ again.data_access_missing().is_empty(),+ "the keys outlive a restart"+ );+}++/// The usual first run: not approved yet. The approval is put on the person's devices once,+/// waited for without asking again, and each key fetched once it is given — through the+/// device's "still uploading" answer.+#[tokio::test]+async fn an_approval_pending_then_given_is_followed_to_the_end() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let shape = Shape {+ drive: false,+ ..ADP+ };+ let mut client = signed_in(&server, dir.path(), shape, true).await;+ // Not approved for the first two looks, then approved.+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(false, 0))+ .up_to_n_times(2)+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(true, in_an_hour_ms()))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(CONSENT))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "isDeviceConsentNotificationSent": true, "isWebAccessAllowed": true,+ "isDeviceConsentedForPCS": false, "isICDRSDisabled": true, "deviceConsentForPCSExpiry": 0+ })))+ .mount(&server)+ .await;+ // The device is still sending the Photos key the first time it is asked for.+ Mock::given(method("POST"))+ .and(path(PCS))+ .and(body_partial_json(json!({ "appName": "photos" })))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "isWebAccessAllowed": true, "isDeviceConsentedForPCS": true, "isICDRSDisabled": true,+ "message": "Requested the device to upload cookies.", "status": "failure"+ })))+ .up_to_n_times(1)+ .mount(&server)+ .await;+ mount_keys(&server, 3600).await;++ assert_eq!(client.data_access(true).await.unwrap(), DataAccess::Waiting);+ assert_eq!(+ asked(&server, CONSENT).await,+ 1,+ "the approval is put on the devices"+ );++ let landed = {+ let client = std::sync::Arc::new(tokio::sync::Mutex::new(client));+ let stepping = std::sync::Arc::clone(&client);+ let landed = follow(quick, || {+ let c = std::sync::Arc::clone(&stepping);+ async move { c.lock().await.data_access(false).await }+ })+ .await+ .unwrap();+ assert!(client.lock().await.data_access_missing().is_empty());+ landed+ };+ assert_eq!(landed, DataAccess::Open);++ let reqs = server.received_requests().await.unwrap();+ assert_eq!(+ to(&reqs, CONSENT).len(),+ 1,+ "waiting never puts a second prompt on the phone"+ );+ let photos: Vec<Value> = to(&reqs, PCS)+ .iter()+ .map(|r| serde_json::from_slice::<Value>(&r.body).unwrap())+ .filter(|v| v["appName"] == "photos")+ .collect();+ assert_eq!(photos.len(), 2, "asked for until it arrives");+ assert_eq!(photos[0]["derivedFromUserAction"], json!(true));+ assert_eq!(+ photos[1]["derivedFromUserAction"],+ json!(false),+ "and only the first ask notifies again"+ );+ assert!(+ !app_names(&to(&reqs, PCS)).contains(&"iclouddrive".to_string()),+ "an account without iCloud Drive is never asked for its key"+ );+}++/// A background pass never puts a prompt on the person's phone: it says one is needed.+#[tokio::test]+async fn a_background_pass_says_an_approval_is_needed_without_asking() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(false, 0))+ .mount(&server)+ .await;+ assert_eq!(client.data_access(false).await.unwrap(), DataAccess::Needed);+ assert_eq!(asked(&server, CONSENT).await, 0);+}++/// Never answered: the wait is bounded, and lands on "needed" — Try Again, not a spinner for+/// ever, and never a second prompt while it waits.+#[tokio::test]+async fn an_approval_never_given_runs_out_and_asks_for_try_again() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(false, 0))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(CONSENT))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "isDeviceConsentNotificationSent": true+ })))+ .mount(&server)+ .await;+ assert_eq!(client.data_access(true).await.unwrap(), DataAccess::Waiting);+ let client = std::sync::Arc::new(tokio::sync::Mutex::new(client));+ let landed = follow(quick, || {+ let c = std::sync::Arc::clone(&client);+ async move { c.lock().await.data_access(false).await }+ })+ .await+ .unwrap();+ assert_eq!(landed, DataAccess::Needed);+ assert_eq!(+ asked(&server, STATE).await,+ 9,+ "one look, then one per wait: bounded"+ );+ assert_eq!(asked(&server, CONSENT).await, 1);+ // The person presses Try Again straight away: the request already on their phone stands.+ assert_eq!(+ client.lock().await.data_access(true).await.unwrap(),+ DataAccess::Waiting+ );+ assert_eq!(+ asked(&server, CONSENT).await,+ 1,+ "not pushed twice within two minutes"+ );+}++/// Apple could not reach any of the person's devices.+#[tokio::test]+async fn an_approval_apple_could_not_send_is_said() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(false, 0))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(CONSENT))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "isDeviceConsentNotificationSent": false, "isWebAccessAllowed": true+ })))+ .mount(&server)+ .await;+ assert_eq!(client.data_access(true).await.unwrap(), DataAccess::NotSent);+}++/// A key Apple refused even though one was held (it let it go early): asked for again, and+/// "Cookies already present." is taken for what it says.+#[tokio::test]+async fn a_refused_key_is_asked_for_again_and_already_present_is_fine() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(true, in_an_hour_ms()))+ .mount(&server)+ .await;+ mount_keys(&server, 3600).await;+ assert_eq!(client.data_access(false).await.unwrap(), DataAccess::Open);+ let before = asked(&server, PCS).await;++ server.reset().await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(true, in_an_hour_ms()))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(PCS))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "isWebAccessAllowed": true, "isDeviceConsentedForPCS": true, "isICDRSDisabled": true,+ "message": "Cookies already present.", "status": "success"+ })))+ .mount(&server)+ .await;+ assert_eq!(before, 4);+ // Drive answered 423 "Missing PCS cookies" (quince_icloud::Error::NeedsDeviceApproval).+ client.data_access_lapsed("drive");+ assert_eq!(client.data_access_missing(), ["drive"]);+ assert_eq!(client.data_access(false).await.unwrap(), DataAccess::Open);+ let reqs = server.received_requests().await.unwrap();+ assert_eq!(+ app_names(&to(&reqs, PCS)),+ ["iclouddrive"],+ "only the refused one"+ );+ assert!(client.data_access_missing().is_empty());+}++/// Keys run out (Apple's hour): asked for again by themselves while the approval holds; once+/// it has run out too, a background pass says an approval is needed.+#[tokio::test]+async fn keys_that_run_out_are_asked_for_again() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(true, in_an_hour_ms()))+ .up_to_n_times(2)+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(false, 0))+ .mount(&server)+ .await;+ mount_keys(&server, 1).await;+ assert_eq!(client.data_access(false).await.unwrap(), DataAccess::Open);+ tokio::time::sleep(Duration::from_millis(2100)).await;+ assert_eq!(+ client.data_access_missing(),+ ["notes", "reminders", "photos", "drive"],+ "every key ran out with its cookies"+ );+ // The approval still holds: attached again, silently.+ assert_eq!(client.data_access(false).await.unwrap(), DataAccess::Open);+ assert_eq!(asked(&server, CONSENT).await, 0);+ assert_eq!(asked(&server, PCS).await, 8);+ // Then the approval runs out as well.+ tokio::time::sleep(Duration::from_millis(2100)).await;+ assert_eq!(client.data_access(false).await.unwrap(), DataAccess::Needed);+}++/// Apple busy or asking for fewer requests: "not now", typed, so the caller waits — never read+/// as a refusal, and never hammered.+#[tokio::test]+async fn throttling_and_outages_are_not_refusals() {+ for status in [429u16, 503] {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(ResponseTemplate::new(status))+ .mount(&server)+ .await;+ let got = client.data_access(true).await;+ assert!(+ matches!(got, Err(Error::Unavailable(s)) if s == status),+ "{status}: {got:?}"+ );+ assert_eq!(+ asked(&server, STATE).await,+ 1,+ "one request, no retry storm"+ );+ }+}++/// A session Apple wants signed back in first: typed as that, for the heartbeat to mend.+#[tokio::test]+async fn a_session_apple_will_not_release_keys_to_needs_a_sign_in() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(true, in_an_hour_ms()))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(PCS))+ .respond_with(ResponseTemplate::new(500).set_body_json(json!({+ "message": "Missing X-APPLE-WEBAUTH-TOKEN cookie", "status": "failure"+ })))+ .mount(&server)+ .await;+ assert!(matches!(+ client.data_access(false).await,+ Err(Error::ReauthRequired)+ ));++ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(ResponseTemplate::new(421))+ .mount(&server)+ .await;+ assert!(matches!(+ client.data_access(true).await,+ Err(Error::ReauthRequired)+ ));+}++/// Accounts Apple keeps from the web in its own way — a child's, a Managed Apple Account — or+/// answers it does not explain: a typed error in words, never a crash, never Apple's JSON.+#[tokio::test]+async fn an_account_apple_refuses_is_classified_not_crashed_on() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(ResponseTemplate::new(403).set_body_json(json!({+ "error": "ACCESS_DENIED", "reason": "managed account: [email protected]"+ })))+ .mount(&server)+ .await;+ match client.data_access(true).await {+ Err(Error::Protocol(words)) => {+ assert!(+ !words.contains("example.invalid"),+ "Apple's words stay out: {words}"+ );+ }+ other => panic!("{other:?}"),+ }++ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(true, in_an_hour_ms()))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(PCS))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "message": "Something new.", "status": "failure"+ })))+ .mount(&server)+ .await;+ assert!(matches!(+ client.data_access(false).await,+ Err(Error::Protocol(_))+ ));++ // Garbage, or nothing at all.+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(ResponseTemplate::new(200).set_body_string("<html>"))+ .mount(&server)+ .await;+ assert!(+ matches!(client.data_access(true).await, Err(Error::Protocol(_))),+ "an account that said it has Advanced Data Protection is not read as having none"+ );+ assert_eq!(asked(&server, CONSENT).await, 0);+}++/// Apple's "User has not disabled iCloud DRS": recovery is on after all, nothing to approve.+#[tokio::test]+async fn recovery_on_after_all_needs_nothing() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(true, in_an_hour_ms()))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(PCS))+ .respond_with(ResponseTemplate::new(412).set_body_json(json!({+ "message": "User has not disabled iCloud DRS", "status": "failure"+ })))+ .mount(&server)+ .await;+ assert_eq!(client.data_access(false).await.unwrap(), DataAccess::Open);+ assert!(client.data_access_missing().is_empty());+}++/// Apple said the key was attached and set nothing — a wrong app name: said, not taken as held.+#[tokio::test]+async fn success_with_no_key_is_not_taken_for_one() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(true, in_an_hour_ms()))+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path(PCS))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "message": "Cookies attached.", "status": "success"+ })))+ .mount(&server)+ .await;+ assert!(matches!(+ client.data_access(false).await,+ Err(Error::Protocol(_))+ ));+ assert!(client.data_access_missing().contains(&"photos"));+}++/// A refusal on an account that never said it had Advanced Data Protection: it does, and the+/// approval flow takes over.+#[tokio::test]+async fn a_refusal_on_an_account_that_never_said_turns_the_flow_on() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), STANDARD, false).await;+ assert!(client.data_access_missing().is_empty());+ client.data_access_lapsed("notes");+ assert_eq!(+ client.data_access_missing(),+ ["notes", "reminders", "photos", "drive"]+ );+ client.data_access_lapsed("calendar");+ assert!(+ !client.data_access_missing().contains(&"calendar"),+ "Calendar never needs one"+ );+}++/// Signing out forgets every key and approval.+#[tokio::test]+async fn signing_out_forgets_the_keys() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(true, in_an_hour_ms()))+ .mount(&server)+ .await;+ mount_keys(&server, 3600).await;+ assert_eq!(client.data_access(false).await.unwrap(), DataAccess::Open);+ client.sign_out().unwrap();+ assert!(client.session().pcs_until.is_empty());+ assert!(+ client.data_access_missing().is_empty(),+ "signed out: no services at all"+ );+}diff --git a/crates/quince-icloud/src/cloudkit.rs b/crates/quince-icloud/src/cloudkit.rsindex 5f9cbda..46c5933 100644--- a/crates/quince-icloud/src/cloudkit.rs+++ b/crates/quince-icloud/src/cloudkit.rs@@ -51,6 +51,9 @@ enum ZoneTrouble {Busy(Option<u64>),/// The session was not accepted for the zone: a fresh sign-in, not a fault in the zone.Unauthenticated,+ /// Advanced Data Protection keeps the zone from this session until it is approved on one+ /// of the person's devices (`ACCESS_DENIED`, "private db access disabled").+ Locked,/// Something else, which is worth showing to somebody.Other(&'static str),}@@ -60,6 +63,14 @@ fn trouble_with(zone_result: &Value) -> Option<ZoneTrouble> {let reason = zone_result.get("reason").and_then(Value::as_str);match code {Some("ZONE_NOT_FOUND") => Some(ZoneTrouble::Missing),+ Some("ACCESS_DENIED")+ if reason.is_some_and(|r| {+ r.to_ascii_lowercase()+ .contains("private db access disabled")+ }) =>+ {+ Some(ZoneTrouble::Locked)+ }// An expired change token, with or without a reason. Without this arm a bare// `CHANGE_TOKEN_EXPIRED` matched nothing below and read as an empty, finished page:// "nothing changed", on a token that would never be read again — every change made@@ -153,6 +164,12 @@ impl<'a> ZoneClient<'a> {.and_then(|v| v.to_str().ok()).and_then(|v| v.trim().parse::<u64>().ok());let text = response.text().await.unwrap_or_default();+ // Advanced Data Protection keeping this session out until it is approved on a+ // device (403 ACCESS_DENIED, "private db access disabled"): said as that, for every+ // CloudKit read and write, rather than as Apple's JSON.+ if !status.is_success() {+ crate::approval_needed(status, &text)?;+ }// A zone busy with another write answers 409 ZONE_BUSY — "rejected, retry", the// whole request not applied — measured when a phone and this app wrote at once.// Two of this app's own writes to one zone close together (notes deleted one after@@ -255,6 +272,7 @@ impl<'a> ZoneClient<'a> {Some(ZoneTrouble::StaleCursor) => return Err(Error::StaleCursor),Some(ZoneTrouble::Busy(asked)) => return Ok(Err(asked)),Some(ZoneTrouble::Unauthenticated) => return Err(Error::ReauthRequired),+ Some(ZoneTrouble::Locked) => return Err(Error::NeedsDeviceApproval),Some(ZoneTrouble::Other(_)) => {let reason = zone_result.get("reason")@@ -2020,6 +2038,60 @@ mod trouble_tests {.expect("refused");assert!(matches!(err, Error::ReauthRequired), "{code}: {err:?}");}+ /// Issue #4: an account with Advanced Data Protection, before its session is approved on+ /// a device. Said as that — typed, so the approval can be asked for and the zone read again+ /// once it is given — never as "iCloud sent back something unexpected" and Apple's JSON.+ #[tokio::test]+ async fn a_zone_kept_by_advanced_data_protection_asks_for_approval() {+ for (status, body) in [+ // As reported, at the HTTP level.+ (+ 403,+ json!({ "serverErrorCode": "ACCESS_DENIED",+ "reason": "private db access disabled for this account" }),+ ),+ // And inside the zone's own result, the way CloudKit answers most zone trouble.+ (+ 200,+ json!({ "zones": [{ "zoneID": { "zoneName": "Reminders" },+ "serverErrorCode": "ACCESS_DENIED",+ "reason": "private db access disabled for this account" }] }),+ ),+ ] {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path_regex(r".*/changes/zone"))+ .respond_with(ResponseTemplate::new(status).set_body_json(body))+ .mount(&server)+ .await;+ let http = reqwest::Client::new();+ let uri = server.uri();+ let client = client(&http, &uri, "com.apple.reminders");+ let err = client.all_records("Reminders", None).await.err();+ assert!(+ matches!(err, Some(Error::NeedsDeviceApproval)),+ "{status}: {err:?}"+ );+ }+ }++ /// ACCESS_DENIED for anything else — a retired endpoint says it too — is not read as+ /// Advanced Data Protection: approving on a phone would not help.+ #[tokio::test]+ async fn another_access_denied_is_not_read_as_advanced_data_protection() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path_regex(r".*/changes/zone"))+ .respond_with(zone_reply(json!({+ "serverErrorCode": "ACCESS_DENIED", "reason": "This endpoint is deprecated."+ })))+ .mount(&server)+ .await;+ let http = reqwest::Client::new();+ let uri = server.uri();+ let client = client(&http, &uri, "com.apple.reminders");+ let err = client.all_records("Reminders", None).await.err();+ assert!(matches!(err, Some(Error::Protocol(_))), "{err:?}");}/// CloudKit expires cursors. An app closed for a while comes back holding one Apple willdiff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rsindex edea7cb..0d69fe6 100644--- a/crates/quince-icloud/src/drive.rs+++ b/crates/quince-icloud/src/drive.rs@@ -131,6 +131,7 @@ pub async fn fetch_folder(return Err(Error::ReauthRequired);}if !status.is_success() {+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("Drive returned {status}: {}",text.chars().take(160).collect::<String>()@@ -202,6 +203,7 @@ async fn link(return Err(Error::ReauthRequired);}if !status.is_success() {+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("couldn't prepare a download ({status}): {}",text.chars().take(160).collect::<String>()@@ -486,6 +488,7 @@ pub async fn create_folder(return Err(Error::ReauthRequired);}if !status.is_success() {+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("Drive refused the folder ({status}): {}",text.chars().take(200).collect::<String>()@@ -532,6 +535,7 @@ async fn raw_listing(return Err(Error::ReauthRequired);}if !status.is_success() {+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("Drive returned {status}: {}",text.chars().take(160).collect::<String>()@@ -586,6 +590,7 @@ pub async fn rename(}if !status.is_success() {let text = response.text().await.unwrap_or_default();+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("Drive refused the rename ({status}): {}",text.chars().take(200).collect::<String>()@@ -756,6 +761,7 @@ async fn ask_for_copy(}if !status.is_success() {let text = response.text().await.unwrap_or_default();+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("Drive refused the copy ({status}): {}",text.chars().take(200).collect::<String>()@@ -838,10 +844,10 @@ pub async fn thumbnails(return Err(Error::ReauthRequired);}if !response.status().is_success() {- return Err(Error::Protocol(format!(- "thumbnails returned {}",- response.status()- )));+ let status = response.status();+ let text = response.text().await.unwrap_or_default();+ crate::approval_needed(status, &text)?;+ return Err(Error::Protocol(format!("thumbnails returned {status}")));}let answer: Value = response.json()@@ -917,6 +923,7 @@ pub async fn recents(}let text = response.text().await.unwrap_or_default();if !status.is_success() {+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("Drive returned {status}: {}",text.chars().take(160).collect::<String>()@@ -979,6 +986,7 @@ pub async fn trash_items(}let text = response.text().await.unwrap_or_default();if !status.is_success() {+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("Drive returned {status}: {}",text.chars().take(160).collect::<String>()@@ -1268,6 +1276,7 @@ pub async fn move_to(}if !status.is_success() {let text = response.text().await.unwrap_or_default();+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("Drive refused the move ({status}): {}",text.chars().take(200).collect::<String>()@@ -2803,6 +2812,7 @@ async fn upload_once(return Err(Error::Refused(BUSY.into()));}if !status.is_success() {+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("Apple would not take the file ({status}): {}",text.chars().take(160).collect::<String>()@@ -3049,6 +3059,7 @@ async fn post_json(return Err(Error::ReauthRequired);}if !status.is_success() {+ crate::approval_needed(status, &text)?;quiet!("drive: a request was refused ({status})");if status.as_u16() == 409 && text.contains("ZONE_BUSY") {return Err(Error::Refused(BUSY.into()));diff --git a/crates/quince-icloud/src/drive_changes.rs b/crates/quince-icloud/src/drive_changes.rsindex 79f4d8d..c668c25 100644--- a/crates/quince-icloud/src/drive_changes.rs+++ b/crates/quince-icloud/src/drive_changes.rs@@ -145,6 +145,7 @@ pub async fn page(}let text = response.text().await.unwrap_or_default();if !status.is_success() {+ crate::approval_needed(status, &text)?;if text.contains("CHANGE_TOKEN_EXPIRED") || status.as_u16() == 400 && token.is_some() {return Err(Error::StaleCursor);}@@ -205,6 +206,7 @@ pub async fn zones_moved(}let text = response.text().await.unwrap_or_default();if !status.is_success() {+ crate::approval_needed(status, &text)?;if text.contains("CHANGE_TOKEN_EXPIRED") || status.as_u16() == 400 && asked_with_token {return Err(Error::StaleCursor);}diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rsindex 99cd83b..02217ab 100644--- a/crates/quince-icloud/src/lib.rs+++ b/crates/quince-icloud/src/lib.rs@@ -47,6 +47,12 @@ pub enum Error {Protocol(String),#[error("this needs a fresh sign-in")]ReauthRequired,+ /// Advanced Data Protection holds this service's keys on the person's devices, and Apple+ /// releases them to a session only once it is approved on one of them (see+ /// `quince_auth::pcs`). Not a fault: the approval is asked for, and the service is read+ /// again once it is given.+ #[error("{APPROVAL_WORDS}")]+ NeedsDeviceApproval,#[error("this changed on another device first — refresh and try again")]Conflict,/// The zone was mid-write for someone else and the change was not applied; it is sent@@ -72,6 +78,37 @@ pub enum Error {pub type Result<T> = std::result::Result<T, Error>;+/// What [`Error::NeedsDeviceApproval`] says to the person.+pub const APPROVAL_WORDS: &str =+ "Approve Skykeep on your iPhone, iPad or Mac to open this. Advanced Data Protection keeps it end-to-end encrypted.";++/// Whether Apple turned a request down only because Advanced Data Protection is keeping the+/// service's keys from this session — the two answers it gives, measured on an account with+/// it on and "Access iCloud Data on the Web" allowed:+///+/// * iCloud Drive: `423 {"errorReason":"Missing PCS cookies from the request","errorCode":423}`+/// * CloudKit (Notes, Reminders, Photos): `403 {"serverErrorCode":"ACCESS_DENIED",+/// "reason":"private db access disabled for this account"}`, the same inside a zone's+/// own result at 200.+///+/// The words are matched, never the status alone: Apple also answers 423 when it is rate+/// limiting, and 403 ACCESS_DENIED for an endpoint it retired (`push`, `courier`).+#[must_use]+pub fn locked_by_data_protection(body: &str) -> bool {+ let lower = body.to_ascii_lowercase();+ lower.contains("missing pcs cookies")+ || (lower.contains("access_denied") && lower.contains("private db access disabled"))+}++/// [`Error::NeedsDeviceApproval`] for an answer [`locked_by_data_protection`] recognises.+pub(crate) fn approval_needed(status: reqwest::StatusCode, body: &str) -> Result<()> {+ if locked_by_data_protection(body) {+ quiet!("icloud: waiting for Advanced Data Protection approval ({status})");+ return Err(Error::NeedsDeviceApproval);+ }+ Ok(())+}+/// What went wrong reaching Apple, in words a person can act on — the address left out.fn network_words(e: &reqwest::Error) -> String {if e.is_timeout() {@@ -84,3 +121,45 @@ fn network_words(e: &reqwest::Error) -> String {"The connection to iCloud dropped. Try again.".into()}}++#[cfg(test)]+mod approval_tests {+ use super::*;++ #[test]+ fn the_two_answers_advanced_data_protection_gives_are_recognised() {+ // As issue #4 reported them, word for word.+ let drive = r#"{"errorReason":"Missing PCS cookies from the request","errorCode":423}"#;+ let cloudkit = r#"{ "serverErrorCode" : "ACCESS_DENIED", "reason" : "private db access disabled for this account" }"#;+ assert!(locked_by_data_protection(drive));+ assert!(locked_by_data_protection(cloudkit));+ // Inside a zone's own result, which CloudKit answers at 200.+ assert!(locked_by_data_protection(&format!(+ r#"{{"zones":[{cloudkit}]}}"#+ )));+ assert!(matches!(+ approval_needed(reqwest::StatusCode::LOCKED, drive),+ Err(Error::NeedsDeviceApproval)+ ));+ assert!(matches!(+ approval_needed(reqwest::StatusCode::FORBIDDEN, cloudkit),+ Err(Error::NeedsDeviceApproval)+ ));+ assert_eq!(Error::NeedsDeviceApproval.to_string(), APPROVAL_WORDS);+ }++ #[test]+ fn look_alikes_are_not_read_as_advanced_data_protection() {+ // 423 is also how Apple says "too many requests"; ACCESS_DENIED is also what a retired+ // endpoint answers.+ assert!(!locked_by_data_protection(""));+ assert!(!locked_by_data_protection(r#"{"error":"Locked"}"#));+ assert!(!locked_by_data_protection(+ r#"{"serverErrorCode":"ACCESS_DENIED","reason":"This endpoint is deprecated."}"#+ ));+ assert!(!locked_by_data_protection(+ "<html>Service Unavailable</html>"+ ));+ assert!(approval_needed(reqwest::StatusCode::LOCKED, "{}").is_ok());+ }+}diff --git a/crates/quince-icloud/src/notes_attach.rs b/crates/quince-icloud/src/notes_attach.rsindex fe0e46c..baf2a57 100644--- a/crates/quince-icloud/src/notes_attach.rs+++ b/crates/quince-icloud/src/notes_attach.rs@@ -343,6 +343,7 @@ async fn post(continue;}if !status.is_success() {+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("CloudKit refused it ({status}): {}",text.chars().take(200).collect::<String>()diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rsindex 1a201b1..cd3b7b3 100644--- a/crates/quince-icloud/src/reminders.rs+++ b/crates/quince-icloud/src/reminders.rs@@ -221,6 +221,7 @@ pub async fn set_completed(}if !status.is_success() {let text = response.text().await.unwrap_or_default();+ crate::approval_needed(status, &text)?;return Err(Error::Protocol(format!("couldn't update that reminder ({status}): {}",text.chars().take(160).collect::<String>()diff --git a/src-tauri/src/data_access.rs b/src-tauri/src/data_access.rsnew file mode 100644index 0000000..ba17c50--- /dev/null+++ b/src-tauri/src/data_access.rs@@ -0,0 +1,324 @@+//! Advanced Data Protection approvals, followed for the window (see `quince_auth::pcs`).+//!+//! An account with Advanced Data Protection and "Access iCloud Data on the Web" on lets this+//! session read Notes, Reminders, Photos and iCloud Drive only once the person approves it on+//! one of their devices, and for about an hour at a time. Here that is asked for, followed and+//! told: the approval is put on their devices when they sign in or open a window — at most once+//! a lapse unless they ask again — and never by a background pass; while it is on its way the+//! client is taken only for each step, so nothing else waits behind it; and once it is given,+//! the services that were waiting on it are read at once.++use crate::Auth;+use quince_auth::pcs::{self, DataAccess};+use quince_auth::Client;+use serde::Serialize;+use std::collections::BTreeSet;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use tauri::{Emitter, Manager};+use tokio::sync::Mutex;++/// Told to every window when where the approval stands changes.+pub const EVENT: &str = "quince://data-access";++/// Where the approval stands, as the window shows it.+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Access {+ pub state: DataAccess,+ /// The services waiting on it, by the app's names; empty when `state` is `open`.+ pub services: Vec<&'static str>,+ /// Why the last step failed, in words, when it did.+ pub problem: Option<String>,+}++impl Access {+ const OPEN: Access = Access {+ state: DataAccess::Open,+ services: Vec::new(),+ problem: None,+ };+}++static NOW: std::sync::Mutex<Access> = std::sync::Mutex::new(Access::OPEN);+/// An approval is being followed: a second follower would only double the requests.+static FOLLOWING: AtomicBool = AtomicBool::new(false);+/// The approval was put on the person's devices without their asking, this lapse: not again+/// until access opens or they ask.+static ASKED_UNASKED: AtomicBool = AtomicBool::new(false);+/// Services a pass found refused for want of their key, for the next step to ask for again.+static REFUSED: std::sync::Mutex<BTreeSet<&'static str>> = std::sync::Mutex::new(BTreeSet::new());++/// Who is asking for a step, which decides whether it may put a prompt on the person's phone.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Ask {+ /// The person, from the prompt's button: always.+ Person,+ /// A sign-in, or a window opening or coming back: once a lapse.+ Window,+ /// A background pass: never.+ Background,+}++/// Where it stands now.+pub fn current() -> Access {+ NOW.lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clone()+}++/// A new sign-in, or a sign-out: nothing from the session before carries over — its approval,+/// its refusals, or that it already asked once.+pub fn forget(app: &tauri::AppHandle) {+ ASKED_UNASKED.store(false, Ordering::SeqCst);+ REFUSED+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clear();+ set(app, Access::OPEN);+}++/// A pass found `service` refused by Advanced Data Protection.+pub fn refused(service: &'static str) {+ REFUSED+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .insert(service);+}++fn set(app: &tauri::AppHandle, next: Access) {+ let changed = {+ let mut now = NOW+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let changed = *now != next;+ *now = next.clone();+ changed+ };+ if changed {+ app.emit(EVENT, next).ok();+ }+}++/// Whether this step may ask the person's devices.+fn may_ask(ask: Ask) -> bool {+ match ask {+ Ask::Person => true,+ Ask::Window => !ASKED_UNASKED.swap(true, Ordering::SeqCst),+ Ask::Background => false,+ }+}++/// Take one step, tell the window, and follow an approval that is on its way.+pub async fn check(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>, ask: Ask) {+ let (step, missing) = {+ let mut guard = client.lock().await;+ if guard.session().webservices.is_none() {+ return;+ }+ for service in std::mem::take(+ &mut *REFUSED+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner),+ ) {+ guard.data_access_lapsed(service);+ }+ let missing = guard.data_access_missing();+ if missing.is_empty() && guard.session().web_access_allowed != Some(false) {+ (Ok(DataAccess::Open), missing)+ } else {+ let asking = may_ask(ask);+ let step = guard.data_access(asking).await;+ (step, guard.data_access_missing())+ }+ };+ settle(app, client, step, missing, ask);+}++/// After a pass: when Advanced Data Protection kept a service out, the step that asks for its+/// key again — at once, so the window says so rather than the service's failure alone.+pub async fn after_pass(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>, ask: Ask) {+ let any = !REFUSED+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .is_empty();+ if any {+ check(app, client, ask).await;+ }+}++/// What one step came to, told; an approval on its way followed until it lands.+fn settle(+ app: &tauri::AppHandle,+ client: &Arc<Mutex<Client>>,+ step: Result<DataAccess, quince_auth::Error>,+ waiting_on: Vec<&'static str>,+ ask: Ask,+) {+ let was = current();+ match step {+ Ok(DataAccess::Open) => opened(app, client, &was),+ Ok(DataAccess::Waiting) => {+ set(+ app,+ Access {+ state: DataAccess::Waiting,+ services: waiting_on.clone(),+ problem: None,+ },+ );+ follow(app.clone(), Arc::clone(client), waiting_on);+ }+ Ok(state) => set(+ app,+ Access {+ state,+ services: waiting_on,+ problem: None,+ },+ ),+ // Not reached, or Apple busy: nothing is known to have changed. Said only when the+ // person asked; a background pass simply tries again next time.+ Err(e @ (quince_auth::Error::Network(_) | quince_auth::Error::Unavailable(_))) => {+ if ask == Ask::Person {+ set(+ app,+ Access {+ problem: Some(e.to_string()),+ ..was+ },+ );+ }+ }+ Err(e) => {+ quiet!("data access: {e:?}");+ set(+ app,+ Access {+ state: DataAccess::Needed,+ services: waiting_on,+ problem: Some(e.to_string()),+ },+ );+ }+ }+}++/// Every key is here (or none was ever needed): said, and what was waiting on it read now.+fn opened(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>, was: &Access) {+ ASKED_UNASKED.store(false, Ordering::SeqCst);+ set(app, Access::OPEN);+ if was.state == DataAccess::Open || was.services.is_empty() {+ return;+ }+ let services = was.services.clone();+ let app = app.clone();+ let client = Arc::clone(client);+ tauri::async_runtime::spawn(async move {+ let data = app.state::<crate::Data>();+ crate::refresh::some(&client, &data.0, &services).await;+ crate::alerts::changed();+ let mut status = crate::refresh::status(&data.0).await;+ status.changed = Some(Vec::new());+ app.emit(crate::SYNCED, status).ok();+ });+}++/// Follow an approval on its way, one step at a time on [`pcs::APPROVAL_SCHEDULE`], taking the+/// client only for each step.+fn follow(app: tauri::AppHandle, client: Arc<Mutex<Client>>, waiting_on: Vec<&'static str>) {+ if FOLLOWING.swap(true, Ordering::SeqCst) {+ return;+ }+ tauri::async_runtime::spawn(async move {+ let stepping = Arc::clone(&client);+ let landed = pcs::follow(pcs::APPROVAL_SCHEDULE, || {+ let client = Arc::clone(&stepping);+ async move {+ let mut guard = client.lock().await;+ if guard.session().webservices.is_none() {+ // Signed out while it was on its way: nothing left to follow.+ return Ok(DataAccess::Open);+ }+ match guard.data_access(false).await {+ // A dropped connection or a busy Apple is waited out like any other step;+ // the schedule still bounds how long.+ Err(quince_auth::Error::Network(_) | quince_auth::Error::Unavailable(_)) => {+ Ok(DataAccess::Waiting)+ }+ other => other,+ }+ }+ })+ .await;+ FOLLOWING.store(false, Ordering::SeqCst);+ let still = client.lock().await.data_access_missing();+ let waiting_on = if still.is_empty() { waiting_on } else { still };+ settle(&app, &client, landed, waiting_on, Ask::Background);+ });+}++/// Where the approval stands, for a window opening.+#[tauri::command]+pub async fn data_access_status() -> Result<Access, String> {+ Ok(current())+}++/// The person asked: put the approval on their devices again, and follow it.+#[tauri::command]+pub async fn data_access_ask(+ app: tauri::AppHandle,+ auth: tauri::State<'_, Auth>,+) -> Result<Access, String> {+ check(&app, &auth.client, Ask::Person).await;+ Ok(current())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_background_pass_never_puts_a_prompt_on_the_phone() {+ assert!(!may_ask(Ask::Background));+ assert!(may_ask(Ask::Person));+ }++ #[test]+ fn a_window_asks_once_a_lapse_and_the_person_whenever_they_like() {+ ASKED_UNASKED.store(false, Ordering::SeqCst);+ assert!(may_ask(Ask::Window), "the first window asks");+ assert!(+ !may_ask(Ask::Window),+ "the next ones do not, until access opens"+ );+ assert!(may_ask(Ask::Person), "the person's own ask always goes");+ ASKED_UNASKED.store(false, Ordering::SeqCst);+ assert!(+ may_ask(Ask::Window),+ "after access opened, the next lapse asks again"+ );+ }++ #[test]+ fn the_window_reads_it_in_its_own_words() {+ let told = serde_json::to_value(Access {+ state: DataAccess::Waiting,+ services: vec!["notes", "drive"],+ problem: None,+ })+ .unwrap();+ assert_eq!(+ told,+ serde_json::json!({ "state": "waiting", "services": ["notes", "drive"], "problem": null })+ );+ assert_eq!(+ serde_json::to_value(DataAccess::WebAccessOff).unwrap(),+ "webAccessOff"+ );+ assert_eq!(+ serde_json::to_value(DataAccess::NotSent).unwrap(),+ "notSent"+ );+ }+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 1cc4c95..1eb1ede 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -19,6 +19,7 @@ mod clipboard;mod contacts_cmds;mod contacts_merge;mod cpu;+mod data_access;mod drive_watch;mod export;mod grants;@@ -1348,7 +1349,13 @@ async fn keep_signed_in(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>) {);}}- Ok(true) => TOLD.store(false, std::sync::atomic::Ordering::Relaxed),+ Ok(true) => {+ TOLD.store(false, std::sync::atomic::Ordering::Relaxed);+ // 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);+ data_access::check(app, client, data_access::Ask::Background).await;+ }// New iCloud terms to accept: nothing syncs until they are, and only icloud.com can// take them. Said with its reason, where "Apple signed you out" would be untrue.Err(e @ quince_auth::Error::TermsPending) => {@@ -1696,6 +1703,15 @@ async fn signed_in(app: &tauri::AppHandle, client: &mut Client) -> Result<(), St.known.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = SessionFacts::of(client);+ // Under Advanced Data Protection, Notes, Reminders, Photos and iCloud Drive wait on an+ // approval on the person's devices: asked for now, as they sign in or open Skykeep —+ // once the caller has let the session go, which this step takes for itself.+ data_access::forget(app);+ let app = app.clone();+ let client = Arc::clone(&auth.client);+ tauri::async_runtime::spawn(async move {+ data_access::check(&app, &client, data_access::Ask::Window).await;+ });}Ok(())}@@ -1942,6 +1958,7 @@ async fn auth_sign_out(keep: bool, app: tauri::AppHandle, auth: State<'_, Auth>).map_err(|e| e.to_string())?;let mut client = auth.client.lock().await;client.sign_out().map_err(|e| e.to_string())?;+ data_access::forget(&app);if !keep {let data = app.state::<Data>();let mut library = data.0.lock().await;@@ -5421,6 +5438,7 @@ async fn sync_all(let client = Arc::clone(&auth.client);keep_signed_in(&app, &client).await;let result = refresh::all(&client, &data.0).await;+ data_access::after_pass(&app, &client, data_access::Ask::Window).await;alerts::changed();warm_contact_photos(app.clone());// Screens read the library, not the network, so they only need to be told to look again —@@ -5445,6 +5463,7 @@ async fn sync_some(keep_signed_in(&app, &client).await;let names: Vec<&str> = services.iter().map(String::as_str).collect();let result = refresh::some(&client, &data.0, &names).await;+ data_access::after_pass(&app, &client, data_access::Ask::Window).await;alerts::changed();if names.contains(&"contacts") {warm_contact_photos(app.clone());@@ -5476,6 +5495,7 @@ fn spawn_auto_sync(app: tauri::AppHandle, client: Arc<Mutex<Client>>) {keep_signed_in(&app, &client).await;let data = app.state::<Data>();let result = refresh::all(&client, &data.0).await;+ data_access::after_pass(&app, &client, data_access::Ask::Background).await;alerts::changed();warm_contact_photos(app.clone());app.emit(SYNCED, told(&result)).ok();@@ -6841,6 +6861,8 @@ fn main() {Ok(())}).invoke_handler(tauri::generate_handler![+ data_access::data_access_status,+ data_access::data_access_ask,grants::pick_open,grants::pick_save,export::library_export_start,diff --git a/src-tauri/src/outbox.rs b/src-tauri/src/outbox.rsindex 04a5aa7..5b43386 100644--- a/src-tauri/src/outbox.rs+++ b/src-tauri/src/outbox.rs@@ -1217,6 +1217,7 @@ fn transient(e: &Error, tries: i64) -> bool {| Error::ReauthRequired| Error::StaleCursor| Error::Busy+ | Error::NeedsDeviceApproval| Error::Io(_)| Error::Storage(_) => true,Error::Protocol(_) | Error::Conflict => tries < PROTOCOL_TRIES,diff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rsindex 9457d32..8a0c0b4 100644--- a/src-tauri/src/refresh.rs+++ b/src-tauri/src/refresh.rs@@ -848,6 +848,11 @@ whereitems: if changed { items } else { None },},Err(e) => {+ // Advanced Data Protection keeping it out: the approval is asked for after the pass,+ // and the service read again once it is given (`data_access`).+ if matches!(e, quince_icloud::Error::NeedsDeviceApproval) {+ crate::data_access::refused(service);+ }let message = e.to_string();library.mark_sync_failed(service, &message).ok();ServiceReport {diff --git a/src/components/DeviceApproval.tsx b/src/components/DeviceApproval.tsxnew file mode 100644index 0000000..2ff2923--- /dev/null+++ b/src/components/DeviceApproval.tsx@@ -0,0 +1,122 @@+import { useLayoutEffect, useRef, useState } from "react";+import { Smartphone } from "lucide-react";+import { fadeIn } from "../lib/fade";+import { api, messageOf, type DataAccess } from "../lib/ipc";+import { Spinner } from "./Spinner";++/** What each service is called on screen. */+const NAMES: Record<string, string> = {+ notes: "Notes",+ reminders: "Reminders",+ photos: "Photos",+ drive: "iCloud Drive",+};++/** The states in which a service waits on an approval on the person's devices. */+export function awaitsApproval(access: DataAccess | null, service: string): boolean {+ return Boolean(+ access && (access.state === "waiting" || access.state === "needed" || access.state === "notSent") && access.services.includes(service),+ );+}++/** Ask Apple again, saying what came back or why it could not be asked. */+function useAsk(onAccess: (a: DataAccess) => void) {+ const [asking, setAsking] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const ask = () => {+ setAsking(true);+ setError(null);+ api+ .dataAccessAsk()+ .then(onAccess, (e) => setError(messageOf(e)))+ .finally(() => setAsking(false));+ };+ return { ask, asking, error };+}++/** The line under the heading: where the approval stands. */+function standing(access: DataAccess): string {+ if (access.state === "notSent") {+ return "Apple couldn’t reach your devices. Check that your iPhone, iPad or Mac is on and connected, then try again.";+ }+ if (access.state === "waiting") return "Waiting for your iPhone, iPad or Mac…";+ return "Click Try Again, then approve on your iPhone, iPad or Mac.";+}++/**+ * Advanced Data Protection keeps this service end-to-end encrypted, and Apple opens it to+ * Skykeep once the person approves on one of their devices. Drawn in place of a screen that has+ * nothing on this computer yet, in the same calm layout as the web-access screen beside it.+ */+export function ApprovalScreen({+ access,+ service,+ onAccess,+}: {+ access: DataAccess;+ service: string;+ onAccess: (a: DataAccess) => void;+}) {+ const { ask, asking, error } = useAsk(onAccess);+ const name = NAMES[service] ?? "this";+ const waiting = access.state === "waiting";+ const problem = error ?? access.problem;+ return (+ <div className="web-access-off device-approval">+ <Smartphone className="device-approval-glyph" size={30} strokeWidth={1.6} aria-hidden="true" />+ <h1>Approve on your iPhone, iPad or Mac</h1>+ <p>+ Your Apple Account uses Advanced Data Protection, which keeps {name} end-to-end encrypted. Once you+ approve Skykeep on one of your devices, it opens here.+ </p>+ <p className="device-approval-status" role="status" aria-live="polite">+ {waiting && <Spinner small />}+ <span>{problem ?? standing(access)}</span>+ </p>+ <button className="primary" onClick={ask} disabled={asking}>+ Try Again+ </button>+ </div>+ );+}++/**+ * The same, for a screen that already has its copy on this computer: the screen stays, and+ * one card at the foot of the content says what would bring it up to date.+ */+export function ApprovalNotice({+ access,+ service,+ onAccess,+}: {+ access: DataAccess;+ service: string;+ onAccess: (a: DataAccess) => void;+}) {+ const { ask, asking, error } = useAsk(onAccess);+ const card = useRef<HTMLDivElement>(null);+ useLayoutEffect(() => fadeIn(card.current, { duration: 140 }), []);+ const name = NAMES[service] ?? "this";+ const waiting = access.state === "waiting";+ const problem = error ?? access.problem;+ return (+ <div ref={card} className="toast update-notice device-approval-notice" role="group" aria-label="Approve on your devices">+ {waiting ? <Spinner small /> : <Smartphone className="toast-glyph" size={15} strokeWidth={2} aria-hidden="true" />}+ <div className="update-body">+ <p className="update-line" role="status" aria-live="polite">+ {problem ??+ (waiting+ ? `Approve Skykeep on your iPhone, iPad or Mac to bring ${name} up to date.`+ : `To bring ${name} up to date, approve Skykeep on your iPhone, iPad or Mac.`)}+ </p>+ {!waiting && (+ <div className="update-actions">+ <button className="toast-action" onClick={ask} disabled={asking}>+ Try Again+ </button>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 5245bba..989ee6b 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -115,6 +115,23 @@ export const OPEN_REMINDER = "quince://open-reminder";export const NEEDS_CODE = "quince://needs-code";/** Apple signed the session out and wants the password again. */export const NEEDS_SIGNIN = "quince://needs-signin";+/** Where an Advanced Data Protection approval stands changed (`DataAccess`). */+export const DATA_ACCESS = "quince://data-access";++/**+ * Advanced Data Protection: whether this session may read the end-to-end encrypted services+ * yet. `open` — nothing waits on an approval; `waiting` — the approval is on the person's+ * devices, or given and the keys on their way; `needed` — one is needed and none is on its+ * way; `notSent` — Apple couldn't put it on any of their devices; `webAccessOff` — "Access+ * iCloud Data on the Web" is off.+ */+export type DataAccess = {+ state: "open" | "waiting" | "needed" | "notSent" | "webAccessOff";+ /** The services waiting on it: `notes`, `reminders`, `photos`, `drive`. */+ services: string[];+ /** Why the last step failed, in words, when it did. */+ problem: string | null;+};export const api = {/** One refresh for every service. Never rejects for a single service failing. */@@ -431,6 +448,10 @@ export const api = {storageInfo: () => invoke<{ usedBytes: number; totalBytes: number }>("storage_info"),/** Who is signed in, as Apple names them. */accountInfo: () => invoke<AccountInfo>("account_info"),+ /** 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. */+ dataAccessAsk: () => invoke<DataAccess>("data_access_ask"),/** Settings' switches, as the backend obeys them. *//** Write a plain diagnostic report to Downloads; answers where. Nothing is sent anywhere. */diagnosticsSave: () => invoke<string>("diagnostics_save"),diff --git a/src/screens/Library.tsx b/src/screens/Library.tsxindex 6d79043..04a4617 100644--- a/src/screens/Library.tsx+++ b/src/screens/Library.tsx@@ -6,7 +6,8 @@ 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, messageOf, NEW_EVENT, OPEN_REMINDER } from "../lib/ipc";+import { api, DATA_ACCESS, messageOf, NEW_EVENT, OPEN_REMINDER, type DataAccess } from "../lib/ipc";+import { ApprovalNotice, ApprovalScreen, awaitsApproval } from "../components/DeviceApproval";import { SyncProvider, useSync } from "../lib/sync";import { AccountCard } from "../components/Account";import { reveal, type Reveal } from "../lib/reveal";@@ -292,6 +293,30 @@ export function Library({ onSignOut, onShown }: { onSignOut: (keep: boolean) =>api.accountInfo().then((a) => setWebAccess(a?.webAccessAllowed ?? null), () => {});}, []);+ /** Advanced Data Protection: which services wait on an approval on the person's devices. */+ const [access, setAccess] = useState<DataAccess | null>(null);+ useEffect(() => {+ let live = true;+ api.dataAccess().then((a) => live && setAccess(a), () => {});+ const off = listen<DataAccess>(DATA_ACCESS, (e) => setAccess(e.payload));+ return () => {+ live = false;+ void off.then((f) => f());+ };+ }, []);+ // Apple saying web access is off, as the session found it, is the same screen as at sign-in.+ useEffect(() => {+ if (access?.state === "webAccessOff") setWebAccess(false);+ }, [access]);+ /** Which services already have their copy on this computer, while an approval is awaited. */+ const [held, setHeld] = useState<Record<string, boolean>>({});+ useEffect(() => {+ if (!access || access.state === "open") return;+ api+ .syncStatus()+ .then((r) => setHeld(Object.fromEntries(r.services.map((s) => [s.service, Boolean(s.lastSyncedAt)]))), () => {});+ }, [access]);+useEffect(() => {api.services()@@ -352,7 +377,14 @@ export function Library({ onSignOut, onShown }: { onSignOut: (keep: boolean) =>told.current = true;onShownRef.current?.();}, []);- const noScreen = Boolean(error) || (ready && (!selected || webAccess === false));+ /**+ * The screen in front waits on an approval: drawn in its place when there is nothing of it on+ * this computer yet, or as a card over it when there is — its copy stays readable meanwhile.+ */+ 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"));useEffect(() => {if (noScreen) drawn();}, [noScreen, drawn]);@@ -627,8 +659,11 @@ export function Library({ onSignOut, onShown }: { onSignOut: (keep: boolean) =>coming back is instant, and finds it as it was left — its place, itsselection, its scroll — as a Mac app's windows are. Out of sight it is inert,draws no menus and answers no keys (lib/screen). */}+ {approval === "screen" && access && frontService && (+ <ApprovalScreen access={access} service={frontService} onAccess={setAccess} />+ )}{kept.map((key) => {- const on = key === selected;+ const on = key === selected && approval !== "screen";return (<div key={key} className="screen-slot" hidden={!on} {...(on ? {} : { inert: "" })}><ScreenActive.Provider value={on}>@@ -652,6 +687,9 @@ export function Library({ onSignOut, onShown }: { onSignOut: (keep: boolean) =>)}</main><ToastHost>+ {approval === "notice" && access && frontService && (+ <ApprovalNotice access={access} service={frontService} onAccess={setAccess} />+ )}<UpdateNotice /></ToastHost></div>diff --git a/src/styles/app.css b/src/styles/app.cssindex 2077ac0..b5d352b 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -1721,6 +1721,12 @@.web-access-off h1 { font-size: var(--t-22); font-weight: 700; margin: 0 0 12px; }.web-access-off p { color: var(--text-2); font-size: var(--t-15); line-height: 1.5; margin: 0 0 12px; }.web-access-off b { color: var(--text); font-weight: 600; }+/* Advanced Data Protection waiting on an approval (components/DeviceApproval): the same calm+ page, with the device it is waiting on above it and where it stands under it. */+.device-approval-glyph { display: block; margin: 0 auto 14px; color: var(--accent); }+.web-access-off .device-approval-status { display: flex; align-items: center; justify-content: center; gap: 8px;+ min-height: 1.5em; color: var(--text-2); font-size: var(--t-13); margin: 4px 0 18px; }+.device-approval-notice .spinner { flex: none; margin-top: 2px; }/* A new folder in the grid, named as Finder names one: the field fits its cell under theicon, its text centred. At the field's own width it overflowed the 112px cell and was cut