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, read from CloudKit
Yashwanth Kamireddid38b0de6097f
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjsindex 55d4ad7..29151cf 100644--- a/.uiverify/a11y.mjs+++ b/.uiverify/a11y.mjs@@ -32,6 +32,10 @@ function installStub({ screen, services, twoFactor }) {case "reminder_create": return null;case "reminder_delete": return null;case "reminder_set_done": return null;+ case "note_folders": return [];+ case "notes_in": return [];+ case "notes_last_synced": return Math.floor(Date.now() / 1000);+ case "notes_sync": return [0, 0];default: return null;}},diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjsindex e419ce1..8cf0be2 100644--- a/.uiverify/assert.mjs+++ b/.uiverify/assert.mjs@@ -21,6 +21,10 @@ await ctx.addInitScript(({ services }) => {if (cmd === "reminder_create") return null;if (cmd === "reminder_delete") return null;if (cmd === "reminder_set_done") return null;+ if (cmd === "note_folders") return [];+ if (cmd === "notes_in") return [];+ if (cmd === "notes_last_synced") return Math.floor(Date.now() / 1000);+ if (cmd === "notes_sync") return [0, 0];return null;},};diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjsindex 4315c8c..6bb253a 100644--- a/.uiverify/keyboard.mjs+++ b/.uiverify/keyboard.mjs@@ -28,6 +28,10 @@ function installStub({ screen, services, twoFactor }) {case "reminder_create": return null;case "reminder_delete": return null;case "reminder_set_done": return null;+ case "note_folders": return [];+ case "notes_in": return [];+ case "notes_last_synced": return Math.floor(Date.now() / 1000);+ case "notes_sync": return [0, 0];default: return null;}},diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjsindex f1f2663..ce061d6 100644--- a/.uiverify/shots.mjs+++ b/.uiverify/shots.mjs@@ -67,6 +67,10 @@ function installStub({ screen, services, twoFactor, calendarFixture }) {case "reminder_create": return null;case "reminder_delete": return null;case "reminder_set_done": return null;+ case "note_folders": return [];+ case "notes_in": return [];+ case "notes_last_synced": return Math.floor(Date.now() / 1000);+ case "notes_sync": return [0, 0];case "auth_two_factor_options": return twoFactor;case "auth_resend_code": return null;case "auth_send_sms": return null;diff --git a/crates/quince-core/src/lib.rs b/crates/quince-core/src/lib.rsindex 49bc8e9..8e6b0fd 100644--- a/crates/quince-core/src/lib.rs+++ b/crates/quince-core/src/lib.rs@@ -5,6 +5,7 @@//! it. That is the whole reason the app can be instant and work offline.pub mod calendar;+pub mod notes;pub mod reminders;pub mod schema;diff --git a/crates/quince-core/src/notes.rs b/crates/quince-core/src/notes.rsnew file mode 100644index 0000000..0757466--- /dev/null+++ b/crates/quince-core/src/notes.rs@@ -0,0 +1,249 @@+//! Notes and their folders in the local library.++use crate::{Library, Result};+use rusqlite::params;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct NoteFolder {+ pub guid: String,+ pub title: String,+ pub sort_order: i64,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct Note {+ pub guid: String,+ pub folder_guid: Option<String>,+ pub title: String,+ pub snippet: Option<String>,+ pub body: Option<String>,+ /// Locked by its owner, so Apple holds it encrypted and there is nothing to show.+ pub locked: bool,+ pub pinned: bool,+ pub created_at: Option<i64>,+ pub modified_at: Option<i64>,+ pub etag: Option<String>,+}++fn now() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))+}++impl Library {+ pub fn put_note_folders(&mut self, folders: &[NoteFolder]) -> Result<()> {+ let tx = self.conn.transaction()?;+ {+ let mut stmt = tx.prepare(+ "INSERT INTO note_folders (guid, title, sort_order, updated_at)+ VALUES (?1, ?2, ?3, ?4)+ ON CONFLICT(guid) DO UPDATE SET+ title = excluded.title, sort_order = excluded.sort_order,+ updated_at = excluded.updated_at",+ )?;+ let stamp = now();+ for f in folders {+ stmt.execute(params![f.guid, f.title, f.sort_order, stamp])?;+ }+ }+ tx.commit()?;+ Ok(())+ }++ pub fn put_notes(&mut self, notes: &[Note]) -> Result<()> {+ let tx = self.conn.transaction()?;+ {+ let mut stmt = tx.prepare(+ "INSERT INTO notes (guid, folder_guid, title, snippet, body, locked, pinned,+ created_at, modified_at, etag, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)+ ON CONFLICT(guid) DO UPDATE SET+ folder_guid = excluded.folder_guid, title = excluded.title,+ snippet = excluded.snippet, body = excluded.body,+ locked = excluded.locked, pinned = excluded.pinned,+ created_at = excluded.created_at, modified_at = excluded.modified_at,+ etag = excluded.etag, updated_at = excluded.updated_at",+ )?;+ let stamp = now();+ for n in notes {+ stmt.execute(params![+ n.guid,+ n.folder_guid,+ n.title,+ n.snippet,+ n.body,+ i64::from(n.locked),+ i64::from(n.pinned),+ n.created_at,+ n.modified_at,+ n.etag,+ stamp+ ])?;+ }+ }+ tx.commit()?;+ Ok(())+ }++ pub fn forget_notes(&mut self, note_guids: &[String]) -> Result<()> {+ let tx = self.conn.transaction()?;+ {+ let mut stmt = tx.prepare("DELETE FROM notes WHERE guid = ?1")?;+ for guid in note_guids {+ stmt.execute(params![guid])?;+ }+ }+ tx.commit()?;+ Ok(())+ }++ pub fn note_folders(&self) -> Result<Vec<NoteFolder>> {+ let mut stmt = self.conn.prepare(+ "SELECT guid, title, sort_order FROM note_folders ORDER BY sort_order, title",+ )?;+ let rows = stmt.query_map([], |row| {+ Ok(NoteFolder {+ guid: row.get(0)?,+ title: row.get(1)?,+ sort_order: row.get(2)?,+ })+ })?;+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)+ }++ /// Notes in a folder, pinned first and then most recently changed — Apple's order.+ ///+ /// Passing `None` returns every note, which is what an "All Notes" view shows.+ pub fn notes_in(&self, folder_guid: Option<&str>) -> Result<Vec<Note>> {+ let mut stmt = self.conn.prepare(+ "SELECT guid, folder_guid, title, snippet, body, locked, pinned,+ created_at, modified_at, etag+ FROM notes+ WHERE ?1 IS NULL OR folder_guid = ?1+ ORDER BY pinned DESC, modified_at DESC, title",+ )?;+ let rows = stmt.query_map(params![folder_guid], |row| {+ Ok(Note {+ guid: row.get(0)?,+ folder_guid: row.get(1)?,+ title: row.get(2)?,+ snippet: row.get(3)?,+ body: row.get(4)?,+ locked: row.get::<_, i64>(5)? != 0,+ pinned: row.get::<_, i64>(6)? != 0,+ created_at: row.get(7)?,+ modified_at: row.get(8)?,+ etag: row.get(9)?,+ })+ })?;+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn folder(guid: &str, title: &str) -> NoteFolder {+ NoteFolder {+ guid: guid.into(),+ title: title.into(),+ sort_order: 0,+ }+ }++ fn note(guid: &str, folder: Option<&str>, pinned: bool, modified: i64) -> Note {+ Note {+ guid: guid.into(),+ folder_guid: folder.map(ToString::to_string),+ title: guid.into(),+ snippet: None,+ body: Some("body".into()),+ locked: false,+ pinned,+ created_at: Some(1),+ modified_at: Some(modified),+ etag: None,+ }+ }++ fn seeded() -> Library {+ let mut lib = Library::in_memory().unwrap();+ lib.put_note_folders(&[folder("f1", "Notes"), folder("f2", "Recently Deleted")])+ .unwrap();+ lib+ }++ /// Apple pins to the top, then orders by most recently changed.+ #[test]+ fn pinned_notes_come_first_then_most_recent() {+ let mut lib = seeded();+ lib.put_notes(&[+ note("old", Some("f1"), false, 100),+ note("newest", Some("f1"), false, 300),+ note("pinned-old", Some("f1"), true, 50),+ ])+ .unwrap();++ let order: Vec<String> = lib+ .notes_in(Some("f1"))+ .unwrap()+ .into_iter()+ .map(|n| n.guid)+ .collect();+ assert_eq!(order, vec!["pinned-old", "newest", "old"]);+ }++ #[test]+ fn every_note_is_returned_when_no_folder_is_given() {+ let mut lib = seeded();+ lib.put_notes(&[+ note("a", Some("f1"), false, 1),+ note("b", Some("f2"), false, 2),+ ])+ .unwrap();+ assert_eq!(lib.notes_in(None).unwrap().len(), 2);+ assert_eq!(lib.notes_in(Some("f1")).unwrap().len(), 1);+ }++ /// A note whose folder disappears must survive, unfiled — losing the note would be worse.+ #[test]+ fn a_note_outlives_its_folder() {+ let mut lib = seeded();+ lib.put_notes(&[note("a", Some("f1"), false, 1)]).unwrap();+ lib.conn()+ .execute("DELETE FROM note_folders WHERE guid = 'f1'", [])+ .unwrap();++ let all = lib.notes_in(None).unwrap();+ assert_eq!(all.len(), 1, "the note must not go with the folder");+ assert!(all[0].folder_guid.is_none(), "it becomes unfiled");+ }++ #[test]+ fn re_syncing_updates_rather_than_duplicates() {+ let mut lib = seeded();+ lib.put_notes(&[note("a", Some("f1"), false, 1)]).unwrap();+ let mut changed = note("a", Some("f1"), false, 2);+ changed.title = "Renamed".into();+ lib.put_notes(&[changed]).unwrap();++ let all = lib.notes_in(None).unwrap();+ assert_eq!(all.len(), 1);+ assert_eq!(all[0].title, "Renamed");+ }++ #[test]+ fn a_locked_note_is_recorded_as_locked() {+ let mut lib = seeded();+ let mut locked = note("secret", Some("f1"), false, 1);+ locked.locked = true;+ locked.body = None;+ lib.put_notes(&[locked]).unwrap();+ assert!(lib.notes_in(None).unwrap()[0].locked);+ }+}diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rsindex 703a85a..c28b1c5 100644--- a/crates/quince-core/src/schema.rs+++ b/crates/quince-core/src/schema.rs@@ -85,4 +85,34 @@ pub const MIGRATIONS: &[&str] = &[r#"ALTER TABLE reminders ADD COLUMN raw TEXT;"#,+ // 4 — notes and their folders.+ r#"+ CREATE TABLE note_folders (+ guid TEXT PRIMARY KEY,+ title TEXT NOT NULL,+ sort_order INTEGER NOT NULL DEFAULT 0,+ updated_at INTEGER NOT NULL+ ) STRICT;++ CREATE TABLE notes (+ guid TEXT PRIMARY KEY,+ folder_guid TEXT REFERENCES note_folders(guid) ON DELETE SET NULL,+ title TEXT NOT NULL,+ -- The first line or so, which Apple sends separately so a list can render without+ -- decoding every body.+ snippet TEXT,+ body TEXT,+ -- A note the owner locked is genuinely encrypted; we can show that it exists and+ -- nothing more, so say so rather than rendering it blank.+ locked INTEGER NOT NULL DEFAULT 0,+ pinned INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER,+ modified_at INTEGER,+ etag TEXT,+ updated_at INTEGER NOT NULL+ ) STRICT;++ CREATE INDEX notes_by_folder ON notes (folder_guid, pinned DESC, modified_at DESC);+ CREATE INDEX notes_by_modified ON notes (modified_at DESC);+ "#,];diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rsindex b95d65c..058e325 100644--- a/crates/quince-icloud/src/ckdocument.rs+++ b/crates/quince-icloud/src/ckdocument.rs@@ -127,8 +127,31 @@ pub fn text_from_base64(value: &str) -> Option<String> {#[must_use]pub fn text_from_bytes(raw: &[u8]) -> Option<String> {let plain = inflate(raw)?;- let found = field_at(&plain, TEXT_PATH)?;- let text = String::from_utf8(found.to_vec()).ok()?;++ // Reminder titles and note bodies are wrapped in Apple's document protobuf.+ if let Some(found) = field_at(&plain, TEXT_PATH) {+ if let Some(text) = usable_text(found) {+ return Some(text);+ }+ }++ // Note and folder titles are not wrapped at all — the payload is the text. Falling back+ // rather than failing is what lets one decoder serve both.+ usable_text(&plain)+}++/// Valid, non-empty UTF-8 with nothing unprintable in it.+///+/// The printability check is what stops a protobuf being mistaken for text: raw wire bytes+/// occasionally decode as UTF-8 but are full of control characters.+fn usable_text(bytes: &[u8]) -> Option<String> {+ let text = std::str::from_utf8(bytes).ok()?;+ if text+ .chars()+ .any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t'))+ {+ return None;+ }let trimmed = text.trim();(!trimmed.is_empty()).then(|| trimmed.to_string())}@@ -321,10 +344,40 @@ mod tests {assert_eq!(field_at(&plain, TEXT_PATH), Some(&b"Milk"[..]));}+ /// Note and folder titles arrive as bare UTF-8 rather than wrapped in the document+ /// protobuf, so one decoder has to serve both shapes.+ #[test]+ fn reads_bare_text_that_was_never_wrapped() {+ assert_eq!(+ text_from_bytes(b"Recently Deleted").as_deref(),+ Some("Recently Deleted")+ );+ assert_eq!(text_from_bytes(b"Notes").as_deref(), Some("Notes"));+ assert_eq!(+ text_from_bytes(&gzipped(b"Shopping")).as_deref(),+ Some("Shopping")+ );+ }++ /// The wrapped form must still win, or a document would be returned as its raw wire bytes.+ #[test]+ fn the_wrapped_form_takes_precedence() {+ let payload = gzipped(&document("Real title"));+ assert_eq!(text_from_bytes(&payload).as_deref(), Some("Real title"));+ }++ /// Binary that happens to be valid UTF-8 must not be mistaken for text.+ #[test]+ fn control_characters_mean_it_is_not_text() {+ assert!(text_from_bytes(&[0x01, 0x02, 0x03]).is_none());+ assert!(text_from_bytes(&[0x00; 16]).is_none());+ }+#[test]fn a_document_without_the_text_field_is_none() {- // Right nesting, wrong final tag.- let wrong = field(2, &field(3, &field(9, b"hidden")));+ // Right nesting, wrong final tag — and binary enough that the plain-text fallback+ // does not rescue it either.+ let wrong = field(2, &field(3, &field(9, &[0x01, 0x02, 0x03])));assert!(text_from_bytes(&wrong).is_none());}}diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rsindex 47e73de..e8458de 100644--- a/crates/quince-icloud/src/lib.rs+++ b/crates/quince-icloud/src/lib.rs@@ -6,6 +6,7 @@pub mod calendar;pub mod ckdocument;pub mod cloudkit;+pub mod notes;pub mod reminders;pub mod sync;diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rsnew file mode 100644index 0000000..026d4e6--- /dev/null+++ b/crates/quince-icloud/src/notes.rs@@ -0,0 +1,332 @@+//! Apple Notes, read from its CloudKit zone.+//!+//! The zone mixes several record types. `Note` holds the content; `Folder` holds a name; and+//! `Note_UserSpecific` carries per-device state — crucially including whether a note was+//! deleted, which is *not* on the note itself.+//!+//! Text arrives in two shapes. Bodies are wrapped in Apple's document protobuf; titles and+//! folder names are bare UTF-8. One decoder handles both.++use crate::cloudkit::{field, ZoneClient};+use crate::Result;+use quince_core::notes::{Note, NoteFolder};+use serde_json::Value;++const CONTAINER: &str = "com.apple.notes";+const ZONE: &str = "Notes";++fn folder_from_record(record: &Value) -> Option<NoteFolder> {+ Some(NoteFolder {+ guid: field::record_name(record)?,+ title: field::document_text(record, "TitleEncrypted").unwrap_or_else(|| "Notes".into()),+ sort_order: 0,+ })+}++fn note_from_record(record: &Value) -> Option<Note> {+ let guid = field::record_name(record)?;+ let title = field::document_text(record, "TitleEncrypted");+ let body = field::document_text(record, "TextDataEncrypted");++ // A note whose body will not decode while a title will is locked by its owner: Apple+ // holds those genuinely encrypted. Saying so beats rendering an empty note.+ let locked = body.is_none()+ && record+ .get("fields")+ .is_some_and(|f| f.get("TextDataEncrypted").is_some());++ Some(Note {+ guid,+ folder_guid: field::reference(record, "Folder"),+ title: title.unwrap_or_else(|| "Untitled".into()),+ snippet: field::document_text(record, "SnippetEncrypted"),+ body,+ locked,+ pinned: false, // carried on the per-user record, applied below+ created_at: field::timestamp_seconds(record, "CreationDate"),+ modified_at: field::timestamp_seconds(record, "ModificationDate"),+ etag: record+ .get("recordChangeTag")+ .and_then(Value::as_str)+ .map(ToString::to_string),+ })+}++/// Read notes from CloudKit into the local library.+///+/// Pass `since` to fetch only what changed; as with reminders, absence in a delta means+/// unchanged rather than deleted.+pub async fn sync_cloudkit(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ library: &mut quince_core::Library,+ since: Option<&str>,+) -> Result<(usize, usize, Option<String>)> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ let (records, token) = client.all_records(ZONE, since).await?;++ let mut folders: Vec<NoteFolder> = Vec::new();+ let mut notes: Vec<Note> = Vec::new();+ let mut gone: Vec<String> = Vec::new();+ // Deletion and pinning live on the per-user record, keyed by a reference to the note.+ let mut deleted_notes: std::collections::HashSet<String> = std::collections::HashSet::new();+ let mut pinned_notes: std::collections::HashSet<String> = std::collections::HashSet::new();++ for record in &records {+ let Some(kind) = field::record_type(record) else {+ continue;+ };+ let removed = record+ .get("deleted")+ .and_then(Value::as_bool)+ .unwrap_or(false)+ || field::flag(record, "Deleted");++ match kind.as_str() {+ "Note" => {+ let Some(name) = field::record_name(record) else {+ continue;+ };+ if removed {+ gone.push(name);+ } else {+ notes.extend(note_from_record(record));+ }+ }+ "Folder" => folders.extend(folder_from_record(record)),+ // Per-user state. The note it refers to is what matters, not this record's name.+ "Note_UserSpecific" | "PasswordProtectedNote_UserSpecific" => {+ if let Some(target) = field::reference(record, "Note") {+ if removed {+ deleted_notes.insert(target);+ } else if field::flag(record, "IsPinned") {+ pinned_notes.insert(target);+ }+ }+ }+ _ => {}+ }+ }++ // A note the owner deleted is still present as a Note record; only the per-user record+ // says so. Without this, deleted notes would keep showing.+ notes.retain(|n| !deleted_notes.contains(&n.guid));+ gone.extend(deleted_notes);+ for note in &mut notes {+ note.pinned = pinned_notes.contains(¬e.guid);+ }++ // A note may reference a folder that this page did not carry; keeping the reference+ // would break the foreign key, so drop it and leave the note unfiled.+ let known: std::collections::HashSet<&str> = folders.iter().map(|f| f.guid.as_str()).collect();+ let stored: std::collections::HashSet<String> = library+ .note_folders()?+ .into_iter()+ .map(|f| f.guid)+ .collect();+ for note in &mut notes {+ if let Some(folder) = ¬e.folder_guid {+ if !known.contains(folder.as_str()) && !stored.contains(folder) {+ note.folder_guid = None;+ }+ }+ }++ library.put_note_folders(&folders)?;+ library.put_notes(¬es)?;+ if !gone.is_empty() {+ library.forget_notes(&gone)?;+ }+ library.mark_synced("notes", token.as_deref())?;+ Ok((folders.len(), notes.len(), token))+}++#[cfg(test)]+mod tests {+ use super::*;+ use quince_core::Library;+ use serde_json::json;+ use wiremock::matchers::{method, path_regex};+ use wiremock::{Mock, MockServer, ResponseTemplate};++ fn bare(text: &str) -> String {+ use base64::{engine::general_purpose::STANDARD as B64, Engine};+ B64.encode(text.as_bytes())+ }++ fn note_record(name: &str, title: &str, body: Option<&str>, folder: &str) -> Value {+ let mut fields = serde_json::Map::new();+ fields.insert(+ "TitleEncrypted".into(),+ json!({ "type": "ENCRYPTED_BYTES", "value": bare(title) }),+ );+ fields.insert(+ "TextDataEncrypted".into(),+ json!({ "type": "ENCRYPTED_BYTES",+ "value": body.map_or_else(|| bare("\u{1}\u{2}"), bare) }),+ );+ fields.insert(+ "Folder".into(),+ json!({ "type": "REFERENCE", "value": { "recordName": folder } }),+ );+ fields.insert(+ "ModificationDate".into(),+ json!({ "type": "TIMESTAMP", "value": 1_700_000_000_000_i64 }),+ );+ json!({ "recordName": name, "recordType": "Note", "fields": fields })+ }++ fn folder_record(name: &str, title: &str) -> Value {+ json!({+ "recordName": name, "recordType": "Folder",+ "fields": { "TitleEncrypted": { "type": "ENCRYPTED_BYTES", "value": bare(title) } }+ })+ }++ async fn serve(body: Value) -> MockServer {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path_regex(r".*/changes/zone$"))+ .respond_with(ResponseTemplate::new(200).set_body_json(body))+ .mount(&server)+ .await;+ server+ }++ #[tokio::test]+ async fn notes_and_folders_land_with_their_titles() {+ let server = serve(json!({ "zones": [{+ "records": [+ folder_record("Folder/f1", "Notes"),+ note_record("Note/n1", "UNIT 1: Testing", Some("the body"), "Folder/f1"),+ ],+ "syncToken": "t1", "moreComing": false }] }))+ .await;++ let mut library = Library::in_memory().unwrap();+ let (folders, notes, _) = sync_cloudkit(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &mut library,+ None,+ )+ .await+ .unwrap();+ assert_eq!((folders, notes), (1, 1));++ let stored = library.notes_in(None).unwrap();+ assert_eq!(stored[0].title, "UNIT 1: Testing");+ assert_eq!(stored[0].body.as_deref(), Some("the body"));+ assert_eq!(library.note_folders().unwrap()[0].title, "Notes");+ }++ /// Deletion lives on the per-user record, not the note. Missing that leaves deleted+ /// notes on screen forever.+ #[tokio::test]+ async fn a_note_deleted_via_its_user_record_disappears() {+ let server = serve(json!({ "zones": [{+ "records": [+ folder_record("Folder/f1", "Notes"),+ note_record("Note/n1", "Gone", Some("x"), "Folder/f1"),+ { "recordName": "NoteUS/1", "recordType": "Note_UserSpecific",+ "fields": {+ "Deleted": { "type": "INT64", "value": 1 },+ "Note": { "type": "REFERENCE", "value": { "recordName": "Note/n1" } }+ }}+ ],+ "syncToken": "t1", "moreComing": false }] }))+ .await;++ let mut library = Library::in_memory().unwrap();+ sync_cloudkit(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &mut library,+ None,+ )+ .await+ .unwrap();+ assert!(library.notes_in(None).unwrap().is_empty());+ }++ #[tokio::test]+ async fn pinning_comes_from_the_per_user_record() {+ let server = serve(json!({ "zones": [{+ "records": [+ folder_record("Folder/f1", "Notes"),+ note_record("Note/n1", "Pinned one", Some("x"), "Folder/f1"),+ { "recordName": "NoteUS/1", "recordType": "Note_UserSpecific",+ "fields": {+ "IsPinned": { "type": "INT64", "value": 1 },+ "Note": { "type": "REFERENCE", "value": { "recordName": "Note/n1" } }+ }}+ ],+ "syncToken": "t1", "moreComing": false }] }))+ .await;++ let mut library = Library::in_memory().unwrap();+ sync_cloudkit(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &mut library,+ None,+ )+ .await+ .unwrap();+ assert!(library.notes_in(None).unwrap()[0].pinned);+ }++ /// A locked note is genuinely encrypted; it should appear, marked, not vanish.+ #[tokio::test]+ async fn a_locked_note_is_kept_and_flagged() {+ let server = serve(json!({ "zones": [{+ "records": [+ folder_record("Folder/f1", "Notes"),+ note_record("Note/n1", "Private", None, "Folder/f1"),+ ],+ "syncToken": "t1", "moreComing": false }] }))+ .await;++ let mut library = Library::in_memory().unwrap();+ sync_cloudkit(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &mut library,+ None,+ )+ .await+ .unwrap();+ let stored = library.notes_in(None).unwrap();+ assert_eq!(stored.len(), 1, "a locked note still exists");+ assert!(stored[0].locked);+ assert_eq!(stored[0].title, "Private", "its title is not secret");+ }++ /// A note pointing at a folder we have never seen must not break the foreign key.+ #[tokio::test]+ async fn an_unknown_folder_leaves_the_note_unfiled() {+ let server = serve(json!({ "zones": [{+ "records": [note_record("Note/n1", "Orphan", Some("x"), "Folder/missing")],+ "syncToken": "t1", "moreComing": false }] }))+ .await;++ let mut library = Library::in_memory().unwrap();+ sync_cloudkit(+ &reqwest::Client::new(),+ &server.uri(),+ vec![],+ &mut library,+ None,+ )+ .await+ .unwrap();+ let stored = library.notes_in(None).unwrap();+ assert_eq!(stored.len(), 1);+ assert!(stored[0].folder_guid.is_none());+ }+}diff --git a/probe/src/main.rs b/probe/src/main.rsindex 245c310..8af69f7 100644--- a/probe/src/main.rs+++ b/probe/src/main.rs@@ -609,6 +609,102 @@ async fn main() -> Result<()> {}}+ // ---- what Notes records look like -------------------------------------------+ println!("\n\x1b[1m── Notes: record census and shapes ──\x1b[0m");+ if let Some(ck) = session.service_url("ckdatabasews") {+ for zone_name in ["Notes", "Metadata"] {+ let zc = quince_icloud::cloudkit::ZoneClient::new(+ client.http(),+ &ck,+ "com.apple.notes",+ client.service_params(),+ );+ match zc.all_records(zone_name, None).await {+ Err(e) => println!(+ " {zone_name:<12} error: {}",+ e.to_string().chars().take(70).collect::<String>()+ ),+ Ok((records, _)) => {+ let mut census: std::collections::BTreeMap<String, usize> =+ std::collections::BTreeMap::new();+ for r in &records {+ let k = r+ .get("recordType")+ .and_then(|t| t.as_str())+ .unwrap_or("(tombstone)");+ *census.entry(k.to_string()).or_default() += 1;+ }+ let summary: Vec<String> =+ census.iter().map(|(k, n)| format!("{k}={n}")).collect();+ println!(+ " {zone_name:<12} {} record(s): {}",+ records.len(),+ summary.join(" ")+ );++ // Does the reminder decoder handle note text too, or is the shape different?+ for r in records+ .iter()+ .filter(|r| {+ matches!(+ r.get("recordType").and_then(|t| t.as_str()),+ Some("Note" | "Folder")+ )+ })+ .take(4)+ {+ let kind = r.get("recordType").and_then(|t| t.as_str()).unwrap_or("");+ let decode = |name: &str| {+ quince_icloud::cloudkit::field::document_text(r, name)+ .map(|t| {+ t.chars().take(64).collect::<String>().replace('\n', " / ")+ })+ .unwrap_or_else(|| "<did not decode>".into())+ };+ println!(" {kind}: title={:?}", decode("TitleEncrypted"));+ if kind == "Note" {+ println!(" text={:?}", decode("TextDataEncrypted"));+ }+ // The title does not decode at the reminders path, so emit the raw+ // payload once and let the structure be read directly.+ if let Some(raw) =+ quince_icloud::cloudkit::field::string(r, "TitleEncrypted")+ {+ println!(" TITLE_B64 {raw}");+ }+ }++ // One sample per type, so field names come from reality.+ let mut seen: std::collections::BTreeSet<String> =+ std::collections::BTreeSet::new();+ for r in &records {+ let Some(kind) = r.get("recordType").and_then(|t| t.as_str()) else {+ continue;+ };+ if !seen.insert(kind.to_string()) {+ continue;+ }+ let fields: Vec<String> = r+ .get("fields")+ .and_then(|f| f.as_object())+ .map(|o| {+ o.iter()+ .map(|(k, v)| {+ format!(+ "{k}:{}",+ v.get("type").and_then(|t| t.as_str()).unwrap_or("?")+ )+ })+ .collect()+ })+ .unwrap_or_default();+ println!(" {kind}: {}", fields.join(", "));+ }+ }+ }+ }+ }+// ---- CloudKit containers ----------------------------------------------------// Apple's legacy /rd and /ca endpoints answer with a placeholder once data has been// upgraded to the modern format. The real records live in CloudKit, so find out whichdiff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 4a8801f..b022178 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -3,6 +3,7 @@use quince_auth::{Client, SignInOutcome, TwoFactorOptions};use quince_core::calendar::{Calendar, Event};+use quince_core::notes::{Note, NoteFolder};use quince_core::reminders::{Reminder, ReminderList};use quince_core::Library;use serde::Serialize;@@ -379,6 +380,39 @@ async fn calendar_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {library.last_synced("calendar").map_err(|e| e.to_string())}+/// Refresh notes from Apple's CloudKit zone.+#[tauri::command]+async fn notes_sync(auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<(usize, usize)> {+ let (http, root, params) = cloudkit_context(&auth).await?;+ let mut library = data.0.lock().await;+ let since = library.sync_token("notes").map_err(|e| e.to_string())?;+ quince_icloud::notes::sync_cloudkit(&http, &root, params, &mut library, since.as_deref())+ .await+ .map(|(folders, notes, _)| (folders, notes))+ .map_err(|e| e.to_string())+}++#[tauri::command]+async fn note_folders(data: State<'_, Data>) -> UiResult<Vec<NoteFolder>> {+ let library = data.0.lock().await;+ library.note_folders().map_err(|e| e.to_string())+}++/// Notes in a folder, or every note when no folder is given.+#[tauri::command]+async fn notes_in(folder_guid: Option<String>, data: State<'_, Data>) -> UiResult<Vec<Note>> {+ let library = data.0.lock().await;+ library+ .notes_in(folder_guid.as_deref())+ .map_err(|e| e.to_string())+}++#[tauri::command]+async fn notes_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {+ let library = data.0.lock().await;+ library.last_synced("notes").map_err(|e| e.to_string())+}+fn main() {tauri::Builder::default().setup(|app| {@@ -416,6 +450,10 @@ fn main() {reminders_due_between,reminder_create,reminder_delete,+ notes_sync,+ note_folders,+ notes_in,+ notes_last_synced,reminder_set_done,]).run(tauri::generate_context!())diff --git a/src/App.tsx b/src/App.tsxindex 45ae7da..72c1594 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -9,6 +9,7 @@ type Phase = "checking" | "signin" | "code" | "library";/** Services worth having ready before anyone asks for them. */const BACKGROUND_SYNCS = [{ lastSynced: api.remindersLastSynced, sync: api.remindersSync },+ { lastSynced: api.notesLastSynced, sync: api.notesSync },];export default function App() {diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 8bd36b0..3c35071 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -44,6 +44,11 @@ export const api = {invoke<void>("reminder_create", { listGuid, title }),reminderDelete: (guid: string, listGuid: string) =>invoke<void>("reminder_delete", { guid, listGuid }),++ notesSync: () => invoke<[number, number]>("notes_sync"),+ noteFolders: () => invoke<NoteFolder[]>("note_folders"),+ notesIn: (folderGuid: string | null) => invoke<Note[]>("notes_in", { folderGuid }),+ notesLastSynced: () => invoke<number | null>("notes_last_synced"),};/** Tauri rejects with a plain string from our commands; keep it readable either way. */@@ -94,6 +99,22 @@ export type Reminder = {etag: string | null;};+export type NoteFolder = { guid: string; title: string; sortOrder: number };++export type Note = {+ guid: string;+ folderGuid: string | null;+ title: string;+ snippet: string | null;+ body: string | null;+ /** Locked by its owner, so Apple holds it encrypted and there is nothing to show. */+ locked: boolean;+ pinned: boolean;+ createdAt: number | null;+ modifiedAt: number | null;+ etag: string | null;+};+export function messageOf(e: unknown): string {if (typeof e === "string") return e;if (e instanceof Error) return e.message;diff --git a/src/screens/Library.tsx b/src/screens/Library.tsxindex 8f5facc..c579647 100644--- a/src/screens/Library.tsx+++ b/src/screens/Library.tsx@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";import { api, messageOf } from "../lib/ipc";import { CalendarView } from "./CalendarView";import { RemindersView } from "./RemindersView";+import { NotesView } from "./NotesView";const NAMES: Record<string, string> = {photos: "Photos",@@ -41,7 +42,7 @@ const NAMES: Record<string, string> = {/** Services with a real screen behind them. Opening on one of these beats opening on a* placeholder, so selection prefers them. */-const BUILT = new Set(["calendar", "reminders"]);+const BUILT = new Set(["calendar", "reminders", "notes"]);/** What a person actually came for, in the order they'd look for it. */const PRIMARY = [@@ -153,6 +154,8 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {<CalendarView />) : selected === "reminders" ? (<RemindersView />+ ) : selected === "notes" ? (+ <NotesView />) : (<><div className="toolbar">diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxnew file mode 100644index 0000000..ae037be--- /dev/null+++ b/src/screens/NotesView.tsx@@ -0,0 +1,183 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { api, messageOf, type Note, type NoteFolder } from "../lib/ipc";++const ALL = "__all__";++const when = (seconds: number | null) => {+ if (seconds === null) return "";+ const d = new Date(seconds * 1000);+ const today = new Date();+ const sameDay =+ d.getFullYear() === today.getFullYear() &&+ d.getMonth() === today.getMonth() &&+ d.getDate() === today.getDate();+ return sameDay+ ? d.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" })+ : d.toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });+};++function relative(seconds: number | null): string {+ if (seconds === null) return "never";+ const ago = Math.max(0, Math.floor(Date.now() / 1000) - seconds);+ if (ago < 60) return "just now";+ if (ago < 3600) return `${Math.floor(ago / 60)} min ago`;+ if (ago < 86_400) return `${Math.floor(ago / 3600)} h ago`;+ return `${Math.floor(ago / 86_400)} d ago`;+}++export function NotesView() {+ const [folders, setFolders] = useState<NoteFolder[]>([]);+ const [folder, setFolder] = useState<string>(ALL);+ const [notes, setNotes] = useState<Note[]>([]);+ const [openGuid, setOpenGuid] = useState<string | null>(null);+ const [lastSynced, setLastSynced] = useState<number | null>(null);+ const [syncing, setSyncing] = useState(false);+ const [loaded, setLoaded] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const read = useCallback(async () => {+ const [found, list, synced] = await Promise.all([+ api.noteFolders(),+ api.notesIn(folder === ALL ? null : folder),+ api.notesLastSynced(),+ ]);+ setFolders(Array.isArray(found) ? found : []);+ setNotes(Array.isArray(list) ? list : []);+ setLastSynced(typeof synced === "number" ? synced : null);+ setLoaded(true);+ }, [folder]);++ const refreshRef = useRef<null | (() => Promise<void>)>(null);++ const refresh = useCallback(async () => {+ setSyncing(true);+ setError(null);+ try {+ await api.notesSync();+ await read();+ } catch (e) {+ setError(messageOf(e));+ } finally {+ setSyncing(false);+ }+ }, [read]);+ refreshRef.current = refresh;++ useEffect(() => {+ let cancelled = false;+ (async () => {+ try {+ await read();+ if (cancelled) return;+ if ((await api.notesLastSynced()) === null) void refreshRef.current?.();+ } catch (e) {+ if (!cancelled) {+ setError(messageOf(e));+ setLoaded(true);+ }+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [read]);++ // Keep a note open across refreshes where possible; fall back to the first.+ useEffect(() => {+ if (notes.length === 0) return setOpenGuid(null);+ setOpenGuid((current) =>+ current && notes.some((n) => n.guid === current) ? current : notes[0].guid+ );+ }, [notes]);++ const open = useMemo(+ () => notes.find((n) => n.guid === openGuid) ?? null,+ [notes, openGuid]+ );++ return (+ <div className="notes">+ <aside className="notes-folders" aria-label="Note folders">+ <button+ className="rem-list"+ aria-current={folder === ALL}+ onClick={() => setFolder(ALL)}+ >+ <span className="rem-list-name">All Notes</span>+ </button>+ {folders.map((f) => (+ <button+ key={f.guid}+ className="rem-list"+ aria-current={folder === f.guid}+ onClick={() => setFolder(f.guid)}+ >+ <span className="rem-list-name">{f.title}</span>+ </button>+ ))}+ </aside>++ <section className="notes-list" aria-label="Notes">+ <header className="cal-bar">+ <div className="cal-nav">+ <h1>{folder === ALL ? "All Notes" : folders.find((f) => f.guid === folder)?.title}</h1>+ </div>+ <div className="cal-actions">+ <span className="badge">Updated {relative(lastSynced)}</span>+ <button className="quiet" onClick={refresh} disabled={syncing}>+ {syncing ? "Refreshing…" : "Refresh"}+ </button>+ </div>+ </header>++ {error && <p className="error" role="alert">{error}</p>}++ <ul className="note-rows">+ {notes.map((note) => (+ <li key={note.guid}>+ <button+ className="note-row"+ aria-current={openGuid === note.guid}+ onClick={() => setOpenGuid(note.guid)}+ >+ <span className="note-row-title">+ {note.pinned && <span className="pin" aria-label="Pinned">●</span>}+ {note.title}+ </span>+ <span className="note-row-meta">+ <span className="note-row-when">{when(note.modifiedAt)}</span>+ <span className="note-row-snippet">+ {note.locked ? "Locked" : note.snippet || note.body?.slice(0, 60) || "No text"}+ </span>+ </span>+ </button>+ </li>+ ))}+ </ul>++ {loaded && notes.length === 0 && !error && (+ <p className="cal-empty">No notes here.</p>+ )}+ </section>++ <article className="note-body" aria-label="Note">+ {open ? (+ open.locked ? (+ <p className="cal-empty">+ This note is locked. Apple keeps it encrypted, so there is nothing here to+ show — open it on a device where you can enter its password.+ </p>+ ) : (+ <>+ <h2>{open.title}</h2>+ <p className="note-when">{when(open.modifiedAt)}</p>+ <pre className="note-text">{open.body ?? ""}</pre>+ </>+ )+ ) : (+ loaded && <p className="cal-empty">Select a note.</p>+ )}+ </article>+ </div>+ );+}diff --git a/src/styles/app.css b/src/styles/app.cssindex 14021cf..0a075de 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -639,3 +639,75 @@.rem-delete:focus-visible { opacity: 1; }.rem-delete:hover { color: var(--danger); background: color-mix(in srgb, var(--danger) 12%, transparent); }.rem-delete:focus-visible { outline: 3px solid var(--gold-ring); outline-offset: 1px; }++/* ---- notes ----------------------------------------------------------------------+ Apple Notes: folders, then a list of notes, then the note itself. */++.notes {+ display: grid;+ grid-template-columns: 150px 250px 1fr;+ gap: 16px;+ height: 100%;+ min-height: 0;+}++.notes-folders { overflow-y: auto; border-right: 1px solid var(--separator); padding-right: 4px; }++.notes-list {+ display: flex;+ flex-direction: column;+ min-height: 0;+ border-right: 1px solid var(--separator);+ padding-right: 12px;+}++.note-rows { list-style: none; margin: 0; padding: 0; overflow-y: auto; min-height: 0; }++.note-row {+ display: flex;+ flex-direction: column;+ gap: 2px;+ width: 100%;+ border: 0;+ background: none;+ color: var(--text);+ font: inherit;+ text-align: left;+ padding: 8px 9px;+ border-radius: var(--r-field);+ cursor: pointer;+}++.note-row:hover { background: color-mix(in srgb, var(--text) 5%, transparent); }+.note-row[aria-current="true"] { background: var(--gold-tint); }+.note-row:focus-visible { outline: 3px solid var(--gold-ring); outline-offset: -1px; }++.note-row-title {+ font-size: var(--t-13);+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.pin { color: var(--gold); font-size: 9px; margin-right: 5px; vertical-align: 2px; }++.note-row-meta { display: flex; gap: 8px; font-size: var(--t-11); color: var(--text-2); min-width: 0; }+.note-row-when { flex: none; }+.note-row-snippet { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }++.note-body { overflow-y: auto; min-height: 0; padding-right: 6px; }+.note-body h2 { margin: 0 0 2px; font-size: var(--t-22); font-weight: 600; letter-spacing: -0.02em; }+.note-when { margin: 0 0 14px; color: var(--text-3); font-size: var(--t-11); }++.note-text {+ margin: 0;+ font: inherit;+ font-size: var(--t-13);+ line-height: 1.55;+ white-space: pre-wrap;+ word-break: break-word;+ max-width: 78ch;+}++.content:has(.notes) { display: flex; flex-direction: column; overflow: hidden; }