findfamily: add custom UWB tracker crowd-finding scaffold behind DEV_BUILD
- Commit
1788ee3ed0fb9b7494dbe7dbf08161525c6f71d4- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-12 23:30 UTC (3 months ago)
- Parents
6ac6b2d
Diff
FINDFAMILY_UWB_TRACKER_DESIGN.md
diff --git a/FINDFAMILY_UWB_TRACKER_DESIGN.md b/FINDFAMILY_UWB_TRACKER_DESIGN.mdnew file mode 100644index 0000000000..5c5e35f7b9--- /dev/null+++ b/FINDFAMILY_UWB_TRACKER_DESIGN.md@@ -0,0 +1,242 @@+# FindFamily Custom UWB Tracker — Design++Design for adding **custom, DIY UWB item-trackers** to FindFamily: binding a+tracker to its owner, and a global crowd-finding network so any phone running+FindFamily can anonymously report a tracker's location back to its owner —+plus phone-native UWB precision finding for the last few meters.++Hardware target: **ESP32 / nRF52 MCU + Qorvo DW3000** (FiRa-capable UWB).++---++## Implementation status (v1 scaffold, DEV_BUILD-gated)++A first full-stack scaffold is implemented behind `BuildConfig.DEV_BUILD`+(true for `assembleDev`/`assembleDebug`, false for `assembleRelease`). Chosen+crypto: **rotating-hash + server-served ML-KEM key** (max reuse; server can+link a rotating id → tracker, accepted tradeoff).++Client (`findfamily/`):+- `build.gradle.kts` — `DEV_BUILD` BuildConfig flag; `src/dev/AndroidManifest.xml` — BLE permissions (dev only).+- `data/User.kt` (`UserKind`, `kind`) + `data/FFDatabase.kt` (migration 9→10).+- `tracker/` — `TrackerFeature` (gate), `TrackerProtocol` (epoch-id HMAC + report seal/open, unit-tested), `TrackerStore` (owner secret/private-key store), `TrackerBle` (BLE contract), `TrackerBeaconScanner` (finder scan), `TrackerProvisioner` (GATT binding), `TrackerBinder` (bind flow), `TrackerReporting` (finder upload + owner fetch), `TrackerUwbGatt` (FiRa-over-GATT seam).+- `util/Networking.kt` — opcodes 0x06–0x0B + `registerTracker`/`resolveTrackerBundle`/`uploadTrackerReport`/`fetchTrackerReports`.+- `util/LocationTrackingService.kt` — finder scan + owner report polling (gated).+- UI — dev-only "Add tracker" FAB (`ui/MainPage.kt`) + `ui/dialogs/AddTrackerDialog.kt` + `Route.AddTrackerDialog`.+- Test — `src/test/.../tracker/TrackerProtocolTest.kt`.++Server (`~/Documents/code/location_share_server`):+- `src/handlers/findfamily.rs` — same opcodes 0x06–0x0B (TRACKER_REGISTER / RESOLVE / REPORT_PUT / REPORT_GET) with HMAC epoch-id, lazy TTL purge, unit tests.+- `src/state.rs`, `src/main.rs` — `ff_trackers` + `ff_reports` maps.++Remaining seams (need hardware/firmware): DW3110 FiRa responder + BLE GATT+firmware; phone↔tracker UWB ranging (`TrackerUwbGatt.startRanging`); DULT+anti-stalking detector.++---++## 1. Locked decisions++| Area | Decision | Rationale |+|---|---|---|+| Tracker identity | Model as `User(kind = TRACKER)` | Reuses map pins, Room DB, the E2E relay, and `processIncomingLocations` with near-zero UI churn — the whole app already keys on `userid`. |+| Crowd-finding crypto | **Option B** — rotating per-epoch EC keys (AirTag-style) | Structurally prevents the server from building a movement history of any tracker; the correct anti-stalking posture for a network where *strangers* report your tracker. |+| UWB | Phone-native **FiRa** ranging; **Android-only** OOB for v1 | The phone's UWB radio speaks FiRa; Android interop only needs matched session params exchanged out-of-band (no Apple MFi/NI needed yet). |+| UWB hardware | **Qorvo DW3110** (DWM3000 module, built on DW3110) + own MCU + **Qorvo FiRa stack** | DW3110 is 802.15.4z with STS, channels 5 & 9 → real FiRa sessions that range with phones. RYUW122 as a *sealed module* runs proprietary AT-command ranging and can't interop with phones. |+| Provisioning | **BLE GATT** | Same radio as the crowd-finding beacon; wireless binding. |++---++## 2. Why not the RYUW122 as-is, and why UWB (not BLE) for finding++- The RYUW122 is built on a **Qorvo DW3000** (FiRa-capable silicon), but it is a+ sealed module whose onboard MCU runs **Reyax's proprietary AT-command**+ ranging over UART. That firmware is not FiRa and (almost certainly) not+ reflashable — so a phone cannot range with it. The fix is to keep the DW3000+ chip but use a board whose MCU **we** flash with a FiRa stack.+- **UWB is not a discovery radio** — it has no advertising/beaconing mode. The+ global "any phone notices it" network therefore rides **BLE advertising**+ (discovery + crowd reports), while **UWB/FiRa** is used only for the owner's+ precision finding once nearby. This mirrors how commercial UWB trackers work.++### Chip choice (locked): Qorvo DW3110++- **DW3110** — 802.15.4z + **STS**, channels **5 & 9** → interoperates with+ phone-native UWB. This is the silicon inside the **DWM3000** module.+- **Single RF port → no on-chip PDoA/AoA.** This is fine: the **phone** measures+ angle with its own multi-antenna array (`UwbController.stream()` reads+ azimuth/elevation from the phone's `RangingData`); the tracker only has to be a+ FiRa **responder**. Distance + arrow still work. The dual-port **DW3210** would+ only be needed if the *tracker* had to sense direction (not required here).+- **Module vs. bare chip**: start with the **DWM3000 module** (RF/antenna/+ shielding done + pre-tested) to skip RF headaches; drop to the bare **DW3110**+ on a custom PCB later if needed.+- **Rejected: DW1000** — first-gen 802.15.4-2011, **no STS**, no channel 9;+ cannot range with phones (same trap as the sealed RYUW122).++### Android FiRa OOB — the key simplification+To interop with an **iPhone**, an accessory must implement Apple's Nearby+Interaction Accessory Protocol (the `UwbAccessoryProtocol.kt` stub) and, for a+product, MFi. To interop with **Android**, the phone (FiRa **controller /+initiator**) simply picks all session params (address, channel, preamble,+session id, STS key) and hands them to the tracker (FiRa **controlee /+responder**) over any side channel. FindFamily already generates exactly these+params in `UwbController.openController()` and already exchanges them for+phone↔phone over its WebSocket. For the tracker we deliver them over **BLE+GATT** instead. This is meaningfully less work than a full MFi accessory.++---++## 3. Entity model++Add a discriminator to `findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt`:++```+enum class UserKind { PERSON, TRACKER }+// User gains: val kind: UserKind = UserKind.PERSON+```++A tracker `User`:+- has its own random 64-bit `userid` and PQC bundle;+- is **owner-only** custodian of the tracker's **private** PQC bundle + **beacon+ master secret** (stored in DataStore, never synced);+- is non-interactive: no sharing toggles, no waypoint auto-toggle, no heartbeat+ publish. It only ever appears as a received location (a map pin).++A tracker report is just a `LocationValue` with `userid = tracker_userid`, so it+renders through the existing `processIncomingLocations` path unchanged.++---++## 4. Binding (goal a) — BLE GATT provisioning++1. Unprovisioned tracker advertises a BLE "new tracker" GATT service.+2. Phone scans → shows "New tracker found" → user taps **Bind**.+3. Phone mints locally:+ - random `userid`,+ - PQC keypair — reuse `Networking.generatePqcKeyPair()`,+ - 32-byte `beacon_secret`,+ - a long-term **UWB STS/session key** derived from `beacon_secret`.+4. Phone writes over a GATT **provisioning characteristic**: `userid`,+ `beacon_secret`, epoch config, UWB base params (channel/preamble + derived+ STS key).+5. Phone persists `User(kind = TRACKER)` + private bundle + secret.+6. **Ownership = possession of the private key + secret.** Unbind requires the+ secret (anti-theft lock), so a found tracker can't be silently re-bound.++The tracker never runs PQC — it only derives rotating beacon keys (cheap). All+heavy crypto stays on phones.++---++## 5. Crowd finding (goal b) — Option B, end to end++### 5.1 Beacon (tracker)+Every epoch (~15 min):+```+priv_epoch = HKDF(beacon_secret, epoch)+pub_epoch = priv_epoch · G // X25519 (recommended curve)+```+BLE-advertise `pub_epoch` (+ a battery byte). No static identifier is ever+broadcast, so the tracker can't be followed by ID. Cost on-device: one HKDF ++one EC scalar-mult per epoch.++### 5.2 Finder (any FindFamily phone)+- Add a **BLE scan callback** in `LocationTrackingService`, right beside+ `handleUwbEnvelopes()` (the foreground service is already the natural host).+- On hearing a tracker beacon:+ - build a `LocationValue` at the finder's **own** current GPS,+ - `ciphertext = ECIES(pub_epoch, LocationValue)`,+ - upload `{ SHA256(pub_epoch), ciphertext }` to the new report-upload endpoint.+- Rate-limit / dedup per `(pub_epoch, coarse-time)`; require decent GPS accuracy.+- The finder never learns whose tracker it is.++### 5.3 Server (new work — the critical piece outside this repo)+Two endpoints on `findfamily.cc`:+- `report-upload { hash, ciphertext }`+- `report-fetch-by-hash [hashes] -> [ciphertext]`+with a retention window (e.g. 7 days) + abuse/rate-limit policy. The server+sees only opaque hashes and ciphertext — it cannot link reports to a tracker or+an owner.++### 5.4 Owner retrieval+- Recompute the expected `SHA256(pub_epoch)` for the last N epochs.+- Fetch matching ciphertexts, decrypt with the per-epoch `priv_epoch`.+- Emit a `LocationValue` with `userid = tracker_userid` → flows through the+ existing `processIncomingLocations` → renders as the tracker's map pin. **No+ map/UI changes required.**++---++## 6. UWB precision finding (owner, FiRa OOB)++Owner-only, once near the tracker:+- Reuse `UwbController.openController()` to mint FiRa params (phone = controller+ / initiator).+- Deliver params to the tracker over a **BLE GATT session characteristic**+ (instead of the WS `UwbEnvelope`). Because the STS key was derived at bind+ time, the per-find handoff carries only channel/slot.+- Both start the FiRa session; `UwbController.stream()` yields distance + AoA+ arrow **unchanged**.+- The `UwbAccessoryProtocol` stubs stay parked for a future iOS phase.++This reuses the entire ranging path; only the *handshake transport* changes+(BLE GATT vs. WebSocket envelope).++---++## 7. Anti-stalking (DULT)++Independent of the above and important to ship: a finder-side detector that+flags a **foreign beacon persisting across time and space** ("unknown tracker+traveling with you"), aligned with the cross-industry DULT specification.++---++## 8. Firmware responsibilities (DW3110 + own MCU)++- BLE GATT server: provisioning characteristic + per-find UWB-session+ characteristic.+- BLE beacon: rotating `pub_epoch` per epoch (HKDF + EC mul).+- Qorvo FiRa **responder / controlee** session on the DW3000.+- **Critical-path risk**: a reliable FiRa responder with solid phone interop+ (STS / timing) is a multi-week embedded effort, and Qorvo stack access+ typically needs registration/NDA. The Android app-side work is comparatively+ small.++---++## 9. Phasing++1. **Entity + binding** — `User.kind`, BLE GATT provisioning, key/secret+ generation & storage.+2. **Crowd network** — beacon format, finder BLE scan + upload, server+ endpoints, owner fetch/decrypt → map.+3. **UWB precision find** — BLE GATT param handoff + firmware FiRa responder ++ wiring into `UwbSessionManager`.+4. **Anti-stalking** detector.++---++## 10. Open items to confirm++- ECIES curve — **X25519** is the clean pick.+- Epoch length vs. beacon-privacy / retrieval-cost tradeoff.+- Server retention window + abuse / rate-limit policy.+- Ownership of the server-side change (the one piece outside this repo).+- Verify (datasheet / Reyax) there is truly no FiRa/NI mode or reflash path on+ the RYUW122 before fully committing to new hardware.++---++## 11. Key existing code this builds on++- `findfamily/.../data/User.kt` — entity to extend with `kind`.+- `findfamily/.../data/LocationValue.kt` — report payload (already `userid`-keyed).+- `findfamily/.../util/Networking.kt` — PQC identity, relay, `generatePqcKeyPair()`.+- `findfamily/.../util/LocationTrackingService.kt` — foreground host for the BLE+ scan + `processIncomingLocations` (renders tracker pins for free).+- `findfamily/.../uwb/UwbController.kt` — FiRa param generation + `stream()`.+- `findfamily/.../util/UwbSessionManager.kt` — session state machine to wire the+ BLE GATT handshake into.+- `findfamily/.../uwb/UwbAccessoryProtocol.kt` — parked for future iOS interop.
build-logic/src/main/kotlin/common-conventions-app.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts b/build-logic/src/main/kotlin/common-conventions-app.gradle.ktsindex 26a5a2f7f6..cb7f879c52 100644--- a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-app.gradle.kts@@ -61,6 +61,11 @@ configure<com.android.build.api.dsl.ApplicationExtension> { } buildFeatures { compose = true+ // Repo-wide DEV_BUILD flag (see buildTypes below). Every app gets a+ // BuildConfig.DEV_BUILD constant: true for assembleDev/assembleDebug,+ // false for assembleRelease. Gate experimental/dev-only features on it so+ // R8 strips them from release builds.+ buildConfig = true } namespace = "com.vayunmathur${path.replace(":", ".")}"@@ -135,11 +140,13 @@ configure<com.android.build.api.dsl.ApplicationExtension> { proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), proguardFile.absolutePath, )+ buildConfigField("boolean", "DEV_BUILD", "false") } debug { ndk { abiFilters.add("arm64-v8a") }+ buildConfigField("boolean", "DEV_BUILD", "true") } create("dev") { initWith(getByName("release"))@@ -150,6 +157,8 @@ configure<com.android.build.api.dsl.ApplicationExtension> { abiFilters.clear() abiFilters.add("arm64-v8a") }+ // initWith(release) copied DEV_BUILD=false; dev is a developer build, so flip it on.+ buildConfigField("boolean", "DEV_BUILD", "true") } }
findfamily/src/dev/AndroidManifest.xml
diff --git a/findfamily/src/dev/AndroidManifest.xml b/findfamily/src/dev/AndroidManifest.xmlnew file mode 100644index 0000000000..cbef43f128--- /dev/null+++ b/findfamily/src/dev/AndroidManifest.xml@@ -0,0 +1,19 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+ Dev-only manifest overlay. AGP merges this ONLY into the `dev` (and, by source-set+ convention, debug) variant, never into `release`. It declares the Bluetooth+ permissions the experimental custom UWB tracker feature needs for BLE binding+ (GATT) and crowd-finding (LE scan). Release builds gate the whole feature off via+ BuildConfig.DEV_BUILD and therefore never declare or request these.+-->+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <!-- Crowd-finding: scan for tracker beacons. Binding: connect to the tracker's+ GATT server. Advertising is reserved for future tracker-emulation testing. -->+ <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />+ <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />+ <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />++ <uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />++</manifest>
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 eeec1f42d7..f471a9c08f 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt@@ -53,6 +53,7 @@ import com.vayunmathur.findfamily.ui.MainPage import com.vayunmathur.findfamily.ui.UwbRangingScreen import com.vayunmathur.findfamily.ui.dialogs.AddLinkDialog import com.vayunmathur.findfamily.ui.dialogs.AddPersonDialog+import com.vayunmathur.findfamily.ui.dialogs.AddTrackerDialog import com.vayunmathur.findfamily.ui.dialogs.decodeBase26 import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.dialog.DatePickerDialog@@ -328,6 +329,10 @@ sealed interface Route: NavKey { @Serializable data object AddLinkDialog: Route + /** Dev-only (DEV_BUILD): bind a new custom UWB tracker. */+ @Serializable+ data object AddTrackerDialog: Route+ @Serializable data object MissingFeaturesDialog: Route @@ -382,6 +387,9 @@ fun Navigation( entry<Route.AddLinkDialog>(metadata = DialogPage()) { AddLinkDialog(backStack, ffViewModel) }+ entry<Route.AddTrackerDialog>(metadata = DialogPage()) {+ AddTrackerDialog(backStack)+ } entry<Route.MissingFeaturesDialog>(metadata = DialogPage()) { MissingFeaturesDialog(backStack) }
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 6e7a6eb50b..d61da0e3ab 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt@@ -149,7 +149,7 @@ interface TemporaryLinkDao { suspend fun delete(value: TemporaryLink): Int } -@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 9, exportSchema = false)+@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 10, exportSchema = false) @TypeConverters(DefaultConverters::class) abstract class FFDatabase : RoomDatabase() { abstract fun userDao(): UserDao@@ -211,6 +211,11 @@ abstract class FFDatabase : RoomDatabase() { }, androidx.room.migration.Migration(8, 9) { it.execSQL("ALTER TABLE `User` ADD COLUMN `sharingAutoToggleWaypointId` INTEGER")+ },+ // Custom UWB tracker support (DEV_BUILD): a `User` can now be a person or a+ // tracker. Room stores the enum as its name; existing rows default to PERSON.+ androidx.room.migration.Migration(9, 10) {+ it.execSQL("ALTER TABLE `User` ADD COLUMN `kind` TEXT NOT NULL DEFAULT 'PERSON'") } ) }
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 d271b8ea60..abbc1e72f7 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/User.kt@@ -14,6 +14,19 @@ enum class RequestStatus { AWAITING_RESPONSE } +/**+ * Distinguishes a normal person contact from a custom UWB item-tracker. Trackers+ * reuse the [User] row (and therefore the whole map/list/relay pipeline) but are+ * non-interactive: they never publish, never auto-toggle, and only ever appear as+ * a received location pin. Stored by Room as the enum name (`"PERSON"`/`"TRACKER"`).+ * Gated behind `BuildConfig.DEV_BUILD`; release rows are always [PERSON].+ */+@Serializable+enum class UserKind {+ PERSON,+ TRACKER+}+ @Serializable @Entity data class User(@@ -35,7 +48,10 @@ data class User( * Mutually exclusive with [sharingAutoToggleAt]: setting one clears the other. */ val sharingAutoToggleWaypointId: Long? = null, /** Peer post-quantum public bundle (base64: [4B kemLen][kemPubDer][dsaPubDer]), nullable for backward compat. */- val pqcEncryptionKey: String? = null+ val pqcEncryptionKey: String? = null,+ /** Whether this row is a person contact or a custom UWB tracker. Defaults to+ * [UserKind.PERSON]; only the DEV_BUILD tracker feature ever writes [UserKind.TRACKER]. */+ val kind: UserKind = UserKind.PERSON ): DatabaseItem { companion object { val EMPTY = User(" ", null, "Unnamed Location", true, RequestStatus.MUTUAL_CONNECTION, Clock.System.now(), null)
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.ktnew file mode 100644index 0000000000..61dcf4f026--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBeaconScanner.kt@@ -0,0 +1,83 @@+package com.vayunmathur.findfamily.tracker++import android.annotation.SuppressLint+import android.bluetooth.BluetoothManager+import android.bluetooth.le.ScanCallback+import android.bluetooth.le.ScanFilter+import android.bluetooth.le.ScanResult+import android.bluetooth.le.ScanSettings+import android.content.Context+import android.os.ParcelUuid+import android.util.Log+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.callbackFlow++/**+ * Finder side of the crowd-finding network: passively scans for tracker beacons+ * ([TrackerBle.SERVICE_UUID]) and emits a [TrackerSighting] for each advertisement+ * seen. Hosted by the foreground `LocationTrackingService` so scanning continues in+ * the background (gated behind `TrackerFeature.enabled`).+ *+ * Permissions (`BLUETOOTH_SCAN`) are declared only in `src/dev/AndroidManifest.xml`;+ * a missing grant surfaces as a `SecurityException` which is caught and closes the+ * flow rather than crashing.+ */+class TrackerBeaconScanner(private val context: Context) {++ @SuppressLint("MissingPermission")+ fun sightings(): Flow<TrackerSighting> = callbackFlow {+ val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager+ val scanner = manager?.adapter?.bluetoothLeScanner+ if (scanner == null) {+ Log.i(TAG, "sightings: no BLE scanner (adapter off or unavailable)")+ close()+ return@callbackFlow+ }++ val callback = object : ScanCallback() {+ override fun onScanResult(callbackType: Int, result: ScanResult) {+ val serviceData = result.scanRecord+ ?.getServiceData(ParcelUuid(TrackerBle.SERVICE_UUID)) ?: return+ if (serviceData.size < TrackerProtocol.EPOCH_ID_LEN) return+ val epochId = serviceData.copyOf(TrackerProtocol.EPOCH_ID_LEN)+ val battery = if (serviceData.size > TrackerProtocol.EPOCH_ID_LEN) {+ serviceData[TrackerProtocol.EPOCH_ID_LEN].toInt() and 0xFF+ } else -1+ trySend(TrackerSighting(epochId, battery, result.rssi))+ }++ override fun onScanFailed(errorCode: Int) {+ Log.w(TAG, "BLE scan failed: $errorCode")+ }+ }++ val filter = ScanFilter.Builder()+ .setServiceUuid(ParcelUuid(TrackerBle.SERVICE_UUID))+ .build()+ val settings = ScanSettings.Builder()+ .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)+ .build()++ try {+ scanner.startScan(listOf(filter), settings, callback)+ Log.i(TAG, "tracker beacon scan started")+ } catch (e: SecurityException) {+ Log.w(TAG, "startScan denied (missing BLUETOOTH_SCAN)", e)+ close(e)+ return@callbackFlow+ } catch (e: Exception) {+ Log.w(TAG, "startScan failed", e)+ close(e)+ return@callbackFlow+ }++ awaitClose {+ runCatching { scanner.stopScan(callback) }+ }+ }++ 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.ktnew file mode 100644index 0000000000..01d0a15721--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.kt@@ -0,0 +1,75 @@+package com.vayunmathur.findfamily.tracker++import android.bluetooth.BluetoothDevice+import android.content.Context+import android.util.Log+import com.vayunmathur.findfamily.data.FFDatabase+import com.vayunmathur.findfamily.data.RequestStatus+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.data.UserKind+import com.vayunmathur.findfamily.util.Networking+import com.vayunmathur.library.room.buildDatabase+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import java.security.SecureRandom+import kotlin.random.Random+import kotlin.time.Clock++/**+ * Owner-side binding: mint a tracker identity, persist it, register it with the+ * server, and provision the physical device over BLE GATT. Centralised here (rather+ * than in the ViewModel) so the whole tracker feature stays in one package behind+ * `TrackerFeature.enabled`.+ */+object TrackerBinder {+ private const val TAG = "TrackerBinder"++ /**+ * Bind [device] as a new tracker named [name].+ *+ * Steps: generate an ML-KEM/ML-DSA keypair (public bundle stored on the `User`+ * row, private bundle kept owner-only in [TrackerStore]); generate a 32-byte+ * beacon secret; create the `User(kind = TRACKER)` row; register the tracker on+ * the server so finders can resolve it; write the provisioning blob to the+ * device. Returns true iff the GATT provisioning write succeeds.+ */+ suspend fun bind(context: Context, name: String, device: BluetoothDevice): Boolean =+ withContext(Dispatchers.IO) {+ runCatching {+ val db = context.buildDatabase<FFDatabase>()+ val userDao = db.userDao()+ val store = TrackerStore(DataStoreUtils.getInstance(context))++ val keys = Networking.generatePqcKeyPair()+ val publicBundle = decodeB64(keys.publicBundleB64)+ val privateBundle = decodeB64(keys.privateBundleB64)+ val secret = ByteArray(TrackerProtocol.SECRET_LEN).also { SecureRandom().nextBytes(it) }+ val trackerId = Random.nextLong(from = 1, until = Long.MAX_VALUE)++ store.save(trackerId, secret, privateBundle)+ userDao.upsert(+ User(+ name = name,+ photo = null,+ locationName = "Unknown Location",+ sendingEnabled = false,+ requestStatus = RequestStatus.MUTUAL_CONNECTION,+ lastLocationChangeTime = Clock.System.now(),+ encryptionKey = null,+ id = trackerId,+ pqcEncryptionKey = keys.publicBundleB64,+ kind = UserKind.TRACKER,+ )+ )+ // Best-effort: registration self-heals on the next heartbeat if the+ // socket is momentarily down (see pollTrackerReports).+ runCatching { Networking.registerTracker(trackerId, secret, publicBundle) }++ TrackerProvisioner(context).provision(device, trackerId, secret)+ }.onFailure { Log.w(TAG, "bind failed", it) }.getOrDefault(false)+ }++ private fun decodeB64(s: String): ByteArray =+ android.util.Base64.decode(s, android.util.Base64.NO_WRAP)+}
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBle.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBle.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBle.ktnew file mode 100644index 0000000000..0b8df30806--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBle.kt@@ -0,0 +1,58 @@+package com.vayunmathur.findfamily.tracker++import java.util.UUID++/**+ * BLE contract shared between the app and the tracker firmware (ESP32/nRF52 ++ * Qorvo DW3110). Documented here so the embedded side has an exact spec.+ *+ * ## Advertising (crowd-finding)+ * A provisioned tracker advertises [SERVICE_UUID] with **service data** laid out as:+ * ```+ * [16B epochId][1B battery%]+ * ```+ * where `epochId = TrackerProtocol.epochId(secret, currentEpoch)` and `battery` is+ * 0..100. The id rotates every [TrackerProtocol.EPOCH_SECONDS]; no static id is ever+ * broadcast.+ *+ * ## Binding (GATT)+ * An unprovisioned tracker advertises [UNPROVISIONED_SERVICE_UUID] and exposes a+ * GATT server with:+ * - [PROVISION_CHARACTERISTIC_UUID] (write): the phone writes the provisioning blob+ * ```+ * [8B trackerUserId BE][32B beaconSecret]+ * ```+ * After a successful write the tracker persists these, stops advertising the+ * unprovisioned service, and begins the rotating beacon above.+ * - [UWB_SESSION_CHARACTERISTIC_UUID] (write/notify): per-find FiRa session params+ * for phone-native UWB precision finding (see [TrackerUwbGatt]).+ */+object TrackerBle {+ /** Service a provisioned tracker advertises its rotating beacon under. */+ val SERVICE_UUID: UUID = UUID.fromString("6b1d2f00-4b3a-4c7e-9a10-1f2e3d4c5b6a")++ /** Service an unprovisioned (pairing-mode) tracker advertises. */+ val UNPROVISIONED_SERVICE_UUID: UUID = UUID.fromString("6b1d2f01-4b3a-4c7e-9a10-1f2e3d4c5b6a")++ /** GATT characteristic the phone writes the provisioning blob to. */+ val PROVISION_CHARACTERISTIC_UUID: UUID = UUID.fromString("6b1d2f02-4b3a-4c7e-9a10-1f2e3d4c5b6a")++ /** GATT characteristic carrying per-find FiRa session params for UWB ranging. */+ val UWB_SESSION_CHARACTERISTIC_UUID: UUID = UUID.fromString("6b1d2f03-4b3a-4c7e-9a10-1f2e3d4c5b6a")+}++/** One crowd-finding beacon sighting heard by a finder phone. */+data class TrackerSighting(+ /** The 16-byte rotating id from the advertisement; used verbatim as the report key. */+ val epochId: ByteArray,+ /** Battery percent from the advertisement, or -1 when absent. */+ val battery: Int,+ /** Received signal strength (dBm) — a coarse proximity hint. */+ val rssi: Int,+) {+ override fun equals(other: Any?): Boolean =+ other is TrackerSighting && epochId.contentEquals(other.epochId) &&+ battery == other.battery && rssi == other.rssi++ override fun hashCode(): Int = epochId.contentHashCode() * 31 + battery * 31 + rssi+}
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerFeature.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerFeature.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerFeature.ktnew file mode 100644index 0000000000..c86693a5b0--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerFeature.kt@@ -0,0 +1,19 @@+package com.vayunmathur.findfamily.tracker++import com.vayunmathur.findfamily.BuildConfig++/**+ * Single on/off gate for the experimental **custom UWB tracker** feature+ * (crowd-finding network + BLE binding + phone-native UWB precision finding).+ *+ * Backed by [BuildConfig.DEV_BUILD], which is `true` for `assembleDev`/`assembleDebug`+ * and `false` for `assembleRelease`. Because it's a compile-time constant, every+ * `if (TrackerFeature.enabled)` branch (and everything it reaches) is stripped from+ * release builds by R8, and the BLE permissions declared only in+ * `src/dev/AndroidManifest.xml` are never requested there.+ *+ * All tracker entry points in the app must be guarded by this flag.+ */+object TrackerFeature {+ val enabled: Boolean get() = BuildConfig.DEV_BUILD+}
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProtocol.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProtocol.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProtocol.ktnew file mode 100644index 0000000000..486181e2f8--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProtocol.kt@@ -0,0 +1,114 @@+package com.vayunmathur.findfamily.tracker++import com.vayunmathur.e2ee.Pqc+import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.LocationValueCompatible+import kotlinx.serialization.json.Json+import javax.crypto.Mac+import javax.crypto.spec.SecretKeySpec++/**+ * Pure-Kotlin crypto/wire logic for the custom UWB tracker crowd-finding network.+ * No Android dependencies, so it is fully unit-testable (see TrackerProtocolTest)+ * and its byte formats can be mirrored exactly on the Rust server and on the+ * ESP32/nRF firmware.+ *+ * Crypto model (chosen tradeoff): **rotating-hash + server-served ML-KEM key**.+ * - The tracker BLE-beacons a small rotating [epochId] derived from a per-tracker+ * [SECRET_LEN]-byte secret it was provisioned with at bind time. No static id is+ * ever broadcast, so a beacon can't be trivially followed by identity.+ * - A finder resolves that epoch-id to the tracker's ML-KEM public bundle via the+ * server, seals its own GPS to it with [sealReport], and uploads the ciphertext+ * keyed by the epoch-id. The finder never learns whose tracker it is (the sealed+ * location carries userid 0).+ * - The owner recomputes [recentEpochIds] (it holds the secret), fetches matching+ * reports, and decrypts each with [openReport] using the tracker's ML-KEM private+ * bundle, stamping the resulting [LocationValue] with the tracker's own userid so+ * it renders as that tracker's map pin.+ */+object TrackerProtocol {++ /** Beacon rotation period. Must equal the server's `TRACKER_EPOCH_SECS`. */+ const val EPOCH_SECONDS: Long = 900L // 15 minutes++ /** Length of the rotating beacon id advertised over BLE and used as the report key. */+ const val EPOCH_ID_LEN: Int = 16++ /** Length of the per-tracker beacon master secret provisioned at bind time. */+ const val SECRET_LEN: Int = 32++ /** Domain-separation tag mixed into every epoch-id HMAC. Must match the server. */+ private const val EPOCH_DOMAIN = "fftrk1"++ private val json = Json { ignoreUnknownKeys = true }++ /** The current epoch number for a wall-clock time in milliseconds. */+ fun currentEpoch(nowMs: Long = System.currentTimeMillis()): Long =+ (nowMs / 1000L) / EPOCH_SECONDS++ /**+ * The 16-byte rotating beacon id for a `(secret, epoch)` pair:+ * `HMAC-SHA256(secret, "fftrk1" || u64_be(epoch))[..16]`. Deterministic and+ * byte-identical to the server's `tracker_epoch_id`.+ */+ fun epochId(secret: ByteArray, epoch: Long): ByteArray {+ val mac = Mac.getInstance("HmacSHA256")+ mac.init(SecretKeySpec(secret, "HmacSHA256"))+ mac.update(EPOCH_DOMAIN.toByteArray(Charsets.US_ASCII))+ mac.update(u64be(epoch))+ return mac.doFinal().copyOf(EPOCH_ID_LEN)+ }++ /**+ * The epoch-ids the owner should query to catch recent sightings: the current+ * epoch and [back] previous ones (so late-delivered reports within roughly+ * `back * EPOCH_SECONDS` are still found).+ */+ fun recentEpochIds(+ secret: ByteArray,+ nowMs: Long = System.currentTimeMillis(),+ back: Int = 8,+ ): List<ByteArray> {+ val cur = currentEpoch(nowMs)+ return (0..back).map { epochId(secret, cur - it) }+ }++ /**+ * Finder side: seal this finder's own [finderLocation] to the tracker's ML-KEM+ * public [trackerBundle]. The userid is zeroed so the report never reveals the+ * finder's identity to the owner; the owner restamps it in [openReport].+ */+ fun sealReport(trackerBundle: ByteArray, finderLocation: LocationValue): ByteArray {+ val anon = finderLocation.copy(userid = 0L).toCompatible(senderPlatform = null)+ val str = json.encodeToString(anon)+ return Pqc.encryptTo(trackerBundle, str.encodeToByteArray())+ }++ /**+ * Owner side: decrypt a crowd report [ciphertext] with the tracker's private+ * bundle ([privateBundle], layout `[4B kemPrivLen][kemPriv][dsaPriv]`, as+ * produced by `Networking.generatePqcKeyPair`) and stamp it with the tracker's+ * [trackerUserId] so it flows through the normal incoming-location pipeline.+ */+ fun openReport(privateBundle: ByteArray, ciphertext: ByteArray, trackerUserId: Long): LocationValue {+ val kemPriv = kemPrivFromPrivateBundle(privateBundle)+ val plain = Pqc.decrypt(kemPriv, ciphertext)+ val compat = json.decodeFromString<LocationValueCompatible>(plain.decodeToString())+ return compat.toLocationValue().copy(userid = trackerUserId)+ }++ /** Extracts the ML-KEM private DER from a `[4B kemPrivLen][kemPriv][dsaPriv]` bundle. */+ fun kemPrivFromPrivateBundle(priv: ByteArray): ByteArray {+ val len = ((priv[0].toInt() and 0xFF) shl 24) or+ ((priv[1].toInt() and 0xFF) shl 16) or+ ((priv[2].toInt() and 0xFF) shl 8) or+ (priv[3].toInt() and 0xFF)+ return priv.copyOfRange(4, 4 + len)+ }++ private fun u64be(v: Long): ByteArray {+ val out = ByteArray(8)+ for (i in 0 until 8) out[i] = (v ushr (56 - i * 8)).toByte()+ return out+ }+}
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.ktnew file mode 100644index 0000000000..3ad12f8f3a--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.kt@@ -0,0 +1,142 @@+package com.vayunmathur.findfamily.tracker++import android.annotation.SuppressLint+import android.bluetooth.BluetoothDevice+import android.bluetooth.BluetoothGatt+import android.bluetooth.BluetoothGattCallback+import android.bluetooth.BluetoothGattCharacteristic+import android.bluetooth.BluetoothManager+import android.bluetooth.BluetoothProfile+import android.bluetooth.le.ScanCallback+import android.bluetooth.le.ScanFilter+import android.bluetooth.le.ScanResult+import android.bluetooth.le.ScanSettings+import android.content.Context+import android.os.Build+import android.os.ParcelUuid+import android.util.Log+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.callbackFlow+import kotlinx.coroutines.suspendCancellableCoroutine+import java.util.concurrent.atomic.AtomicBoolean+import kotlin.coroutines.resume++/**+ * Binding side: discovers unprovisioned trackers over BLE and writes the+ * provisioning blob to them over GATT (see [TrackerBle] for the contract).+ *+ * The GATT round-trip (connect → discover services → write) is real; the only+ * device-dependent seam is the firmware's own persistence + mode switch after the+ * write, which can't be exercised without hardware. Errors are surfaced as `false`+ * / a closed flow rather than crashes.+ */+class TrackerProvisioner(private val context: Context) {++ /** Scans for trackers currently in pairing mode ([TrackerBle.UNPROVISIONED_SERVICE_UUID]). */+ @SuppressLint("MissingPermission")+ fun unprovisioned(): Flow<BluetoothDevice> = callbackFlow {+ val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager+ val scanner = manager?.adapter?.bluetoothLeScanner+ if (scanner == null) { close(); return@callbackFlow }++ val callback = object : ScanCallback() {+ override fun onScanResult(callbackType: Int, result: ScanResult) {+ trySend(result.device)+ }+ override fun onScanFailed(errorCode: Int) {+ Log.w(TAG, "unprovisioned scan failed: $errorCode")+ }+ }+ val filter = ScanFilter.Builder()+ .setServiceUuid(ParcelUuid(TrackerBle.UNPROVISIONED_SERVICE_UUID))+ .build()+ val settings = ScanSettings.Builder()+ .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)+ .build()+ try {+ scanner.startScan(listOf(filter), settings, callback)+ } catch (e: Exception) {+ close(e); return@callbackFlow+ }+ awaitClose { runCatching { scanner.stopScan(callback) } }+ }++ /**+ * Connect to [device], discover services, and write the provisioning blob+ * `[8B trackerUserId BE][32B secret]` to [TrackerBle.PROVISION_CHARACTERISTIC_UUID].+ * Returns true iff the characteristic write reports success.+ */+ @SuppressLint("MissingPermission")+ @Suppress("DEPRECATION")+ suspend fun provision(device: BluetoothDevice, trackerUserId: Long, secret: ByteArray): Boolean =+ suspendCancellableCoroutine { cont ->+ require(secret.size == TrackerProtocol.SECRET_LEN) { "secret must be ${TrackerProtocol.SECRET_LEN} bytes" }+ val blob = ByteArray(8 + secret.size)+ for (i in 0 until 8) blob[i] = (trackerUserId.toULong() shr (56 - i * 8)).toByte()+ secret.copyInto(blob, 8)++ val resumed = AtomicBoolean(false)+ var gatt: BluetoothGatt? = null+ fun finish(result: Boolean) {+ if (resumed.compareAndSet(false, true)) {+ runCatching { gatt?.disconnect() }+ runCatching { gatt?.close() }+ if (cont.isActive) cont.resume(result)+ }+ }++ val callback = object : BluetoothGattCallback() {+ override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {+ if (newState == BluetoothProfile.STATE_CONNECTED) {+ runCatching { g.discoverServices() }+ } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {+ finish(false)+ }+ }++ override fun onServicesDiscovered(g: BluetoothGatt, status: Int) {+ if (status != BluetoothGatt.GATT_SUCCESS) { finish(false); return }+ val ch = g.getService(TrackerBle.UNPROVISIONED_SERVICE_UUID)+ ?.getCharacteristic(TrackerBle.PROVISION_CHARACTERISTIC_UUID)+ if (ch == null) { finish(false); return }+ val ok = writeChar(g, ch, blob)+ if (!ok) finish(false)+ }++ @Deprecated("compat shim for API < 33")+ override fun onCharacteristicWrite(g: BluetoothGatt, ch: BluetoothGattCharacteristic, status: Int) {+ finish(status == BluetoothGatt.GATT_SUCCESS)+ }+ }++ gatt = try {+ device.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE)+ } catch (e: Exception) {+ Log.w(TAG, "connectGatt failed", e); null+ }+ if (gatt == null) { finish(false); return@suspendCancellableCoroutine }++ cont.invokeOnCancellation { finish(false) }+ }++ @SuppressLint("MissingPermission")+ @Suppress("DEPRECATION")+ private fun writeChar(gatt: BluetoothGatt, ch: BluetoothGattCharacteristic, value: ByteArray): Boolean =+ try {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ gatt.writeCharacteristic(+ ch, value, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT+ ) == BluetoothGatt.GATT_SUCCESS+ } else {+ ch.value = value+ gatt.writeCharacteristic(ch)+ }+ } catch (e: Exception) {+ Log.w(TAG, "writeCharacteristic failed", e); false+ }++ companion object {+ private const val TAG = "TrackerProvisioner"+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerReporting.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerReporting.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerReporting.ktnew file mode 100644index 0000000000..6ec4fdae49--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerReporting.kt@@ -0,0 +1,63 @@+package com.vayunmathur.findfamily.tracker++import android.util.Log+import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.data.UserKind+import com.vayunmathur.findfamily.util.Networking+import kotlin.io.encoding.Base64++/**+ * Ties the tracker crypto ([TrackerProtocol]) to the relay ([Networking]) for both+ * roles of the crowd-finding network.+ */+object TrackerReporting {+ private const val TAG = "TrackerReporting"++ /**+ * Owner: (re)register a bound tracker with the server so finders can resolve its+ * rotating beacon ids to its ML-KEM bundle. Idempotent — safe to call on every+ * socket (re)connect. The public bundle lives on the `User` row+ * ([User.pqcEncryptionKey]); the beacon secret lives in [TrackerStore].+ */+ suspend fun registerTracker(tracker: User, store: TrackerStore): Boolean {+ if (tracker.kind != UserKind.TRACKER) return false+ val secret = store.secret(tracker.id) ?: return false+ val bundleB64 = tracker.pqcEncryptionKey ?: return false+ val bundle = runCatching { Base64.decode(bundleB64) }.getOrNull() ?: return false+ return Networking.registerTracker(tracker.id, secret, bundle)+ }++ /**+ * Finder: resolve a sighting's rotating id to the owning tracker's ML-KEM bundle,+ * seal this finder's current [finderLocation] to it, and upload the report keyed+ * by the beacon id. Returns false when the id can't be resolved (unknown/foreign+ * tracker) or the socket is down.+ */+ suspend fun reportSighting(sighting: TrackerSighting, finderLocation: LocationValue): Boolean {+ val bundle = Networking.resolveTrackerBundle(sighting.epochId) ?: return false+ val ct = TrackerProtocol.sealReport(bundle, finderLocation)+ val ok = Networking.uploadTrackerReport(sighting.epochId, ct)+ if (ok) Log.i(TAG, "uploaded sighting (rssi=${sighting.rssi}, battery=${sighting.battery})")+ return ok+ }++ /**+ * Owner: fetch and decrypt recent crowd reports for a single [tracker]. Each+ * decrypted [LocationValue] is stamped with the tracker's userid so it flows+ * through the normal incoming-location pipeline and renders as that tracker's pin.+ */+ suspend fun fetchTrackerLocations(tracker: User, store: TrackerStore): List<LocationValue> {+ if (tracker.kind != UserKind.TRACKER) return emptyList()+ val secret = store.secret(tracker.id) ?: return emptyList()+ val priv = store.privateBundle(tracker.id) ?: return emptyList()+ val ids = TrackerProtocol.recentEpochIds(secret)+ val cts = Networking.fetchTrackerReports(ids)+ if (cts.isEmpty()) return emptyList()+ return cts.mapNotNull { ct ->+ runCatching { TrackerProtocol.openReport(priv, ct, tracker.id) }+ .onFailure { Log.w(TAG, "openReport failed for tracker ${tracker.id}", it) }+ .getOrNull()+ }+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerStore.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerStore.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerStore.ktnew file mode 100644index 0000000000..279cf8617b--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerStore.kt@@ -0,0 +1,29 @@+package com.vayunmathur.findfamily.tracker++import com.vayunmathur.library.util.DataStoreUtils++/**+ * Owner-only persistence for bound trackers. Holds, per tracker userid, the two+ * secrets that never leave the owner's device:+ * - the beacon master secret (used to recompute rotating epoch-ids), and+ * - the tracker's ML-KEM **private** bundle (used to decrypt crowd reports).+ *+ * The tracker's **public** bundle is stored on the `User` row itself+ * (`User.pqcEncryptionKey`), reusing the existing key-directory plumbing. The set+ * of owned trackers is simply the `User` rows with `kind == UserKind.TRACKER`, so+ * no separate index is kept here.+ */+class TrackerStore(private val ds: DataStoreUtils) {++ suspend fun save(trackerUserId: Long, secret: ByteArray, privateBundle: ByteArray) {+ ds.setByteArray(secretKey(trackerUserId), secret)+ ds.setByteArray(privKey(trackerUserId), privateBundle)+ }++ suspend fun secret(trackerUserId: Long): ByteArray? = ds.getByteArrayAwait(secretKey(trackerUserId))++ suspend fun privateBundle(trackerUserId: Long): ByteArray? = ds.getByteArrayAwait(privKey(trackerUserId))++ private fun secretKey(id: Long) = "ff_tracker_secret_$id"+ private fun privKey(id: Long) = "ff_tracker_priv_$id"+}
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerUwbGatt.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerUwbGatt.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerUwbGatt.ktnew file mode 100644index 0000000000..aa0e817586--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerUwbGatt.kt@@ -0,0 +1,56 @@+package com.vayunmathur.findfamily.tracker++/**+ * Phone-native **FiRa UWB precision finding** to a bound tracker, over BLE GATT.+ *+ * This is the owner-only "point me to it" last-few-meters step. The design reuses+ * the existing FiRa ranging stack unchanged (`UwbController.openController()` mints+ * the params; `UwbController.stream()` yields distance + AoA); the ONLY thing that+ * differs from the phone-to-phone flow is the transport of the handshake: params go+ * to the tracker over [TrackerBle.UWB_SESSION_CHARACTERISTIC_UUID] instead of the+ * WebSocket `UwbEnvelope`.+ *+ * The wire encoding below is complete and testable; [startRanging] is a documented+ * seam (like `UwbAccessoryProtocol`) because the GATT write + the firmware's FiRa+ * responder session can only be exercised against real DW3110 hardware.+ */+object TrackerUwbGatt {++ /** FiRa session params handed to the tracker for one ranging session. */+ data class SessionParams(+ val localAddress: ByteArray, // phone (controller) 2-byte MAC+ val sessionId: Int,+ val channelNumber: Int,+ val preambleIndex: Int,+ // The STS/session key is derived from the bind-time beacon secret on both+ // ends, so it is NOT sent over the air per-find (only channel/slot are).+ )++ /**+ * Encode the per-find params written to the tracker's UWB session characteristic:+ * `[2B localAddress][4B sessionId BE][1B channel][1B preamble]`.+ */+ fun encodeSessionParams(p: SessionParams): ByteArray {+ require(p.localAddress.size == 2) { "localAddress must be 2 bytes" }+ val out = ByteArray(2 + 4 + 1 + 1)+ p.localAddress.copyInto(out, 0)+ out[2] = (p.sessionId ushr 24).toByte()+ out[3] = (p.sessionId ushr 16).toByte()+ out[4] = (p.sessionId ushr 8).toByte()+ out[5] = p.sessionId.toByte()+ out[6] = p.channelNumber.toByte()+ out[7] = p.preambleIndex.toByte()+ return out+ }++ /**+ * Begin a UWB ranging session to a bound tracker. Requires: (a) writing+ * [encodeSessionParams] to the tracker over GATT, and (b) the DW3110 firmware+ * starting a matching FiRa responder session. Both need hardware, so this is a+ * seam for the on-device implementation phase.+ */+ fun startRanging(): Nothing = throw NotImplementedError(+ "Phone↔tracker FiRa ranging over BLE GATT is not wired yet. " ++ "See TrackerUwbGatt.kt and the DW3110 firmware FiRa-responder contract."+ )+}
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 674b9ab87c..e1f7637eb3 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -94,6 +94,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlin.math.roundToInt import com.vayunmathur.findfamily.R+import com.vayunmathur.findfamily.BuildConfig import com.vayunmathur.findfamily.Route import com.vayunmathur.findfamily.data.LocationValue import com.vayunmathur.findfamily.data.TemporaryLink@@ -470,6 +471,13 @@ fun MainPage( }, { Text(stringResource(R.string.fab_link)) }, { IconLink() })+ if (BuildConfig.DEV_BUILD) {+ FloatingActionButtonMenuItem({+ backStack.add(Route.AddTrackerDialog)+ },+ { Text(stringResource(R.string.fab_tracker)) },+ { IconNavigationArrow() })+ } } } else if (selectedWaypointId != null) { FloatingActionButton(
findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/AddTrackerDialog.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/AddTrackerDialog.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/AddTrackerDialog.ktnew file mode 100644index 0000000000..ca2b121fa0--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/AddTrackerDialog.kt@@ -0,0 +1,123 @@+package com.vayunmathur.findfamily.ui.dialogs++import android.annotation.SuppressLint+import android.bluetooth.BluetoothDevice+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.compose.ui.window.Dialog+import com.vayunmathur.findfamily.R+import com.vayunmathur.findfamily.Route+import com.vayunmathur.findfamily.tracker.TrackerBinder+import com.vayunmathur.findfamily.tracker.TrackerProvisioner+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.ListItemDefaults+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.launch++/**+ * Dev-only dialog to bind a new custom UWB tracker. Scans for trackers in pairing+ * mode ([TrackerProvisioner.unprovisioned]), lets the user name and pick one, then+ * runs the full bind ([TrackerBinder.bind]). Gated at the call site by+ * `BuildConfig.DEV_BUILD` (see the FAB menu in MainPage).+ */+@SuppressLint("MissingPermission")+@Composable+fun AddTrackerDialog(backStack: NavBackStack<Route>) {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()++ var name by remember { mutableStateOf("") }+ var binding by remember { mutableStateOf(false) }+ var failed by remember { mutableStateOf(false) }+ val devices = remember { mutableStateListOf<BluetoothDevice>() }++ LaunchedEffect(Unit) {+ runCatching {+ TrackerProvisioner(context).unprovisioned().collect { d ->+ if (devices.none { it.address == d.address }) devices.add(d)+ }+ }+ }++ Dialog({ if (!binding) backStack.pop() }) {+ Card {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text(stringResource(R.string.add_tracker_title), style = MaterialTheme.typography.headlineMedium)++ OutlinedTextField(+ name, { name = it },+ label = { Text(stringResource(R.string.add_tracker_name_label)) },+ modifier = Modifier.fillMaxWidth(),+ )++ Text(+ stringResource(R.string.add_tracker_scan_hint),+ style = MaterialTheme.typography.bodySmall,+ )++ if (devices.isEmpty()) {+ Text(stringResource(R.string.add_tracker_scanning), style = MaterialTheme.typography.bodyMedium)+ } else {+ LazyColumn(Modifier.fillMaxWidth().heightIn(max = 220.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {+ items(devices, key = { it.address }) { device ->+ val label = runCatching { device.name }.getOrNull() ?: device.address+ Card(Modifier.clickable(enabled = !binding && name.isNotBlank()) {+ failed = false+ binding = true+ scope.launch {+ val ok = TrackerBinder.bind(context, name, device)+ binding = false+ if (ok) backStack.pop() else failed = true+ }+ }) {+ ListItem(+ { Text(label) },+ colors = ListItemDefaults.colors(),+ supportingContent = { Text(device.address) },+ )+ }+ }+ }+ }++ if (binding) {+ Text(stringResource(R.string.add_tracker_binding), style = MaterialTheme.typography.bodyMedium)+ }+ if (failed) {+ Text(+ stringResource(R.string.add_tracker_failed),+ color = MaterialTheme.colorScheme.error,+ style = MaterialTheme.typography.bodyMedium,+ )+ }++ Button({ if (!binding) backStack.pop() }, enabled = !binding) {+ Text(stringResource(android.R.string.cancel))+ }+ }+ }+ }+}
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 1c3d029e60..8a7c3b188a 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt@@ -48,6 +48,11 @@ import com.vayunmathur.findfamily.data.havershine import com.vayunmathur.findfamily.uwb.UwbEnvelope import com.vayunmathur.findfamily.uwb.UwbEnvelopeKind import com.vayunmathur.findfamily.uwb.UwbInbox+import com.vayunmathur.findfamily.BuildConfig+import com.vayunmathur.findfamily.data.UserKind+import com.vayunmathur.findfamily.tracker.TrackerBeaconScanner+import com.vayunmathur.findfamily.tracker.TrackerReporting+import com.vayunmathur.findfamily.tracker.TrackerStore import com.vayunmathur.findfamily.MainActivity import com.vayunmathur.findfamily.R import com.vayunmathur.library.util.DataStoreUtils@@ -104,6 +109,11 @@ class LocationTrackingService : Service(), SensorEventListener { private var heartbeatJob: Job? = null private var trackingInitialized = false + // Custom UWB tracker feature (DEV_BUILD only). Owner-side store of tracker+ // secrets/private keys, and the finder-side beacon scan job.+ private var trackerStore: TrackerStore? = null+ private var trackerScanJob: Job? = null+ private val networkListener = LocationListener { location -> lastKnownLocation = location if (location.accuracy > 100f) {@@ -318,6 +328,59 @@ class LocationTrackingService : Service(), SensorEventListener { } } + // -----------------------------------------------------------------+ // Custom UWB tracker crowd-finding (DEV_BUILD only)+ // -----------------------------------------------------------------++ /**+ * Finder path: subscribe to tracker beacon sightings and, for each, upload a+ * report stamped with this device's current GPS (if accurate enough). The sealed+ * report is readable only by the tracker's owner. Started once from startTracking.+ */+ private fun startTrackerScanner() {+ if (trackerScanJob?.isActive == true) return+ trackerScanJob = serviceScope.launch {+ runCatching {+ TrackerBeaconScanner(this@LocationTrackingService).sightings().collect { sighting ->+ val loc = lastKnownLocation ?: return@collect+ if (loc.accuracy > 100f) return@collect+ val battery = runCatching {+ bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY).toFloat()+ }.getOrDefault(0f)+ val lv = LocationValue(+ Networking.userid,+ Coord(loc.latitude, loc.longitude),+ 0f,+ loc.accuracy,+ Clock.System.now(),+ battery,+ )+ runCatching { TrackerReporting.reportSighting(sighting, lv) }+ .onFailure { Log.w("FF-Tracker", "reportSighting failed", it) }+ }+ }.onFailure { Log.w("FF-Tracker", "tracker scan collect failed", it) }+ }+ }++ /**+ * Owner path: (re)register owned trackers so finders can resolve them, then fetch+ * and decrypt recent crowd reports and feed them through the normal incoming+ * pipeline so each tracker shows up as a map pin. Runs on the heartbeat tick.+ */+ private suspend fun pollTrackerReports() {+ val store = trackerStore ?: return+ val trackers = runCatching { userDao.getAll().filter { it.kind == UserKind.TRACKER } }+ .getOrDefault(emptyList())+ if (trackers.isEmpty()) return+ val locs = ArrayList<LocationValue>()+ for (t in trackers) {+ runCatching { TrackerReporting.registerTracker(t, store) }+ locs += runCatching { TrackerReporting.fetchTrackerLocations(t, store) }+ .getOrDefault(emptyList())+ }+ if (locs.isNotEmpty()) processIncomingLocations(locs)+ }+ override fun onSensorChanged(event: SensorEvent?) { if (event?.sensor?.type == Sensor.TYPE_LINEAR_ACCELERATION) { val x = event.values[0]@@ -405,6 +468,12 @@ class LocationTrackingService : Service(), SensorEventListener { // bring the app to foreground first. See UwbSessionManager. UwbSessionManager.init(this@LocationTrackingService, userDao) + // Custom UWB tracker crowd-finding (DEV_BUILD): owner-side secret/key+ // store. Gated so release builds never touch it.+ if (BuildConfig.DEV_BUILD) {+ trackerStore = TrackerStore(DataStoreUtils.getInstance(this@LocationTrackingService))+ }+ withContext(Dispatchers.Main) { registerSensors() // If we don't have any recent location (e.g. fresh start or recovery@@ -433,6 +502,7 @@ class LocationTrackingService : Service(), SensorEventListener { break } syncHeartbeat()+ if (BuildConfig.DEV_BUILD) runCatching { pollTrackerReports() } delay(30.seconds) } }@@ -445,6 +515,10 @@ class LocationTrackingService : Service(), SensorEventListener { onLocations = { processIncomingLocations(it) }, onUwb = { handleUwbEnvelopes(it) }, )++ // Finder side of the crowd-finding network: scan for tracker beacons and+ // report each sighting with our own GPS. DEV_BUILD only.+ if (BuildConfig.DEV_BUILD) startTrackerScanner() } }
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 cb5a70376f..a8f26aa470 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt@@ -26,6 +26,7 @@ import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.json.Json import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.ConcurrentLinkedQueue import kotlin.io.encoding.Base64 import kotlin.random.Random import kotlin.time.Clock@@ -138,6 +139,16 @@ object Networking { private const val WS_OP_GETKEY_RESP: Byte = 0x05 private const val WS_FLAG_UWB = 0x01 + // Custom UWB tracker crowd-finding opcodes (DEV_BUILD). Mirrored on the server+ // (src/handlers/findfamily.rs). Older servers ignore unknown opcodes, so these+ // are backward-compatible: resolve/report-get simply time out to null/empty.+ private const val WS_OP_TRACKER_REGISTER: Byte = 0x06 // [0x06][u64 tracker_id][u16 secretLen][secret][bundle…]+ private const val WS_OP_RESOLVE_REQ: Byte = 0x07 // [0x07][16B epochId]+ private const val WS_OP_RESOLVE_RESP: Byte = 0x08 // [0x08][status][16B epochId][bundle…]+ private const val WS_OP_REPORT_PUT: Byte = 0x09 // [0x09][16B epochId][ciphertext…]+ private const val WS_OP_REPORT_GET_REQ: Byte = 0x0A // [0x0A][u16 n]([16B epochId]×n)+ private const val WS_OP_REPORT_GET_RESP: Byte = 0x0B // [0x0B][u16 count]([u32 len][ct]×count)+ private const val WS_KEY_NONE = 0 private const val WS_KEY_CLASSIC = 1 private const val WS_KEY_PQC = 2@@ -150,6 +161,12 @@ object Networking { /** In-flight GETKEY requests, keyed by target userid, completed when the KEYRESP arrives. */ private val pendingKeyRequests = ConcurrentHashMap<Long, CompletableDeferred<KeyResult?>>() + /** In-flight tracker RESOLVE requests, keyed by the epoch-id hex, completed on RESOLVE_RESP. */+ private val pendingResolves = ConcurrentHashMap<String, CompletableDeferred<ByteArray?>>()++ /** In-flight tracker REPORT_GET requests (FIFO — the owner polls them one at a time). */+ private val pendingReportGets = ConcurrentLinkedQueue<CompletableDeferred<List<ByteArray>>>()+ /** True while the live socket is connected. */ val liveConnected: Boolean get() = wsSession != null @@ -211,6 +228,9 @@ object Networking { // Fail any awaiting key lookups so their callers don't hang until timeout. pendingKeyRequests.values.forEach { it.complete(null) } pendingKeyRequests.clear()+ pendingResolves.values.forEach { it.complete(null) }+ pendingResolves.clear()+ while (true) { (pendingReportGets.poll() ?: break).complete(emptyList()) } if (!isActive) break delay(backoff) backoff = (backoff * 2).coerceAtMost(15_000)@@ -222,6 +242,9 @@ object Networking { liveJob?.cancel(); liveJob = null; wsSession = null pendingKeyRequests.values.forEach { it.complete(null) } pendingKeyRequests.clear()+ pendingResolves.values.forEach { it.complete(null) }+ pendingResolves.clear()+ while (true) { (pendingReportGets.poll() ?: break).complete(emptyList()) } } /** Parse one server frame and dispatch: MSG → decrypt+deliver; KEYRESP → complete the lookup. */@@ -257,6 +280,32 @@ object Networking { val bundle = if (buf.size > 10) buf.copyOfRange(10, buf.size) else null pendingKeyRequests.remove(target)?.complete(KeyResult(status, bundle)) }+ WS_OP_RESOLVE_RESP -> {+ // [0x08][status][16B epochId][bundle…]+ if (buf.size < 18) return+ val found = buf[1].toInt() == 1+ val epochHex = buf.copyOfRange(2, 18).toHex()+ val bundle = if (found && buf.size > 18) buf.copyOfRange(18, buf.size) else null+ pendingResolves.remove(epochHex)?.complete(bundle)+ }+ WS_OP_REPORT_GET_RESP -> {+ // [0x0B][u16 count]([u32 len][ct]×count)+ if (buf.size < 3) return+ val count = ((buf[1].toInt() and 0xFF) shl 8) or (buf[2].toInt() and 0xFF)+ val out = ArrayList<ByteArray>(count)+ var off = 3+ var i = 0+ while (i < count && off + 4 <= buf.size) {+ val len = ((buf[off].toInt() and 0xFF) shl 24) or+ ((buf[off + 1].toInt() and 0xFF) shl 16) or+ ((buf[off + 2].toInt() and 0xFF) shl 8) or+ (buf[off + 3].toInt() and 0xFF)+ off += 4+ if (len < 0 || off + len > buf.size) break+ out.add(buf.copyOfRange(off, off + len)); off += len; i+++ }+ pendingReportGets.poll()?.complete(out)+ } else -> Unit } }@@ -364,6 +413,93 @@ object Networking { } } + // ----------------------------------------------------------------+ // Custom UWB tracker crowd-finding (DEV_BUILD). All methods no-op / return+ // empty when the socket is down or the server is an older build that doesn't+ // implement these opcodes (resolve/report-get time out). See TrackerProtocol+ // and the mirror implementation in the server's findfamily.rs.+ // ----------------------------------------------------------------++ /** Owner: register/refresh a tracker's secret + ML-KEM public bundle on the server. */+ suspend fun registerTracker(trackerUserId: Long, secret: ByteArray, publicBundle: ByteArray): Boolean {+ val session = wsSession ?: return false+ return try {+ val frame = ByteArray(11 + secret.size + publicBundle.size)+ frame[0] = WS_OP_TRACKER_REGISTER+ putU64Be(frame, 1, trackerUserId.toULong())+ frame[9] = (secret.size ushr 8).toByte()+ frame[10] = secret.size.toByte()+ secret.copyInto(frame, 11)+ publicBundle.copyInto(frame, 11 + secret.size)+ session.send(frame)+ true+ } catch (e: Exception) {+ Log.w(TAG, "registerTracker failed", e); false+ }+ }++ /** Finder: resolve a beacon epoch-id to the owning tracker's ML-KEM public bundle. */+ suspend fun resolveTrackerBundle(epochId: ByteArray): ByteArray? {+ val session = wsSession ?: return null+ val hex = epochId.toHex()+ val deferred = CompletableDeferred<ByteArray?>()+ pendingResolves[hex] = deferred+ return try {+ val req = ByteArray(1 + epochId.size)+ req[0] = WS_OP_RESOLVE_REQ+ epochId.copyInto(req, 1)+ session.send(req)+ withTimeoutOrNull(GETKEY_TIMEOUT_MS) { deferred.await() }+ } catch (e: Exception) {+ Log.w(TAG, "resolveTrackerBundle failed", e); null+ } finally {+ pendingResolves.remove(hex)+ }+ }++ /** Finder: upload a sealed crowd report keyed by the beacon epoch-id. */+ suspend fun uploadTrackerReport(epochId: ByteArray, ciphertext: ByteArray): Boolean {+ val session = wsSession ?: return false+ return try {+ val frame = ByteArray(1 + epochId.size + ciphertext.size)+ frame[0] = WS_OP_REPORT_PUT+ epochId.copyInto(frame, 1)+ ciphertext.copyInto(frame, 1 + epochId.size)+ session.send(frame)+ true+ } catch (e: Exception) {+ Log.w(TAG, "uploadTrackerReport failed", e); false+ }+ }++ /** Owner: fetch (and drain) sealed reports for a batch of recent epoch-ids. */+ suspend fun fetchTrackerReports(epochIds: List<ByteArray>): List<ByteArray> {+ val session = wsSession ?: return emptyList()+ if (epochIds.isEmpty()) return emptyList()+ val deferred = CompletableDeferred<List<ByteArray>>()+ pendingReportGets.add(deferred)+ return try {+ val n = epochIds.size.coerceAtMost(0xFFFF)+ val frame = ByteArray(3 + n * 16)+ frame[0] = WS_OP_REPORT_GET_REQ+ frame[1] = (n ushr 8).toByte()+ frame[2] = n.toByte()+ var off = 3+ for (i in 0 until n) {+ epochIds[i].copyInto(frame, off, 0, 16.coerceAtMost(epochIds[i].size))+ off += 16+ }+ session.send(frame)+ withTimeoutOrNull(GETKEY_TIMEOUT_MS) { deferred.await() } ?: emptyList()+ } catch (e: Exception) {+ Log.w(TAG, "fetchTrackerReports failed", e); emptyList()+ } finally {+ pendingReportGets.remove(deferred)+ }+ }++ private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) }+ // ---------------------------------------------------------------- // Encryption helpers (post-quantum only) // ----------------------------------------------------------------
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 f3cda83b3b..c698d42f2a 100644--- a/findfamily/src/main/res/values/strings.xml+++ b/findfamily/src/main/res/values/strings.xml@@ -57,6 +57,21 @@ <!-- MainPage FAB menu: Option to create temporary share link. Noun --> <string name="fab_link">Link</string> + <!-- MainPage FAB menu (dev builds only): bind a custom UWB tracker. Noun -->+ <string name="fab_tracker">Tracker</string>+ <!-- Add Tracker dialog title -->+ <string name="add_tracker_title">Add tracker</string>+ <!-- Add Tracker dialog: label for the tracker name text field -->+ <string name="add_tracker_name_label">Tracker name</string>+ <!-- Add Tracker dialog: hint explaining the tracker must be in pairing mode -->+ <string name="add_tracker_scan_hint">Put the tracker in pairing mode, then pick it below.</string>+ <!-- Add Tracker dialog: shown while scanning for nearby trackers -->+ <string name="add_tracker_scanning">Scanning for trackers…</string>+ <!-- Add Tracker dialog: shown while binding to the selected tracker -->+ <string name="add_tracker_binding">Binding…</string>+ <!-- Add Tracker dialog: shown when binding fails -->+ <string name="add_tracker_failed">Could not bind to that tracker. Try again.</string>+ <!-- MainPage: Section header for pending location-sharing requests list. Noun phrase --> <string name="section_location_sharing_requests">Location Sharing Requests</string> <!-- MainPage: Section header for temporary links grid. Noun phrase -->
findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerProtocolTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerProtocolTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerProtocolTest.ktnew file mode 100644index 0000000000..9fe8de332d--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerProtocolTest.kt@@ -0,0 +1,59 @@+package com.vayunmathur.findfamily.tracker++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Pure-JVM tests for the tracker beacon crypto. These assert the exact properties+ * the server's `tracker_epoch_id` mirror relies on; a regression here silently+ * breaks crowd resolution between the app and the Rust server.+ */+class TrackerProtocolTest {++ private val secret = ByteArray(32) { it.toByte() }++ @Test+ fun epochIdIsDeterministicAndSized() {+ val a = TrackerProtocol.epochId(secret, 100)+ val b = TrackerProtocol.epochId(secret, 100)+ assertEquals(TrackerProtocol.EPOCH_ID_LEN, a.size)+ assertTrue(a.contentEquals(b), "same (secret, epoch) -> same id")+ }++ @Test+ fun epochIdRotatesWithEpochAndSecret() {+ val a = TrackerProtocol.epochId(secret, 100)+ assertFalse(a.contentEquals(TrackerProtocol.epochId(secret, 101)), "different epoch -> different id")+ val other = ByteArray(32) { (it + 1).toByte() }+ assertFalse(a.contentEquals(TrackerProtocol.epochId(other, 100)), "different secret -> different id")+ }++ @Test+ fun currentEpochMatchesFormula() {+ val nowMs = 1_786_570_000_000L+ assertEquals((nowMs / 1000L) / TrackerProtocol.EPOCH_SECONDS, TrackerProtocol.currentEpoch(nowMs))+ }++ @Test+ fun recentEpochIdsCoverTheWindowNewestFirst() {+ val nowMs = 1_786_570_000_000L+ val ids = TrackerProtocol.recentEpochIds(secret, nowMs = nowMs, back = 8)+ assertEquals(9, ids.size)+ val cur = TrackerProtocol.currentEpoch(nowMs)+ assertTrue(ids[0].contentEquals(TrackerProtocol.epochId(secret, cur)), "index 0 is the current epoch id")+ assertTrue(ids[8].contentEquals(TrackerProtocol.epochId(secret, cur - 8)), "last is 8 epochs back")+ }++ @Test+ fun kemPrivParsingExtractsLengthPrefixedComponent() {+ val kem = byteArrayOf(1, 2, 3, 4, 5)+ val dsa = byteArrayOf(9, 9)+ val bundle = ByteArray(4 + kem.size + dsa.size)+ bundle[3] = kem.size.toByte() // 4-byte big-endian length = 5+ kem.copyInto(bundle, 4)+ dsa.copyInto(bundle, 4 + kem.size)+ assertTrue(TrackerProtocol.kemPrivFromPrivateBundle(bundle).contentEquals(kem))+ }+}