various fixes
- Commit
e906329587bbb4d859e1509dcf4d3a3a60a091f9- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-07 21:59 UTC (2 months ago)
- Parents
2b6a9db
Diff
.github/ISSUE_TEMPLATE/bug_report.yml
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 984a00b1d9..5a94b5589f 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -29,6 +29,7 @@ body: - hub - keyboard - logicgate+ - logviewer - maps - measure - messages
.github/ISSUE_TEMPLATE/feature_request.yml
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex f54bdb8a7d..557fd4a34c 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -29,6 +29,7 @@ body: - hub - keyboard - logicgate+ - logviewer - maps - measure - messages
.github/workflows/issue_labeler.yml
diff --git a/.github/workflows/issue_labeler.yml b/.github/workflows/issue_labeler.ymlindex 64be80cbe1..0a014bf78f 100644--- a/.github/workflows/issue_labeler.yml+++ b/.github/workflows/issue_labeler.yml@@ -21,7 +21,7 @@ jobs: if (match && match[1]) { const selectedApp = match[1].trim().toLowerCase();- const validApps = ['alchemist', 'appstore', 'astronomy', 'calculator', 'calendar', 'camera', 'chess', 'clock', 'code', 'contacts', 'education', 'email', 'everysync', 'files', 'findfamily', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'maps', 'measure', 'messages', 'music', 'musicbrainz', 'notes', 'nowplaying', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'solitaire', 'speech', 'things', 'translate', 'travel', 'tuner', 'unblockjam', 'vpn', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];+ const validApps = ['alchemist', 'appstore', 'astronomy', 'calculator', 'calendar', 'camera', 'chess', 'clock', 'code', 'contacts', 'education', 'email', 'everysync', 'files', 'findfamily', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'messages', 'music', 'musicbrainz', 'notes', 'nowplaying', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'solitaire', 'speech', 'things', 'translate', 'travel', 'tuner', 'unblockjam', 'vpn', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe']; if (validApps.includes(selectedApp)) { await github.rest.issues.addLabels({
CONTRIBUTING.md
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 64dce07eac..cbc7220a92 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -579,7 +579,7 @@ Prefer an existing shared module over a new dependency: | `:library:biometric` / `:library:ink` | Biometric prompts / stylus ink | | `:library:downloadservice` | Foreground downloads for large assets and models | | `:library:locationprovider` | Location provider abstraction |-| `:library:euicc-stubs` / `:library:backup-stubs` | Compile-only hidden-API stubs |+| `:library:euicc-stubs` / `:library:backup-stubs` / `:library:remotedisplay-stubs` | Compile-only hidden-API stubs | | `:sdk:games` / `:sdk:cast` / `:sdk:openassistant` | Games hub, casting, assistant tool calling | See [SUPPLY_CHAIN_RISKS.md](SUPPLY_CHAIN_RISKS.md) before adding anything third-party.
README.md
diff --git a/README.md b/README.mdindex 8b9cfb40f3..ca46e8aa65 100644--- a/README.md+++ b/README.md@@ -59,6 +59,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Health** | [Homepage](https://ma.vayunmathur.com/apps/health) | [](https://f-droid.org/packages/com.vayunmathur.health/) | [](https://api.vayunmathur.com/obtainium-link?name=Health&packageName=com.vayunmathur.health&apk=health-release.apk) | | **Keyboard** | [Homepage](https://ma.vayunmathur.com/apps/keyboard) | [](https://f-droid.org/packages/com.vayunmathur.keyboard/) | [](https://api.vayunmathur.com/obtainium-link?name=Keyboard&packageName=com.vayunmathur.keyboard&apk=keyboard-release.apk) | | **Launcher** | [Homepage](https://ma.vayunmathur.com/apps/launcher) | In Progress | In Progress |+| **Log Viewer** | [Homepage](https://ma.vayunmathur.com/apps/logviewer) | In Progress | In Progress | | **Maps** | [Homepage](https://ma.vayunmathur.com/apps/maps) | In Progress | In Progress | | **Measure** | [Homepage](https://ma.vayunmathur.com/apps/measure) | [](https://ma.vayunmathur.com/fdroid) | [](https://api.vayunmathur.com/obtainium-link?name=Measure&packageName=com.vayunmathur.measure&apk=measure-release.apk) | | **Messages** | [Homepage](https://ma.vayunmathur.com/apps/messages) | In Progress | In Progress |
backup/src/main/AndroidManifest.xml
diff --git a/backup/src/main/AndroidManifest.xml b/backup/src/main/AndroidManifest.xmlindex 16e6c04099..7ec4698e75 100644--- a/backup/src/main/AndroidManifest.xml+++ b/backup/src/main/AndroidManifest.xml@@ -14,6 +14,16 @@ <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" /> <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" /> + <!--+ Guards the settings UI so only the system can open it. Backup has no launcher icon -+ it is reached from Settings > System > Backup, which starts it via the transport's+ dataManagementIntent - and an exported activity with no guard would let any installed+ app open the backup configuration.+ -->+ <permission+ android:name="com.vayunmathur.backup.OPEN_SETTINGS"+ android:protectionLevel="signature" />+ <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules"@@ -22,16 +32,19 @@ android:roundIcon="@mipmap/ic_launcher" android:supportsRtl="true" android:theme="@style/Theme.General">+ <!--+ No MAIN/LAUNCHER filter: backup is configured from Settings, not from a home-screen+ icon, the same way Seedvault is on GrapheneOS. The framework reaches this activity+ through ConfigurableBackupTransport.dataManagementIntent(), and Settings' backup page+ renders it under the label the transport supplies.+ --> <activity android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:name=".MainActivity" android:exported="true"- android:theme="@style/Theme.General">- <intent-filter>- <action android:name="android.intent.action.MAIN" />- <category android:name="android.intent.category.LAUNCHER" />- </intent-filter>- </activity>+ android:launchMode="singleTask"+ android:permission="com.vayunmathur.backup.OPEN_SETTINGS"+ android:theme="@style/Theme.General" /> <service android:name=".service.ConfigurableBackupTransportService"
backup/src/main/java/com/vayunmathur/backup/service/ConfigurableBackupTransport.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/service/ConfigurableBackupTransport.kt b/backup/src/main/java/com/vayunmathur/backup/service/ConfigurableBackupTransport.ktindex 2a845b72e2..22016d942f 100644--- a/backup/src/main/java/com/vayunmathur/backup/service/ConfigurableBackupTransport.kt+++ b/backup/src/main/java/com/vayunmathur/backup/service/ConfigurableBackupTransport.kt@@ -6,10 +6,13 @@ import android.app.backup.BackupTransport import android.app.backup.RestoreDescription import android.app.backup.RestoreSet import android.content.Context+import android.content.Intent import android.content.pm.PackageInfo import android.os.Build import android.os.ParcelFileDescriptor import android.util.Base64+import com.vayunmathur.backup.MainActivity+import com.vayunmathur.backup.R import com.vayunmathur.backup.data.backend.BackendFactory import com.vayunmathur.backup.data.backend.BackupRepository import com.vayunmathur.backup.domain.crypto.Crypto@@ -59,12 +62,31 @@ class ConfigurableBackupTransport(private val context: Context) : BackupTranspor override fun name(): String = COMPONENT override fun transportDirName(): String = "com.vayunmathur.backup"- override fun configurationIntent() = null- override fun dataManagementIntent() = null- override fun dataManagementIntentLabel(): CharSequence? = null++ /**+ * Settings' backup page is this app's only entry point - there is no launcher icon - so+ * both intents point at [MainActivity].+ *+ * The framework distinguishes the two: [configurationIntent] is opened by tapping the+ * destination row (where a cloud transport would put account selection), while+ * [dataManagementIntent] is the "manage" affordance labelled with+ * [dataManagementIntentLabel]. This transport has a single screen covering both, so both+ * lead there rather than one of them dead-ending.+ *+ * NEW_TASK because the framework starts these from Settings' context, not an activity.+ */+ override fun configurationIntent(): Intent = settingsIntent()++ override fun dataManagementIntent(): Intent = settingsIntent()++ override fun dataManagementIntentLabel(): CharSequence =+ context.getString(R.string.data_management_label)++ private fun settingsIntent(): Intent =+ Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) override fun currentDestinationString(): String =- repoOrNull()?.backend?.displayName ?: "Not configured"+ repoOrNull()?.backend?.displayName ?: context.getString(R.string.destination_not_configured) override fun getTransportFlags(): Int = 0 override fun requestBackupTime(): Long = 0
backup/src/main/res/values/strings.xml
diff --git a/backup/src/main/res/values/strings.xml b/backup/src/main/res/values/strings.xmlindex dc0e705ee3..20baa57901 100644--- a/backup/src/main/res/values/strings.xml+++ b/backup/src/main/res/values/strings.xml@@ -1,4 +1,11 @@ <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Backup</string>++ <!--+ Shown by Settings' backup page, which reads them from the backup transport rather than+ from this app's resources directly - see ConfigurableBackupTransport.+ -->+ <string name="data_management_label">Backup settings</string>+ <string name="destination_not_configured">Not configured</string> </resources>
calendar/src/main/AndroidManifest.xml
diff --git a/calendar/src/main/AndroidManifest.xml b/calendar/src/main/AndroidManifest.xmlindex f164bec8ec..acbd8f8b69 100644--- a/calendar/src/main/AndroidManifest.xml+++ b/calendar/src/main/AndroidManifest.xml@@ -115,6 +115,7 @@ <receiver android:name=".util.ReminderReceiver" android:enabled="true"+ android:directBootAware="true" android:exported="false" /> <receiver android:name=".util.BootReceiver"
calendar/src/main/java/com/vayunmathur/calendar/data/ReminderMirror.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/data/ReminderMirror.kt b/calendar/src/main/java/com/vayunmathur/calendar/data/ReminderMirror.ktnew file mode 100644index 0000000000..27bdc1dd9c--- /dev/null+++ b/calendar/src/main/java/com/vayunmathur/calendar/data/ReminderMirror.kt@@ -0,0 +1,67 @@+package com.vayunmathur.calendar.data++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils++/**+ * A scheduling-only mirror of upcoming reminders kept in device-protected storage,+ * so alarms can be re-armed at `ACTION_LOCKED_BOOT_COMPLETED`.+ *+ * The system CalendarProvider is credential-encrypted and simply unreadable before the+ * first unlock after a reboot, so the locked boot pass has no way to discover reminders+ * on its own. It reads this instead. Written by+ * [com.vayunmathur.calendar.util.ReminderScheduler.reconcileAll] while unlocked.+ *+ * PRIVACY - device-protected storage is NOT encrypted with the user's credential, so+ * everything below is readable with the device merely powered on. Event titles are+ * therefore deliberately NOT mirrored; this holds only the numbers needed to compute a+ * trigger time and a PendingIntent request code. A reminder that fires before the first+ * unlock shows the generic "Event reminder" title.+ *+ * Mirroring titles was considered and rejected because it buys almost nothing: the+ * post-unlock reconcile re-schedules the same request codes with FLAG_UPDATE_CURRENT,+ * which replaces the intent extras, so every reminder that has not yet fired gets its+ * real title back on unlock for free. Titles would only change what is displayed in the+ * narrow window between a reboot and the first unlock - and would cost leaving every+ * upcoming event title sitting in the clear for as long as the mirror exists.+ *+ * Event ids and start times do still leak here. That is the irreducible minimum: without+ * a time there is no alarm to set, and without an id there is no stable request code.+ */+object ReminderMirror {+ /** Bumping this invalidates any previously written mirror rather than misparsing it. */+ private const val FORMAT_VERSION = "1"+ private const val KEY = "calendar_locked_boot_reminders"++ data class Entry(+ val eventId: Long,+ val minutes: Int,+ val instanceStart: Long,+ val instanceEnd: Long,+ )++ suspend fun write(context: Context, entries: List<Entry>) {+ val serialized = entries.joinToString(separator = "\n", prefix = "$FORMAT_VERSION\n") {+ "${it.eventId},${it.minutes},${it.instanceStart},${it.instanceEnd}"+ }+ store(context).setString(KEY, serialized)+ }++ suspend fun read(context: Context): List<Entry> {+ val lines = store(context).getStringAwait(KEY)?.split('\n') ?: return emptyList()+ if (lines.firstOrNull() != FORMAT_VERSION) return emptyList()+ return lines.drop(1).mapNotNull { line ->+ val parts = line.split(',')+ if (parts.size != 4) return@mapNotNull null+ Entry(+ eventId = parts[0].toLongOrNull() ?: return@mapNotNull null,+ minutes = parts[1].toIntOrNull() ?: return@mapNotNull null,+ instanceStart = parts[2].toLongOrNull() ?: return@mapNotNull null,+ instanceEnd = parts[3].toLongOrNull() ?: return@mapNotNull null,+ )+ }+ }++ private fun store(context: Context) =+ DataStoreUtils.getInstance(context, deviceProtected = true)+}
calendar/src/main/java/com/vayunmathur/calendar/util/BootReceiver.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/BootReceiver.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/BootReceiver.ktindex a980b41c65..aa30aa293d 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/BootReceiver.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/BootReceiver.kt@@ -3,6 +3,8 @@ package com.vayunmathur.calendar.util import android.content.BroadcastReceiver import android.content.Context import android.content.Intent+import android.os.UserManager+import android.util.Log import androidx.glance.appwidget.updateAll import com.vayunmathur.calendar.glance.CalendarGlanceWidget import com.vayunmathur.library.widgets.scheduleHourlyUpdate@@ -16,6 +18,13 @@ import kotlinx.coroutines.launch * AlarmManager alarms don't survive either. Mirrors the clock app's * [com.vayunmathur.clock.util.BootReceiver] plus findfamily's * package-replaced handling.+ *+ * Runs twice on a reboot and does different work each time. At+ * ACTION_LOCKED_BOOT_COMPLETED the calendar provider is credential-encrypted and+ * unreadable, so alarms are re-armed from the device-protected+ * [com.vayunmathur.calendar.data.ReminderMirror]. At ACTION_BOOT_COMPLETED - which an+ * FBE device only delivers once the user has unlocked - the provider is authoritative+ * and a full reconcile runs, replacing whatever the locked pass armed. */ class BootReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) {@@ -24,13 +33,14 @@ class BootReceiver : BroadcastReceiver() { Intent.ACTION_LOCKED_BOOT_COMPLETED, Intent.ACTION_MY_PACKAGE_REPLACED, "android.intent.action.QUICKBOOT_POWERON" -> {+ val unlocked =+ context.getSystemService(UserManager::class.java)?.isUserUnlocked != false+ val action = intent.action val pendingResult = goAsync() CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { try {- ReminderScheduler.reconcileAll(context)- context.scheduleHourlyUpdate(CalendarGlanceWidget::class)- CalendarGlanceWidget().updateAll(context)- } catch (_: Exception) {+ if (unlocked) reconcileFromProvider(context, action)+ else armFromMirror(context, action) } finally { pendingResult.finish() }@@ -38,4 +48,35 @@ class BootReceiver : BroadcastReceiver() { } } }++ private suspend fun armFromMirror(context: Context, action: String?) {+ try {+ val armed = ReminderScheduler.scheduleFromMirror(context)+ Log.i(TAG, "$action: armed $armed reminder(s) from the device-protected mirror")+ } catch (e: Exception) {+ Log.e(TAG, "$action: could not arm reminders from the mirror", e)+ }+ // Widgets are deliberately skipped: Glance keeps its state in credential-encrypted+ // storage, and the launcher does not render before the first unlock anyway.+ }++ private suspend fun reconcileFromProvider(context: Context, action: String?) {+ // Reminders and widgets are caught separately so a failure in one cannot silently+ // take out the other - a single blanket catch here is what hid the locked-boot bug.+ try {+ ReminderScheduler.reconcileAll(context)+ } catch (e: Exception) {+ Log.e(TAG, "$action: could not reschedule reminders from the calendar provider", e)+ }+ try {+ context.scheduleHourlyUpdate(CalendarGlanceWidget::class)+ CalendarGlanceWidget().updateAll(context)+ } catch (e: Exception) {+ Log.e(TAG, "$action: could not refresh widgets", e)+ }+ }++ private companion object {+ const val TAG = "CalendarBootReceiver"+ } }
calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.ktindex 1cbb039809..098b01f829 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.kt@@ -5,7 +5,9 @@ import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent+import android.os.UserManager import android.text.format.DateFormat+import android.util.Log import androidx.core.app.NotificationCompat import com.vayunmathur.calendar.MainActivity import com.vayunmathur.calendar.R@@ -47,6 +49,9 @@ class ReminderReceiver : BroadcastReceiver() { ) val timeString = DateFormat.getTimeFormat(context).format(Date(instanceStart))+ // Visibility is left at the platform default (VISIBILITY_PRIVATE) on purpose: that is+ // what lets the system redact this on the lock screen when the user has asked for+ // sensitive content to be hidden. Do not set VISIBILITY_PUBLIC. val notification = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_reminder_notification) .setContentTitle(title)@@ -66,8 +71,15 @@ class ReminderReceiver : BroadcastReceiver() { val pendingResult = goAsync() CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { try {- ReminderScheduler.reconcileAll(context)- } catch (_: Exception) {+ // Before the first unlock the provider is unreadable, so there is nothing to+ // reconcile against. The post-unlock BOOT_COMPLETED pass picks this up; the+ // cost is that a recurring reminder firing pre-unlock does not arm its next+ // occurrence until the user unlocks.+ if (context.getSystemService(UserManager::class.java)?.isUserUnlocked != false) {+ ReminderScheduler.reconcileAll(context)+ }+ } catch (e: Exception) {+ Log.e(TAG, "could not reschedule after a reminder fired", e) } finally { pendingResult.finish() }@@ -76,5 +88,6 @@ class ReminderReceiver : BroadcastReceiver() { companion object { const val CHANNEL_ID = "calendar_reminders"+ private const val TAG = "CalendarReminderReceiver" } }
calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.ktindex 8f3f11750e..9df7b31a20 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.kt@@ -6,6 +6,7 @@ import android.content.Context import android.content.Intent import com.vayunmathur.calendar.data.Event import com.vayunmathur.calendar.data.Instance+import com.vayunmathur.calendar.data.ReminderMirror import kotlin.time.Clock import kotlin.time.Duration.Companion.days @@ -28,6 +29,10 @@ import kotlin.time.Duration.Companion.days * correct across insert / update / delete / exdate without per-mutation * bookkeeping. The set of currently-scheduled request codes is persisted so a * later reconcile can cancel alarms belonging to events that no longer exist.+ *+ * Because the provider is unreadable before the first unlock after a reboot,+ * [reconcileAll] also writes a small [ReminderMirror] to device-protected storage,+ * and [scheduleFromMirror] re-arms alarms from it at ACTION_LOCKED_BOOT_COMPLETED. */ object ReminderScheduler { const val EXTRA_EVENT_ID = "event_id"@@ -42,16 +47,25 @@ object ReminderScheduler { // How far ahead to look for the next occurrence of a recurring event. private val RECURRENCE_WINDOW = 400.days + // How far ahead the device-protected mirror reaches. The mirror only has to cover+ // the gap between the last unlocked reconcile and the first unlock after a reboot,+ // and it is rewritten on every reconcile, so a week is generous - it survives a+ // phone left off over a long weekend. Keeping it short also bounds both the size of+ // the blob and how much scheduling metadata sits in unencrypted storage.+ private val MIRROR_WINDOW = 7.days+ /** Convenience for boot / package-replaced: reschedule from the provider. */- fun reconcileAll(context: Context) =+ suspend fun reconcileAll(context: Context) = reconcileAll(context, Event.getAllEvents(context)) - fun reconcileAll(context: Context, events: List<Event>) {+ suspend fun reconcileAll(context: Context, events: List<Event>) { val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return cancelAllTracked(context, alarmManager) val nowMillis = Clock.System.now().toEpochMilliseconds() val scheduled = mutableSetOf<Int>()+ val mirrorHorizon = nowMillis + MIRROR_WINDOW.inWholeMilliseconds+ val mirrored = mutableListOf<ReminderMirror.Entry>() for (event in events) { val eventId = event.id ?: continue@@ -68,6 +82,11 @@ object ReminderScheduler { eventId, minutes, event.start, event.end, event.title, ) scheduled += code+ if (triggerAt <= mirrorHorizon) {+ mirrored += ReminderMirror.Entry(+ eventId, minutes, event.start, event.end,+ )+ } } } else { val now = Clock.System.now()@@ -85,10 +104,54 @@ object ReminderScheduler { eventId, minutes, next.begin, next.end, event.title, ) scheduled += code+ if (triggerAt <= mirrorHorizon) {+ mirrored += ReminderMirror.Entry(+ eventId, minutes, next.begin, next.end,+ )+ } } } } saveTracked(context, scheduled)+ ReminderMirror.write(context, mirrored)+ }++ /**+ * Re-arm alarms at ACTION_LOCKED_BOOT_COMPLETED, when the calendar provider cannot be+ * read. Returns how many were armed.+ *+ * Deliberately does not cancel or track anything: [loadTracked] / [saveTracked] live in+ * credential-encrypted storage and are unreachable here. It does not need to. The mirror+ * is written by the same [reconcileAll] pass that writes the tracked set and is a subset+ * of it, so every code armed here is already tracked and will be cancelled by the next+ * post-unlock [cancelAllTracked] - which is what makes deletions that happened while the+ * phone was off resolve correctly. Re-arming is otherwise idempotent: request codes are+ * derived from the event, so a second locked boot just replaces the same alarms.+ *+ * The mirror carries no title, so pre-unlock notifications fall back to the generic+ * string. See [ReminderMirror] for why.+ */+ suspend fun scheduleFromMirror(context: Context): Int {+ val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return 0+ val nowMillis = Clock.System.now().toEpochMilliseconds()+ var armed = 0+ for (entry in ReminderMirror.read(context)) {+ val triggerAt = entry.instanceStart - entry.minutes.toLong() * 60_000L+ if (triggerAt <= nowMillis) continue+ scheduleExact(+ context,+ alarmManager,+ requestCode(entry.eventId, entry.minutes, entry.instanceStart),+ triggerAt,+ entry.eventId,+ entry.minutes,+ entry.instanceStart,+ entry.instanceEnd,+ title = null,+ )+ armed+++ }+ return armed } private fun scheduleExact(@@ -100,14 +163,14 @@ object ReminderScheduler { minutes: Int, instanceStart: Long, instanceEnd: Long,- title: String,+ title: String?, ) { val intent = Intent(context, ReminderReceiver::class.java).apply { putExtra(EXTRA_EVENT_ID, eventId) putExtra(EXTRA_MINUTES, minutes) putExtra(EXTRA_INSTANCE_START, instanceStart) putExtra(EXTRA_INSTANCE_END, instanceEnd)- putExtra(EXTRA_TITLE, title)+ if (title != null) putExtra(EXTRA_TITLE, title) } val pendingIntent = PendingIntent.getBroadcast( context,
cast/build.gradle.kts
diff --git a/cast/build.gradle.kts b/cast/build.gradle.ktsindex 207579888d..728582b80e 100644--- a/cast/build.gradle.kts+++ b/cast/build.gradle.kts@@ -19,6 +19,10 @@ android { } dependencies {+ // Compile-only stubs for `com.android.media.remotedisplay`, the remote display provider API.+ // A shared library on the system image, pulled in at runtime by the `<uses-library>` tag;+ // must NOT be packaged. See :library:remotedisplay-stubs.+ compileOnly(project(":library:remotedisplay-stubs")) // The wire format, shared verbatim with the TV receiver. Nothing here re-implements it. implementation(project(":cast:protocol")) // The IPC contract, shared with every app that streams its content through here. Depended on
cast/src/main/AndroidManifest.xml
diff --git a/cast/src/main/AndroidManifest.xml b/cast/src/main/AndroidManifest.xmlindex 2393a95e44..7712bbf00c 100644--- a/cast/src/main/AndroidManifest.xml+++ b/cast/src/main/AndroidManifest.xml@@ -16,6 +16,22 @@ permission gates the API, not the source. --> <uses-permission android:name="android.permission.RECORD_AUDIO" /> + <!-- Both halves of RemoteDisplayProviderWatcher.verifyServiceTrusted: the app must hold+ REMOTE_DISPLAY_PROVIDER and the service must be guarded by BIND_REMOTE_DISPLAY. Failing+ either one is not an error the user sees - the watcher logs and skips the service, and the+ Cast page is simply empty. Signature|privileged, so it needs the priv-app allowlist entry+ in vendor/modern-apps/privapp-permissions-modern-apps.xml. -->+ <uses-permission android:name="android.permission.REMOTE_DISPLAY_PROVIDER" />+ <!-- Selecting a route in Settings has to end at MirrorConsentActivity, because screen-capture+ consent needs an Activity and is single-use. By then Settings is in front and this app is a+ bound service in the background, so without this the launch is silently dropped and the+ route sits at CONNECTING for ever. protectionLevel is+ signature|privileged|vendorPrivileged|oem|verifier|role, so the priv-app allowlist entry is+ what grants it - this app is presigned with its own key, not the platform key.+ CAPTURE_VIDEO_OUTPUT, which would let a VirtualDisplay mirror with no consent Activity at+ all, is signature-only and therefore unreachable for a presigned app. -->+ <uses-permission android:name="android.permission.START_ACTIVITIES_FROM_BACKGROUND" />+ <uses-feature android:name="android.hardware.wifi" android:required="false" /> <permission@@ -32,6 +48,13 @@ android:roundIcon="@mipmap/ic_launcher" android:supportsRtl="true" android:theme="@style/Theme.General">+ <!-- The remote display provider API is a shared library, not part of the base framework.+ Optional so the app still installs on a stock device, where nothing binds+ CastRemoteDisplayService anyway. -->+ <uses-library+ android:name="com.android.media.remotedisplay"+ android:required="false" />+ <activity android:name=".MainActivity" android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"@@ -68,6 +91,18 @@ android:exported="false" android:foregroundServiceType="mediaProjection|mediaPlayback" /> + <!-- Bound by system_server's RemoteDisplayProviderWatcher, which is what puts this app's+ receivers in Settings' Cast page. BIND_REMOTE_DISPLAY is required by the watcher, not+ merely prudent - see MaRemoteDisplayProvider. -->+ <service+ android:name=".service.CastRemoteDisplayService"+ android:exported="true"+ android:permission="android.permission.BIND_REMOTE_DISPLAY">+ <intent-filter>+ <action android:name="com.android.media.remotedisplay.RemoteDisplayProvider" />+ </intent-filter>+ </service>+ <service android:name=".service.ContentCastService" android:exported="true"
cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/MaRemoteDisplayProvider.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/MaRemoteDisplayProvider.kt b/cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/MaRemoteDisplayProvider.ktnew file mode 100644index 0000000000..164b8558a1--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/MaRemoteDisplayProvider.kt@@ -0,0 +1,151 @@+package com.vayunmathur.cast.platform.remotedisplay++import android.content.Context+import android.util.Log+import com.android.media.remotedisplay.RemoteDisplay+import com.android.media.remotedisplay.RemoteDisplayProvider+import com.vayunmathur.cast.R+import com.vayunmathur.cast.domain.CastDevice+import com.vayunmathur.cast.platform.CastController+import com.vayunmathur.cast.platform.MirrorPhase+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch++private const val TAG = "CastRemoteDisplay"++/**+ * Publishes discovered MA Cast receivers to the framework as remote display routes.+ *+ * This is what puts the app in Settings' Cast page. That screen is `WifiDisplaySettings`, which+ * lists `MediaRouter` routes of type `ROUTE_TYPE_REMOTE_DISPLAY`; those routes come from provider+ * services that `RemoteDisplayProviderWatcher` finds, binds and drives through this class. The+ * watcher only trusts a service guarded by `BIND_REMOTE_DISPLAY` in an app holding+ * `REMOTE_DISPLAY_PROVIDER`, so both are required for any of this to appear - see the manifest.+ *+ * **No second discovery path.** The routes are the same [CastDevice]s the in-app list shows, from+ * the same [com.vayunmathur.cast.platform.discovery.CastDiscoveryManager] owned by [CastController],+ * and connecting drives the same session. A route selected here and a device tapped in the app are+ * the same action arriving from two places, which is also why route status is derived from+ * [CastController]'s own phase rather than tracked separately - the app's Stop button and the+ * route's disconnect have to agree.+ *+ * Everything runs on the main thread: the framework calls the callbacks there, and+ * `RemoteDisplayProvider`'s own published state is not synchronised.+ */+class MaRemoteDisplayProvider(context: Context) : RemoteDisplayProvider(context) {++ private val appContext = context.applicationContext+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)++ /** Route by [CastDevice.id], which is also the route id handed back on connect. */+ private val routes = mutableMapOf<String, RemoteDisplay>()+ private val devices = mutableMapOf<String, CastDevice>()++ /** The browse plus the two observers, all cancelled together when discovery is turned off. */+ private var discoveryJob: Job? = null++ /** The route the user selected, so a phase change knows which row to move. */+ private var connectingId: String? = null++ init {+ scope.launch { CastController.mirrorPhase.collect { onMirrorPhase(it) } }+ }++ override fun onDiscoveryModeChanged(mode: Int) {+ if (mode == RemoteDisplayProvider.DISCOVERY_MODE_NONE) {+ discoveryJob?.cancel()+ discoveryJob = null+ clearRoutes()+ return+ }+ if (discoveryJob != null) return+ val discovery = CastController.discovery(appContext)+ discoveryJob = scope.launch {+ // The browse itself. `devices` only fills while something is collecting `discover()`,+ // so this collection is what makes the list happen rather than a duplicate of it - the+ // devices are read off the state flow below, not out of this lambda.+ launch { discovery.discover().collect { } }+ launch { discovery.devices.collect { syncRoutes(it) } }+ }+ }++ override fun onConnect(display: RemoteDisplay) {+ val id = display.id ?: return+ val device = devices[id]+ if (device == null) {+ Log.w(TAG, "asked to connect to a route with no device behind it: $id")+ display.status = RemoteDisplay.STATUS_NOT_AVAILABLE+ updateDisplay(display)+ return+ }+ connectingId = id+ display.status = RemoteDisplay.STATUS_CONNECTING+ updateDisplay(display)+ // Pairing may stop here and wait for six digits off the TV, which only the app's own UI can+ // take - there is no text field in a route row. `thenMirror` is what carries on to consent+ // once the TV has accepted.+ CastController.connect(appContext, device, thenMirror = true)+ }++ override fun onDisconnect(display: RemoteDisplay) {+ connectingId = null+ CastController.disconnect(appContext)+ display.status = RemoteDisplay.STATUS_AVAILABLE+ updateDisplay(display)+ }++ fun shutdown() {+ scope.cancel()+ }++ private fun onMirrorPhase(phase: MirrorPhase) {+ val id = connectingId ?: return+ val display = routes[id] ?: return+ val status = when (phase) {+ MirrorPhase.Mirroring -> RemoteDisplay.STATUS_CONNECTED+ MirrorPhase.Negotiating -> RemoteDisplay.STATUS_CONNECTING+ // Idle covers both "never started" and "the user stopped", and Failed has already put a+ // sentence in front of the user in the app; either way this route is selectable again.+ MirrorPhase.Idle, MirrorPhase.Failed -> RemoteDisplay.STATUS_AVAILABLE+ }+ if (status == RemoteDisplay.STATUS_AVAILABLE) connectingId = null+ if (display.status == status) return+ display.status = status+ updateDisplay(display)+ }++ private fun syncRoutes(found: List<CastDevice>) {+ val seen = found.associateBy { it.id }+ devices.clear()+ devices.putAll(seen)+ for ((id, device) in seen) {+ val existing = routes[id]+ if (existing == null) {+ routes[id] = RemoteDisplay(id, device.friendlyName).apply {+ description = appContext.getString(R.string.cast_route_description)+ status = RemoteDisplay.STATUS_AVAILABLE+ }.also { addDisplay(it) }+ continue+ }+ if (existing.name != device.friendlyName) {+ existing.name = device.friendlyName+ updateDisplay(existing)+ }+ }+ // A receiver that stopped announcing itself is gone, unless it is the one being cast to -+ // mDNS goes quiet on a busy network and dropping the live route would leave the session+ // running with nothing in Settings to stop it from.+ val stale = routes.keys.filter { it !in seen && it != connectingId }+ for (id in stale) routes.remove(id)?.let { removeDisplay(it) }+ }++ private fun clearRoutes() {+ for (display in routes.values) removeDisplay(display)+ routes.clear()+ devices.clear()+ }+}
cast/src/main/java/com/vayunmathur/cast/service/CastRemoteDisplayService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/CastRemoteDisplayService.kt b/cast/src/main/java/com/vayunmathur/cast/service/CastRemoteDisplayService.ktnew file mode 100644index 0000000000..a8e9a07bc4--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/service/CastRemoteDisplayService.kt@@ -0,0 +1,46 @@+package com.vayunmathur.cast.service++import android.app.Service+import android.content.Intent+import android.os.IBinder+import android.util.Log+import com.android.media.remotedisplay.RemoteDisplayProvider+import com.vayunmathur.cast.platform.remotedisplay.MaRemoteDisplayProvider++private const val TAG = "CastRemoteDisplaySvc"++/**+ * The service `RemoteDisplayProviderWatcher` in system_server binds to put MA Cast receivers in+ * Settings' Cast page. See [MaRemoteDisplayProvider] for what it publishes.+ *+ * Bound only by the platform, and only when this app is a privileged app holding+ * `REMOTE_DISPLAY_PROVIDER`; the `BIND_REMOTE_DISPLAY` guard in the manifest is the other half of+ * that check. On an ordinary install nothing ever binds this, which is why it is inert rather than+ * conditionally registered.+ *+ * `com.android.media.remotedisplay` is a shared library rather than part of the base framework, and+ * `<uses-library>` marks it optional so the app still installs on a stock device - so constructing+ * the provider is the point where its absence shows up, and it is caught rather than left to crash+ * a bind that should simply have found nothing.+ */+class CastRemoteDisplayService : Service() {++ private var provider: MaRemoteDisplayProvider? = null++ override fun onBind(intent: Intent?): IBinder? {+ if (intent?.action != RemoteDisplayProvider.SERVICE_INTERFACE) return null+ val existing = provider ?: try {+ MaRemoteDisplayProvider(this).also { provider = it }+ } catch (e: LinkageError) {+ Log.w(TAG, "com.android.media.remotedisplay is not on this device", e)+ return null+ }+ return existing.binder+ }++ override fun onDestroy() {+ provider?.shutdown()+ provider = null+ super.onDestroy()+ }+}
cast/src/main/res/values/strings.xml
diff --git a/cast/src/main/res/values/strings.xml b/cast/src/main/res/values/strings.xmlindex 59202358b8..a17f4d0dd2 100644--- a/cast/src/main/res/values/strings.xml+++ b/cast/src/main/res/values/strings.xml@@ -89,4 +89,8 @@ <string name="cast_picker_title">Cast %1$s to</string> <string name="cast_picker_title_generic">Choose a television</string> <string name="cast_picker_cancel">Cancel</string>++ <!-- The secondary line on the row in Settings' Cast page. The primary line is the TV's own+ name, so this says what kind of thing it is rather than repeating it. -->+ <string name="cast_route_description">MA Cast receiver</string> </resources>
clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.ktindex eb5714f4c4..efe111d402 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt@@ -24,9 +24,10 @@ class BootReceiver : BroadcastReceiver() { enabled.forEach { AlarmScheduler.schedule(context, it) } Log.i(TAG, "${intent.action}: rescheduled ${enabled.size} alarm(s)") } catch (e: Exception) {- // Expected at LOCKED_BOOT_COMPLETED: the database lives in- // credential-encrypted storage, so BOOT_COMPLETED is what actually- // reschedules. A failure there means no alarm survives the reboot.+ // Not expected at either action: ClockRepository is built with+ // useDeviceProtectedStorage = true precisely so the alarm database is+ // readable while the device is still locked. A failure here means no+ // alarm survives the reboot. Log.e(TAG, "${intent.action}: could not reschedule alarms", e) } finally { pendingResult.finish()
email/src/main/AndroidManifest.xml
diff --git a/email/src/main/AndroidManifest.xml b/email/src/main/AndroidManifest.xmlindex 28fdd3bf90..91bd0c2226 100644--- a/email/src/main/AndroidManifest.xml+++ b/email/src/main/AndroidManifest.xml@@ -92,7 +92,6 @@ <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />- <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" /> <action android:name="android.intent.action.QUICKBOOT_POWERON" /> </intent-filter> </receiver>
email/src/main/java/com/vayunmathur/email/platform/BootReceiver.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/BootReceiver.kt b/email/src/main/java/com/vayunmathur/email/platform/BootReceiver.ktindex 87a0c6a4a2..8f450755b1 100644--- a/email/src/main/java/com/vayunmathur/email/platform/BootReceiver.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/BootReceiver.kt@@ -31,7 +31,6 @@ class BootReceiver : BroadcastReceiver() { when (intent.action) { Intent.ACTION_BOOT_COMPLETED, Intent.ACTION_MY_PACKAGE_REPLACED,- Intent.ACTION_LOCKED_BOOT_COMPLETED, "android.intent.action.QUICKBOOT_POWERON" -> { val pending = goAsync() val appContext = context.applicationContext
findfamily/build.gradle.kts
diff --git a/findfamily/build.gradle.kts b/findfamily/build.gradle.ktsindex c122d506aa..7cedb64f4d 100644--- a/findfamily/build.gradle.kts+++ b/findfamily/build.gradle.kts@@ -31,6 +31,9 @@ dependencies { implementation(project(":library:image")) implementation(project(":library:map"))+ // @SystemApi android.nearby.NearbyManager, for powered-off finding. Present at runtime,+ // absent from the public SDK, and must NOT be packaged. See :library:nearby-stubs.+ compileOnly(project(":library:nearby-stubs")) } // The Compose screenshot renderer draws previews from the compiled `screenshotTest` classes
findfamily/src/main/AndroidManifest.xml
diff --git a/findfamily/src/main/AndroidManifest.xml b/findfamily/src/main/AndroidManifest.xmlindex eb37ace290..ae011a2d27 100644--- a/findfamily/src/main/AndroidManifest.xml+++ b/findfamily/src/main/AndroidManifest.xml@@ -15,7 +15,23 @@ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> + <!--+ Powered-off finding, finder half. Arming a beacon needs BLUETOOTH_PRIVILEGED, which is+ signature|privileged and so only ever available to a preinstalled build — but *hearing* one+ is ordinary BLE, and the network is only worth anything if plenty of phones are listening.+ So this is declared here rather than in src/dev: an F-Droid install has to be able to+ contribute sightings too. Scanning still does nothing until the user opts in+ (CROWD_FINDING_ENABLED_KEY, default off).+ -->+ <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />+ <uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />+ <uses-permission android:name="android.permission.RANGING" />+ <!-- Powered-off finding (NearbyManager#setPoweredOffFindingEphemeralIds). signature|privileged,+ so this is only actually granted when findfamily is installed as a MAOS priv-app with a+ matching privapp-permissions entry; everywhere else the calls throw SecurityException and+ PoweredOffBeacon treats the feature as absent. Requesting it here is harmless either way. -->+ <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" /> <uses-feature android:name="android.hardware.uwb" android:required="false" /> <permission@@ -62,6 +78,7 @@ <service android:name=".util.LocationTrackingService" android:foregroundServiceType="location"+ android:directBootAware="true" android:exported="false" /> <service@@ -102,8 +119,12 @@ </service> - <receiver android:name=".util.BootReceiver" android:exported="false">+ <receiver+ android:name=".util.BootReceiver"+ android:directBootAware="true"+ android:exported="false"> <intent-filter>+ <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" /> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.MY_PACKAGE_REPLACED" /> </intent-filter>
findfamily/src/main/java/com/vayunmathur/findfamily/data/DirectBootStore.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/DirectBootStore.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/DirectBootStore.ktnew file mode 100644index 0000000000..71b99cf690--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/DirectBootStore.kt@@ -0,0 +1,117 @@+package com.vayunmathur.findfamily.data++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.serialization.Serializable+import kotlinx.serialization.builtins.ListSerializer+import kotlinx.serialization.json.Json++/**+ * The slice of state a location publish needs, mirrored into device-protected storage.+ *+ * Everything findfamily normally reads at startup — the Room database and the default+ * DataStore — lives in credential-encrypted storage, which the kernel cannot decrypt until+ * the user types their passcode. That is why nothing was reported between a reboot and the+ * first unlock. Room and the main DataStore deliberately stay where they are: the location+ * history, contact names and photos, waypoints and share-link keys are the genuinely private+ * data and belong behind the passcode. Only what is strictly required to encrypt and address+ * an outbound fix is duplicated here.+ *+ * The mirror is written after unlock, from the credential-encrypted originals, and is only+ * ever read before one. [userid] returning null means it has not been seeded yet, which is+ * the expected state on the first boot after this ships.+ *+ * Note the identity keys below are private. They have to be reachable pre-unlock or an+ * authenticated, encrypted publish cannot be produced at all — that is inherent to reporting+ * before unlock rather than a shortcut taken here.+ */+object DirectBootStore {++ /** Same key names the credential-encrypted store uses, so the values copy across as-is. */+ private const val KEY_USERID = "userid"+ private const val KEY_ROSTER = "directboot_roster"++ /**+ * The two user-facing switches, mirrored so the pre-unlock path honours them. Without+ * these, someone who had turned tracking or sharing off would silently get both back for+ * the whole window between a reboot and their passcode.+ */+ private const val KEY_TRACKING_ENABLED = "tracking_enabled"+ private const val KEY_SHARING_ENABLED = "global_sharing_enabled"++ /**+ * The PQC identity blobs, named exactly as [com.vayunmathur.e2ee.PqcIdentity] stores them+ * under the `ff_pqc` prefix. All four must be present for the identity to load; a partial+ * copy would make `loadOrCreate` mint a fresh one (see [isSeeded]).+ */+ private val PQC_KEYS = listOf(+ "ff_pqcKemPub", "ff_pqcKemPriv", "ff_pqcDsaPub", "ff_pqcDsaPriv",+ )++ /** A peer we may publish to, reduced to the two fields the publish path actually reads. */+ @Serializable+ data class Target(val id: Long, val bundle: String)++ private val json = Json { ignoreUnknownKeys = true }++ fun store(context: Context): DataStoreUtils =+ DataStoreUtils.getInstance(context, deviceProtected = true)++ /**+ * True once the mirror holds a usable identity. The pre-unlock path must refuse to run+ * without this: minting a userid or PQC identity here would not match the one in+ * credential-encrypted storage, and peers would see the publishes as coming from a+ * stranger they have never added.+ */+ suspend fun isSeeded(context: Context): Boolean {+ val ds = store(context)+ if (ds.getLongAwait(KEY_USERID) == null) return false+ return PQC_KEYS.all { ds.getByteArrayAwait(it) != null }+ }++ suspend fun userid(context: Context): Long? = store(context).getLongAwait(KEY_USERID)++ suspend fun roster(context: Context): List<Target> {+ val raw = store(context).getStringAwait(KEY_ROSTER) ?: return emptyList()+ return runCatching {+ json.decodeFromString(ListSerializer(Target.serializer()), raw)+ }.getOrDefault(emptyList())+ }++ suspend fun isTrackingEnabled(context: Context): Boolean =+ store(context).getBooleanAwait(KEY_TRACKING_ENABLED, true)++ suspend fun isGlobalSharingEnabled(context: Context): Boolean =+ store(context).getBooleanAwait(KEY_SHARING_ENABLED, true)++ /**+ * Copy the current identity, switches and publish roster out of credential-encrypted+ * storage. Called after unlock, when both stores are readable, so the next reboot has+ * something to work from. [targets] should already be filtered to who we actually publish+ * to, so the pre-unlock path needs to make no policy decisions of its own.+ *+ * The identity keys are overwritten rather than filled in only when missing. Credential-+ * encrypted storage is authoritative for who we are, and it can legitimately re-mint:+ * `Networking.init` generates a fresh `userid` whenever CE has none, and+ * `PqcIdentity.loadOrCreate` does the same for the `ff_pqc*` blobs. If the mirror were+ * allowed to keep the older copy the two would drift apart, and every pre-unlock publish+ * would go out signed by an identity the recipients have never seen — silently, with+ * nothing in the UI to show for it.+ */+ suspend fun seed(+ context: Context,+ targets: List<Target>,+ trackingEnabled: Boolean,+ globalSharingEnabled: Boolean,+ ) {+ DataStoreUtils.seedDeviceProtectedStorage(+ context,+ listOf(KEY_USERID) + PQC_KEYS,+ overwrite = true,+ )+ val de = store(context)+ de.setBoolean(KEY_TRACKING_ENABLED, trackingEnabled)+ de.setBoolean(KEY_SHARING_ENABLED, globalSharingEnabled)+ de.setString(KEY_ROSTER, json.encodeToString(ListSerializer(Target.serializer()), targets))+ }+}
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 fe63ba62e7..58c6cf5d03 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt@@ -16,7 +16,14 @@ import kotlinx.coroutines.flow.Flow @Dao interface LocationValueDao {- @Query("SELECT * FROM LocationValue WHERE (userid, timestamp) IN ( SELECT userid, MAX(timestamp) FROM LocationValue GROUP BY userid )")+ /**+ * The newest report per user, ranked by when it was *sent* rather than when its position was+ * measured. Shutdown and low-battery reports deliberately carry a stale fix, so ranking on+ * `timestamp` would let the live heartbeat that preceded them win and the parting report+ * would never reach the UI — stored, but invisible. For live-only data the two columns are+ * equal and this behaves exactly as it always did.+ */+ @Query("SELECT * FROM LocationValue WHERE (userid, reportedAt) IN ( SELECT userid, MAX(reportedAt) FROM LocationValue GROUP BY userid )") fun getLatest(): Flow<List<LocationValue>> @Query("SELECT * FROM LocationValue WHERE userid = :userid")@@ -147,7 +154,7 @@ interface TemporaryLinkDao { suspend fun delete(value: TemporaryLink): Int } -@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 11, exportSchema = false)+@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 12, exportSchema = false) @ColumnTypeConverters(DefaultConverters::class) abstract class FFDatabase : RoomDatabase() { abstract fun userDao(): UserDao@@ -234,6 +241,20 @@ abstract class FFDatabase : RoomDatabase() { ) it.execSQL("DROP TABLE `TemporaryLink`") it.execSQL("ALTER TABLE `TemporaryLink_new` RENAME TO `TemporaryLink`")+ },+ // A fix now records when it was measured (`timestamp`) separately from when it was+ // sent (`reportedAt`), because shutdown and low-battery reports deliberately publish+ // a stale last known position. Existing rows were all live reports, so `reportedAt`+ // backfills from `timestamp` and `source` defaults to LIVE. The index mirrors the+ // existing (userid, timestamp) one because getLatest now ranks on `reportedAt`.+ androidx.room3.migration.Migration(11, 12) {+ it.execSQL("ALTER TABLE `LocationValue` ADD COLUMN `reportedAt` INTEGER NOT NULL DEFAULT 0")+ it.execSQL("UPDATE `LocationValue` SET `reportedAt` = `timestamp`")+ it.execSQL("ALTER TABLE `LocationValue` ADD COLUMN `source` TEXT NOT NULL DEFAULT 'LIVE'")+ it.execSQL(+ "CREATE INDEX IF NOT EXISTS `index_LocationValue_userid_reportedAt` " ++ "ON `LocationValue` (`userid`, `reportedAt`)"+ ) } ) }
findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.ktindex 39c4ade3b3..b2870937c5 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/LocationValue.kt@@ -9,16 +9,99 @@ import com.vayunmathur.library.util.DatabaseItem import kotlinx.serialization.Serializable import kotlin.time.Instant +/**+ * Why a fix was published, so a receiver can tell a live report from a device's parting shot.+ *+ * Stored by Room as the enum name and carried on the wire as that same string. A value this+ * build does not recognise decodes to [UNKNOWN] rather than throwing or being guessed at — see+ * [LocationValueCompatible].+ *+ * ## Adding a value here is a wire-compatibility decision. Read this first.+ *+ * A peer older than your new value will **drop** fixes carrying it (see [UNKNOWN]). That is only+ * safe because every value below except [LIVE] is *supplementary*: a device still emits [LIVE]+ * for its ordinary heartbeat, so an older peer that discards the rest still tracks the person+ * normally and merely misses the extra context.+ *+ * **Do not add a value that becomes a device's primary or only report stream.** If you do, that+ * person does not appear stale on older peers — they vanish outright, with no pin and no error,+ * and the user cannot tell "they stopped sharing" from "my build is too old to understand them".+ * In a family-location app that silence is its own safety failure.+ *+ * If you genuinely need a new primary stream, change the receiving policy first: ship a build+ * that downgrades rather than drops, wait for it to reach the fleet, and only then start+ * emitting. The drop cannot be the thing you rely on.+ */ @Serializable-@Entity(indices = [Index(value = ["userid", "timestamp"])])+enum class LocationSource {+ /** The ordinary heartbeat, roughly as current as the fix age allows. */+ LIVE,++ /** Sent while the device was powering down or rebooting. The position is wherever it last was. */+ SHUTDOWN,++ /** Sent when the battery crossed the system low threshold, before the device dies on its own. */+ BATTERY_LOW,++ /**+ * Not sent by the device at all. Another phone running findfamily heard this device's+ * powered-off beacon and reported *its own* position as a proxy. The coordinate is where the+ * finder was standing, not where the device is, so it is only as precise as BLE range —+ * treat it as "somewhere within a block or so of here", never as a fix.+ */+ NETWORK_SIGHTING,++ /**+ * A source string this build has never heard of, from a peer newer than it. Never published —+ * decode-only.+ *+ * This exists because the categories are not interchangeable. [NETWORK_SIGHTING] is the+ * proof: its coordinate is *someone else's* position, so a build that guessed "probably+ * [LIVE]" would render a stranger's location as a precise, current fix of the person being+ * looked for, and send whoever is searching to the wrong place. That is the worst direction+ * for this app to be wrong in, and there is no way to know in advance which future category+ * carries the same trap.+ *+ * So an unrecognised source is treated as unusable rather than assumed benign, and inbound+ * fixes carrying it are dropped (see `LocationTrackingService.processIncomingLocations`).+ * That is safe only while new categories stay supplementary to [LIVE] — see the note on the+ * enum itself before adding one. Note this is distinct from a peer that omits the field+ * entirely: those predate the field, only ever sent live reports, and correctly decode+ * to [LIVE].+ */+ UNKNOWN,+}++@Serializable+@Entity(indices = [Index(value = ["userid", "timestamp"]), Index(value = ["userid", "reportedAt"])]) data class LocationValue( val userid: Long, @Embedded val coord: Coord, val speed: Float, val acc: Float,+ /**+ * When the position was actually measured — not when it was sent.+ *+ * The distinction only bites on [LocationSource.SHUTDOWN] and+ * [LocationSource.BATTERY_LOW] reports, which deliberately publish a possibly-stale+ * last known fix rather than wait for a fresh one. Keeping the measurement time here is+ * what lets "last seen" stay truthful instead of claiming the phone was there at the+ * moment it switched off. [reportedAt] carries the other half.+ */ @ColumnInfo(index = true) val timestamp: Instant, val battery: Float,+ /**+ * When the report was sent, as opposed to when the position in it was measured.+ *+ * Equal to [timestamp] on live reports and later than it on shutdown and low-battery ones.+ * This, not [timestamp], is what "which report is newest" has to be decided on: a parting+ * report carries a deliberately stale fix, so ranking by measurement time would let the live+ * heartbeat that preceded it win and the shutdown would never surface. See+ * `LocationValueDao.getLatest`.+ */+ val reportedAt: Instant = timestamp,+ val source: LocationSource = LocationSource.LIVE, @PrimaryKey(autoGenerate = true) override val id: Long = 0 ): DatabaseItem { fun toCompatible(senderPlatform: String? = null): LocationValueCompatible {@@ -31,7 +114,9 @@ data class LocationValue( battery = battery, sleep = false, id = id.toULong(),- senderPlatform = senderPlatform+ senderPlatform = senderPlatform,+ reportedAt = reportedAt.toEpochMilliseconds(),+ source = source.name, ) } }@@ -47,7 +132,17 @@ data class LocationValueCompatible( val battery: Float, val sleep: Boolean? = null, /** Sender's platform tag (`"android"` or `"ios"`). Optional for backward compatibility. */- val senderPlatform: String? = null+ val senderPlatform: String? = null,+ /** [LocationValue.reportedAt] in epoch milliseconds. Absent from peers that predate it, in+ * which case it falls back to [timestamp] — an older peer only ever sent live reports. */+ val reportedAt: Long? = null,+ /**+ * [LocationSource] by name. A plain string rather than the enum so a value this build has+ * never heard of degrades to [LocationSource.UNKNOWN] instead of failing the whole decode —+ * iOS and older Android peers have to keep interoperating. Absent entirely (null) means the+ * peer predates the field and only ever sent live reports, which is [LocationSource.LIVE].+ */+ val source: String? = null ) { fun toLocationValue(): LocationValue { return LocationValue(@@ -57,6 +152,15 @@ data class LocationValueCompatible( acc = acc, timestamp = Instant.fromEpochMilliseconds(timestamp), battery = battery,+ reportedAt = Instant.fromEpochMilliseconds(reportedAt ?: timestamp),+ // Absent means a peer older than the field, which only ever sent live reports.+ // Present but unrecognised means a peer NEWER than this build, whose category we+ // cannot interpret — guessing LIVE there would be unsafe, see LocationSource.UNKNOWN.+ source = when (source) {+ null -> LocationSource.LIVE+ else -> LocationSource.entries.firstOrNull { it.name == source }+ ?: LocationSource.UNKNOWN+ }, // NOT id = id.toLong(): `id` is the *sender's* local autogenerate primary // key. Reusing it here makes @Upsert collide across devices (every device's // ids grow from 1 in lockstep), so peers overwrite each other's — and your
findfamily/src/main/java/com/vayunmathur/findfamily/ipc/FamilyLocationService.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ipc/FamilyLocationService.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ipc/FamilyLocationService.ktindex 20ce643853..8e7d029654 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ipc/FamilyLocationService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ipc/FamilyLocationService.kt@@ -10,6 +10,7 @@ import android.os.Message import android.os.Messenger import android.os.RemoteException import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.util.Networking import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob@@ -161,7 +162,17 @@ class FamilyLocationService : Service() { val timestamps = ArrayList<Long>(locations.size) val batteries = ArrayList<Float>(locations.size) + // This device's own row is deliberately not sent. Maps already draws the user's own+ // position as the location puck, from its own fix rather than a round trip through here,+ // so including it would put a second, staler marker on top of the puck.+ //+ // Filtered at the source rather than in the client: the wire format has no self marker,+ // and adding one would mean every consumer had to remember to honour it. `userid` is 0+ // until the identity bootstrap has run, and no real id is 0, so the guard also stops a+ // pre-init snapshot dropping an innocent row.+ val self = Networking.userid for ((id, location) in locations) {+ if (self != 0L && id == self) continue // Skip anyone we can't label — a nameless pin isn't actionable. val name = namesById[id] ?: continue ids.add(id)
findfamily/src/main/java/com/vayunmathur/findfamily/platform/FinalLocationReporter.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FinalLocationReporter.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FinalLocationReporter.ktnew file mode 100644index 0000000000..66686b3c22--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FinalLocationReporter.kt@@ -0,0 +1,242 @@+package com.vayunmathur.findfamily.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.location.Location+import android.os.BatteryManager+import android.os.SystemClock+import android.util.Log+import com.vayunmathur.findfamily.data.Coord+import com.vayunmathur.findfamily.data.DirectBootStore+import com.vayunmathur.findfamily.data.LocationSource+import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.util.Networking+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.coroutines.withTimeoutOrNull+import java.util.concurrent.atomic.AtomicBoolean+import kotlin.time.Clock+import kotlin.time.Instant+import kotlin.time.Duration.Companion.milliseconds+import kotlin.time.Duration.Companion.seconds++/**+ * Publishes one last position when the device is about to stop reporting — on shutdown or+ * reboot, and when the battery crosses the system's low threshold.+ *+ * This is the cheap answer to "where did I lose it": a phone that is switched off or flat is+ * indistinguishable from one out of coverage, and the last live heartbeat can be half an hour+ * old. A parting report collapses that to the moment the device actually went away.+ *+ * Three things this deliberately does *not* do:+ *+ * - **It does not wait for a fresh fix.** The shutdown window is a couple of seconds, and a GPS+ * lock takes tens. Whatever the tracking service last held is what gets sent, however stale.+ * - **It does not claim that position is current.** The fix's own measurement time goes out as+ * [LocationValue.timestamp] and the moment of the shutdown as [LocationValue.reportedAt], so a+ * receiver can say "last seen twenty minutes before it switched off" rather than dropping a pin+ * where the phone demonstrably is not.+ * - **It does not reconnect, look up keys, or touch the database.** Every one of those can block+ * for seconds. It publishes to peers whose keys are already cached, over a socket that is+ * already open, or it publishes nothing and says so in the log.+ *+ * Registration has to happen at runtime, from the running tracking service. Both halves of that+ * were checked against the platform source in this tree:+ *+ * - `ShutdownThread.java:548` adds `FLAG_RECEIVER_REGISTERED_ONLY` to the shutdown broadcast, and+ * `Intent.ACTION_SHUTDOWN`'s own javadoc says it has only gone to `registerReceiver` callers+ * since P. A manifest entry would never fire.+ * - `frameworks/base/data/etc/framework-sysconfig.xml` is the `allow-implicit-broadcast`+ * exemption list, and its 23 entries are all telephony, SMS, media and package actions.+ * `ACTION_BATTERY_LOW` is not among them, so it is caught by the API-26 background limits.+ * Same conclusion, different mechanism.+ *+ * `ACTION_REBOOT` is in the filter as belt and braces. A reboot on this platform goes through+ * ShutdownThread and arrives as `ACTION_SHUTDOWN`; nothing in `services/core` broadcasts+ * `ACTION_REBOOT`, though Watchdog is built around receiving it, so it is not impossible.+ *+ * The corollary of runtime registration is that this only works while the tracking service is+ * alive — if the user has tracking switched off, there is nothing to report from.+ */+object FinalLocationReporter {++ private const val TAG = "FF-FinalReport"++ /**+ * How long the shutdown broadcast may be held open.+ *+ * [BroadcastReceiver.goAsync] keeps the broadcast in flight until `finish()`, and+ * `ShutdownThread` blocks on exactly that completion callback — so this is a delay to the+ * user's power-off, not free time. Its own ceiling is `MAX_BROADCAST_TIME = 10s`+ * (`ShutdownThread.java:81`), after which it logs "Shutdown broadcast timed out" and carries+ * on regardless. A quarter of that is long enough for a write on an already-open socket and+ * short enough that a wedged network stack cannot make the phone look hung.+ */+ private val BUDGET = 2.5.seconds++ /**+ * Separate budget for arming the powered-off beacon, which runs concurrently with the report+ * rather than after it — they contend for nothing, and serialising them would put the sum of+ * both on the user's power-off. The work is one binder call carrying 256 EIDs, which the+ * framework splits into ~22 vendor HCI commands to the controller. I have not been able to+ * measure how long that takes (no device), so this is a ceiling chosen to be invisible next+ * to [BUDGET], not a measurement.+ */+ private val BEACON_BUDGET = 2.seconds++ private var receiver: BroadcastReceiver? = null++ /** Set once a shutdown report goes out, so ACTION_REBOOT and ACTION_SHUTDOWN don't both fire. */+ private val shutdownReported = AtomicBoolean(false)++ /**+ * Deliberately not the tracking service's scope: that is cancelled in `onDestroy`, and the+ * whole point of this class is to still be able to work while everything is being torn down.+ */+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ /**+ * Start listening. [lastFix] and [roster] are read at broadcast time, not now, so the caller+ * keeps ownership of both. [roster] must already have the user's sharing switches applied —+ * this class makes no policy decisions of its own.+ */+ fun start(+ context: Context,+ lastFix: () -> Location?,+ roster: () -> List<DirectBootStore.Target>,+ ) {+ if (receiver != null) return+ val appContext = context.applicationContext+ val r = object : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ val source = when (intent.action) {+ Intent.ACTION_SHUTDOWN, Intent.ACTION_REBOOT -> LocationSource.SHUTDOWN+ Intent.ACTION_BATTERY_LOW -> LocationSource.BATTERY_LOW+ else -> return+ }+ if (source == LocationSource.SHUTDOWN && !shutdownReported.compareAndSet(false, true)) return++ val pending = goAsync()+ scope.launch {+ try {+ // Only on a real shutdown: the controller only advertises once the AP is+ // actually down, so arming on BATTERY_LOW would be pointless work in the+ // one window where the battery is the scarce thing.+ val beacon = if (source == LocationSource.SHUTDOWN) {+ // runCatching is load-bearing. This async is a child of the coroutine+ // sending the location report, so anything thrown out of it cancels+ // that report. armForShutdown catches its own expected failures, but+ // the work before its try block reads DataStore and derives 256 EIDs,+ // and a throw from there would cost us the fix. The report is the+ // proven feature and the beacon is speculative; the beacon never gets+ // to take the report down with it.+ //+ // Note the ordering: withTimeoutOrNull inside, runCatching outside.+ // The reverse would let runCatching swallow the timeout's own+ // CancellationException and defeat the budget.+ async {+ runCatching {+ withTimeoutOrNull(BEACON_BUDGET) {+ PoweredOffBeacon.armForShutdown(appContext)+ }+ }.onFailure { Log.w(TAG, "beacon arming threw", it) }.getOrNull()+ }+ } else {+ null+ }+ val done = withTimeoutOrNull(BUDGET) {+ report(appContext, source, lastFix(), roster())+ }+ if (beacon?.await() == null && source == LocationSource.SHUTDOWN) {+ Log.i(TAG, "powered-off beacon not armed")+ }+ // Swallowed on purpose: a parting report that did not make it out must+ // never be the reason the device refuses to power off.+ if (done == null) Log.w(TAG, "$source report gave up after $BUDGET")+ } catch (e: Exception) {+ Log.w(TAG, "$source report failed", e)+ } finally {+ pending.finish()+ }+ }+ }+ }+ val filter = IntentFilter().apply {+ addAction(Intent.ACTION_SHUTDOWN)+ addAction(Intent.ACTION_REBOOT)+ addAction(Intent.ACTION_BATTERY_LOW)+ }+ appContext.registerReceiver(r, filter, Context.RECEIVER_NOT_EXPORTED)+ receiver = r+ }++ fun stop(context: Context) {+ val r = receiver ?: return+ receiver = null+ runCatching { context.applicationContext.unregisterReceiver(r) }+ }++ private suspend fun report(+ context: Context,+ source: LocationSource,+ location: Location?,+ targets: List<DirectBootStore.Target>,+ ) {+ if (location == null) {+ Log.i(TAG, "$source: no fix has ever been taken, nothing to report")+ return+ }+ if (targets.isEmpty()) {+ Log.i(TAG, "$source: nobody to report to")+ return+ }+ if (Networking.userid == 0L) {+ Log.i(TAG, "$source: identity not loaded, nothing to report as")+ return+ }+ if (!Networking.liveConnected) {+ // Reconnecting costs a TLS handshake we do not have time for, and on shutdown the+ // radios are going down anyway. Saying so beats silently sending nothing.+ Log.i(TAG, "$source: socket is down, dropping the report")+ return+ }++ val now = Clock.System.now()+ val battery = runCatching {+ (context.getSystemService(BatteryManager::class.java))+ ?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)?.toFloat()+ }.getOrNull() ?: 0f++ val value = LocationValue(+ Networking.userid,+ Coord(location.latitude, location.longitude),+ 0f,+ location.accuracy,+ measuredAt(location, now),+ battery,+ reportedAt = now,+ source = source,+ )+ Log.i(TAG, "$source: reporting a fix ${now - value.timestamp} old to ${targets.size} peer(s)")+ targets.forEach {+ runCatching { Networking.publishLocation(value, it.id, it.bundle) }+ .onFailure { e -> Log.w(TAG, "$source publish to ${it.id.toULong()} failed", e) }+ }+ }++ /**+ * When the fix was actually taken, derived from the monotonic clock rather than+ * [Location.time]. Wall-clock time can be stepped by NTP or the user between the fix and+ * now, and the number this feeds is a claim about how stale the position is — an hour of+ * drift there would be an hour of lying about where someone last was.+ */+ private fun measuredAt(location: Location, now: Instant): Instant {+ val ageMs = (SystemClock.elapsedRealtimeNanos() - location.elapsedRealtimeNanos) / 1_000_000+ return now - ageMs.coerceAtLeast(0).milliseconds+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/platform/PoweredOffBeacon.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/PoweredOffBeacon.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/PoweredOffBeacon.ktnew file mode 100644index 0000000000..0f18ea3f9a--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/PoweredOffBeacon.kt@@ -0,0 +1,253 @@+package com.vayunmathur.findfamily.platform++import android.content.Context+import android.nearby.NearbyManager+import android.os.Build+import android.util.Log+import com.vayunmathur.findfamily.BuildConfig+import com.vayunmathur.findfamily.data.DirectBootStore+import com.vayunmathur.findfamily.tracker.PoweredOffKeyStore+import com.vayunmathur.findfamily.tracker.PoweredOffProtocol+import com.vayunmathur.findfamily.util.Networking+import java.security.SecureRandom++/**+ * Powered-off finding, beacon half: hands the Bluetooth controller a batch of rotating ephemeral+ * identifiers just before the device powers down, so a family member walking past can still+ * sight it.+ *+ * Off unless the user has explicitly turned it on. See [isEnabled].+ *+ * The scheme itself lives in [PoweredOffProtocol] and is deliberately **not** restated here — the+ * finder half derives from the same object, and two copies of a derivation that must agree+ * byte-for-byte is exactly how this feature fails silently. This class only decides *when* to+ * arm, *what* to persist, and *what* to tell the user.+ *+ * ## What the platform does with the list+ *+ * `NearbyManager.setPoweredOffFindingEphemeralIds` copies it into the Bluetooth controller's own+ * memory over vendor HCI `0xfd62`. Once the AP is down the controller — not Android — advertises+ * it: ~20 s delay, then index 0, advancing one index every 1024 s at a 2 s advertising interval.+ *+ * The consequences are all in [PoweredOffProtocol]: 256 keys maximum because the key index is one+ * byte on the wire, so 3.03 days of coverage per shutdown, and unspecified behaviour when the+ * list runs out. That last one is the reason for [ARM_CONTROLLER] below.+ */+object PoweredOffBeacon {++ private const val TAG = "FF-POF"++ /**+ * Whether to actually switch the controller on.+ *+ * Everything else in this class runs regardless: EIDs are derived, registered with the relay+ * and persisted, and the user-facing switch works. This gates only the final+ * `setPoweredOffFindingMode(ENABLED)` — the step that makes a switched-off phone transmit.+ *+ * It is dev-only on purpose, and the reason is not caution for its own sake. What the+ * controller does when it walks past the last key is not defined in the AIDL, the HAL, or any+ * test we can read; the walk happens in closed Broadcom firmware. If it stops, the feature+ * quietly expires after three days. If it wraps, the phone replays the same 256 identifiers+ * on a loop until the battery dies, and an observer who sees one twice knows it is the same+ * device — a fixed trackable identifier emitted by a phone the user believes is off. We+ * cannot test which, cannot fix it if it is the bad one (the SoC is down; nothing can refill+ * the buffer), and the app's threat model includes the people best placed to notice.+ *+ * The team's position is that stopping is far more likely, because Google ships this same+ * controller on retail Pixels and a static identifier would trip the unwanted-tracking+ * standard they co-authored. That is inference, not proof, and it is not enough to ship a+ * transmitter on. Flip this to unconditional when someone documents the firmware behaviour.+ */+ private val ARM_CONTROLLER = BuildConfig.DEV_BUILD++ private const val KEY_ENABLED = "pof_enabled"++ /**+ * Device-protected, for the same reason [DirectBootStore] exists: arming runs from a+ * broadcast receiver that can fire before first unlock, because a battery-low shutdown does+ * not wait for a passcode. Credential-encrypted storage is unreadable exactly then.+ *+ * **Every reader of [PoweredOffKeyStore] must pass this same store**, and nothing enforces+ * that — the class takes whatever [com.vayunmathur.library.util.DataStoreUtils] it is handed.+ * Writing here and reading from the credential-encrypted store makes `canRead` false forever:+ * no exception, no failed call, nothing in logcat, just zero sightings retrieved. That has+ * already happened once between the two halves of this feature. If a third caller appears,+ * make the store choice internal to [PoweredOffKeyStore] rather than repeating this comment.+ */+ private fun keys(context: Context) = PoweredOffKeyStore(DirectBootStore.store(context))++ /**+ * Opt-in, default OFF, and it must stay default OFF. A phone the user believes is switched+ * off does not start advertising because a default said so.+ */+ suspend fun isEnabled(context: Context): Boolean =+ DirectBootStore.store(context).getBooleanAwait(KEY_ENABLED, false)++ /**+ * Turn the beacon on or off.+ *+ * Turning it on mints the beacon secret and files it, with this device's ML-KEM private+ * bundle, under the owner's own userid — so sightings are readable from the user's other+ * devices rather than only by the phone that is lost and switched off.+ *+ * Turning it off clears the controller as well as the flag, so a device armed by an earlier+ * shutdown stops at the next one instead of running out its three days.+ */+ suspend fun setEnabled(context: Context, enabled: Boolean) {+ DirectBootStore.store(context).setBoolean(KEY_ENABLED, enabled)+ if (enabled) provisionKeys(context) else disarm(context)+ }++ /**+ * The system service, or null if this build cannot have it.+ *+ * The SDK_INT gate is not belt and braces. `:library:nearby-stubs` is `compileOnly`, so+ * `android.nearby.NearbyManager` is a compile-time promise about a class that only exists at+ * runtime from API 35 — and findfamily's minSdk is 31. Touching `NearbyManager::class.java`+ * on API 31-34 raises NoClassDefFoundError, which is an [Error] and would sail straight past+ * every `catch (e: Exception)` below and out through the shutdown receiver. Resolving the+ * class must be guarded by the version check, not by a try block.+ */+ private fun manager(context: Context): NearbyManager? {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.VANILLA_ICE_CREAM) return null+ return context.getSystemService(NearbyManager::class.java)+ }++ /**+ * Whether this device can do powered-off finding, as far as we are allowed to ask.+ *+ * There is no clean test. The framework's own `isPoweredOffFindingSupported()` is private,+ * and the one public method that reports it — `getPoweredOffFindingMode()` — is itself behind+ * BLUETOOTH_PRIVILEGED. So where findfamily is not a priv-app we cannot distinguish "the chip+ * cannot do this" from "we are not allowed to ask". Both mean it will not work here, so both+ * return false and the UI says the same thing.+ */+ suspend fun isSupported(context: Context): Boolean {+ val manager = manager(context) ?: return false+ return runCatching {+ manager.getPoweredOffFindingMode() != NearbyManager.POWERED_OFF_FINDING_MODE_UNSUPPORTED+ }.getOrDefault(false)+ }++ /**+ * Mint and file the keys needed to read this device's future sightings.+ *+ * Done at opt-in rather than at shutdown because it writes to storage and the shutdown window+ * is measured in seconds.+ *+ * What gets filed is the **raw ML-KEM private DER** — `ff_pqcKemPriv`, one of the four+ * separate `ff_pqc*` blobs in the direct-boot identity mirror — and NOT a composite+ * `[4B kemPrivLen][kemPriv][dsaPriv]` bundle of the kind `TrackerProtocol` uses. A tracker's+ * identity is minted by the phone on the tracker's behalf and is carried as that composite; a+ * powered-off phone is not a tracker and reuses its own existing identity, so there is no+ * bundle to carry. The distinction is invisible at the type level — both are `ByteArray` —+ * and getting it wrong is silent: the bundle parser reads the DER's leading SEQUENCE header+ * as a length field and every decrypt fails into a log line. It has already happened once.+ *+ * The sealing side needs no equivalent care: finders seal with `Pqc.encryptTo`, which takes a+ * public bundle, and the relay already holds this user's public bundle in that shape.+ *+ * NOT DONE, and the feature is much weaker without it: sharing these keys with a chosen family+ * member. A powered-off phone cannot decrypt its own sightings, so today this only helps a+ * user who has a second device of their own signed in. `PoweredOffKeyStore` is already keyed+ * by userid to hold a peer's keys; the distribution path over the e2ee peer channel, and the+ * UI to choose who gets them, are not written. Handing someone this key lets them locate the+ * device for as long as it lives, so it must never be synced to the whole roster by default.+ * Whoever writes it: file the raw DER here too, not a bundle.+ */+ private suspend fun provisionKeys(context: Context) {+ val userId = Networking.userid+ if (userId == 0L) {+ Log.i(TAG, "no identity yet, deferring key provisioning")+ return+ }+ val store = keys(context)+ if (store.canRead(userId)) return+ val secret = store.secret(userId)+ ?: ByteArray(32).also { SecureRandom().nextBytes(it) }+ val priv = DirectBootStore.store(context).getByteArrayAwait("ff_pqcKemPriv")+ if (priv == null) {+ Log.i(TAG, "identity mirror not seeded, deferring key provisioning")+ return+ }+ store.save(userId, secret, priv)+ }++ /**+ * Hand a fresh batch to the controller and, if [ARM_CONTROLLER], switch advertising on.+ * Called from [FinalLocationReporter] on the shutdown broadcast.+ *+ * Returns the EID count armed, or null if nothing was armed — which is an ordinary outcome,+ * not an error. Everything is logged rather than thrown: this runs inside the broadcast that+ * blocks the user's power-off and nothing here is worth delaying that for.+ *+ * The EIDs are derived here rather than precomputed because index 0 must be the slot+ * containing the shutdown instant, which is only known now. The cost is 256 HMAC-SHA256+ * invocations over a 14-byte message — negligible beside the ~22 vendor HCI commands the+ * framework then issues to move the result into the controller.+ */+ suspend fun armForShutdown(context: Context): Int? {+ if (!isEnabled(context)) return null++ val userId = Networking.userid+ if (userId == 0L) return null+ val secret = keys(context).secret(userId) ?: run {+ Log.i(TAG, "no beacon secret, not armed")+ return null+ }++ val eids = PoweredOffProtocol.armingEids(secret)++ // Before the radios go down, and before the controller is told anything. Once the phone+ // is off it cannot re-register and will not self-heal, so a beacon the relay has never+ // heard of would advertise for three days into nothing.+ if (!Networking.registerPoweredOffEids(userId, eids)) {+ Log.i(TAG, "relay did not accept the EID list, not arming")+ return null+ }++ val manager = manager(context)+ if (manager == null) {+ Log.i(TAG, "no NearbyManager on this build")+ return null+ }++ return try {+ manager.setPoweredOffFindingEphemeralIds(eids)+ if (ARM_CONTROLLER) {+ manager.setPoweredOffFindingMode(NearbyManager.POWERED_OFF_FINDING_MODE_ENABLED)+ Log.i(TAG, "armed ${eids.size} EIDs (~3 days)")+ } else {+ Log.i(TAG, "loaded ${eids.size} EIDs; controller NOT enabled (release build)")+ }+ eids.size+ } catch (e: UnsupportedOperationException) {+ // Neither ro. nor persist.bluetooth.finder.supported is set. There is no public+ // predicate to ask first, so catching this is the supported way to feature-detect.+ Log.i(TAG, "powered-off finding unsupported on this device")+ null+ } catch (e: SecurityException) {+ // BLUETOOTH_PRIVILEGED is signature|privileged. findfamily only holds it when it is+ // installed as a MAOS priv-app with a privapp-permissions entry, which as of today it+ // is not — vendor/modern-apps/Android.bp declares it an ordinary user app.+ Log.i(TAG, "BLUETOOTH_PRIVILEGED not held, beacon not armed")+ null+ } catch (e: IllegalStateException) {+ // setPoweredOffFindingMode(ENABLED) requires Bluetooth and location both on. The EIDs+ // are already in the controller but will not be advertised, which is correct: the+ // user turned a radio off.+ Log.i(TAG, "Bluetooth or location is off, beacon not armed")+ null+ } catch (e: Exception) {+ Log.w(TAG, "arming failed", e)+ null+ }+ }++ private fun disarm(context: Context) {+ val manager = manager(context) ?: return+ runCatching {+ manager.setPoweredOffFindingMode(NearbyManager.POWERED_OFF_FINDING_MODE_DISABLED)+ }.onFailure { Log.i(TAG, "disarm skipped: ${it.javaClass.simpleName}") }+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffBle.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffBle.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffBle.ktnew file mode 100644index 0000000000..631ac962fc--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffBle.kt@@ -0,0 +1,96 @@+package com.vayunmathur.findfamily.tracker++import android.bluetooth.le.ScanFilter+import android.os.ParcelUuid+import java.util.UUID++/**+ * The on-air shape of a powered-off beacon, and the one part of this feature that is **assumed+ * rather than verified**. Read this before trusting the scanner.+ *+ * ## Why it cannot be read out of the source+ * Powered-off beacons are emitted after Android is gone, by the Bluetooth controller itself. All+ * the HAL does is hand the controller a list of 20-byte keys and some advertising parameters+ * over vendor HCI opcode `0xfd62`+ * (`hardware/interfaces/bluetooth/bluetooth_hal/extensions/finder/bluetooth_finder_handler.cc`).+ * It sets the advertising interval (2000ms), the TX power (0x0A), the key rotation period+ * (1024s) and a 20s start delay — and nothing else. Closed controller firmware composes the+ * actual advertisement. There is no service UUID, no frame type and no payload assembly anywhere+ * in the platform tree, so the byte layout below is **not confirmed by anything we can read**.+ * Confirming it needs an on-air capture from a powered-off device.+ *+ * ## What is assumed+ * Service data under one of [CANDIDATE_SERVICE_UUIDS], laid out as:+ * ```+ * [0] frame type 0x40+ * [1..21] 20-byte EID+ * [21] hashed flags (optional, ignored)+ * ```+ * Two service UUIDs are matched because the evidence points at one and does not rule out the+ * other, and guessing wrong costs everything: the symptom of a wrong UUID is a scanner that+ * matches nothing, silently, forever. [FAST_PAIR_UUID] (0xFE2C) is the stronger candidate —+ * Find My Device Network is built on top of Google Fast Pair, and 0xFE2C is the only relevant+ * service constant anywhere in the tree+ * (`packages/modules/Bluetooth/.../le_scan/MsftAdvMonitorTest.kt`, credit to the lead for+ * finding it). [EDDYSTONE_UUID] (0xFEAA) is kept as a second filter because Eddystone-EID is the+ * other published 20-byte EID format. Both filters are evaluated in controller hardware, so+ * carrying the second one costs no battery.+ *+ * If a capture ever settles it, delete the loser and nothing else changes: [FRAME_TYPE] and+ * [EID_OFFSET] are the only other guesses, and nothing downstream of [PoweredOffScanner] depends+ * on any of them. The derivation, the sealing, the upload and the retrieval are all unaffected.+ */+object PoweredOffBle {++ /** Google Fast Pair Service. Find My Device Network frames are a GFPS frame type. */+ val FAST_PAIR_UUID: UUID = UUID.fromString("0000fe2c-0000-1000-8000-00805f9b34fb")++ /** Eddystone, the other published home for a 20-byte EID. Kept as a fallback match. */+ val EDDYSTONE_UUID: UUID = UUID.fromString("0000feaa-0000-1000-8000-00805f9b34fb")++ /** Every service UUID the beacon might be advertising under, best guess first. */+ val CANDIDATE_SERVICE_UUIDS: List<ParcelUuid> =+ listOf(ParcelUuid(FAST_PAIR_UUID), ParcelUuid(EDDYSTONE_UUID))++ /** First service-data byte, identifying the frame as an FMDN one. */+ const val FRAME_TYPE: Byte = 0x40++ /** Where the EID starts within the service data, i.e. straight after [FRAME_TYPE]. */+ const val EID_OFFSET: Int = 1++ /** Shortest service data that can still carry a whole EID. */+ const val MIN_SERVICE_DATA_LEN: Int = EID_OFFSET + PoweredOffProtocol.EID_LEN++ /**+ * Filters matching only FMDN frames, tight enough for the controller to evaluate in hardware+ * so the application processor is never woken by unrelated advertisements — which on a busy+ * street is essentially all of them. Matching on the service-data prefix rather than just the+ * service UUID matters: ordinary Fast Pair and Eddystone beacons are common and share these+ * UUIDs, and each one would otherwise cost a wakeup.+ */+ fun scanFilters(): List<ScanFilter> = CANDIDATE_SERVICE_UUIDS.map { uuid ->+ ScanFilter.Builder()+ .setServiceData(uuid, byteArrayOf(FRAME_TYPE), byteArrayOf(0xFF.toByte()))+ .build()+ }++ /** The EID carried by this service data, or null if it is malformed or not an FMDN frame. */+ fun eidFrom(serviceData: ByteArray?): ByteArray? {+ if (serviceData == null || serviceData.size < MIN_SERVICE_DATA_LEN) return null+ if (serviceData[0] != FRAME_TYPE) return null+ return serviceData.copyOfRange(EID_OFFSET, EID_OFFSET + PoweredOffProtocol.EID_LEN)+ }+}++/** One powered-off beacon heard by a finder phone. */+data class PoweredOffSighting(+ /** The 20-byte rotating EID from the advertisement. */+ val eid: ByteArray,+ /** Received signal strength (dBm) — a very coarse proximity hint, not reported to anyone. */+ val rssi: Int,+) {+ override fun equals(other: Any?): Boolean =+ other is PoweredOffSighting && eid.contentEquals(other.eid) && rssi == other.rssi++ override fun hashCode(): Int = eid.contentHashCode() * 31 + rssi+}
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffKeyStore.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffKeyStore.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffKeyStore.ktnew file mode 100644index 0000000000..524f6ee54e--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffKeyStore.kt@@ -0,0 +1,62 @@+package com.vayunmathur.findfamily.tracker++import com.vayunmathur.library.util.DataStoreUtils++/**+ * The keys needed to read a device's powered-off sightings, held per device userid.+ *+ * ## Who holds what, and why it matters+ * A powered-off phone cannot decrypt anything — it is off, and by the time it is back on you+ * have already found it. So keeping the private key only on the device that beacons would make+ * the whole feature useless. The AOSP javadoc anticipates this: reports are readable by "the+ * device owner **or someone that the device owner shared the key with**".+ *+ * So there are two cases, and this store handles both identically:+ * - **your own device**, whose keys you keep so you can look up its sightings from your tablet+ * or after it comes back;+ * - **a family member's device**, whose keys they sent you over the existing end-to-end+ * encrypted peer channel when they armed it, so you can go and look for their lost phone.+ *+ * Handing someone your powered-off private key lets them locate that device for as long as the+ * key lives, so the beacon half must only ever distribute it to peers the user has explicitly+ * chosen — it is not something to sync to everyone by default.+ *+ * The secret is the same per-device value the rest of the crowd network uses; it is here rather+ * than in [TrackerStore] because [TrackerStore] is keyed on tracker `User` rows and these are+ * ordinary people.+ * ## What is stored, and why the name matters+ * The key half is the device's **raw ML-KEM private DER** — the `ff_pqcKemPriv` blob from the+ * identity mirror — and deliberately NOT the composite `[4B kemPrivLen][kemPriv][dsaPriv]` that+ * the word "bundle" means everywhere else in this package. A powered-off phone reuses its own+ * existing identity, whereas a tracker's identity is minted on its behalf and is composite.+ * These accessors are named [kemPrivateKey] rather than `privateBundle` because calling it a+ * bundle already caused one silent bug: the value was fed to+ * [TrackerProtocol.kemPrivFromPrivateBundle], which read the DER's leading SEQUENCE header as a+ * length field and failed every decrypt. Both shapes are `ByteArray`, so nothing but the name+ * stops the next caller repeating it. Decrypt this with `Pqc.decrypt` directly.+ *+ * The set of owned trackers is simply the `User` rows with `kind == UserKind.TRACKER`, so+ * no separate index is kept here.+ */+class PoweredOffKeyStore(private val ds: DataStoreUtils) {++ /**+ * Stores (or replaces) the beacon secret and the raw ML-KEM private DER for [userId].+ * [kemPrivateKey] must be the raw key, not a composite bundle — see the class KDoc.+ */+ suspend fun save(userId: Long, secret: ByteArray, kemPrivateKey: ByteArray) {+ ds.setByteArray(secretKey(userId), secret)+ ds.setByteArray(privKey(userId), kemPrivateKey)+ }++ suspend fun secret(userId: Long): ByteArray? = ds.getByteArrayAwait(secretKey(userId))++ /** The raw ML-KEM private DER, ready to hand straight to `Pqc.decrypt`. */+ suspend fun kemPrivateKey(userId: Long): ByteArray? = ds.getByteArrayAwait(privKey(userId))++ /** True when both keys are present, i.e. this device's sightings are readable here. */+ suspend fun canRead(userId: Long): Boolean = secret(userId) != null && kemPrivateKey(userId) != null++ private fun secretKey(id: Long) = "ff_pof_secret_$id"+ private fun privKey(id: Long) = "ff_pof_priv_$id"+}
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffProtocol.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffProtocol.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffProtocol.ktnew file mode 100644index 0000000000..69c3850c84--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffProtocol.kt@@ -0,0 +1,122 @@+package com.vayunmathur.findfamily.tracker++import javax.crypto.Mac+import javax.crypto.spec.SecretKeySpec++/**+ * Shared contract for powered-off finding. **Both halves of the feature derive from this+ * object** — the beacon half arms the Bluetooth controller with [eids] before shutdown, the+ * finder half matches what it hears and the owner half looks reports up by [handleOf]. If the+ * two halves ever disagree the feature fails completely silently: no error, no log, just zero+ * sightings forever. Change nothing here without changing both sides.+ *+ * ## Why this is separate from [TrackerProtocol]+ * Powered-off beacons are emitted by the Bluetooth *controller* after Android is gone, so the+ * shape is dictated by the vendor HCI interface rather than by us+ * (`hardware/interfaces/bluetooth/bluetooth_hal/extensions/finder/`). Two constants there are+ * not negotiable and neither matches the UWB tracker network:+ * - `Eid.aidl` is literally `byte[20] bytes` and the vendor command copies exactly 20 bytes+ * per key, so [EID_LEN] is 20, not [TrackerProtocol.EPOCH_ID_LEN].+ * - the HAL hardcodes `kPrecomputedKeyRotatedInterval = 0x400`, so [SLOT_SECONDS] is 1024, not+ * [TrackerProtocol.EPOCH_SECONDS]. Deriving on the tracker's 900s period would drift 124s per+ * slot against the controller's own timer and desynchronise within a couple of hours.+ * A distinct [EID_DOMAIN] keeps the two id spaces from ever colliding.+ *+ * ## Slot anchoring — the subtle part+ * The controller starts key index 0 shortly after shutdown and advances every [SLOT_SECONDS] on+ * its own timer, so its schedule is anchored to *shutdown time*, not to the wall clock. The+ * beacon half still derives on wall-clock slots and arms key 0 = the slot containing the+ * shutdown instant. The consequence is that a key is emitted slightly *later* than the slot it+ * was derived for, by an amount strictly less than one slot that does not accumulate. That+ * bounded lag is the whole reason the owner queries [recentHandles] backwards in time rather+ * than for a single slot. A shutdown-anchored counter would not be derivable by anyone who does+ * not already know the shutdown timestamp, which is why we do not use one.+ *+ * ## The EID is not a public key+ * The AOSP javadoc describes Find My Device network EIDs as "the public part of asymmetric key+ * pairs" that finders encrypt to directly. That is not implementable here: 20 bytes cannot hold+ * an X25519 or ML-KEM-768 public key, and Google only manages it by using secp160r1, which+ * Conscrypt does not support. So an EID here is an opaque rotating *handle*; the actual+ * encryption target is the device's ML-KEM-768 public bundle, which the finder fetches by+ * handle. See [PoweredOffReporting] for what that costs in privacy terms.+ */+object PoweredOffProtocol {++ /** Length of one EID. Fixed at 20 by `Eid.aidl` and the vendor HCI command. */+ const val EID_LEN: Int = 20++ /** EID rotation period. Fixed at 1024s by `kPrecomputedKeyRotatedInterval` in the HAL. */+ const val SLOT_SECONDS: Long = 1024L++ /**+ * How many slots the beacon half arms, and therefore how many the owner half queries.+ *+ * 256 is the hard ceiling and there is no reason to arm fewer: the controller's key index is+ * a single byte on the wire (`command[5]` and `command[10]` in+ * `bluetooth_finder_handler.cc`), so 0..255 is everything it can address. At+ * [SLOT_SECONDS] each that is 72.8 hours — a little over three days of powered-off+ * advertising, which is the real limit on how long a switched-off phone stays findable.+ *+ * What the controller does when the list runs out is **not specified anywhere we can read**.+ * The likeliest behaviour by a distance is that it stops advertising, since a beacon that+ * degenerated into a static identifier after three days would trip the unwanted-tracking+ * standard Google co-authored. That is inference from the fact that Google ships this same+ * HAL on retail hardware, not something confirmed from source, and it should keep being+ * described that way.+ */+ const val ARMED_SLOTS: Int = 256++ /** Domain-separation tag. Deliberately not `TrackerProtocol`'s, so the id spaces cannot collide. */+ private const val EID_DOMAIN = "ffpof1"++ /** The wall-clock slot number for a time in milliseconds. */+ fun currentSlot(nowMs: Long = System.currentTimeMillis()): Long = (nowMs / 1000L) / SLOT_SECONDS++ /**+ * The 20-byte EID for a `(secret, slot)` pair:+ * `HMAC-SHA256(secret, "ffpof1" || u64_be(slot))[..20]`. The secret is the same per-device+ * [TrackerProtocol.SECRET_LEN]-byte value the rest of the crowd network uses.+ */+ fun eid(secret: ByteArray, slot: Long): ByteArray {+ val mac = Mac.getInstance("HmacSHA256")+ mac.init(SecretKeySpec(secret, "HmacSHA256"))+ mac.update(EID_DOMAIN.toByteArray(Charsets.US_ASCII))+ mac.update(TrackerProtocol.u64be(slot))+ return mac.doFinal().copyOf(EID_LEN)+ }++ /**+ * The EIDs to arm the controller with when shutting down at [nowMs], oldest first. Index 0+ * is the slot containing the shutdown instant, which is the key the controller starts on.+ */+ fun armingEids(secret: ByteArray, nowMs: Long = System.currentTimeMillis(), count: Int = ARMED_SLOTS): List<ByteArray> {+ val first = currentSlot(nowMs)+ return (0 until count).map { eid(secret, first + it) }+ }++ /**+ * The lookup handle for an EID: its first 16 bytes.+ *+ * The relay keys resolutions and report buckets on 16 bytes+ * (`[0x07][16B]`, `[0x09][16B][ct]`), and there is no reason to widen a wire format that+ * already works. Truncating a 20-byte HMAC output to 16 leaves it just as unpredictable, and+ * a collision between two devices' handles would only cause a wasted resolve.+ */+ fun handleOf(eid: ByteArray): ByteArray = eid.copyOf(TrackerProtocol.EPOCH_ID_LEN)++ /**+ * Handles the owner should query to collect sightings from a powered-off window that started+ * up to [back] slots ago, newest first.+ *+ * Reaches one slot into the future as well, because the beacon may have been armed by a+ * device whose clock ran slightly ahead of this one; the extra query is free.+ */+ fun recentHandles(+ secret: ByteArray,+ nowMs: Long = System.currentTimeMillis(),+ back: Int = ARMED_SLOTS,+ ): List<ByteArray> {+ val cur = currentSlot(nowMs)+ return (-1..back).map { handleOf(eid(secret, cur - it)) }+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffReporting.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffReporting.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffReporting.ktnew file mode 100644index 0000000000..1e374a58df--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffReporting.kt@@ -0,0 +1,110 @@+package com.vayunmathur.findfamily.tracker++import android.util.Log+import com.vayunmathur.e2ee.Pqc+import com.vayunmathur.findfamily.data.LocationSource+import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.data.LocationValueCompatible+import com.vayunmathur.findfamily.util.Networking+import kotlinx.serialization.json.Json++/**+ * Ties powered-off sightings to the relay, for both roles.+ *+ * ## The privacy property, stated exactly+ * A finder sees an opaque rotating [PoweredOffProtocol.eid], asks the relay for the ML-KEM-768+ * *public* bundle it belongs to, seals **its own** GPS position to that bundle, and uploads the+ * ciphertext. So:+ * - the **finder** learns a random-looking 20 bytes and a public key. Not an identity, not a+ * name, not where the beaconing device is, not even that it is a phone. Its own userid is+ * stripped from the sealed payload, so the owner cannot tell who found their device either.+ * - the **relay** stores bytes it has no key for.+ * - only the **owner**, or a peer they deliberately shared with, can open it.+ *+ * What is *not* true, and should not be claimed: the relay does learn "handle X was sighted",+ * and since it holds the registration it can tie that to a device. It does not learn where — the+ * position is inside the ciphertext. That linkability is inherent to the existing crowd design+ * rather than something added here, but it is real.+ */+object PoweredOffReporting {+ private const val TAG = "PoweredOffReporting"++ /**+ * EIDs already reported, so a beacon two metres away does not cost a resolve and an upload+ * every two seconds. Reporting each EID once is the natural rate: the EID rotates every+ * [PoweredOffProtocol.SLOT_SECONDS], so a beacon we sit next to all day still produces a+ * steady trickle of fresh sightings rather than nothing.+ */+ private val reportedEids = LinkedHashMap<String, Long>()+ private const val MAX_REMEMBERED_EIDS = 512++ private val json = Json { ignoreUnknownKeys = true }++ /**+ * Finder: resolve, seal this finder's [finderLocation] to the beacon's public bundle, and+ * upload. Returns false when the handle resolves to nothing (a beacon from a device we have+ * no business reporting, or a relay that predates this feature) or the socket is down.+ */+ suspend fun reportSighting(sighting: PoweredOffSighting, finderLocation: LocationValue): Boolean {+ if (!shouldReport(sighting.eid)) return false+ val handle = PoweredOffProtocol.handleOf(sighting.eid)+ val bundle = Networking.resolveTrackerBundle(handle) ?: return false+ val ct = TrackerProtocol.sealReport(bundle, finderLocation)+ val ok = Networking.uploadTrackerReport(handle, ct)+ if (ok) Log.i(TAG, "uploaded powered-off sighting (rssi=${sighting.rssi})")+ return ok+ }++ /**+ * Owner: fetch and decrypt sightings of [userId]'s powered-off beacon, newest first, or an+ * empty list if there are none — which is the ordinary case and must not be dressed up as+ * anything else. Each result is stamped [LocationSource.NETWORK_SIGHTING] here rather than+ * trusting the finder to have set it, so a sighting can never be rendered as a live fix.+ */+ suspend fun fetchSightings(userId: Long, store: PoweredOffKeyStore): List<LocationValue> {+ val secret = store.secret(userId) ?: return emptyList()+ val kemPriv = store.kemPrivateKey(userId) ?: return emptyList()+ val cts = Networking.fetchTrackerReports(PoweredOffProtocol.recentHandles(secret))+ if (cts.isEmpty()) return emptyList()+ return cts.mapNotNull { ct ->+ runCatching { openSighting(kemPriv, ct, userId) }+ .onFailure { Log.w(TAG, "could not open a sighting for $userId", it) }+ .getOrNull()+ }.sortedByDescending { it.timestamp }+ }++ /**+ * Decrypt one sealed sighting.+ *+ * Deliberately **not** [TrackerProtocol.openReport], even though the envelope is identical.+ * That one takes a tracker's composite `[4B kemPrivLen][kemPriv][dsaPriv]` bundle, because a+ * tracker's identity is minted by the phone on its behalf. A powered-off phone is not a+ * tracker: it reuses its own existing ML-KEM identity, and what the beacon half files is the+ * **raw** private DER straight out of the direct-boot identity mirror (`ff_pqcKemPriv`, one of+ * the four separate `ff_pqc*` blobs). Passing that to the bundle parser makes it read the+ * DER's leading SEQUENCE header as a length field, and every decrypt fails.+ *+ * The sealing side needs no equivalent care: finders seal with `Pqc.encryptTo`, which takes a+ * *public* bundle, and the relay hands back this user's ordinary public bundle, which is+ * already in that shape.+ */+ private fun openSighting(kemPriv: ByteArray, ciphertext: ByteArray, userId: Long): LocationValue {+ val plain = Pqc.decrypt(kemPriv, ciphertext)+ return json.decodeFromString<LocationValueCompatible>(plain.decodeToString())+ .toLocationValue()+ .copy(userid = userId, source = LocationSource.NETWORK_SIGHTING)+ }++ @Synchronized+ private fun shouldReport(eid: ByteArray): Boolean {+ val hex = eid.joinToString("") { "%02x".format(it) }+ val now = System.currentTimeMillis()+ val staleBefore = now - PoweredOffProtocol.SLOT_SECONDS * 2000L+ reportedEids.entries.removeAll { it.value < staleBefore }+ if (reportedEids.put(hex, now) != null) return false+ while (reportedEids.size > MAX_REMEMBERED_EIDS) {+ reportedEids.remove(reportedEids.keys.first())+ }+ return true+ }+}
findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffScanner.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffScanner.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffScanner.ktnew file mode 100644index 0000000000..5b16da3a1b--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/PoweredOffScanner.kt@@ -0,0 +1,114 @@+package com.vayunmathur.findfamily.tracker++import android.annotation.SuppressLint+import android.bluetooth.BluetoothAdapter+import android.bluetooth.BluetoothManager+import android.bluetooth.le.ScanCallback+import android.bluetooth.le.ScanResult+import android.bluetooth.le.ScanSettings+import android.content.Context+import android.util.Log+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.callbackFlow++/**+ * Scans for powered-off beacons ([PoweredOffBle]) and emits a [PoweredOffSighting] for each.+ *+ * This is the half of powered-off finding that needs **no privileged permission and no custom+ * OS**. Arming a beacon requires `BLUETOOTH_PRIVILEGED`, which is `signature|privileged`, so only+ * a preinstalled build can do it — but hearing one is ordinary `BLUETOOTH_SCAN`, so any phone+ * with findfamily on it can contribute sightings. Keep it that way: nothing in this file, or+ * anything it calls, may come to depend on a privileged API.+ *+ * ## Battery+ * A finder is doing a favour for a stranger, so this has to cost close to nothing or nobody will+ * leave it on and the network is worthless. Three things do the work:+ * - **Hardware offload filtering.** [PoweredOffBle.scanFilter] matches on the service-data+ * prefix, so the controller discards non-FMDN advertisements without waking the application+ * processor. On a busy street that is essentially all of them.+ * - **First-match callbacks.** With offloaded filtering the controller reports each matching+ * device *once* rather than every 2 seconds forever. A beacon's EID only rotates every+ * [PoweredOffProtocol.SLOT_SECONDS], so per-advertisement callbacks would be ~500 wakeups per+ * beacon per useful report. Where the controller can't do it we fall back to+ * `CALLBACK_TYPE_ALL_MATCHES` and [PoweredOffReporting] dedupes in software instead —+ * correct either way, just less efficient.+ * - **Low-power duty cycle**, the longest window/interval the framework offers.+ *+ * There is deliberately **no wakelock**. This runs inside the existing location foreground+ * service; if that service is not running we simply are not a finder for a while, which is the+ * right trade for someone else's benefit.+ */+class PoweredOffScanner(private val context: Context) {++ @SuppressLint("MissingPermission")+ fun sightings(): Flow<PoweredOffSighting> = callbackFlow {+ val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager+ val adapter = manager?.adapter+ val scanner = adapter?.bluetoothLeScanner+ if (adapter == null || scanner == null) {+ Log.i(TAG, "no BLE scanner (adapter off or unavailable)")+ close()+ return@callbackFlow+ }++ val callback = object : ScanCallback() {+ override fun onScanResult(callbackType: Int, result: ScanResult) {+ val record = result.scanRecord ?: return+ // Which of the candidate UUIDs the frame actually arrived under is unknown until+ // someone captures one, so try each and take the first that parses.+ val eid = PoweredOffBle.CANDIDATE_SERVICE_UUIDS+ .firstNotNullOfOrNull { PoweredOffBle.eidFrom(record.getServiceData(it)) } ?: return+ trySend(PoweredOffSighting(eid, result.rssi))+ }++ override fun onBatchScanResults(results: MutableList<ScanResult>) {+ results.forEach { onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, it) }+ }++ override fun onScanFailed(errorCode: Int) {+ Log.w(TAG, "scan failed: $errorCode")+ }+ }++ try {+ scanner.startScan(PoweredOffBle.scanFilters(), scanSettings(adapter), callback)+ Log.i(TAG, "powered-off 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) } }+ }++ private fun scanSettings(adapter: BluetoothAdapter): ScanSettings {+ val builder = ScanSettings.Builder()+ .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)+ // The frame is assumed legacy, but the firmware composes it and we cannot read it+ // (see PoweredOffBle). setLegacy(false) reports legacy *and* extended results, so+ // this stays correct whichever the controller chose.+ .setLegacy(false)+ .setPhy(ScanSettings.PHY_LE_ALL_SUPPORTED)+ if (adapter.isOffloadedFilteringSupported) {+ builder.setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH)+ // STICKY only reports a beacon once it has been heard convincingly, which suits+ // a report that costs a network round-trip; AGGRESSIVE would fire on a single+ // weak advertisement from something we may never hear again.+ .setMatchMode(ScanSettings.MATCH_MODE_STICKY)+ .setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)+ } else {+ Log.i(TAG, "no offloaded filtering; falling back to all-matches and software dedup")+ }+ return builder.build()+ }++ companion object {+ private const val TAG = "PoweredOffScanner"+ }+}
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.ktindex 2b4a54ce17..6385d0062e 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProtocol.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/tracker/TrackerProtocol.kt@@ -106,7 +106,7 @@ object TrackerProtocol { return priv.copyOfRange(4, 4 + len) } - private fun u64be(v: Long): ByteArray {+ internal 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/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 64163ebe84..7548077a5b 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -2,6 +2,7 @@ package com.vayunmathur.findfamily.ui import com.vayunmathur.library.ui.DateString import com.vayunmathur.library.ui.is24Hour+import android.Manifest import android.content.Context import androidx.activity.compose.BackHandler import androidx.compose.foundation.Image@@ -63,6 +64,8 @@ import com.vayunmathur.library.ui.ToggleFloatingActionButton import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.ui.dynamicLightColorScheme import com.vayunmathur.library.ui.rememberBottomSheetScaffoldState+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.library.ui.rememberPermissionRequest import com.vayunmathur.library.ui.rememberSliderState import com.vayunmathur.library.room.SqlCipherDbCodec import com.vayunmathur.findfamily.ui.dialogs.interactionSourceClickable@@ -98,6 +101,7 @@ import kotlin.math.roundToInt import com.vayunmathur.findfamily.R import com.vayunmathur.findfamily.BuildConfig import com.vayunmathur.findfamily.Route+import com.vayunmathur.findfamily.data.LocationSource import com.vayunmathur.findfamily.data.LocationValue import com.vayunmathur.findfamily.data.TemporaryLink import com.vayunmathur.findfamily.data.User@@ -190,6 +194,7 @@ fun MainPage( val temporaryLinks by ffViewModel.temporaryLinks.collectAsState() val waypoints by ffViewModel.waypoints.collectAsState() val globalSharingEnabled by ffViewModel.globalSharingEnabled.collectAsState()+ val crowdFindingEnabled by ffViewModel.crowdFindingEnabled.collectAsState() val connectedUsers by ffViewModel.connectedUsers.collectAsState() val awaitingRequestUsers by ffViewModel.awaitingRequestUsers.collectAsState()@@ -280,7 +285,7 @@ fun MainPage( userNamesByLocationName = usersByLocationName ), person = selectedUser?.let {- PersonUiState(it, userPositions[it.id], waypoints, globalSharingEnabled)+ PersonUiState(it, userPositions[it.id], waypoints, globalSharingEnabled, crowdFindingEnabled) } ) @@ -772,6 +777,50 @@ fun PersonDetailSheet(state: PersonUiState, actions: PersonActions) { ) { Text(stringResource(R.string.change_connected_contact)) }+ // Only offered on your own entry: both are properties of this phone, not of a relationship+ // with a particular person. They are the two halves of powered-off finding and sit+ // together on purpose — "keep mine findable" next to "help find theirs" is what makes the+ // bargain legible. Showing either alone invites the fair objection that you are taking+ // from the network without giving back, or giving without getting.+ if (user.id == Networking.userid) {+ Spacer(Modifier.height(4.dp))+ PoweredOffFindingSetting()+ Spacer(Modifier.height(8.dp))+ CrowdFindingRow(state.crowdFindingEnabled) { actions.setCrowdFinding(it) }+ }+ }+}++/**+ * Opt-in for acting as a finder. Deliberately a switch with the explanation always visible rather+ * than a one-time dialog: the user is agreeing to have their phone do work on strangers' behalf,+ * so what it actually does should stay readable, not be buried in a consent they clicked once.+ */+@Composable+private fun CrowdFindingRow(enabled: Boolean, onChange: (Boolean) -> Unit) {+ val context = LocalContext.current+ val messenger = rememberMessenger()+ // BLUETOOTH_SCAN is a runtime permission, and without it the scanner silently starts and+ // immediately closes. Ask at the moment the user opts in, so a denial can be explained here+ // rather than leaving a switch that is on but doing nothing.+ val requestScan = rememberPermissionRequest(Manifest.permission.BLUETOOTH_SCAN) { granted ->+ if (granted) onChange(true)+ else messenger.show(context.getString(R.string.crowd_finding_needs_bluetooth))+ }+ Column(Modifier.fillMaxWidth().padding(horizontal = 4.dp)) {+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+ Text(+ stringResource(R.string.crowd_finding_title),+ Modifier.weight(1f),+ style = MaterialTheme.typography.bodyMedium+ )+ Switch(enabled, { on -> if (on) requestScan() else onChange(false) })+ }+ Text(+ stringResource(R.string.crowd_finding_explanation),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ ) } } @@ -927,22 +976,38 @@ fun UserCard(user: User, locationValue: LocationValue?, showSupportingContent: B }, supportingContent = { if (showSupportingContent) {+ // A network sighting is not a fix: it is where some other phone happened to+ // be standing when it heard this device. Saying "Updated 5 minutes ago at+ // Home" would imply a precision and a freshness that isn't there, so it gets+ // its own deliberately vaguer wording. Text(- stringResource(- R.string.user_card_status,- lastUpdatedTime,- user.locationName,- sinceString- )+ if (locationValue?.source == LocationSource.NETWORK_SIGHTING) {+ stringResource(+ R.string.user_card_network_sighting,+ lastUpdatedTime,+ user.locationName+ )+ } else {+ stringResource(+ R.string.user_card_status,+ lastUpdatedTime,+ user.locationName,+ sinceString+ )+ } ) } }, trailingContent = { if (showSupportingContent) { Column(horizontalAlignment = Alignment.End) {- Text(speedString, style = MaterialTheme.typography.labelMedium)- Spacer(Modifier.height(2.dp))- locationValue?.battery?.let { BatteryBar(it) }+ // Speed and battery come from the device itself. A network sighting has+ // neither — the numbers would be the finder's, so show nothing.+ if (locationValue?.source != LocationSource.NETWORK_SIGHTING) {+ Text(speedString, style = MaterialTheme.typography.labelMedium)+ Spacer(Modifier.height(2.dp))+ locationValue?.battery?.let { BatteryBar(it) }+ } } } }
findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffFindingSetting.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffFindingSetting.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffFindingSetting.ktnew file mode 100644index 0000000000..849b014263--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PoweredOffFindingSetting.kt@@ -0,0 +1,102 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import andr
Diff truncated.