PeachSyncService.kt

13.7 KB · raw

1package com.peachpasswords.sync23import android.app.Notification4import android.app.NotificationChannel5import android.app.NotificationManager6import android.app.PendingIntent7import android.app.Service8import android.content.BroadcastReceiver9import android.content.Context10import android.content.Intent11import android.os.Build12import android.os.IBinder13import androidx.core.app.NotificationCompat14import com.peachpasswords.MainActivity15import com.peachpasswords.R16import dagger.hilt.EntryPoint17import dagger.hilt.InstallIn18import dagger.hilt.android.AndroidEntryPoint19import dagger.hilt.android.EntryPointAccessors20import dagger.hilt.components.SingletonComponent21import com.peachpasswords.vault.VaultCrypto22import com.peachpasswords.vault.VaultRepository23import kotlinx.coroutines.CancellationException24import kotlinx.coroutines.CoroutineScope25import kotlinx.coroutines.SupervisorJob26import kotlinx.coroutines.cancel27import kotlinx.coroutines.launch28import java.security.MessageDigest29import javax.inject.Inject3031/**32 * Keeps this device reachable on its deterministic relay waiter edges and33 * drives its dialer edges. Every supported client now uses the same public-key34 * role ordering, but Android still needs a foreground service: Doze and App35 * Standby will take an ordinary background socket away.36 *37 * The notification is deliberately plain about what it is. A persistent38 * notification the user does not understand gets the app force-stopped.39 */40@AndroidEntryPoint41class PeachSyncService : Service() {4243    @Inject lateinit var cloudRelayListener: CloudRelayReconnectListener44    @Inject lateinit var vault: VaultRepository45    @Inject lateinit var deviceStore: PairedDeviceStore46    @Inject lateinit var pendingVouchedStore: PendingVouchedDeviceStore47    @Inject lateinit var syncAlertStore: SyncAlertStore48    @Inject lateinit var syncOutcomes: SyncOutcomeStore49    @Inject lateinit var lockedSyncSpool: LockedSyncSpoolStore50    @Inject lateinit var syncGeneration: SyncGenerationStore5152    private val scope = CoroutineScope(SupervisorJob())5354    override fun onBind(intent: Intent?): IBinder? = null5556    /**57     * The reported reason when this device must not sync, or null when it may.58     * §11.3: RESET_REQUIRED and RESET_CONFIRMED block every session.59     */60    private fun syncRefusal(): SyncOutcomeSummary? =61        syncRefusalReason(syncGeneration, System.currentTimeMillis())62            ?.let { SyncOutcomeSummary(reason = it) }6364    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {65        // A decoy unlock has no sync identity. Stop before foreground promotion66        // so it cannot expose a notification or drain the locked spool.67        if (vault.isUnlocked.value && vault.syncVaultId() == null) {68            stopSelf()69            return START_NOT_STICKY70        }71        // The same restriction that can refuse [start] applies again here, and72        // a START_STICKY restart is exactly when it bites: the system brings us73        // back while the app is in the background. A service that stays up74        // without its notification is killed a second later by a different75        // exception, so stop deliberately and leave the reported reason76        // standing rather than come back to be refused every time.77        if (!startOrReportBlocked(syncOutcomes::report) {78                startForeground(SYNC_NOTIFICATION_ID, buildSyncNotification(this))79            }80        ) {81            stopSelf()82            return START_NOT_STICKY83        }84        if (vault.isUnlocked.value) {85            scope.launch { runCatching { lockedSyncSpool.drainInto(vault) } }86        }87        val listenerStarted = startReconnectListener()88        // A start command means something changed — a new pairing, a manual89        // "sync now", the app coming forward. Re-read the device list now90        // rather than on the next interval; the listener is already running91        // on every start but the first.92        // Replace existing waiters as well as re-reading the device list. A93        // locally active coroutine does not prove its idle WebSocket still94        // routes through the relay, and "sync now" must recover that state.95        cloudRelayListener.requestReconcile(96            refreshExisting = shouldRefreshExistingWaiters(listenerStarted),97        )98        // START_STICKY: if the system reclaims us under pressure, come back —99        // a listener that silently stays down looks identical to a peer that100        // has simply gone offline, and the user gets no signal either way.101        return START_STICKY102    }103104    override fun onDestroy() {105        cloudRelayListener.stop()106        scope.cancel()107        super.onDestroy()108    }109110    /** Uses the Keystore-wrapped transport identity after full lock. */111    private fun startReconnectListener(): Boolean {112        val master = vault.syncMasterKey()113        var credentials: ReconnectListenerCredentials? = null114        return try {115            credentials = if (master != null) {116                lockedSyncSpool.refresh(vault)117                deriveUnlockedListenerCredentials(118                    credentials = loadOrCreateLocalIdentity(this),119                    deviceName = getDeviceName(this),120                    relayUrl = RelaySettingsStore.readRelayUrl(this),121                )122            } else {123                lockedSyncSpool.identity()?.let { ReconnectListenerCredentials(it.first, it.second) }124                    ?: return false125            }126            cloudRelayListener.start(127                scope,128                credentials.keys.secretKey,129                credentials.keys.publicKey,130                credentials.identity,131            ) {132                // A decoy session can replace a real unlock while an existing133                // relay callback is still being scheduled. Cancel that callback134                // without reporting a misleading locked-vault outcome.135                when {136                    vault.syncVaultId() == null -> throw CancellationException("decoy session")137                    // §11: a device waiting on, or part-way through, its reset opens138                    // no session at all — neither unlocked nor through the locked139                    // spool, whose staged ciphertext belongs to the retired140                    // generation and must not be applied.141                    else -> syncRefusal()?.let { refusal ->142                        syncOutcomes.report(refusal)143                        null144                    } ?: if (!vault.isUnlocked.value) {145                        lockedSyncSpool.adapter()146                    } else {147                        val credentials = loadOrCreateLocalIdentity(this)148                        VaultSyncAdapter(149                            repo = vault,150                            ourDeviceId = credentials.deviceId,151                            pairedDevices = deviceStore,152                            pendingVouched = pendingVouchedStore,153                            syncAlerts = syncAlertStore,154                            localCredentials = credentials,155                        )156                    }157                }158            }159        } finally {160            master?.let(VaultCrypto::zero)161            credentials?.keys?.secretKey?.let(VaultCrypto::zero)162        }163    }164165    companion object {166        fun start(context: Context) {167            val intent = Intent(context, PeachSyncService::class.java)168            startOrReportBlocked({ context.reportSyncOutcome(it) }) {169                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {170                    context.startForegroundService(intent)171                } else {172                    context.startService(intent)173                }174            }175        }176177        fun stop(context: Context) {178            context.stopService(Intent(context, PeachSyncService::class.java))179        }180    }181}182183internal data class ReconnectListenerCredentials(184    val keys: SyncIdentityKeypair,185    val identity: LocalDeviceIdentity,186)187188internal fun deriveUnlockedListenerCredentials(189    credentials: LocalIdentityCredentials,190    deviceName: String,191    relayUrl: String = Rendezvous.DEFAULT_RELAY_URL,192): ReconnectListenerCredentials {193    val keys = localSyncKeypair(credentials)194    val identity = LocalDeviceIdentity(195        deviceId = credentials.deviceId,196        deviceName = deviceName,197        deviceType = DeviceType.ANDROID,198        longTermPublicKeyHex = pubkeyToHex(keys.publicKey),199        signingPublicKeyHex = pubkeyToHex(credentials.ed25519PublicKey),200        relayUrl = relayUrl,201    )202    return ReconnectListenerCredentials(keys, identity)203}204205internal fun shouldRefreshExistingWaiters(listenerStarted: Boolean): Boolean = !listenerStarted206207internal const val SYNC_NOTIFICATION_CHANNEL_ID = "peach_sync"208internal const val SYNC_NOTIFICATION_ID = 4201209internal const val ACTION_RESTORE_SYNC_NOTIFICATION =210    "com.peachpasswords.action.RESTORE_SYNC_NOTIFICATION"211212internal fun buildSyncNotification(context: Context): Notification {213    val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager214    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {215        manager.createNotificationChannel(216            NotificationChannel(217                SYNC_NOTIFICATION_CHANNEL_ID,218                "Peach sync",219                NotificationManager.IMPORTANCE_LOW,220            ).apply {221                description = "Shown while Peach is reachable for encrypted device sync."222                setShowBadge(false)223            },224        )225    }226    val open = PendingIntent.getActivity(227        context,228        0,229        Intent(context, MainActivity::class.java),230        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,231    )232    val restore = PendingIntent.getBroadcast(233        context,234        0,235        Intent(context, SyncNotificationDismissedReceiver::class.java)236            .setAction(ACTION_RESTORE_SYNC_NOTIFICATION),237        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,238    )239    return NotificationCompat.Builder(context, SYNC_NOTIFICATION_CHANNEL_ID)240        .setContentTitle("Peach sync is active")241        .setContentText("Your other devices can reach this phone for encrypted sync.")242        .setSmallIcon(R.drawable.ic_launcher_monochrome)243        .setOngoing(true)244        .setPriority(NotificationCompat.PRIORITY_LOW)245        .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)246        .setContentIntent(open)247        .setDeleteIntent(restore)248        .build()249        .also {250            // FLAG_NO_CLEAR protects Clear all. Android 14 deliberately allows251            // users to swipe ongoing notifications individually, so the252            // deleteIntent above restores this status surface while the user253            // preference still says background sync is active.254            it.flags = it.flags or Notification.FLAG_ONGOING_EVENT or Notification.FLAG_NO_CLEAR255        }256}257258internal fun shouldRestoreSyncNotification(action: String?, backgroundSyncEnabled: Boolean): Boolean =259    action == ACTION_RESTORE_SYNC_NOTIFICATION && backgroundSyncEnabled260261/**262 * Android 14 permits an ongoing foreground-service notification to be swiped263 * away while its service keeps running. Peach's notification is the only264 * visible indication that the phone remains reachable, so restore it after a265 * user dismissal whenever background sync is still enabled.266 */267class SyncNotificationDismissedReceiver : BroadcastReceiver() {268    override fun onReceive(context: Context, intent: Intent?) {269        if (!shouldRestoreSyncNotification(270                intent?.action,271                BackgroundSyncPreference.isEnabled(context),272            )273        ) {274            return275        }276        val manager =277            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager278        manager.notify(SYNC_NOTIFICATION_ID, buildSyncNotification(context))279    }280}281282/**283 * Every sync path asks for this service first, so a throw here is a sync that284 * never happened — and it used to take the caller with it: a crash from the285 * pairing and unlock screens, nothing at all from the fire-and-forget286 * coroutines. Returns false when the start was refused, having said why.287 *288 * [IllegalStateException] rather than API 31's289 * `ForegroundServiceStartNotAllowedException` is deliberate: that class is a290 * subclass of this one and does not exist on this app's minSdk, and 26..30291 * throws the plain one for the same background start. Catching the supertype292 * covers both without an SDK_INT guard around a class that may not be there.293 */294internal fun startOrReportBlocked(295    report: (SyncOutcomeSummary) -> Unit,296    start: () -> Unit,297): Boolean = try {298    start()299    true300} catch (blocked: IllegalStateException) {301    report(302        SyncOutcomeSummary(303            reason = SyncOutcomeReason.FOREGROUND_START_BLOCKED,304            detail = blocked.message,305        ),306    )307    false308} catch (error: Exception) {309    // Nothing about asking for a service is worth crashing the app over; the310    // reason is the only part of this a person can act on.311    report(SyncOutcomeSummary(reason = SyncOutcomeReason.RUN_FAILED, detail = error.message))312    false313}314315/**316 * [PeachSyncService.start] is called from five screens and coordinators that317 * hold no injector of their own, so the store is fetched here rather than318 * threaded through every one of them. Wrapped because a store that cannot even319 * be opened must not become the crash the guard above exists to prevent.320 */321private fun Context.reportSyncOutcome(summary: SyncOutcomeSummary) {322    runCatching {323        EntryPointAccessors324            .fromApplication(applicationContext, SyncOutcomeEntryPoint::class.java)325            .syncOutcomes()326            .report(summary)327    }328}329330@EntryPoint331@InstallIn(SingletonComponent::class)332internal interface SyncOutcomeEntryPoint {333    fun syncOutcomes(): SyncOutcomeStore334}