PeachSyncService.kt

12.8 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                    credentials = loadOrCreateLocalIdentity(this),110                    deviceName = getDeviceName(this),111                    relayUrl = RelaySettingsStore.readRelayUrl(this),112                )113            } else {114                lockedSyncSpool.identity()?.let { ReconnectListenerCredentials(it.first, it.second) }115                    ?: return false116            }117            cloudRelayListener.start(118                scope,119                credentials.keys.secretKey,120                credentials.keys.publicKey,121                credentials.identity,122            ) {123                // A decoy session can replace a real unlock while an existing124                // relay callback is still being scheduled. Cancel that callback125                // without reporting a misleading locked-vault outcome.126                when {127                    vault.syncVaultId() == null -> throw CancellationException("decoy session")128                    !vault.isUnlocked.value -> lockedSyncSpool.adapter()129                    else -> {130                        val credentials = loadOrCreateLocalIdentity(this)131                        VaultSyncAdapter(132                            repo = vault,133                            ourDeviceId = credentials.deviceId,134                            pairedDevices = deviceStore,135                            pendingVouched = pendingVouchedStore,136                            syncAlerts = syncAlertStore,137                            localCredentials = credentials,138                        )139                    }140            }141            }142        } finally {143            master?.let(VaultCrypto::zero)144            credentials?.keys?.secretKey?.let(VaultCrypto::zero)145        }146    }147148    companion object {149        fun start(context: Context) {150            val intent = Intent(context, PeachSyncService::class.java)151            startOrReportBlocked({ context.reportSyncOutcome(it) }) {152                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {153                    context.startForegroundService(intent)154                } else {155                    context.startService(intent)156                }157            }158        }159160        fun stop(context: Context) {161            context.stopService(Intent(context, PeachSyncService::class.java))162        }163    }164}165166internal data class ReconnectListenerCredentials(167    val keys: SyncIdentityKeypair,168    val identity: LocalDeviceIdentity,169)170171internal fun deriveUnlockedListenerCredentials(172    credentials: LocalIdentityCredentials,173    deviceName: String,174    relayUrl: String = Rendezvous.DEFAULT_RELAY_URL,175): ReconnectListenerCredentials {176    val keys = localSyncKeypair(credentials)177    val identity = LocalDeviceIdentity(178        deviceId = credentials.deviceId,179        deviceName = deviceName,180        deviceType = DeviceType.ANDROID,181        longTermPublicKeyHex = pubkeyToHex(keys.publicKey),182        signingPublicKeyHex = pubkeyToHex(credentials.ed25519PublicKey),183        relayUrl = relayUrl,184    )185    return ReconnectListenerCredentials(keys, identity)186}187188internal fun shouldRefreshExistingWaiters(listenerStarted: Boolean): Boolean = !listenerStarted189190internal const val SYNC_NOTIFICATION_CHANNEL_ID = "peach_sync"191internal const val SYNC_NOTIFICATION_ID = 4201192internal const val ACTION_RESTORE_SYNC_NOTIFICATION =193    "com.peachpasswords.action.RESTORE_SYNC_NOTIFICATION"194195internal fun buildSyncNotification(context: Context): Notification {196    val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager197    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {198        manager.createNotificationChannel(199            NotificationChannel(200                SYNC_NOTIFICATION_CHANNEL_ID,201                "Peach sync",202                NotificationManager.IMPORTANCE_LOW,203            ).apply {204                description = "Shown while Peach is reachable for encrypted device sync."205                setShowBadge(false)206            },207        )208    }209    val open = PendingIntent.getActivity(210        context,211        0,212        Intent(context, MainActivity::class.java),213        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,214    )215    val restore = PendingIntent.getBroadcast(216        context,217        0,218        Intent(context, SyncNotificationDismissedReceiver::class.java)219            .setAction(ACTION_RESTORE_SYNC_NOTIFICATION),220        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,221    )222    return NotificationCompat.Builder(context, SYNC_NOTIFICATION_CHANNEL_ID)223        .setContentTitle("Peach sync is active")224        .setContentText("Your other devices can reach this phone for encrypted sync.")225        .setSmallIcon(R.drawable.ic_launcher_monochrome)226        .setOngoing(true)227        .setPriority(NotificationCompat.PRIORITY_LOW)228        .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)229        .setContentIntent(open)230        .setDeleteIntent(restore)231        .build()232        .also {233            // FLAG_NO_CLEAR protects Clear all. Android 14 deliberately allows234            // users to swipe ongoing notifications individually, so the235            // deleteIntent above restores this status surface while the user236            // preference still says background sync is active.237            it.flags = it.flags or Notification.FLAG_ONGOING_EVENT or Notification.FLAG_NO_CLEAR238        }239}240241internal fun shouldRestoreSyncNotification(action: String?, backgroundSyncEnabled: Boolean): Boolean =242    action == ACTION_RESTORE_SYNC_NOTIFICATION && backgroundSyncEnabled243244/**245 * Android 14 permits an ongoing foreground-service notification to be swiped246 * away while its service keeps running. Peach's notification is the only247 * visible indication that the phone remains reachable, so restore it after a248 * user dismissal whenever background sync is still enabled.249 */250class SyncNotificationDismissedReceiver : BroadcastReceiver() {251    override fun onReceive(context: Context, intent: Intent?) {252        if (!shouldRestoreSyncNotification(253                intent?.action,254                BackgroundSyncPreference.isEnabled(context),255            )256        ) {257            return258        }259        val manager =260            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager261        manager.notify(SYNC_NOTIFICATION_ID, buildSyncNotification(context))262    }263}264265/**266 * Every sync path asks for this service first, so a throw here is a sync that267 * never happened — and it used to take the caller with it: a crash from the268 * pairing and unlock screens, nothing at all from the fire-and-forget269 * coroutines. Returns false when the start was refused, having said why.270 *271 * [IllegalStateException] rather than API 31's272 * `ForegroundServiceStartNotAllowedException` is deliberate: that class is a273 * subclass of this one and does not exist on this app's minSdk, and 26..30274 * throws the plain one for the same background start. Catching the supertype275 * covers both without an SDK_INT guard around a class that may not be there.276 */277internal fun startOrReportBlocked(278    report: (SyncOutcomeSummary) -> Unit,279    start: () -> Unit,280): Boolean = try {281    start()282    true283} catch (blocked: IllegalStateException) {284    report(285        SyncOutcomeSummary(286            reason = SyncOutcomeReason.FOREGROUND_START_BLOCKED,287            detail = blocked.message,288        ),289    )290    false291} catch (error: Exception) {292    // Nothing about asking for a service is worth crashing the app over; the293    // reason is the only part of this a person can act on.294    report(SyncOutcomeSummary(reason = SyncOutcomeReason.RUN_FAILED, detail = error.message))295    false296}297298/**299 * [PeachSyncService.start] is called from five screens and coordinators that300 * hold no injector of their own, so the store is fetched here rather than301 * threaded through every one of them. Wrapped because a store that cannot even302 * be opened must not become the crash the guard above exists to prevent.303 */304private fun Context.reportSyncOutcome(summary: SyncOutcomeSummary) {305    runCatching {306        EntryPointAccessors307            .fromApplication(applicationContext, SyncOutcomeEntryPoint::class.java)308            .syncOutcomes()309            .report(summary)310    }311}312313@EntryPoint314@InstallIn(SingletonComponent::class)315internal interface SyncOutcomeEntryPoint {316    fun syncOutcomes(): SyncOutcomeStore317}