2 Commits
Author SHA1 Message Date
bvandeusenandClaude Opus 5.5 8592b83538 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>
2026-10-08 10:23:22 -04:00
bvandeusenandClaude Opus 5.5 bb591871a4 Account page: change your password, or sign out everywhere else
Family idea #5105, practice 4. Either action signs the account out of every
other browser and unlinks every device. The browser that made the change stays
signed in.

- POST /api/auth/password needs the current password. A wrong one returns 403,
  not 401, so this browser doesn't read as signed out, and it counts against the
  sign-in throttle. A short new password returns 400.
- POST /api/auth/sign-out-elsewhere does the same sign-out without a password
  change. Called from a device, it keeps that device linked.
- _sign_out_elsewhere moves session_epoch on and deletes device tokens. The
  reset route now uses it too, keeping no device.
- The page is renamed from "Linked devices" to "Account", in the router title
  and both nav entries. Its sections are Linked devices, Password (one short
  line, then the form) and Sessions (a single "Sign out everywhere else" row in
  the device rows' style), per preference 188: one line each, no paragraphs.
- docs/public-hosting.md says how sessions end, and why a browser session isn't
  listed the way a device is: it is a signed cookie, ended by moving the epoch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:22:16 -04:00
16 changed files with 669 additions and 40 deletions
+8
View File
@@ -90,6 +90,14 @@
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!--
allowBackup stays true, which family idea #5105 (practice 12) says to turn
off. Inkwell is local-first, so an unlinked phone's notes exist only on the
phone, and Android's backup is their one other copy. The device token is what
the practice protects, and it is stored sealed under a Keystore key that never
leaves the phone (KeystoreTokenSeal.kt). A backup therefore carries the notes
and a token nothing can open, and a restored app asks to sign in again.
-->
<application
android:name=".InkwellApplication"
android:allowBackup="true"
@@ -40,7 +40,7 @@ class InkwellApplication : Application() {
setClientAgent("inkwell-android", installedVersionName() ?: "unknown")
try {
val handle = Inkwell(filesDir.absolutePath)
val handle = Inkwell(filesDir.absolutePath, KeystoreTokenSeal())
core = handle
Log.i(TAG, "local store ready — ${handle.summary()}")
} catch (e: Exception) {
@@ -0,0 +1,98 @@
package com.fabledsword.inkwell
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Log
import com.fabledsword.inkwell.core.TokenSeal
import java.security.KeyStore
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/**
* Keeps the device token sealed under a key in the Android Keystore (family idea
* #5105, practice 12). The core stores what this returns, never the token itself.
*
* The key never leaves this phone, so a copy of the app's files yields a token
* nothing can open. That includes Android's backup, which stays on: an unlinked
* phone's notes exist only here, and a backup is their one other copy. Restored
* onto another phone, the notes come back and the app asks to sign in again.
*
* Both methods answer null rather than throw, because an exception crossing into
* the core would be a panic there. The core reads null from [sealToken] as "store
* it as is for now" and from [openToken] as "sign in again".
*
* Shaped after Minstrel's KeystoreSessionVault (Scribe snippet #5025).
*/
class KeystoreTokenSeal : TokenSeal {
override fun sealToken(token: String): String? =
runCatching { SealedBox.seal(key(), token) }
.onFailure { Log.w(TAG, "couldn't seal the device token", it) }
.getOrNull()
override fun openToken(sealed: String): String? =
runCatching { SealedBox.open(key(), sealed) }
.onFailure { Log.w(TAG, "the device token won't open on this phone", it) }
.getOrNull()
private fun key(): SecretKey {
val store = KeyStore.getInstance(KEYSTORE).apply { load(null) }
(store.getKey(ALIAS, null) as? SecretKey)?.let { return it }
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE)
generator.init(
KeyGenParameterSpec
.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(KEY_BITS)
.build(),
)
return generator.generateKey()
}
private companion object {
const val TAG = "Inkwell"
const val KEYSTORE = "AndroidKeyStore"
const val ALIAS = "inkwell-device-token"
const val KEY_BITS = 256
}
}
/**
* AES-GCM with a fresh IV per seal, the IV stored in front of the ciphertext. Split
* from the Keystore so it can be tested on the JVM with an ordinary key.
*/
internal object SealedBox {
private const val TRANSFORMATION = "AES/GCM/NoPadding"
private const val TAG_BITS = 128
private const val IV_BYTES = 12
// Binds a sealed value to what it is, so it can't be passed off as another secret.
private val AAD = "inkwell-device-token-v1".toByteArray(Charsets.UTF_8)
fun seal(
key: SecretKey,
plaintext: String,
): String {
val cipher = Cipher.getInstance(TRANSFORMATION)
// The provider picks a random IV; the Keystore refuses a caller-chosen one.
cipher.init(Cipher.ENCRYPT_MODE, key)
cipher.updateAAD(AAD)
val sealed = cipher.iv + cipher.doFinal(plaintext.toByteArray(Charsets.UTF_8))
return Base64.getEncoder().encodeToString(sealed)
}
fun open(
key: SecretKey,
sealed: String,
): String {
val bytes = Base64.getDecoder().decode(sealed)
require(bytes.size > IV_BYTES) { "sealed value too short" }
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, bytes, 0, IV_BYTES))
cipher.updateAAD(AAD)
return String(cipher.doFinal(bytes, IV_BYTES, bytes.size - IV_BYTES), Charsets.UTF_8)
}
}
@@ -0,0 +1,38 @@
package com.fabledsword.inkwell
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertThrows
import org.junit.Test
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
class SealedBoxTest {
private fun aesKey(): SecretKey = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey()
@Test
fun `a sealed token opens with the key that sealed it`() {
val key = aesKey()
val sealed = SealedBox.seal(key, "tok-1")
assertNotEquals("tok-1", sealed)
assertEquals("tok-1", SealedBox.open(key, sealed))
}
@Test
fun `sealing twice gives two different values`() {
// A fresh IV each time, so equal tokens can't be spotted in the file.
val key = aesKey()
assertNotEquals(SealedBox.seal(key, "tok-1"), SealedBox.seal(key, "tok-1"))
}
@Test
fun `another key can't open it, as on a phone the backup was restored to`() {
val sealed = SealedBox.seal(aesKey(), "tok-1")
assertThrows(Exception::class.java) { SealedBox.open(aesKey(), sealed) }
}
@Test
fun `a value that was never sealed is refused`() {
assertThrows(Exception::class.java) { SealedBox.open(aesKey(), "dG9vIHNob3J0") }
}
}
+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));
+144
View File
@@ -8,6 +8,10 @@
//! the `keyring` crate needs libsecret/DBus on Linux, which adds a C dependency to a
//! binary that has to cross-compile, and fails outright on headless or minimal-WM
//! setups. Protecting the database file is the portable trade.
//!
//! A client that has somewhere better to keep a key passes a [`TokenSeal`], and the
//! token is stored sealed. Android does, with a key in the Keystore (family idea
//! #5105, practice 12); the desktop does not.
use rusqlite::{params, Connection};
use serde::Serialize;
@@ -107,6 +111,79 @@ pub fn set_link(conn: &Connection, server_url: &str, device_token: &str) -> rusq
Ok(())
}
/// Seals the device token for storage, and opens it again.
///
/// Neither method fails loudly: a client's key store can be briefly unavailable, and
/// a token sealed on another device can never be opened here. `None` says so, and
/// [`set_sealed_link`] and [`open_token`] decide what happens next.
pub trait TokenSeal {
/// The token sealed for storage, or None when that isn't possible right now.
fn seal(&self, token: &str) -> Option<String>;
/// The sealed token opened, or None when this device can't open it.
fn open(&self, sealed: &str) -> Option<String>;
}
/// Marks a stored token as sealed. A device token is URL-safe base64, which has no
/// colon, so a plain one can't be mistaken for a sealed one.
const SEALED: &str = "sealed:";
/// [`set_link`] for a client that seals its token.
///
/// When sealing fails, the token is stored as it is and [`open_token`] seals it on
/// its next read. Refusing the link instead would leave someone unable to sync
/// over a passing key-store error.
pub fn set_sealed_link(
conn: &Connection,
server_url: &str,
device_token: &str,
seal: &dyn TokenSeal,
) -> rusqlite::Result<()> {
let stored = match seal.seal(device_token) {
Some(sealed) => format!("{SEALED}{sealed}"),
None => {
log::warn!("couldn't seal the device token; it is stored as is until the next read");
device_token.to_string()
}
};
set_link(conn, server_url, &stored)
}
/// The device token the server expects, from the `stored` one.
///
/// - A sealed token is opened. If it won't open, it is dropped, so the app reads as
/// unlinked and asks to sign in again. That is what happens when Android restores
/// the app's files onto another phone, whose Keystore never held the key. The
/// server address and cursor stay, for the sign-in form and the same server.
/// - A plain token, stored before tokens were sealed or when sealing failed, is
/// sealed in place and returned.
pub fn open_token(
conn: &Connection,
stored: &str,
seal: &dyn TokenSeal,
) -> rusqlite::Result<Option<String>> {
if let Some(sealed) = stored.strip_prefix(SEALED) {
let token = seal.open(sealed);
if token.is_none() {
log::warn!("the stored device token won't open on this device; sign in again");
store_token(conn, None)?;
}
return Ok(token);
}
if let Some(sealed) = seal.seal(stored) {
store_token(conn, Some(&format!("{SEALED}{sealed}")))?;
}
Ok(Some(stored.to_string()))
}
/// Replace the stored token alone, leaving the server and cursor as they are.
fn store_token(conn: &Connection, token: Option<&str>) -> rusqlite::Result<()> {
conn.execute(
"UPDATE sync_state SET device_token = ?1 WHERE id = 1",
params![token],
)?;
Ok(())
}
/// Drop the notes other people shared with the account this device was linked to.
/// They were only ever here through that link: kept after it ends, they would sit
/// on the board as notes nobody here can edit and nothing would ever update.
@@ -240,6 +317,73 @@ mod tests {
assert_eq!(state.device_token.as_deref(), Some("tok-1"));
}
/// Reverses the token: enough to tell sealed from plain. `broken` stands in for a
/// key store that is unavailable, or a key this device never held.
struct Reverse {
broken: bool,
}
impl TokenSeal for Reverse {
fn seal(&self, token: &str) -> Option<String> {
(!self.broken).then(|| token.chars().rev().collect())
}
fn open(&self, sealed: &str) -> Option<String> {
(!self.broken).then(|| sealed.chars().rev().collect())
}
}
const WORKING: Reverse = Reverse { broken: false };
const BROKEN: Reverse = Reverse { broken: true };
fn stored_token(conn: &Connection) -> Option<String> {
read(conn).expect("read").device_token
}
#[test]
fn a_sealed_token_is_stored_sealed_and_opens() {
let conn = db();
set_sealed_link(&conn, "https://notes.example.com", "tok-1", &WORKING).expect("link");
assert_eq!(stored_token(&conn).as_deref(), Some("sealed:1-kot"));
let opened = open_token(&conn, "sealed:1-kot", &WORKING).expect("open");
assert_eq!(opened.as_deref(), Some("tok-1"));
}
#[test]
fn a_plain_token_is_sealed_on_its_next_read() {
let conn = db();
set_link(&conn, "https://notes.example.com", "tok-1").expect("link");
let opened = open_token(&conn, "tok-1", &WORKING).expect("open");
assert_eq!(opened.as_deref(), Some("tok-1"));
assert_eq!(stored_token(&conn).as_deref(), Some("sealed:1-kot"));
}
#[test]
fn a_token_that_cant_be_sealed_is_kept_plain_and_still_works() {
let conn = db();
set_sealed_link(&conn, "https://notes.example.com", "tok-1", &BROKEN).expect("link");
assert_eq!(stored_token(&conn).as_deref(), Some("tok-1"));
let opened = open_token(&conn, "tok-1", &BROKEN).expect("open");
assert_eq!(opened.as_deref(), Some("tok-1"));
}
#[test]
fn a_token_that_wont_open_here_is_dropped_but_the_server_is_kept() {
let conn = db();
set_sealed_link(&conn, "https://notes.example.com", "tok-1", &WORKING).expect("link");
let opened = open_token(&conn, "sealed:1-kot", &BROKEN).expect("open");
assert_eq!(opened, None);
let state = read(&conn).expect("read");
assert!(!state.is_linked());
assert_eq!(state.device_token, None);
assert_eq!(
state.server_url.as_deref(),
Some("https://notes.example.com")
);
}
#[test]
fn an_unlinked_device_uses_its_own_retention_window() {
let conn = db();
+6
View File
@@ -113,6 +113,12 @@ docker run --rm -v inkwell-data:/d -v "$PWD":/out alpine tar czf /out/media.tgz
on a note shared with you can't run script in your session.
- **Session cookies are `HttpOnly` and `SameSite=Lax`**, which is also what stands in
for CSRF protection: a `Lax` cookie is not sent on a cross-site POST.
- **Sessions can be ended from the Account page.** Changing your password there needs
the current one. It signs you out of every other browser and unlinks every app,
and you stay signed in where you made the change. **Sign out everywhere else**
does the same without changing the password. A browser session doesn't appear in
a list the way a linked app does: it is a signed cookie in that browser, ended by
moving the account on rather than by deleting a row.
## Email and forgotten passwords
+2
View File
@@ -29,6 +29,8 @@ export const local: Repo = {
login: () => Promise.reject(new Error("You're offline — there's no account to sign in to.")),
register: () => Promise.reject(new Error("You're offline — accounts are created on a server.")),
logout: () => Promise.resolve(),
changePassword: () => Promise.reject(new Error(NEEDS_SERVER)),
signOutElsewhere: () => Promise.reject(new Error(NEEDS_SERVER)),
},
devices: {
+9
View File
@@ -105,6 +105,15 @@ export interface AuthRepo {
* while registration is closed. */
register(email: string, password: string, displayName: string, invite?: string): Promise<User>;
logout(): Promise<void>;
/** Signs the account out of every other browser and unlinks every device; this
* browser stays signed in. Rejects with a 403 when `current` is wrong. */
changePassword(current: string, next: string): Promise<SignedOutElsewhere>;
/** The same sign-out as `changePassword`, without changing the password. */
signOutElsewhere(): Promise<SignedOutElsewhere>;
}
export interface SignedOutElsewhere {
devices_unlinked: number;
}
export interface DevicesRepo {
+4
View File
@@ -22,6 +22,7 @@ import type {
ChecklistItemChanges,
Repo,
ServerSetting,
SignedOutElsewhere,
} from "./repo";
// Render a board query to the GET /api/notes query string. Mirrors the param
@@ -58,6 +59,9 @@ export const rest: Repo = {
register: (email, password, displayName, invite) =>
api.post<User>("/api/auth/register", { email, password, display_name: displayName, invite }),
logout: () => api.post<void>("/api/auth/logout"),
changePassword: (current, next) =>
api.post<SignedOutElsewhere>("/api/auth/password", { current_password: current, new_password: next }),
signOutElsewhere: () => api.post<SignedOutElsewhere>("/api/auth/sign-out-elsewhere"),
},
devices: {
+3 -3
View File
@@ -346,8 +346,8 @@ async function signOut() {
v-if="!desktopApp"
to="/account"
class="icon-btn hidden sm:inline-flex"
title="Linked devices"
aria-label="Linked devices"
title="Account"
aria-label="Account"
>
<Icon name="device" />
</RouterLink>
@@ -458,7 +458,7 @@ async function signOut() {
>
<p class="truncate px-3 pb-1 text-xs text-neutral-400">{{ session.user?.display_name }}</p>
<RouterLink to="/account" class="nav-link" exact-active-class="nav-link-active">
<Icon name="device" /> Linked devices
<Icon name="device" /> Account
</RouterLink>
<RouterLink
v-if="session.user?.is_admin"
+3 -2
View File
@@ -48,7 +48,8 @@ const router = createRouter({
meta: { title: "Sync", requiresAuth: true, requiresDesktop: true },
},
{
// Per-user account: linked devices (native-client sync tokens). Any user.
// Per-user account: linked devices (native-client sync tokens), the password,
// and signing out everywhere else. Any user.
//
// The mirror of `requiresDesktop` above: this one needs a SERVER. The desktop
// is itself one of the devices this page lists, so offline the list is always
@@ -58,7 +59,7 @@ const router = createRouter({
path: "/account",
name: "account",
component: () => import("../views/AccountView.vue"),
meta: { title: "Linked devices", requiresAuth: true, requiresServer: true },
meta: { title: "Account", requiresAuth: true, requiresServer: true },
},
{
path: "/login",
+11 -1
View File
@@ -37,5 +37,15 @@ export const useSessionStore = defineStore("session", () => {
user.value = null;
}
return { user, loaded, fetchMe, login, register, logout };
// Both end every other session and unlink every device, and keep this one: the
// signed-in user doesn't change. Each resolves to how many devices were unlinked.
async function changePassword(current: string, next: string): Promise<number> {
return (await repo.auth.changePassword(current, next)).devices_unlinked;
}
async function signOutElsewhere(): Promise<number> {
return (await repo.auth.signOutElsewhere()).devices_unlinked;
}
return { user, loaded, fetchMe, login, register, logout, changePassword, signOutElsewhere };
});
+90 -3
View File
@@ -2,6 +2,7 @@
import { onMounted, ref } from "vue";
import { useConfigStore } from "../stores/config";
import { useDevicesStore } from "../stores/devices";
import { useSessionStore } from "../stores/session";
import { useUiStore } from "../stores/ui";
import BaseButton from "../components/BaseButton.vue";
import BaseInput from "../components/BaseInput.vue";
@@ -11,9 +12,11 @@ import PageHeader from "../components/PageHeader.vue";
import { errorMessage } from "../api/errors";
import { formatDateTime } from "../notes/datetime";
// Per-user (not admin) management of linked native clients — the Tauri desktop and
// Android apps authenticate sync with a device bearer token issued here.
// The signed-in person's own account (not admin): the native clients linked to it
// (the desktop and Android apps sync with a device bearer token issued here), its
// password, and signing out everywhere else (family idea #5105, practice 4).
const devices = useDevicesStore();
const session = useSessionStore();
const ui = useUiStore();
// Loaded here rather than in ClientDownloads: this view already awaits it, and a
// component that fetches its own config would race the one that does.
@@ -68,6 +71,50 @@ async function revoke(id: string, name: string) {
}
}
const currentPassword = ref("");
const newPassword = ref("");
const changing = ref(false);
const passwordError = ref("");
const signingOut = ref(false);
function unlinkedNote(n: number): string {
if (n === 0) return "";
return n === 1 ? " 1 device was unlinked." : ` ${n} devices were unlinked.`;
}
async function changePassword() {
changing.value = true;
passwordError.value = "";
try {
const unlinked = await session.changePassword(currentPassword.value, newPassword.value);
currentPassword.value = "";
newPassword.value = "";
ui.showToast(`Password changed. You're signed out everywhere else.${unlinkedNote(unlinked)}`);
await devices.load();
} catch (e) {
passwordError.value = errorMessage(e, "Couldn't change your password.");
} finally {
changing.value = false;
}
}
async function signOutElsewhere() {
const ok = window.confirm(
"Sign out of every other browser and unlink every device? Each app will need to sign in again.",
);
if (!ok) return;
signingOut.value = true;
try {
const unlinked = await session.signOutElsewhere();
ui.showToast(`Signed out everywhere else.${unlinkedNote(unlinked)}`);
await devices.load();
} catch (e) {
ui.showToast(errorMessage(e, "Couldn't sign out everywhere else."));
} finally {
signingOut.value = false;
}
}
onMounted(() => {
void load();
});
@@ -75,8 +122,9 @@ onMounted(() => {
<template>
<div class="mx-auto min-h-full max-w-2xl px-4 py-8">
<PageHeader title="Linked devices" />
<PageHeader title="Account" />
<h2 class="mb-2 text-xs font-semibold uppercase tracking-wide text-neutral-400">Linked devices</h2>
<p class="mb-6 max-w-xl text-sm text-neutral-500 dark:text-neutral-400">
Link the Inkwell desktop or mobile app to sync your notes. Create a device token here, then
paste it into the app when it asks to connect. You can revoke a device at any time.
@@ -164,5 +212,44 @@ onMounted(() => {
</button>
</li>
</ul>
<h2 class="mb-2 mt-10 text-xs font-semibold uppercase tracking-wide text-neutral-400">Password</h2>
<p class="mb-4 text-sm text-neutral-500 dark:text-neutral-400">Changing it signs you out everywhere else.</p>
<form class="flex max-w-sm flex-col gap-3" @submit.prevent="changePassword">
<BaseInput
id="current-password"
v-model="currentPassword"
type="password"
label="Current password"
autocomplete="current-password"
required
/>
<BaseInput
id="new-password"
v-model="newPassword"
type="password"
label="New password"
autocomplete="new-password"
placeholder="At least 8 characters"
:error="passwordError"
required
/>
<div>
<BaseButton type="submit" :loading="changing">Change password</BaseButton>
</div>
</form>
<h2 class="mb-2 mt-10 text-xs font-semibold uppercase tracking-wide text-neutral-400">Sessions</h2>
<div
class="flex items-center justify-between gap-4 rounded-xl border border-neutral-200 px-4 py-3 dark:border-neutral-800"
>
<div class="min-w-0">
<p class="text-sm font-medium text-neutral-800 dark:text-neutral-100">Sign out everywhere else</p>
<p class="text-xs text-neutral-400">Every other browser, and every linked device</p>
</div>
<BaseButton variant="ghost" class="shrink-0" :loading="signingOut" @click="signOutElsewhere">
Sign out
</BaseButton>
</div>
</div>
</template>
+79 -4
View File
@@ -424,10 +424,7 @@ async def reset_password():
return json_error(INVALID_RESET, 403)
user = await db.get(User, user_id)
user.password_hash = hash_password(password)
user.session_epoch = User.session_epoch + 1
unlinked = (await db.execute(delete(DeviceToken).where(DeviceToken.user_id == user_id))).rowcount
await db.commit()
await db.refresh(user)
unlinked = await _sign_out_elsewhere(db, user, keep_token=None)
_sign_in(user)
logger.info(
"password reset email=%s devices_unlinked=%s from=%s", user.email, unlinked, client_address()
@@ -435,6 +432,84 @@ async def reset_password():
return jsonify(_serialize_user(user))
async def _sign_out_elsewhere(db, user: User, keep_token: str | None) -> int:
"""End the account's sessions, and commit. Returns how many devices were unlinked.
Web sessions end because the account's epoch moves on: they are signed cookies
in other browsers, out of reach. Linked devices are deleted, except the one
holding `keep_token`, when the request came from a device. The caller signs
this browser in again under the new epoch, if it should stay signed in.
"""
user.session_epoch = User.session_epoch + 1
unlink = delete(DeviceToken).where(DeviceToken.user_id == user.id)
if keep_token:
unlink = unlink.where(DeviceToken.token_hash != hash_token(keep_token))
unlinked = (await db.execute(unlink)).rowcount
await db.commit()
await db.refresh(user)
return unlinked
def _stay_signed_in(user: User) -> None:
"""Keep the browser making this request signed in after `_sign_out_elsewhere`. A
device has no session to keep, and isn't given one."""
if _session_user_id() is not None:
_sign_in(user)
@bp.post("/password")
@login_required
async def change_password():
"""Change the account's password, and sign it out everywhere else: every other
web session, and every linked device (family idea #5105, practice 4). The
browser that changed it stays signed in.
The current password is required, so a session left open on someone else's
screen can't take the account over. A wrong one counts against the sign-in
budget, the same as a failed sign-in.
"""
data = await request.get_json(silent=True) or {}
current = data.get("current_password") or ""
password = data.get("new_password") or ""
if len(password) < MIN_PASSWORD_LEN:
return json_error(f"password must be at least {MIN_PASSWORD_LEN} characters", 400)
async with session_scope() as db:
user = await db.get(User, g.user_id)
if user is None:
return json_error("authentication required", 401)
wait = _sign_in_block(user.email)
if wait is not None:
return _throttled(wait)
# 403, not 401: the caller IS signed in, and a 401 would read as "you were
# signed out" to anything that acts on it.
if not user.password_hash or not verify_password(current, user.password_hash):
_sign_in_failed(user.email)
logger.warning("password change refused (wrong password) email=%s from=%s", user.email, client_address())
return json_error("your current password isn't right", 403)
user.password_hash = hash_password(password)
unlinked = await _sign_out_elsewhere(db, user, keep_token=_bearer_token())
_stay_signed_in(user)
logger.info("password changed email=%s devices_unlinked=%s from=%s", user.email, unlinked, client_address())
return jsonify({"ok": True, "devices_unlinked": unlinked})
@bp.post("/sign-out-elsewhere")
@login_required
async def sign_out_elsewhere():
"""Sign the account out of every other browser and unlink every device, keeping
this one signed in (family idea #5105, practice 4). For a session or a device
the person doesn't recognise, or one on a machine they no longer have."""
async with session_scope() as db:
user = await db.get(User, g.user_id)
if user is None:
return json_error("authentication required", 401)
unlinked = await _sign_out_elsewhere(db, user, keep_token=_bearer_token())
_stay_signed_in(user)
logger.info("signed out elsewhere email=%s devices_unlinked=%s from=%s", user.email, unlinked, client_address())
return jsonify({"ok": True, "devices_unlinked": unlinked})
# --- Device (bearer) tokens for native clients — M8 sync hub ---
+86
View File
@@ -1200,6 +1200,92 @@ async def test_a_short_password_leaves_the_reset_link_usable(app_client, db):
assert ok.status_code == 200
# --- Changing a password, and signing out everywhere else (#5105, practice 4) ---
async def _elsewhere(app_client):
"""The owner signed in on `app_client`, a second browser of theirs, and a linked
device. Returns the second browser and the device's bearer header."""
await app_client.post("/api/auth/register", json={"email": "owner@example.test", "password": _PASSWORD})
other = create_app().test_client()
signed = await other.post("/api/auth/login", json={"email": "owner@example.test", "password": _PASSWORD})
assert signed.status_code == 200
device = await app_client.post("/api/auth/devices", json={"name": "Phone"})
return other, {"Authorization": f"Bearer {(await device.get_json())['token']}"}
async def _me(client, headers=None) -> int:
return (await client.get("/api/auth/me", headers=headers or {})).status_code
async def test_changing_the_password_signs_out_everywhere_but_here(app_client, db):
other, bearer = await _elsewhere(app_client)
resp = await app_client.post(
"/api/auth/password", json={"current_password": _PASSWORD, "new_password": "a-brand-new-password"}
)
assert resp.status_code == 200, await resp.get_data(as_text=True)
assert (await resp.get_json())["devices_unlinked"] == 1
# This browser stays signed in; the other one and the device are out.
assert await _me(app_client) == 200
assert await _me(other) == 401
assert await _me(create_app().test_client(), bearer) == 401
fresh = create_app().test_client()
old = await fresh.post("/api/auth/login", json={"email": "owner@example.test", "password": _PASSWORD})
assert old.status_code == 401
new = await fresh.post("/api/auth/login", json={"email": "owner@example.test", "password": "a-brand-new-password"})
assert new.status_code == 200
async def test_a_wrong_current_password_changes_nothing(app_client, db):
other, bearer = await _elsewhere(app_client)
wrong = await app_client.post(
"/api/auth/password", json={"current_password": "not-the-password", "new_password": "a-brand-new-password"}
)
# 403, not 401: this browser is still signed in, and must not read as signed out.
assert wrong.status_code == 403
short = await app_client.post("/api/auth/password", json={"current_password": _PASSWORD, "new_password": "short"})
assert short.status_code == 400
assert await _me(app_client) == 200
assert await _me(other) == 200
assert await _me(create_app().test_client(), bearer) == 200
signed = await create_app().test_client().post(
"/api/auth/login", json={"email": "owner@example.test", "password": _PASSWORD}
)
assert signed.status_code == 200
async def test_sign_out_elsewhere_keeps_this_browser_and_the_password(app_client, db):
other, bearer = await _elsewhere(app_client)
resp = await app_client.post("/api/auth/sign-out-elsewhere")
assert resp.status_code == 200
assert (await resp.get_json())["devices_unlinked"] == 1
assert await _me(app_client) == 200
assert await _me(other) == 401
assert await _me(create_app().test_client(), bearer) == 401
signed = await create_app().test_client().post(
"/api/auth/login", json={"email": "owner@example.test", "password": _PASSWORD}
)
assert signed.status_code == 200
async def test_sign_out_elsewhere_from_a_device_keeps_that_device(app_client, db):
other, bearer = await _elsewhere(app_client)
second = await app_client.post("/api/auth/devices", json={"name": "Laptop"})
laptop = {"Authorization": f"Bearer {(await second.get_json())['token']}"}
resp = await create_app().test_client().post("/api/auth/sign-out-elsewhere", headers=bearer)
assert resp.status_code == 200
assert (await resp.get_json())["devices_unlinked"] == 1
assert await _me(create_app().test_client(), bearer) == 200
assert await _me(create_app().test_client(), laptop) == 401
assert await _me(app_client) == 401
assert await _me(other) == 401
async def test_revoking_this_device_from_a_web_session_is_a_bad_request(app_client, db):
"""A session-cookie caller holds no device token, so "revoke the one I'm using"
has nothing to name. Moved here from the unit lane when the session check began