findfamily: extended-adv tracker beacon, time sync, derived UWB keys
- Commit
0f36ac8e4610f208d34fecec0ba3af9d195ab9cf- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 20:14 UTC (3 months ago)
- Parents
a1b515d
Diff
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 61dcf4f026..d4a5f07e7d 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBeaconScanner.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBeaconScanner.kt@@ -57,6 +57,11 @@ class TrackerBeaconScanner(private val context: Context) { .build() val settings = ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)+ // The beacon is a BLE 5 extended advertisement — 17B of service data under a+ // 128-bit UUID doesn't fit the 31-byte legacy limit (see TrackerBle). The+ // default legacy-only filter would drop it entirely. setLegacy(false) reports+ // both legacy and extended results, so pairing-mode discovery is unaffected.+ .setLegacy(false) .build() try {
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 7e290f6cc8..2f2cb2f52d 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBinder.kt@@ -45,7 +45,7 @@ object TrackerBinder { 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)+ store.save(trackerId, secret, privateBundle, device.address) repository.upsertUser( User( name = name,
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.ktindex 0b8df30806..165416f97e 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBle.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerBle.kt@@ -3,8 +3,9 @@ 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.+ * BLE contract shared between the app and the tracker firmware (nRF52 + Qorvo DW3110;+ * the reference build is a DWM3001CDK, see `firmware/findfamily-tracker/`).+ * 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:@@ -15,17 +16,38 @@ import java.util.UUID * 0..100. The id rotates every [TrackerProtocol.EPOCH_SECONDS]; no static id is ever * broadcast. *+ * This AD structure does **not** fit a legacy advertisement: `Service Data — 128-bit+ * UUID` costs `1B length + 1B type + 16B UUID = 18B` of overhead, so with the 17-byte+ * payload above it is 35 bytes against the 31-byte legacy limit. The full 16-byte UUID+ * has to be on air because [TrackerBeaconScanner] reads it back via+ * `ScanRecord.getServiceData(ParcelUuid)`, so no legacy encoding works and the beacon+ * is sent as a **BLE 5 extended advertisement** (secondary PHY 1M, connectable so the+ * phone can still write UWB session params post-bind). Scanners must therefore pass+ * `ScanSettings.Builder().setLegacy(false)`.+ * * ## Binding (GATT)- * An unprovisioned tracker advertises [UNPROVISIONED_SERVICE_UUID] and exposes a- * GATT server with:+ * An unprovisioned tracker advertises [UNPROVISIONED_SERVICE_UUID] — as a *legacy*+ * advertisement, since `Flags` + a 128-bit service UUID is only 21 bytes and that keeps+ * `TrackerProvisioner.unprovisioned()` working on default (legacy-only) scan settings.+ * It exposes a GATT server with: * - [PROVISION_CHARACTERISTIC_UUID] (write): the phone writes the provisioning blob * ```- * [8B trackerUserId BE][32B beaconSecret]+ * [8B trackerUserId BE][32B beaconSecret][8B unixSeconds BE] * ```+ * ([PROVISION_BLOB_LEN] bytes). Firmware should also accept a+ * [PROVISION_BLOB_LEN_NO_TIME]-byte write without the trailing timestamp, leaving its+ * time base unset. The timestamp exists because the tracker has no battery-backed RTC+ * and cannot otherwise compute `unix_seconds / 900`. * 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]).+ * for phone-native UWB precision finding (see [TrackerUwbGatt]). The STS key and the+ * tracker's UWB address are **not** in this write — both ends derive them from the+ * beacon secret (see [TrackerUwbKeys]).+ *+ * Both characteristics live under [UNPROVISIONED_SERVICE_UUID] for the device's whole+ * life; provisioning only stops that service being *advertised*, so an owner can still+ * connect to a bound tracker and write session params. */ object TrackerBle { /** Service a provisioned tracker advertises its rotating beacon under. */@@ -39,6 +61,12 @@ object TrackerBle { /** GATT characteristic carrying per-find FiRa session params for UWB ranging. */ val UWB_SESSION_CHARACTERISTIC_UUID: UUID = UUID.fromString("6b1d2f03-4b3a-4c7e-9a10-1f2e3d4c5b6a")++ /** Length of the provisioning blob: `[8B userId][32B secret][8B unixSeconds]`. */+ const val PROVISION_BLOB_LEN: Int = 8 + TrackerProtocol.SECRET_LEN + 8++ /** Length of the pre-time-sync provisioning blob firmware still accepts. */+ const val PROVISION_BLOB_LEN_NO_TIME: Int = 8 + TrackerProtocol.SECRET_LEN } /** One crowd-finding beacon sighting heard by a finder phone. */
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 3ad12f8f3a..56a7611fe3 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProvisioner.kt@@ -64,17 +64,30 @@ class TrackerProvisioner(private val context: Context) { /** * 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.+ * `[8B trackerUserId BE][32B secret][8B unixSeconds BE]` to+ * [TrackerBle.PROVISION_CHARACTERISTIC_UUID]. Returns true iff the characteristic+ * write reports success.+ *+ * The trailing timestamp is the tracker's only source of wall-clock time: it has no+ * battery-backed RTC, and epoch ids are a function of `unix_seconds / 900`, so an+ * unsynced tracker would beacon ids outside the owner's+ * [TrackerProtocol.recentEpochIds] search window and resolve to nothing. */ @SuppressLint("MissingPermission") @Suppress("DEPRECATION")- suspend fun provision(device: BluetoothDevice, trackerUserId: Long, secret: ByteArray): Boolean =+ suspend fun provision(+ device: BluetoothDevice,+ trackerUserId: Long,+ secret: ByteArray,+ nowMs: Long = System.currentTimeMillis(),+ ): Boolean = suspendCancellableCoroutine { cont -> require(secret.size == TrackerProtocol.SECRET_LEN) { "secret must be ${TrackerProtocol.SECRET_LEN} bytes" }- val blob = ByteArray(8 + secret.size)+ val blob = ByteArray(TrackerBle.PROVISION_BLOB_LEN) for (i in 0 until 8) blob[i] = (trackerUserId.toULong() shr (56 - i * 8)).toByte() secret.copyInto(blob, 8)+ val unixSeconds = (nowMs / 1000L).toULong()+ for (i in 0 until 8) blob[8 + secret.size + i] = (unixSeconds shr (56 - i * 8)).toByte() val resumed = AtomicBoolean(false) var gatt: BluetoothGatt? = null
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.ktindex 279cf8617b..aa249b5177 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerStore.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerStore.kt@@ -12,18 +12,27 @@ import com.vayunmathur.library.util.DataStoreUtils * (`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.+ *+ * The tracker's BLE address is kept here too. It isn't secret, but the owner needs it+ * to re-open GATT for a UWB find ([TrackerUwbGatt.startRanging]) — the crowd-finding+ * path only ever scans by service UUID, so nothing else would retain it. */ class TrackerStore(private val ds: DataStoreUtils) { - suspend fun save(trackerUserId: Long, secret: ByteArray, privateBundle: ByteArray) {+ suspend fun save(trackerUserId: Long, secret: ByteArray, privateBundle: ByteArray, bleAddress: String? = null) { ds.setByteArray(secretKey(trackerUserId), secret) ds.setByteArray(privKey(trackerUserId), privateBundle)+ if (bleAddress != null) ds.setString(macKey(trackerUserId), bleAddress) } suspend fun secret(trackerUserId: Long): ByteArray? = ds.getByteArrayAwait(secretKey(trackerUserId)) suspend fun privateBundle(trackerUserId: Long): ByteArray? = ds.getByteArrayAwait(privKey(trackerUserId)) + /** The BLE address this tracker was bound over, or null if it was bound before this was stored. */+ suspend fun bleAddress(trackerUserId: Long): String? = ds.getStringAwait(macKey(trackerUserId))+ private fun secretKey(id: Long) = "ff_tracker_secret_$id" private fun privKey(id: Long) = "ff_tracker_priv_$id"+ private fun macKey(id: Long) = "ff_tracker_mac_$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.ktindex aa0e817586..f3806eff07 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerUwbGatt.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerUwbGatt.kt@@ -1,5 +1,23 @@ 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.content.Context+import android.os.Build+import android.util.Log+import androidx.annotation.RequiresApi+import com.vayunmathur.findfamily.uwb.RangingSample+import com.vayunmathur.findfamily.uwb.UwbController+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.suspendCancellableCoroutine+import java.util.concurrent.atomic.AtomicBoolean+import kotlin.coroutines.resume+ /** * Phone-native **FiRa UWB precision finding** to a bound tracker, over BLE GATT. *@@ -10,12 +28,15 @@ package com.vayunmathur.findfamily.tracker * 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.+ * The phone is the **controller/initiator** and the tracker the controlee/responder.+ * Neither the STS key nor the tracker's UWB address is transmitted — both sides derive+ * them from the bind-time beacon secret ([TrackerUwbKeys]), so the unbonded GATT link+ * carries nothing an attacker could use to range against someone else's tracker. */ object TrackerUwbGatt { + private const val TAG = "TrackerUwbGatt"+ /** FiRa session params handed to the tracker for one ranging session. */ data class SessionParams( val localAddress: ByteArray, // phone (controller) 2-byte MAC@@ -44,13 +65,120 @@ object TrackerUwbGatt { } /**- * 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.+ * Begin a UWB ranging session to the bound tracker at [bleAddress], whose beacon+ * [secret] the owner holds. Opens GATT, writes [encodeSessionParams] so the tracker+ * starts a matching FiRa responder session, and returns the ranging stream.+ *+ * Returns null if the tracker can't be reached or the write fails. [ctrl] is+ * single-use — `UwbController.stop()` shuts down its executor — so pass a fresh+ * instance per find. */- 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."- )+ @RequiresApi(Build.VERSION_CODES.BAKLAVA)+ suspend fun startRanging(+ context: Context,+ ctrl: UwbController,+ bleAddress: String,+ secret: ByteArray,+ ): Flow<RangingSample>? {+ val info = ctrl.openController().getOrElse {+ Log.e(TAG, "openController failed", it)+ return null+ }+ val params = SessionParams(+ localAddress = info.localAddress,+ sessionId = info.sessionId,+ channelNumber = info.channelNumber,+ preambleIndex = info.preambleIndex,+ )+ if (!writeSessionParams(context, bleAddress, encodeSessionParams(params))) {+ Log.w(TAG, "could not hand session params to tracker at $bleAddress")+ return null+ }+ // Both ends derive these from the beacon secret rather than exchanging them.+ return ctrl.stream(+ role = UwbController.Role.Initiator,+ localAddress = info.localAddress,+ peerAddress = TrackerUwbKeys.uwbAddress(secret),+ sessionId = info.sessionId,+ sessionKey = TrackerUwbKeys.stsKey(secret, info.sessionId),+ channelNumber = info.channelNumber,+ preambleIndex = info.preambleIndex,+ )+ }++ /**+ * Connect to the tracker at [bleAddress] and write [value] to+ * [TrackerBle.UWB_SESSION_CHARACTERISTIC_UUID]. Returns true iff the write reports+ * success. Mirrors [TrackerProvisioner]'s GATT round-trip; failures surface as false+ * rather than throwing.+ */+ @SuppressLint("MissingPermission")+ @Suppress("DEPRECATION")+ private suspend fun writeSessionParams(+ context: Context,+ bleAddress: String,+ value: ByteArray,+ ): Boolean = suspendCancellableCoroutine { cont ->+ val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager+ val device = try {+ manager?.adapter?.getRemoteDevice(bleAddress)+ } catch (e: Exception) {+ Log.w(TAG, "getRemoteDevice($bleAddress) failed", e); null+ }+ if (device == null) { cont.resume(false); return@suspendCancellableCoroutine }++ 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.UWB_SESSION_CHARACTERISTIC_UUID)+ if (ch == null) { finish(false); return }+ val ok = try {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ g.writeCharacteristic(+ ch, value, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT+ ) == BluetoothGatt.GATT_SUCCESS+ } else {+ ch.value = value+ g.writeCharacteristic(ch)+ }+ } catch (e: Exception) {+ Log.w(TAG, "writeCharacteristic failed", e); false+ }+ 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) }+ } }
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerUwbKeys.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerUwbKeys.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerUwbKeys.ktnew file mode 100644index 0000000000..346dc306db--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerUwbKeys.kt@@ -0,0 +1,68 @@+package com.vayunmathur.findfamily.tracker++import com.vayunmathur.library.util.Hkdf++/**+ * FiRa session material for phone↔tracker ranging, derived on both ends from the+ * bind-time beacon secret rather than sent over the air.+ *+ * The GATT link to a tracker is unbonded and unencrypted, so anything transmitted on+ * it is spoofable — a nearby attacker could hand the tracker its own session key and+ * range against it. Deriving instead means the per-find GATT write only carries+ * channel/slot params (see [TrackerUwbGatt.encodeSessionParams]), which are useless+ * without the secret.+ *+ * Pure JVM (no Android dependencies) so it is unit-testable next to [TrackerProtocol],+ * and simple enough to mirror byte-for-byte in the tracker firmware's PSA-Crypto HKDF.+ */+object TrackerUwbKeys {++ /** Length of the FiRa STS key: exactly what `UwbRangingParams.setSessionKeyInfo` takes. */+ const val STS_KEY_LEN: Int = 8++ private const val STS_INFO = "com.vayunmathur.findfamily/uwb-sts"+ private const val ADDR_INFO = "com.vayunmathur.findfamily/uwb-addr"++ /**+ * The 8-byte static-STS key for one ranging session:+ * `HKDF-SHA256(secret, info = "…/uwb-sts" || u32_be(sessionId))`.+ *+ * Under FiRa these 8 bytes are `[2B VendorID][6B STATIC_STS_IV]`, which is what+ * `CONFIG_UNICAST_DS_TWR` expects. Mixing in [sessionId] gives every find a+ * distinct IV without either side transmitting key material.+ */+ fun stsKey(secret: ByteArray, sessionId: Int): ByteArray {+ require(secret.size == TrackerProtocol.SECRET_LEN) {+ "secret must be ${TrackerProtocol.SECRET_LEN} bytes"+ }+ return Hkdf.derive(secret, STS_INFO.toByteArray(Charsets.US_ASCII) + u32be(sessionId), STS_KEY_LEN)+ }++ /**+ * The tracker's 2-byte UWB MAC address: `HKDF-SHA256(secret, info = "…/uwb-addr")`.+ *+ * Derived rather than carried in the session-params write so the wire format stays+ * 8 bytes. Fixed per tracker, which is fine: it is only ever used inside a session+ * keyed by [stsKey], and it is never broadcast in the clear.+ *+ * The reserved FiRa addresses `0x0000` and `0xFFFF` are nudged to `..01`, the same+ * way `UwbController.openController` handles its random address.+ */+ fun uwbAddress(secret: ByteArray): ByteArray {+ require(secret.size == TrackerProtocol.SECRET_LEN) {+ "secret must be ${TrackerProtocol.SECRET_LEN} bytes"+ }+ val addr = Hkdf.derive(secret, ADDR_INFO.toByteArray(Charsets.US_ASCII), 2)+ val reserved = (addr[0] == 0x00.toByte() && addr[1] == 0x00.toByte()) ||+ (addr[0] == 0xFF.toByte() && addr[1] == 0xFF.toByte())+ if (reserved) addr[1] = 0x01+ return addr+ }++ private fun u32be(v: Int): ByteArray = byteArrayOf(+ (v ushr 24).toByte(),+ (v ushr 16).toByte(),+ (v ushr 8).toByte(),+ v.toByte(),+ )+}
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 0dc370449a..99a8242d82 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/UwbSessionManager.kt@@ -13,6 +13,9 @@ import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.data.UserKind+import com.vayunmathur.findfamily.tracker.TrackerStore+import com.vayunmathur.findfamily.tracker.TrackerUwbGatt import com.vayunmathur.findfamily.uwb.RangingSample import com.vayunmathur.findfamily.uwb.UwbAccessoryProtocol import com.vayunmathur.findfamily.uwb.UwbBytes@@ -21,10 +24,12 @@ import com.vayunmathur.findfamily.uwb.UwbEnvelope import com.vayunmathur.findfamily.uwb.UwbEnvelopeKind import com.vayunmathur.findfamily.uwb.UwbHandshake import com.vayunmathur.findfamily.uwb.UwbInbox+import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow@@ -103,6 +108,13 @@ object UwbSessionManager { private var waitJob: Job? = null private var currentSessionId: String? = null + /**+ * True while the current session is a find against a custom tracker. Trackers aren't+ * on the WebSocket, so the envelope handshake (REQUEST/ACK/CANCEL) is skipped entirely+ * for them; params go over GATT instead (see [TrackerUwbGatt]).+ */+ private var currentPeerIsTracker: Boolean = false+ /** * Wire up the manager. No-op on devices below API 36. Safe to call * multiple times — only the first call has effect.@@ -167,6 +179,10 @@ object UwbSessionManager { stopLocal() return@launch }+ if (peerUser.kind == UserKind.TRACKER) {+ beginTrackerFind(peerUserId)+ return@launch+ } if (peerUser.platform == "ios") { beginCrossPlatformInitiateToIos(peerUserId, sessionId) return@launch@@ -298,6 +314,36 @@ object UwbSessionManager { } } + /**+ * Tracker find: the peer is a bound UWB tracker, not a phone. There is no envelope+ * handshake — the tracker isn't on the WebSocket at all — so we hand it the session+ * params over BLE GATT and range straight away. The STS key and the tracker's UWB+ * address come from the bind-time beacon secret on both ends.+ */+ @RequiresApi(Build.VERSION_CODES.BAKLAVA)+ private suspend fun beginTrackerFind(trackerUserId: Long) {+ currentPeerIsTracker = true+ val store = TrackerStore(DataStoreUtils.getInstance(appContext))+ val secret = store.secret(trackerUserId)+ val bleAddress = store.bleAddress(trackerUserId)+ if (secret == null || bleAddress == null) {+ Log.w(TAG, "beginTrackerFind: tracker $trackerUserId has no stored secret/address")+ _state.value = UwbSessionState.Failed("This tracker isn't bound on this device")+ stopLocal()+ return+ }+ val ctrl = UwbController(appContext)+ controller = ctrl+ _state.value = UwbSessionState.WaitingForPeer+ val stream = TrackerUwbGatt.startRanging(appContext, ctrl, bleAddress, secret)+ if (stream == null) {+ _state.value = UwbSessionState.Failed("Could not reach tracker")+ stopLocal()+ return+ }+ collectRangingStream(stream)+ }+ // ----------------------------------------------------------------- // Responder path (REQUEST envelope arrived — auto-accept in background) // -----------------------------------------------------------------@@ -424,18 +470,25 @@ object UwbSessionManager { channelNumber: Int, preambleIndex: Int, ) {+ collectRangingStream(+ ctrl.stream(+ role = role,+ localAddress = localAddress,+ peerAddress = peerAddress,+ sessionId = sessionId,+ sessionKey = sessionKey,+ channelNumber = channelNumber,+ preambleIndex = preambleIndex,+ )+ )+ }++ /** Drive an already-opened ranging [stream] into the UI state machine. */+ private fun collectRangingStream(stream: Flow<RangingSample>) { streamJob?.cancel() streamJob = scope.launch { try {- ctrl.stream(- role = role,- localAddress = localAddress,- peerAddress = peerAddress,- sessionId = sessionId,- sessionKey = sessionKey,- channelNumber = channelNumber,- preambleIndex = preambleIndex,- ).collect { sample ->+ stream.collect { sample -> _state.value = if (sample.peerDisconnected) { UwbSessionState.PeerDisconnected } else {@@ -452,12 +505,13 @@ object UwbSessionManager { /** * User-initiated stop. Sends a CANCEL envelope to the peer so its UI can- * exit too, then tears down the local UWB scope.+ * exit too, then tears down the local UWB scope. Trackers get no CANCEL —+ * they have no server-side identity to route one to. */ fun stop() { val sessionId = currentSessionId val peerId = _peerUserId.value- if (sessionId != null && peerId != null) {+ if (!currentPeerIsTracker && sessionId != null && peerId != null) { scope.launch { publish( UwbEnvelope(@@ -500,6 +554,7 @@ object UwbSessionManager { if (isSupportedSdk) controller?.stop() controller = null currentSessionId = null+ currentPeerIsTracker = false _peerUserId.value = null _state.value = UwbSessionState.Idle }
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.ktindex 9fe8de332d..2b6a6364d3 100644--- a/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerProtocolTest.kt+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerProtocolTest.kt@@ -30,6 +30,15 @@ class TrackerProtocolTest { assertFalse(a.contentEquals(TrackerProtocol.epochId(other, 100)), "different secret -> different id") } + @Test+ fun epochIdMatchesFixedVector() {+ // Golden vector for the mirrors of this function: the Rust server's+ // `tracker_epoch_id` and the tracker firmware's PSA-Crypto HMAC. Generated by an+ // independent HMAC-SHA256 implementation over "fftrk1" || u64_be(100).+ val id = TrackerProtocol.epochId(secret, 100)+ assertEquals("96592d5163eb7de24e634bde7eec9ef7", id.joinToString("") { "%02x".format(it) })+ }+ @Test fun currentEpochMatchesFormula() { val nowMs = 1_786_570_000_000L
findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerUwbKeysTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerUwbKeysTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerUwbKeysTest.ktnew file mode 100644index 0000000000..aab75f4c2c--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/tracker/TrackerUwbKeysTest.kt@@ -0,0 +1,76 @@+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 derived UWB session material.+ *+ * The fixed vectors matter more than the property assertions: the tracker firmware+ * recomputes these with PSA-Crypto HKDF, and if the two implementations disagree by a+ * byte the FiRa session simply never converges, with no error to point at the cause.+ * They were generated by an independent HKDF-SHA256 implementation.+ */+class TrackerUwbKeysTest {++ private val secret = ByteArray(32) { it.toByte() }++ private fun hex(b: ByteArray) = b.joinToString("") { "%02x".format(it) }++ @Test+ fun stsKeyMatchesFixedVector() {+ assertEquals("d1a3d794d6914e30", hex(TrackerUwbKeys.stsKey(secret, 0x01020304)))+ assertEquals("920bcfae670059c2", hex(TrackerUwbKeys.stsKey(secret, 0)))+ }++ @Test+ fun stsKeyIsEightBytesAndDeterministic() {+ val a = TrackerUwbKeys.stsKey(secret, 42)+ assertEquals(TrackerUwbKeys.STS_KEY_LEN, a.size)+ assertTrue(a.contentEquals(TrackerUwbKeys.stsKey(secret, 42)), "same (secret, sessionId) -> same key")+ }++ @Test+ fun stsKeyVariesWithSessionIdAndSecret() {+ val a = TrackerUwbKeys.stsKey(secret, 42)+ assertFalse(a.contentEquals(TrackerUwbKeys.stsKey(secret, 43)), "different sessionId -> different key")+ val other = ByteArray(32) { (it + 1).toByte() }+ assertFalse(a.contentEquals(TrackerUwbKeys.stsKey(other, 42)), "different secret -> different key")+ }++ @Test+ fun uwbAddressMatchesFixedVector() {+ assertEquals("1eef", hex(TrackerUwbKeys.uwbAddress(secret)))+ }++ @Test+ fun uwbAddressIsTwoBytesAndNeverReserved() {+ // 0x0000 and 0xFFFF are reserved by FiRa. The derivation can't be steered, so+ // sweep a range of secrets and assert the guard holds for whatever comes out.+ for (i in 0 until 512) {+ val s = ByteArray(32) { (it + i).toByte() }+ val addr = TrackerUwbKeys.uwbAddress(s)+ assertEquals(2, addr.size)+ assertFalse(addr[0] == 0x00.toByte() && addr[1] == 0x00.toByte(), "0x0000 is reserved")+ assertFalse(addr[0] == 0xFF.toByte() && addr[1] == 0xFF.toByte(), "0xFFFF is reserved")+ }+ }++ @Test+ fun derivationsRejectWrongSizedSecrets() {+ val short = ByteArray(16)+ assertFalse(runCatching { TrackerUwbKeys.stsKey(short, 1) }.isSuccess)+ assertFalse(runCatching { TrackerUwbKeys.uwbAddress(short) }.isSuccess)+ }++ @Test+ fun stsKeyAndAddressAreDomainSeparated() {+ // Same secret, same HKDF — only the info string differs. A copy-paste slip in+ // either info string would show up as one being a prefix of the other.+ val sts = TrackerUwbKeys.stsKey(secret, 0)+ val addr = TrackerUwbKeys.uwbAddress(secret)+ assertFalse(sts.copyOf(2).contentEquals(addr), "sts key and address must not share a derivation")+ }+}