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.

Never carry a dead challenge into the next sign-in

Yashwanth Kamireddi44c17308b56d
diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjs
index 5bf3608..edd651e 100644
--- a/.uiverify/shots.mjs
+++ b/.uiverify/shots.mjs
@@ -13,7 +13,7 @@ const SERVICES = ["account","calendar","ckdatabasews","contacts","drivews","find
/* addInitScript SERIALIZES this function — closures do not cross into the page, so every
value it needs must arrive through the single argument. */
-function installStub({ screen, services }) {
+function installStub({ screen, services, twoFactor }) {
window.__TAURI_INTERNALS__ = {
transformCallback: (cb) => cb,
invoke: async (cmd) => {
@@ -24,6 +24,10 @@ function installStub({ screen, services }) {
case "auth_sign_in": return screen === "code" ? "needs_two_factor" : "complete";
case "auth_submit_code": return null;
case "account_services": return services;
+ case "auth_two_factor_options": return twoFactor;
+ case "auth_resend_code": return null;
+ case "auth_send_sms": return null;
+ case "auth_submit_sms_code": return null;
case "auth_sign_out": return null;
default: throw new Error(`unstubbed command: ${cmd}`);
}
@@ -31,6 +35,9 @@ function installStub({ screen, services }) {
};
}
+const PUSHED = { trustedDeviceCount: 2, phones: [{ id: 1, maskedNumber: "+91 ••••• ••318" }], tooManyCodesSent: false };
+const NOTHING = { trustedDeviceCount: 0, phones: [{ id: 1, maskedNumber: "+91 ••••• ••318" }], tooManyCodesSent: false };
+
const shots = [
{ name: "01-signin", screen: "signin", theme: "light" },
{ name: "02-signin-dark", screen: "signin", theme: "dark" },
@@ -44,18 +51,25 @@ const shots = [
await p.fill('input[aria-label="Digit 2"]', "8");
await p.fill('input[aria-label="Digit 3"]', "1");
} },
+ { name: "06-code-no-device", screen: "code", theme: "light", twoFactor: NOTHING,
+ act: async (p) => {
+ await p.fill('input[aria-label="Apple ID"]', "[email protected]");
+ await p.fill('input[aria-label="Password"]', "••••••••••••");
+ await p.click('button[type="submit"]');
+ await p.waitForSelector(".help", { timeout: 5000 });
+ } },
{ name: "04-library", screen: "library", theme: "light" },
{ name: "05-library-dark", screen: "library", theme: "dark" },
];
const browser = await chromium.launch();
-for (const { name, screen, theme, act } of shots) {
+for (const { name, screen, theme, act, twoFactor = PUSHED } of shots) {
const ctx = await browser.newContext({
viewport: { width: 1040, height: 720 },
deviceScaleFactor: 2,
colorScheme: theme,
});
- await ctx.addInitScript(installStub, { screen, services: SERVICES });
+ await ctx.addInitScript(installStub, { screen, services: SERVICES, twoFactor });
const page = await ctx.newPage();
const errors = [];
page.on("console", (m) => m.type() === "error" && errors.push(m.text()));
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rs
index 817578a..14bd18b 100644
--- a/crates/quince-auth/src/lib.rs
+++ b/crates/quince-auth/src/lib.rs
@@ -247,6 +247,25 @@ impl Client {
with_srp_origin(self.auth_headers())
}
+ /// Headers for `/signin/init` specifically.
+ ///
+ /// Deliberately omits `scnt` and the session id: the flow has not issued them yet, and
+ /// sending leftovers from an abandoned challenge is a conflict.
+ fn srp_init_headers(&mut self) -> HeaderMap {
+ let client_id = self.session.client_id();
+ with_srp_origin(base_oauth_headers(&client_id, None, None))
+ }
+
+ /// Drop transient challenge state, keeping what identifies this install.
+ ///
+ /// `trust_token` and `client_id` survive — they are what lets Apple skip 2FA next time.
+ /// Everything else belongs to a single sign-in attempt and must not leak into the next.
+ fn clear_challenge_state(&mut self) {
+ self.session.scnt = None;
+ self.session.session_id = None;
+ self.session.session_token = None;
+ }
+
// ---- the restart test -----------------------------------------------------------
/// Try to resume a stored session without a password.
@@ -264,7 +283,12 @@ impl Client {
self.persist()?;
Ok(true)
}
- Err(_) => Ok(false),
+ Err(_) => {
+ // The stored session is dead. Drop its challenge state now so it cannot
+ // contaminate the sign-in that follows.
+ self.clear_challenge_state();
+ Ok(false)
+ }
}
}
@@ -307,10 +331,14 @@ 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> {
+ // Start clean. An interrupted previous attempt would otherwise announce a
+ // half-finished session and Apple would reject this one as a conflict.
+ self.clear_challenge_state();
+
let client = srp::Client::new(apple_id);
// --- /signin/init: send A, receive salt, B, protocol, iteration count ---
- let headers = self.srp_headers();
+ let headers = self.srp_init_headers();
let r = self
.http
.post(format!("{AUTH}/signin/init"))
@@ -640,6 +668,21 @@ mod tests {
assert_eq!(h.get("x-apple-id-session-id").unwrap(), "session-value");
}
+ /// Sign-in must not advertise a session that does not exist yet.
+ #[test]
+ fn init_headers_omit_challenge_state() {
+ let stale = base_oauth_headers("auth-test", Some("stale-scnt"), Some("stale-session"));
+ assert!(stale.get("scnt").is_some(), "sanity: the helper does forward them");
+
+ let init = with_srp_origin(base_oauth_headers("auth-test", None, None));
+ assert!(init.get("scnt").is_none(), "/signin/init must not send scnt");
+ assert!(
+ init.get("x-apple-id-session-id").is_none(),
+ "/signin/init must not send a session id"
+ );
+ assert_eq!(init.get("origin").unwrap(), AUTH_ROOT);
+ }
+
#[test]
fn apple_errors_are_classified() {
let wrong = r#"{"serviceErrors":[{"code":"-21669","message":"Incorrect verification code."}]}"#;
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 2f7e9fb..ee1dfb4 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1,7 +1,7 @@
// Quince — desktop shell.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
-use quince_auth::{Client, SignInOutcome};
+use quince_auth::{Client, SignInOutcome, TwoFactorOptions};
use serde::Serialize;
use std::path::PathBuf;
use tauri::{Manager, State};
@@ -63,6 +63,36 @@ async fn auth_submit_code(code: String, auth: State<'_, Auth>) -> UiResult<()> {
client.submit_two_factor(&code).await.map_err(|e| e.to_string())
}
+/// Where Apple can send a code, and whether it already pushed one.
+/// A `trustedDeviceCount` of zero means nothing was sent and waiting is pointless.
+#[tauri::command]
+async fn auth_two_factor_options(auth: State<'_, Auth>) -> UiResult<TwoFactorOptions> {
+ let mut client = auth.0.lock().await;
+ client.two_factor_options().await.map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+async fn auth_resend_code(auth: State<'_, Auth>) -> UiResult<()> {
+ let mut client = auth.0.lock().await;
+ client.resend_to_devices().await.map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+async fn auth_send_sms(phone_id: u64, auth: State<'_, Auth>) -> UiResult<()> {
+ let mut client = auth.0.lock().await;
+ client.send_sms(phone_id).await.map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+async fn auth_submit_sms_code(
+ phone_id: u64,
+ code: String,
+ auth: State<'_, Auth>,
+) -> UiResult<()> {
+ let mut client = auth.0.lock().await;
+ client.submit_sms_code(phone_id, &code).await.map_err(|e| e.to_string())
+}
+
#[tauri::command]
async fn auth_sign_out(auth: State<'_, Auth>) -> UiResult<()> {
let mut client = auth.0.lock().await;
@@ -99,6 +129,10 @@ fn main() {
auth_resume,
auth_sign_in,
auth_submit_code,
+ auth_two_factor_options,
+ auth_resend_code,
+ auth_send_sms,
+ auth_submit_sms_code,
auth_sign_out,
account_services,
])
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 78d3c35..6dff85d 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -3,12 +3,24 @@ import { invoke } from "@tauri-apps/api/core";
export type Status = { hasStoredSession: boolean; signedIn: boolean };
export type SignInResult = "complete" | "needs_two_factor";
+export type TrustedPhone = { id: number; maskedNumber: string };
+export type TwoFactorOptions = {
+ trustedDeviceCount: number;
+ phones: TrustedPhone[];
+ tooManyCodesSent: boolean;
+};
+
export const api = {
status: () => invoke<Status>("auth_status"),
resume: () => invoke<boolean>("auth_resume"),
signIn: (appleId: string, password: string) =>
invoke<SignInResult>("auth_sign_in", { appleId, password }),
submitCode: (code: string) => invoke<void>("auth_submit_code", { code }),
+ twoFactorOptions: () => invoke<TwoFactorOptions>("auth_two_factor_options"),
+ resendCode: () => invoke<void>("auth_resend_code"),
+ sendSms: (phoneId: number) => invoke<void>("auth_send_sms", { phoneId }),
+ submitSmsCode: (phoneId: number, code: string) =>
+ invoke<void>("auth_submit_sms_code", { phoneId, code }),
signOut: () => invoke<void>("auth_sign_out"),
services: () => invoke<string[]>("account_services"),
};
diff --git a/src/screens/CodeEntry.tsx b/src/screens/CodeEntry.tsx
index 2b8b9ef..ef94e51 100644
--- a/src/screens/CodeEntry.tsx
+++ b/src/screens/CodeEntry.tsx
@@ -1,7 +1,7 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { Mark } from "../components/Mark";
import { CodeInput } from "../components/CodeInput";
-import { api, messageOf } from "../lib/ipc";
+import { api, messageOf, type TwoFactorOptions } from "../lib/ipc";
export function CodeEntry({
onVerified,
@@ -13,12 +13,29 @@ export function CodeEntry({
const [code, setCode] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
+ const [options, setOptions] = useState<TwoFactorOptions | null>(null);
+ const [showHelp, setShowHelp] = useState(false);
+ /** Set once a code has been texted, so it verifies through the SMS endpoint instead. */
+ const [smsPhoneId, setSmsPhoneId] = useState<number | null>(null);
+
+ useEffect(() => {
+ api.twoFactorOptions().then(setOptions).catch(() => setOptions(null));
+ }, []);
+
+ // If Apple pushed to nothing, say so immediately rather than letting someone wait.
+ const nothingSent = options?.trustedDeviceCount === 0;
+ useEffect(() => {
+ if (nothingSent) setShowHelp(true);
+ }, [nothingSent]);
async function verify(value: string) {
setBusy(true);
setError(null);
+ setNotice(null);
try {
- await api.submitCode(value);
+ if (smsPhoneId !== null) await api.submitSmsCode(smsPhoneId, value);
+ else await api.submitCode(value);
onVerified();
} catch (err) {
setError(messageOf(err));
@@ -27,19 +44,97 @@ export function CodeEntry({
}
}
+ async function run(action: () => Promise<void>, done: string) {
+ setBusy(true);
+ setError(null);
+ setNotice(null);
+ try {
+ await action();
+ setNotice(done);
+ } catch (err) {
+ setError(messageOf(err));
+ } finally {
+ setBusy(false);
+ }
+ }
+
return (
<div className="sheet enter-sheet">
<Mark className="mark" />
<h1>Enter the code</h1>
- <p className="lede">Apple sent a six-digit code to your trusted devices.</p>
+ <p className="lede">
+ {options === null
+ ? "Apple sent a six-digit code to your trusted devices."
+ : nothingSent
+ ? "No trusted device is available."
+ : `Apple sent a six-digit code to ${options.trustedDeviceCount} of your devices.`}
+ </p>
<CodeInput value={code} onChange={setCode} onComplete={verify} disabled={busy} />
{error && <p className="error" role="alert">{error}</p>}
+ {notice && <p className="notice" role="status">{notice}</p>}
+
+ {!showHelp && (
+ <button className="quiet" type="button" onClick={() => setShowHelp(true)}>
+ Didn't get a code?
+ </button>
+ )}
+
+ {showHelp && (
+ <div className="help">
+ {options?.tooManyCodesSent && (
+ <p className="error">
+ Apple is limiting new codes. Wait a few minutes — repeated tries risk a
+ temporary lock.
+ </p>
+ )}
+
+ <p>
+ The code is only created once you tap <strong>Allow</strong> on your iPhone. If no
+ prompt appeared, no code exists yet.
+ </p>
+
+ <div className="help-actions">
+ {!nothingSent && (
+ <button
+ className="quiet"
+ type="button"
+ disabled={busy}
+ onClick={() => run(api.resendCode, "Sent again — check your devices.")}
+ >
+ Send to my devices again
+ </button>
+ )}
+ {options?.phones.map((phone) => (
+ <button
+ key={phone.id}
+ className="quiet"
+ type="button"
+ disabled={busy}
+ onClick={() =>
+ run(async () => {
+ await api.sendSms(phone.id);
+ setSmsPhoneId(phone.id);
+ }, `Texted ${phone.maskedNumber}.`)
+ }
+ >
+ Text {phone.maskedNumber}
+ </button>
+ ))}
+ </div>
+
+ <p>
+ Still nothing? On iPhone, turn on <strong>Airplane Mode</strong>, then open
+ Settings → your name → Sign-In &amp; Security. A popup offers a code while the
+ phone is offline. (iOS hides that option when the phone is online.)
+ </p>
+ </div>
+ )}
<p className="assurance">
- After this, Quince stays signed in. You won't be asked again unless Apple retires
- the session, which takes about two months.
+ After this, Quince stays signed in. You won't be asked again unless Apple retires the
+ session, which takes about two months.
</p>
<button className="quiet" type="button" onClick={onCancel} disabled={busy}>
diff --git a/src/styles/app.css b/src/styles/app.css
index 8741ad8..6311b01 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -139,6 +139,43 @@
font-size: var(--t-11);
}
+.notice {
+ margin: 16px auto 0;
+ max-width: 34ch;
+ color: var(--text-2);
+ font-size: var(--t-13);
+}
+
+/* Recovery options stay folded away until asked for: the code field is the task. */
+.help {
+ margin: 18px auto 0;
+ max-width: 38ch;
+ text-align: left;
+ padding: 14px 15px;
+ border-radius: var(--r-field);
+ background: color-mix(in srgb, var(--text) 4.5%, transparent);
+}
+
+.help p {
+ margin: 0 0 10px;
+ color: var(--text-2);
+ font-size: var(--t-11);
+ line-height: 1.55;
+}
+
+.help p:last-child { margin-bottom: 0; }
+.help strong { color: var(--text); font-weight: 600; }
+
+.help-actions {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 2px;
+ margin: 0 0 10px;
+}
+
+.help-actions .quiet { margin-top: 0; padding: 3px 6px; }
+
.error {
margin: 16px auto 0;
max-width: 32ch;