Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Sign-in works without a keyring; the session's files are written whole

Yashwanth Kamireddif328dad0119b
diff --git a/.uiverify/keyring-notice.mjs b/.uiverify/keyring-notice.mjs
new file mode 100644
index 0000000..d0ab2ab
--- /dev/null
+++ b/.uiverify/keyring-notice.mjs
@@ -0,0 +1,53 @@
+// No keyring to keep the session (a window manager without one, a session over SSH): signed in
+// all the same, and said once, calmly — a quiet line under the account in the sidebar, the
+// whole sentence with what fixes it in Settings. With a keyring, nothing is said.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub } from "./stub.mjs";
+const BASE = process.env.BASE ?? process.env.URL ?? "http://localhost:4173";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+async function open(notKept) {
+ 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((notKept) => {
+ const inner = window.__TAURI_INTERNALS__.invoke;
+ window.__TAURI_INTERNALS__.invoke = async (cmd, args) => {
+ if (cmd === "auth_status") return { hasStoredSession: true, signedIn: true, libraryReady: true, notKept };
+ return inner(cmd, args);
+ };
+ }, notKept);
+ const page = await ctx.newPage();
+ await page.goto(BASE, { waitUntil: "networkidle" });
+ await page.waitForTimeout(400);
+ return { ctx, page };
+}
+
+{
+ const { ctx, page } = await open(true);
+ const line = page.locator(".sidebar-not-kept");
+ ok(await line.isVisible(), "the sidebar says the sign-in is not saved");
+ ok((await line.innerText()).trim() === "Sign-in not saved", `in a few words [${await line.innerText()}]`);
+ ok(/keyring/.test((await line.getAttribute("title")) ?? ""), "and the whole sentence is under the pointer");
+ const fits = await line.evaluate((el) => el.scrollWidth <= el.clientWidth);
+ ok(fits, "its words fit the sidebar");
+ await page.locator(".sidebar-account").click();
+ await page.waitForSelector(".settings");
+ const note = page.locator(".settings-account-note");
+ const said = (await note.innerText()).trim();
+ ok(await note.isVisible() && /until Skykeep closes/.test(said) && /GNOME Keyring or KWallet/.test(said), `Settings says what it means and what fixes it [${said}]`);
+ ok(!(await page.locator(".settings [role=alert]").count()), "calmly: no alert");
+ await ctx.close();
+}
+{
+ const { ctx, page } = await open(false);
+ ok(!(await page.locator(".sidebar-not-kept").count()), "with a keyring, the sidebar says nothing");
+ await page.locator(".sidebar-account").click();
+ await page.waitForSelector(".settings");
+ ok(!(await page.locator(".settings-account-note").count()), "nor does Settings");
+ await ctx.close();
+}
+await b.close();
+console.log(failures ? `\n${failures} FAILED` : "\nall passed");
+process.exit(failures ? 1 : 0);
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rs
index ef12c04..e49013d 100644
--- a/crates/quince-auth/src/lib.rs
+++ b/crates/quince-auth/src/lib.rs
@@ -257,6 +257,10 @@ pub struct Client {
/// The keyring would not answer when this started — locked, or not up yet. Not the same
/// as nothing stored: it is asked again before anything else happens.
keyring_error: Option<String>,
+ /// The session signed in, or taken up, but the keyring would not keep it (none running:
+ /// a window manager without one, a session over SSH): held in memory for as long as
+ /// Skykeep runs, and written again at every heartbeat until a keyring takes it.
+ unsaved: Option<String>,
/// What was last written, as a hash of the session and one of the cookies: a heartbeat that
/// changed neither writes neither (see [`Client::persist`]).
persisted: std::sync::Mutex<Persisted>,
@@ -340,6 +344,7 @@ impl Client {
pending: None,
awaiting_code: false,
keyring_error,
+ unsaved: None,
persisted: std::sync::Mutex::new(Persisted::default()),
})
}
@@ -386,7 +391,10 @@ impl Client {
.map_err(|e| Error::Protocol(format!("couldn't save the session: {e}")))?;
let mut cookies = Vec::new();
{
- let jar = self.jar.lock().expect("cookie jar mutex poisoned");
+ let jar = self
+ .jar
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
cookie_store::serde::json::save(&jar, &mut cookies)
.map_err(|e| Error::Protocol(format!("couldn't save cookies: {e}")))?;
}
@@ -406,29 +414,42 @@ impl Client {
Ok(())
}
+ /// [`Self::persist`] once Apple has accepted the session: a keyring that will not take it
+ /// never undoes that.
+ ///
+ /// With no Secret Service at all, the password went through, then the write failed and
+ /// the sign-in failed with it — before the code was even asked for — so a machine without
+ /// a keyring could never sign in, not just never stay signed in. The session is kept in
+ /// memory instead, said so ([`Self::unsaved`]), and written again on the next heartbeat.
+ /// A live session in memory is newer than anything the keyring holds, so a keyring that
+ /// would not answer at the start is not asked to replace it either.
+ fn keep(&mut self) {
+ self.keyring_error = None;
+ match self.persist() {
+ Ok(()) => self.unsaved = None,
+ Err(e) => {
+ quiet!("quince: the session is kept in memory only: {e}");
+ self.unsaved = Some(e.to_string());
+ }
+ }
+ }
+
+ /// Why the session is held in memory only, when a keyring would not keep it: Skykeep
+ /// stays signed in while it runs, but not after it closes.
+ #[must_use]
+ pub fn unsaved(&self) -> Option<&str> {
+ self.unsaved.as_deref()
+ }
+
/// The cookie jar, as `cookie_store` wrote it, to its file.
fn write_cookies(&self, cookies: &[u8]) -> Result<()> {
- use std::io::Write;
// The session's cookies are a credential: readable by this user alone, whatever folder
// they end up in (a backup, a copy), not only by the private data folder around them.
- let mut options = std::fs::OpenOptions::new();
- options.write(true).create(true).truncate(true);
- #[cfg(unix)]
- {
- use std::os::unix::fs::OpenOptionsExt;
- options.mode(0o600);
- }
- let file = options.open(self.store.cookie_path())?;
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- // A file made before this kept its old mode: set it, too.
- file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
- }
- let mut w = std::io::BufWriter::new(file);
- w.write_all(cookies)?;
- w.flush()?;
- Ok(())
+ Ok(session::write_whole(
+ self.store.cookie_path(),
+ cookies,
+ true,
+ )?)
}
/// Forget this account entirely.
@@ -512,7 +533,7 @@ impl Client {
let validated = match self.validate().await {
Ok(data) => {
self.absorb(&data);
- self.persist()?;
+ self.keep();
return Ok(true);
}
Err(e) => e,
@@ -527,7 +548,7 @@ impl Client {
let logged_in = match self.account_login().await {
Ok(data) => {
self.absorb(&data);
- self.persist()?;
+ self.keep();
return Ok(true);
}
Err(e) => e,
@@ -566,7 +587,7 @@ impl Client {
// The password was changed elsewhere: the kept one is worthless now.
Err(Error::BadCredentials) => {
self.session.password = None;
- self.persist()?;
+ self.keep();
}
Err(_) => {}
}
@@ -604,7 +625,7 @@ impl Client {
pub async fn heartbeat(&mut self) -> Result<bool> {
match self.validate().await {
Ok(_) => {
- self.persist()?;
+ self.keep();
Ok(true)
}
// Cookies lapse after an idle spell long before the session does. Giving up here
@@ -784,7 +805,7 @@ impl Client {
match status {
StatusCode::CONFLICT => {
- self.persist()?;
+ self.keep();
// Ask for the code. Apple used to push it to trusted devices on this 409 by
// itself; since iOS 26.4 it waits to be asked (PUT verify/trusteddevice/
// securitycode), and until asked no "Allow sign-in?" ever reaches a phone —
@@ -799,7 +820,7 @@ impl Client {
s if s.is_success() => {
let data = self.account_login().await?;
self.absorb(&data);
- self.persist()?;
+ self.keep();
Ok(SignInOutcome::Complete)
}
StatusCode::UNAUTHORIZED => Err(Error::BadCredentials),
@@ -927,7 +948,7 @@ impl Client {
if self.trust().await.is_ok() {
let data = self.account_login().await?;
self.absorb(&data);
- self.persist()?;
+ self.keep();
return Ok(());
}
return Err(err);
@@ -935,7 +956,7 @@ impl Client {
self.trust().await?;
let data = self.account_login().await?;
self.absorb(&data);
- self.persist()?;
+ self.keep();
Ok(())
}
@@ -974,7 +995,7 @@ impl Client {
if self.trust().await.is_ok() {
let data = self.account_login().await?;
self.absorb(&data);
- self.persist()?;
+ self.keep();
return Ok(());
}
return Err(err);
@@ -983,7 +1004,7 @@ impl Client {
self.trust().await?;
let data = self.account_login().await?;
self.absorb(&data);
- self.persist()?;
+ self.keep();
Ok(())
}
diff --git a/crates/quince-auth/src/session.rs b/crates/quince-auth/src/session.rs
index 017fd17..6301a03 100644
--- a/crates/quince-auth/src/session.rs
+++ b/crates/quince-auth/src/session.rs
@@ -260,9 +260,9 @@ fn entry_name(state_dir: &Path) -> String {
/// Windows' Credential Manager keeps at most 2,560 bytes in one credential, and the keyring
/// crate stores text there as UTF-16 — 1,280 characters. A signed-in session is larger, so on
/// Windows sign-in failed outright ("longer than platform limit of 2560 chars"). There the
-/// secret is written as parts (`<name>#1`, `<name>#2`, …) and the entry itself holds only
-/// `pomander-parts:<n>`, written last, so a save cut short never leaves a half that reads as
-/// whole. Elsewhere the whole secret stays in the one entry, as it always has; reading takes
+/// secret is written as parts (`<name>#g<k>#1`, `<name>#g<k>#2`, …, a generation `k` of their
+/// own each save) and the entry itself holds only `pomander-parts:g<k>:<n>`, written last, so a
+/// save cut short never leaves a half that reads as whole (see [`write_secret`]). Elsewhere the whole secret stays in the one entry, as it always has; reading takes
/// either shape on every platform.
trait Secrets {
fn get(&self, name: &str) -> Result<Option<String>, String>;
@@ -326,24 +326,55 @@ fn part_name(name: &str, i: usize) -> String {
format!("{name}#{i}")
}
+/// A part of generation `generation`: `name#g<k>#<i>`. Each save writes a generation of its
+/// own, beside the one the head names, and switches the head over last.
+fn generation_part(name: &str, generation: u64, i: usize) -> String {
+ format!("{name}#g{generation}#{i}")
+}
+
+/// What a head says: the secret itself, or parts — the generation they are under (`None`:
+/// written before generations, as `name#<i>`) and how many.
+enum Head {
+ Whole(String),
+ Parts(Option<u64>, usize),
+}
+
+fn head_of(value: String) -> Result<Head, String> {
+ let Some(rest) = value.strip_prefix(PARTS) else {
+ return Ok(Head::Whole(value));
+ };
+ let damaged = || "the stored sign-in is damaged".to_string();
+ let (generation, n) = match rest.strip_prefix('g').and_then(|r| r.split_once(':')) {
+ Some((g, n)) => (Some(g.parse().map_err(|_| damaged())?), n),
+ None => (None, rest),
+ };
+ let n: usize = n.parse().map_err(|_| damaged())?;
+ if n == 0 || n > MOST_PARTS {
+ return Err(damaged());
+ }
+ Ok(Head::Parts(generation, n))
+}
+
+fn part_of(name: &str, generation: Option<u64>, i: usize) -> String {
+ match generation {
+ Some(g) => generation_part(name, g, i),
+ None => part_name(name, i),
+ }
+}
+
/// The secret under `name`, whole or reassembled from its parts.
fn read_secret(k: &dyn Secrets, name: &str) -> Result<Option<String>, String> {
let Some(head) = k.get(name)? else {
return Ok(None);
};
- let Some(n) = head.strip_prefix(PARTS) else {
- return Ok(Some(head));
+ let (generation, n) = match head_of(head)? {
+ Head::Whole(value) => return Ok(Some(value)),
+ Head::Parts(generation, n) => (generation, n),
};
- let n: usize = n
- .parse()
- .map_err(|_| "the stored sign-in is damaged".to_string())?;
- if n == 0 || n > MOST_PARTS {
- return Err("the stored sign-in is damaged".into());
- }
let mut whole = String::new();
for i in 1..=n {
let part = k
- .get(&part_name(name, i))?
+ .get(&part_of(name, generation, i))?
.ok_or_else(|| "part of the stored sign-in is missing".to_string())?;
whole.push_str(&part);
}
@@ -351,6 +382,13 @@ fn read_secret(k: &dyn Secrets, name: &str) -> Result<Option<String>, String> {
}
/// Keep `value` under `name`, in parts where one entry cannot hold it.
+///
+/// The parts were written over the very names the stored session's parts had, and only then
+/// the head: a crash between them left the old head over a mix of new and old parts, read as
+/// damaged — the session lost, and two-factor asked for again. Each save's parts now go under
+/// names of their own (a new generation), the head is switched to them in one write, and only
+/// then are the old ones let go of: a crash anywhere leaves either the old session whole or
+/// the new one.
fn write_secret(
k: &dyn Secrets,
name: &str,
@@ -367,18 +405,28 @@ fn write_secret(
if parts.len() > MOST_PARTS {
return Err("the sign-in is too large to keep".into());
}
+ // What the head names now, to be let go of once the new one is in place. A damaged head
+ // names nothing to keep.
+ let before = match k.get(name)?.map(head_of) {
+ Some(Ok(Head::Parts(generation, n))) => Some((generation, n)),
+ _ => None,
+ };
+ let generation = before.and_then(|(g, _)| g).map_or(1, |g| g.wrapping_add(1));
if parts.is_empty() {
k.set(name, value)?;
} else {
- // The parts first, then the entry that says how many: read before it is written, the
- // old session (or nothing) is what is found, never a mix.
for (i, part) in parts.iter().enumerate() {
- k.set(&part_name(name, i + 1), part)?;
+ k.set(&generation_part(name, generation, i + 1), part)?;
+ }
+ k.set(name, &format!("{PARTS}g{generation}:{}", parts.len()))?;
+ }
+ // The generation before, and parts left under the names used before generations.
+ if let Some((Some(old), n)) = before {
+ for i in 1..=n {
+ k.delete(&generation_part(name, old, i))?;
}
- k.set(name, &format!("{PARTS}{}", parts.len()))?;
}
- // Parts left from a longer secret before: let go of.
- for i in parts.len() + 1..=MOST_PARTS {
+ for i in 1..=MOST_PARTS {
if k.get(&part_name(name, i))?.is_none() {
break;
}
@@ -389,6 +437,11 @@ fn write_secret(
/// Forget the secret under `name`, and every part of it.
fn delete_secret(k: &dyn Secrets, name: &str) -> Result<(), String> {
+ if let Some(Ok(Head::Parts(Some(generation), n))) = k.get(name)?.map(head_of) {
+ for i in 1..=n {
+ k.delete(&generation_part(name, generation, i))?;
+ }
+ }
k.delete(name)?;
for i in 1..=MOST_PARTS {
if k.get(&part_name(name, i))?.is_none() {
@@ -441,6 +494,42 @@ fn read_moving(
Ok(Some(old))
}
+/// Write `bytes` to `path` whole or not at all: to a file beside it, made sure of on disk, then
+/// renamed over it. Truncated in place, a crash or a full disk part way left an empty or cut-off
+/// cookie jar, read as no cookies at all: the session checked again from the start, and maybe
+/// a code asked for. `private`: readable by this user alone.
+pub(crate) fn write_whole(path: &Path, bytes: &[u8], private: bool) -> std::io::Result<()> {
+ use std::io::Write;
+ let part = path.with_file_name(format!(
+ ".{}.part",
+ path.file_name().unwrap_or_default().to_string_lossy()
+ ));
+ let written = (|| {
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ if private {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut file = options.open(&part)?;
+ #[cfg(unix)]
+ if private {
+ use std::os::unix::fs::PermissionsExt;
+ // A part left by a run before kept the mode it was made with: set it, too.
+ file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
+ }
+ let _ = private;
+ file.write_all(bytes)?;
+ file.sync_all()?;
+ std::fs::rename(&part, path)
+ })();
+ if written.is_err() {
+ let _ = std::fs::remove_file(&part);
+ }
+ written
+}
+
impl Store {
/// Production: secrets in the OS keyring.
pub fn keyring(state_dir: &Path) -> std::io::Result<Self> {
@@ -491,7 +580,7 @@ impl Store {
/// with no keyring still remembers to wait.
pub fn save_cooldown(&self, cooldown: &Cooldown) -> std::io::Result<()> {
let json = serde_json::to_string(cooldown).unwrap_or_else(|_| "{}".into());
- std::fs::write(&self.cooldown_path, json)
+ write_whole(&self.cooldown_path, json.as_bytes(), false)
}
fn name(&self) -> &str {
@@ -804,6 +893,32 @@ mod entry_tests {
}
}
+#[cfg(test)]
+mod whole_tests {
+ use super::*;
+
+ /// Written whole or not at all, owner-only, and never a part file left behind.
+ #[test]
+ fn a_file_is_replaced_whole_and_kept_private() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("cookies.json");
+ std::fs::write(&path, "old cookies").unwrap();
+ write_whole(&path, b"new cookies", true).unwrap();
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "new cookies");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode, 0o600);
+ }
+ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
+ // One that cannot be written leaves what was there as it was.
+ let gone = dir.path().join("missing").join("cookies.json");
+ assert!(write_whole(&gone, b"x", true).is_err());
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "new cookies");
+ }
+}
+
/// A secret kept in parts where one entry cannot hold it — Windows' Credential Manager — and
/// read back whole, whichever shape it was written in.
#[cfg(test)]
@@ -839,15 +954,15 @@ mod parts_tests {
write_secret(&k, "s", &session, Some(1000)).unwrap();
assert_eq!(
k.0.borrow().get("s").map(String::as_str),
- Some("pomander-parts:4")
+ Some("pomander-parts:g1:4")
);
assert_eq!(
read_secret(&k, "s").unwrap().as_deref(),
Some(session.as_str())
);
- // Shorter next time: the old fourth part goes.
+ // Shorter next time, under a generation of its own: the old parts all go.
write_secret(&k, "s", &"y".repeat(1500), Some(1000)).unwrap();
- assert!(k.0.borrow().get("s#3").is_none() && k.0.borrow().get("s#4").is_none());
+ assert_eq!(k.0.borrow().len(), 3, "{:?}", k.0.borrow().keys());
assert_eq!(read_secret(&k, "s").unwrap(), Some("y".repeat(1500)));
delete_secret(&k, "s").unwrap();
assert!(k.0.borrow().is_empty());
@@ -877,9 +992,55 @@ mod parts_tests {
fn a_missing_part_is_an_error_not_a_session() {
let k = Memory::default();
write_secret(&k, "s", &"q".repeat(2500), Some(1000)).unwrap();
- k.delete("s#2").unwrap();
+ k.delete("s#g1#2").unwrap();
assert!(read_secret(&k, "s").is_err());
}
+
+ /// A save that stops part way — the process killed, the machine off — leaves the session
+ /// before it whole. Writing the new parts over the old ones' names, it left the old head
+ /// over a mix, and the person was signed out.
+ #[test]
+ fn a_save_cut_short_leaves_the_last_session_whole() {
+ let k = Memory(RefCell::default(), Some(1280));
+ let first = "a".repeat(2500);
+ write_secret(&k, "s", &first, Some(1000)).unwrap();
+ // Cut short after its first part: the store refuses everything after.
+ struct CutShort<'a>(&'a Memory, std::cell::Cell<usize>);
+ impl Secrets for CutShort<'_> {
+ fn get(&self, name: &str) -> Result<Option<String>, String> {
+ self.0.get(name)
+ }
+ fn set(&self, name: &str, value: &str) -> Result<(), String> {
+ if self.1.get() == 0 {
+ return Err("the process ended".into());
+ }
+ self.1.set(self.1.get() - 1);
+ self.0.set(name, value)
+ }
+ fn delete(&self, name: &str) -> Result<(), String> {
+ self.0.delete(name)
+ }
+ }
+ let cut = CutShort(&k, std::cell::Cell::new(1));
+ assert!(write_secret(&cut, "s", &"b".repeat(2500), Some(1000)).is_err());
+ assert_eq!(read_secret(&k, "s").unwrap(), Some(first));
+ // The next save goes through, and nothing of the cut one is left.
+ write_secret(&k, "s", &"c".repeat(1500), Some(1000)).unwrap();
+ assert_eq!(read_secret(&k, "s").unwrap(), Some("c".repeat(1500)));
+ }
+
+ /// Parts written before generations are read, and replaced cleanly by the next save.
+ #[test]
+ fn parts_kept_before_generations_still_read_and_go() {
+ let k = Memory::default();
+ k.set("s#1", "ab").unwrap();
+ k.set("s#2", "cd").unwrap();
+ k.set("s", "pomander-parts:2").unwrap();
+ assert_eq!(read_secret(&k, "s").unwrap().as_deref(), Some("abcd"));
+ write_secret(&k, "s", &"e".repeat(1500), Some(1000)).unwrap();
+ assert!(k.0.borrow().get("s#1").is_none() && k.0.borrow().get("s#2").is_none());
+ assert_eq!(read_secret(&k, "s").unwrap(), Some("e".repeat(1500)));
+ }
}
/// The session moving from the old identifier's keyring service to the new one.
@@ -946,7 +1107,7 @@ mod move_tests {
#[test]
fn a_session_in_parts_moves_whole_with_every_part() {
- // Windows: the Credential Manager's targets are `session` and `session#1..n`.
+ // Windows: the Credential Manager's targets are `session` and `session#g1#1..n`.
let big = "w".repeat(3500);
let old = holding("session", &big, Some(1000));
assert_eq!(old.held.borrow().len(), 5);
@@ -957,7 +1118,7 @@ mod move_tests {
);
assert_eq!(
new.held.borrow().get("session").map(String::as_str),
- Some("pomander-parts:4")
+ Some("pomander-parts:g1:4")
);
assert_eq!(read_secret(&new, "session").unwrap(), Some(big));
assert!(
diff --git a/crates/quince-auth/tests/auth_flow.rs b/crates/quince-auth/tests/auth_flow.rs
index cf06464..33fb586 100644
--- a/crates/quince-auth/tests/auth_flow.rs
+++ b/crates/quince-auth/tests/auth_flow.rs
@@ -885,3 +885,49 @@ async fn a_heartbeat_writes_the_session_only_when_it_changed() {
let kept = std::fs::read_to_string(&stored).expect("a changed session is written");
assert!(kept.contains("scnt-renewed"));
}
+
+/// No Secret Service (a window manager without a keyring, a session over SSH): the store
+/// refuses every write. The password went through and then the sign-in failed on that write,
+/// before the code was even asked for, so such a machine could never sign in at all. Now it
+/// signs in, holds the session in memory, says so, and writes it once the store takes it.
+#[tokio::test]
+async fn a_store_that_will_not_keep_the_session_never_fails_the_sign_in() {
+ 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;
+ Mock::given(method("POST"))
+ .and(path("/setup/ws/1/validate"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
+ .mount(&server)
+ .await;
+
+ let dir = tempfile::tempdir().unwrap();
+ // Where the session would be written is a folder: every save fails.
+ let blocked = dir.path().join("session.json");
+ std::fs::create_dir(&blocked).unwrap();
+ let mut client = client_for(&server, dir.path());
+
+ let outcome = client
+ .sign_in("[email protected]", "hunter2")
+ .await
+ .expect("the password was accepted: the code is asked for");
+ assert_eq!(outcome, SignInOutcome::NeedsTwoFactor);
+ client
+ .submit_two_factor("123456")
+ .await
+ .expect("signed in, if only for as long as it runs");
+ assert!(client.session().webservices.is_some());
+ assert!(client.unsaved().is_some(), "said that it is not kept");
+
+ // A keyring comes up: the next heartbeat writes it, and nothing is said any more.
+ std::fs::remove_dir(&blocked).unwrap();
+ assert!(client.heartbeat().await.unwrap());
+ assert!(client.unsaved().is_none());
+ assert!(client_for(&server, dir.path()).has_stored_session());
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index dc894ef..345383d 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -92,6 +92,8 @@ struct SessionFacts {
email: Option<String>,
web_access_allowed: Option<bool>,
data_protection: Option<bool>,
+ /// Signed in, but no keyring would keep the session: it lasts as long as Skykeep runs.
+ unsaved: bool,
}
impl SessionFacts {
@@ -115,6 +117,7 @@ impl SessionFacts {
email: s.account_email.clone().or_else(|| s.apple_id.clone()),
web_access_allowed: s.web_access_allowed,
data_protection: s.data_protection,
+ unsaved: client.unsaved().is_some(),
}
}
}
@@ -161,6 +164,8 @@ struct Status {
/// The stored session's account is the one the library already belongs to: the library
/// can open on what it holds at once, while the session is taken up again behind it.
library_ready: bool,
+ /// Signed in for as long as Skykeep runs only: no keyring would keep the session.
+ not_kept: bool,
}
struct Data(library_lock::LibraryLock);
@@ -985,6 +990,7 @@ async fn auth_status(auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<S
library_ready: facts.has_stored_session
&& facts.account.is_some()
&& owner == facts.account,
+ not_kept: facts.signed_in && facts.unsaved,
})
}
diff --git a/src/components/Account.tsx b/src/components/Account.tsx
index 649857b..2420ca0 100644
--- a/src/components/Account.tsx
+++ b/src/components/Account.tsx
@@ -1,6 +1,27 @@
import { useEffect, useRef, useState } from "react";
import { Face } from "./Face";
import { api, contactPhotoSrc, type AccountInfo } from "../lib/ipc";
+
+/** Said where the session is held in memory only: what it means, and what fixes it. */
+export const NOT_KEPT =
+ "Signed in until Skykeep closes: start a system keyring (GNOME Keyring or KWallet) to stay signed in.";
+
+/**
+ * Whether the session lasts only as long as Skykeep runs — no keyring would keep it. Asked
+ * again after every update, which is when the session is written again.
+ */
+export function useNotKept(): boolean {
+ const { report } = useSync();
+ const [notKept, setNotKept] = useState(false);
+ useEffect(() => {
+ let live = true;
+ api.status().then((s) => live && setNotKept(!!s.notKept), () => {});
+ return () => {
+ live = false;
+ };
+ }, [report]);
+ return notKept;
+}
import { freshness, useServiceState, useSync } from "../lib/sync";
/** "Asha Rao" → "AR"; an address → its first letter. */
@@ -38,6 +59,7 @@ export type FooterApp = { service: string; name: string };
export function AccountCard({ current, onOpen, app }: { current: boolean; onOpen: () => void; app?: FooterApp | null }) {
const [account, setAccount] = useState<AccountInfo | null>(null);
const { report, syncing, error, refreshService, refresh: refreshAll } = useSync();
+ const notKept = useNotKept();
const own = useServiceState(app?.service ?? "");
// "Updated just now" has to become "2 min ago" without anything else happening.
const [, tick] = useState(0);
@@ -118,6 +140,11 @@ export function AccountCard({ current, onOpen, app }: { current: boolean; onOpen
<AccountAvatar account={account} />
<span className="sidebar-account-name">{name}</span>
</button>
+ {notKept && (
+ <p className="sidebar-not-kept" title={NOT_KEPT}>
+ Sign-in not saved
+ </p>
+ )}
</div>
);
}
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 379b819..fb006ba 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -1,6 +1,12 @@
import { convertFileSrc, invoke } from "@tauri-apps/api/core";
-export type Status = { hasStoredSession: boolean; signedIn: boolean; libraryReady: boolean };
+export type Status = {
+ hasStoredSession: boolean;
+ signedIn: boolean;
+ libraryReady: boolean;
+ /** Signed in only while Skykeep runs: no system keyring would keep the session. */
+ notKept: boolean;
+};
/** A change made here waiting for Apple. */
export type WaitingChange = { service: string; record: string; kind: string };
diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsx
index ac498a5..9a5ac62 100644
--- a/src/screens/SettingsView.tsx
+++ b/src/screens/SettingsView.tsx
@@ -26,7 +26,7 @@ import {
import { freshness, useSync } from "../lib/sync";
import { setTheme, storedTheme, type Theme } from "../lib/theme";
import { AppIcon } from "../components/AppIcon";
-import { AccountAvatar } from "../components/Account";
+import { AccountAvatar, NOT_KEPT, useNotKept } from "../components/Account";
import { Picker } from "../components/Picker";
import { localeFirstDay, setWeekStart, weekStartChoice, type WeekStartChoice } from "./calendar/model";
@@ -488,6 +488,7 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom
const [login, setLogin] = useState<LoginItem | null>(null);
const [loginBusy, setLoginBusy] = useState(false);
const { report, syncing, refresh } = useSync();
+ const notKept = useNotKept();
useEffect(() => {
api.accountInfo().then(setAccount, () => setAccount({ name: null, email: null }));
@@ -572,6 +573,7 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom
<div className="settings-account-text">
<strong>{account?.name ?? "Your Apple Account"}</strong>
<span>{account?.email ?? ""}</span>
+ {notKept && <span className="settings-account-note">{NOT_KEPT}</span>}
</div>
<button
className="quiet"
diff --git a/src/styles/app.css b/src/styles/app.css
index 4acd6f3..83788f1 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -1687,6 +1687,7 @@
.settings-account-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
.settings-account-text strong { font-size: var(--t-17); font-weight: 600; }
.settings-account-text span { color: var(--text-2); font-size: var(--t-13); overflow: hidden; text-overflow: ellipsis; }
+.settings-account-text .settings-account-note { font-size: var(--t-12); overflow: visible; text-overflow: clip; text-wrap: pretty; }
.storage-bar { height: 8px; border-radius: var(--r-pill); background: color-mix(in srgb, var(--text) 10%, transparent); overflow: hidden; }
.storage-bar > span { display: block; height: 100%; border-radius: inherit; background: var(--accent); }
@@ -1826,6 +1827,13 @@
.is-rail .sidebar-sync { justify-content: center; padding-inline: 0; }
.is-rail .sidebar-sync-text, .is-rail .sidebar-sync-now { display: none; }
.is-rail .sidebar-foot-stack .sidebar-account-name { display: none; }
+/* A session no keyring would keep: one quiet line under who is signed in, the whole sentence
+ in Settings. */
+.sidebar-not-kept {
+ margin: 0; padding: 0 8px 0 47px; color: var(--text-2); font-size: var(--t-11);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+}
+.is-rail .sidebar-not-kept { display: none; }
.sidebar .status-line { padding: 4px 8px; font-size: var(--t-11); }
.drive-bar .drive-title { flex: 1 1 14ch; }