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: approvals only when the person acts, one for every service
Yashwanth Kamireddi2116779da810
diff --git a/.uiverify/device-approval.mjs b/.uiverify/device-approval.mjsindex e263443..f1c6ee2 100644--- a/.uiverify/device-approval.mjs+++ b/.uiverify/device-approval.mjs@@ -1,8 +1,11 @@-// 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.+// Advanced Data Protection (issue #4): Notes, Reminders, Photos and iCloud Drive sync only for a+// while after the person approves Skykeep on one of their devices, and every approval puts a+// notice on those devices — so nothing but the person asks for one. A screen with nothing on+// this computer yet is replaced by one calm page saying so, with Sync Now; a screen that has+// its copy here keeps it, readable, with one card at the foot saying how it syncs and when it+// last did. Calendar and Contacts are never held up. Once approved, it all goes by itself;+// with web access off, the existing page shows. The window's own passes never ask for an+// approval; Sync Now does.import { engine } from "./engine.mjs";import { SERVICES, installStub, openScreen } from "./stub.mjs";const BASE = process.env.BASE ?? process.env.URL ?? "http://localhost:4173";@@ -11,6 +14,7 @@ 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";+const EVERY = "Notes, Reminders, iCloud Drive and Photos";async function open(access, afterAsk) {const ctx = await b.newContext({ viewport: { width: 1180, height: 820 } });@@ -18,6 +22,12 @@ async function open(access, afterAsk) {await ctx.addInitScript(({ access, afterAsk }) => {window.__dataAccess = access;window.__dataAccessAfterAsk = afterAsk;+ // Every pass the window asks for, and whether the person asked for it.+ const inner = window.__TAURI_INTERNALS__.invoke;+ window.__TAURI_INTERNALS__.invoke = async (cmd, args) => {+ if (cmd === "sync_all" || cmd === "sync_some") (window.__passes ??= []).push(Boolean(args?.asked));+ return inner(cmd, args);+ };}, { access, afterAsk });const page = await ctx.newPage();await page.goto(BASE, { waitUntil: "networkidle" });@@ -30,14 +40,15 @@ 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 });+ ok((await page.evaluate(() => window.__passes ?? [])).every((asked) => !asked), "the window's own passes never ask for an approval");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(`Advanced Data Protection is on, so Skykeep syncs ${EVERY} when you approve it on one of your devices.`), "it says how syncing works under Advanced Data Protection");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.getByRole("button", { name: "Sync Now" }).isVisible(), "and Sync Now");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.@@ -63,26 +74,29 @@ const heading = (page) => page.getByRole("heading", { name: HEADING });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();+ ok(await card.isVisible(), "a card at the foot says how it syncs");+ const said = await card.innerText();+ ok(said.includes(`Advanced Data Protection is on, so Skykeep syncs ${EVERY} when you approve on your iPhone, iPad or Mac. Your copy here stays available in between.`), "in plain words");+ ok(/Updated (just now|\d+ min ago)/.test(said), "and when it last synced");+ ok((await page.evaluate(() => window.__dataAccessAsks ?? 0)) === 0, "nothing is asked until the person asks");+ await card.getByRole("button", { name: "Sync Now" }).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");+ ok((await page.evaluate(() => window.__dataAccessAsks)) === 1, "Sync Now asks Apple once");+ ok((await card.innerText()).includes(`Approve on your iPhone, iPad or Mac to sync ${EVERY}.`), "and the card then says to approve");+ ok(!(await card.getByRole("button", { name: "Sync Now" }).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.+// Apple couldn't reach any of the person's devices; then, Sync Now 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.getByRole("button", { name: "Sync Now" }).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");+ ok((await page.locator(".device-approval").innerText()).includes("Waiting for your iPhone, iPad or Mac…"), "Sync Now puts it on its way");// A service not waiting on it opens as usual.await openScreen(page, "Notes");await page.waitForTimeout(200);@@ -90,6 +104,16 @@ const heading = (page) => page.getByRole("heading", { name: HEADING });await ctx.close();}+// The person's own refresh is the one pass that may ask for an approval.+{+ const { ctx, page } = await open({ state: "needed", services: ALL, problem: null });+ await page.evaluate(() => { window.__passes = []; });+ await page.locator(".sidebar-sync").click();+ await page.waitForTimeout(300);+ ok(JSON.stringify(await page.evaluate(() => window.__passes)) === "[true]", "the sync button's pass is the person asking");+ 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 });@@ -107,8 +131,8 @@ const heading = (page) => page.getByRole("heading", { name: HEADING });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 page.getByRole("button", { name: "Sync Now" }).focus();+ ok(await page.evaluate(() => document.activeElement?.textContent === "Sync Now"), "Sync Now takes focus");await ctx.close();}diff --git a/SECURITY.md b/SECURITY.mdindex 5b28033..48f80c8 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -134,13 +134,15 @@ plainly 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 oneicloud.com uses (`crates/quince-auth/src/pcs.rs`). Calendar and Contacts work as usual. ForNotes, 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.+your trusted iPhone, iPad or Mac. It asks only when you act: when you sign in, or when you+press Sync Now. It never asks from a background sync, a window opening or the timer. One+approval covers all four services, which Skykeep asks for one after another.+Once you approve, Apple's servers have that device send each service's key to this session,+and your devices show that they did. 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. Skykeep stops syncing those four services when the approval or+its keys run out, whichever comes first. Your copy on this computer stays readable, and+changes you make wait in the queue until you approve again.Skykeep never sees your device keys. It never approves anything for you, and it never turnsAdvanced Data Protection or any other Apple setting on or off. Health data and passwords indiff --git a/crates/quince-auth/src/pcs.rs b/crates/quince-auth/src/pcs.rsindex e15b52e..27b600a 100644--- a/crates/quince-auth/src/pcs.rs+++ b/crates/quince-auth/src/pcs.rs@@ -164,9 +164,6 @@ where/// 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@@ -175,9 +172,6 @@ pub(crate) struct Pcs {/// 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.@@ -202,13 +196,6 @@ impl Client {if self.session.web_access_allowed == Some(false) || self.waits_on_icloud_com() {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)@@ -220,8 +207,9 @@ impl Client {/// 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;+ // Apple's own refusal is proof the account has Advanced Data Protection, whatever its+ // flags said (iCDPEnabled can read false with it on: rclone#9658).+ self.session.data_protection_seen = Some(true);self.pcs.stale.insert(p.service);self.session.pcs_until.remove(p.app_name);}@@ -235,22 +223,31 @@ impl Client {..Pcs::default()};self.session.pcs_until.clear();+ // Perhaps another account: what Apple showed of the last one says nothing of this one.+ self.session.data_protection_seen = None;+ }++ /// Whether this account has Advanced Data Protection in effect, on evidence: Apple's own+ /// word from `requestWebAccessState` or a refusal for want of a key, which outrank the+ /// sign-in's `iCDPEnabled`. `pcsRequired` alone is not evidence (icloudpy#214): an account+ /// without ADP can carry it, and reading it as ADP held such an account's Notes back.+ fn data_protection_on(&self) -> bool {+ match self.session.data_protection_seen {+ Some(seen) => seen,+ None => self.session.data_protection == Some(true),+ }}- /// 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.+ /// The protected services Apple offers this account, when it has Advanced Data Protection.fn protected_here(&self) -> impl Iterator<Item = &'static Protected> + '_ {- let adp = self.session.data_protection == Some(true) || self.pcs.seen_locked;+ let adp = self.data_protection_on();PROTECTED.iter().filter(move |p| {- let Some(ws) = self+ adp && 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)+ .is_some()})}@@ -260,13 +257,19 @@ impl Client {return false;}let now = crate::unix_now();+ // Every key is held only until the time recorded when it arrived — its cookie's+ // expiry, the approval's, and Apple's hour, whichever is first — so a pass stops asking+ // for the service before Apple would refuse it, never after.let recorded = self.session.pcs_until.get(p.app_name).is_some_and(|until| *until > now);+ if !recorded {+ return false;+ }if p.cookies.is_empty() {- return recorded;+ return true;}let jar = self.jar@@ -276,26 +279,46 @@ impl Client {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.+ /// When the keys just attached run out: whichever comes first of the earliest PCS cookie's+ /// expiry, the approval's (`deviceConsentForPCSExpiry`) and Apple's hour from now — the+ /// hour Apple's security guide gives an approval, and what people report seeing.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()+ let cookie = 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)+ .min();+ [cookie, consent_until, Some(now + KEY_HOUR)]+ .into_iter()+ .flatten().filter(|t| *t > now)+ .min().unwrap_or(now + KEY_HOUR)}+ /// Where letting this session read end-to-end encrypted data stands, from what is held+ /// here alone: no request, no prompt, no notification on anyone's phone. What a background+ /// pass goes by — only the person's own action asks Apple ([`Self::data_access`]).+ #[must_use]+ pub fn data_access_standing(&self) -> DataAccess {+ if self.session.web_access_allowed == Some(false) {+ return DataAccess::WebAccessOff;+ }+ if self.data_access_missing().is_empty() {+ DataAccess::Open+ } else {+ DataAccess::Needed+ }+ }+/// 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> {@@ -326,9 +349,11 @@ impl Client {/// 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.+ /// Called only for something the person did — signing in, pressing Sync Now — or to follow+ /// the approval that asked for: every key Apple releases shows a notice on their devices,+ /// so a background pass reads [`Self::data_access_standing`] instead and asks nothing.+ /// `ask` lets this put the approval itself on their devices when none is given; following+ /// one already asked for, it is `false`.pub async fn data_access(&mut self, ask: bool) -> Result<DataAccess> {if self.session.web_access_allowed == Some(false) {return Ok(DataAccess::WebAccessOff);@@ -356,7 +381,7 @@ impl Client {// 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;+ let said_adp = self.data_protection_on();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 {})",@@ -364,10 +389,13 @@ impl Client {)));}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);+ // Recovery is on, so Apple holds the keys itself: no approval opens anything more,+ // and nothing is held back for one — remembered, so it is not asked again.+ self.session.data_protection_seen = Some(false);+ self.keep();return Ok(DataAccess::Open);}+ self.session.data_protection_seen = Some(true);let consent_until = state.body.get("deviceConsentForPCSExpiry")@@ -425,7 +453,8 @@ impl Client {}// 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);+ self.session.data_protection_seen = Some(false);+ self.keep();return Ok(DataAccess::Open);}if answer.status.as_u16() == 500 && message.contains(WEB_AUTH_COOKIE) {diff --git a/crates/quince-auth/src/session.rs b/crates/quince-auth/src/session.rsindex 6507c43..15ad69b 100644--- a/crates/quince-auth/src/session.rs+++ b/crates/quince-auth/src/session.rs@@ -117,6 +117,11 @@ pub struct Session {/// whose key cookie is not known by name; the rest are read from the cookies themselves.#[serde(default)]pub pcs_until: std::collections::BTreeMap<String, u64>,+ /// Whether Advanced Data Protection is in effect, as Apple itself has shown it — its+ /// `requestWebAccessState` answer, or a refusal for want of a key — rather than as the+ /// sign-in's flags say. `None` until Apple has shown either.+ #[serde(default)]+ pub data_protection_seen: Option<bool>,/// Apple has new iCloud terms the person has not agreed to (`termsUpdateNeeded`). Until/// they do, `accountLogin` opens only part of a web session — no `X-APPLE-WEBAUTH-TOKEN`/// — and every service, Calendar and Contacts too, answers "Missing X-APPLE-WEBAUTH-TOKENdiff --git a/crates/quince-auth/tests/data_protection.rs b/crates/quince-auth/tests/data_protection.rsindex b01721d..38af424 100644--- a/crates/quince-auth/tests/data_protection.rs+++ b/crates/quince-auth/tests/data_protection.rs@@ -241,6 +241,23 @@ async fn pcs_required_with_recovery_on_asks_once_and_needs_nothing() {}))).mount(&server).await;+ // `pcsRequired` alone is no evidence: nothing held back, nothing asked.+ assert!(client.data_access_missing().is_empty());+ assert_eq!(client.data_access_standing(), DataAccess::Open);+ assert_eq!(client.data_access(true).await.unwrap(), DataAccess::Open);+ assert_eq!(asked(&server, STATE).await, 0, "nothing asked of Apple");++ // iCDPEnabled, and Apple says recovery is on: asked once, then remembered, a restart too.+ 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!({+ "dsid": 1234567890, "isWebAccessAllowed": true, "isICDRSDisabled": false+ })))+ .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!(@@ -254,6 +271,17 @@ async fn pcs_required_with_recovery_on_asks_once_and_needs_nothing() {"no prompt on anyone's phone");assert!(client.data_access_missing().is_empty());+ drop(client);+ let again = Client::with(+ dir.path(),+ Endpoints::at(&server.uri()),+ Store::file(dir.path()).unwrap(),+ )+ .unwrap();+ assert!(+ again.data_access_missing().is_empty(),+ "and after a restart"+ );}/// Advanced Data Protection with web access off: the existing page, and nothing asked.@@ -817,3 +845,106 @@ async fn signing_out_forgets_the_keys() {"signed out: no services at all");}++/// What a background pass goes by: read from what is held here — no request to Apple, so no+/// prompt and no notice on anyone's phone, however often it runs.+#[tokio::test]+async fn where_access_stands_is_read_without_asking_apple() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let client = signed_in(&server, dir.path(), ADP, false).await;+ let before = server.received_requests().await.unwrap().len();+ for _ in 0..10 {+ assert_eq!(client.data_access_standing(), DataAccess::Needed);+ }+ assert_eq!(+ server.received_requests().await.unwrap().len(),+ before,+ "nothing asked of Apple"+ );++ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let client = signed_in(&server, dir.path(), STANDARD, false).await;+ assert_eq!(+ client.data_access_standing(),+ DataAccess::Open,+ "no ADP: nothing waits"+ );+ let shape = Shape {+ web_access: Some(false),+ ..ADP+ };+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let client = signed_in(&server, dir.path(), shape, false).await;+ assert_eq!(client.data_access_standing(), DataAccess::WebAccessOff);+}++/// One approval, every protected service: a single consent request, then each service's key+/// asked for back to back in the same step.+#[tokio::test]+async fn one_approval_covers_every_protected_service_in_one_go() {+ 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))+ .up_to_n_times(1)+ .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+ })))+ .mount(&server)+ .await;+ mount_keys(&server, 3600).await;+ assert_eq!(client.data_access(true).await.unwrap(), DataAccess::Waiting);+ assert_eq!(client.data_access(false).await.unwrap(), DataAccess::Open);+ let reqs = server.received_requests().await.unwrap();+ assert_eq!(to(&reqs, CONSENT).len(), 1, "one approval");+ assert_eq!(+ app_names(&to(&reqs, PCS)),+ ["notes3", "reminders", "photos", "iclouddrive"],+ "every service, one after another, in the step after it"+ );+}++/// Keys are held only until the approval runs out, even when their cookies would last longer:+/// a pass stops asking for the service at that moment, never after Apple refuses it.+#[tokio::test]+async fn keys_are_let_go_when_the_approval_runs_out() {+ let server = MockServer::start().await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = signed_in(&server, dir.path(), ADP, false).await;+ let soon_ms = {+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_millis();+ u64::try_from(now).unwrap() + 1500+ };+ Mock::given(method("POST"))+ .and(path(STATE))+ .respond_with(state(true, soon_ms))+ .mount(&server)+ .await;+ mount_keys(&server, 3600).await; // cookies good for an hour+ assert_eq!(client.data_access(false).await.unwrap(), DataAccess::Open);+ assert!(client.data_access_missing().is_empty());+ tokio::time::sleep(Duration::from_millis(2600)).await;+ assert_eq!(+ client.data_access_missing(),+ ["notes", "reminders", "photos", "drive"],+ "the approval's expiry, not the cookies', is when they go"+ );+ assert_eq!(client.data_access_standing(), DataAccess::Needed);+}diff --git a/src-tauri/src/data_access.rs b/src-tauri/src/data_access.rsindex ba17c50..038690c 100644--- a/src-tauri/src/data_access.rs+++ b/src-tauri/src/data_access.rs@@ -2,11 +2,20 @@//!//! 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.+//! one of their devices, for about an hour at a time, and every key Apple then releases shows a+//! notice on their devices. So this is never background work:+//!+//! * Apple is asked only when the person acts — signing in, or pressing Sync Now (the approval+//! card's button, or an explicit refresh). Every protected service is asked for in that one+//! go, back to back, so one approval covers them all.+//! * A background pass (the timer, a push, a window coming back) asks Apple nothing about it:+//! it reads where things stand from what is held here ([`Client::data_access_standing`]), and+//! the protected services wait — not fail — until the next approval. Calendar and Contacts,+//! which Apple does not protect this way, carry on as usual.+//! * Keys are held only until they run out, by the time recorded when they arrived, so passes+//! stop asking for a protected service before Apple would refuse it.+//! * While an approval is on its way the client is taken only for each step, so nothing waits+//! behind it; once it is given, what was waiting is read and the changes queued meanwhile go.use crate::Auth;use quince_auth::pcs::{self, DataAccess};@@ -43,23 +52,25 @@ impl Access {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.+/// Services a pass found refused for want of their key, for the next step to count as missing.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.+/// Who is asking, which decides whether Apple is asked at all.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Ask {- /// The person, from the prompt's button: always.+ /// The person: signing in, or pressing Sync Now. Apple is asked, and the approval put on+ /// their devices when it is needed.Person,- /// A sign-in, or a window opening or coming back: once a lapse.- Window,- /// A background pass: never.+ /// Anything else — the timer, a push, a window opening or coming back. Nothing is asked of+ /// Apple; where things stand is read from what is held here.Background,}+/// Whether a step for `ask` may send anything to Apple.+fn asks_apple(ask: Ask) -> bool {+ ask == Ask::Person+}+/// Where it stands now.pub fn current() -> Access {NOW.lock()@@ -67,10 +78,14 @@ pub fn current() -> Access {.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.+/// The protected services a pass should leave alone now: their keys are not held, so asking+/// Apple for them would only be refused. Read from what is held here; asks Apple nothing.+pub fn waiting(client: &Client) -> Vec<&'static str> {+ client.data_access_missing()+}++/// A new sign-in, or a sign-out: nothing from the session before carries over.pub fn forget(app: &tauri::AppHandle) {- ASKED_UNASKED.store(false, Ordering::SeqCst);REFUSED.lock().unwrap_or_else(std::sync::PoisonError::into_inner)@@ -78,7 +93,7 @@ pub fn forget(app: &tauri::AppHandle) {set(app, Access::OPEN);}-/// A pass found `service` refused by Advanced Data Protection.+/// A pass found `service` refused by Advanced Data Protection: a key Apple let go early.pub fn refused(service: &'static str) {REFUSED.lock()@@ -100,16 +115,9 @@ fn set(app: &tauri::AppHandle, next: Access) {}}-/// 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.+/// Take one step and tell the window. For the person, Apple is asked — every missing service+/// in one go — and an approval on its way is followed; for anything else, only what is held+/// here is read.pub async fn check(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>, ask: Ask) {let (step, missing) = {let mut guard = client.lock().await;@@ -123,27 +131,30 @@ pub async fn check(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>, ask: Ask) {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)+ let step = if asks_apple(ask) {+ guard.data_access(true).await} else {- let asking = may_ask(ask);- let step = guard.data_access(asking).await;- (step, guard.data_access_missing())- }+ Ok(guard.data_access_standing())+ };+ (step, guard.data_access_missing())};+ // An approval being followed is the follower's to settle; a background look at what is+ // held here (nothing yet) must not say "needed" over "waiting".+ if ask == Ask::Background && FOLLOWING.load(Ordering::SeqCst) {+ return;+ }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) {+/// After a pass: when Advanced Data Protection kept a service out (a key let go early), say+/// where things stand — from what is held here, asking Apple nothing.+pub async fn after_pass(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>) {let any = !REFUSED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).is_empty();if any {- check(app, client, ask).await;+ check(app, client, Ask::Background).await;}}@@ -177,8 +188,8 @@ fn settle(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.+ // Not reached, or Apple busy: nothing is known to have changed. Said to the person who+ // asked; nothing else asks.Err(e @ (quince_auth::Error::Network(_) | quince_auth::Error::Unavailable(_))) => {if ask == Ask::Person {set(@@ -204,9 +215,9 @@ fn settle(}}-/// Every key is here (or none was ever needed): said, and what was waiting on it read now.+/// Every key is here (or none was ever needed): said, and what was waiting on it read now —+/// and the changes made here meanwhile sent.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;@@ -215,6 +226,7 @@ fn opened(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>, was: &Access) {let app = app.clone();let client = Arc::clone(client);tauri::async_runtime::spawn(async move {+ crate::outbox::kick();let data = app.state::<crate::Data>();crate::refresh::some(&client, &data.0, &services).await;crate::alerts::changed();@@ -224,8 +236,9 @@ fn opened(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>, was: &Access) {});}-/// Follow an approval on its way, one step at a time on [`pcs::APPROVAL_SCHEDULE`], taking the-/// client only for each step.+/// Follow an approval the person asked for, one step at a time on [`pcs::APPROVAL_SCHEDULE`],+/// taking the client only for each step. Each step asks only whether it was given, and fetches+/// the keys once it is: no second prompt.fn follow(app: tauri::AppHandle, client: Arc<Mutex<Client>>, waiting_on: Vec<&'static str>) {if FOLLOWING.swap(true, Ordering::SeqCst) {return;@@ -254,7 +267,7 @@ fn follow(app: tauri::AppHandle, client: Arc<Mutex<Client>>, waiting_on: Vec<&'sFOLLOWING.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);+ settle(&app, &client, landed, waiting_on, Ask::Person);});}@@ -264,7 +277,8 @@ pub async fn data_access_status() -> Result<Access, String> {Ok(current())}-/// The person asked: put the approval on their devices again, and follow it.+/// The person pressed Sync Now: ask Apple — the approval on their devices when it is needed,+/// every protected service in one go — and follow it.#[tauri::command]pub async fn data_access_ask(app: tauri::AppHandle,@@ -279,24 +293,11 @@ 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);+ fn only_the_person_ever_has_apple_asked() {+ assert!(asks_apple(Ask::Person));assert!(- may_ask(Ask::Window),- "after access opened, the next lapse asks again"+ !asks_apple(Ask::Background),+ "no background pass sends Apple anything about keys");}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 6f2c2a2..0915218 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -1715,6 +1715,17 @@ fn still_owned(library: &quince_core::Library, account: Option<&str>) -> Result</// Signed in, then the library made this account's; if it could not be, signed out again with/// the reason, never left signed in over someone else's data.async fn signed_in(app: &tauri::AppHandle, client: &mut Client) -> Result<(), String> {+ signed_in_as(app, client, data_access::Ask::Background).await+}++/// [`signed_in`], saying who it was for: the person signing in by hand is an action of theirs,+/// and Advanced Data Protection's approval is asked for with it; a session taken up again at a+/// launch — perhaps at login, the window in the tray — asks Apple nothing about it.+async fn signed_in_as(+ app: &tauri::AppHandle,+ client: &mut Client,+ ask: data_access::Ask,+) -> Result<(), String> {if let Err(e) = claim_library(app, client).await {let _ = client.sign_out();return Err(e);@@ -1726,13 +1737,14 @@ async fn signed_in(app: &tauri::AppHandle, client: &mut Client) -> Result<(), St.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.+ // approval on the person's devices: asked for when they sign in by hand, read from what+ // is held here otherwise — 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;+ data_access::check(&app, &client, ask).await;});}Ok(())@@ -1760,7 +1772,7 @@ async fn auth_sign_in(let mut client = auth.client.lock().await;match client.sign_in(&apple_id, &password).await {Ok(SignInOutcome::Complete) => {- signed_in(&app, &mut client).await?;+ signed_in_as(&app, &mut client, data_access::Ask::Person).await?;drop(client);folders_up(&app).await;Ok("complete")@@ -1781,7 +1793,7 @@ async fn auth_submit_code(.submit_two_factor(&code).await.map_err(|e| e.to_string())?;- signed_in(&app, &mut client).await?;+ signed_in_as(&app, &mut client, data_access::Ask::Person).await?;drop(client);folders_up(&app).await;Ok(())@@ -1828,7 +1840,7 @@ async fn auth_submit_sms_code(.submit_sms_code(phone_id, &code).await.map_err(|e| e.to_string())?;- signed_in(&app, &mut client).await?;+ signed_in_as(&app, &mut client, data_access::Ask::Person).await?;drop(client);folders_up(&app).await;Ok(())@@ -5498,11 +5510,17 @@ async fn sync_all(app: tauri::AppHandle,auth: State<'_, Auth>,data: State<'_, Data>,+ asked: Option<bool>,) -> UiResult<refresh::Refresh> {let client = Arc::clone(&auth.client);keep_signed_in(&app, &client).await;+ // The person pressed Sync Now: Advanced Data Protection's approval is asked for with it.+ // A pass the window starts by itself (opening, coming back) asks Apple nothing about it.+ if asked == Some(true) {+ data_access::check(&app, &client, data_access::Ask::Person).await;+ }let result = refresh::all(&client, &data.0).await;- data_access::after_pass(&app, &client, data_access::Ask::Window).await;+ data_access::after_pass(&app, &client).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 —@@ -5522,12 +5540,16 @@ async fn sync_some(auth: State<'_, Auth>,data: State<'_, Data>,services: Vec<String>,+ asked: Option<bool>,) -> UiResult<refresh::Refresh> {let client = Arc::clone(&auth.client);keep_signed_in(&app, &client).await;+ if asked == Some(true) {+ data_access::check(&app, &client, data_access::Ask::Person).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;+ data_access::after_pass(&app, &client).await;alerts::changed();if names.contains(&"contacts") {warm_contact_photos(app.clone());@@ -5559,7 +5581,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;+ data_access::after_pass(&app, &client).await;alerts::changed();warm_contact_photos(app.clone());app.emit(SYNCED, told(&result)).ok();diff --git a/src-tauri/src/outbox.rs b/src-tauri/src/outbox.rsindex 5b43386..11e3dfd 100644--- a/src-tauri/src/outbox.rs+++ b/src-tauri/src/outbox.rs@@ -1152,9 +1152,30 @@ pub fn start(app: AppHandle) {() = WAKE.notified() => {}() = tokio::time::sleep(wait) => {}}+ // Reminders and Notes changes wait in the queue while Advanced Data Protection keeps+ // their keys until the next approval — sent then, never refused meanwhile.+ let waiting = {+ let auth = app.state::<Auth>();+ let client = auth.client.lock().await;+ crate::data_access::waiting(&client)+ };let outcomes = [- (REMINDERS, drain_reminders(&app).await),- (NOTES, drain_notes(&app).await),+ (+ REMINDERS,+ if held(REMINDERS, &waiting) {+ Outcome::Idle+ } else {+ drain_reminders(&app).await+ },+ ),+ (+ NOTES,+ if held(NOTES, &waiting) {+ Outcome::Idle+ } else {+ drain_notes(&app).await+ },+ ),(CONTACTS, drain_contacts(&app).await),(CALENDAR, drain_calendar(&app).await),];@@ -1175,6 +1196,12 @@ pub fn start(app: AppHandle) {});}+/// Whether `service`'s queued changes wait for Advanced Data Protection's next approval:+/// its key is not held, so sending would only be refused. Kept, in order, for then.+fn held(service: &str, waiting: &[&'static str]) -> bool {+ waiting.contains(&service)+}+/// Told to the window whenever what waits may have changed.pub const CHANGED: &str = "quince://outbox-changed";@@ -4021,3 +4048,19 @@ mod tests {}}}++#[cfg(test)]+mod held_tests {+ use super::*;++ #[test]+ fn changes_wait_for_the_next_approval_and_go_with_it() {+ let waiting = ["notes", "reminders", "photos", "drive"];+ assert!(held(NOTES, &waiting) && held(REMINDERS, &waiting));+ assert!(+ !held(CONTACTS, &waiting) && !held(CALENDAR, &waiting),+ "never held"+ );+ assert!(!held(NOTES, &[]), "approved: sent");+ }+}diff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rsindex 8a0c0b4..8cc42ba 100644--- a/src-tauri/src/refresh.rs+++ b/src-tauri/src/refresh.rs@@ -34,6 +34,10 @@ pub enum Outcome {Unavailable,/// It was tried and failed. What is on screen is the last good data.Failed,+ /// Advanced Data Protection keeps it until the person next approves on one of their+ /// devices: not asked for, not failed. What is on screen is the copy here, and changes+ /// made meanwhile wait to be sent.+ Paused,}/// What one service's refresh did.@@ -131,6 +135,8 @@ struct Context {/// The account it is all for (`account_tag`): nothing it brings is kept in a library that/// is not that account's.account: Option<String>,+ /// Services Advanced Data Protection keeps until the next approval: left alone this pass.+ waiting: Vec<&'static str>,}async fn context(client: &Arc<Mutex<Client>>) -> Context {@@ -144,9 +150,36 @@ async fn context(client: &Arc<Mutex<Client>>) -> Context {cloudkit: session.service_url("ckdatabasews"),drive: session.service_url("drivews"),account: session.dsid.as_deref().map(crate::account_tag),+ waiting: crate::data_access::waiting(&guard),}}+/// A service Advanced Data Protection keeps until the next approval, reported as waiting —+/// with when it last synced — and not asked of Apple: asked, it would only be refused.+async fn paused(service: &'static str, label: &'static str, data: &LibraryLock) -> ServiceReport {+ ServiceReport {+ service,+ label,+ outcome: Outcome::Paused,+ detail: Some(PAUSED_WORDS.into()),+ last_synced_at: data+ .read(|library| Ok(library.last_synced(service).ok().flatten()))+ .await+ .ok()+ .flatten(),+ changed: false,+ items: None,+ }+}++/// What a waiting service says.+pub const PAUSED_WORDS: &str = "Syncs when you approve Skykeep on your iPhone, iPad or Mac.";++/// Whether this pass leaves `service` alone for Advanced Data Protection.+fn waits(service: &str, waiting: &[&'static str]) -> bool {+ waiting.contains(&service)+}+/// Told each time one service's part of a pass has been stored, before the rest are done,/// with whether it changed anything a screen shows, and which items when that is known.type Landed = Box<dyn Fn(&'static str, bool, Option<Items>) + Send + Sync>;@@ -320,6 +353,9 @@ async fn run(client: &Arc<Mutex<Client>>, data: &LibraryLock, services: &[&str])}let report = match ctx.cloudkit.as_deref() {None => arrived((unavailable("reminders", "Reminders"), true)),+ Some(_) if waits("reminders", &ctx.waiting) => {+ paused("reminders", "Reminders", data).await+ }Some(root) => arrived(once("reminders", &crate::REMINDERS_PASS, || async {let since = token(data, "reminders").await;@@ -368,6 +404,7 @@ async fn run(client: &Arc<Mutex<Client>>, data: &LibraryLock, services: &[&str])}let report = match ctx.cloudkit.as_deref() {None => arrived((unavailable("notes", "Notes"), true)),+ Some(_) if waits("notes", &ctx.waiting) => paused("notes", "Notes", data).await,Some(root) => arrived(once("notes", &crate::NOTES_PASS, || async {// One notes pass at a time, from reading the position through storing what came@@ -477,6 +514,7 @@ async fn run(client: &Arc<Mutex<Client>>, data: &LibraryLock, services: &[&str])}let report = match ctx.drive.as_deref() {None => arrived((unavailable("drive", "Drive"), true)),+ Some(_) if waits("drive", &ctx.waiting) => paused("drive", "Drive", data).await,Some(root) => {let pass = crate::drive_pass(quince_core::drive::ROOT);arrived(@@ -520,6 +558,7 @@ async fn run(client: &Arc<Mutex<Client>>, data: &LibraryLock, services: &[&str])}let report = match ctx.cloudkit.as_deref() {None => arrived((unavailable("photos", "Photos"), true)),+ Some(_) if waits("photos", &ctx.waiting) => paused("photos", "Photos", data).await,Some(root) => arrived(once("photos", &crate::PHOTOS_PASS, || async {// A large library is read a few pages at a time, each stored before the next@@ -852,6 +891,15 @@ where// and the service read again once it is given (`data_access`).if matches!(e, quince_icloud::Error::NeedsDeviceApproval) {crate::data_access::refused(service);+ return ServiceReport {+ service,+ label,+ outcome: Outcome::Paused,+ detail: Some(PAUSED_WORDS.into()),+ last_synced_at: library.last_synced(service).ok().flatten(),+ changed: false,+ items: None,+ };}let message = e.to_string();library.mark_sync_failed(service, &message).ok();@@ -1044,3 +1092,29 @@ mod tests {assert_eq!(report.detail.as_deref(), Some("pass 3"));}}++#[cfg(test)]+mod paused_tests {+ use super::*;++ #[test]+ fn a_waiting_service_is_left_alone_and_the_rest_are_not() {+ let waiting = ["notes", "reminders", "photos", "drive"];+ for s in waiting {+ assert!(waits(s, &waiting));+ }+ for s in ["calendar", "contacts"] {+ assert!(+ !waits(s, &waiting),+ "{s} is never held by Advanced Data Protection"+ );+ }+ assert!(!waits("notes", &[]), "approved: nothing is left alone");+ }++ #[test]+ fn waiting_reads_as_waiting_not_failure() {+ assert_eq!(serde_json::to_value(Outcome::Paused).unwrap(), "paused");+ assert!(!PAUSED_WORDS.to_lowercase().contains("error"));+ }+}diff --git a/src/components/Account.tsx b/src/components/Account.tsxindex 57132d9..d174919 100644--- a/src/components/Account.tsx+++ b/src/components/Account.tsx@@ -107,7 +107,7 @@ export function AccountCard({ current, onOpen, app }: { current: boolean; onOpenconst asked = useRef(false);const refresh = () => {asked.current = true;- void (app ? refreshService(app.service) : refreshAll());+ void (app ? refreshService(app.service, true) : refreshAll(true));};// Said aloud, politely: how an update someone asked for ended, and any update that newly// failed. The routine updates in the background are left unsaid — a line every few minutesdiff --git a/src/components/DeviceApproval.tsx b/src/components/DeviceApproval.tsxindex 2ff2923..53f94f3 100644--- a/src/components/DeviceApproval.tsx+++ b/src/components/DeviceApproval.tsx@@ -2,15 +2,23 @@ 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 { freshness } from "../lib/sync";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",-};+/** What each service is called on screen, in the order they are listed. */+const NAMES: [string, string][] = [+ ["notes", "Notes"],+ ["reminders", "Reminders"],+ ["drive", "iCloud Drive"],+ ["photos", "Photos"],+];++/** "Notes, Reminders and iCloud Drive". */+function listed(services: readonly string[]): string {+ const names = NAMES.filter(([key]) => services.includes(key)).map(([, name]) => name);+ if (names.length <= 1) return names[0] ?? "your iCloud";+ return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;+}/** The states in which a service waits on an approval on the person's devices. */export function awaitsApproval(access: DataAccess | null, service: string): boolean {@@ -19,8 +27,8 @@ export function awaitsApproval(access: DataAccess | null, service: string): bool);}-/** Ask Apple again, saying what came back or why it could not be asked. */-function useAsk(onAccess: (a: DataAccess) => void) {+/** Sync Now: Apple is asked, the approval put on the person's devices when it is needed. */+function useSyncNow(onAccess: (a: DataAccess) => void) {const [asking, setAsking] = useState(false);const [error, setError] = useState<string | null>(null);const ask = () => {@@ -34,85 +42,84 @@ function useAsk(onAccess: (a: DataAccess) => void) {return { ask, asking, error };}-/** The line under the heading: where the approval stands. */-function standing(access: DataAccess): string {+/** The line that says where the approval stands, when there is something to say. */+function standing(access: DataAccess, problem: string | null): string | null {+ if (problem) return problem;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.";+ return null;}/**- * 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.+ * Advanced Data Protection keeps these services end-to-end encrypted, and Apple lets Skykeep+ * sync them for a while each time 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+ * page 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 { ask, asking, error } = useSyncNow(onAccess);const waiting = access.state === "waiting";- const problem = error ?? access.problem;+ const line = standing(access, 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.+ Advanced Data Protection is on, so Skykeep syncs {listed(access.services)} when you approve it on one of+ your devices.</p><p className="device-approval-status" role="status" aria-live="polite">{waiting && <Spinner small />}- <span>{problem ?? standing(access)}</span>+ <span>{line ?? ""}</span></p><button className="primary" onClick={ask} disabled={asking}>- Try Again+ Sync Now</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.+ * The same, for a screen whose copy is already on this computer: the screen stays, readable and+ * editable, and one card at the foot of the content says how it syncs and when it last did.*/export function ApprovalNotice({access,- service,+ lastSyncedAt,onAccess,}: {access: DataAccess;- service: string;+ lastSyncedAt: number | null;onAccess: (a: DataAccess) => void;}) {- const { ask, asking, error } = useAsk(onAccess);+ const { ask, asking, error } = useSyncNow(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;+ const names = listed(access.services);+ const line = standing(access, error ?? access.problem);return (- <div ref={card} className="toast update-notice device-approval-notice" role="group" aria-label="Approve on your devices">+ <div ref={card} className="toast update-notice device-approval-notice" role="group" aria-label="Advanced Data Protection">{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.`)}+ {waiting+ ? `Approve on your iPhone, iPad or Mac to sync ${names}.`+ : `Advanced Data Protection is on, so Skykeep syncs ${names} when you approve on your iPhone, iPad or Mac. Your copy here stays available in between.`}</p>+ <p className="update-line device-approval-when">{line ?? freshness(lastSyncedAt)}</p>{!waiting && (<div className="update-actions"><button className="toast-action" onClick={ask} disabled={asking}>- Try Again+ Sync Now</button></div>)}diff --git a/src/components/SyncStatus.tsx b/src/components/SyncStatus.tsxindex 6151596..fb2e7df 100644--- a/src/components/SyncStatus.tsx+++ b/src/components/SyncStatus.tsx@@ -25,7 +25,7 @@ export function SyncStatus() {<div className="sync"><buttonclassName="sync-row"- onClick={() => void refresh()}+ onClick={() => void refresh(true)}disabled={syncing}aria-label={syncing ? "Updating your iCloud" : `${label}. Update now`}>diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 3c6d0fc..d85f46a 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -35,7 +35,8 @@ export type TwoFactorOptions = {};/** How one service's refresh ended. */-export type SyncOutcome = "ok" | "unavailable" | "failed";+/** `paused`: Advanced Data Protection keeps it until the next approval — waiting, not failed. */+export type SyncOutcome = "ok" | "unavailable" | "failed" | "paused";export type ServiceReport = {service: string;@@ -137,11 +138,13 @@ export type DataAccess = {export const api = {/** One refresh for every service. Never rejects for a single service failing. */- syncAll: () => invoke<Refresh>("sync_all"),+ /** `asked`: the person pressed Sync Now, so Advanced Data Protection's approval may be asked for. */+ syncAll: (asked?: boolean) => invoke<Refresh>("sync_all", { asked: asked ?? false }),/** What the library already knows about its own freshness, fetching nothing. */syncStatus: () => invoke<Refresh>("sync_status"),/** A refresh of only the services named — one app's "update now". */- syncSome: (services: string[]) => invoke<Refresh>("sync_some", { services }),+ syncSome: (services: string[], asked?: boolean) =>+ invoke<Refresh>("sync_some", { services, asked: asked ?? false }),status: () => invoke<Status>("auth_status"),/** Where a returning person goes: their library, the code Apple wants, or sign-in. */diff --git a/src/lib/sync.tsx b/src/lib/sync.tsxindex 9366eb0..f8d9f8f 100644--- a/src/lib/sync.tsx+++ b/src/lib/sync.tsx@@ -30,11 +30,12 @@ type Sync = {/** Ticks per service whose rows a pass changed; `all` for a change not placed. */revisions: Readonly<Record<string, number>>;/** Ask for a pass now. Safe to call while one is running; it will not start a second. */- refresh: () => Promise<void>;+ /** `asked`: the person pressed Sync Now (see `api.syncAll`). */+ refresh: (asked?: boolean) => Promise<void>;/** The last refresh that failed outright, rather than a single service reporting trouble. */error: string | null;/** Refresh one service alone — one app's "update now". Never starts a second pass of it. */- refreshService: (service: string) => Promise<void>;+ refreshService: (service: string, asked?: boolean) => Promise<void>;/** The services being refreshed on their own right now. */updating: readonly string[];/** Why a service's own refresh failed outright, by service. */@@ -106,7 +107,7 @@ export function SyncProvider({ children }: { children: ReactNode }) {const [passStartedAt, setPassStartedAt] = useState<number | null>(null);const serviceInFlight = useRef(new Set<string>());- const refresh = useCallback(async () => {+ const refresh = useCallback(async (asked?: boolean) => {if (inFlight.current) return;inFlight.current = true;setSyncing(true);@@ -116,7 +117,7 @@ export function SyncProvider({ children }: { children: ReactNode }) {// that cannot say so has every screen read again, as before.let told = false;try {- const done = await api.syncAll();+ const done = await api.syncAll(asked);told = Array.isArray(done?.changed);setReport(done);} catch (e) {@@ -129,14 +130,14 @@ export function SyncProvider({ children }: { children: ReactNode }) {}}, [bump]);- const refreshService = useCallback(async (service: string) => {+ const refreshService = useCallback(async (service: string, asked?: boolean) => {if (serviceInFlight.current.has(service)) return;serviceInFlight.current.add(service);setUpdating([...serviceInFlight.current]);setServiceErrors(({ [service]: _gone, ...rest }) => rest);let told = false;try {- const part = await api.syncSome([service]);+ const part = await api.syncSome([service], asked);told = Array.isArray(part?.changed);// The backend's event brings the whole picture; this keeps the answer on screen even// where no event arrives, by folding this service's own report into the last one.@@ -317,7 +318,7 @@ export function useArriving(service: string): boolean {const { report, syncing, error } = useSync();if (error) return false;const mine = report?.services.find((s) => s.service === service);- if (mine?.outcome === "failed" || mine?.outcome === "unavailable") return false;+ if (mine?.outcome === "failed" || mine?.outcome === "unavailable" || mine?.outcome === "paused") return false;if (mine?.lastSyncedAt) return false;return syncing || report === null;}@@ -342,7 +343,9 @@ export function useServiceState(service: string): ServiceState {const mine = report?.services.find((s) => s.service === service);const lastSyncedAt = mine?.lastSyncedAt ?? null;const landed = passStartedAt !== null && lastSyncedAt !== null && lastSyncedAt >= passStartedAt;- const working = updating.includes(service) || (syncing && !landed && mine?.outcome !== "unavailable");+ const working =+ updating.includes(service) ||+ (syncing && !landed && mine?.outcome !== "unavailable" && mine?.outcome !== "paused");const failure = serviceErrors[service] ?? (mine?.outcome === "failed" ? (mine.detail ?? "It didn’t update") : null);return { working, failure, lastSyncedAt, unavailable: mine?.outcome === "unavailable" };}diff --git a/src/screens/Library.tsx b/src/screens/Library.tsxindex 2e85139..0808fb2 100644--- a/src/screens/Library.tsx+++ b/src/screens/Library.tsx@@ -100,8 +100,8 @@ function UpdateKeys({ screen }: { screen: string | null }) {if (!reload) return;e.preventDefault();if (e.repeat) return;- if (screen && SCREENS.some((s) => s.key === screen)) void refreshService(serviceOf(screen));- else void refresh();+ if (screen && SCREENS.some((s) => s.key === screen)) void refreshService(serviceOf(screen), true);+ else void refresh(true);};window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);@@ -334,13 +334,19 @@ export function Library({ onSignOut, onShown }: { onSignOut: (keep: boolean) =>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>>({});+ /** When each service last synced, while an approval is awaited: one with a copy here keeps it. */+ const [lastSynced, setLastSynced] = useState<Record<string, number | null>>({});useEffect(() => {- if (!access || access.state === "open") return;- api- .syncStatus()- .then((r) => setHeld(Object.fromEntries(r.services.map((s) => [s.service, Boolean(s.lastSyncedAt)]))), () => {});+ if (!access || access.state === "open") return undefined;+ const read = () =>+ api+ .syncStatus()+ .then((r) => setLastSynced(Object.fromEntries(r.services.map((s) => [s.service, s.lastSyncedAt ?? null]))), () => {});+ void read();+ const off = listen(SYNCED, () => void read());+ return () => {+ void off.then((f) => f());+ };}, [access]);useEffect(() => {@@ -409,7 +415,7 @@ export function Library({ onSignOut, onShown }: { onSignOut: (keep: boolean) =>*/const frontService = selected && selected !== "settings" ? serviceOf(selected) : null;const approval: "screen" | "notice" | null =- frontService && access && awaitsApproval(access, frontService) ? (held[frontService] ? "notice" : "screen") : null;+ frontService && access && awaitsApproval(access, frontService) ? (lastSynced[frontService] ? "notice" : "screen") : null;const noScreen =Boolean(error) || (ready && (!selected || webAccess === false || approval === "screen" || atIcloud !== null));useEffect(() => {@@ -708,7 +714,7 @@ export function Library({ onSignOut, onShown }: { onSignOut: (keep: boolean) =>selection, 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} />+ <ApprovalScreen access={access} onAccess={setAccess} />)}{kept.map((key) => {const on = key === selected && approval !== "screen";@@ -736,7 +742,7 @@ export function Library({ onSignOut, onShown }: { onSignOut: (keep: boolean) =></main><ToastHost>{approval === "notice" && access && frontService && (- <ApprovalNotice access={access} service={frontService} onAccess={setAccess} />+ <ApprovalNotice access={access} lastSyncedAt={lastSynced[frontService] ?? null} onAccess={setAccess} />)}<UpdateNotice /></ToastHost>diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsxindex 3a43ea7..cd5e739 100644--- a/src/screens/SettingsView.tsx+++ b/src/screens/SettingsView.tsx@@ -627,6 +627,8 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom<span className={`settings-value${s.outcome === "failed" ? " is-trouble" : ""}`}>{s.outcome === "failed"? (s.detail ?? "Didn't update")+ : s.outcome === "paused"+ ? `${freshness(s.lastSyncedAt ?? null)}. Syncs when you approve`: syncing && !s.lastSyncedAt? "Downloading…": freshness(s.lastSyncedAt ?? null)}@@ -635,7 +637,7 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom))}<div className="settings-row"><span className="settings-label settings-hint">Changes from your other devices arrive within seconds.</span>- <button className="quiet" onClick={() => void refresh()} disabled={syncing}>+ <button className="quiet" onClick={() => void refresh(true)} disabled={syncing}>{syncing ? "Syncing…" : "Sync Now"}</button></div>