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: keep Apple's session cookies, and send a code only when the person asks

Yashwanth Kamireddie81fc93e7bcf
diff --git a/.uiverify/code-lapse.mjs b/.uiverify/code-lapse.mjs
new file mode 100644
index 0000000..1b6fe02
--- /dev/null
+++ b/.uiverify/code-lapse.mjs
@@ -0,0 +1,59 @@
+// Skykeep signed itself back in and Apple wants a code before it trusts this computer again.
+// Nothing reaches the person's phone until they ask: the library stays, readable, with one calm
+// line and Sign In; the code is asked for once they press it — never by the launch, the timer
+// or a sync behind their back. The same when it lapses while the window is open.
+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++; };
+const LINE = "Sign in again to keep syncing. Your copy on this computer is still here.";
+
+async function open(resume) {
+ const ctx = await b.newContext({ viewport: { width: 1180, height: 800 } });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: { trustedDeviceCount: 1, phones: [], tooManyCodesSent: false } });
+ await ctx.addInitScript((resume) => {
+ const inner = window.__TAURI_INTERNALS__.invoke;
+ window.__TAURI_INTERNALS__.invoke = async (cmd, args) => {
+ if (cmd === "auth_status") return { hasStoredSession: true, signedIn: false, libraryReady: true, notKept: false };
+ if (cmd === "auth_resume") return resume;
+ return inner(cmd, args);
+ };
+ }, resume);
+ const page = await ctx.newPage();
+ await page.goto(BASE, { waitUntil: "networkidle" });
+ await page.waitForTimeout(500);
+ return { ctx, page };
+}
+const requests = (page) => page.evaluate(() => window.__codeRequests ?? 0);
+
+// At launch.
+{
+ const { ctx, page } = await open("code");
+ ok(await page.locator(".sidebar").isVisible(), "the library opens on what it holds");
+ ok(!(await page.locator(".code").count()), "not the code screen by itself");
+ ok((await page.locator("body").innerText()).includes(LINE), "one calm line says to sign in again");
+ ok((await requests(page)) === 0, "and no code is asked for");
+ await page.getByRole("button", { name: "Sign In" }).click();
+ await page.locator(".code").waitFor({ timeout: 5000 }).catch(() => {});
+ await page.waitForTimeout(200);
+ ok(await page.locator(".code").first().isVisible(), "Sign In opens the code screen");
+ ok((await requests(page)) === 1, "which asks Apple for the code, once");
+ await ctx.close();
+}
+
+// While the window is open.
+{
+ const { ctx, page } = await open("library");
+ await page.evaluate(() => window.__emit?.("quince://needs-code", null));
+ await page.waitForTimeout(300);
+ ok(await page.locator(".sidebar").isVisible(), "a lapse while open keeps the library in front");
+ ok((await page.locator("body").innerText()).includes(LINE), "with the same line");
+ ok((await requests(page)) === 0, "and nothing sent to the phone");
+ await ctx.close();
+}
+
+await b.close();
+if (failures) { console.log(`${failures} failed`); process.exit(1); }
+console.log("all passed");
diff --git a/.uiverify/resume.mjs b/.uiverify/resume.mjs
index cef59ad..a9a2cef 100644
--- a/.uiverify/resume.mjs
+++ b/.uiverify/resume.mjs
@@ -1,6 +1,10 @@
// 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.
+//
+// Nothing is sent to the person's phone until they ask: the window may have opened by itself
+// (at login), and a code nobody asked for, pushed to their iPhone, is exactly what they should
+// never get. The screen says Apple wants a code and offers Send Code.
import { engine } from "./engine.mjs";
const b = await engine.launch();
@@ -12,6 +16,10 @@ await ctx.addInitScript(() => {
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 === "auth_request_code") {
+ window.__codeRequests = (window.__codeRequests ?? 0) + 1;
+ return null;
+ }
if (cmd === "plugin:event|listen") return 0;
return [];
},
@@ -20,12 +28,22 @@ await ctx.addInitScript(() => {
const page = await ctx.newPage();
await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
await page.waitForTimeout(500);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
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)}`);
+ok(where.code && !where.library && !where.signIn, `a lapsed session that needs a code opens on the code screen (${JSON.stringify(where)})`);
+ok(!(await page.evaluate(() => window.__codeRequests)), "no code is asked for until the person asks");
+ok((await page.locator(".lede").innerText()).includes("Apple wants a code before it trusts this computer again."), "the screen says Apple wants a code, not that one was sent");
+const send = page.getByRole("button", { name: "Send Code" });
+ok(await send.isVisible(), "and offers Send Code");
+await send.click();
+await page.waitForTimeout(200);
+ok((await page.evaluate(() => window.__codeRequests)) === 1, "Send Code asks Apple once");
+ok(!(await send.isVisible()), "then the button goes");
+ok((await page.locator(".lede").innerText()).includes("Apple sent a code"), "and the screen says where it went");
await b.close();
-process.exitCode = ok ? 0 : 1;
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index cad255a..fd4e880 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -1130,6 +1130,10 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "drive_item": return null;
case "auth_two_factor_options": return twoFactor;
case "auth_resend_code": return null;
+ // Counted, so a suite can tell a code was asked for only when the person was there.
+ case "auth_request_code":
+ window.__codeRequests = (window.__codeRequests ?? 0) + 1;
+ return null;
case "auth_send_sms": return null;
case "auth_submit_sms_code": window.__codeVia = `sms:${args?.phoneId}`; return null;
case "auth_sign_out": sessionStorage.setItem("__signedOut", JSON.stringify(args)); return null;
diff --git a/check.sh b/check.sh
index fc9dc79..0396c0c 100755
--- a/check.sh
+++ b/check.sh
@@ -169,6 +169,7 @@ step "webkit: drive nav" env ENGINE=webkit node .uiverify/drive-nav.mjs
step "sign-in keyring" node .uiverify/signin-keyring.mjs
step "lapse reason" node .uiverify/lapse-reason.mjs
step "device approval" node .uiverify/device-approval.mjs
+step "code only when asked" node .uiverify/code-lapse.mjs
step "webkit: approval" env ENGINE=webkit node .uiverify/device-approval.mjs
step "calendar undo" node .uiverify/calendar-undo.mjs
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rs
index 97541b6..2d4c91c 100644
--- a/crates/quince-auth/src/lib.rs
+++ b/crates/quince-auth/src/lib.rs
@@ -354,6 +354,15 @@ pub enum SignInOutcome {
NeedsTwoFactor,
}
+/// Whether a sign-in that Apple wants a code for asks Apple to send it now.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Code {
+ /// The person just typed their password and the code screen is next: ask.
+ Send,
+ /// Nobody is watching (a lapse mended in the background): leave it to the code screen.
+ Wait,
+}
+
/// OAuth headers every idmsa call carries. Deliberately sets no Origin: the HTTP client
/// defaults to the icloud.com origin, which is what the verify, trust and phone endpoints
/// expect. Only SRP overrides it — see [`with_srp_origin`].
@@ -410,6 +419,9 @@ pub struct Client {
pending: Option<(String, String)>,
/// A lapsed session tried to sign itself back in and Apple wants a code first.
awaiting_code: bool,
+ /// Apple has been asked to send this sign-in's code — to the devices, or by text — so the
+ /// code screen opening does not ask for another.
+ code_sent: bool,
/// 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>,
@@ -488,9 +500,7 @@ fn read_jar(store: &Store) -> (cookie_store::CookieStore, Cookies) {
};
let sealed_in_place = (|| -> Result<()> {
let key = store.cookie_key_or_new()?;
- let mut json = Vec::new();
- cookie_store::serde::json::save(&jar, &mut json)
- .map_err(|e| Error::Protocol(format!("couldn't save cookies: {e}")))?;
+ let json = jar_bytes(&jar)?;
Ok(session::write_whole(
path,
&sealed::seal(&key, &json)?,
@@ -504,6 +514,23 @@ fn read_jar(store: &Store) -> (cookie_store::CookieStore, Cookies) {
(jar, Cookies::Read)
}
+/// The jar as it is written to disk: every cookie that has not run out, Apple's session
+/// cookies among them.
+///
+/// `cookie_store`'s own `save` keeps only cookies with an expiry, and Apple sets several of the
+/// ones its sign-in leans on without one — idmsa's own, and some of icloud.com's. Each start
+/// came back without them, so the next sign-in was a stranger's and Apple asked for a code
+/// again, about every day. pyicloud and icloudpd keep them the same way (`LWPCookieJar.save(
+/// ignore_discard=True)`), as a browser that restores its session does. They are a credential
+/// like the rest of the jar, and sealed with it (see [`sealed`]).
+fn jar_bytes(jar: &cookie_store::CookieStore) -> Result<Vec<u8>> {
+ let cookies: Vec<&cookie_store::Cookie<'static>> = jar.iter_unexpired().collect();
+ let mut out = serde_json::to_vec_pretty(&cookies)
+ .map_err(|e| Error::Protocol(format!("couldn't save cookies: {e}")))?;
+ out.push(b'\n');
+ Ok(out)
+}
+
/// Hashes of the session and the cookie jar as last written; `None` for not written yet.
#[derive(Default)]
struct Persisted {
@@ -572,6 +599,7 @@ impl Client {
endpoints,
pending: None,
awaiting_code: false,
+ code_sent: false,
keyring_error,
unsaved: None,
persisted: std::sync::Mutex::new(Persisted::default()),
@@ -658,15 +686,13 @@ impl Client {
fn persist(&self) -> Result<()> {
let session = serde_json::to_vec(&self.session)
.map_err(|e| Error::Protocol(format!("couldn't save the session: {e}")))?;
- let mut cookies = Vec::new();
- {
+ let cookies = {
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}")))?;
- }
+ jar_bytes(&jar)?
+ };
let (session, cookies) = (hash_of(&session), (hash_of(&cookies), cookies));
let mut last = self
.persisted
@@ -854,7 +880,10 @@ impl Client {
(self.session.apple_id.clone(), self.session.password.clone())
{
let before = self.session.clone();
- match self.sign_in(&apple_id, &password).await {
+ // Quietly: a code is asked for only once the person is at the code screen. Asked
+ // for here, every lapse — the heartbeat's, a sync's, a launch at login — put an
+ // "Allow sign-in?" and a code on their phone while they were nowhere near Skykeep.
+ match self.sign_in_as(&apple_id, &password, Code::Wait).await {
Ok(SignInOutcome::Complete) => return Ok(true),
// Lost the network part way, or Apple busy, down or asking to wait: not a
// refusal. What was kept is put back as it was and the next try is left to
@@ -932,6 +961,16 @@ impl Client {
/// The password is never sent to Apple — SRP proves knowledge of it without transmitting
/// it. Apple retired the old cleartext endpoint; it now answers 503.
pub async fn sign_in(&mut self, apple_id: &str, password: &str) -> Result<SignInOutcome> {
+ self.sign_in_as(apple_id, password, Code::Send).await
+ }
+
+ /// [`Self::sign_in`], saying whether a code Apple wants is asked for now.
+ async fn sign_in_as(
+ &mut self,
+ apple_id: &str,
+ password: &str,
+ code: Code,
+ ) -> Result<SignInOutcome> {
// What this account already owes, from beside the cookies rather than from the
// keyring — so a machine with no keyring still remembers, which is where forgetting
// would matter most. Per account, so signing in as somebody else inherits nothing.
@@ -942,7 +981,7 @@ impl Client {
// 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;
+ let outcome = self.sign_in_inner(apple_id, password, code).await;
if outcome.is_err() {
self.pending = None;
}
@@ -988,7 +1027,12 @@ impl Client {
outcome
}
- async fn sign_in_inner(&mut self, apple_id: &str, password: &str) -> Result<SignInOutcome> {
+ async fn sign_in_inner(
+ &mut self,
+ apple_id: &str,
+ password: &str,
+ code: Code,
+ ) -> Result<SignInOutcome> {
// Refuse before touching Apple. Hammering sign-in is what gets an account
// temporarily locked, and an impatient user clicking twice should not risk that.
if let Some(until) = self.session.retry_after {
@@ -1005,6 +1049,7 @@ impl Client {
self.clear_challenge_state();
// A new web session: its encrypted services' keys are its own to ask for.
self.data_access_forget();
+ self.code_sent = false;
let client = srp::Client::new(apple_id);
@@ -1106,14 +1151,19 @@ impl Client {
match status {
StatusCode::CONFLICT => {
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 —
- // which is why the only way a code ever arrived here was Airplane Mode and
- // Settings, or pressing "Send again". Not fatal if it fails: the code screen
- // still offers sending it again, and a text.
- if let Err(e) = self.resend_to_devices().await {
- quiet!("asking Apple to send the code: {e}");
+ // Ask for the code — when the person has just typed their password. 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 — which is why the only way a code ever
+ // arrived here was Airplane Mode and Settings, or pressing "Send again". Not
+ // fatal if it fails: the code screen still offers sending it again, and a text.
+ //
+ // A sign-in nobody is watching (a lapse mended in the background) asks for
+ // nothing: the code screen asks once the person opens it ([`Self::request_code`]).
+ if code == Code::Send {
+ if let Err(e) = self.resend_to_devices().await {
+ quiet!("asking Apple to send the code: {e}");
+ }
}
Ok(SignInOutcome::NeedsTwoFactor)
}
@@ -1180,6 +1230,16 @@ impl Client {
)
}
+ /// The code screen is open: ask Apple to send the code, unless it was already asked for
+ /// this sign-in (the person typed their password a moment ago, or had it texted). A lapse
+ /// mended in the background left it unasked on purpose — see [`Self::resume`].
+ pub async fn request_code(&mut self) -> Result<()> {
+ if self.code_sent {
+ return Ok(());
+ }
+ self.resend_to_devices().await
+ }
+
/// Ask Apple to push the code to trusted devices again.
pub async fn resend_to_devices(&mut self) -> Result<()> {
let mut headers = self.auth_headers();
@@ -1199,6 +1259,7 @@ impl Client {
let body = r.text().await.unwrap_or_default();
return Err(apple_error("sending the code again", status, &body));
}
+ self.code_sent = true;
Ok(())
}
@@ -1222,6 +1283,7 @@ impl Client {
let body = r.text().await.unwrap_or_default();
return Err(apple_error("texting the code", status, &body));
}
+ self.code_sent = true;
Ok(())
}
diff --git a/crates/quince-auth/tests/auth_flow.rs b/crates/quince-auth/tests/auth_flow.rs
index 38213bc..084746a 100644
--- a/crates/quince-auth/tests/auth_flow.rs
+++ b/crates/quince-auth/tests/auth_flow.rs
@@ -1325,3 +1325,230 @@ async fn new_terms_on_a_kept_session_keep_it() {
"no sign-in into the same terms"
);
}
+
+/// The PUTs that ask Apple to send a code to the person's devices.
+fn code_pushes(reqs: &[Request]) -> usize {
+ requests_to(reqs, "/verify/trusteddevice/securitycode")
+ .into_iter()
+ .filter(|r| r.method.as_str() == "PUT")
+ .count()
+}
+
+/// "My iPhone shows a code prompt out of nowhere." A lapse mended in the background — the
+/// heartbeat, a sync, a launch at login — that Apple answers with "a code first" asks Apple to
+/// send nothing: the person is nowhere near the code screen. The code is sent once they open
+/// it, and only once.
+#[tokio::test]
+async fn signing_back_in_by_itself_never_pushes_a_code_to_the_phone() {
+ 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("PUT"))
+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))
+ .respond_with(ResponseTemplate::new(202))
+ .mount(&server)
+ .await;
+
+ let mut client = client_for(&server, dir.path());
+ assert!(!client.resume().await.unwrap());
+ assert!(client.awaiting_code(), "the code screen is what comes next");
+ assert_eq!(
+ code_pushes(&server.received_requests().await.unwrap()),
+ 0,
+ "and nothing was sent to the phone meanwhile"
+ );
+ // A heartbeat later, still nothing.
+ let _ = client.heartbeat().await;
+ assert_eq!(code_pushes(&server.received_requests().await.unwrap()), 0);
+
+ // The person opens the code screen: now it is sent — once, however often it opens.
+ client.request_code().await.unwrap();
+ client.request_code().await.unwrap();
+ assert_eq!(code_pushes(&server.received_requests().await.unwrap()), 1);
+}
+
+/// Typing the password is asking for the code: sent straight away, as before — and the code
+/// screen opening after it does not send a second.
+#[tokio::test]
+async fn a_sign_in_by_hand_sends_the_code_once() {
+ let server = MockServer::start().await;
+ mount_init(&server, 200).await;
+ mount_complete(&server, 409).await;
+ Mock::given(method("PUT"))
+ .and(path("/appleauth/auth/verify/trusteddevice/securitycode"))
+ .respond_with(ResponseTemplate::new(202))
+ .mount(&server)
+ .await;
+ let dir = tempfile::tempdir().unwrap();
+ let mut client = client_for(&server, dir.path());
+ assert_eq!(
+ client
+ .sign_in("[email protected]", "hunter2")
+ .await
+ .unwrap(),
+ SignInOutcome::NeedsTwoFactor
+ );
+ client.request_code().await.unwrap();
+ assert_eq!(code_pushes(&server.received_requests().await.unwrap()), 1);
+ // Sending it again by hand always goes.
+ client.resend_to_devices().await.unwrap();
+ assert_eq!(code_pushes(&server.received_requests().await.unwrap()), 2);
+}
+
+/// Apple's sign-in leans on cookies it sets without an expiry (idmsa's own, some of
+/// icloud.com's). `cookie_store`'s save dropped every one of them, so each start's sign-in came
+/// back a stranger's and Apple asked for a code again — about daily. They are kept now, sealed
+/// with the rest, and sent again after a restart; ones that ran out are not.
+#[tokio::test]
+async fn the_cookies_apple_sets_without_an_expiry_survive_a_restart() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/appleauth/auth/signin/init"))
+ .respond_with(
+ ResponseTemplate::new(200)
+ .append_header("set-cookie", "aasp=idmsa-session; Path=/")
+ .append_header("set-cookie", "dslang=GB-EN; Path=/")
+ .set_body_json(json!({
+ "salt": b64(&[0x77; 16]), "b": b64(&[0x5e; 256]), "c": "challenge-c",
+ "iteration": 20173, "protocol": "s2k",
+ })),
+ )
+ .mount(&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;
+ Mock::given(method("GET"))
+ .and(path("/appleauth/auth/2sv/trust"))
+ .respond_with(
+ ResponseTemplate::new(204)
+ .insert_header("X-Apple-TwoSV-Trust-Token", "trust-token-xyz")
+ .insert_header("X-Apple-Session-Token", "session-token-def"),
+ )
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path("/setup/ws/1/accountLogin"))
+ .respond_with(
+ ResponseTemplate::new(200)
+ .append_header("set-cookie", "X-APPLE-WEBAUTH-HSA-LOGIN=login; Path=/")
+ .append_header("set-cookie", "X-APPLE-WEBAUTH-USER=user; Path=/; Max-Age=2592000")
+ .append_header("set-cookie", "gone=old; Path=/; Max-Age=0")
+ .set_body_json(json!({
+ "dsInfo": { "dsid": "1234567890" },
+ "webservices": { "calendar": { "url": "https://p00-calendarws.test.invalid:443" } }
+ })),
+ )
+ .mount(&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();
+ let client_id = {
+ let mut client = client_for(&server, dir.path());
+ client
+ .sign_in("[email protected]", "hunter2")
+ .await
+ .unwrap();
+ client.submit_two_factor("123456").await.unwrap();
+ client.session().client_id.clone()
+ };
+ assert!(client_id.is_some());
+
+ // The next start.
+ server.reset().await;
+ Mock::given(method("POST"))
+ .and(path("/setup/ws/1/validate"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
+ .mount(&server)
+ .await;
+ let mut again = client_for(&server, dir.path());
+ assert_eq!(
+ again.session().client_id,
+ client_id,
+ "the same client id: Apple ties the trust to it"
+ );
+ assert!(again.resume().await.unwrap());
+ let reqs = server.received_requests().await.unwrap();
+ let validate = requests_to(&reqs, "/setup/ws/1/validate");
+ let sent: Vec<String> = validate[0]
+ .headers
+ .get_all("cookie")
+ .iter()
+ .filter_map(|v| v.to_str().ok())
+ .flat_map(|v| v.split(';'))
+ .filter_map(|c| c.split('=').next())
+ .map(|n| n.trim().to_string())
+ .collect();
+ for name in [
+ "aasp",
+ "dslang",
+ "X-APPLE-WEBAUTH-HSA-LOGIN",
+ "X-APPLE-WEBAUTH-USER",
+ ] {
+ assert!(
+ sent.iter().any(|n| n == name),
+ "{name} came back after a restart: {sent:?}"
+ );
+ }
+ assert!(
+ !sent.iter().any(|n| n == "gone"),
+ "one that ran out did not"
+ );
+}
+
+/// The whole promise, end to end: a computer Apple already trusts, signing in again with its
+/// trust token, gets no code — nothing pushed, no code screen.
+#[tokio::test]
+async fn a_trusted_computer_signing_in_again_is_asked_for_no_code() {
+ let dir = tempfile::tempdir().unwrap();
+ signed_in(dir.path()).await;
+
+ let server = MockServer::start().await;
+ mount_init(&server, 200).await;
+ // Apple honours the trust token only when it is sent: 409 without it, 200 with it.
+ Mock::given(method("POST"))
+ .and(path("/appleauth/auth/signin/complete"))
+ .and(wiremock::matchers::body_partial_json(
+ json!({ "trustTokens": ["trust-token-xyz"] }),
+ ))
+ .respond_with(
+ ResponseTemplate::new(200)
+ .insert_header("X-Apple-Session-Token", "session-token-new")
+ .set_body_json(json!({})),
+ )
+ .mount(&server)
+ .await;
+ mount_complete(&server, 409).await;
+ mount_trust_and_login(&server).await;
+
+ let mut client = client_for(&server, dir.path());
+ assert_eq!(
+ client
+ .sign_in("[email protected]", "hunter2")
+ .await
+ .unwrap(),
+ SignInOutcome::Complete
+ );
+ let reqs = server.received_requests().await.unwrap();
+ assert_eq!(code_pushes(&reqs), 0, "nothing sent to the phone");
+ assert!(
+ requests_to(&reqs, "/2sv/trust").is_empty(),
+ "no code to trust"
+ );
+ assert_eq!(
+ client.session().trust_token.as_deref(),
+ Some("trust-token-xyz"),
+ "and the trust is kept as it was"
+ );
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 1eb1ede..4a94c53 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1331,9 +1331,19 @@ async fn keep_signed_in(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>) {
return;
}
match guard.heartbeat().await {
+ // Apple wants a code before it trusts this computer again. None has been asked for:
+ // the window says so calmly, and the code is sent once the person opens the code
+ // screen from there — never pushed to their phone from a background pass.
Ok(false) if guard.awaiting_code() => {
LIVE.store(false, Ordering::SeqCst);
app.emit(NEEDS_CODE, ()).ok();
+ if !TOLD.swap(true, std::sync::atomic::Ordering::Relaxed) {
+ alerts::tell(
+ app,
+ "Sign in again to keep syncing",
+ "Open Skykeep to get a code from Apple. Your copy on this computer is still here.",
+ );
+ }
}
// Apple will not take the session back without the password: every sync would fail
// quietly from here on. The window says so where it is open, and the desktop once,
@@ -1773,6 +1783,15 @@ async fn auth_two_factor_options(auth: State<'_, Auth>) -> UiResult<TwoFactorOpt
client.two_factor_options().await.map_err(|e| e.to_string())
}
+/// The code screen opened: Apple is asked for the code now, unless this sign-in already asked
+/// (the person typed their password a moment ago). A lapse mended in the background leaves it
+/// unasked, so nothing reaches the person's phone until they are here for it.
+#[tauri::command]
+async fn auth_request_code(auth: State<'_, Auth>) -> UiResult<()> {
+ let mut client = auth.client.lock().await;
+ client.request_code().await.map_err(|e| e.to_string())
+}
+
#[tauri::command]
async fn auth_resend_code(auth: State<'_, Auth>) -> UiResult<()> {
let mut client = auth.client.lock().await;
@@ -6887,6 +6906,7 @@ fn main() {
auth_submit_code,
auth_two_factor_options,
auth_resend_code,
+ auth_request_code,
auth_send_sms,
auth_submit_sms_code,
auth_sign_out,
diff --git a/src/App.tsx b/src/App.tsx
index f25fa91..5a15454 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -13,6 +13,14 @@ type Phase = "checking" | "signin" | "code" | "library";
export default function App() {
const [phase, setPhase] = useState<Phase>("checking");
+ /** How the code screen asks for its code (`CodeEntry`'s `request`). */
+ const [codeRequest, setCodeRequest] = useState<"now" | "ask" | undefined>(undefined);
+ /**
+ * Skykeep signed itself back in and Apple wants a code first. Nothing has been sent: the
+ * library stays, with one line saying so, and the code is asked for once the person opens
+ * the code screen from it.
+ */
+ const [codeLapse, setCodeLapse] = useState(false);
// Why the stored session could not be taken up, said once on the sign-in screen.
const [why, setWhy] = useState<string | null>(null);
// The window is shown once the first real screen (the library, or sign-in) is in the page:
@@ -65,7 +73,7 @@ export default function App() {
return "signin" as const;
});
if (cancelled) return;
- if (next === "code") setPhase("code");
+ if (next === "code") setCodeLapse(true);
else if (next === "signin") setLapsed(true);
return;
}
@@ -76,6 +84,7 @@ export default function App() {
if (!cancelled) setWhy(messageOf(err));
return "signin" as const;
});
+ if (next === "code") setCodeRequest("ask");
if (next !== "signin") return !cancelled && setPhase(next);
}
} catch {
@@ -91,7 +100,7 @@ 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"));
+ const stop = listen(NEEDS_CODE, () => setCodeLapse(true));
return () => {
void stop.then((unlisten) => unlisten()).catch(() => {});
};
@@ -124,6 +133,22 @@ export default function App() {
return () => dismissToast(id);
}, [lapsed, phase, why]);
+ useEffect(() => {
+ if (!codeLapse || phase !== "library") return undefined;
+ const id = toast({
+ message: "Sign in again to keep syncing. Your copy on this computer is still here.",
+ duration: null,
+ action: {
+ label: "Sign In",
+ run: () => {
+ setCodeRequest("now");
+ setPhase("code");
+ },
+ },
+ });
+ return () => dismissToast(id);
+ }, [codeLapse, phase]);
+
// Signed out, the window starts over: nothing of the account is left in its memory either —
// no picture, no list, no cached answer — for whoever signs in next.
async function signOut(keep: boolean) {
@@ -153,12 +178,21 @@ export default function App() {
notice={why}
onResult={(r) => {
setLapsed(false);
+ setCodeLapse(false);
+ setCodeRequest(undefined);
setPhase(r === "complete" ? "library" : "code");
}}
/>
)}
{phase === "code" && (
- <CodeEntry onVerified={() => setPhase("library")} onCancel={() => setPhase("signin")} />
+ <CodeEntry
+ request={codeRequest}
+ onVerified={() => {
+ setCodeLapse(false);
+ setPhase("library");
+ }}
+ onCancel={() => setPhase("signin")}
+ />
)}
</div>
);
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 989ee6b..a11cf35 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -149,6 +149,8 @@ export const api = {
submitCode: (code: string) => invoke<void>("auth_submit_code", { code }),
twoFactorOptions: () => invoke<TwoFactorOptions>("auth_two_factor_options"),
resendCode: () => invoke<void>("auth_resend_code"),
+ /** The code screen is open: Apple sends the code, unless this sign-in already asked. */
+ requestCode: () => invoke<void>("auth_request_code"),
sendSms: (phoneId: number) => invoke<void>("auth_send_sms", { phoneId }),
submitSmsCode: (phoneId: number, code: string) =>
invoke<void>("auth_submit_sms_code", { phoneId, code }),
diff --git a/src/screens/CodeEntry.tsx b/src/screens/CodeEntry.tsx
index d2dba02..7ec9621 100644
--- a/src/screens/CodeEntry.tsx
+++ b/src/screens/CodeEntry.tsx
@@ -8,9 +8,16 @@ import { api, messageOf, type TwoFactorOptions } from "../lib/ipc";
export function CodeEntry({
onVerified,
onCancel,
+ request,
}: {
onVerified: () => void;
onCancel: () => void;
+ /**
+ * How the code is asked for, when Skykeep signed itself back in and Apple wants one: `now`,
+ * the person came here to get it; `ask`, they did not (the window opened with Skykeep), so
+ * it is theirs to send. Absent, the sign-in a moment ago already asked.
+ */
+ request?: "now" | "ask";
}) {
const [code, setCode] = useState("");
const [busy, setBusy] = useState(false);
@@ -26,6 +33,18 @@ export function CodeEntry({
api.twoFactorOptions().then(setOptions).catch(() => setOptions(null));
}, []);
+ /** Apple has been asked for this sign-in's code. */
+ const [asked, setAsked] = useState(request === undefined);
+ const askForCode = () =>
+ run(async () => {
+ await api.requestCode();
+ setAsked(true);
+ }, "");
+ useEffect(() => {
+ if (request === "now") void askForCode();
+ // Once, as the screen opens.
+ }, []);
+
// If Apple pushed to nothing, say so immediately rather than letting someone wait.
const nothingSent = options?.trustedDeviceCount === 0;
/**
@@ -82,7 +101,9 @@ export function CodeEntry({
<Mark className="mark" />
<h1>Enter the code</h1>
<p className="lede">
- {texted
+ {!asked && !texted
+ ? "Apple wants a code before it trusts this computer again."
+ : texted
? calls(texted)
? `Apple is calling ${texted.maskedNumber} with a code.`
: `Apple texted a code to ${texted.maskedNumber}.`
@@ -97,6 +118,12 @@ export function CodeEntry({
: `Apple sent a code to ${devices === 1 ? "one of your devices" : `${devices} of your devices`}.`}
</p>
+ {!asked && !texted && (
+ <button className="primary" type="button" disabled={busy} onClick={() => void askForCode()}>
+ Send Code
+ </button>
+ )}
+
<CodeInput
value={code}
onChange={(next) => {