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.

Two-factor: find trusted numbers wherever Apple keeps them, and reach each the way it takes a code

Yashwanth Kamireddi84299e9d9b93
diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjs
index e60eb2d..e179ab7 100644
--- a/.uiverify/assert.mjs
+++ b/.uiverify/assert.mjs
@@ -663,6 +663,9 @@ let failures = 0;
{ resend: false, text: true, says: /texted/i }],
["devices and a number", { trustedDeviceCount: 2, phones: [{ id: 1, maskedNumber: "+91 •••318" }], tooManyCodesSent: false },
{ resend: true, text: true, says: /2 of your devices/ }],
+ // A number Apple calls rather than texts (timlaing/pyicloud#210): offered as a call.
+ ["no device, a number Apple calls", { trustedDeviceCount: 0, phones: [{ id: 1, maskedNumber: "+44 •••• ••12", mode: "voice" }], tooManyCodesSent: false },
+ { resend: false, text: false, call: true, says: /call you/i }],
]) {
const page = await ctx.newPage();
await page.addInitScript((tf) => {
@@ -690,15 +693,17 @@ let failures = 0;
const body = await page.locator(".sheet").innerText();
const resend = await page.locator('button:has-text("Send to my devices again")').count();
const text = await page.locator('button:has-text("Text ")').count();
+ const call = await page.locator('button:has-text("Call ")').count();
const right =
(resend > 0) === wants.resend &&
(text > 0) === wants.text &&
+ (call > 0) === !!wants.call &&
wants.says.test(body);
console.log(
right
? `PASS ${label}: offers only what can work`
- : `FAIL ${label}: resend=${resend} text=${text}, said ${JSON.stringify(body.slice(0, 90))}`
+ : `FAIL ${label}: resend=${resend} text=${text} call=${call}, said ${JSON.stringify(body.slice(0, 90))}`
);
if (!right) failures++;
await page.close();
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rs
index 20c8055..1c5c8f9 100644
--- a/crates/quince-auth/src/lib.rs
+++ b/crates/quince-auth/src/lib.rs
@@ -223,13 +223,110 @@ fn refused_password(context: &str, status: StatusCode, body: &str) -> Error {
}
}
-/// A phone Apple will text a code to, when no trusted device responds.
+/// A phone Apple will send a code to, when no trusted device responds.
#[derive(Debug, Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustedPhone {
pub id: u64,
/// Already masked by Apple, e.g. "+91 ••••• ••123".
pub masked_number: String,
+ /// How Apple reaches this number: `sms`, or `voice` for a number it calls (a landline).
+ /// Sent back as it came (timlaing/pyicloud#210): Apple takes a code for a number the way
+ /// it sends one there.
+ pub mode: String,
+ /// Apple's `nonFTEU` flag on the number, sent back with it when Apple gave one.
+ #[serde(skip)]
+ pub non_fteu: Option<bool>,
+}
+
+impl TrustedPhone {
+ /// The `phoneNumber` Apple's phone endpoints take for this number.
+ fn as_payload(&self) -> Value {
+ let mut phone = json!({ "id": self.id });
+ if let Some(flag) = self.non_fteu {
+ phone["nonFTEU"] = Value::Bool(flag);
+ }
+ phone
+ }
+}
+
+/// What Apple's `GET /appleauth/auth` answered, as JSON: the reply itself, or — when Apple
+/// sends its sign-in page instead — the JSON that page carries in its `boot_args` script
+/// (timlaing/pyicloud#322).
+fn auth_options_of(text: &str) -> Value {
+ if let Ok(v) = serde_json::from_str::<Value>(text) {
+ return v;
+ }
+ let Some(at) = text.find("boot_args") else {
+ return Value::Null;
+ };
+ let rest = &text[at..];
+ rest.find('>')
+ .map(|open| &rest[open + 1..])
+ .and_then(|body| body.find("</script").map(|end| &body[..end]))
+ .and_then(|json| serde_json::from_str(json.trim()).ok())
+ .unwrap_or(Value::Null)
+}
+
+/// Every place Apple has kept the two-factor details in that reply: at the top, and — since
+/// its 2026 sign-in — under `phoneNumberVerification`, `direct.twoSV`, and
+/// `direct.twoSV.bridgeInitiateData.phoneNumberVerification` (icloud_photos_downloader#1335,
+/// timlaing/pyicloud#322).
+fn two_factor_places(v: &Value) -> Vec<&Value> {
+ let two_sv = v.pointer("/direct/twoSV");
+ [
+ Some(v),
+ v.get("phoneNumberVerification"),
+ v.get("direct"),
+ two_sv,
+ two_sv.and_then(|t| t.get("phoneNumberVerification")),
+ two_sv.and_then(|t| t.pointer("/bridgeInitiateData/phoneNumberVerification")),
+ ]
+ .into_iter()
+ .flatten()
+ .filter(|p| p.is_object())
+ .collect()
+}
+
+/// The trusted phones in Apple's two-factor reply, wherever it kept them, each once.
+///
+/// Read only at the top, an account whose numbers Apple had moved inward showed "Apple has
+/// nowhere to send a code" — for someone with no other device, no way to sign in at all.
+fn trusted_phones(v: &Value) -> Vec<TrustedPhone> {
+ let mut phones: Vec<TrustedPhone> = Vec::new();
+ for place in two_factor_places(v) {
+ let listed = place
+ .get("trustedPhoneNumbers")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .chain(place.get("trustedPhoneNumber").filter(|p| p.is_object()));
+ for p in listed {
+ let id = p["id"]
+ .as_u64()
+ .or_else(|| p["id"].as_str().and_then(|s| s.trim().parse().ok()));
+ let Some(id) = id else { continue };
+ if phones.iter().any(|known| known.id == id) {
+ continue;
+ }
+ phones.push(TrustedPhone {
+ id,
+ masked_number: p["numberWithDialCode"]
+ .as_str()
+ .or_else(|| p["obfuscatedNumber"].as_str())
+ .unwrap_or("(hidden)")
+ .to_string(),
+ mode: p["pushMode"]
+ .as_str()
+ .map(str::trim)
+ .filter(|m| !m.is_empty())
+ .unwrap_or("sms")
+ .to_string(),
+ non_fteu: p["nonFTEU"].as_bool(),
+ });
+ }
+ }
+ phones
}
/// Where Apple is willing to send a code. Read after a `NeedsTwoFactor` outcome.
@@ -320,6 +417,9 @@ pub struct Client {
persisted: std::sync::Mutex<Persisted>,
/// The cookies on disk, as this start found them (see [`read_jar`]).
cookies: Cookies,
+ /// The trusted phones Apple last listed, so a code is sent to and checked for each number
+ /// the way that number takes one.
+ phones: Vec<TrustedPhone>,
}
/// What became of the cookies kept on disk when the client started.
@@ -469,6 +569,7 @@ impl Client {
unsaved: None,
persisted: std::sync::Mutex::new(Persisted::default()),
cookies,
+ phones: Vec::new(),
})
}
@@ -1031,35 +1132,40 @@ impl Client {
.await?;
self.capture(&r);
let text = r.text().await.unwrap_or_default();
- let v: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
-
- let phones = v["trustedPhoneNumbers"]
- .as_array()
- .map(|arr| {
- arr.iter()
- .filter_map(|p| {
- Some(TrustedPhone {
- id: p["id"].as_u64()?,
- masked_number: p["numberWithDialCode"]
- .as_str()
- .or_else(|| p["obfuscatedNumber"].as_str())
- .unwrap_or("(hidden)")
- .to_string(),
- })
- })
- .collect()
- })
- .unwrap_or_default();
+ let v = auth_options_of(&text);
+ let places = two_factor_places(&v);
+
+ let phones = trusted_phones(&v);
+ self.phones.clone_from(&phones);
+ // A count where Apple gives one; where it says only that there are trusted devices
+ // (`direct.hasTrustedDevices`), at least one.
+ let counted = places
+ .iter()
+ .find_map(|p| p.get("trustedDeviceCount").and_then(Value::as_u64));
+ let has_devices = places
+ .iter()
+ .any(|p| p.get("hasTrustedDevices").and_then(Value::as_bool) == Some(true));
+ let too_many = places.iter().any(|p| {
+ p.pointer("/securityCode/tooManyCodesSent")
+ .and_then(Value::as_bool)
+ == Some(true)
+ });
Ok(TwoFactorOptions {
- trusted_device_count: v["trustedDeviceCount"].as_u64().unwrap_or(0),
+ trusted_device_count: counted.unwrap_or(u64::from(has_devices)),
phones,
- too_many_codes_sent: v["securityCode"]["tooManyCodesSent"]
- .as_bool()
- .unwrap_or(false),
+ too_many_codes_sent: too_many,
})
}
+ /// The `phoneNumber` and `mode` for `phone_id`, as Apple last described the number.
+ fn phone_payload(&self, phone_id: u64) -> (Value, String) {
+ self.phones.iter().find(|p| p.id == phone_id).map_or_else(
+ || (json!({ "id": phone_id }), "sms".to_string()),
+ |p| (p.as_payload(), p.mode.clone()),
+ )
+ }
+
/// 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();
@@ -1090,7 +1196,10 @@ impl Client {
.http
.put(format!("{}/verify/phone", self.endpoints.auth))
.headers(headers)
- .body(json!({ "phoneNumber": { "id": phone_id }, "mode": "sms" }).to_string())
+ .body({
+ let (phone, mode) = self.phone_payload(phone_id);
+ json!({ "phoneNumber": phone, "mode": mode }).to_string()
+ })
.send()
.await?;
self.capture(&r);
@@ -1106,15 +1215,16 @@ impl Client {
pub async fn submit_sms_code(&mut self, phone_id: u64, code: &str) -> Result<()> {
let mut headers = self.auth_headers();
headers.insert("accept", HeaderValue::from_static("application/json"));
+ let (phone, mode) = self.phone_payload(phone_id);
let r = self
.http
.post(format!("{}/verify/phone/securitycode", self.endpoints.auth))
.headers(headers)
.body(
json!({
- "phoneNumber": { "id": phone_id },
+ "phoneNumber": phone,
"securityCode": { "code": code },
- "mode": "sms",
+ "mode": mode,
})
.to_string(),
)
diff --git a/crates/quince-auth/tests/auth_flow.rs b/crates/quince-auth/tests/auth_flow.rs
index c4b8e73..be2cd61 100644
--- a/crates/quince-auth/tests/auth_flow.rs
+++ b/crates/quince-auth/tests/auth_flow.rs
@@ -1134,3 +1134,127 @@ async fn a_bare_refusal_is_still_a_wrong_password() {
);
}
}
+
+/// Since its 2026 sign-in Apple can keep the trusted numbers under
+/// `direct.twoSV.bridgeInitiateData.phoneNumberVerification` (icloud_photos_downloader#1335),
+/// or send its sign-in page with them in a `boot_args` script (timlaing/pyicloud#322). Read
+/// only at the top, an account reached only by text showed "nowhere to send a code".
+#[tokio::test]
+async fn trusted_numbers_are_found_wherever_apple_keeps_them() {
+ let nested = json!({
+ "direct": {
+ "hasTrustedDevices": false,
+ "twoSV": {
+ "bridgeInitiateData": {
+ "phoneNumberVerification": {
+ "trustedPhoneNumbers": [
+ { "id": 1, "numberWithDialCode": "+91 ••••• ••318", "pushMode": "sms" },
+ { "id": 2, "obfuscatedNumber": "(•••) •••-••12", "pushMode": "voice", "nonFTEU": true }
+ ],
+ "trustedPhoneNumber": { "id": 1, "numberWithDialCode": "+91 ••••• ••318", "pushMode": "sms" },
+ "securityCode": { "tooManyCodesSent": true }
+ }
+ }
+ }
+ }
+ });
+ let page = format!(
+ "<html><head><script type=\"application/json\" class=\"boot_args\">\n{nested}\n</script></head></html>"
+ );
+ for (label, reply) in [
+ (
+ "json",
+ ResponseTemplate::new(200).set_body_json(nested.clone()),
+ ),
+ (
+ "page",
+ ResponseTemplate::new(200)
+ .insert_header("content-type", "text/html")
+ .set_body_string(page.clone()),
+ ),
+ ] {
+ let server = MockServer::start().await;
+ mount_init(&server, 200).await;
+ mount_complete(&server, 409).await;
+ Mock::given(method("GET"))
+ .and(path("/appleauth/auth"))
+ .respond_with(reply)
+ .mount(&server)
+ .await;
+ Mock::given(method("PUT"))
+ .and(path("/appleauth/auth/verify/phone"))
+ .respond_with(ResponseTemplate::new(200))
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path("/appleauth/auth/verify/phone/securitycode"))
+ .respond_with(ResponseTemplate::new(200))
+ .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();
+
+ let options = client.two_factor_options().await.unwrap();
+ let ids: Vec<u64> = options.phones.iter().map(|p| p.id).collect();
+ assert_eq!(ids, vec![1, 2], "{label}: each number once");
+ assert_eq!(options.phones[0].masked_number, "+91 ••••• ••318");
+ assert_eq!(options.phones[1].mode, "voice", "{label}");
+ assert_eq!(options.trusted_device_count, 0, "{label}");
+ assert!(options.too_many_codes_sent, "{label}");
+
+ // Sent and checked the way Apple reaches that number: by a call, with its flag.
+ client.send_sms(2).await.unwrap();
+ client.submit_sms_code(2, "123456").await.unwrap();
+ let reqs = server.received_requests().await.unwrap();
+ for sent in requests_to(&reqs, "/verify/phone")
+ .into_iter()
+ .chain(requests_to(&reqs, "/verify/phone/securitycode"))
+ {
+ let body: serde_json::Value = serde_json::from_slice(&sent.body).unwrap();
+ assert_eq!(body["mode"], "voice", "{label}: {body}");
+ assert_eq!(body["phoneNumber"]["id"], 2, "{label}: {body}");
+ assert_eq!(body["phoneNumber"]["nonFTEU"], true, "{label}: {body}");
+ }
+ }
+}
+
+/// The reply as it has always been, with the numbers at the top: read as before, texted.
+#[tokio::test]
+async fn trusted_numbers_at_the_top_are_still_texted() {
+ let server = MockServer::start().await;
+ mount_init(&server, 200).await;
+ mount_complete(&server, 409).await;
+ Mock::given(method("GET"))
+ .and(path("/appleauth/auth"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "trustedDeviceCount": 2,
+ "trustedPhoneNumbers": [{ "id": 7, "numberWithDialCode": "+1 (•••) •••-••01" }],
+ })))
+ .mount(&server)
+ .await;
+ Mock::given(method("PUT"))
+ .and(path("/appleauth/auth/verify/phone"))
+ .respond_with(ResponseTemplate::new(200))
+ .mount(&server)
+ .await;
+ let dir = tempfile::tempdir().unwrap();
+ let mut client = client_for(&server, dir.path());
+ client
+ .sign_in("[email protected]", "hunter2")
+ .await
+ .unwrap();
+ let options = client.two_factor_options().await.unwrap();
+ assert_eq!(options.trusted_device_count, 2);
+ assert_eq!(options.phones.len(), 1);
+ assert_eq!(options.phones[0].mode, "sms");
+ client.send_sms(7).await.unwrap();
+ let reqs = server.received_requests().await.unwrap();
+ let sent = requests_to(&reqs, "/verify/phone");
+ let body: serde_json::Value = serde_json::from_slice(&sent[0].body).unwrap();
+ assert_eq!(body, json!({ "phoneNumber": { "id": 7 }, "mode": "sms" }));
+}
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 2d90ae0..fae7f21 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -24,7 +24,8 @@ export type RefusedChange = {
export type OutboxStatus = { waiting: WaitingChange[]; refused: RefusedChange[] };
export type SignInResult = "complete" | "needs_two_factor";
-export type TrustedPhone = { id: number; maskedNumber: string };
+/** `mode` is how Apple reaches the number: "sms", or "voice" for one it calls. */
+export type TrustedPhone = { id: number; maskedNumber: string; mode?: string };
export type TwoFactorOptions = {
trustedDeviceCount: number;
phones: TrustedPhone[];
diff --git a/src/screens/CodeEntry.tsx b/src/screens/CodeEntry.tsx
index c07f27d..d2dba02 100644
--- a/src/screens/CodeEntry.tsx
+++ b/src/screens/CodeEntry.tsx
@@ -41,6 +41,9 @@ export function CodeEntry({
}, [nothingSent]);
const texted = options?.phones.find((p) => p.id === smsPhoneId);
+ /** A number Apple calls with the code rather than texting it (a landline). */
+ const calls = (phone: { mode?: string }) => phone.mode === "voice";
+ const onlyCalls = !!options && options.phones.length > 0 && options.phones.every(calls);
const devices = options?.trustedDeviceCount ?? 0;
async function verify(value: string) {
@@ -80,13 +83,17 @@ export function CodeEntry({
<h1>Enter the code</h1>
<p className="lede">
{texted
- ? `Apple texted a code to ${texted.maskedNumber}.`
+ ? calls(texted)
+ ? `Apple is calling ${texted.maskedNumber} with a code.`
+ : `Apple texted a code to ${texted.maskedNumber}.`
: options === null
? "Apple sent a code to your devices."
: nowhereToSend
? "Apple has nowhere to send a code for this account."
: nothingSent
- ? "No device is reachable, but a code can be texted to you."
+ ? onlyCalls
+ ? "No device is reachable, but Apple can call you with a code."
+ : "No device is reachable, but a code can be texted to you."
: `Apple sent a code to ${devices === 1 ? "one of your devices" : `${devices} of your devices`}.`}
</p>
@@ -183,7 +190,7 @@ export function CodeEntry({
}, "")
}
>
- Text {phone.maskedNumber}
+ {calls(phone) ? "Call" : "Text"} {phone.maskedNumber}
</button>
))}
</div>