Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Notes: no write can leave an attachment in two places
Yashwanth Kamireddia8710485928b
diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rsindex 71074b5..705f591 100644--- a/crates/quince-icloud/src/ckdocument.rs+++ b/crates/quince-icloud/src/ckdocument.rs@@ -1152,6 +1152,39 @@ fn attachments_sound(old: &[Vec<u8>], new: &[Vec<u8>], units: &[u16]) -> Option<Some(())}+/// Whether a note document (as the CloudKit field carries it) refers to any attachment.+#[must_use]+pub fn has_attachments_in_base64(document: &str) -> bool {+ B64.decode(document.trim()).is_ok_and(|raw| {+ debug_attribute_runs(&raw)+ .iter()+ .any(|r| bytes_field(r, ATTACHMENT_INFO).is_some())+ })+}++/// Whether `edited` (a note document, as the CloudKit field carries it) is sound against+/// `original`, what Apple held: every attachment reference one `original` had, none used+/// twice, each on its own object-replacement character. Checked on every write of a note's+/// text, whichever path built it — a note this app once saved with a table referenced twice+/// made Notes on his iPhone lag and crash, and Notes kept copies of the notes it could not+/// merge.+#[must_use]+pub fn attachments_sound_in_base64(original: &str, edited: &str) -> bool {+ let (Ok(old), Ok(new)) = (B64.decode(original.trim()), B64.decode(edited.trim())) else {+ return false;+ };+ let Some(text) = text_from_bytes(&new) else {+ return false;+ };+ let units: Vec<u16> = text.encode_utf16().collect();+ attachments_sound(+ &debug_attribute_runs(&old),+ &debug_attribute_runs(&new),+ &units,+ )+ .is_some()+}+/// The text and its formatting together: the text replaced as [`replace_text`] replaces it,/// then the runs set as [`set_runs`] sets them. Over the base64 a CloudKit field carries.#[must_use]@@ -2992,6 +3025,41 @@ mod run_tests {);}+ /// Every write of a note's text is checked against what Apple held: an attachment kept+ /// once passes; one referenced twice, or one the note never had, is refused.+ #[test]+ fn a_write_that_doubles_or_borrows_an_attachment_is_refused() {+ let info = |id: &[u8]| {+ let mut inner = Vec::new();+ len_field(1, id, &mut inner);+ let mut out = Vec::new();+ len_field(12, &inner, &mut out);+ out+ };+ let had = B64.encode(doc_with("\u{FFFC}\n", &[(1, info(b"T1")), (1, Vec::new())]));+ let kept = B64.encode(replace_text(&B64.decode(&had).unwrap(), "\u{FFFC}hi\n").unwrap());+ assert!(attachments_sound_in_base64(&had, &kept));+ let twice = B64.encode(doc_with(+ "\u{FFFC}\u{FFFC}\n",+ &[(1, info(b"T1")), (1, info(b"T1")), (1, Vec::new())],+ ));+ assert!(+ !attachments_sound_in_base64(&had, &twice),+ "a table referenced twice"+ );+ let borrowed = B64.encode(doc_with("\u{FFFC}\n", &[(1, info(b"T2")), (1, Vec::new())]));+ assert!(+ !attachments_sound_in_base64(&had, &borrowed),+ "another note's table"+ );+ let gone = B64.encode(doc_with("hi\n", &[(3, Vec::new())]));+ assert!(+ attachments_sound_in_base64(&had, &gone),+ "a table deleted is fine"+ );+ assert!(has_attachments_in_base64(&had) && !has_attachments_in_base64(&gone));+ }+/// An edit that removes a whole run leaves every later run with its own styling.#[test]fn removing_a_whole_run_does_not_shift_the_styles_after_it() {diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rsindex bfd457f..9659afc 100644--- a/crates/quince-icloud/src/notes.rs+++ b/crates/quince-icloud/src/notes.rs@@ -120,6 +120,11 @@ fn note_from_record(record: &Value) -> Option<Note> {////// Pass `since` to fetch only what changed; as with reminders, absence in a delta means/// unchanged rather than deleted.+/// Said when a write would leave a note's attachments unsound (see+/// [`crate::ckdocument::attachments_sound_in_base64`]): nothing is sent.+const ATTACHMENTS_UNSOUND: &str =+ "Quince didn’t save this: it would have left a table or attachment in this note referenced twice, which Notes on iPhone can’t open. Nothing was changed.";+pub async fn sync_cloudkit(http: &reqwest::Client,ckdatabasews_root: &str,@@ -603,6 +608,9 @@ pub async fn edit_rich_cloudkit_from()})?;fits_inline(&rewritten)?;+ if !crate::ckdocument::attachments_sound_in_base64(encoded, &rewritten) {+ return Err(Error::Refused(ATTACHMENTS_UNSOUND.into()));+ }let (title, snippet) = title_and_snippet(&target);let Some(tag) = current.get("recordChangeTag").and_then(Value::as_str) else {return Err(Error::Refused(@@ -766,6 +774,10 @@ pub async fn set_paragraph_cloudkit(*refused.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e);return None;}+ if !crate::ckdocument::attachments_sound_in_base64(encoded, &rewritten) {+ *refused.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Error::Refused(ATTACHMENTS_UNSOUND.into()));+ return None;+ }Some(serde_json::json!({"TextDataEncrypted": { "type": "ENCRYPTED_BYTES", "value": rewritten },"ModificationDate": { "type": "TIMESTAMP", "value": now_millis() },@@ -896,6 +908,9 @@ fn document_like_apples(template: Option<&str>, body: &str) -> String {// word repeated, with gaps where the arithmetic ran off the end of it..and_then(crate::ckdocument::without_history).and_then(|document| crate::ckdocument::replace_text_in_base64(&document, body))+ // Another note's tables are never a new note's: a reference carried over would be one+ // attachment in two notes, which Notes on a phone cannot open.+ .filter(|document| !crate::ckdocument::has_attachments_in_base64(document)).unwrap_or_else(|| crate::ckdocument::text_to_base64(body))}diff --git a/probe/examples/notes_list.rs b/probe/examples/notes_list.rsnew file mode 100644index 0000000..14d8f70--- /dev/null+++ b/probe/examples/notes_list.rs@@ -0,0 +1,65 @@+//! Read-only: every note Apple holds — its first line, folder, whether deleted, how many+//! attachment references it has — for checking the library against the account.+use anyhow::{anyhow, Result};+#[tokio::main]+async fn main() -> Result<()> {+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");+ let mut client = quince_auth::Client::new(&dir)?;+ if !client.resume().await? {+ return Err(anyhow!("no session"));+ }+ let root = client+ .session()+ .service_url("ckdatabasews")+ .ok_or_else(|| anyhow!("no ck"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p);+ let walk = zc.all_records("Notes", None).await?;+ let mut kinds = std::collections::BTreeMap::<String, usize>::new();+ for r in &walk.records {+ *kinds+ .entry(r["recordType"].as_str().unwrap_or("?").to_string())+ .or_default() += 1;+ }+ println!("records: {kinds:?}");+ for r in walk.records.iter().filter(|r| r["recordType"] == "Note") {+ let f = &r["fields"];+ let text = f["TextDataEncrypted"]["value"]+ .as_str()+ .and_then(quince_icloud::ckdocument::text_from_base64)+ .unwrap_or_default();+ let atts = f["TextDataEncrypted"]["value"]+ .as_str()+ .map(quince_icloud::ckdocument::runs_from_base64)+ .unwrap_or_default()+ .iter()+ .filter(|x| x.attachment.is_some())+ .count();+ let first: String = text.lines().next().unwrap_or("").chars().take(30).collect();+ let ids: Vec<String> = f["TextDataEncrypted"]["value"]+ .as_str()+ .map(quince_icloud::ckdocument::runs_from_base64)+ .unwrap_or_default()+ .iter()+ .filter_map(|x| x.attachment.clone())+ .map(|a| a.chars().take(4).collect())+ .collect();+ println!(+ "{} | {:30} | deleted {} | folder {} | atts {} | created {} | {:?} | modified {}",+ &r["recordName"].as_str().unwrap_or("")[..8],+ first,+ f["Deleted"]["value"],+ f["Folder"]["value"]["recordName"]+ .as_str()+ .unwrap_or("-")+ .chars()+ .take(8)+ .collect::<String>(),+ atts,+ f["CreationDate"]["value"],+ ids,+ f["ModificationDate"]["value"]+ );+ }+ Ok(())+}