android: the device token is stored sealed under a Keystore key
CI & Build / Build now, or wait for Android? (push) Successful in 3s
Android / Build, or is the channel already serving this? (push) Successful in 4s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Web typecheck and unit tests (push) Successful in 20s
CI & Build / Python tests (push) Successful in 20s
Desktop (Tauri) / Build, or is the channel already serving this? (push) Successful in 2s
Android / Core and FFI clippy and tests (push) Successful in 1m12s
CI & Build / integration (push) Successful in 1m44s
CI & Build / Build & push image (push) Skipped
Desktop (Tauri) / Web tests, clippy, Rust tests and rustfmt (push) Successful in 2m17s
Desktop (Tauri) / Windows installer (cross-compiled) (push) Successful in 3m30s
Desktop (Tauri) / Tauri desktop (Linux) (push) Successful in 4m27s
Desktop (Tauri) / Update manifest (push) Successful in 4s
Android / Kotlin + Rust (APK) (push) Successful in 9m15s
Android / Build the server image (push) Successful in 1s

Family idea #5105, practice 12, as the operator chose on 2026-10-08: the token
is encrypted, and Android backup stays on.

The core:
- Adds a TokenSeal trait in sync/state.rs, with set_sealed_link and
  open_token.
- A sealed token is stored as "sealed:<value>".
- A plain token, stored before this change or while sealing failed, is sealed
  in place on its next read.
- A sealed token that won't open is dropped, and the server address and cursor
  are kept, so the app reads as unlinked and asks to sign in again. That is
  what happens after Android restores the app onto another phone.
- The desktop passes no seal and keeps storing the token as before.

The FFI:
- Exports TokenSeal as a uniffi foreign trait (seal_token / open_token, null
  rather than an exception).
- Requires it in Inkwell's constructor, so there is no moment a token could be
  stored unsealed.
- Routes credentials(), unlink() and store_link() through it.

Kotlin:
- KeystoreTokenSeal is AES-GCM under an Android Keystore key, using the
  SealedBox framing from Minstrel's KeystoreSessionVault (Scribe snippet #5025),
  with no new dependency.
- SealedBoxTest checks the framing on the JVM.

allowBackup stays true, and the manifest says why. An unlinked phone's notes
exist only on the phone, and the backup is their one other copy. The backup
carries a token nothing can open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 10:23:22 -04:00
co-authored by Claude Opus 5.5
parent bb591871a4
commit 8592b83538
6 changed files with 376 additions and 27 deletions
+87 -26
View File
@@ -104,15 +104,46 @@ impl CoreError {
}
}
/// Seals the device token before it is stored, and opens it when it is read: Kotlin's
/// half of [`state::TokenSeal`] (family idea #5105, practice 12).
///
/// Implemented with a key in the Android Keystore. The key never leaves the phone,
/// so a copy of the app's files carries a token nothing else can open. That includes
/// Android's own backup, which stays on because an unlinked phone's notes exist only
/// there. Restored onto another phone, the app asks to sign in again.
///
/// Return null rather than throw: an exception escaping into the core would be a
/// panic there.
#[uniffi::export(with_foreign)]
pub trait TokenSeal: Send + Sync {
/// The token sealed for storage, or null when that isn't possible right now.
fn seal_token(&self, token: String) -> Option<String>;
/// The sealed token opened, or null when this phone can't open it.
fn open_token(&self, sealed: String) -> Option<String>;
}
/// Kotlin's seal, as the core asks for one.
struct ForeignSeal(Arc<dyn TokenSeal>);
impl state::TokenSeal for ForeignSeal {
fn seal(&self, token: &str) -> Option<String> {
self.0.seal_token(token.to_string())
}
fn open(&self, sealed: &str) -> Option<String> {
self.0.open_token(sealed.to_string())
}
}
/// The client handle: the on-device store plus the attachment directory beside it.
///
/// Held by Kotlin for the process lifetime. Both halves are `Send + Sync` — the store
/// behind its mutex, the blob store being a path — which is what lets uniffi share
/// one instance across coroutines.
/// Held by Kotlin for the process lifetime. Every part is `Send + Sync` (the store
/// behind its mutex, the blob store being a path, the seal by its trait bound),
/// which is what lets uniffi share one instance across coroutines.
#[derive(uniffi::Object)]
pub struct Inkwell {
db: Db,
blobs: BlobStore,
seal: ForeignSeal,
}
#[uniffi::export]
@@ -124,8 +155,11 @@ impl Inkwell {
/// storage is; the core must not guess at a platform path. The layout inside is
/// the core's business and matches the desktop's exactly — `inkwell.db` and
/// `blobs/` — so a store is readable by any client that opens it.
///
/// `seal` is required rather than set later, so there is no moment in which a
/// token could be stored unsealed by a caller that forgot.
#[uniffi::constructor]
pub fn new(data_dir: String) -> Result<Arc<Self>, CoreError> {
pub fn new(data_dir: String, seal: Arc<dyn TokenSeal>) -> Result<Arc<Self>, CoreError> {
let dir = PathBuf::from(data_dir);
std::fs::create_dir_all(&dir).map_err(CoreError::store)?;
@@ -133,7 +167,11 @@ impl Inkwell {
log::info!("local store ready — {}", local::summary(&db));
let blobs = BlobStore::new(dir.join("blobs")).map_err(CoreError::store)?;
Ok(Arc::new(Inkwell { db, blobs }))
Ok(Arc::new(Inkwell {
db,
blobs,
seal: ForeignSeal(seal),
}))
}
/// A one-line count summary, for the boot log.
@@ -506,11 +544,12 @@ impl Inkwell {
pub async fn unlink(&self) -> Result<RevokeOutcome, CoreError> {
// Read and release before the network call: a std MutexGuard isn't Send, so
// it cannot be held across an await, and holding the store through a
// round-trip would freeze every note operation in the UI.
let link = {
let conn = self.db.conn().map_err(CoreError::store)?;
let current = state::read(&conn).map_err(CoreError::store)?;
current.server_url.zip(current.device_token)
// round-trip would freeze every note operation in the UI. A token that won't
// open on this phone can't be revoked from here, so it is skipped.
let link = match self.credentials() {
Ok(link) => Some(link),
Err(CoreError::NotLinked) => None,
Err(e) => return Err(e),
};
let revoked = match &link {
Some((base_url, token)) => client::revoke_self(base_url, token).await,
@@ -699,12 +738,18 @@ pub fn body_tags(body: String) -> Vec<BodyTag> {
impl Inkwell {
/// The server URL + token, or the `NotLinked` state. Every networked call needs
/// exactly this, and none of them may hold the lock past it.
///
/// `NotLinked` also when the stored token won't open on this phone, which drops
/// it (`state::open_token`), so the app asks to sign in again.
fn credentials(&self) -> Result<(String, String), CoreError> {
let conn = self.db.conn().map_err(CoreError::store)?;
let current = state::read(&conn).map_err(CoreError::store)?;
match (current.server_url, current.device_token) {
(Some(url), Some(token)) => Ok((url, token)),
_ => Err(CoreError::NotLinked),
let (Some(url), Some(stored)) = (current.server_url, current.device_token) else {
return Err(CoreError::NotLinked);
};
match state::open_token(&conn, &stored, &self.seal).map_err(CoreError::store)? {
Some(token) => Ok((url, token)),
None => Err(CoreError::NotLinked),
}
}
@@ -718,7 +763,7 @@ impl Inkwell {
retention_days: Option<u32>,
) -> Result<(), CoreError> {
let conn = self.db.conn().map_err(CoreError::store)?;
state::set_link(&conn, base_url, token).map_err(CoreError::store)?;
state::set_sealed_link(&conn, base_url, token, &self.seal).map_err(CoreError::store)?;
if let Some(days) = retention_days {
state::set_server_retention(&conn, days as i64).map_err(CoreError::store)?;
}
@@ -736,6 +781,22 @@ mod tests {
/// Process id + a counter rather than a uuid dependency: the FFI crate has no
/// business pulling one in to name a temp folder, and this is the same approach
/// the desktop's updater tests settled on.
/// A seal that can't seal: tokens are stored as they are, as on the desktop.
struct Plain;
impl TokenSeal for Plain {
fn seal_token(&self, _token: String) -> Option<String> {
None
}
fn open_token(&self, _sealed: String) -> Option<String> {
None
}
}
fn plain() -> Arc<dyn TokenSeal> {
Arc::new(Plain)
}
fn scratch_dir() -> String {
use std::sync::atomic::{AtomicU32, Ordering};
static NEXT: AtomicU32 = AtomicU32::new(0);
@@ -761,7 +822,7 @@ mod tests {
#[test]
fn creates_a_store_and_round_trips_a_note() {
let dir = scratch_dir();
let app = Inkwell::new(dir.clone()).expect("a fresh data dir should open");
let app = Inkwell::new(dir.clone(), plain()).expect("a fresh data dir should open");
let created = app
.create_note(draft("Groceries\nmilk"))
@@ -783,7 +844,7 @@ mod tests {
#[test]
fn a_note_is_named_by_its_first_line() {
let dir = scratch_dir();
let app = Inkwell::new(dir.clone()).expect("a fresh data dir should open");
let app = Inkwell::new(dir.clone(), plain()).expect("a fresh data dir should open");
let created = app
.create_note(draft("just a thought"))
@@ -798,7 +859,7 @@ mod tests {
#[test]
fn a_note_with_only_items_is_named_by_its_first_item() {
let dir = scratch_dir();
let app = Inkwell::new(dir.clone()).expect("a fresh data dir should open");
let app = Inkwell::new(dir.clone(), plain()).expect("a fresh data dir should open");
let created = app
.create_note(NoteDraft {
@@ -817,7 +878,7 @@ mod tests {
#[test]
fn syncing_unlinked_reports_not_linked() {
let dir = scratch_dir();
let app = Inkwell::new(dir.clone()).expect("a fresh data dir should open");
let app = Inkwell::new(dir.clone(), plain()).expect("a fresh data dir should open");
let status = app.sync_status().expect("status should read");
assert!(!status.linked);
@@ -833,7 +894,7 @@ mod tests {
#[test]
fn ticking_an_item_rewrites_only_its_box() {
let dir = scratch_dir();
let app = Inkwell::new(dir.clone()).expect("a fresh data dir should open");
let app = Inkwell::new(dir.clone(), plain()).expect("a fresh data dir should open");
let note = app
.create_note(NoteDraft {
body: "Packing".to_string(),
@@ -865,7 +926,7 @@ mod tests {
#[test]
fn setting_labels_leaves_tag_derived_ones_alone() {
let dir = scratch_dir();
let app = Inkwell::new(dir.clone()).expect("a fresh data dir should open");
let app = Inkwell::new(dir.clone(), plain()).expect("a fresh data dir should open");
let note = app
.create_note(draft("Trip\nbook the ferry #travel"))
@@ -906,7 +967,7 @@ mod tests {
#[test]
fn deleting_forever_removes_the_note() {
let dir = scratch_dir();
let app = Inkwell::new(dir.clone()).expect("a fresh data dir should open");
let app = Inkwell::new(dir.clone(), plain()).expect("a fresh data dir should open");
let note = app.create_note(draft("Ephemeral\nbody")).expect("create");
app.delete_note_forever(note.id.clone())
@@ -924,7 +985,7 @@ mod tests {
#[test]
fn an_attached_file_is_stored_found_and_removable() {
let dir = scratch_dir();
let app = Inkwell::new(dir.clone()).expect("a fresh data dir should open");
let app = Inkwell::new(dir.clone(), plain()).expect("a fresh data dir should open");
let note = app.create_note(draft("Receipt")).expect("create");
let attached = app
@@ -973,7 +1034,7 @@ mod tests {
#[test]
fn reminders_can_be_snoozed_and_completed() {
let dir = scratch_dir();
let app = Inkwell::new(dir.clone()).expect("a fresh data dir should open");
let app = Inkwell::new(dir.clone(), plain()).expect("a fresh data dir should open");
let note = app.create_note(draft("Call back")).expect("create");
assert_eq!(note.remind_at, None);
@@ -999,7 +1060,7 @@ mod tests {
#[test]
fn completing_a_recurring_reminder_moves_it_rather_than_ending_it() {
let dir = scratch_dir();
let app = Inkwell::new(dir.clone()).expect("a fresh data dir should open");
let app = Inkwell::new(dir.clone(), plain()).expect("a fresh data dir should open");
let note = app.create_note(draft("Water the plants")).expect("create");
let armed = app
@@ -1061,7 +1122,7 @@ mod tests {
#[test]
fn renaming_onto_an_existing_tag_merges_into_the_older_one() {
let dir = scratch_dir();
let app = Inkwell::new(dir.clone()).expect("a fresh data dir should open");
let app = Inkwell::new(dir.clone(), plain()).expect("a fresh data dir should open");
let older = app.create_label("grocery".to_string()).expect("older");
// `created_at` is RFC3339 to the MILLISECOND. Without a gap the two rows can
@@ -1106,7 +1167,7 @@ mod tests {
#[test]
fn the_rename_merge_survivor_does_not_depend_on_the_direction() {
let dir = scratch_dir();
let app = Inkwell::new(dir.clone()).expect("a fresh data dir should open");
let app = Inkwell::new(dir.clone(), plain()).expect("a fresh data dir should open");
let older = app.create_label("grocery".to_string()).expect("older");
std::thread::sleep(std::time::Duration::from_millis(5));