Modern Apps git

← Modern-Apps.git

various fixes

Commit
1a49dda204cd49d1935c168add8695ea56b32201
Author
vayun-mathur <[email protected]>
When
2026-09-08 04:46 UTC (2 months ago)
Parents
cd22504

Diff

clock/src/main/java/com/vayunmathur/clock/platform/ClockUiContract.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/ClockUiContract.kt b/clock/src/main/java/com/vayunmathur/clock/platform/ClockUiContract.ktindex f98ebd519e..b9950c4d1d 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/ClockUiContract.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/ClockUiContract.kt@@ -51,7 +51,12 @@ data class WorldClock(val city: String, val zone: TimeZone)  /** Everything the clock tab draws. */ data class ClockUiState(-    val now: Instant,+    /**+     * The current instant, as a getter so the tick is read inside the header and the individual+     * world-clock rows rather than in the screen's own scope. Read high, a tick invalidates the+     * whole screen and re-composes every visible row; the rows only render minutes.+     */+    val now: () -> Instant,     val zone: TimeZone,     val is24Hour: Boolean = false,     val worldClocks: List<WorldClock> = emptyList(),@@ -59,7 +64,8 @@ data class ClockUiState(  /** Everything the timer tab draws. */ data class TimerUiState(-    val now: Instant,+    /** See [ClockUiState.now]. Read inside each timer's own row. */+    val now: () -> Instant,     val timers: List<Timer> = emptyList(), ) 
clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.kt b/clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.ktindex 65a574fbeb..c9c9a234fc 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/ClockViewModel.kt@@ -121,10 +121,16 @@ class ClockViewModel(     }      /**-     * Current wall-clock time, updated every 100ms. Pauses when no screen-     * collects (via [SharingStarted.WhileSubscribed]).+     * Wall-clock time at [TICK_MS], for the stopwatch only. Pauses when nothing collects.+     *+     * Private on purpose. This is 100ms because the stopwatch renders centiseconds, and it used to+     * be shared with the clock and timer tabs - which show seconds and minutes, and so recomposed+     * ten times a second to redraw a label that changes once a second, or once a minute. Screens+     * that need a displayable clock should use `rememberClock` from `:library:ui`, which lets them+     * pick their own period and hands back a getter so the tick reaches only the labels that show+     * it.      */-    val now: StateFlow<Instant> = tick.stateIn(+    private val now: StateFlow<Instant> = tick.stateIn(         viewModelScope,         SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS),         Clock.System.now(),
clock/src/main/java/com/vayunmathur/clock/ui/ClockPage.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/ClockPage.kt b/clock/src/main/java/com/vayunmathur/clock/ui/ClockPage.ktindex 5e4bfbd3ce..672ff6e1da 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/ClockPage.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/ClockPage.kt@@ -4,6 +4,7 @@ import android.text.format.DateFormat import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.platform.LocalContext import com.vayunmathur.clock.Route@@ -13,15 +14,21 @@ import com.vayunmathur.clock.platform.WorldClock import com.vayunmathur.clock.platform.WorldClockCities import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.ui.rememberClock import kotlinx.coroutines.launch import kotlinx.datetime.TimeZone+import kotlin.time.Instant  /** Binds [ClockViewModel] to the stateless [ClockScreen]. */ @Composable fun ClockPage(backStack: NavBackStack<Route>, ds: DataStoreUtils, clockViewModel: ClockViewModel) {     val context = LocalContext.current     val scope = rememberCoroutineScope()-    val now by clockViewModel.now.collectAsState()+    // The clock tab shows seconds in the header and minutes in the rows, so it ticks once a+    // second - not on the ViewModel's 100ms stopwatch flow, which this used to share. A getter+    // rather than a value so the tick reaches only the labels that display it.+    val clock = rememberClock()+    val now = remember(clock) { { Instant.fromEpochMilliseconds(clock()) } }     val cities by clockViewModel.cities.collectAsState()     val selectedCities by WorldClockCities.flow(ds).collectAsState(listOf()) 
clock/src/main/java/com/vayunmathur/clock/ui/ClockScreen.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/ClockScreen.kt b/clock/src/main/java/com/vayunmathur/clock/ui/ClockScreen.ktindex 986a1b8c7c..b4838cb124 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/ClockScreen.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/ClockScreen.kt@@ -55,7 +55,6 @@ fun ClockScreen(     state: ClockUiState,     onReorder: (List<String>) -> Unit = {}, ) {-    val time = state.now.toLocalDateTime(state.zone)     val haptics = LocalHapticFeedback.current     val listState = rememberLazyListState()     var localClocks by remember { mutableStateOf(state.worldClocks) }@@ -86,6 +85,7 @@ fun ClockScreen(     }, state = listState, verticalArrangement = Arrangement.spacedBy(4.dp), scrollBehavior = appBarScrollBehavior()) {         item {             val is24h = state.is24Hour+            val time = state.now().toLocalDateTime(state.zone)             Row(Modifier.fillParentMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.Bottom) {                 Text(DateString.timeSecondsNumeric(time.time, is24h), style = MaterialTheme.typography.displayLarge)                 if (!is24h) {@@ -98,10 +98,11 @@ fun ClockScreen(             }         }         item {+            val time = state.now().toLocalDateTime(state.zone)             Text(DateString.dateWeekdayNoYear(time.date), Modifier.fillParentMaxWidth(), textAlign = TextAlign.Center)         }         itemsIndexed(localClocks, key = { _, worldClock -> worldClock.city }) { index, worldClock ->-            val timeHere = state.now.toLocalDateTime(worldClock.zone)+            val timeHere = state.now().toLocalDateTime(worldClock.zone)             val is24h = state.is24Hour             val amPm = if (is24h) "" else if (timeHere.time.hour >= 12) stringResource(R.string.time_pm) else stringResource(R.string.time_am)             ReorderableItem(reorderState, key = worldClock.city, modifier = Modifier.fillParentMaxWidth().animateItem()) { isDragging ->
clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.kt b/clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.ktindex 3e331f72a0..a6487f1cb5 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/TimerPage.kt@@ -12,14 +12,19 @@ import com.vayunmathur.clock.platform.ClockViewModel import com.vayunmathur.clock.platform.TimerActions import com.vayunmathur.clock.platform.TimerUiState import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.ui.rememberClock import kotlin.time.Clock import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes+import kotlin.time.Instant  /** Binds [ClockViewModel] to the stateless [TimerScreen]. */ @Composable fun TimerPage(backStack: NavBackStack<Route>, clockViewModel: ClockViewModel) {-    val now by clockViewModel.now.collectAsState()+    // Countdowns are shown to the second, so a one-second tick is enough; the ViewModel's 100ms+    // flow exists for the stopwatch's centiseconds. Read inside each timer's row, not here.+    val ticker = rememberClock()+    val now = remember(ticker) { { Instant.fromEpochMilliseconds(ticker()) } }     val timers by clockViewModel.timers.collectAsState()     val context = LocalContext.current 
clock/src/main/java/com/vayunmathur/clock/ui/TimerScreen.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/TimerScreen.kt b/clock/src/main/java/com/vayunmathur/clock/ui/TimerScreen.ktindex 5dc54fba43..0d59a64328 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/TimerScreen.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/TimerScreen.kt@@ -63,7 +63,7 @@ fun TimerScreen(                 }             }         } else {-            items(timers, key = { it.id }) { timer -> TimerCard(timer, state.now, actions) }+            items(timers, key = { it.id }) { timer -> TimerCard(timer, state.now(), actions) }         }     } }
clock/src/screenshotTest/kotlin/com/vayunmathur/clock/ui/MetadataPreviews.kt
diff --git a/clock/src/screenshotTest/kotlin/com/vayunmathur/clock/ui/MetadataPreviews.kt b/clock/src/screenshotTest/kotlin/com/vayunmathur/clock/ui/MetadataPreviews.ktindex ad7cb807f1..fa6a37436f 100644--- a/clock/src/screenshotTest/kotlin/com/vayunmathur/clock/ui/MetadataPreviews.kt+++ b/clock/src/screenshotTest/kotlin/com/vayunmathur/clock/ui/MetadataPreviews.kt@@ -86,7 +86,7 @@ class MetadataPreviews {             ClockScreen(                 backStack = rememberNavBackStack<Route>(Route.Clock),                 state = ClockUiState(-                    now = MORNING,+                    now = { MORNING },                     zone = TimeZone.of("America/Los_Angeles"),                     worldClocks = listOf(                         WorldClock("London", TimeZone.of("Europe/London")),@@ -108,7 +108,7 @@ class MetadataPreviews {                 backStack = rememberNavBackStack<Route>(Route.Timer),                 // No timers yet, which is what puts the keypad up; "1000" is the digits                 // for a ten-minute timer, mid-entry.-                state = TimerUiState(now = MORNING),+                state = TimerUiState(now = { MORNING }),                 actions = TimerActions.Noop,                 initialKeypadInput = "1000",             )
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.ktindex 20272cfea7..9fce814540 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactList.kt@@ -299,10 +299,18 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions) {         }          if (favorites.isNotEmpty()) {-            item(key = "favorites-header") {+            item(key = "favorites-header", contentType = "header") {                 FavoritesHeader(Modifier.animateItem().padding(vertical = 6.dp))             }-            itemsIndexed(favorites, key = { _, c -> "favorite-${c.id}" }) { idx, contact ->+            itemsIndexed(+                favorites,+                key = { _, c -> "favorite-${c.id}" },+                // Headers and rows are structurally different subtrees. Left untyped they all+                // share the default null content type, so the list will happily try to reuse a+                // header's slot for a contact row - the reuse then fails and the row composes+                // from scratch anyway, having wasted the attempt.+                contentType = { _, _ -> "contact" },+            ) { idx, contact ->                 GroupedContactRow(idx, favorites.size, itemMotion()) {                     ContactItem(                         contact = contact,@@ -328,10 +336,14 @@ fun ContactListScreen(state: ContactListUiState, actions: ContactsActions) {         }          groupedContacts.forEach { (letter, contactsInGroup) ->-            item(key = "letter-header-$letter") {+            item(key = "letter-header-$letter", contentType = "header") {                 LetterHeader(letter, Modifier.animateItem().padding(vertical = 6.dp))             }-            itemsIndexed(contactsInGroup, key = { _, c -> "contact-${c.id}" }) { idx, contact ->+            itemsIndexed(+                contactsInGroup,+                key = { _, c -> "contact-${c.id}" },+                contentType = { _, _ -> "contact" },+            ) { idx, contact ->                 GroupedContactRow(idx, contactsInGroup.size, itemMotion()) {                     ContactItem(                         contact = contact,@@ -563,7 +575,9 @@ fun ContactItem(         modifier     } -    val contactGroups = contactGroupsOf(contact, allGroups)+    // Remembered per (contact, group list): this filters every group and trims each name, and+    // without the remember it re-ran on every composition of every visible row while scrolling.+    val contactGroups = remember(contact, allGroups) { contactGroupsOf(contact, allGroups) }      val trimmedOrg = contact.org.company.trim()     val showOrg = trimmedOrg.isNotEmpty()
contacts/src/main/java/com/vayunmathur/contacts/util/ContactSorting.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactSorting.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactSorting.ktindex e8a39cd8da..a92b09684d 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactSorting.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactSorting.kt@@ -60,12 +60,19 @@ object ContactSorting {     /** Sort a list of contacts locale-aware. */     fun List<Contact>.sortedLocale(): List<Contact> {         val col = collator()-        return sortedWith(compareBy(col) { it.name.value })+        // Collation keys, not repeated compares. Collator.compare re-analyses both strings on+        // every comparison, so an n-element sort pays O(n log n) analyses; generating a key per+        // contact makes it O(n), and the sort itself then compares cheap byte arrays. This runs+        // on the UI thread from the contact list's grouping, on every change to the list.+        return map { it to col.getCollationKey(it.name.value) }+            .sortedWith(compareBy { it.second })+            .map { it.first }     }-     /** Sort a list of groups by name locale-aware. */     fun <T> List<T>.sortedByNameLocale(selector: (T) -> String): List<T> {         val col = collator()-        return sortedWith(compareBy(col, selector))+        return map { it to col.getCollationKey(selector(it)) }+            .sortedWith(compareBy { it.second })+            .map { it.first }     } }
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.ktindex 161889de75..0640b3248f 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt@@ -107,7 +107,13 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)             key !in hidden && c.accountName !in hidden         }         filterBySearch(filtered, query)-    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())+    }+        // viewModelScope is Main.immediate, so without this the whole address book was filtered+        // on the UI thread on every keystroke - and filterBySearch builds a fresh concatenated,+        // lowercased haystack per contact, so that is O(contacts x fields) of string allocation+        // between one frame and the next.+        .flowOn(Dispatchers.Default)+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())      // Virtual SIM account display labels: key is "type|name" -> "SIM N — Carrier"     private val _simAccountLabels = MutableStateFlow<Map<String, String>>(emptyMap())
findfamily/src/main/java/com/vayunmathur/findfamily/platform/PoweredOffBeacon.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/PoweredOffBeacon.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/PoweredOffBeacon.ktindex 0f18ea3f9a..17348fefd3 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/PoweredOffBeacon.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/PoweredOffBeacon.kt@@ -1,15 +1,27 @@+@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)+ package com.vayunmathur.findfamily.platform  import android.content.Context import android.nearby.NearbyManager import android.os.Build import android.util.Log+import com.vayunmathur.e2ee.E2eeKeyStore import com.vayunmathur.findfamily.BuildConfig import com.vayunmathur.findfamily.data.DirectBootStore import com.vayunmathur.findfamily.tracker.PoweredOffKeyStore import com.vayunmathur.findfamily.tracker.PoweredOffProtocol+import com.vayunmathur.findfamily.tracker.PoweredOffRecovery+import com.vayunmathur.findfamily.tracker.RecoveryDistribution+import com.vayunmathur.findfamily.tracker.poweredOffGrantSigningBytes import com.vayunmathur.findfamily.util.Networking+import com.vayunmathur.findfamily.uwb.PoweredOffGrant+import com.vayunmathur.findfamily.uwb.UwbEnvelope+import com.vayunmathur.findfamily.uwb.UwbEnvelopeKind+import com.vayunmathur.library.util.DataStoreUtils import java.security.SecureRandom+import kotlin.io.encoding.Base64+import kotlin.uuid.Uuid  /**  * Powered-off finding, beacon half: hands the Bluetooth controller a batch of rotating ephemeral@@ -76,6 +88,27 @@ object PoweredOffBeacon {      */     private fun keys(context: Context) = PoweredOffKeyStore(DirectBootStore.store(context)) +    /** Adapts the direct-boot store to the e2ee module's storage abstraction. */+    private class DirectBootKeyStore(private val ds: DataStoreUtils) : E2eeKeyStore {+        override suspend fun getBytes(name: String): ByteArray? = ds.getByteArrayAwait(name)+        override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) =+            ds.setByteArray(name, value, onlyIfAbsent)+    }++    /**+     * The recovery keypair and its grant roster, on the **same** direct-boot store as [keys] for+     * the reason spelled out above: two stores is how this feature has already broken once, and+     * the recovery private key has to be filed into [PoweredOffKeyStore] alongside the beacon+     * secret anyway.+     *+     * Device-protected storage is not credential-encrypted, so this is a key sitting outside the+     * passcode. That is not a regression — the identity key it replaces was already mirrored here+     * as `ff_pqcKemPriv` — and it is a strict improvement, because what is exposed now only opens+     * powered-off sightings instead of every location the user has ever shared.+     */+    private fun recovery(context: Context) =+        PoweredOffRecovery(DirectBootKeyStore(DirectBootStore.store(context)))+     /**      * Opt-in, default OFF, and it must stay default OFF. A phone the user believes is switched      * off does not start advertising because a default said so.@@ -86,16 +119,28 @@ object PoweredOffBeacon {     /**      * Turn the beacon on or off.      *-     * Turning it on mints the beacon secret and files it, with this device's ML-KEM private-     * bundle, under the owner's own userid — so sightings are readable from the user's other-     * devices rather than only by the phone that is lost and switched off.+     * Turning it on mints the beacon secret and a dedicated recovery keypair, and files both+     * under the owner's own userid — so sightings are readable here, and can be made readable by+     * a family member the user explicitly picks. Nobody is picked by default; see+     * [grantRecovery].      *      * Turning it off clears the controller as well as the flag, so a device armed by an earlier-     * shutdown stops at the next one instead of running out its three days.+     * shutdown stops at the next one instead of running out its three days. It also drops the+     * recovery keypair and the whole grant roster: leaving the roster behind would silently+     * re-entitle everyone on it the next time the switch went back on, which is not what "off"+     * looked like it meant.      */     suspend fun setEnabled(context: Context, enabled: Boolean) {         DirectBootStore.store(context).setBoolean(KEY_ENABLED, enabled)-        if (enabled) provisionKeys(context) else disarm(context)+        if (enabled) {+            provisionKeys(context)+        } else {+            recovery(context).clear()+            // Also drop this device's own entry, or `canRead` stays true and the retrieval loop+            // keeps querying 258 handles every five minutes for a beacon that is switched off.+            Networking.userid.takeIf { it != 0L }?.let { keys(context).forget(it) }+            disarm(context)+        }     }      /**@@ -135,25 +180,26 @@ object PoweredOffBeacon {      * Done at opt-in rather than at shutdown because it writes to storage and the shutdown window      * is measured in seconds.      *-     * What gets filed is the **raw ML-KEM private DER** — `ff_pqcKemPriv`, one of the four-     * separate `ff_pqc*` blobs in the direct-boot identity mirror — and NOT a composite-     * `[4B kemPrivLen][kemPriv][dsaPriv]` bundle of the kind `TrackerProtocol` uses. A tracker's-     * identity is minted by the phone on the tracker's behalf and is carried as that composite; a-     * powered-off phone is not a tracker and reuses its own existing identity, so there is no-     * bundle to carry. The distinction is invisible at the type level — both are `ByteArray` —-     * and getting it wrong is silent: the bundle parser reads the DER's leading SEQUENCE header-     * as a length field and every decrypt fails into a log line. It has already happened once.-     *-     * The sealing side needs no equivalent care: finders seal with `Pqc.encryptTo`, which takes a-     * public bundle, and the relay already holds this user's public bundle in that shape.-     *-     * NOT DONE, and the feature is much weaker without it: sharing these keys with a chosen family-     * member. A powered-off phone cannot decrypt its own sightings, so today this only helps a-     * user who has a second device of their own signed in. `PoweredOffKeyStore` is already keyed-     * by userid to hold a peer's keys; the distribution path over the e2ee peer channel, and the-     * UI to choose who gets them, are not written. Handing someone this key lets them locate the-     * device for as long as it lives, so it must never be synced to the whole roster by default.-     * Whoever writes it: file the raw DER here too, not a bundle.+     * What gets filed is the **raw ML-KEM private DER** of the dedicated recovery keypair, and+     * NOT a composite `[4B kemPrivLen][kemPriv][dsaPriv]` bundle of the kind `TrackerProtocol`+     * uses. A tracker's identity is minted by the phone on the tracker's behalf and is carried as+     * that composite; a powered-off phone is not a tracker. The distinction is invisible at the+     * type level — both are `ByteArray` — and getting it wrong is silent: the bundle parser reads+     * the DER's leading SEQUENCE header as a length field and every decrypt fails into a log+     * line. It has already happened once.+     *+     * ## Why this is no longer `ff_pqcKemPriv`+     * It used to be, and that is exactly what made the feature unshareable. A powered-off phone+     * cannot decrypt its own sightings, so somebody else has to hold the key — and the identity+     * private key decrypts every live location this user publishes to anyone, forever. Handing+     * that to a family member to help find a lost phone is not a trade worth making, so sightings+     * are sealed to a key that opens sightings and nothing else. See [PoweredOffRecovery] for the+     * grant model and for the two things rotation cannot undo.+     *+     * Unconditionally re-files rather than returning early when the store already has something:+     * [PoweredOffRecovery.revoke] rotates, and a stale private key left here would leave the+     * owner's own device unable to read its own sightings — silently, like every other failure in+     * this feature.      */     private suspend fun provisionKeys(context: Context) {         val userId = Networking.userid@@ -162,17 +208,116 @@ object PoweredOffBeacon {             return         }         val store = keys(context)-        if (store.canRead(userId)) return         val secret = store.secret(userId)             ?: ByteArray(32).also { SecureRandom().nextBytes(it) }-        val priv = DirectBootStore.store(context).getByteArrayAwait("ff_pqcKemPriv")-        if (priv == null) {-            Log.i(TAG, "identity mirror not seeded, deferring key provisioning")-            return+        store.save(userId, secret, recovery(context).ensure().kemPrivate)+    }++    // ------------------------------------------------------------------+    // Recovery-key sharing: who, besides this device, can find it when it is off+    // ------------------------------------------------------------------++    /** Peers currently able to decrypt this device's sightings. Empty until an explicit grant. */+    suspend fun recoveryGrantees(context: Context): Set<Long> = recovery(context).grantees()++    /**+     * Let [peerId] find this phone while it is switched off, and send them the keys to do it.+     *+     * Returns false when there is nothing to send yet (no identity, or the beacon has never been+     * switched on so there is no secret) or the peer could not be reached. A false here leaves+     * the roster updated but the peer without keys; re-granting redelivers, which is the intended+     * repair and is why [PoweredOffRecovery.grant] is not idempotent about delivery.+     *+     * What [peerId] can do afterwards, stated because the UI has to say it: decrypt this device's+     * powered-off sightings, *and* derive its EIDs from the beacon secret and recognise it in the+     * wild. The secret is not optional — [PoweredOffProtocol.recentHandles] is what tells them+     * which handles to ask the relay for — so the second capability comes with the first.+     */+    suspend fun grantRecovery(context: Context, peerId: Long): Boolean {+        val userId = Networking.userid+        if (userId == 0L) return false+        val secret = keys(context).secret(userId) ?: run {+            Log.i(TAG, "no beacon secret yet, cannot grant recovery")+            return false         }-        store.save(userId, secret, priv)+        val distribution = recovery(context).grant(peerId)+        return deliver(distribution, secret)     } +    /**+     * Withdraw [peerId]'s ability to find this phone when it is off.+     *+     * Rotates **both** halves of what they were given, because they do two different things and+     * only rotating one leaves the other alive:+     *  - the recovery keypair, so nothing sealed from now on is readable with their copy;+     *  - the beacon secret, so they can no longer derive this phone's EIDs. Without this they+     *    could go on recognising and following the powered-off phone indefinitely — the exact+     *    capability the grant UI warns about, and therefore the exact capability revoking has to+     *    take back.+     *+     * Re-files both locally so this device can still read its own sightings, then redelivers to+     * everyone still granted. Returns false if any redelivery failed; the revocation itself has+     * already taken effect locally either way.+     *+     * **Forward-only.** [peerId] can still open any ciphertext they already fetched, and the new+     * public half does not reach finders until this phone next registers on shutdown, so a beacon+     * window already in flight keeps being sealed to the old key. Rotation also retires the+     * previous private key, so sightings still sitting on the relay from the current window+     * become unreadable to the owner as well.+     */+    suspend fun revokeRecovery(context: Context, peerId: Long): Boolean {+        val userId = Networking.userid+        if (userId == 0L) return false+        val store = keys(context)+        val distribution = recovery(context).revoke(peerId)+        val freshSecret = ByteArray(32).also { SecureRandom().nextBytes(it) }+        // Before anything goes out: the owner reads their own sightings through the same store,+        // so a rotation that forgot this would revoke the user from themselves.+        store.save(userId, freshSecret, distribution.kemPrivate)+        return deliver(distribution, freshSecret)+    }++    /** Seal [distribution] to each recipient's own public bundle and send. */+    private suspend fun deliver(distribution: RecoveryDistribution, secret: ByteArray): Boolean {+        val owner = Networking.userid+        var allOk = true+        for (peer in distribution.to) {+            // Signed per recipient, because the recipient is inside the signed bytes: a grant+            // lifted off one peer cannot be replayed at another.+            val signature = Networking.signAsMe(+                poweredOffGrantSigningBytes(owner, peer, distribution.epoch, secret, distribution.kemPrivate)+            )+            if (signature == null) {+                Log.w(TAG, "cannot sign recovery grant, not delivering to ${peer.toULong()}")+                allOk = false+                continue+            }+            val grant = PoweredOffGrant(+                epoch = distribution.epoch,+                secretB64 = Base64.encode(secret),+                recoveryPrivB64 = Base64.encode(distribution.kemPrivate),+                sigB64 = Base64.encode(signature),+            )+            // publishUwbMessage resolves the peer's existing ML-KEM bundle and seals with+            // Pqc.encryptTo before the frame reaches the socket, so the relay only ever forwards+            // bytes it has no key for.+            val ok = Networking.publishUwbMessage(grantEnvelope(grant), peer)+            if (!ok) Log.w(TAG, "could not deliver recovery keys to ${peer.toULong()}")+            allOk = allOk && ok+        }+        return allOk+    }++    private fun grantEnvelope(grant: PoweredOffGrant) = UwbEnvelope(+        // Nothing correlates these to a ranging session; the field is required by the shared+        // envelope and a fresh id keeps them from matching any `UwbSessionManager` await.+        sessionId = Uuid.random().toString(),+        sender = Networking.userid.toULong(),+        senderPlatform = "android",+        kind = UwbEnvelopeKind.POF_GRANT,+        recovery = grant,+    )+     /**      * Hand a fresh batch to the controller and, if [ARM_CONTROLLER], switch advertising on.      * Called from [FinalLocationReporter] on the shutdown broadcast.@@ -201,7 +346,17 @@ object PoweredOffBeacon {         // Before the radios go down, and before the controller is told anything. Once the phone         // is off it cannot re-register and will not self-heal, so a beacon the relay has never         // heard of would advertise for three days into nothing.-        if (!Networking.registerPoweredOffEids(userId, eids)) {+        //+        // The recovery bundle goes up with the EIDs because this is the only moment it can: it is+        // what finders will seal to for the whole window, and a rotation since the last shutdown+        // does not reach the relay until now.+        val recoveryKeys = recovery(context).ensure()+        // `ensure` mints when the keypair is blank, and it is blank after `setEnabled(false)`.+        // Registering a public half whose private half is not in the sighting store would leave+        // the owner unable to read their own sightings, so re-file before registering — the same+        // trap `revokeRecovery` guards against.+        keys(context).save(userId, secret, recoveryKeys.kemPrivate)+        if (!Networking.registerPoweredOffEids(userId, eids, recoveryKeys.publicBundle)) {             Log.i(TAG, "relay did not accept the EID list, not arming")             return null         }
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffKeyStore.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffKeyStore.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffKeyStore.ktindex 524f6ee54e..6b2e7fe228 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffKeyStore.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffKeyStore.kt@@ -25,15 +25,19 @@ import com.vayunmathur.library.util.DataStoreUtils  * than in [TrackerStore] because [TrackerStore] is keyed on tracker `User` rows and these are  * ordinary people.  * ## What is stored, and why the name matters- * The key half is the device's **raw ML-KEM private DER** — the `ff_pqcKemPriv` blob from the- * identity mirror — and deliberately NOT the composite `[4B kemPrivLen][kemPriv][dsaPriv]` that- * the word "bundle" means everywhere else in this package. A powered-off phone reuses its own- * existing identity, whereas a tracker's identity is minted on its behalf and is composite.- * These accessors are named [kemPrivateKey] rather than `privateBundle` because calling it a- * bundle already caused one silent bug: the value was fed to- * [TrackerProtocol.kemPrivFromPrivateBundle], which read the DER's leading SEQUENCE header as a- * length field and failed every decrypt. Both shapes are `ByteArray`, so nothing but the name- * stops the next caller repeating it. Decrypt this with `Pqc.decrypt` directly.+ * The key half is the device's **raw ML-KEM private DER** for its dedicated *recovery* keypair —+ * never `ff_pqcKemPriv`, the identity key the beacon half used to file here. That key decrypts+ * every live location the user publishes to anyone, and this store exists to be handed to other+ * people, so the two must not meet. See [PoweredOffRecovery].+ *+ * It is deliberately NOT the composite `[4B kemPrivLen][kemPriv][dsaPriv]` that the word "bundle"+ * means everywhere else in this package. A tracker's identity is minted on its behalf and is+ * composite; a powered-off phone's recovery key is a bare ML-KEM private key. These accessors are+ * named [kemPrivateKey] rather than `privateBundle` because calling it a bundle already caused one+ * silent bug: the value was fed to [TrackerProtocol.kemPrivFromPrivateBundle], which read the+ * DER's leading SEQUENCE header as a length field and failed every decrypt. Both shapes are+ * `ByteArray`, so nothing but the name stops the next caller repeating it. Decrypt this with+ * `Pqc.decrypt` directly.  *  * The set of owned trackers is simply the `User` rows with `kind == UserKind.TRACKER`, so  * no separate index is kept here.@@ -43,20 +47,55 @@ class PoweredOffKeyStore(private val ds: DataStoreUtils) {     /**      * Stores (or replaces) the beacon secret and the raw ML-KEM private DER for [userId].      * [kemPrivateKey] must be the raw key, not a composite bundle — see the class KDoc.+     *+     * [epoch] is the owner's rotation counter for these keys, kept so a stale grant that arrives+     * after a fresher one cannot overwrite it. Zero for this device's own keys, which nothing+     * else races with.      */-    suspend fun save(userId: Long, secret: ByteArray, kemPrivateKey: ByteArray) {+    suspend fun save(userId: Long, secret: ByteArray, kemPrivateKey: ByteArray, epoch: Long = 0L) {         ds.setByteArray(secretKey(userId), secret)         ds.setByteArray(privKey(userId), kemPrivateKey)+        ds.setByteArray(epochKey(userId), epoch.toString().encodeToByteArray())     } -    suspend fun secret(userId: Long): ByteArray? = ds.getByteArrayAwait(secretKey(userId))+    /**+     * The beacon secret, or null if there is none.+     *+     * Empty reads as absent. [forget] and the recovery reset blank values rather than deleting+     * them, because the backing store has no delete, and a zero-length secret is not a secret:+     * handing one to `PoweredOffProtocol.eid` throws `"Empty key"` out of `SecretKeySpec`, and the+     * caller that would do it is the shutdown broadcast, where nothing may throw.+     */+    suspend fun secret(userId: Long): ByteArray? =+        ds.getByteArrayAwait(secretKey(userId))?.takeIf { it.isNotEmpty() }++    /** The raw ML-KEM private DER, ready to hand straight to `Pqc.decrypt`. Empty reads as absent. */+    suspend fun kemPrivateKey(userId: Long): ByteArray? =+        ds.getByteArrayAwait(privKey(userId))?.takeIf { it.isNotEmpty() } -    /** The raw ML-KEM private DER, ready to hand straight to `Pqc.decrypt`. */-    suspend fun kemPrivateKey(userId: Long): ByteArray? = ds.getByteArrayAwait(privKey(userId))+    /** Rotation counter of the stored keys, or 0 if none were ever stored for [userId]. */+    suspend fun epoch(userId: Long): Long =+        ds.getByteArrayAwait(epochKey(userId))?.decodeToString()?.toLongOrNull() ?: 0L++    /**+     * Forget [userId]'s keys, so this device stops polling for a beacon it can no longer read.+     *+     * Only ever this device's own entry today, from turning powered-off finding off. Blanks+     * rather than deletes because that is all the backing store offers, which is why [secret],+     * [kemPrivateKey] and [canRead] all treat an empty value as absent. The epoch is left behind+     * deliberately: it is a monotonic replay floor for grants received from a peer, and nothing+     * is gained by resetting it.+     */+    suspend fun forget(userId: Long) {+        ds.setByteArray(secretKey(userId), ByteArray(0))+        ds.setByteArray(privKey(userId), ByteArray(0))+    }      /** True when both keys are present, i.e. this device's sightings are readable here. */-    suspend fun canRead(userId: Long): Boolean = secret(userId) != null && kemPrivateKey(userId) != null+    suspend fun canRead(userId: Long): Boolean =+        secret(userId) != null && kemPrivateKey(userId) != null      private fun secretKey(id: Long) = "ff_pof_secret_$id"     private fun privKey(id: Long) = "ff_pof_priv_$id"+    private fun epochKey(id: Long) = "ff_pof_epoch_$id" }
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffRecovery.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffRecovery.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffRecovery.ktnew file mode 100644index 0000000000..fa406eddb7--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffRecovery.kt@@ -0,0 +1,238 @@+package com.vayunmathur.findfamily.tracker++import com.vayunmathur.e2ee.E2eeKeyStore+import com.vayunmathur.e2ee.Pqc++/**+ * An ML-KEM keypair used for nothing but powered-off sightings.+ *+ * [publicBundle] is an ordinary `Pqc` public bundle with an **empty ML-DSA half**, the same shape+ * `Pqc.generateLinkKey` produces. That is not a shortcut: a key we hand to other people should be+ * able to receive a sighting and nothing else, and a bundle with no signing half cannot be used to+ * sign anything in this user's name even by a peer who holds the private side.+ *+ * [kemPrivate] is the **raw ML-KEM private DER**, matching what [PoweredOffKeyStore] stores and+ * what `Pqc.decrypt` expects — deliberately not the composite `[4B kemPrivLen][kemPriv][dsaPriv]`+ * that the word "bundle" means elsewhere in this package. See the [PoweredOffKeyStore] KDoc for+ * the bug that naming cost last time.+ */+class RecoveryKeypair(val publicBundle: ByteArray, val kemPrivate: ByteArray)++/**+ * The work a [PoweredOffRecovery] roster change leaves for the caller to actually send.+ *+ * Returned rather than sent here so the roster is decidable without a socket, a `Context` or the+ * native crypto library — which is what makes grant/revoke unit-testable, and this is the code+ * where being able to test the exact set of recipients matters most.+ */+class RecoveryDistribution(+    /** Rotation counter of [kemPrivate]. Monotonic; a peer must ignore a lower one. */+    val epoch: Long,+    /** The private half to seal individually to each peer in [to]. Never leaves the device in clear. */+    val kemPrivate: ByteArray,+    /** The public half to re-register with the relay so finders seal to it. */+    val publicBundle: ByteArray,+    /** Every peer that should hold the current key, not only the one that just changed. */+    val to: Set<Long>,+    /** Peer to ask to drop its copy. Advisory — see [PoweredOffRecovery]. */+    val revoked: Long? = null,+)++/**+ * Who, besides this device, can decrypt this device's powered-off sightings — and the dedicated+ * keypair that makes answering "somebody" possible without handing out the identity key.+ *+ * ## Why a separate keypair exists at all+ * A powered-off phone cannot decrypt its own sightings; it is off, and by the time it is back on+ * the finding is over. So somebody else has to hold a key. The obvious key is the one the beacon+ * used to use — `ff_pqcKemPriv`, the device's ML-KEM identity private key — and handing that to a+ * family member would let them decrypt **every** live location this user ever publishes, to+ * anyone, forever. That is not a trade worth making for a recovery convenience, so sightings are+ * sealed to a key that can open sightings and nothing else. Compromising it costs the user their+ * powered-off location history; it does not cost them their live location channel.+ *+ * ## What this class will not do+ * The roster starts empty and only ever grows by an explicit [grant]. There is deliberately no+ * "share with everyone I already share location with": the existing roster is a list of people+ * allowed to see where the user is *now*, which is revocable in practice by turning sharing off.+ * A recovery key is not revocable in that sense, so consent for one is not consent for the other.+ *+ * ## Two things rotation cannot undo, which the UI must say out loud+ *  - A grantee also needs the beacon secret, because [PoweredOffProtocol.recentHandles] is what+ *    tells them which handles to fetch. Holding it lets them derive this device's EIDs and track+ *    the powered-off phone themselves for as long as the keypair lives. For a person the user+ *    picked by name that is inside the trust model, but it is a real capability and not a+ *    side effect worth hiding in a comment.+ *  - [revoke] rotates, which stops the revoked peer opening anything sealed **after** it. It+ *    cannot claw back ciphertexts they already fetched, and it cannot stop them having written+ *    the old key down. Revocation is forward-only. Saying otherwise in the UI would be a lie.+ *+ * Rotation also retires the previous private key outright, so sightings still sitting on the relay+ * sealed to the old public half become unreadable to the owner too. That is the honest cost of+ * revoking mid-window and is preferred to keeping a retired key alive to satisfy it.+ */+class PoweredOffRecovery(+    private val ks: E2eeKeyStore,+    /**+     * Seam for tests. The real implementation reaches into the native ML-KEM library, which a JVM+     * unit test has no business loading — and the roster arithmetic this class exists for is worth+     * testing without it.+     */+    private val mint: () -> RecoveryKeypair = ::mintRecoveryKeypair,+) {++    /** The current keypair, minting and filing one on first use. */+    suspend fun ensure(): RecoveryKeypair {+        val priv = ks.present(KEY_PRIV)+        val pub = ks.present(KEY_PUB)+        if (priv != null && pub != null) return RecoveryKeypair(pub, priv)+        return rotate()+    }++    /** The peers currently entitled to decrypt this device's sightings. Empty until a [grant]. */+    suspend fun grantees(): Set<Long> = decodeIds(ks.present(KEY_GRANTS))++    suspend fun isGranted(peerId: Long): Boolean = peerId in grantees()++    /** Rotation counter of the current keypair. 0 before one exists. */+    suspend fun epoch(): Long = ks.present(KEY_EPOCH)?.decodeToString()?.toLongOrNull() ?: 0L++    /**+     * Entitle [peerId] to decrypt this device's sightings.+     *+     * Does **not** rotate: the peers that already hold this key are supposed to hold it, so+     * churning it would only cost every one of them a redelivery. The returned distribution is+     * therefore addressed to [peerId] alone.+     *+     * Re-granting a peer that is already on the roster still returns a distribution, because the+     * ordinary reason to do it is that the first delivery did not arrive.+     */+    suspend fun grant(peerId: Long): RecoveryDistribution {+        require(peerId != 0L) { "peerId 0 is not a real peer" }+        val keys = ensure()+        val updated = grantees() + peerId+        ks.setBytes(KEY_GRANTS, encodeIds(updated))+        return RecoveryDistribution(+            epoch = epoch(),+            kemPrivate = keys.kemPrivate,+            publicBundle = keys.publicBundle,+            to = setOf(peerId),+        )+    }++    /**+     * Withdraw [peerId]'s entitlement and rotate, so nothing sealed from now on is readable with+     * the key they were given.+     *+     * The distribution is addressed to **every remaining grantee**, not to nobody: rotating+     * without redelivering would silently revoke the innocent peers too, and they would go on+     * polling with a dead key and finding nothing, which is the failure mode this whole feature+     * is riddled with and the one hardest to notice.+     *+     * Revoking a peer that was never granted still rotates. The caller reached for revoke, and a+     * new key costs one registration; guessing that they were mistaken does not.+     */+    suspend fun revoke(peerId: Long): RecoveryDistribution {+        val remaining = grantees() - peerId+        ks.setBytes(KEY_GRANTS, encodeIds(remaining))+        val keys = rotate()+        return RecoveryDistribution(+            epoch = epoch(),+            kemPrivate = keys.kemPrivate,+            publicBundle = keys.publicBundle,+            to = remaining,+            revoked = peerId,+        )+    }++    /**+     * Drop the keypair and the whole roster, for when the user turns powered-off finding off.+     *+     * Leaving the roster behind would silently re-entitle everyone on it the next time the switch+     * went back on, which is not what "off" looked like it meant.+     */+    suspend fun clear() {+        ks.setBytes(KEY_GRANTS, ByteArray(0))+        ks.setBytes(KEY_PRIV, ByteArray(0))+        ks.setBytes(KEY_PUB, ByteArray(0))+    }++    private suspend fun rotate(): RecoveryKeypair {+        val fresh = mint()+        ks.setBytes(KEY_PRIV, fresh.kemPrivate)+        ks.setBytes(KEY_PUB, fresh.publicBundle)+        ks.setBytes(KEY_EPOCH, (epoch() + 1).toString().encodeToByteArray())+        return fresh+    }++    // E2eeKeyStore can write but not delete, so `clear` blanks rather than removes. Every read+    // therefore has to treat an empty value as absent, or a cleared keypair would read back as a+    // zero-length private key and fail inside the native decrypt instead of being re-minted.+    private suspend fun E2eeKeyStore.present(name: String): ByteArray? =+        getBytes(name)?.takeIf { it.isNotEmpty() }++    private fun encodeIds(ids: Set<Long>): ByteArray =+        ids.sorted().joinToString(",").encodeToByteArray()++    private fun decodeIds(raw: ByteArray?): Set<Long> {+        if (raw == null || raw.isEmpty()) return emptySet()+        return raw.decodeToString().split(',').mapNotNull { it.trim().toLongOrNull() }.toSet()+    }++    private companion object {+        const val KEY_PRIV = "ff_pofrec_priv"+        const val KEY_PUB = "ff_pofrec_pub"+        const val KEY_GRANTS = "ff_pofrec_grants"+        const val KEY_EPOCH = "ff_pofrec_epoch"+    }+}++/**+ * Mint a recovery keypair with the real ML-KEM implementation.+ *+ * ML-KEM only, with an empty ML-DSA half — see [RecoveryKeypair]. Top-level rather than a method+ * so [PoweredOffRecovery]'s default argument does not drag the native library into a unit test+ * that never calls it.+ */+fun mintRecoveryKeypair(): RecoveryKeypair {+    val (kemPub, kemPriv) = Pqc.generateKem()+    return RecoveryKeypair(publicBundle = Pqc.bundle(kemPub, ByteArray(0)), kemPrivate = kemPriv)+}++/**+ * The exact bytes a grant is signed over, so the recipient can tell who really sent it.+ *+ * The peer channel encrypts to the recipient but does not authenticate the sender: `sender` on a+ * [com.vayunmathur.findfamily.uwb.UwbEnvelope] is self-declared, and anyone who knows a userid can+ * seal an envelope to it. Without a signature a connected peer could deliver keys claiming to be+ * somebody else, and every sighting decrypted with them would be stamped with that somebody's+ * userid by `PoweredOffReporting.fetchSightings` and drawn on the map as their phone. Forged+ * locations attributed to a family member is a worse outcome than the feature not working.+ *+ * [owner] and [recipient] are both inside the signature. Owner binds the keys to the identity+ * being claimed; recipient stops a grant being replayed to a third party who was never chosen.+ *+ * The secret's length is written before it so the two variable-length fields cannot be traded off+ * against each other: without it, a 4-byte secret followed by an 8-byte key hashes identically to+ * an 8-byte secret followed by a 4-byte key of the same bytes. Both are fixed-length in practice,+ * which is exactly the kind of reasoning that stops being true later.+ */+fun poweredOffGrantSigningBytes(+    owner: Long,+    recipient: Long,+    epoch: Long,+    secret: ByteArray,+    recoveryPrivate: ByteArray,+): ByteArray {+    val domain = "ffpofgrant1".toByteArray(Charsets.US_ASCII)+    val out = ByteArray(domain.size + 32 + secret.size + recoveryPrivate.size)+    var off = 0+    domain.copyInto(out, off); off += domain.size+    TrackerProtocol.u64be(owner).copyInto(out, off); off += 8+    TrackerProtocol.u64be(recipient).copyInto(out, off); off += 8+    TrackerProtocol.u64be(epoch).copyInto(out, off); off += 8+    TrackerProtocol.u64be(secret.size.toLong()).copyInto(out, off); off += 8+    secret.copyInto(out, off); off += secret.size+    recoveryPrivate.copyInto(out, off)+    return out+}
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.ktindex 7548077a5b..c21d574537 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -285,7 +285,17 @@ fun MainPage(             userNamesByLocationName = usersByLocationName         ),         person = selectedUser?.let {-            PersonUiState(it, userPositions[it.id], waypoints, globalSharingEnabled, crowdFindingEnabled)+            PersonUiState(+                it,+                userPositions[it.id],+                waypoints,+                globalSharingEnabled,+                crowdFindingEnabled,+                // Only the user's own sheet shows the powered-off controls, and it is the only+                // one that needs a peer list. Passing it unconditionally keeps the state a plain+                // projection rather than something that depends on which row was tapped.+                connectedUsers,+            )         }     ) @@ -784,7 +794,7 @@ fun PersonDetailSheet(state: PersonUiState, actions: PersonActions) {         // from the network without giving back, or giving without getting.         if (user.id == Networking.userid) {             Spacer(Modifier.height(4.dp))-            PoweredOffFindingSetting()+            PoweredOffFindingSetting(state.connectedUsers.filter { it.id != user.id })             Spacer(Modifier.height(8.dp))             CrowdFindingRow(state.crowdFindingEnabled) { actions.setCrowdFinding(it) }         }
findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffFindingSetting.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffFindingSetting.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffFindingSetting.ktindex 849b014263..2c3d7f8044 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffFindingSetting.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffFindingSetting.kt@@ -21,6 +21,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.findfamily.R+import com.vayunmathur.findfamily.data.User import com.vayunmathur.findfamily.platform.PoweredOffBeacon import com.vayunmathur.library.ui.Switch import kotlinx.coroutines.launch@@ -39,7 +40,7 @@ import kotlinx.coroutines.launch  *   up front, not left to conclude it was broken.  */ @Composable-fun PoweredOffFindingSetting() {+fun PoweredOffFindingSetting(peers: List<User>) {     val context = LocalContext.current     val scope = rememberCoroutineScope()     var supported by remember { mutableStateOf<Boolean?>(null) }@@ -97,6 +98,10 @@ fun PoweredOffFindingSetting() {                 style = MaterialTheme.typography.bodySmall,                 color = MaterialTheme.colorScheme.onSurfaceVariant,             )+            // Only once the beacon is on: there is nothing to grant access to before that, and+            // offering the choice first would imply the phone is already findable.+            Spacer(Modifier.height(8.dp))+            PoweredOffGrantSetting(peers)         }     } }
findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffGrantSetting.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffGrantSetting.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffGrantSetting.ktnew file mode 100644index 0000000000..827227ea13--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffGrantSetting.kt@@ -0,0 +1,113 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.findfamily.R+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.platform.PoweredOffBeacon+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Switch+import com.vayunmathur.library.ui.Text+import kotlinx.coroutines.launch++/**+ * Who, besides this phone, may locate it once it is switched off.+ *+ * ## Why this is a list of people and not one more switch+ * A powered-off phone cannot decrypt its own sightings, so the feature is inert until somebody+ * else holds a key. The tempting shortcut is to send that key to everyone the user already shares+ * location with, and it is the wrong one: that roster means "may see where I am now", which the+ * user can withdraw at any moment by turning sharing off. A recovery key cannot be withdrawn in+ * that sense — see [R.string.poweroff_grant_revoke_warning] — so consent for the first is not+ * consent for the second. Everyone starts off.+ *+ * ## Why both warnings are always on screen+ * The same rule the switch above follows, for the same reason, and here it matters more. Two+ * things about this feature cannot be engineered away, so the only honest place for them is the+ * screen where the user decides:+ *+ *  - **Choosing someone lets them track the phone**, not merely read where it has been. They need+ *    the beacon secret to know which handles to fetch, and that same secret derives the phone's+ *    identifiers. One key, both capabilities, no way to split them.+ *  - **Removing someone is forward-only.** Revoking rotates both the recovery keypair and the+ *    beacon secret, so it does end the tracking above — but only from that moment. Sightings the+ *    peer already fetched stay readable to them and nothing can change that.+ *+ * Neither is a footnote and neither is behind an info icon. A user who discovers the first one+ * afterwards was misled by this screen, not by the Bluetooth stack.+ */+@Composable+fun PoweredOffGrantSetting(peers: List<User>) {+    val context = LocalContext.current+    val scope = rememberCoroutineScope()+    var granted by remember { mutableStateOf(emptySet<Long>()) }++    LaunchedEffect(Unit) { granted = PoweredOffBeacon.recoveryGrantees(context) }++    Column(Modifier.fillMaxWidth()) {+        Text(+            stringResource(R.string.poweroff_grant_title),+            style = MaterialTheme.typography.bodyMedium,+        )+        Text(+            stringResource(R.string.poweroff_grant_explanation),+            style = MaterialTheme.typography.bodySmall,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+        Spacer(Modifier.height(4.dp))+        Text(+            stringResource(R.string.poweroff_grant_tracking_warning),+            style = MaterialTheme.typography.bodySmall,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+        Spacer(Modifier.height(4.dp))+        Text(+            stringResource(R.string.poweroff_grant_revoke_warning),+            style = MaterialTheme.typography.bodySmall,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+        Spacer(Modifier.height(4.dp))++        if (peers.isEmpty()) {+            Text(+                stringResource(R.string.poweroff_grant_no_peers),+                style = MaterialTheme.typography.bodySmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+            return@Column+        }++        for (peer in peers) {+            Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+                Text(peer.name, Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium)+                Switch(peer.id in granted, { on ->+                    // Optimistic, then reconciled from the store once the grant or the rotation+                    // has actually been written. Delivery can fail — the peer may be offline —+                    // and the roster is what decides who gets the next redistribution, so the+                    // switch follows the roster rather than the send.+                    granted = if (on) granted + peer.id else granted - peer.id+                    scope.launch {+                        if (on) PoweredOffBeacon.grantRecovery(context, peer.id)+                        else PoweredOffBeacon.revokeRecovery(context, peer.id)+                        granted = PoweredOffBeacon.recoveryGrantees(context)+                    }+                })+            }+        }+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyUiContract.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyUiContract.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyUiContract.ktindex cebd79e1db..59af755b82 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyUiContract.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyUiContract.kt@@ -61,6 +61,12 @@ data class PersonUiState(     val sharingGloballyEnabled: Boolean = true,     /** Whether this phone has opted in to finding other people's powered-off devices. */     val crowdFindingEnabled: Boolean = false,+    /**+     * Connected family members, offered on the user's own entry as the choice of who may locate+     * this phone once it is switched off. Empty for anyone else's sheet — the powered-off+     * controls are properties of this device, not of a relationship.+     */+    val connectedUsers: List<User> = emptyList(), )  /** Person-sheet callbacks. Same no-op-default arrangement as [FamilyListActions]. */
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.ktindex 5ae48f9621..c550c2f98d 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt@@ -55,6 +55,7 @@ import com.vayunmathur.findfamily.data.UserKind import com.vayunmathur.findfamily.tracker.PoweredOffKeyStore import com.vayunmathur.findfamily.tracker.PoweredOffReporting import com.vayunmathur.findfamily.tracker.PoweredOffScanner+import com.vayunmathur.findfamily.tracker.poweredOffGrantSigningBytes import com.vayunmathur.findfamily.tracker.TrackerBeaconScanner import com.vayunmathur.findfamily.tracker.TrackerReporting import com.vayunmathur.findfamily.tracker.TrackerStore@@ -77,6 +78,7 @@ import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import java.util.Locale import kotlin.coroutines.resume+import kotlin.io.encoding.Base64 import kotlin.time.Clock import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.hours@@ -461,21 +463,84 @@ class LocationTrackingService : Service(), SensorEventListener {     /**      * Forwards decrypted UWB envelopes to [UwbInbox] and fires a local      * notification for REQUEST envelopes. Driven by the live WebSocket push.+     *+     * Powered-off recovery grants ride the same channel (see [UwbEnvelopeKind.POF_GRANT]) and are+     * handled here instead, deliberately without reaching [UwbInbox]: they are not ranging+     * traffic and have no business waking the Find Nearby screen.      */     private suspend fun handleUwbEnvelopes(list: List<UwbEnvelope>) {         if (list.isEmpty()) return         val users = repository.getAllUsers()         for (envelope in list) {-            UwbInbox.tryEmit(envelope)-            if (envelope.kind == UwbEnvelopeKind.REQUEST) {-                val senderId = envelope.sender.toLong()-                val senderName = users.firstOrNull { it.id == senderId }?.name-                    ?: getString(R.string.uwb_unknown_peer_name)-                createUwbRequestNotification(senderName, senderId)+            when (envelope.kind) {+                UwbEnvelopeKind.POF_GRANT -> acceptPoweredOffGrant(envelope)+                else -> {+                    UwbInbox.tryEmit(envelope)+                    if (envelope.kind == UwbEnvelopeKind.REQUEST) {+                        val senderId = envelope.sender.toLong()+                        val senderName = users.firstOrNull { it.id == senderId }?.name+                            ?: getString(R.string.uwb_unknown_peer_name)+                        createUwbRequestNotification(senderName, senderId)+                    }+                }             }         }     } +    /**+     * Store a family member's powered-off keys so this device can go and find their lost phone.+     *+     * Everything after this is already built: [PoweredOffKeyStore] is keyed by userid and+     * [pollPoweredOffSightings] already walks every user it can read, so filing the keys here is+     * the entire receiving side.+     *+     * Three reasons to refuse, all of them silent by design — a rejected grant is either an+     * attack or a stale duplicate, and neither is worth a notification:+     *  - the sender is not someone we have a [User] row for, so nobody chose to trust them;+     *  - the signature does not verify against that sender's identity bundle. The envelope is+     *    encrypted to us but its `sender` field is self-declared, so without this check any+     *    connected peer could deliver keys under a different family member's userid and have+     *    every sighting decrypted from them drawn on the map as that person's phone;+     *  - the grant is older than one we already hold, which happens when a revoke-triggered+     *    redistribution overtakes the grant it replaces.+     */+    private suspend fun acceptPoweredOffGrant(envelope: UwbEnvelope) {+        val store = poweredOffKeys ?: return+        val grant = envelope.recovery ?: return+        val ownerId = envelope.sender.toLong()+        if (ownerId == 0L || ownerId == Networking.userid) return+        if (repository.getUser(ownerId) == null) {+            Log.w(TAG_POWERED_OFF, "recovery grant from unknown sender, ignored")+            return+        }+        val decoded = runCatching {+            Triple(+                Base64.decode(grant.secretB64),+                Base64.decode(grant.recoveryPrivB64),+                Base64.decode(grant.sigB64),+            )+        }.getOrNull() ?: return+        val (secret, recoveryPriv, signature) = decoded++        val signed = poweredOffGrantSigningBytes(+            owner = ownerId,+            recipient = Networking.userid,+            epoch = grant.epoch,+            secret = secret,+            recoveryPrivate = recoveryPriv,+        )+        if (!Networking.verifyFrom(ownerId, signed, signature)) {+            Log.w(TAG_POWERED_OFF, "recovery grant signature did not verify, ignored")+            return+        }+        if (grant.epoch < store.epoch(ownerId)) {+            Log.i(TAG_POWERED_OFF, "ignoring superseded recovery grant (epoch ${grant.epoch})")+            return+        }+        store.save(ownerId, secret, recoveryPriv, grant.epoch)+        Log.i(TAG_POWERED_OFF, "stored recovery keys for a peer (epoch ${grant.epoch})")+    }+     // -----------------------------------------------------------------     // Custom UWB tracker crowd-finding (DEV_BUILD only)     // -----------------------------------------------------------------
findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.ktindex f7d7eca806..d75561e61f 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt@@ -227,7 +227,12 @@ object Networking {     // the EIDs it armed with and the server just remembers them, after which the existing     // 0x07/0x09/0x0A path resolves and carries reports unchanged. Additive: a server that     // predates this ignores 0x0C, and the only symptom is that no sightings are ever resolved.-    private const val WS_OP_POF_REGISTER: Byte = 0x0C // [0x0C][u64 userid][u16 count]([20B eid]×count)+    //+    // The trailing recovery bundle is what finders seal to, in place of the owner's identity+    // bundle — the change that makes a sighting readable by a family member rather than only by+    // the dead phone. Additive in the other direction too: the server sizes the EID array from+    // `count`, so a relay that predates the bundle never reads those trailing bytes.+    private const val WS_OP_POF_REGISTER: Byte = 0x0C // [0x0C][u64 userid][u16 count]([20B eid]×count)[u16 bundleLen][bundle]      private const val WS_KEY_NONE = 0     private const val WS_KEY_CLASSIC = 1@@ -667,14 +672,31 @@ object Networking {      /**      * Beacon: register the EIDs this device armed its Bluetooth controller with before shutting-     * down, so finders can resolve them to this device's ML-KEM public bundle.+     * down, together with the public half of the **recovery** keypair finders should seal to.      *      * Must be sent *before* the device powers off — once it is off it cannot re-register, and      * unlike a live tracker it will not self-heal on the next heartbeat. Registrations are held      * in memory server-side, so a relay restart during the powered-off window silently ends      * findability until the device boots again.+     *+     * ## [recoveryBundle] and what it depends on+     * The relay's `ff_pof_eids` maps an EID to a *userid* and then answers RESOLVE with that+     * user's ordinary identity bundle from `pqc_keys_db`. That is the reason the feature could+     * not be shared: the only key that opened a sighting was `ff_pqcKemPriv`, and handing that to+     * a family member hands them every live location this user will ever publish. Sightings are+     * therefore sealed to a dedicated recovery bundle instead — see+     * [com.vayunmathur.findfamily.tracker.PoweredOffRecovery].+     *+     * The bundle is appended after the EID array as `[u16 bundleLen][bundle]`, and is optional:+     * a relay that predates it sizes the array from `count` and never reads those trailing bytes.+     * When the relay has no bundle for an EID set it falls back to the owner's identity bundle+     * exactly as before, so an old client and an old server both keep working.      */-    suspend fun registerPoweredOffEids(userId: Long, eids: List<ByteArray>): Boolean {+    suspend fun registerPoweredOffEids(+        userId: Long,+        eids: List<ByteArray>,+        recoveryBundle: ByteArray,+    ): Boolean {         val session = wsSession ?: return false         if (eids.isEmpty()) return false         val n = eids.size.coerceAtMost(PoweredOffProtocol.ARMED_SLOTS)@@ -682,7 +704,7 @@ object Networking {             // u16 count, not u8: the controller addresses 256 keys (index 0..255) and 256 does             // not fit in a byte. Getting this wrong would silently drop the last EID, costing the             // final 17 minutes of the window.-            val frame = ByteArray(11 + n * PoweredOffProtocol.EID_LEN)+            val frame = ByteArray(11 + n * PoweredOffProtocol.EID_LEN + 2 + recoveryBundle.size)             frame[0] = WS_OP_POF_REGISTER             putU64Be(frame, 1, userId.toULong())             frame[9] = (n ushr 8).toByte()@@ -692,6 +714,9 @@ object Networking {                 eids[i].copyInto(frame, off, 0, PoweredOffProtocol.EID_LEN)                 off += PoweredOffProtocol.EID_LEN             }+            frame[off] = (recoveryBundle.size ushr 8).toByte()+            frame[off + 1] = recoveryBundle.size.toByte()+            recoveryBundle.copyInto(frame, off + 2)             session.send(frame)             true         } catch (e: Exception) {@@ -808,6 +833,26 @@ object Networking {         return null     } +    /**+     * Sign [data] with this device's ML-DSA identity key, or null if PQC is unavailable.+     *+     * Used to authenticate powered-off recovery grants. The peer channel encrypts to the+     * recipient but leaves the sender field self-declared, which is tolerable for a UWB handshake+     * and is not tolerable for handing over decryption keys.+     */+    fun signAsMe(data: ByteArray): ByteArray? {+        if (!pqcReady) return null+        return runCatching { pqcIdentity.sign(data) }+            .onFailure { Log.w(TAG, "signAsMe failed", it) }.getOrNull()+    }++    /** Whether [signature] over [data] was really produced by [userId]'s identity key. */+    suspend fun verifyFrom(userId: Long, data: ByteArray, signature: ByteArray): Boolean {+        val user = runCatching { repository.getUser(userId) }.getOrNull() ?: return false+        val bundle = peerPqcBundle(user) ?: return false+        return Pqc.verify(bundle, data, signature)+    }+     /** The post-quantum capability of a peer, used to gate connecting/sharing. */     enum class PeerCrypto {         /** Peer has a PQC bundle registered — sharing works. */
findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.ktindex f65d18664c..91e5c176e8 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt@@ -25,7 +25,48 @@ data class UwbEnvelope(     /** Envelope kind: `"request"`, `"ack"`, `"config"`, `"cancel"`. */     val kind: String,     /** Optional payload — see [UwbHandshake]. */-    val payload: UwbHandshake? = null+    val payload: UwbHandshake? = null,+    /**+     * Powered-off recovery key material, for the [UwbEnvelopeKind.POF_GRANT] kind only.+     * Null on every UWB envelope.+     *+     * This rides the UWB channel rather than getting a channel of its own because that channel is+     * already end-to-end encrypted to the peer's ML-KEM bundle, already routed by the relay into+     * a queue the relay cannot read, and needs no server change to carry a new kind. The name is+     * now wrong for what the envelope carries; a second flag bit would have been cleaner but the+     * relay maps every unset bit0 to the *location* queue (`ff_kind`, findfamily.rs), where an+     * iOS peer would drain it and fail to parse it as a location.+     */+    val recovery: PoweredOffGrant? = null,+)++/**+ * The keys a peer needs to find this device once it is switched off, sealed to that peer's own+ * public bundle before it ever reaches the relay.+ *+ * Both halves are necessary and neither is sufficient:+ *  - [secretB64] is the beacon secret, which drives [com.vayunmathur.findfamily.tracker.PoweredOffProtocol.recentHandles]+ *    and so decides *what to ask the relay for*. It is also, unavoidably, the ability to derive+ *    this device's EIDs and recognise it in the wild.+ *  - [recoveryPrivB64] is the raw ML-KEM private DER that opens the sightings. Deliberately the+ *    dedicated recovery key and never `ff_pqcKemPriv`, which would hand over every live location+ *    this user publishes rather than only their powered-off sightings.+ *+ * [epoch] exists because delivery is asynchronous and rotation is not: a redistribution triggered+ * by a revoke can overtake an older grant still in the queue, and a peer that stored the older+ * one last would sit there polling with a dead key. Recipients keep the highest epoch they have+ * seen and drop anything below it.+ *+ * [sigB64] authenticates the sender, which the channel itself does not — see+ * [com.vayunmathur.findfamily.tracker.poweredOffGrantSigningBytes] for why an unsigned grant+ * would let one connected peer put forged locations on the map under another's name.+ */+@Serializable+data class PoweredOffGrant(+    val epoch: Long,+    val secretB64: String,+    val recoveryPrivB64: String,+    val sigB64: String, )  /**@@ -66,4 +107,21 @@ object UwbEnvelopeKind {     const val ACK = "ack"     const val CONFIG = "config"     const val CANCEL = "cancel"++    /**+     * Powered-off recovery key delivery, carried in [UwbEnvelope.recovery].+     *+     * Additive on purpose. Every existing consumer matches these kinds by equality — Android's+     * [UwbInbox] caches only REQUEST/CANCEL, `UwbSessionManager` waits on a matching `sessionId`,+     * and iOS `UwbInbox.swift` acts only on request/cancel — so a peer that predates this drops+     * the envelope on the floor and behaves exactly as it does today. Swift's `JSONDecoder`+     * likewise ignores the unknown `recovery` key rather than failing the whole decode.+     *+     * There is deliberately **no matching "forget these keys" message**. It would be a remote+     * delete triggered by an unauthenticated `sender` field, so any connected peer could wipe the+     * keys a third party had sent us; and it would buy nothing, because revoking rotates both the+     * recovery keypair and the beacon secret. A revoked peer keeps bytes that no longer decrypt+     * anything and no longer derive any live identifier.+     */+    const val POF_GRANT = "pofgrant" }
findfamily/src/main/res/values/strings.xml
diff --git a/findfamily/src/main/res/values/strings.xml b/findfamily/src/main/res/values/strings.xmlindex 7b58f61260..2a582b15d3 100644--- a/findfamily/src/main/res/values/strings.xml+++ b/findfamily/src/main/res/values/strings.xml@@ -320,12 +320,22 @@     <!-- PersonDetailSheet, own entry: label for the opt-in switch that makes THIS phone findable after it is switched off. Short noun phrase -->     <string name="poweroff_finding_title">Findable when switched off</string>     <!-- PersonDetailSheet, own entry: explanation under the powered-off finding switch. Must stay honest that the Bluetooth chip keeps advertising after the phone appears to be off. Paragraph -->-    <string name="poweroff_finding_explanation">When you switch this phone off, its Bluetooth chip keeps sending out a short anonymous signal so a family member who walks past can tell you where it is. The signal changes every 17 minutes and only your family can recognise it. Nobody, including us, can read where it was seen except you.</string>+    <string name="poweroff_finding_explanation">When you switch this phone off, its Bluetooth chip keeps sending out a short anonymous signal so a family member who walks past can tell you where it is. The signal changes every 17 minutes and only your family can recognise it. Nobody, including us, can read where it was seen except you and anyone you choose below.</string>     <!-- PersonDetailSheet, own entry: the limit, shown under the explanation whether the switch is on or off. Must not be hidden behind the switch. Two sentences -->     <string name="poweroff_finding_limit">This lasts about 3 days after you switch the phone off, then it stops. It is a limit of the Bluetooth chip, not a setting.</string>     <!-- PersonDetailSheet, own entry: shown when the switch is on, confirming the user can undo it. Sentence -->     <string name="poweroff_finding_off_hint">Turn this off and the phone sends nothing at all once it is switched off.</string>     <!-- PersonDetailSheet, own entry: shown instead of the switch when the phone's Bluetooth chip cannot do this. Sentence -->     <string name="poweroff_finding_unsupported">This phone\'s Bluetooth chip cannot stay findable while switched off.</string>+    <!-- PersonDetailSheet, own entry: heading for the per-person list choosing who may locate this phone while it is switched off. Short noun phrase -->+    <string name="poweroff_grant_title">Who can find this phone when it\'s off</string>+    <!-- PersonDetailSheet, own entry: explanation under the grant list. Must make clear the list starts empty and why anyone is needed at all. Paragraph -->+    <string name="poweroff_grant_explanation">Nobody, until you choose someone here. A switched-off phone cannot show you its own location, so somebody else\'s phone has to be able to read where yours was seen — otherwise the notes pile up and no one can open them.</string>+    <!-- PersonDetailSheet, own entry: the capability the user cannot be shielded from. Must not be softened or hidden behind a tap: choosing someone also lets that person track the phone. Paragraph -->+    <string name="poweroff_grant_tracking_warning">Anyone you choose can also go looking for this phone themselves, whenever they like, for as long as they stay on this list. Reading where it was seen and looking for it use the same key, so there is no way to give one without the other. Only choose people you would be happy to have find this phone.</string>+    <!-- PersonDetailSheet, own entry: what removing someone does and does not do. Must state plainly that revocation is forward-only. Paragraph -->+    <string name="poweroff_grant_revoke_warning">Taking someone off the list stops them seeing anywhere this phone goes from then on. It cannot take back places they have already collected, and it cannot make them forget. Anything this phone was seen at recently, but nobody has picked up yet, may be lost to you as well.</string>+    <!-- PersonDetailSheet, own entry: shown in place of the list when the user has no connected family members to choose from. Sentence -->+    <string name="poweroff_grant_no_peers">Once you are connected to someone, you can choose them here.</string>  </resources>
findfamily/src/test/java/com/vayunmathur/findfamily/tracker/PoweredOffRecoveryTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/PoweredOffRecoveryTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/PoweredOffRecoveryTest.ktnew file mode 100644index 0000000000..9ef39ba355--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/PoweredOffRecoveryTest.kt@@ -0,0 +1,322 @@+package com.vayunmathur.findfamily.tracker++import com.vayunmathur.e2ee.E2eeKeyStore+import kotlinx.coroutines.runBlocking+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Pure-JVM tests for who can decrypt a powered-off phone's sightings.+ *+ * This is the security boundary of the whole feature, and every property it has is a property of+ * the roster arithmetic rather than of the crypto: the ML-KEM library is assumed to work, but+ * "default nobody", "grant does not widen past the named peer", "revoke actually rotates" and+ * "the identity key is never touched" are all decisions made here and are all silent when wrong.+ * A grant that leaked to the whole roster would look identical in the UI to a correct one.+ *+ * [PoweredOffRecovery] takes its keypair source as a parameter precisely so this file can run+ * without the native ML-KEM library, which a JVM unit test cannot load.+ */+class PoweredOffRecoveryTest {++    /**+     * In-memory [E2eeKeyStore] that also records every key it is asked for, so a test can assert+     * on what was *not* touched.+     */+    private class FakeKeyStore : E2eeKeyStore {+        val values = HashMap<String, ByteArray>()+        val namesTouched = LinkedHashSet<String>()++        override suspend fun getBytes(name: String): ByteArray? {+            namesTouched += name+            return values[name]+        }++        override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {+            namesTouched += name+            if (onlyIfAbsent && values.containsKey(name)) return+            values[name] = value+        }+    }++    /** Distinct, deterministic, obviously-fake keypairs. Counts how many times it was called. */+    private class CountingMint {+        var calls = 0+            private set++        operator fun invoke(): RecoveryKeypair {+            calls+++            return RecoveryKeypair(+                publicBundle = "pub-$calls".encodeToByteArray(),+                kemPrivate = "priv-$calls".encodeToByteArray(),+            )+        }+    }++    private val ks = FakeKeyStore()+    private val mint = CountingMint()+    private val recovery = PoweredOffRecovery(ks, mint::invoke)++    // --- default state -------------------------------------------------------------------++    @Test+    fun nobodyIsGrantedByDefault() = runBlocking {+        // The single most important assertion in this file. The feature is useless without a+        // grant and dangerous if one appears on its own, so "off" has to be the state you get+        // for free rather than the state you have to arrange.+        assertEquals(emptySet<Long>(), recovery.grantees())+        assertFalse(recovery.isGranted(1234L))+        assertEquals(0, mint.calls, "no keypair is minted just by asking who can read")+    }++    @Test+    fun enablingTheBeaconDoesNotEntitleAnyone() = runBlocking {+        recovery.ensure()+        assertEquals(emptySet<Long>(), recovery.grantees())+    }++    // --- the identity key is out of bounds -----------------------------------------------++    @Test+    fun neverReadsOrWritesTheIdentityPrivateKey() = runBlocking {+        // The whole point of a separate recovery keypair: `ff_pqcKemPriv` decrypts every live+        // location this user publishes to anyone, forever, so it must never be what gets shared.+        // Asserting on the key *names* catches a future edit that quietly reaches for it again,+        // which reviewing a diff for `Pqc.decrypt` call sites would not.+        recovery.ensure()+        recovery.grant(11L)+        recovery.revoke(11L)+        recovery.clear()++        assertFalse("ff_pqcKemPriv" in ks.namesTouched, "identity private key must be untouchable")+        assertTrue(+            ks.namesTouched.all { it.startsWith("ff_pofrec_") },+            "recovery state must stay in its own namespace, saw ${ks.namesTouched}",+        )+        // And nothing it stores may be the identity key by value either.+        assertFalse(ks.values.values.any { it.decodeToString() == "ff_pqcKemPriv" })+    }++    @Test+    fun recoveryKeysDoNotCollideWithThePerPeerSightingStore() {+        // PoweredOffKeyStore owns `ff_pof_secret_$id` / `ff_pof_priv_$id` in the same DataStore.+        // A prefix clash would have one silently overwrite the other, and the symptom would be+        // zero sightings with no error anywhere — the failure this feature keeps producing.+        val peerId = 42L+        assertFalse("ff_pofrec_priv".startsWith("ff_pof_priv_$peerId"))+        assertFalse("ff_pof_priv_$peerId".startsWith("ff_pofrec_"))+        assertFalse("ff_pof_secret_$peerId".startsWith("ff_pofrec_"))+    }++    // --- grant ---------------------------------------------------------------------------++    @Test+    fun grantAddsOnlyTheNamedPeer() = runBlocking {+        val d = recovery.grant(7L)+        assertEquals(setOf(7L), recovery.grantees())+        // Addressed to the new grantee alone. If this ever returned the whole roster it would+        // still "work", so only a test says otherwise.+        assertEquals(setOf(7L), d.to)+        assertEquals(null, d.revoked)+    }++    @Test+    fun grantingASecondPeerLeavesTheFirstAloneAndDoesNotRotate() = runBlocking {+        val first = recovery.grant(7L)+        val second = recovery.grant(8L)++        assertEquals(setOf(7L, 8L), recovery.grantees())+        // Same key: the existing grantee is entitled to it, so churning it would cost them a+        // redelivery for nothing.+        assertTrue(first.kemPrivate.contentEquals(second.kemPrivate))+        assertTrue(first.publicBundle.contentEquals(second.publicBundle))+        assertEquals(first.epoch, second.epoch)+        assertEquals(1, mint.calls)+        // The second grant is not addressed to the first peer.+        assertEquals(setOf(8L), second.to)+    }++    @Test+    fun regrantingTheSamePeerIsIdempotentButStillRedelivers() = runBlocking {+        recovery.grant(7L)+        val again = recovery.grant(7L)+        assertEquals(setOf(7L), recovery.grantees())+        // The ordinary reason to re-grant is that the first delivery never arrived, so returning+        // nothing to send would make the retry a no-op.+        assertEquals(setOf(7L), again.to)+        assertEquals(1, mint.calls, "re-granting must not rotate")+    }++    @Test+    fun grantDistributesThePrivateHalfAndTheMatchingPublicHalf() = runBlocking {+        val d = recovery.grant(7L)+        val keys = recovery.ensure()+        assertTrue(d.kemPrivate.contentEquals(keys.kemPrivate))+        assertTrue(d.publicBundle.contentEquals(keys.publicBundle))+        assertEquals(1L, d.epoch, "first keypair is epoch 1")+    }++    @Test+    fun peerZeroIsRejected() = runBlocking {+        // 0 is the "no identity yet" sentinel used throughout Networking; granting to it would+        // file the key under a userid no peer can ever be.+        assertFailsWith<IllegalArgumentException> { runBlocking { recovery.grant(0L) } }+        assertEquals(emptySet<Long>(), recovery.grantees())+    }++    // --- revoke and rotation -------------------------------------------------------------++    @Test+    fun revokeRemovesThePeerAndRotatesTheKeypair() = runBlocking {+        val granted = recovery.grant(7L)+        val revoked = recovery.revoke(7L)++        assertEquals(emptySet<Long>(), recovery.grantees())+        assertFalse(recovery.isGranted(7L))+        assertEquals(2, mint.calls, "revoke must rotate")+        assertFalse(+            granted.kemPrivate.contentEquals(revoked.kemPrivate),+            "the revoked peer's key must not still be the live one",+        )+    }++    @Test+    fun afterRevokeFindersSealToAKeyTheRevokedPeerDoesNotHave() = runBlocking {+        // The property revocation actually buys, stated exactly: the public half the relay will+        // hand to finders from now on is not the one whose private half was handed out.+        val granted = recovery.grant(7L)+        val afterRevoke = recovery.revoke(7L)+        assertFalse(granted.publicBundle.contentEquals(afterRevoke.publicBundle))+        assertTrue(afterRevoke.publicBundle.contentEquals(recovery.ensure().publicBundle))+    }++    @Test+    fun revokeRedistributesToTheRemainingGranteesAndNotToTheRevokedPeer() = runBlocking {+        recovery.grant(7L)+        recovery.grant(8L)+        recovery.grant(9L)++        val d = recovery.revoke(8L)++        assertEquals(setOf(7L, 9L), recovery.grantees())+        // Rotating without redelivering would revoke the innocent peers too, and they would keep+        // polling with a dead key and finding nothing — silently, like everything else here.+        assertEquals(setOf(7L, 9L), d.to)+        assertFalse(8L in d.to)+        assertEquals(8L, d.revoked)+    }++    @Test+    fun revokingTheLastGranteeStillRotatesAndAddressesNobody() = runBlocking {+        recovery.grant(7L)+        val d = recovery.revoke(7L)+        assertEquals(emptySet<Long>(), d.to)+        assertEquals(7L, d.revoked)+        assertEquals(2, mint.calls)+    }++    @Test+    fun revokingSomeoneWhoWasNeverGrantedStillRotates() = runBlocking {+        recovery.grant(7L)+        val d = recovery.revoke(999L)+        // Documented behaviour: the caller reached for revoke. A spare rotation costs one+        // registration; second-guessing them could leave a key live that they believe is dead.+        assertEquals(2, mint.calls)+        assertEquals(setOf(7L), recovery.grantees())+        assertEquals(setOf(7L), d.to)+    }++    @Test+    fun epochIsMonotonicAcrossRotations() = runBlocking {+        assertEquals(0L, recovery.epoch(), "no keypair yet")+        recovery.ensure()+        assertEquals(1L, recovery.epoch())+        recovery.grant(7L)+        assertEquals(1L, recovery.epoch(), "granting does not rotate")+        assertEquals(2L, recovery.revoke(7L).epoch)+        assertEquals(3L, recovery.revoke(8L).epoch)+        // A peer must be able to reject a stale grant that overtakes a fresh one on the wire.+        assertEquals(3L, recovery.epoch())+    }++    // --- clear / persistence ---------------------------------------------------------------++    @Test+    fun clearForgetsTheRosterSoTurningTheBeaconBackOnDoesNotReEntitleAnyone() = runBlocking {+        recovery.grant(7L)+        recovery.grant(8L)+        recovery.clear()++        assertEquals(emptySet<Long>(), recovery.grantees())+        // A blanked keypair must be re-minted, not read back as a zero-length private key.+        val fresh = recovery.ensure()+        assertEquals(2, mint.calls)+        assertTrue(fresh.kemPrivate.isNotEmpty())+        assertEquals(emptySet<Long>(), recovery.grantees())+    }++    @Test+    fun rosterAndKeypairSurviveANewInstanceOverTheSameStore() = runBlocking {+        recovery.grant(7L)+        val original = recovery.ensure()++        val reopened = PoweredOffRecovery(ks, mint::invoke)+        assertEquals(setOf(7L), reopened.grantees())+        assertTrue(reopened.ensure().kemPrivate.contentEquals(original.kemPrivate))+        assertEquals(1, mint.calls, "reopening must not mint a second keypair")+    }++    @Test+    fun rosterRoundTripsManyPeers() = runBlocking {+        val peers = setOf(1L, -5L, Long.MAX_VALUE, 987654321L)+        for (p in peers) recovery.grant(p)+        assertEquals(peers, PoweredOffRecovery(ks, mint::invoke).grantees())+        // Negative ids are real: userids are signed longs on this side of the wire.+        assertTrue(recovery.grantees().isNotEmpty())+    }++    // --- what a grant is signed over -------------------------------------------------------++    @Test+    fun signingBytesBindTheOwnerTheRecipientAndTheEpoch() {+        val secret = ByteArray(32) { 1 }+        val priv = ByteArray(8) { 2 }+        val base = poweredOffGrantSigningBytes(10L, 20L, 3L, secret, priv)++        // Owner: without this, a peer could deliver keys claiming to be a different family+        // member, and every sighting decrypted from them would be drawn as that person's phone.+        assertFalse(base.contentEquals(poweredOffGrantSigningBytes(11L, 20L, 3L, secret, priv)))+        // Recipient: without this, a grant lifted off one peer replays at another.+        assertFalse(base.contentEquals(poweredOffGrantSigningBytes(10L, 21L, 3L, secret, priv)))+        // Epoch: without this, a signature from an old grant re-authenticates a rolled-back one.+        assertFalse(base.contentEquals(poweredOffGrantSigningBytes(10L, 20L, 4L, secret, priv)))+        // And the key material itself, obviously.+        assertFalse(base.contentEquals(poweredOffGrantSigningBytes(10L, 20L, 3L, secret, ByteArray(8) { 9 })))+        assertFalse(base.contentEquals(poweredOffGrantSigningBytes(10L, 20L, 3L, ByteArray(32) { 9 }, priv)))+    }++    @Test+    fun signingBytesAreDeterministicAndDomainSeparated() {+        val secret = ByteArray(4) { 1 }+        val priv = ByteArray(4) { 2 }+        val a = poweredOffGrantSigningBytes(10L, 20L, 3L, secret, priv)+        assertTrue(a.contentEquals(poweredOffGrantSigningBytes(10L, 20L, 3L, secret, priv)))+        // A signature over these bytes must not be reusable as a signature over anything else+        // this identity signs.+        assertTrue(a.decodeToString().startsWith("ffpofgrant1"))+    }++    @Test+    fun signingBytesCannotBeConfusedByShiftingTheFieldBoundary() {+        // The two variable-length fields are separated by an explicit length, so the same bytes+        // split differently between secret and key cannot produce the same signing input. Without+        // that prefix these two would be byte-identical and one signature would cover both.+        val a = poweredOffGrantSigningBytes(1L, 2L, 3L, ByteArray(4) { 7 }, ByteArray(8) { 7 })+        val b = poweredOffGrantSigningBytes(1L, 2L, 3L, ByteArray(8) { 7 }, ByteArray(4) { 7 })+        assertEquals(a.size, b.size)+        assertFalse(a.contentEquals(b))+    }+}
library/map/src/main/java/com/vayunmathur/library/map/Projection.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt b/library/map/src/main/java/com/vayunmathur/library/map/Projection.ktindex 0344d9ac7e..38a9f08021 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt@@ -89,8 +89,8 @@ class Projection internal constructor(      *      * The [queryRenderedFeatures]-equivalent the maps `FeatureSource` adapter      * needs: `source = { box, layerIds -> projection.queryRenderedLabels(box,-     * layerIds).map { it.toFeature1() } }`. Empty until a rendered surface-     * registers its native pick (and when nothing placed hits).+     * layerIds).map { it.toFeature1() } }`. Registered by `VulkanMapSurface`, so this+     * is empty only when nothing placed is under the query box.      */     fun queryRenderedLabels(box: DpRect, layerIds: Set<String>): List<PlacedLabel> =         labelQuery?.invoke(box, layerIds) ?: emptyList()
library/map/src/main/rust/src/bridge.rs
diff --git a/library/map/src/main/rust/src/bridge.rs b/library/map/src/main/rust/src/bridge.rsindex a4ba1859a4..9a16819b01 100644--- a/library/map/src/main/rust/src/bridge.rs+++ b/library/map/src/main/rust/src/bridge.rs@@ -1,4 +1,4 @@-//! The JNI surface: five entry points, and nothing per-feature or per-vertex.+//! The JNI surface: ten entry points, and nothing per-feature or per-vertex. //! //! Kotlin creates and destroys the renderer for a `Surface`, resizes it, tells it whether //! the device is online, and hands it **one camera snapshot per frame**. Tile selection,
library/map/src/main/rust/src/style/paint.rs
diff --git a/library/map/src/main/rust/src/style/paint.rs b/library/map/src/main/rust/src/style/paint.rsindex d9183a97b2..fa526781be 100644--- a/library/map/src/main/rust/src/style/paint.rs+++ b/library/map/src/main/rust/src/style/paint.rs@@ -1576,6 +1576,27 @@ mod tests {             }             admitted.sort_unstable();             drawn.sort_unstable();+            // Kinds we deliberately do not draw, and why. Checked explicitly so the assertion+            // below still catches an *accidental* divergence from upstream, which is what it is+            // for — a silent one would mean a kind quietly stopped rendering.+            //+            // `protected_area` and `nature_reserve` are the tags the world's MARINE protected+            // areas carry. The sea has no geometry, so nothing is drawn over them, and on a planet+            // build they painted green across open water — the reported bug. Deriving sea geometry+            // to cover them was attempted twice and failed twice; see `mamaps_build`'s+            // `tiler::add_ocean` for both failure modes. Not drawing them is the fix that works.+            //+            // The cost, stated plainly: a protected area or nature reserve *on land* is no longer+            // green. Restore them here the day the sea can paint over them.+            const NOT_DRAWN: &[&str] = &["protected_area", "nature_reserve"];+            let (skipped, admitted): (Vec<String>, Vec<String>) =+                admitted.into_iter().partition(|k| NOT_DRAWN.contains(&k.as_str()));+            for kind in &skipped {+                assert!(+                    !drawn.contains(kind),+                    "`{kind}` is in NOT_DRAWN but a flat layer still draws it",+                );+            }             // Every kind exactly once: two flat layers claiming the same kind would draw it             // twice, in whichever colour came last.             assert_eq!(
library/map/src/main/rust/src/tile/source.rs
diff --git a/library/map/src/main/rust/src/tile/source.rs b/library/map/src/main/rust/src/tile/source.rsindex 8ae5c56137..e8090f648b 100644--- a/library/map/src/main/rust/src/tile/source.rs+++ b/library/map/src/main/rust/src/tile/source.rs@@ -87,6 +87,11 @@ pub struct CachingRangeReader<F: RangeFetcher> {     /// Set from Kotlin, which owns the `ConnectivityManager`. When offline the network is     /// not attempted at all and a stale entry is served instead.     online: std::sync::atomic::AtomicBool,+    /// False until the first read of the session has gone to the network.+    ///+    /// That read is the archive header, and it is the one entry the cache must not answer from+    /// itself — see the note in [`RangeReader::read`].+    prefix_checked: std::sync::atomic::AtomicBool, }  impl<F: RangeFetcher> CachingRangeReader<F> {@@ -96,6 +101,7 @@ impl<F: RangeFetcher> CachingRangeReader<F> {             cache,             fetcher,             online: std::sync::atomic::AtomicBool::new(true),+            prefix_checked: std::sync::atomic::AtomicBool::new(false),         }     } @@ -123,9 +129,25 @@ impl<F: RangeFetcher> RangeReader for CachingRangeReader<F> {         let range = format!("bytes={}-{}", offset, offset + length as u64 - 1);         let key = RangeCache::key(&self.url, &range); +        // The archive header decides whether every other entry is still valid, so it cannot be+        // served from the cache it is meant to validate. Once per session the first read — which+        // is always the header, because nothing can be located without it — goes to the network.+        //+        // Without this the staleness is self-consistent: a cached prefix reports the *previous*+        // build's id, `basemap_origin` therefore matches, the cache is kept, and every leaf index+        // in it keeps addressing the previous build's byte offsets. The archive is republished+        // under a stable URL by design, so nothing else ever catches it, and the entry only+        // expires on the 24-hour refresh interval. Republishing twice in an afternoon meant a map+        // built from two different archives at once: bodies that would not inflate, and a+        // coastline drawn from offsets that had moved.+        //+        // One small request per app start, and only when online.+        let first = !self.prefix_checked.swap(true, std::sync::atomic::Ordering::Relaxed);+        let revalidate = first && self.is_online();+         let cached = self.cache.read(&key);         if let Some(entry) = &cached {-            if self.cache.is_fresh(entry) || !self.is_online() {+            if !revalidate && (self.cache.is_fresh(entry) || !self.is_online()) {                 return Ok(entry.body.clone());             }         }@@ -341,8 +363,54 @@ mod tests {         }         // A second reader over the same directory: the entry is on disk and fresh.         let r = reader(&f.dir, clock, Fake::ok(vec![9u8; 16]));-        assert_eq!(r.read(0, 16).unwrap(), vec![7u8; 16], "the cached bytes, not the new ones");-        assert!(r.fetcher.ranges.borrow().is_empty(), "no request at all");+        // The first read of a session always revalidates — it is the archive header, and a stale+        // one would validate the very cache it is meant to invalidate.+        assert_eq!(r.read(0, 16).unwrap(), vec![9u8; 16], "the header is refetched");+        assert_eq!(r.fetcher.ranges.borrow().len(), 1);+        // Everything after it is served from the cache.+        assert_eq!(r.read(0, 16).unwrap(), vec![9u8; 16], "the cached bytes");+        assert_eq!(r.fetcher.ranges.borrow().len(), 1, "no second request");+    }++    /// The archive header cannot be answered from the cache it decides the fate of.+    ///+    /// `basemap_origin` keys the cache on the archive's `build_id`, which is read from the header.+    /// If the header itself comes from the cache it reports the *previous* build's id, the marker+    /// matches, and every leaf index in the cache goes on addressing byte offsets from an archive+    /// that no longer exists. Nothing else catches it, because the archive is deliberately+    /// republished under the same URL, so the entry survives until the 24-hour refresh — which in+    /// practice meant a map drawn from two different archives at once.+    #[test]+    fn the_first_read_of_a_session_bypasses_a_fresh_cache() {+        let f = Fixture::new("prefix");+        let clock = Arc::new(AtomicU64::new(1_000_000));+        {+            let r = reader(&f.dir, clock.clone(), Fake::ok(vec![1u8; 16]));+            assert_eq!(r.read(0, 16).unwrap(), vec![1u8; 16]);+        }+        // Same directory, same clock, so the entry is unambiguously fresh — and the archive has+        // been republished behind it.+        let r = reader(&f.dir, clock, Fake::ok(vec![2u8; 16]));+        assert_eq!(+            r.read(0, 16).unwrap(),+            vec![2u8; 16],+            "a fresh cache must not hide a republished archive from the header read",+        );+    }++    /// Offline, the rule reverses: a stale header beats no map at all.+    #[test]+    fn the_first_read_still_uses_the_cache_when_offline() {+        let f = Fixture::new("prefix_offline");+        let clock = Arc::new(AtomicU64::new(1_000_000));+        {+            let r = reader(&f.dir, clock.clone(), Fake::ok(vec![3u8; 16]));+            assert_eq!(r.read(0, 16).unwrap(), vec![3u8; 16]);+        }+        let r = reader(&f.dir, clock, Fake::ok(vec![4u8; 16]));+        r.set_online(false);+        assert_eq!(r.read(0, 16).unwrap(), vec![3u8; 16], "the cached header");+        assert!(r.fetcher.ranges.borrow().is_empty(), "and no request attempted");     }      #[test]
library/map/src/main/rust/style/basemap.flat.json
diff --git a/library/map/src/main/rust/style/basemap.flat.json b/library/map/src/main/rust/style/basemap.flat.jsonindex e67c11b01c..957dba7472 100644--- a/library/map/src/main/rust/style/basemap.flat.json+++ b/library/map/src/main/rust/style/basemap.flat.json@@ -88,8 +88,6 @@         "national_park",         "park",         "cemetery",-        "protected_area",-        "nature_reserve",         "forest",         "golf_course"       ],
library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.kt
diff --git a/library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.kt b/library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.ktindex 5dd5f8c1ec..4c7fd5adc5 100644--- a/library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.kt+++ b/library/room/src/main/java/com/vayunmathur/library/room/SqlCipher.kt@@ -137,6 +137,25 @@ private fun <T : RoomDatabase> Context.openRoomDatabase(      builder.setDriver(SQLCipherDriver(password.toByteArray(Charsets.UTF_8), null, null)) +    // One connection, not Room's default pool of five.+    //+    // Room picks the pool from the journal mode in `RoomDatabase.Builder.build()`: TRUNCATE gets+    // `SingleConnection`, anything else - including the AUTOMATIC default, which resolves to WAL -+    // gets `MultipleConnection(4, 1)`. That is fine for plain SQLite, where opening a connection is+    // cheap, but SQLCipher derives the page key on every open, and at the default 256,000 PBKDF2+    // iterations that is on the order of a second each. Five of them is the several-second blank+    // screen on a cold start.+    //+    // This is a restoration rather than a new tuning decision: before the Room 3 migration the+    // builder set `setJournalMode(TRUNCATE)`, which under Room 3 means exactly this pool. The+    // migration swapped the open-helper for the driver and dropped that line, silently turning one+    // key derivation into five. Keeping WAL and asking for a single connection explicitly is+    // strictly better than going back to TRUNCATE, which would also slow every write down.+    //+    // The cost is that reads no longer run concurrently with a write. These are single-user apps+    // with small databases, and it is what they did for their whole history before the migration.+    builder.setSingleConnectionPool()+     return builder.build() } 
library/src/main/java/com/vayunmathur/library/util/Navigation.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/Navigation.kt b/library/src/main/java/com/vayunmathur/library/util/Navigation.ktindex ffc19ed39c..bb981ae6aa 100644--- a/library/src/main/java/com/vayunmathur/library/util/Navigation.kt+++ b/library/src/main/java/com/vayunmathur/library/util/Navigation.kt@@ -3,6 +3,7 @@ package com.vayunmathur.library.util import androidx.compose.animation.AnimatedVisibilityScope import androidx.compose.animation.BoundsTransform import androidx.compose.animation.ContentTransform+import androidx.compose.animation.EnterExitState import androidx.compose.animation.ExperimentalSharedTransitionApi import androidx.compose.animation.SharedTransitionLayout import androidx.compose.animation.SharedTransitionScope@@ -642,6 +643,24 @@ fun Modifier.expandFromLine(): Modifier { fun isNavMorphing(): Boolean =     LocalSharedTransitionScope.current?.isTransitionActive == true +/**+ * True while this destination is being pushed away from, false while it is being returned to.+ *+ * For a graph that loops, where an element's counterpart is not the one it came from. Music is the+ * case this exists for: tapping a song carries it from the list row up to the now-playing screen,+ * but coming back it belongs in the mini-player, not in the row. Both the row and the mini-player+ * are composed the whole time, so a static key would give the morph two origins to choose between;+ * asking which way the entry is travelling picks exactly one.+ *+ * Only meaningful during a transition. Outside one - and outside a [MainNavigation] - it is false,+ * which reads as "arriving", so a screen sitting still keeps whichever element it settled on.+ */+@Composable+fun isNavLeaving(): Boolean {+    val animated = LocalEntryAnimatedScope.current ?: return false+    return animated.transition.targetState == EnterExitState.PostExit+}+ fun DialogPage() = DialogSceneStrategy.dialog()  @OptIn(ExperimentalMaterial3AdaptiveApi::class)
library/ui/src/main/java/com/vayunmathur/library/ui/ListPage.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/ListPage.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/ListPage.ktindex 237c3d9588..a12321815a 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/ListPage.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/ListPage.kt@@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState@@ -31,32 +32,111 @@ import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.DatabaseItem import kotlinx.coroutines.launch +/**+ * A searchable, sortable list screen with the standard bar, FAB and row layout.+ *+ * Only [EditPage] needs reifying - to recognise the edit destination on the back stack - so this+ * is a thin inline shell that lowers it to a predicate and hands everything else to+ * [ListPageContent]. Keeping the body out of here is deliberate: an `inline` composable has no+ * restart scope, so if the `Scaffold` and `LazyColumn` lived here they would be inlined into the+ * caller and recompose whenever *anything* the caller reads changes - including the search field's+ * own state, which lives inside this function. That turned one keystroke into a full re-filter,+ * re-sort and re-composition of the whole list.+ *+ * [sortOrder] must be a stable instance. A `Comparator` built inline at the call site is a new+ * object on every recomposition, which invalidates the memoised sort and re-sorts the entire list;+ * wrap it in `remember { }`.+ */ @Composable-inline fun <reified T : DatabaseItem, Route : NavKey, reified EditPage : Route> ListPage(+inline fun <T : DatabaseItem, Route : NavKey, reified EditPage : Route> ListPage(     backStack: NavBackStack<Route>,     data: List<T>,     title: String,-    crossinline headlineContent: @Composable (T) -> Unit,-    crossinline supportingContent: @Composable (T) -> Unit,-    crossinline viewPage: suspend (id: Long) -> Route,+    noinline headlineContent: @Composable (T) -> Unit,+    noinline supportingContent: @Composable (T) -> Unit,+    noinline viewPage: suspend (id: Long) -> Route,     scrollBehavior: TopAppBarScrollBehavior,     noinline editPage: (() -> Route)? = null,     settingsPage: Route? = null,-    crossinline otherActions: @Composable () -> Unit = {},-    crossinline leadingContent: @Composable (T) -> Unit = {},-    crossinline trailingContent: @Composable (T) -> Unit = {},+    noinline otherActions: @Composable () -> Unit = {},+    noinline leadingContent: @Composable (T) -> Unit = {},+    noinline trailingContent: @Composable (T) -> Unit = {},     noinline itemModifier: @Composable (T) -> Modifier = { Modifier },     noinline itemColors: @Composable (T) -> ListItemColors = { ListItemDefaults.colors() },     searchEnabled: Boolean = false,     sortOrder: Comparator<T>? = null,-    crossinline searchString: (T) -> String = { it.toString() },+    noinline searchString: (T) -> String = { it.toString() },     noinline bottomBar: @Composable () -> Unit = {},     noinline fab: (@Composable () -> Unit)? = null,+    loading: Boolean = false,+) = ListPageContent(+    backStack = backStack,+    data = data,+    title = title,+    headlineContent = headlineContent,+    supportingContent = supportingContent,+    viewPage = viewPage,+    scrollBehavior = scrollBehavior,+    editPage = editPage,+    settingsPage = settingsPage,+    otherActions = otherActions,+    leadingContent = leadingContent,+    trailingContent = trailingContent,+    itemModifier = itemModifier,+    itemColors = itemColors,+    searchEnabled = searchEnabled,+    sortOrder = sortOrder,+    searchString = searchString,+    bottomBar = bottomBar,+    fab = fab,+    loading = loading,+    isEditPage = { it is EditPage },+)++/**+ * The body of [ListPage]. Not inline, so it owns a restart scope and the search field's state, and+ * skips when its caller recomposes for unrelated reasons.+ *+ * Internal - it exists only because [ListPage] has to stay inline to reify its edit route, and a+ * public inline function cannot call a private one.+ */+@PublishedApi+@Composable+internal fun <T : DatabaseItem, Route : NavKey> ListPageContent(+    backStack: NavBackStack<Route>,+    data: List<T>,+    title: String,+    headlineContent: @Composable (T) -> Unit,+    supportingContent: @Composable (T) -> Unit,+    viewPage: suspend (id: Long) -> Route,+    scrollBehavior: TopAppBarScrollBehavior,+    isEditPage: (Any?) -> Boolean,+    editPage: (() -> Route)? = null,+    settingsPage: Route? = null,+    otherActions: @Composable () -> Unit = {},+    leadingContent: @Composable (T) -> Unit = {},+    trailingContent: @Composable (T) -> Unit = {},+    itemModifier: @Composable (T) -> Modifier = { Modifier },+    itemColors: @Composable (T) -> ListItemColors = { ListItemDefaults.colors() },+    searchEnabled: Boolean = false,+    sortOrder: Comparator<T>? = null,+    searchString: (T) -> String = { it.toString() },+    bottomBar: @Composable () -> Unit = {},+    fab: (@Composable () -> Unit)? = null,+    loading: Boolean = false, ) {     var searchQuery by remember { mutableStateOf("") }-    val displayed = remember(data, searchQuery, sortOrder) {-        val filtered = if (searchQuery.isBlank()) data-        else data.filter { searchString(it).contains(searchQuery, true) }+    // Built once per data change, not once per keystroke. `searchString` concatenates several+    // fields, and doing that (plus a case-insensitive `contains`, which lowercases as it goes) for+    // every row on every keypress is a whole-list pass between two frames of typing.+    val haystacks = remember(data, searchString) {+        if (!searchEnabled) emptyList() else data.map { searchString(it).lowercase() }+    }+    val displayed = remember(data, haystacks, searchQuery, sortOrder) {+        val query = searchQuery.trim().lowercase()+        val filtered =+            if (query.isEmpty()) data+            else data.filterIndexed { index, _ -> haystacks[index].contains(query) }         if (sortOrder != null) filtered.sortedWith(sortOrder) else filtered     } @@ -98,7 +178,7 @@ inline fun <reified T : DatabaseItem, Route : NavKey, reified EditPage : Route>         floatingActionButton = {             Column {                 fab?.invoke()-                if (editPage != null && backStack.backStack.lastOrNull() !is EditPage) {+                if (editPage != null && !isEditPage(backStack.backStack.lastOrNull())) {                     FloatingActionButton(onClick = { backStack.add(editPage()) }) {                         IconAdd()                     }@@ -106,12 +186,19 @@ inline fun <reified T : DatabaseItem, Route : NavKey, reified EditPage : Route>             }         }     ) { paddingValues ->+        // An empty list and a list that has not arrived yet are both "no items", and rendering+        // them the same way means a slow first load reads as an empty vault/library rather than+        // as work in progress.+        if (loading && displayed.isEmpty()) {+            LoadingState(Modifier.fillMaxSize().padding(paddingValues))+            return@Scaffold+        }         LazyColumn(             state = listState,             modifier = Modifier.fillMaxSize(),             contentPadding = paddingValues         ) {-            items(displayed, key = { it.id }) { item ->+            items(displayed, key = { it.id }, contentType = { it::class }) { item ->                 val modifier = itemModifier(item)                 ListItem(                     modifier = modifier.clickable {
library/ui/src/main/java/com/vayunmathur/library/ui/RememberClock.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/RememberClock.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/RememberClock.ktnew file mode 100644index 0000000000..363574f803--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/RememberClock.kt@@ -0,0 +1,40 @@+package com.vayunmathur.library.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import kotlin.time.Duration+import kotlin.time.Duration.Companion.seconds+import kotlinx.coroutines.delay++/**+ * A wall clock that ticks every [period], handed back as a getter rather than a value.+ *+ * The return type is the whole point. Obtaining the clock subscribes nobody, so only the scope+ * that *invokes* the getter is invalidated when it ticks. The usual way to get this wrong is+ * `val now by viewModel.ticker.collectAsState()` at the top of a screen: that subscribes the+ * screen, and on a list screen a tick then recomposes every visible row even though only one+ * label in each row shows the time. Call the getter inside the row, slot or draw lambda that+ * actually displays it instead.+ *+ * Ticks land on the [period] boundary rather than being spaced by a plain `delay(period)`, which+ * drifts - a one-second clock spaced that way visibly skips a second every so often.+ *+ * Each call site owns its own coroutine for as long as it is in composition, so a screen picks the+ * period it needs. Prefer that to sharing one fast ticker across screens: a stopwatch showing+ * centiseconds and a world-clock list showing minutes have no business running at the same rate.+ */+@Composable+fun rememberClock(period: Duration = 1.seconds): () -> Long {+    val time = remember { mutableLongStateOf(System.currentTimeMillis()) }+    LaunchedEffect(period) {+        val periodMs = period.inWholeMilliseconds.coerceAtLeast(1)+        while (true) {+            val now = System.currentTimeMillis()+            time.longValue = now+            delay(periodMs - now % periodMs)+        }+    }+    return remember(time) { { time.longValue } }+}
library/updateengine-stubs/build.gradle.kts
diff --git a/library/updateengine-stubs/build.gradle.kts b/library/updateengine-stubs/build.gradle.ktsnew file mode 100644index 0000000000..6af6dc2ea0--- /dev/null+++ b/library/updateengine-stubs/build.gradle.kts@@ -0,0 +1,20 @@+plugins {+    id("common-conventions-library")+}++// Compile-only stubs for the framework's @SystemApi `android.os.UpdateEngine` and+// `android.os.UpdateEngineCallback` — the A/B slot writer that applies an OTA payload.+//+// Both are `@SystemApi`, so they exist at runtime on a MAOS build but are absent from the+// public SDK. Depend on this with `compileOnly`; it must NOT be packaged into any APK.+//+// Only the surface :updater actually calls is declared. A stub is a compile-time promise about+// the runtime class, and every method here is one more thing that has to stay true.+//+// Signatures are copied verbatim from+//   frameworks/base/core/java/android/os/UpdateEngine.java+//   frameworks/base/core/java/android/os/UpdateEngineCallback.java+// in the MAOS tree. If they drift, the failure is a runtime NoSuchMethodError at the moment an+// update is applied — the worst possible time, and nothing in this repo can catch it for us.+// The constant VALUES matter as much as the signatures: javac inlines `static final int`, so a+// wrong number here is silently baked into the APK.
library/updateengine-stubs/src/main/java/android/os/UpdateEngine.java
diff --git a/library/updateengine-stubs/src/main/java/android/os/UpdateEngine.java b/library/updateengine-stubs/src/main/java/android/os/UpdateEngine.javanew file mode 100644index 0000000000..f7d6e0ed69--- /dev/null+++ b/library/updateengine-stubs/src/main/java/android/os/UpdateEngine.java@@ -0,0 +1,102 @@+package android.os;++/**+ * Compile-only stub. See the module's build.gradle.kts.+ *+ * <p>Mirrors the surface of the real {@code @SystemApi android.os.UpdateEngine} that+ * {@code :updater} calls. Behaviour that is NOT visible from these signatures but that callers+ * must handle, taken from the AOSP source:+ *+ * <ul>+ *   <li>The constructor binds to the {@code android.os.UpdateEngineService} binder. It throws+ *       {@link IllegalStateException} when that service is unavailable, which is the case on+ *       any build where the caller is not privileged.+ *   <li>{@link #applyPayload} is asynchronous. Completion and failure both arrive on+ *       {@link UpdateEngineCallback#onPayloadApplicationComplete}, never as a thrown exception,+ *       so a caller that only tries/catches will silently believe it succeeded.+ *   <li>Only ONE payload may be applied at a time, process-wide and device-wide. Calling+ *       {@link #applyPayload} while an update is in progress throws+ *       {@link ServiceSpecificException}. {@link #cancel()} or {@link #resetStatus()} first.+ *   <li>{@link #resetStatus()} is only valid when an update has been applied but not yet booted+ *       ({@link UpdateStatusConstants#UPDATED_NEED_REBOOT}); it throws otherwise.+ *   <li>The {@code url} passed to {@link #applyPayload} may be an {@code http(s)://} address —+ *       update_engine streams the payload itself — or a {@code file://} path.+ * </ul>+ */+public class UpdateEngine {++    /**+     * Error codes delivered to+     * {@link UpdateEngineCallback#onPayloadApplicationComplete(int)}.+     *+     * <p>Values are inlined by javac, so they must match AOSP exactly. Note the gap: there is+     * no 2 or 3, and the tail jumps to 51.+     */+    public static final class ErrorCodeConstants {+        public static final int SUCCESS = 0;+        public static final int ERROR = 1;+        public static final int FILESYSTEM_COPIER_ERROR = 4;+        public static final int POST_INSTALL_RUNNER_ERROR = 5;+        public static final int PAYLOAD_MISMATCHED_TYPE_ERROR = 6;+        public static final int INSTALL_DEVICE_OPEN_ERROR = 7;+        public static final int KERNEL_DEVICE_OPEN_ERROR = 8;+        public static final int DOWNLOAD_TRANSFER_ERROR = 9;+        public static final int PAYLOAD_HASH_MISMATCH_ERROR = 10;+        public static final int PAYLOAD_SIZE_MISMATCH_ERROR = 11;+        public static final int DOWNLOAD_PAYLOAD_VERIFICATION_ERROR = 12;+        public static final int PAYLOAD_TIMESTAMP_ERROR = 51;+        public static final int UPDATED_BUT_NOT_ACTIVE = 52;+        public static final int NOT_ENOUGH_SPACE = 60;+        public static final int DEVICE_CORRUPTED = 61;+    }++    /** Status values delivered to {@link UpdateEngineCallback#onStatusUpdate(int, float)}. */+    public static final class UpdateStatusConstants {+        public static final int IDLE = 0;+        public static final int CHECKING_FOR_UPDATE = 1;+        public static final int UPDATE_AVAILABLE = 2;+        public static final int DOWNLOADING = 3;+        public static final int VERIFYING = 4;+        public static final int FINALIZING = 5;+        public static final int UPDATED_NEED_REBOOT = 6;+        public static final int REPORTING_ERROR_EVENT = 7;+        public static final int ATTEMPTING_ROLLBACK = 8;+        public static final int DISABLED = 9;+    }++    public UpdateEngine() {+        throw new UnsupportedOperationException("stub");+    }++    public boolean bind(final UpdateEngineCallback callback, final Handler handler) {+        throw new UnsupportedOperationException("stub");+    }++    public boolean bind(final UpdateEngineCallback callback) {+        throw new UnsupportedOperationException("stub");+    }++    public void applyPayload(String url, long offset, long size, String[] headerKeyValuePairs) {+        throw new UnsupportedOperationException("stub");+    }++    public void cancel() {+        throw new UnsupportedOperationException("stub");+    }++    public void suspend() {+        throw new UnsupportedOperationException("stub");+    }++    public void resume() {+        throw new UnsupportedOperationException("stub");+    }++    public void resetStatus() {+        throw new UnsupportedOperationException("stub");+    }++    public void setShouldSwitchSlotOnReboot(String payloadMetadataFilename) {+        throw new UnsupportedOperationException("stub");+    }+}
library/updateengine-stubs/src/main/java/android/os/UpdateEngineCallback.java
diff --git a/library/updateengine-stubs/src/main/java/android/os/UpdateEngineCallback.java b/library/updateengine-stubs/src/main/java/android/os/UpdateEngineCallback.javanew file mode 100644index 0000000000..313eaa7094--- /dev/null+++ b/library/updateengine-stubs/src/main/java/android/os/UpdateEngineCallback.java@@ -0,0 +1,26 @@+package android.os;++/**+ * Compile-only stub. See the module's build.gradle.kts.+ *+ * <p>Mirrors {@code @SystemApi android.os.UpdateEngineCallback}. Both methods are abstract in+ * the real class, so a subclass must implement both.+ *+ * <p>Notes from the AOSP source that the signatures do not show:+ *+ * <ul>+ *   <li>Callbacks arrive on the {@link Handler} passed to+ *       {@link UpdateEngine#bind(UpdateEngineCallback, Handler)}, or on a binder thread when+ *       the single-argument {@code bind} is used. The single-argument form therefore delivers+ *       {@code onStatusUpdate} OFF the main thread.+ *   <li>{@code onStatusUpdate} fires immediately on bind with the current status, not only on+ *       change — so a freshly bound caller sees the state of an update already in progress.+ *   <li>{@code percent} is 0..1, not 0..100.+ * </ul>+ */+public abstract class UpdateEngineCallback {++    public abstract void onStatusUpdate(int status, float percent);++    public abstract void onPayloadApplicationComplete(int errorCode);+}
maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.ktindex 21896379bb..80c811cb5c 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt@@ -19,17 +19,25 @@ sealed interface SpecificFeature {         val name: String     } +    /**+     * A country. [iso] and [wikipedia] are optional because the basemap archive carries neither:+     * a picked label supplies a name and a position, and the Wikidata round trip that fills these+     * in needs the network. Requiring them meant tapping a country did nothing at all offline.+     */     @Serializable-    data class Admin0Label(@SerialName("iso3166_1") val iso: String, val wikipedia: String, val name: String) : SpecificFeature+    data class Admin0Label(@SerialName("iso3166_1") val iso: String? = null, val wikipedia: String? = null, val name: String) : SpecificFeature+    /** A state or region. [iso] and [wikipedia] are optional for the same reason as [Admin0Label]. */     @Serializable-    data class Admin1Label(@SerialName("iso3166_2") val iso: String, val wikipedia: String, val name: String) : SpecificFeature+    data class Admin1Label(@SerialName("iso3166_2") val iso: String? = null, val wikipedia: String? = null, val name: String) : SpecificFeature     /**      * A city / town. Unlike the country and region labels there is no ISO code to      * key on — the baked `admin_city` layer carries only `name` / `name_en` — so      * the border highlight matches on the name instead.+     *+     * [wikipedia] is optional for the same reason as [Admin0Label].      */     @Serializable-    data class Admin2Label(val wikipedia: String, val name: String) : SpecificFeature+    data class Admin2Label(val wikipedia: String? = null, val name: String) : SpecificFeature     @Serializable     data class Restaurant(override val name: String, val phone: String?, val website: String?, val menu: String?, val openingHours: OpeningHours?,                           override val position: Position): RoutableFeature@@ -93,35 +101,34 @@ fun JsonObject.string(key: String): String? = this[key]?.jsonPrimitive?.content  */ suspend fun parse(feature: Feature1): SpecificFeature? {     val properties = feature.properties ?: return null-    return when(properties.string("kind")) {-        "country" -> {-            // Each of these tags may be missing on tiles for small/disputed-            // territories or when Wikidata returns no result. Skip the feature-            // rather than crashing the bottom sheet.-            val wikidataId = properties.string("wikidata") ?: return null-            val wiki = try { Wikidata.get(wikidataId) } catch (_: Exception) { return null }-            val iso = wiki.getProperty("P297") ?: return null-            val wikipediaUrl = wiki.getWikipedia() ?: return null-            val name = properties.string("name:en") ?: properties.string("name") ?: return null-            SpecificFeature.Admin0Label(iso, wikipediaUrl, name)-        }-        "region" -> {-            val wikidataId = properties.string("wikidata") ?: return null-            val wiki = try { Wikidata.get(wikidataId) } catch (_: Exception) { return null }-            val iso = wiki.getProperty("P300") ?: return null-            val wikipediaUrl = wiki.getWikipedia() ?: return null-            val name = properties.string("name:en") ?: properties.string("name") ?: return null-            SpecificFeature.Admin1Label(iso, wikipediaUrl, name)-        }-        "locality" -> {-            // No ISO lookup: a city has no ISO 3166 code, so the Wikidata round-            // trip is only for the article URL.-            val wikidataId = properties.string("wikidata") ?: return null-            val wiki = try { Wikidata.get(wikidataId) } catch (_: Exception) { return null }-            val wikipediaUrl = wiki.getWikipedia() ?: return null-            val name = properties.string("name:en") ?: properties.string("name") ?: return null-            SpecificFeature.Admin2Label(wikipediaUrl, name)-        }+    // The name is the only thing an admin label truly needs. Everything below it is enrichment+    // from Wikidata, which the basemap archive does not carry and which needs the network.+    //+    // Requiring that enrichment is what made tapping a city, state or country do nothing: a+    // picked label supplies `kind`, `name` and `name:en` and nothing else, so `wikidata` was+    // a

Diff truncated.