PeachSyncService.kt

12.9 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: LockedSyncSpoolStore5051    private val scope = CoroutineScope(SupervisorJob())5253    override fun onBind(intent: Intent?): IBinder? = null5455    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {56        // A decoy unlock has no sync identity. Stop before foreground promotion57        // so it cannot expose a notification or drain the locked spool.58        if (vault.isUnlocked.value && vault.syncVaultId() == null) {59            stopSelf()60            return START_NOT_STICKY61        }62        // The same restriction that can refuse [start] applies again here, and63        // a START_STICKY restart is exactly when it bites: the system brings us64        // back while the app is in the background. A service that stays up65        // without its notification is killed a second later by a different66        // exception, so stop deliberately and leave the reported reason67        // standing rather than come back to be refused every time.68        if (!startOrReportBlocked(syncOutcomes::report) {69                startForeground(SYNC_NOTIFICATION_ID, buildSyncNotification(this))70            }71        ) {72            stopSelf()73            return START_NOT_STICKY74        }75        if (vault.isUnlocked.value) {76            scope.launch { runCatching { lockedSyncSpool.drainInto(vault) } }77        }78        val listenerStarted = startReconnectListener()79        // A start command means something changed — a new pairing, a manual80        // "sync now", the app coming forward. Re-read the device list now81        // rather than on the next interval; the listener is already running82        // on every start but the first.83        // Replace existing waiters as well as re-reading the device list. A84        // locally active coroutine does not prove its idle WebSocket still85        // routes through the relay, and "sync now" must recover that state.86        cloudRelayListener.requestReconcile(87            refreshExisting = shouldRefreshExistingWaiters(listenerStarted),88        )89        // START_STICKY: if the system reclaims us under pressure, come back —90        // a listener that silently stays down looks identical to a peer that91        // has simply gone offline, and the user gets no signal either way.92        return START_STICKY93    }9495    override fun onDestroy() {96        cloudRelayListener.stop()97        scope.cancel()98        super.onDestroy()99    }100101    /** Uses the Keystore-wrapped transport identity after full lock. */102    private fun startReconnectListener(): Boolean {103        val master = vault.syncMasterKey()104        var credentials: ReconnectListenerCredentials? = null105        return try {106            credentials = if (master != null) {107                lockedSyncSpool.refresh(vault)108                deriveUnlockedListenerCredentials(109                    masterKey = master,110                    deviceId = getOrCreateDeviceId(this),111                    deviceName = getDeviceName(this),112                    relayUrl = RelaySettingsStore.readRelayUrl(this),113                )114            } else {115                lockedSyncSpool.identity()?.let { ReconnectListenerCredentials(it.first, it.second) }116                    ?: return false117            }118            cloudRelayListener.start(119                scope,120                credentials.keys.secretKey,121                credentials.keys.publicKey,122                credentials.identity,123            ) {124                // A decoy session can replace a real unlock while an existing125                // relay callback is still being scheduled. Cancel that callback126                // without reporting a misleading locked-vault outcome.127                when {128                    vault.syncVaultId() == null -> throw CancellationException("decoy session")129                    !vault.isUnlocked.value -> lockedSyncSpool.adapter()130                    else -> VaultSyncAdapter(131                        repo = vault,132                        ourDeviceId = getOrCreateDeviceId(this),133                        pairedDevices = deviceStore,134                        pendingVouched = pendingVouchedStore,135                        syncAlerts = syncAlertStore,136                    )137                }138            }139        } finally {140            master?.let(VaultCrypto::zero)141            credentials?.keys?.secretKey?.let(VaultCrypto::zero)142        }143    }144145    companion object {146        fun start(context: Context) {147            val intent = Intent(context, PeachSyncService::class.java)148            startOrReportBlocked({ context.reportSyncOutcome(it) }) {149                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {150                    context.startForegroundService(intent)151                } else {152                    context.startService(intent)153                }154            }155        }156157        fun stop(context: Context) {158            context.stopService(Intent(context, PeachSyncService::class.java))159        }160    }161}162163internal data class ReconnectListenerCredentials(164    val keys: SyncIdentityKeypair,165    val identity: LocalDeviceIdentity,166)167168internal fun deriveUnlockedListenerCredentials(169    masterKey: ByteArray,170    deviceId: String,171    deviceName: String,172    relayUrl: String = Rendezvous.DEFAULT_RELAY_URL,173): ReconnectListenerCredentials {174    val keys = deriveLocalSyncKeypair(masterKey, deviceId)175    val signing = deriveSyncSigningKeypair(masterKey, deviceId)176    val identity = LocalDeviceIdentity(177        deviceId = deviceId,178        deviceName = deviceName,179        deviceType = DeviceType.ANDROID,180        longTermPublicKeyHex = pubkeyToHex(keys.publicKey),181        signingPublicKeyHex = pubkeyToHex(signing.publicKeyRaw),182        relayUrl = relayUrl,183    )184    if (!MessageDigest.isEqual(keys.publicKey, hexToPubkey(identity.longTermPublicKeyHex))) {185        VaultCrypto.zero(keys.secretKey)186        throw IllegalStateException("derived reconnect identity mismatch")187    }188    return ReconnectListenerCredentials(keys, identity)189}190191internal fun shouldRefreshExistingWaiters(listenerStarted: Boolean): Boolean = !listenerStarted192193internal const val SYNC_NOTIFICATION_CHANNEL_ID = "peach_sync"194internal const val SYNC_NOTIFICATION_ID = 4201195internal const val ACTION_RESTORE_SYNC_NOTIFICATION =196    "com.peachpasswords.action.RESTORE_SYNC_NOTIFICATION"197198internal fun buildSyncNotification(context: Context): Notification {199    val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager200    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {201        manager.createNotificationChannel(202            NotificationChannel(203                SYNC_NOTIFICATION_CHANNEL_ID,204                "Peach sync",205                NotificationManager.IMPORTANCE_LOW,206            ).apply {207                description = "Shown while Peach is reachable for encrypted device sync."208                setShowBadge(false)209            },210        )211    }212    val open = PendingIntent.getActivity(213        context,214        0,215        Intent(context, MainActivity::class.java),216        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,217    )218    val restore = PendingIntent.getBroadcast(219        context,220        0,221        Intent(context, SyncNotificationDismissedReceiver::class.java)222            .setAction(ACTION_RESTORE_SYNC_NOTIFICATION),223        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,224    )225    return NotificationCompat.Builder(context, SYNC_NOTIFICATION_CHANNEL_ID)226        .setContentTitle("Peach sync is active")227        .setContentText("Your other devices can reach this phone for encrypted sync.")228        .setSmallIcon(R.drawable.ic_launcher_monochrome)229        .setOngoing(true)230        .setPriority(NotificationCompat.PRIORITY_LOW)231        .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)232        .setContentIntent(open)233        .setDeleteIntent(restore)234        .build()235        .also {236            // FLAG_NO_CLEAR protects Clear all. Android 14 deliberately allows237            // users to swipe ongoing notifications individually, so the238            // deleteIntent above restores this status surface while the user239            // preference still says background sync is active.240            it.flags = it.flags or Notification.FLAG_ONGOING_EVENT or Notification.FLAG_NO_CLEAR241        }242}243244internal fun shouldRestoreSyncNotification(action: String?, backgroundSyncEnabled: Boolean): Boolean =245    action == ACTION_RESTORE_SYNC_NOTIFICATION && backgroundSyncEnabled246247/**248 * Android 14 permits an ongoing foreground-service notification to be swiped249 * away while its service keeps running. Peach's notification is the only250 * visible indication that the phone remains reachable, so restore it after a251 * user dismissal whenever background sync is still enabled.252 */253class SyncNotificationDismissedReceiver : BroadcastReceiver() {254    override fun onReceive(context: Context, intent: Intent?) {255        if (!shouldRestoreSyncNotification(256                intent?.action,257                BackgroundSyncPreference.isEnabled(context),258            )259        ) {260            return261        }262        val manager =263            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager264        manager.notify(SYNC_NOTIFICATION_ID, buildSyncNotification(context))265    }266}267268/**269 * Every sync path asks for this service first, so a throw here is a sync that270 * never happened — and it used to take the caller with it: a crash from the271 * pairing and unlock screens, nothing at all from the fire-and-forget272 * coroutines. Returns false when the start was refused, having said why.273 *274 * [IllegalStateException] rather than API 31's275 * `ForegroundServiceStartNotAllowedException` is deliberate: that class is a276 * subclass of this one and does not exist on this app's minSdk, and 26..30277 * throws the plain one for the same background start. Catching the supertype278 * covers both without an SDK_INT guard around a class that may not be there.279 */280internal fun startOrReportBlocked(281    report: (SyncOutcomeSummary) -> Unit,282    start: () -> Unit,283): Boolean = try {284    start()285    true286} catch (blocked: IllegalStateException) {287    report(288        SyncOutcomeSummary(289            reason = SyncOutcomeReason.FOREGROUND_START_BLOCKED,290            detail = blocked.message,291        ),292    )293    false294} catch (error: Exception) {295    // Nothing about asking for a service is worth crashing the app over; the296    // reason is the only part of this a person can act on.297    report(SyncOutcomeSummary(reason = SyncOutcomeReason.RUN_FAILED, detail = error.message))298    false299}300301/**302 * [PeachSyncService.start] is called from five screens and coordinators that303 * hold no injector of their own, so the store is fetched here rather than304 * threaded through every one of them. Wrapped because a store that cannot even305 * be opened must not become the crash the guard above exists to prevent.306 */307private fun Context.reportSyncOutcome(summary: SyncOutcomeSummary) {308    runCatching {309        EntryPointAccessors310            .fromApplication(applicationContext, SyncOutcomeEntryPoint::class.java)311            .syncOutcomes()312            .report(summary)313    }314}315316@EntryPoint317@InstallIn(SingletonComponent::class)318internal interface SyncOutcomeEntryPoint {319    fun syncOutcomes(): SyncOutcomeStore320}