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
Stay signed in: a lapsed session signs itself back in
Yashwanth Kamireddi5971ed55b375
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjsindex 915365d..41d4834 100644--- a/.uiverify/a11y.mjs+++ b/.uiverify/a11y.mjs@@ -17,7 +17,7 @@ function installStub({ screen, services, twoFactor, driveItems = [] }) {switch (cmd) {case "auth_status":return { hasStoredSession: screen === "library", signedIn: screen === "library" };- case "auth_resume": return screen === "library";+ case "auth_resume": return screen === "library" ? "library" : "signin";case "auth_sign_in": return screen === "code" ? "needs_two_factor" : "complete";case "auth_two_factor_options": return twoFactor;case "account_services": return services;diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjsindex 651ef66..5d69481 100644--- a/.uiverify/assert.mjs+++ b/.uiverify/assert.mjs@@ -18,7 +18,7 @@ await ctx.addInitScript(({ services }) => {transformCallback: (cb) => cb,invoke: async (cmd) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return services;if (cmd === "calendar_events") return [];if (cmd === "calendar_list")@@ -293,7 +293,7 @@ let failures = 0;transformCallback: (cb) => cb,invoke: async (cmd) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return ["reminders"];if (cmd === "reminder_lists")return [list("A", "Daily", true, "#FFCC00"), list("B", "Everything for the house move", true, "#FF8D28"),@@ -478,7 +478,7 @@ let failures = 0;transformCallback: (cb) => cb,invoke: async (cmd, args) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return ["notes"];if (cmd === "note_folders") return [{ guid: "F", title: "Notes", sortOrder: 0, parentGuid: null }];if (cmd === "notes_in") return [n("A", "Curtains"), n("B", "Shopping")];@@ -520,7 +520,7 @@ let failures = 0;transformCallback: (cb) => cb,invoke: async (cmd, args) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return ["reminders"];if (cmd === "reminder_lists") return [{ guid: "G", title: "GYM", colour: "#0a84ff", ctag: null, sortOrder: 0, enabled: true },@@ -565,7 +565,7 @@ let failures = 0;transformCallback: (cb) => cb,invoke: async (cmd) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return ["reminders"];if (cmd === "reminder_lists") return [{ guid: "L", title: "Life Goals", colour: "#1badf8", ctag: null, sortOrder: 0, enabled: true }];if (cmd === "reminder_counts") return { today: 0, scheduled: 0, flagged: 0, all: 3, lists: [["L", 3]] };@@ -614,7 +614,7 @@ let failures = 0;transformCallback: (cb) => cb,invoke: async (cmd) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return ["reminders"];if (cmd === "sync_all") { window.__passes++; return { services: [], asOf: 1, tookMs: 0 }; }if (cmd === "sync_status") return { services: [], asOf: 1, tookMs: 0 };@@ -758,7 +758,7 @@ let failures = 0;transformCallback: (cb) => cb,invoke: async (cmd) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return services;if (cmd === "reminder_counts")return { today: 0, scheduled: 0, flagged: 0, all: 0, lists: [] };diff --git a/.uiverify/calendar.mjs b/.uiverify/calendar.mjsindex d7afa73..fdba144 100644--- a/.uiverify/calendar.mjs+++ b/.uiverify/calendar.mjs@@ -15,7 +15,7 @@ await ctx.addInitScript(() => {transformCallback: (cb) => cb,invoke: async (cmd, args) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return ["calendar"];if (cmd === "calendar_list") return [{ guid: "c", title: "Home", colour: "#0088FF", ctag: null, sortOrder: 0, enabled: true, writable: true, isDefault: true }];if (cmd === "calendar_events") return [{ guid: "e", calendarGuid: "c", title: "New Event", location: null,diff --git a/.uiverify/crash.mjs b/.uiverify/crash.mjsindex 15f0be0..c657ed7 100644--- a/.uiverify/crash.mjs+++ b/.uiverify/crash.mjs@@ -9,7 +9,7 @@ await ctx.addInitScript(() => {invoke: async (cmd) => {switch (cmd) {case "auth_status": return { hasStoredSession: true, signedIn: true };- case "auth_resume": return true;+ case "auth_resume": return "library";case "account_services": return ["calendar", "reminders", "notes", "contacts", "drivews", "photos"];case "calendar_events": case "calendar_list": case "reminders_due_between": return [];case "calendar_last_synced": case "reminders_last_synced": case "notes_last_synced":diff --git a/.uiverify/drive-upload.mjs b/.uiverify/drive-upload.mjsindex 6d55fd0..84eaa09 100644--- a/.uiverify/drive-upload.mjs+++ b/.uiverify/drive-upload.mjs@@ -15,7 +15,7 @@ await ctx.addInitScript(() => {transformCallback: (cb) => cb,invoke: async (cmd, args) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return ["drivews", "docws"];if (cmd === "plugin:event|listen") {(handlers[args.event] ??= []).push(args.handler);diff --git a/.uiverify/elsewhere.mjs b/.uiverify/elsewhere.mjsindex 89676b9..07e031f 100644--- a/.uiverify/elsewhere.mjs+++ b/.uiverify/elsewhere.mjs@@ -39,7 +39,7 @@ const stub = ({ services, now, edge }) => {invoke: async (cmd) => {switch (cmd) {case "auth_status": return { hasStoredSession: true, signedIn: true };- case "auth_resume": return true;+ case "auth_resume": return "library";case "account_services": return services;case "reminder_counts": return { today: 0, scheduled: 2, flagged: 0, all: 2, lists: [["L1", 2]] };case "reminder_lists": return lists;diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjsindex d1e2f16..1e600ee 100644--- a/.uiverify/keyboard.mjs+++ b/.uiverify/keyboard.mjs@@ -30,7 +30,7 @@ function installStub({ screen, services, twoFactor }) {switch (cmd) {case "auth_status":return { hasStoredSession: screen === "library", signedIn: screen === "library" };- case "auth_resume": return screen === "library";+ case "auth_resume": return screen === "library" ? "library" : "signin";case "auth_sign_in": return screen === "code" ? "needs_two_factor" : "complete";case "auth_two_factor_options": return twoFactor;case "account_services": return services;diff --git a/.uiverify/look.mjs b/.uiverify/look.mjsindex aa51fa6..ce23b72 100644--- a/.uiverify/look.mjs+++ b/.uiverify/look.mjs@@ -18,7 +18,7 @@ for (const scheme of ["dark", "light"]) {transformCallback: (cb) => cb,invoke: async (cmd, args) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return ["reminders", "notes", "calendar", "contacts", "drivews"];if (cmd === "reminder_lists") return fx.lists;if (cmd === "reminder_groups") return fx.groups;diff --git a/.uiverify/notes-compose.mjs b/.uiverify/notes-compose.mjsindex 08c9d5a..9aea557 100644--- a/.uiverify/notes-compose.mjs+++ b/.uiverify/notes-compose.mjs@@ -27,7 +27,7 @@ await ctx.addInitScript(() => {transformCallback: (cb) => cb,invoke: async (cmd, args) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return ["notes", "ckdatabasews"];if (cmd === "note_folders") return [];if (cmd === "notes_in") return notes.slice();diff --git a/.uiverify/notes-long.mjs b/.uiverify/notes-long.mjsindex e893e0d..c1d439e 100644--- a/.uiverify/notes-long.mjs+++ b/.uiverify/notes-long.mjs@@ -19,7 +19,7 @@ await ctx.addInitScript(() => {transformCallback: (cb) => cb,invoke: async (cmd, args) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return ["notes", "ckdatabasews"];if (cmd === "notes_in") return [{ ...note }];if (cmd === "note_counts") return [1, []];diff --git a/.uiverify/notes-trash.mjs b/.uiverify/notes-trash.mjsindex c3e7abd..d3f8e43 100644--- a/.uiverify/notes-trash.mjs+++ b/.uiverify/notes-trash.mjs@@ -13,7 +13,7 @@ await ctx.addInitScript(() => {transformCallback: (cb) => cb,invoke: async (cmd, args) => {if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true };- if (cmd === "auth_resume") return true;+ if (cmd === "auth_resume") return "library";if (cmd === "account_services") return ["notes", "ckdatabasews"];if (cmd === "note_folders")return [{ guid: "TrashFolder-CloudKit", title: "Recently Deleted", sortOrder: 9, parentGuid: null }];diff --git a/.uiverify/resume.mjs b/.uiverify/resume.mjsnew file mode 100644index 0000000..cef59ad--- /dev/null+++ b/.uiverify/resume.mjs@@ -0,0 +1,31 @@+// Coming back to a lapsed session: Quince signs itself back in, and when Apple wants a code+// before trusting this computer again, the code screen is what opens — not the library, which+// could not refresh, and not the sign-in screen, whose password is already kept.+import { engine } from "./engine.mjs";++const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1040, height: 720 } });+await ctx.addInitScript(() => {+ window.__TAURI_INTERNALS__ = {+ transformCallback: (cb) => cb,+ invoke: async (cmd) => {+ if (cmd === "auth_status") return { hasStoredSession: true, signedIn: false };+ if (cmd === "auth_resume") return "code";+ if (cmd === "auth_two_factor_options") return { trustedDeviceCount: 1, phones: [], tooManyCodesSent: false };+ if (cmd === "plugin:event|listen") return 0;+ return [];+ },+ };+});+const page = await ctx.newPage();+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });+await page.waitForTimeout(500);+const where = await page.evaluate(() => ({+ code: Boolean(document.querySelector(".code, input[autocomplete='one-time-code']")),+ library: Boolean(document.querySelector(".sidebar")),+ signIn: Boolean(document.querySelector("input[type='password']")),+}));+const ok = where.code && !where.library && !where.signIn;+console.log(ok ? "PASS a lapsed session that needs a code opens on the code screen" : `FAIL it opened on: ${JSON.stringify(where)}`);+await b.close();+process.exitCode = ok ? 0 : 1;diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex e067bf1..5db912e 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -118,7 +118,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteswitch (cmd) {case "auth_status":return { hasStoredSession: screen === "library", signedIn: screen === "library" };- case "auth_resume": return screen === "library";+ case "auth_resume": return screen === "library" ? "library" : "signin";case "auth_sign_in": return screen === "code" ? "needs_two_factor" : "complete";case "auth_submit_code": return null;case "account_services": return services;diff --git a/check.sh b/check.shindex ad5683b..6f8a90a 100755--- a/check.sh+++ b/check.sh@@ -43,6 +43,7 @@ step "calendar grids" node .uiverify/calendar.mjsstep "every size" node .uiverify/sizes.mjsstep "narrow windows" node .uiverify/compact.mjsstep "a screen failing" node .uiverify/boundary.mjs+step "coming back" node .uiverify/resume.mjs# The same screens in WebKit, the engine Quince draws in. Chromium above catches most things;# this catches what only WebKit does — pointer capture, blur on removal, its own layout.@@ -56,6 +57,7 @@ step "webkit: calendar" env ENGINE=webkit node .uiverify/calendar.mjsstep "webkit: sizes" env ENGINE=webkit node .uiverify/sizes.mjsstep "webkit: narrow" env ENGINE=webkit node .uiverify/compact.mjsstep "webkit: failing" env ENGINE=webkit node .uiverify/boundary.mjs+step "webkit: back" env ENGINE=webkit node .uiverify/resume.mjsprintf '\n'if [ "$fail" -eq 0 ]; then printf '\033[32mAll checks passed.\033[0m\n'; else printf '\033[31mSome checks failed.\033[0m\n'; fidiff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex 24a8d4a..9201891 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -239,6 +239,10 @@ pub struct Client {store: Store,session: Session,endpoints: Endpoints,+ /// An Apple ID and password being signed in with, kept only once the sign-in completes.+ pending: Option<(String, String)>,+ /// A lapsed session tried to sign itself back in and Apple wants a code first.+ awaiting_code: bool,}impl Client {@@ -289,9 +293,18 @@ impl Client {store,session,endpoints,+ pending: None,+ awaiting_code: false,})}+ /// A lapsed session tried to sign itself back in, and Apple wants a code before it will+ /// trust this computer again. The code screen is the next thing to show.+ #[must_use]+ pub fn awaiting_code(&self) -> bool {+ self.awaiting_code+ }+pub fn session(&self) -> &Session {&self.session}@@ -397,19 +410,38 @@ impl Client {//// This is what makes staying signed in survive a lost cookie file, a copied install,// or cookies expiring before the trust token does.- match self.account_login().await {- Ok(data) => {- self.absorb(&data);- self.persist()?;- Ok(true)- }- Err(_) => {- // Genuinely dead. Drop the challenge state so it cannot contaminate the- // sign-in that follows.- self.clear_challenge_state();- Ok(false)+ if let Ok(data) = self.account_login().await {+ self.absorb(&data);+ self.persist()?;+ return Ok(true);+ }++ // The session token has lapsed too — Apple keeps one for days, not months. With the+ // password kept, sign in again: this computer is still trusted, so Apple asks for no+ // code, and nobody sees a sign-in screen. Only when the trust itself has run out+ // (about two months) does Apple want a code, and then the code screen is what shows.+ if let (Some(apple_id), Some(password)) =+ (self.session.apple_id.clone(), self.session.password.clone())+ {+ match self.sign_in(&apple_id, &password).await {+ Ok(SignInOutcome::Complete) => return Ok(true),+ Ok(SignInOutcome::NeedsTwoFactor) => {+ self.awaiting_code = true;+ return Ok(false);+ }+ // The password was changed elsewhere: the kept one is worthless now.+ Err(Error::BadCredentials) => {+ self.session.password = None;+ self.persist()?;+ }+ Err(_) => {}}}++ // Genuinely dead. Drop the challenge state so it cannot contaminate the sign-in that+ // follows.+ self.clear_challenge_state();+ Ok(false)}/// `POST /validate` — cheap liveness check. Doubles as the session heartbeat.@@ -440,7 +472,10 @@ impl Client {self.persist()?;Ok(true)}- Err(_) => Ok(false),+ // Cookies lapse after an idle spell long before the session does. Giving up here+ // left a running window signed out for good — every refresh failing quietly —+ // when the stored tokens, or the kept password, would have carried on.+ Err(_) => self.resume().await,}}@@ -458,7 +493,13 @@ impl Client {self.session.consecutive_failures = owed.consecutive_failures;self.session.retry_after = owed.retry_after;+ // Kept only once Apple has accepted it all the way: see `absorb`.+ self.pending = Some((apple_id.trim().to_string(), password.to_string()));+ self.awaiting_code = false;let outcome = self.sign_in_inner(apple_id, password).await;+ if outcome.is_err() {+ self.pending = None;+ }match &outcome {// Reaching the two-factor step means the password was accepted: not a failure.Ok(_) => {@@ -835,6 +876,13 @@ impl Client {}fn absorb(&mut self, data: &Value) {+ // A completed sign-in — with or without a code — is when a password has proved+ // itself, so that is when it is kept.+ if let Some((apple_id, password)) = self.pending.take() {+ self.session.apple_id = Some(apple_id);+ self.session.password = Some(password);+ self.awaiting_code = false;+ }if let Some(ws) = data.get("webservices") {self.session.webservices = Some(ws.clone());}diff --git a/crates/quince-auth/src/session.rs b/crates/quince-auth/src/session.rsindex 8336a34..68086be 100644--- a/crates/quince-auth/src/session.rs+++ b/crates/quince-auth/src/session.rs@@ -47,6 +47,18 @@ pub struct Session {pub webservices: Option<serde_json::Value>,pub dsid: Option<String>,+ /// The Apple ID and password, so a session that lapsed can sign itself back in.+ ///+ /// Apple keeps a web session alive for days, not months: once its token lapses only the+ /// password opens a new one, so without it every few days meant signing in by hand —+ /// which is what someone promised "sign in once" ran into. With this machine still+ /// trusted (the 60-day trust token), that sign-in needs no code. It lives here, in the OS+ /// keyring with the rest of this, never in a file; signing out erases it.+ #[serde(default)]+ pub apple_id: Option<String>,+ #[serde(default)]+ pub password: Option<String>,+/// Failed sign-ins in a row. Drives the local backoff.#[serde(default)]pub consecutive_failures: u32,diff --git a/crates/quince-auth/tests/auth_flow.rs b/crates/quince-auth/tests/auth_flow.rsindex 3ebc3db..e1921a3 100644--- a/crates/quince-auth/tests/auth_flow.rs+++ b/crates/quince-auth/tests/auth_flow.rs@@ -615,3 +615,125 @@ async fn a_different_account_does_not_inherit_the_wait() {"a different account must start clean, got: {err}");}++/// Sign in once, all the way through the code, into `dir`.+async fn signed_in(dir: &std::path::Path) {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 409).await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(ResponseTemplate::new(204))+ .mount(&server)+ .await;+ mount_trust_and_login(&server).await;+ let mut client = client_for(&server, dir);+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();+ client.submit_two_factor("123456").await.unwrap();+}++/// Apple, days later: the cookies and the session token have both lapsed.+async fn lapsed(server: &MockServer) {+ Mock::given(method("POST"))+ .and(path("/setup/ws/1/validate"))+ .respond_with(ResponseTemplate::new(421))+ .mount(server)+ .await;+ Mock::given(method("POST"))+ .and(path("/setup/ws/1/accountLogin"))+ .respond_with(ResponseTemplate::new(421))+ .up_to_n_times(1)+ .mount(server)+ .await;+ mount_init(server, 200).await;+}++/// "I was told I wouldn't need to sign in again": a session token lapses in days, and+/// without the password the only way back was the sign-in screen. Kept, it signs this+/// still-trusted computer back in — no screen, no code.+#[tokio::test]+async fn a_lapsed_session_signs_itself_back_in_without_a_code() {+ let dir = tempfile::tempdir().unwrap();+ signed_in(dir.path()).await;++ let server = MockServer::start().await;+ lapsed(&server).await;+ mount_complete(&server, 200).await; // trusted: no code asked for+ mount_trust_and_login(&server).await;++ let mut client = client_for(&server, dir.path());+ assert!(client.resume().await.unwrap(), "back in, by itself");+ assert!(!client.awaiting_code());+ let reqs = server.received_requests().await.unwrap();+ let complete = requests_to(&reqs, "/signin/complete");+ assert_eq!(complete.len(), 1);+ let body: serde_json::Value = serde_json::from_slice(&complete[0].body).unwrap();+ assert_eq!(+ body["trustTokens"][0], "trust-token-xyz",+ "this computer's trust went with it"+ );+ assert!(+ requests_to(&reqs, "/securitycode").is_empty(),+ "and no code was asked for"+ );+}++/// When the trust itself has run out, Apple wants a code: the code screen is next, not the+/// sign-in screen, and the code finishes it.+#[tokio::test]+async fn when_the_trust_has_run_out_the_code_is_all_that_is_asked() {+ let dir = tempfile::tempdir().unwrap();+ signed_in(dir.path()).await;++ let server = MockServer::start().await;+ lapsed(&server).await;+ mount_complete(&server, 409).await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(ResponseTemplate::new(204))+ .mount(&server)+ .await;+ mount_trust_and_login(&server).await;++ let mut client = client_for(&server, dir.path());+ assert!(!client.resume().await.unwrap());+ assert!(client.awaiting_code(), "the code screen is next");+ client.submit_two_factor("123456").await.unwrap();+ assert!(!client.awaiting_code());+ assert_eq!(+ client.session().password.as_deref(),+ Some("hunter2"),+ "and it stays kept"+ );+}++/// A password is kept only once Apple has accepted it all the way, and signing out erases it.+#[tokio::test]+async fn a_password_is_kept_only_once_it_has_worked_and_forgotten_on_sign_out() {+ let server = MockServer::start().await;+ mount_init(&server, 200).await;+ mount_complete(&server, 409).await;+ Mock::given(method("POST"))+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))+ .respond_with(ResponseTemplate::new(204))+ .mount(&server)+ .await;+ mount_trust_and_login(&server).await;+ let dir = tempfile::tempdir().unwrap();+ let mut client = client_for(&server, dir.path());+ client+ .sign_in("[email protected]", "hunter2")+ .await+ .unwrap();+ assert!(client.session().password.is_none(), "not before the code");+ client.submit_two_factor("123456").await.unwrap();+ assert_eq!(client.session().password.as_deref(), Some("hunter2"));+ client.sign_out().unwrap();+ assert!(+ client_for(&server, dir.path()).session().password.is_none(),+ "gone on sign-out"+ );+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex dff7006..58e2843 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -168,9 +168,36 @@ async fn auth_status(auth: State<'_, Auth>) -> UiResult<Status> {/// Try the stored session. `false` just means a sign-in is needed — not an error.#[tauri::command]-async fn auth_resume(auth: State<'_, Auth>) -> UiResult<bool> {+async fn auth_resume(auth: State<'_, Auth>) -> UiResult<&'static str> {let mut client = auth.client.lock().await;- client.resume().await.map_err(|e| e.to_string())+ let resumed = client.resume().await.map_err(|e| e.to_string())?;+ // Back in; or back in but for the code Apple wants before trusting this computer again;+ // or out, with nothing kept to sign in with.+ Ok(if resumed {+ "library"+ } else if client.awaiting_code() {+ "code"+ } else {+ "signin"+ })+}++/// Emitted when a lapsed session signed itself back in only as far as Apple's code.+const NEEDS_CODE: &str = "quince://needs-code";++/// Make sure the session is alive before a refresh uses it, signing back in if it lapsed.+///+/// A window left open past the life of Apple's cookies, or of its session token, had every+/// refresh failing quietly from then on. Checked here, a lapse is mended before it is felt;+/// one that needs a code brings the code screen up instead.+async fn keep_signed_in(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>) {+ let mut guard = client.lock().await;+ if guard.session().webservices.is_none() {+ return;+ }+ if matches!(guard.heartbeat().await, Ok(false)) && guard.awaiting_code() {+ app.emit(NEEDS_CODE, ()).ok();+ }}#[tauri::command]@@ -1512,6 +1539,7 @@ async fn sync_all(data: State<'_, Data>,) -> UiResult<refresh::Refresh> {let client = Arc::clone(&auth.client);+ keep_signed_in(&app, &client).await;let result = refresh::all(&client, &data.0).await;alerts::changed();// Screens read the library, not the network, so they only need to be told to look again.@@ -1536,6 +1564,7 @@ fn spawn_auto_sync(app: tauri::AppHandle, client: Arc<Mutex<Client>>) {if !signed_in {continue;}+ keep_signed_in(&app, &client).await;let data = app.state::<Data>();let result = refresh::all(&client, &data.0).await;alerts::changed();diff --git a/src/App.tsx b/src/App.tsxindex f9e6c99..1b79745 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -2,7 +2,8 @@ import { useEffect, useState } from "react";import { SignIn } from "./screens/SignIn";import { CodeEntry } from "./screens/CodeEntry";import { Library } from "./screens/Library";-import { api } from "./lib/ipc";+import { listen } from "@tauri-apps/api/event";+import { api, NEEDS_CODE } from "./lib/ipc";type Phase = "checking" | "signin" | "code" | "library";@@ -19,8 +20,9 @@ export default function App() {// Always resume rather than trusting stored metadata. Apple's service endpoints// authenticate by cookie, and holding a token is not the same as being able to call// them — resuming is what establishes the cookies that make the session usable.- if (status.hasStoredSession && (await api.resume())) {- return !cancelled && setPhase("library");+ if (status.hasStoredSession) {+ const next = await api.resume();+ if (next !== "signin") return !cancelled && setPhase(next);}} catch {/* fall through to sign-in */@@ -32,6 +34,15 @@ export default function App() {};}, []);+ // A session that lapsed while the window was open, and that Apple will take back only+ // with a code: the code screen, not the sign-in screen — the password is already kept.+ useEffect(() => {+ const stop = listen(NEEDS_CODE, () => setPhase("code"));+ return () => {+ void stop.then((unlisten) => unlisten()).catch(() => {});+ };+ }, []);+async function signOut() {await api.signOut().catch(() => {});setPhase("signin");diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 720a636..256c320 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -50,6 +50,8 @@ export type UploadEvent = {export const SYNCED = "quince://synced";/** An alert was clicked: open Reminders, where that reminder is. */export const OPEN_REMINDER = "quince://open-reminder";+/** A lapsed session signed itself back in only as far as Apple's code. */+export const NEEDS_CODE = "quince://needs-code";export const api = {/** One refresh for every service. Never rejects for a single service failing. */@@ -58,7 +60,8 @@ export const api = {syncStatus: () => invoke<Refresh>("sync_status"),status: () => invoke<Status>("auth_status"),- resume: () => invoke<boolean>("auth_resume"),+ /** Where a returning person goes: their library, the code Apple wants, or sign-in. */+ resume: () => invoke<"library" | "code" | "signin">("auth_resume"),signIn: (appleId: string, password: string) =>invoke<SignInResult>("auth_sign_in", { appleId, password }),submitCode: (code: string) => invoke<void>("auth_submit_code", { code }),diff --git a/src/screens/SignIn.tsx b/src/screens/SignIn.tsxindex d3529dd..44498a9 100644--- a/src/screens/SignIn.tsx+++ b/src/screens/SignIn.tsx@@ -63,7 +63,8 @@ export function SignIn({ onResult }: { onResult: (r: SignInResult) => void }) {<p className="assurance">Your password never leaves this computer. Quince proves you know it without sending- it, and keeps the result in your system keyring.+ it, and keeps it in your system keyring so it can sign itself back in. Signing out+ erases it.</p>{/** What somebody is owed before they type an Apple ID into software a stranger wrote.