PeachSyncService.kt

12.2 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.CoroutineScope24import kotlinx.coroutines.SupervisorJob25import kotlinx.coroutines.cancel26import kotlinx.coroutines.launch27import java.security.MessageDigest28import javax.inject.Inject2930/**31 * Keeps this device reachable on its deterministic relay waiter edges and32 * drives its dialer edges. Every supported client now uses the same public-key33 * role ordering, but Android still needs a foreground service: Doze and App34 * Standby will take an ordinary background socket away.35 *36 * The notification is deliberately plain about what it is. A persistent37 * notification the user does not understand gets the app force-stopped.38 */39@AndroidEntryPoint40class PeachSyncService : Service() {4142    @Inject lateinit var cloudRelayListener: CloudRelayReconnectListener43    @Inject lateinit var vault: VaultRepository44    @Inject lateinit var deviceStore: PairedDeviceStore45    @Inject lateinit var pendingVouchedStore: PendingVouchedDeviceStore46    @Inject lateinit var syncAlertStore: SyncAlertStore47    @Inject lateinit var syncOutcomes: SyncOutcomeStore48    @Inject lateinit var lockedSyncSpool: LockedSyncSpoolStore4950    private val scope = CoroutineScope(SupervisorJob())5152    override fun onBind(intent: Intent?): IBinder? = null5354    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {55        // The same restriction that can refuse [start] applies again here, and56        // a START_STICKY restart is exactly when it bites: the system brings us57        // back while the app is in the background. A service that stays up58        // without its notification is killed a second later by a different59        // exception, so stop deliberately and leave the reported reason60        // standing rather than come back to be refused every time.61        if (!startOrReportBlocked(syncOutcomes::report) {62                startForeground(SYNC_NOTIFICATION_ID, buildSyncNotification(this))63            }64        ) {65            stopSelf()66            return START_NOT_STICKY67        }68        if (vault.isUnlocked.value) {69            scope.launch { runCatching { lockedSyncSpool.drainInto(vault) } }70        }71        val listenerStarted = startReconnectListener()72        // A start command means something changed — a new pairing, a manual73        // "sync now", the app coming forward. Re-read the device list now74        // rather than on the next interval; the listener is already running75        // on every start but the first.76        // Replace existing waiters as well as re-reading the device list. A77        // locally active coroutine does not prove its idle WebSocket still78        // routes through the relay, and "sync now" must recover that state.79        cloudRelayListener.requestReconcile(80            refreshExisting = shouldRefreshExistingWaiters(listenerStarted),81        )82        // START_STICKY: if the system reclaims us under pressure, come back —83        // a listener that silently stays down looks identical to a peer that84        // has simply gone offline, and the user gets no signal either way.85        return START_STICKY86    }8788    override fun onDestroy() {89        cloudRelayListener.stop()90        scope.cancel()91        super.onDestroy()92    }9394    /** Uses the Keystore-wrapped transport identity after full lock. */95    private fun startReconnectListener(): Boolean {96        val master = vault.syncMasterKey()97        var credentials: ReconnectListenerCredentials? = null98        return try {99            credentials = if (master != null) {100                lockedSyncSpool.refresh(vault)101                deriveUnlockedListenerCredentials(102                    masterKey = master,103                    deviceId = getOrCreateDeviceId(this),104                    deviceName = getDeviceName(this),105                    relayUrl = RelaySettingsStore.readRelayUrl(this),106                )107            } else {108                lockedSyncSpool.identity()?.let { ReconnectListenerCredentials(it.first, it.second) }109                    ?: return false110            }111            cloudRelayListener.start(112                scope,113                credentials.keys.secretKey,114                credentials.keys.publicKey,115                credentials.identity,116            ) {117                if (!vault.isUnlocked.value) lockedSyncSpool.adapter() else VaultSyncAdapter(118                    repo = vault,119                    ourDeviceId = getOrCreateDeviceId(this),120                    pairedDevices = deviceStore,121                    pendingVouched = pendingVouchedStore,122                    syncAlerts = syncAlertStore,123                )124            }125        } finally {126            master?.let(VaultCrypto::zero)127            credentials?.keys?.secretKey?.let(VaultCrypto::zero)128        }129    }130131    companion object {132        fun start(context: Context) {133            val intent = Intent(context, PeachSyncService::class.java)134            startOrReportBlocked({ context.reportSyncOutcome(it) }) {135                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {136                    context.startForegroundService(intent)137                } else {138                    context.startService(intent)139                }140            }141        }142143        fun stop(context: Context) {144            context.stopService(Intent(context, PeachSyncService::class.java))145        }146    }147}148149internal data class ReconnectListenerCredentials(150    val keys: SyncIdentityKeypair,151    val identity: LocalDeviceIdentity,152)153154internal fun deriveUnlockedListenerCredentials(155    masterKey: ByteArray,156    deviceId: String,157    deviceName: String,158    relayUrl: String = Rendezvous.DEFAULT_RELAY_URL,159): ReconnectListenerCredentials {160    val keys = deriveLocalSyncKeypair(masterKey, deviceId)161    val signing = deriveSyncSigningKeypair(masterKey, deviceId)162    val identity = LocalDeviceIdentity(163        deviceId = deviceId,164        deviceName = deviceName,165        deviceType = DeviceType.ANDROID,166        longTermPublicKeyHex = pubkeyToHex(keys.publicKey),167        signingPublicKeyHex = pubkeyToHex(signing.publicKeyRaw),168        relayUrl = relayUrl,169    )170    if (!MessageDigest.isEqual(keys.publicKey, hexToPubkey(identity.longTermPublicKeyHex))) {171        VaultCrypto.zero(keys.secretKey)172        throw IllegalStateException("derived reconnect identity mismatch")173    }174    return ReconnectListenerCredentials(keys, identity)175}176177internal fun shouldRefreshExistingWaiters(listenerStarted: Boolean): Boolean = !listenerStarted178179internal const val SYNC_NOTIFICATION_CHANNEL_ID = "peach_sync"180internal const val SYNC_NOTIFICATION_ID = 4201181internal const val ACTION_RESTORE_SYNC_NOTIFICATION =182    "com.peachpasswords.action.RESTORE_SYNC_NOTIFICATION"183184internal fun buildSyncNotification(context: Context): Notification {185    val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager186    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {187        manager.createNotificationChannel(188            NotificationChannel(189                SYNC_NOTIFICATION_CHANNEL_ID,190                "Peach sync",191                NotificationManager.IMPORTANCE_LOW,192            ).apply {193                description = "Shown while Peach is reachable for encrypted device sync."194                setShowBadge(false)195            },196        )197    }198    val open = PendingIntent.getActivity(199        context,200        0,201        Intent(context, MainActivity::class.java),202        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,203    )204    val restore = PendingIntent.getBroadcast(205        context,206        0,207        Intent(context, SyncNotificationDismissedReceiver::class.java)208            .setAction(ACTION_RESTORE_SYNC_NOTIFICATION),209        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,210    )211    return NotificationCompat.Builder(context, SYNC_NOTIFICATION_CHANNEL_ID)212        .setContentTitle("Peach sync is active")213        .setContentText("Your other devices can reach this phone for encrypted sync.")214        .setSmallIcon(R.drawable.ic_launcher_monochrome)215        .setOngoing(true)216        .setPriority(NotificationCompat.PRIORITY_LOW)217        .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)218        .setContentIntent(open)219        .setDeleteIntent(restore)220        .build()221        .also {222            // FLAG_NO_CLEAR protects Clear all. Android 14 deliberately allows223            // users to swipe ongoing notifications individually, so the224            // deleteIntent above restores this status surface while the user225            // preference still says background sync is active.226            it.flags = it.flags or Notification.FLAG_ONGOING_EVENT or Notification.FLAG_NO_CLEAR227        }228}229230internal fun shouldRestoreSyncNotification(action: String?, backgroundSyncEnabled: Boolean): Boolean =231    action == ACTION_RESTORE_SYNC_NOTIFICATION && backgroundSyncEnabled232233/**234 * Android 14 permits an ongoing foreground-service notification to be swiped235 * away while its service keeps running. Peach's notification is the only236 * visible indication that the phone remains reachable, so restore it after a237 * user dismissal whenever background sync is still enabled.238 */239class SyncNotificationDismissedReceiver : BroadcastReceiver() {240    override fun onReceive(context: Context, intent: Intent?) {241        if (!shouldRestoreSyncNotification(242                intent?.action,243                BackgroundSyncPreference.isEnabled(context),244            )245        ) {246            return247        }248        val manager =249            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager250        manager.notify(SYNC_NOTIFICATION_ID, buildSyncNotification(context))251    }252}253254/**255 * Every sync path asks for this service first, so a throw here is a sync that256 * never happened — and it used to take the caller with it: a crash from the257 * pairing and unlock screens, nothing at all from the fire-and-forget258 * coroutines. Returns false when the start was refused, having said why.259 *260 * [IllegalStateException] rather than API 31's261 * `ForegroundServiceStartNotAllowedException` is deliberate: that class is a262 * subclass of this one and does not exist on this app's minSdk, and 26..30263 * throws the plain one for the same background start. Catching the supertype264 * covers both without an SDK_INT guard around a class that may not be there.265 */266internal fun startOrReportBlocked(267    report: (SyncOutcomeSummary) -> Unit,268    start: () -> Unit,269): Boolean = try {270    start()271    true272} catch (blocked: IllegalStateException) {273    report(274        SyncOutcomeSummary(275            reason = SyncOutcomeReason.FOREGROUND_START_BLOCKED,276            detail = blocked.message,277        ),278    )279    false280} catch (error: Exception) {281    // Nothing about asking for a service is worth crashing the app over; the282    // reason is the only part of this a person can act on.283    report(SyncOutcomeSummary(reason = SyncOutcomeReason.RUN_FAILED, detail = error.message))284    false285}286287/**288 * [PeachSyncService.start] is called from five screens and coordinators that289 * hold no injector of their own, so the store is fetched here rather than290 * threaded through every one of them. Wrapped because a store that cannot even291 * be opened must not become the crash the guard above exists to prevent.292 */293private fun Context.reportSyncOutcome(summary: SyncOutcomeSummary) {294    runCatching {295        EntryPointAccessors296            .fromApplication(applicationContext, SyncOutcomeEntryPoint::class.java)297            .syncOutcomes()298            .report(summary)299    }300}301302@EntryPoint303@InstallIn(SingletonComponent::class)304internal interface SyncOutcomeEntryPoint {305    fun syncOutcomes(): SyncOutcomeStore306}