Modern Apps git

← Modern-Apps.git

findfamily: detekt clean (300 tests)

Commit
238ed53b00dac061fb29dd791953041c8c948776
Author
Vayun Mathur <[email protected]>
When
2026-11-14 23:16 UTC (21 days ago)
Parents
43864a5
Fix all 72 detekt findings: real KDoc for 61 undocumented public classes; processIncomingFixes (complexity 19, 66 lines, LoopWithTooManyJumpStatements) extracted collectAuthenticatedFix(); InboundSpool loop extracted readNextRecord() returning null on EOF/corrupt records; FindFamilyRepository TooManyFunctions (26) reduced by extracting WaypointStore; Networking object TooManyFunctions (26) reduced by moving PQC key functions to new util/NetworkingPqc.kt as Networking extensions with call sites unchanged; 5 MaxLineLength lines wrapped.

Verified: ./gradlew :findfamily:detekt :findfamily:testDevUnitTest :findfamily:lint --max-workers=32 — BUILD SUCCESSFUL, 300 unit tests pass. No @Suppress added.

Diff

findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.ktindex d341d33cba..01d18073aa 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt@@ -56,7 +56,12 @@ import com.vayunmathur.findfamily.util.Platform import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle +/**+ * FindFamily entry activity: initialises the first-party network client, parses invite+ * and no-show intents, and hosts the permission-gated navigation graph.+ */ class MainActivity : MaActivity() {+    /** Intent-extra keys for launching [MainActivity]. */     companion object {         /** Extra key for launching directly into [Route.UwbRangingPage] via notification tap. */         const val EXTRA_UWB_PEER_ID = "com.vayunmathur.findfamily.EXTRA_UWB_PEER_ID"@@ -226,17 +231,22 @@ fun MissingFeaturesDialog(backStack: NavBackStack<Route>) { }  @Serializable+/** Navigation destinations for FindFamily's single-activity graph. */ sealed interface Route: NavKey {     @Serializable+    /** Map home destination, optionally preselecting a person or waypoint. */     data class MainPage(val selectedUserId: Long? = null, val selectedWaypointId: Long? = null): Route      @Serializable+    /** Dialog for picking the date whose location history to show. */     data class UserPageHistoryDatePicker(val initialDate: LocalDate): Route      @Serializable+    /** Dialog for connecting to a person, optionally prefilled from an invite link. */     data class AddPersonDialog(val id: Long? = null, val fingerprint: String? = null): Route      @Serializable+    /** Dialog for creating a temporary share link. */     data object AddLinkDialog: Route      /** Dev-only (DEV_BUILD): bind a new custom UWB tracker. */@@ -244,6 +254,7 @@ sealed interface Route: NavKey {     data object AddTrackerDialog: Route      @Serializable+    /** Dialog explaining features unavailable on this device. */     data object MissingFeaturesDialog: Route      /** UWB Find Nearby (UWB) screen for the given peer. Full screen (no DialogPage metadata). */
findfamily/src/main/java/com/vayunmathur/findfamily/data/Coord.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/Coord.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/Coord.ktindex 79cdf2f09f..f171dc8d96 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/Coord.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/Coord.kt@@ -6,6 +6,7 @@ import kotlinx.serialization.Serializable import kotlin.math.PI  @Serializable+/** Geographic coordinate in decimal degrees, embedded in Room rows and carried on the wire. */ data class Coord(val lat: Double, val lon: Double)  fun Coord.toGeoPoint() = GeoPoint(lon, lat)
findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.ktindex b3a84325dd..358183f6e1 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt@@ -15,6 +15,7 @@ import kotlinx.coroutines.flow.Flow   @Dao+/** Room access for stored location reports, including latest-per-user queries. */ interface LocationValueDao {     /**      * The newest report per user, ranked by when it was *sent* rather than when its position was@@ -46,6 +47,7 @@ interface LocationValueDao { }  @Dao+/** Room access for saved places (waypoints). */ interface WaypointDao {     @Query("SELECT * FROM Waypoint")     fun getAllFlow(): Flow<List<Waypoint>>@@ -67,6 +69,7 @@ interface WaypointDao { }  @Dao+/** Room access for people, trackers, and their sharing and sender-auth state. */ interface UserDao {     @Query("SELECT * FROM User")     fun getAllFlow(): Flow<List<User>>@@ -195,6 +198,7 @@ interface UserDao { }  @Dao+/** Room access for temporary share links. */ interface TemporaryLinkDao {     @Query("SELECT * FROM TemporaryLink")     fun getAllFlow(): Flow<List<TemporaryLink>>@@ -218,6 +222,7 @@ interface TemporaryLinkDao {     exportSchema = false ) @ColumnTypeConverters(DefaultConverters::class)+/** Room database holding users, waypoints, location reports, share links, and no-show alerts. */ abstract class FFDatabase : RoomDatabase() {     abstract fun userDao(): UserDao     abstract fun waypointDao(): WaypointDao@@ -225,6 +230,7 @@ abstract class FFDatabase : RoomDatabase() {     abstract fun temporaryLinkDao(): TemporaryLinkDao     abstract fun noShowAlertDao(): NoShowAlertDao +    /** Schema migrations from version 1 to the current database version. */     companion object : com.vayunmathur.library.util.DatabaseMigrations {         override val migrations: List<androidx.room3.migration.Migration> = listOf(             androidx.room3.migration.Migration(1, 2) {
findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.ktindex 7aeccf8d97..bb4ee2a5bb 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.kt@@ -119,23 +119,13 @@ class FindFamilyRepository internal constructor(     // Waypoint reads / writes     // ------------------------------------------------------------------ -    suspend fun getAllWaypoints(): List<Waypoint> = waypointDao.getAll()-    suspend fun getWaypoint(id: Long): Waypoint = waypointDao.get(id)-    suspend fun upsertWaypoint(waypoint: Waypoint): Long = waypointDao.upsert(waypoint)-     /**-     * Delete a saved place and its dangling references: arrival auto-toggles-     * and current-place pointers naming it, plus no-show watches expecting-     * arrivals there. Without this they pointed at a place that no longer-     * exists - toggles silently dead, watches firing for a deleted place.+     * Saved-place rows. Exposed as a store (rather than flat repository methods)+     * so the repository stays under the function cap — call sites use+     * `repository.waypointStore.*`.      */-    suspend fun deleteWaypoint(waypoint: Waypoint): Int {-        val deleted = waypointDao.delete(waypoint)-        userDao.clearArrivalTogglesForWaypoint(waypoint.id)-        userDao.clearLastWaypointForWaypoint(waypoint.id)-        noShowAlertDao.deleteByWaypointId(waypoint.id)-        return deleted-    }+    internal val waypointStore: WaypointStore+        get() = WaypointStore(waypointDao, userDao, noShowAlertDao)      // ------------------------------------------------------------------     // LocationValue reads / writes@@ -163,6 +153,7 @@ class FindFamilyRepository internal constructor(      */     internal val noShowAlertStore: NoShowAlertStore get() = NoShowAlertStore(noShowAlertDao) +    /** Process-wide singleton access for [FindFamilyRepository]. */     companion object {         @Volatile         private var instance: FindFamilyRepository? = null@@ -194,3 +185,28 @@ internal class NoShowAlertStore(private val dao: NoShowAlertDao) {     suspend fun markFired(id: Long): Int = dao.markFired(id)     suspend fun rearm(id: Long): Int = dao.rearm(id) }++/** Thin facade over [WaypointDao], owned by [FindFamilyRepository]. */+internal class WaypointStore(+    private val dao: WaypointDao,+    private val userDao: UserDao,+    private val noShowAlertDao: NoShowAlertDao,+) {+    suspend fun getAll(): List<Waypoint> = dao.getAll()+    suspend fun get(id: Long): Waypoint = dao.get(id)+    suspend fun upsert(waypoint: Waypoint): Long = dao.upsert(waypoint)++    /**+     * Delete a saved place and its dangling references: arrival auto-toggles+     * and current-place pointers naming it, plus no-show watches expecting+     * arrivals there. Without this they pointed at a place that no longer+     * exists - toggles silently dead, watches firing for a deleted place.+     */+    suspend fun delete(waypoint: Waypoint): Int {+        val deleted = dao.delete(waypoint)+        userDao.clearArrivalTogglesForWaypoint(waypoint.id)+        userDao.clearLastWaypointForWaypoint(waypoint.id)+        noShowAlertDao.deleteByWaypointId(waypoint.id)+        return deleted+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/data/InboundSpool.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/InboundSpool.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/InboundSpool.ktindex 517a77fc1f..eb3f0317c2 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/InboundSpool.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/InboundSpool.kt@@ -130,26 +130,33 @@ object InboundSpool {                 if (skipped <= 0) return out                 pos += skipped             }-            while (true) {-                val len = try {-                    input.readInt()-                } catch (_: EOFException) {-                    break-                }-                if (len < 0 || len > MAX_FRAME_BYTES) break-                val buf = ByteArray(len)-                try {-                    input.readFully(buf)-                } catch (_: EOFException) {-                    break // torn final record from a crash mid-append-                }-                pos += LENGTH_PREFIX_BYTES + len-                out.add(buf to pos)+            var record = readNextRecord(input, pos)+            while (record != null) {+                out.add(record)+                pos = record.second+                record = readNextRecord(input, pos)             }         }         return out     } +    /** One complete record starting at [pos], or null at EOF, on a corrupt length, or on a torn final record. */+    private fun readNextRecord(input: DataInputStream, pos: Long): Pair<ByteArray, Long>? {+        val len = try {+            input.readInt()+        } catch (_: EOFException) {+            return null+        }+        if (len < 0 || len > MAX_FRAME_BYTES) return null+        val buf = ByteArray(len)+        try {+            input.readFully(buf)+        } catch (_: EOFException) {+            return null // torn final record from a crash mid-append+        }+        return buf to (pos + LENGTH_PREFIX_BYTES + len)+    }+     /** Bytes taken by the length prefix of each record (for tests). */     internal const val RECORD_OVERHEAD: Int = LENGTH_PREFIX_BYTES }
findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.ktindex fc06e7bc6a..0e4d7cc999 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt@@ -74,6 +74,7 @@ enum class LocationSource {  @Serializable @Entity(indices = [Index(value = ["userid", "timestamp"]), Index(value = ["userid", "reportedAt"])])+/** One stored location report for a person, with measured and sent timestamps. */ data class LocationValue(     val userid: Long,     @Embedded val coord: Coord,@@ -123,6 +124,7 @@ data class LocationValue( }  @Serializable+/** Wire form of [LocationValue] exchanged with peers, using epoch millis and unsigned ids. */ data class LocationValueCompatible(     val id: ULong = 0uL,     val userid: ULong,
findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlertDao.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlertDao.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlertDao.ktindex e314b36b69..c1aabd9509 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlertDao.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlertDao.kt@@ -7,6 +7,7 @@ import androidx.room3.Upsert import kotlinx.coroutines.flow.Flow  @Dao+/** Room access for no-show alerts watching expected arrivals. */ interface NoShowAlertDao {     @Query("SELECT * FROM NoShowAlert")     fun getAllFlow(): Flow<List<NoShowAlert>>
findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.ktindex 62c46bf14f..cf993f0521 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt@@ -8,6 +8,7 @@ import kotlin.time.Clock import kotlin.time.Instant  @Serializable+/** Connection state between this device and a person. */ enum class RequestStatus {     MUTUAL_CONNECTION,     AWAITING_REQUEST,@@ -29,6 +30,7 @@ enum class UserKind {  @Serializable @Entity+/** A person (or DEV_BUILD tracker) this device shares location with. */ data class User(     val name: String,     val photo: String?,@@ -70,6 +72,7 @@ data class User(      * [UserKind.PERSON]; only the DEV_BUILD tracker feature ever writes [UserKind.TRACKER]. */     val kind: UserKind = UserKind.PERSON ): DatabaseItem {+    /** Shared placeholder values for [User]. */     companion object {         val EMPTY = User(" ", null, "Unnamed Location", true, RequestStatus.MUTUAL_CONNECTION, Clock.System.now(), null)     }
findfamily/src/main/java/com/vayunmathur/findfamily/data/Waypoint.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/Waypoint.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/Waypoint.ktindex 62fee4dd7f..416ba6c01d 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/Waypoint.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/Waypoint.kt@@ -8,12 +8,14 @@ import kotlinx.serialization.Serializable  @Serializable @Entity+/** A saved place whose entry and exit drive notifications and sharing toggles. */ data class Waypoint(     val name: String,     val range: Double,     @Embedded val coord: Coord,     @PrimaryKey(autoGenerate = true) override val id: Long = 0 ): DatabaseItem {+    /** Shared placeholder values for [Waypoint]. */     companion object {         val NEW_WAYPOINT = Waypoint("", 100.0, Coord(0.0, 0.0))     }
findfamily/src/main/java/com/vayunmathur/findfamily/intents/CreateLinkIntent.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/intents/CreateLinkIntent.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/intents/CreateLinkIntent.ktindex 58f6b3cb36..7542fb380e 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/intents/CreateLinkIntent.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/intents/CreateLinkIntent.kt@@ -1,4 +1,5 @@ package com.vayunmathur.findfamily.intents+import com.vayunmathur.findfamily.util.generatePqcLinkKey  import com.vayunmathur.findfamily.data.FindFamilyRepository import com.vayunmathur.findfamily.data.TemporaryLink
findfamily/src/main/java/com/vayunmathur/findfamily/intents/GetIntent.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/intents/GetIntent.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/intents/GetIntent.ktindex 175c1a522b..ea7b05f609 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/intents/GetIntent.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/intents/GetIntent.kt@@ -7,6 +7,7 @@ import kotlinx.serialization.InternalSerializationApi import kotlinx.serialization.serializer  @OptIn(InternalSerializationApi::class)+/** Assistant intent returning family members' names and latest locations. */ class GetIntent :     AssistantIntent<Unit, List<FamilyMemberData>>(serializer<Unit>(), serializer<List<FamilyMemberData>>()) { 
findfamily/src/main/java/com/vayunmathur/findfamily/platform/NoShowCheckScheduler.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/NoShowCheckScheduler.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/NoShowCheckScheduler.ktindex a02d685343..f23f243532 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/NoShowCheckScheduler.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/NoShowCheckScheduler.kt@@ -63,7 +63,7 @@ class NoShowCheckWorker(         alert: NoShowAlert,     ) {         val user = repository.getUser(alert.watchedUserId) ?: return-        val waypoint = alert.waypointId?.let { runCatching { repository.getWaypoint(it) }.getOrNull() }+        val waypoint = alert.waypointId?.let { runCatching { repository.waypointStore.get(it) }.getOrNull() }         val message = if (waypoint != null) {             context.getString(R.string.notification_noshow_at_place, user.name, waypoint.name)         } else {@@ -72,12 +72,14 @@ class NoShowCheckWorker(         context.notifyNoShowAlert(user, message, alert.id, alert.waypointId)     } +    /** WorkManager keys and logging tag for [NoShowCheckWorker]. */     companion object {         private const val TAG = "FF-NoShow"         internal const val KEY_ALERT_ID = "alert_id"     } } +/** Enqueues and sweeps deadline checks for no-show alerts. */ object NoShowCheckScheduler {      private const val TAG = "FF-NoShow"@@ -167,7 +169,7 @@ object NoShowCheckScheduler {                 fixAccuracyMeters = fix.acc.toDouble(),             )         }-        val waypoint = runCatching { repository.getWaypoint(waypointId) }.getOrNull()+        val waypoint = runCatching { repository.waypointStore.get(waypointId) }.getOrNull()             ?: return false         return NoShowPolicy.hasArrivedAtWaypoint(             fixLat = fix.coord.lat,
findfamily/src/main/java/com/vayunmathur/findfamily/service/SharingTileService.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/service/SharingTileService.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/service/SharingTileService.ktindex 49e0017f7e..319b335d38 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/service/SharingTileService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/service/SharingTileService.kt@@ -62,6 +62,7 @@ class SharingTileService : TileService() {         scope.cancel()     } +    /** Helpers for refreshing the sharing Quick Settings tile. */     companion object {         /**          * Ask the system to bind the tile so it re-reads the flag. Without this a
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffScanner.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffScanner.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffScanner.ktindex 3aa5f4d208..17171687c0 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffScanner.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffScanner.kt@@ -110,6 +110,7 @@ class PoweredOffScanner(private val context: Context) {         return builder.build()     } +    /** Logging tag for [PoweredOffScanner]. */     companion object {         private const val TAG = "PoweredOffScanner"     }
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBeaconScanner.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBeaconScanner.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBeaconScanner.ktindex 2c8b1ac39c..32cd664979 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBeaconScanner.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBeaconScanner.kt@@ -89,6 +89,7 @@ class TrackerBeaconScanner(private val context: Context) {         }     } +    /** Logging tag for [TrackerBeaconScanner]. */     companion object {         private const val TAG = "TrackerBeaconScanner"     }
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.ktindex 96102f0746..163b14a71d 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.kt@@ -1,4 +1,5 @@ package com.vayunmathur.findfamily.tracker+import com.vayunmathur.findfamily.util.generatePqcIdentityKeyPair  import android.bluetooth.BluetoothDevice import android.content.Context
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.ktindex 655e721f15..b15f902c94 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.kt@@ -181,6 +181,7 @@ class TrackerProvisioner(private val context: Context) {             Log.status(TAG, "writeCharacteristic failed", e); false         } +    /** Logging tag and provisioning-blob layout constants for [TrackerProvisioner]. */     companion object {         private const val TAG = "TrackerProvisioner" 
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.ktindex 23fb54606a..3031706bc6 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt@@ -57,7 +57,9 @@ import kotlin.io.encoding.Base64 import kotlin.math.abs import kotlin.math.cos +/** Person selected on the map, with whether the present or a historical position is shown. */ data class SelectedUser(val user: User, val isShowingPresent: Boolean, val historicalPosition: GeoPoint?)+/** Waypoint selected on the map, with its range and move callback. */ data class SelectedWaypoint(val waypoint: Waypoint, val range: Double, val onMoveWaypoint: (Coord) -> Unit)  private fun GeoPoint.toCoord() = Coord(latitude, longitude)
findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/AddPersonDialog.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/AddPersonDialog.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/AddPersonDialog.ktindex 195fdb5b75..423af59073 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/AddPersonDialog.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/AddPersonDialog.kt@@ -1,4 +1,5 @@ package com.vayunmathur.findfamily.ui.dialogs+import com.vayunmathur.findfamily.util.myInviteFingerprint import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Arrangement
findfamily/src/main/java/com/vayunmathur/findfamily/util/AppBackupAgent.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/AppBackupAgent.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/AppBackupAgent.ktindex 4a1f7021f4..321160b84f 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/AppBackupAgent.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/AppBackupAgent.kt@@ -5,6 +5,7 @@ import com.vayunmathur.library.util.BaseBackupAgent import com.vayunmathur.library.util.DatabaseHelper import java.io.File +/** Android backup agent covering the SQLCipher database passphrase and identity DataStore. */ class AppBackupAgent : BaseBackupAgent() {     override val dbCodec = SqlCipherDbCodec 
findfamily/src/main/java/com/vayunmathur/findfamily/util/BootReceiver.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/BootReceiver.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/BootReceiver.ktindex 2adb895d07..d3c1256ece 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/BootReceiver.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/BootReceiver.kt@@ -7,6 +7,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch +/** Restarts location sharing and no-show checks after boot or app replacement. */ class BootReceiver : BroadcastReceiver() {     override fun onReceive(context: Context, intent: Intent) {         // LOCKED_BOOT_COMPLETED is the only one of these delivered before the user unlocks,
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 05cd2145ae..249864e9f3 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyUiContract.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyUiContract.kt@@ -47,6 +47,7 @@ interface FamilyListActions {     fun deleteTemporaryLink(link: TemporaryLink) {}     fun beginEditWaypoint(waypoint: Waypoint) {} +    /** No-op [FamilyListActions] for previews. */     companion object {         val Noop: FamilyListActions = object : FamilyListActions {}     }@@ -93,6 +94,7 @@ interface PersonActions {     /** Opt in or out of acting as a finder for other people's powered-off devices. */     fun setCrowdFinding(enabled: Boolean) {} +    /** No-op [PersonActions] for previews. */     companion object {         val Noop: PersonActions = object : PersonActions {}     }@@ -153,6 +155,7 @@ interface MainPageActions {     fun setWaypointName(name: String) {}     fun setWaypointRange(range: String) {} +    /** No-op [MainPageActions] for previews. */     companion object {         val Noop: MainPageActions = object : MainPageActions {}     }
findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.ktindex 0ff71d7fa8..1131d1ab31 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt@@ -212,7 +212,7 @@ class FindFamilyViewModel(                     .filter { it.waypointId == waypoint.id }                     .forEach { NoShowCheckScheduler.cancel(ctx, it.id) }             }-            repository.deleteWaypoint(waypoint)+            repository.waypointStore.delete(waypoint)         }     } 
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingCrowdFinding.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingCrowdFinding.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingCrowdFinding.ktindex 799f5bdb70..509d2dadf4 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingCrowdFinding.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingCrowdFinding.kt@@ -37,7 +37,10 @@ internal fun LocationTrackingService.startTrackerScanner() {                     return@collect                 }                 if (loc.accuracy > MAX_FIX_ACCURACY_METERS) {-                    Log.status("FF-Tracker", "sighting dropped: accuracy ${loc.accuracy}m > ${MAX_FIX_ACCURACY_METERS}m")+                    Log.status(+                        "FF-Tracker",+                        "sighting dropped: accuracy ${loc.accuracy}m > ${MAX_FIX_ACCURACY_METERS}m"+                    )                     return@collect                 }                 val battery = runCatching {@@ -132,9 +135,13 @@ internal fun LocationTrackingService.startPoweredOffScanner() {                             0f,                         )                         runCatching { PoweredOffReporting.reportSighting(sighting, lv) }-                            .onFailure { Log.status(LocationTrackingService.TAG_POWERED_OFF, "reportSighting failed", it) }+                            .onFailure {+                                Log.status(LocationTrackingService.TAG_POWERED_OFF, "reportSighting failed", it)+                            }                     }-                }.onFailure { Log.status(LocationTrackingService.TAG_POWERED_OFF, "powered-off scan collect failed", it) }+                }.onFailure {+                    Log.status(LocationTrackingService.TAG_POWERED_OFF, "powered-off scan collect failed", it)+                }             }     } }
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeat.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeat.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeat.ktindex 0ece34bf24..9d75e38ec2 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeat.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeat.kt@@ -154,7 +154,7 @@ private suspend fun LocationTrackingService.applyArrivalAutoToggles(     // waypoint-id-guarded update as the timer path so a stale snapshot cannot mis-flip.     try {         val myCoord = Coord(location.latitude, location.longitude)-        val insideWaypointIds = repository.getAllWaypoints()+        val insideWaypointIds = repository.waypointStore.getAll()             .filter { havershine(it.coord, myCoord) < it.range }             .map { it.id }         if (insideWaypointIds.isNotEmpty()) {@@ -250,7 +250,8 @@ internal suspend fun LocationTrackingService.seedDirectBootMirror() {     val targets = repository.getAllUsers()         .filter { it.id != Networking.userid && it.sendingEnabled }         .mapNotNull { u -> u.pqcEncryptionKey?.let { DirectBootStore.Target(u.id, it, u.outboundPairId) } }-    val signature = "$sharingOut|$trackingEnabled|" + targets.joinToString(",") { "${it.id}:${it.bundle.length}:${it.pairId?.take(4)}" }+    val targetSignature = targets.joinToString(",") { "${it.id}:${it.bundle.length}:${it.pairId?.take(4)}" }+    val signature = "$sharingOut|$trackingEnabled|$targetSignature"     publishRoster = if (sharingOut) targets else emptyList()     if (signature == lastSeededMirror) return     DirectBootStore.seed(
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingInbound.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingInbound.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingInbound.ktindex 52b8002350..90b432f123 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingInbound.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingInbound.kt@@ -84,51 +84,7 @@ internal suspend fun LocationTrackingService.processIncomingFixes(incoming: List     val authenticated = ArrayList<LocationValue>(incoming.size)     val strangerIds = LinkedHashSet<Long>()     for (fix in incoming) {-        val loc = fix.location-        val senderId = loc.userid-        if (senderId == Networking.userid) continue-        if (PairAuth.isFromTheFuture(loc.reportedAt, loc.timestamp, now)) {-            Log.status(-                "FF-Heartbeat",-                "dropped future-dated fix from ${senderId.toULong()} " +-                    "reportedAt=${loc.reportedAt} timestamp=${loc.timestamp}"-            )-            continue-        }-        val peer = usersById[senderId]-        if (peer == null || peer.kind != UserKind.PERSON || senderId !in eligibleIds) {-            // Stranger, tracker claim, or not-yet-mutual: request row at most, never a pin,-            // never storage. Collected for the single insert below.-            if (peer == null && senderId != Networking.userid) strangerIds.add(senderId)-            else Log.status(-                "FF-Heartbeat",-                "dropped fix from ineligible sender ${senderId.toULong()} " +-                    "(known=${peer != null} kind=${peer?.kind} status=${peer?.requestStatus})"-            )-            continue-        }-        when (PairAuth.checkInbound(peer.inboundPairId, fix.pairId)) {-            PairAuth.InboundVerdict.ACCEPT_MATCH,-            PairAuth.InboundVerdict.ACCEPT_LEGACY,-            -> authenticated.add(loc)-            PairAuth.InboundVerdict.ACCEPT_PIN -> {-                runCatching { repository.pinInboundPairId(senderId, fix.pairId!!) }-                Log.dev(-                    "FF-Heartbeat",-                    "pinned inbound pair ID for ${senderId.toULong()} " +-                        "(preview ${PairAuth.logPreview(fix.pairId)})"-                )-                authenticated.add(loc)-            }-            PairAuth.InboundVerdict.DROP_MISMATCH,-            PairAuth.InboundVerdict.DROP_MISSING,-            -> Log.status(-                "FF-Heartbeat",-                "dropped unauthenticated fix claiming ${senderId.toULong()} " +-                    "(pair ${PairAuth.logPreview(fix.pairId)}, " +-                    "expected ${PairAuth.logPreview(peer.inboundPairId)})"-            )-        }+        collectAuthenticatedFix(fix, usersById, eligibleIds, now, authenticated, strangerIds)     }     if (strangerIds.isNotEmpty()) {         Log.dev("FF-Heartbeat", "newUsers to insert=${strangerIds.map { it.toULong() }}")@@ -139,6 +95,61 @@ internal suspend fun LocationTrackingService.processIncomingFixes(incoming: List     processIncomingLocations(authenticated) } +private suspend fun LocationTrackingService.collectAuthenticatedFix(+    fix: InboundFix,+    usersById: Map<Long, User>,+    eligibleIds: Set<Long>,+    now: kotlin.time.Instant,+    authenticated: MutableList<LocationValue>,+    strangerIds: MutableSet<Long>,+) {+    val loc = fix.location+    val senderId = loc.userid+    if (senderId == Networking.userid) return+    if (PairAuth.isFromTheFuture(loc.reportedAt, loc.timestamp, now)) {+        Log.status(+            "FF-Heartbeat",+            "dropped future-dated fix from ${senderId.toULong()} " ++                "reportedAt=${loc.reportedAt} timestamp=${loc.timestamp}"+        )+        return+    }+    val peer = usersById[senderId]+    if (peer == null || peer.kind != UserKind.PERSON || senderId !in eligibleIds) {+        // Stranger, tracker claim, or not-yet-mutual: request row at most, never a pin,+        // never storage. Collected for the single insert in the caller.+        if (peer == null) strangerIds.add(senderId)+        else Log.status(+            "FF-Heartbeat",+            "dropped fix from ineligible sender ${senderId.toULong()} " ++                "(known=true kind=${peer.kind} status=${peer.requestStatus})"+        )+        return+    }+    when (PairAuth.checkInbound(peer.inboundPairId, fix.pairId)) {+        PairAuth.InboundVerdict.ACCEPT_MATCH,+        PairAuth.InboundVerdict.ACCEPT_LEGACY,+        -> authenticated.add(loc)+        PairAuth.InboundVerdict.ACCEPT_PIN -> {+            runCatching { repository.pinInboundPairId(senderId, fix.pairId!!) }+            Log.dev(+                "FF-Heartbeat",+                "pinned inbound pair ID for ${senderId.toULong()} " ++                    "(preview ${PairAuth.logPreview(fix.pairId)})"+            )+            authenticated.add(loc)+        }+        PairAuth.InboundVerdict.DROP_MISMATCH,+        PairAuth.InboundVerdict.DROP_MISSING,+        -> Log.status(+            "FF-Heartbeat",+            "dropped unauthenticated fix claiming ${senderId.toULong()} " ++                "(pair ${PairAuth.logPreview(fix.pairId)}, " ++                "expected ${PairAuth.logPreview(peer.inboundPairId)})"+        )+    }+}+ /**  * Persists a batch of authenticated peer locations. Every element must have passed  * [processIncomingFixes] (or be a local crowd-report path that vouches for its own@@ -228,7 +239,7 @@ internal suspend fun LocationTrackingService.enrichIncomingLocations(     latestMap: Map<Long, LocationValue>, ) {     val currentUsers = repository.getAllUsers()-    val currentWaypoints = repository.getAllWaypoints()+    val currentWaypoints = repository.waypointStore.getAll()     currentUsers.forEach { user ->         enrichOneUser(user, locList, latestMap, currentWaypoints)     }
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 0a2ac95c7d..93305c40a1 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt@@ -98,6 +98,7 @@ import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds +/** Foreground service that publishes this device's location and receives peers' fixes. */ class LocationTrackingService : Service(), SensorEventListener {     internal val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)     internal lateinit var locationManager: LocationManager@@ -613,6 +614,7 @@ class LocationTrackingService : Service(), SensorEventListener {         stopGps()     } +    /** Notification channels, tags, and timing constants for [LocationTrackingService]. */     companion object {         internal const val CHANNEL_ID = "location_tracking_channel"         internal const val BATTERY_CHANNEL_ID = "battery_channel"@@ -739,6 +741,7 @@ suspend fun Context.fetchAddress(lat: Double, lng: Double): Address? {     } } +/** Periodic worker that reconciles the tracking service with current sharing state. */ class ServiceRestartWorker(     appContext: Context,     workerParams: WorkerParameters
findfamily/src/main/java/com/vayunmathur/findfamily/util/MapPageState.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/MapPageState.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/MapPageState.ktindex 84209e3499..d2f3dc6376 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/MapPageState.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/MapPageState.kt@@ -120,8 +120,8 @@ class MapPageState(         val id = _selectedWaypointId.value ?: return         val coord = _waypointCoord.value         scope.launch(Dispatchers.IO) {-            val base = if (id == 0L) Waypoint.NEW_WAYPOINT else repository.getWaypoint(id)-            repository.upsertWaypoint(base.copy(name = name, range = range, coord = coord))+            val base = if (id == 0L) Waypoint.NEW_WAYPOINT else repository.waypointStore.get(id)+            repository.waypointStore.upsert(base.copy(name = name, range = range, coord = coord))             withContext(Dispatchers.Main) {                 _selectedWaypointId.value = null             }
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 8d8f028d47..57ef954b21 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt@@ -472,7 +472,12 @@ object Networking {      */     // Broad catch is deliberate: relay-socket boundary, same as [wsGetKey].     @Suppress("TooGenericExceptionCaught")-    suspend fun publishLocation(location: LocationValue, targetId: Long, bundleB64: String, pairId: String? = null): Boolean {+    suspend fun publishLocation(+        location: LocationValue,+        targetId: Long,+        bundleB64: String,+        pairId: String? = null+    ): Boolean {         return try {             val ok = sendLivePublish(targetId, "location", sealLocation(location, Base64.decode(bundleB64), pairId))             Log.dev(TAG, "publishLocation PQC to ${targetId.toULong()} (direct boot) ok=$ok")@@ -544,66 +549,12 @@ object Networking {             .getOrNull() ?: fresh     } -    /**-     * Generates a fresh share-link key. The link is ML-KEM only and derived from a-     * 32-byte seed, which is the whole secret handed to the recipient in the URL-     * fragment — short enough to fit in an SMS. The private key is never stored:-     * the sender only ever encrypts, and the recipient re-derives it from the seed.-     */-    fun generatePqcLinkKey(): PqcLinkKey {-        val key = Pqc.generateLinkKey()-        return PqcLinkKey(-            seedB64Url = Base64.UrlSafe.encode(key.seed).trimEnd('='),-            publicBundleB64 = Base64.encode(key.publicBundle)-        )-    }-+    /** Fresh share-link key: the recipient seed and the sender public bundle. */     data class PqcLinkKey(val seedB64Url: String, val publicBundleB64: String) -    /**-     * This device's invite fingerprint, as the unpadded base64url `k=` value of a share link.-     * Null when PQC is unavailable — the link then goes out without it and the recipient simply-     * has nothing to pre-verify against, exactly as before this parameter existed.-     */-    fun myInviteFingerprint(): String? {-        if (!pqcReady) return null-        return runCatching {-            Base64.UrlSafe.encode(Pqc.inviteFingerprint(userid, pqcIdentity.publicBundle)).trimEnd('=')-        }.onFailure { Log.status(TAG, "invite fingerprint failed", it) }.getOrNull()-    }--    /**-     * Generates a full PQC identity (ML-KEM + ML-DSA) for a device we own but that cannot-     * run keygen itself — currently only UWB trackers, whose private bundle we hold on-     * their behalf. Returns (publicBundleBase64, privateBundleBase64) where the private-     * bundle is [4B kemPrivLen][kemPrivDer][dsaPrivDer] — DERs, BC-compatible, same KDF-     * as Office. Share links use [generatePqcLinkKey] instead.-     */-    fun generatePqcIdentityKeyPair(): PqcIdentityKeyPair {-        val (kemPub, kemPriv) = Pqc.generateKem()-        val (dsaPub, dsaPriv) = Pqc.generateDsa()-        val pubBundle = Pqc.bundle(kemPub, dsaPub)-        val privBundle = buildPrivBundle(kemPriv, dsaPriv)-        return PqcIdentityKeyPair(-            publicBundleB64 = Base64.encode(pubBundle),-            privateBundleB64 = Base64.encode(privBundle)-        )-    }-+    /** Generated PQC identity public and private bundles for a device unable to run keygen itself. */     data class PqcIdentityKeyPair(val publicBundleB64: String, val privateBundleB64: String) -    /** Private bundle layout: [u32 kemPrivLen BE][kemPriv][dsaPriv] — mirrors public bundle. */-    private fun buildPrivBundle(kemPriv: ByteArray, dsaPriv: ByteArray): ByteArray {-        val out = ByteArray(U32_LEN + kemPriv.size + dsaPriv.size)-        out[0] = (kemPriv.size ushr U32_BYTE0_SHIFT).toByte()-        out[1] = (kemPriv.size ushr U32_BYTE1_SHIFT).toByte()-        out[2] = (kemPriv.size ushr BITS_PER_BYTE).toByte()-        out[U32_LEN - 1] = kemPriv.size.toByte()-        kemPriv.copyInto(out, U32_LEN)-        dsaPriv.copyInto(out, U32_LEN + kemPriv.size)-        return out-    }-     /**      * Computes the quantum-safe verification "security code" for a connection: a fingerprint of      * *both* this device's and [user]'s PQC bundles. Identical on both peers; comparing them
findfamily/src/main/java/com/vayunmathur/findfamily/util/NetworkingPqc.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/NetworkingPqc.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/NetworkingPqc.ktnew file mode 100644index 0000000000..495ba5c64b--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/NetworkingPqc.kt@@ -0,0 +1,61 @@+package com.vayunmathur.findfamily.util++import com.vayunmathur.e2ee.Pqc+import com.vayunmathur.library.log.Log+import kotlin.io.encoding.Base64++/**+ * Generates a fresh share-link key. The link is ML-KEM only and derived from a+ * 32-byte seed, which is the whole secret handed to the recipient in the URL+ * fragment — short enough to fit in an SMS. The private key is never stored:+ * the sender only ever encrypts, and the recipient re-derives it from the seed.+ */+fun Networking.generatePqcLinkKey(): Networking.PqcLinkKey {+    val key = Pqc.generateLinkKey()+    return Networking.PqcLinkKey(+        seedB64Url = Base64.UrlSafe.encode(key.seed).trimEnd('='),+        publicBundleB64 = Base64.encode(key.publicBundle)+    )+}++/**+ * This device's invite fingerprint, as the unpadded base64url `k=` value of a share link.+ * Null when PQC is unavailable — the link then goes out without it and the recipient simply+ * has nothing to pre-verify against, exactly as before this parameter existed.+ */+fun Networking.myInviteFingerprint(): String? {+    if (!pqcReady) return null+    return runCatching {+        Base64.UrlSafe.encode(Pqc.inviteFingerprint(userid, pqcIdentity.publicBundle)).trimEnd('=')+    }.onFailure { Log.status(TAG, "invite fingerprint failed", it) }.getOrNull()+}++/**+ * Generates a full PQC identity (ML-KEM + ML-DSA) for a device we own but that cannot+ * run keygen itself — currently only UWB trackers, whose private bundle we hold on+ * their behalf. Returns (publicBundleBase64, privateBundleBase64) where the private+ * bundle is [4B kemPrivLen][kemPrivDer][dsaPrivDer] — DERs, BC-compatible, same KDF+ * as Office. Share links use [generatePqcLinkKey] instead.+ */+fun Networking.generatePqcIdentityKeyPair(): Networking.PqcIdentityKeyPair {+    val (kemPub, kemPriv) = Pqc.generateKem()+    val (dsaPub, dsaPriv) = Pqc.generateDsa()+    val pubBundle = Pqc.bundle(kemPub, dsaPub)+    val privBundle = buildPrivBundle(kemPriv, dsaPriv)+    return Networking.PqcIdentityKeyPair(+        publicBundleB64 = Base64.encode(pubBundle),+        privateBundleB64 = Base64.encode(privBundle)+    )+}++/** Private bundle layout: [u32 kemPrivLen BE][kemPriv][dsaPriv] — mirrors public bundle. */+private fun buildPrivBundle(kemPriv: ByteArray, dsaPriv: ByteArray): ByteArray {+    val out = ByteArray(Networking.U32_LEN + kemPriv.size + dsaPriv.size)+    out[0] = (kemPriv.size ushr Networking.U32_BYTE0_SHIFT).toByte()+    out[1] = (kemPriv.size ushr Networking.U32_BYTE1_SHIFT).toByte()+    out[2] = (kemPriv.size ushr Networking.BITS_PER_BYTE).toByte()+    out[Networking.U32_LEN - 1] = kemPriv.size.toByte()+    kemPriv.copyInto(out, Networking.U32_LEN)+    dsaPriv.copyInto(out, Networking.U32_LEN + kemPriv.size)+    return out+}
findfamily/src/main/java/com/vayunmathur/findfamily/util/Platform.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Platform.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Platform.ktindex 2dc4eb5419..f4e955f2c7 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Platform.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Platform.kt@@ -41,6 +41,7 @@ private data class PickedContact( private fun withPhoto(photos: List<String>, photo: String?): List<String> =     if (photo != null) photos + photo else photos +/** Android platform helpers for contact picking, clipboard, and last known device location. */ class Platform(private val context: Context) {     @SuppressLint("Range")     @Composable
findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.ktindex 76170043d5..29700d7e8c 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt@@ -58,17 +58,24 @@ object UwbSessionManager {      /** UI-facing state machine for the Find Nearby (UWB) screen. */     sealed interface UwbSessionState {+        /** No Find Nearby session is active. */         data object Idle : UwbSessionState+        /** A Find Nearby session is being set up. */         data object Starting : UwbSessionState+        /** Waiting for the peer to answer the Find Nearby request. */         data object WaitingForPeer : UwbSessionState+        /** Actively ranging, carrying the latest sample. */         data class Ranging(val sample: RangingSample) : UwbSessionState+        /** The peer left the ranging session. */         data object PeerDisconnected : UwbSessionState+        /** Find Nearby is unavailable, optionally with the reason. */         data class Unsupported(val reason: String? = null) : UwbSessionState         /**          * The peer's phone declined the REQUEST because it can't do Find Nearby at all          * (CANCEL with [UwbCancelReason.UNSUPPORTED], #869). Terminal until the screen closes.          */         data object PeerUnsupported : UwbSessionState+        /** Terminal failure state carrying the reason. */         data class Failed(val reason: String) : UwbSessionState     } 
findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbAccessoryProtocol.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbAccessoryProtocol.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbAccessoryProtocol.ktindex 76c8841e48..50c2f555c8 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbAccessoryProtocol.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbAccessoryProtocol.kt@@ -44,6 +44,7 @@ object UwbAccessoryProtocol {         )     } +    /** FiRa parameters parsed from a peer's shareable configuration data. */     data class Parsed(         val peerAddress: ByteArray,         val sessionId: Int,
findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbController.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbController.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbController.ktindex 4fd8e5dd18..1d69df44b0 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbController.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbController.kt@@ -64,10 +64,15 @@ class UwbController(context: Context) {      */     private var lastWorkingTier: Int = -1 +    /** Lifecycle state of a UWB ranging controller session. */     sealed interface State {+        /** No ranging session is open. */         data object Idle : State+        /** A ranging session is being opened. */         data object Opening : State+        /** Session parameters are ready, carrying the local UWB address. */         data class Ready(val localAddress: ByteArray) : State+        /** Opening or ranging failed, carrying the reason. */         data class Failed(val reason: String) : State     } @@ -424,6 +429,7 @@ class UwbController(context: Context) {         _state.value = State.Idle     } +    /** Local FiRa parameters generated for an initiator session. */     data class ControllerInfo(         val localAddress: ByteArray,         val channelNumber: Int,@@ -433,6 +439,7 @@ class UwbController(context: Context) {         val uuid: UUID,     ) +    /** Whether this device starts ranging or answers it. */     enum class Role { Initiator, Responder }      /** Marker sample for "the peer is gone / the session failed" — one call site per failure path. */@@ -456,6 +463,7 @@ class UwbController(context: Context) {             "rssi=${runCatching { data.rssi }.getOrNull()}"     } +    /** Default FiRa channel and preamble and logging tag for [UwbController]. */     companion object {         private const val TAG = "UwbController"         /** FiRa channel 9 (the most common UWB channel; supported by every iPhone with U1/U2). */
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 24c9606fae..2adee27510 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/uwb/UwbEnvelope.kt@@ -121,6 +121,7 @@ data class UwbHandshake(     val shareableConfigDataB64: String? = null, ) +/** Envelope kinds carried on the UWB session-setup channel. */ object UwbEnvelopeKind {     const val REQUEST = "request"     const val ACK = "ack"
findfamily/src/test/java/com/vayunmathur/findfamily/data/FindFamilyRepositoryTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/data/FindFamilyRepositoryTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/data/FindFamilyRepositoryTest.ktindex 070306c2c8..29ecde3574 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/data/FindFamilyRepositoryTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/data/FindFamilyRepositoryTest.kt@@ -77,8 +77,8 @@ class FindFamilyRepositoryTest {      @Test     fun deleteWaypointCascadesReferences() = runTest {-        val wpId = repo.upsertWaypoint(Waypoint(name = "Home", range = 150.0, coord = Coord(3.0, 4.0)))-        val otherWp = repo.upsertWaypoint(Waypoint(name = "Work", range = 150.0, coord = Coord(5.0, 6.0)))+        val wpId = repo.waypointStore.upsert(Waypoint(name = "Home", range = 150.0, coord = Coord(3.0, 4.0)))+        val otherWp = repo.waypointStore.upsert(Waypoint(name = "Work", range = 150.0, coord = Coord(5.0, 6.0)))         val uid = repo.upsertUser(user())         repo.setSharingAutoToggleWaypointId(uid, wpId)         repo.updateLocationMeta(uid, "Home", wpId, 1234L)@@ -88,7 +88,7 @@ class FindFamilyRepositoryTest {         repo.noShowAlertStore.upsert(             NoShowAlert(watchedUserId = uid, waypointId = otherWp, expectedAt = Clock.System.now(), grace = 5.minutes)         )-        assertEquals(1, repo.deleteWaypoint(repo.getWaypoint(wpId)))+        assertEquals(1, repo.waypointStore.delete(repo.waypointStore.get(wpId)))         val row = repo.getUser(uid)!!         assertNull(row.sharingAutoToggleWaypointId)         assertNull(row.lastWaypointId)@@ -145,9 +145,9 @@ class FindFamilyRepositoryTest {      @Test     fun waypointAndLocationPaths() = runTest {-        val wpId = repo.upsertWaypoint(Waypoint(name = "Home", range = 150.0, coord = Coord(3.0, 4.0)))-        assertEquals("Home", repo.getWaypoint(wpId).name)-        assertEquals(1, repo.getAllWaypoints().size)+        val wpId = repo.waypointStore.upsert(Waypoint(name = "Home", range = 150.0, coord = Coord(3.0, 4.0)))+        assertEquals("Home", repo.waypointStore.get(wpId).name)+        assertEquals(1, repo.waypointStore.getAll().size)         assertEquals(1, repo.waypoints.first().size)         val uid = repo.upsertUser(user())         repo.upsertLocation(fix(uid, 1000))@@ -157,7 +157,7 @@ class FindFamilyRepositoryTest {         assertEquals(1, repo.latestLocationsOnce().size)         repo.deleteLocationsOlderThan(2) // timestamps are stored as epoch seconds (1s, 2s, 3s)         assertEquals(2, repo.locationHistory(uid).first().size)-        assertEquals(1, repo.deleteWaypoint(repo.getWaypoint(wpId)))+        assertEquals(1, repo.waypointStore.delete(repo.waypointStore.get(wpId)))     }      @Test
findfamily/src/test/java/com/vayunmathur/findfamily/util/FindFamilyViewModelDbTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/FindFamilyViewModelDbTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/FindFamilyViewModelDbTest.ktindex 727818e189..b176d5cf2d 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/util/FindFamilyViewModelDbTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/FindFamilyViewModelDbTest.kt@@ -75,7 +75,7 @@ class FindFamilyViewModelDbTest {         val alice = repo.upsertUser(user("Alice"))         repo.upsertUser(user("Bob", RequestStatus.AWAITING_REQUEST, loc = "Office"))         repo.upsertUser(user("Carol", RequestStatus.AWAITING_RESPONSE, loc = "Office"))-        repo.upsertWaypoint(Waypoint(name = "Home", range = 100.0, coord = Coord(1.0, 2.0)))+        repo.waypointStore.upsert(Waypoint(name = "Home", range = 100.0, coord = Coord(1.0, 2.0)))         // Recent fix: the ViewModel startup cleanup deletes week-old locations.         val nowFix = Clock.System.now()         repo.upsertLocation(LocationValue(userid = alice, coord = Coord(1.0, 2.0), speed = 0f, acc = 5f,@@ -125,15 +125,15 @@ class FindFamilyViewModelDbTest {         val id = repo.upsertUser(user("Dave"))         vm.updateContactNamePhoto(id, "David", "photo://d")         awaitTrue("rename") { kotlinx.coroutines.runBlocking { repo.getUser(id)?.name == "David" } }-        val wpId = repo.upsertWaypoint(Waypoint(name = "Gym", range = 50.0, coord = Coord(0.0, 0.0)))-        vm.beginEditWaypoint(repo.getWaypoint(wpId))+        val wpId = repo.waypointStore.upsert(Waypoint(name = "Gym", range = 50.0, coord = Coord(0.0, 0.0)))+        vm.beginEditWaypoint(repo.waypointStore.get(wpId))         assertEquals("Gym", vm.waypointName.value)         vm.mapState.setWaypointName("Gym2")         vm.mapState.setWaypointRange("75")         vm.mapState.saveCurrentWaypoint()-        awaitTrue("waypoint saved") { kotlinx.coroutines.runBlocking { repo.getWaypoint(wpId).name == "Gym2" } }-        vm.deleteWaypoint(repo.getWaypoint(wpId))-        awaitTrue("waypoint deleted") { kotlinx.coroutines.runBlocking { repo.getAllWaypoints().isEmpty() } }+        awaitTrue("waypoint saved") { kotlinx.coroutines.runBlocking { repo.waypointStore.get(wpId).name == "Gym2" } }+        vm.deleteWaypoint(repo.waypointStore.get(wpId))+        awaitTrue("waypoint deleted") { kotlinx.coroutines.runBlocking { repo.waypointStore.getAll().isEmpty() } }         val link = TemporaryLink(name = "L", deleteAt = Clock.System.now(), pqcPublicKey = "pub")         repo.temporaryLinkStore.upsert(link)         vm.deleteTemporaryLink(repo.temporaryLinkStore.getAll().first())@@ -153,11 +153,11 @@ class FindFamilyViewModelDbTest {         vm.mapState.setWaypointRange("200")         vm.mapState.setWaypointCoord(Coord(5.0, 6.0))         vm.mapState.saveCurrentWaypoint()-        awaitTrue("waypoint created") { kotlinx.coroutines.runBlocking { repo.getAllWaypoints().any { it.name == "Park" } } }+        awaitTrue("waypoint created") { kotlinx.coroutines.runBlocking { repo.waypointStore.getAll().any { it.name == "Park" } } }         val uid = repo.upsertUser(user("Frank"))         vm.applyInitialSelection(uid, null)         assertEquals(uid, vm.selectedUserId.value)-        vm.applyInitialSelection(null, repo.getAllWaypoints().first().id)+        vm.applyInitialSelection(null, repo.waypointStore.getAll().first().id)         assertNotNull(vm.mapState.selectedWaypointId.value)         vm.refreshPermissions()         // Permission flags must be readable (values depend on Robolectric grants).
findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeatTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeatTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeatTest.ktindex 887b4e12b0..a0afb3ca35 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeatTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingHeartbeatTest.kt@@ -83,7 +83,7 @@ class LocationTrackingHeartbeatTest {     @Test     fun syncHeartbeatPersistsSelfAndCleansExpiredLinks() = runBlocking {         val peer = repo.upsertUser(user("Peer"))-        repo.upsertWaypoint(Waypoint(name = "Home", range = 500.0, coord = Coord(51.5, -0.12)))+        repo.waypointStore.upsert(Waypoint(name = "Home", range = 500.0, coord = Coord(51.5, -0.12)))         val expired = TemporaryLink(name = "old", deleteAt = Instant.fromEpochMilliseconds(1), pqcPublicKey = "pub")         repo.temporaryLinkStore.upsert(expired)         service.lastKnownLocation = location()
findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.ktindex b994cd1984..5114402228 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/util/LocationTrackingInboundTest.kt@@ -125,7 +125,7 @@ class LocationTrackingInboundTest {     @Test     fun enrichResolvesWaypointAndNotifies() = runBlocking {         val uid = repo.upsertUser(user("Carol"))-        val wpId = repo.upsertWaypoint(Waypoint(name = "HomeBase", range = 500.0, coord = Coord(51.5, -0.12)))+        val wpId = repo.waypointStore.upsert(Waypoint(name = "HomeBase", range = 500.0, coord = Coord(51.5, -0.12)))         val now = Clock.System.now()         service.enrichIncomingLocations(             listOf(fix(uid, at = now, battery = 10f, coord = Coord(51.5, -0.12))),@@ -140,7 +140,7 @@ class LocationTrackingInboundTest {      @Test     fun networkSightingDoesNotFireLowBattery() = runBlocking {-        val wpId = repo.upsertWaypoint(Waypoint(name = "HomeBase", range = 500.0, coord = Coord(51.5, -0.12)))+        val wpId = repo.waypointStore.upsert(Waypoint(name = "HomeBase", range = 500.0, coord = Coord(51.5, -0.12)))         val uid = repo.upsertUser(user("Eve").copy(locationName = "HomeBase", lastWaypointId = wpId))         val now = Clock.System.now()         val previous = fix(uid, at = now, battery = 90f)