PeachSyncService.kt

11.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 javax.inject.Inject2728/**29 * Keeps this device reachable on the relay so an already-paired peer can30 * reconnect. A browser extension can never listen, so if the phone is not31 * registered the two devices simply never sync and neither shows an error —32 * "no connection" and "nothing to sync" look identical.33 *34 * A browser extension can never listen for a connection, so the phone has to be35 * the side that is dialable — and a phone that is only dialable while its app36 * is foregrounded is not dialable in any useful sense. Doze and App Standby37 * will take an ordinary background socket away. This is the same standard38 * pattern Syncthing and Tailscale use for exactly the same reason: a foreground39 * service with a visible, honest notification.40 *41 * The notification is deliberately plain about what it is. A persistent42 * notification the user does not understand gets the app force-stopped, which43 * is the one outcome that breaks sync entirely.44 */45@AndroidEntryPoint46class PeachSyncService : Service() {4748    @Inject lateinit var cloudRelayListener: CloudRelayReconnectListener49    @Inject lateinit var vault: VaultRepository50    @Inject lateinit var deviceStore: PairedDeviceStore51    @Inject lateinit var pendingVouchedStore: PendingVouchedDeviceStore52    @Inject lateinit var syncAlertStore: SyncAlertStore53    @Inject lateinit var syncOutcomes: SyncOutcomeStore5455    private val scope = CoroutineScope(SupervisorJob())5657    override fun onBind(intent: Intent?): IBinder? = null5859    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {60        // The same restriction that can refuse [start] applies again here, and61        // a START_STICKY restart is exactly when it bites: the system brings us62        // back while the app is in the background. A service that stays up63        // without its notification is killed a second later by a different64        // exception, so stop deliberately and leave the reported reason65        // standing rather than come back to be refused every time.66        if (!startOrReportBlocked(syncOutcomes::report) {67                startForeground(SYNC_NOTIFICATION_ID, buildSyncNotification(this))68            }69        ) {70            stopSelf()71            return START_NOT_STICKY72        }73        startReconnectListener()74        // A start command means something changed — a new pairing, a manual75        // "sync now", the app coming forward. Re-read the device list now76        // rather than on the next interval; the listener is already running77        // on every start but the first.78        // Replace existing waiters as well as re-reading the device list. A79        // locally active coroutine does not prove its idle WebSocket still80        // routes through the relay, and "sync now" must recover that state.81        cloudRelayListener.requestReconcile(refreshExisting = true)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    /**95     * Only possible while unlocked — the sync identity is derived from the96     * vault's root key, so a locked phone genuinely has nothing to listen with.97     * That is also why this is re-attempted on every start command rather than98     * once: the service may well come up before the user has unlocked.99     *100     * The early return is deliberately the one terminating path that reports no101     * outcome. Coming up locked is the normal boot order, not a failed sync;102     * reporting it would leave a red light waiting on the other side of the103     * unlock screen. The locked case a person can actually see is reported from104     * `SyncViewModel.syncNow`, and from a session that reaches a locked vault105     * mid-handshake.106     */107    private fun startReconnectListener() {108        val master = vault.syncMasterKey() ?: return109        try {110            val keys = deriveLocalSyncKeypair(master, getOrCreateDeviceId(this))111            val identity = buildLocalIdentity(this, master)112            cloudRelayListener.start(scope, keys.secretKey, keys.publicKey, identity) {113                if (!vault.isUnlocked.value) null else VaultSyncAdapter(114                    repo = vault,115                    ourDeviceId = getOrCreateDeviceId(this),116                    pairedDevices = deviceStore,117                    pendingVouched = pendingVouchedStore,118                    syncAlerts = syncAlertStore,119                )120            }121        } finally {122            VaultCrypto.zero(master)123        }124    }125126    companion object {127        fun start(context: Context) {128            val intent = Intent(context, PeachSyncService::class.java)129            startOrReportBlocked({ context.reportSyncOutcome(it) }) {130                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {131                    context.startForegroundService(intent)132                } else {133                    context.startService(intent)134                }135            }136        }137138        fun stop(context: Context) {139            context.stopService(Intent(context, PeachSyncService::class.java))140        }141    }142}143144internal const val SYNC_NOTIFICATION_CHANNEL_ID = "peach_sync"145internal const val SYNC_NOTIFICATION_ID = 4201146internal const val ACTION_RESTORE_SYNC_NOTIFICATION =147    "com.peachpasswords.action.RESTORE_SYNC_NOTIFICATION"148149internal fun buildSyncNotification(context: Context): Notification {150    val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager151    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {152        manager.createNotificationChannel(153            NotificationChannel(154                SYNC_NOTIFICATION_CHANNEL_ID,155                "Peach sync",156                NotificationManager.IMPORTANCE_LOW,157            ).apply {158                description = "Shown while Peach is reachable for encrypted device sync."159                setShowBadge(false)160            },161        )162    }163    val open = PendingIntent.getActivity(164        context,165        0,166        Intent(context, MainActivity::class.java),167        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,168    )169    val restore = PendingIntent.getBroadcast(170        context,171        0,172        Intent(context, SyncNotificationDismissedReceiver::class.java)173            .setAction(ACTION_RESTORE_SYNC_NOTIFICATION),174        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,175    )176    return NotificationCompat.Builder(context, SYNC_NOTIFICATION_CHANNEL_ID)177        .setContentTitle("Peach sync is active")178        .setContentText("Your other devices can reach this phone for encrypted sync.")179        .setSmallIcon(R.drawable.ic_launcher_monochrome)180        .setOngoing(true)181        .setPriority(NotificationCompat.PRIORITY_LOW)182        .setContentIntent(open)183        .setDeleteIntent(restore)184        .build()185        .also {186            // FLAG_NO_CLEAR protects Clear all. Android 14 deliberately allows187            // users to swipe ongoing notifications individually, so the188            // deleteIntent above restores this status surface while the user189            // preference still says background sync is active.190            it.flags = it.flags or Notification.FLAG_ONGOING_EVENT or Notification.FLAG_NO_CLEAR191        }192}193194internal fun shouldRestoreSyncNotification(action: String?, backgroundSyncEnabled: Boolean): Boolean =195    action == ACTION_RESTORE_SYNC_NOTIFICATION && backgroundSyncEnabled196197/**198 * Android 14 permits an ongoing foreground-service notification to be swiped199 * away while its service keeps running. Peach's notification is the only200 * visible indication that the phone remains reachable, so restore it after a201 * user dismissal whenever background sync is still enabled.202 */203class SyncNotificationDismissedReceiver : BroadcastReceiver() {204    override fun onReceive(context: Context, intent: Intent?) {205        if (!shouldRestoreSyncNotification(206                intent?.action,207                BackgroundSyncPreference.isEnabled(context),208            )209        ) {210            return211        }212        val manager =213            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager214        manager.notify(SYNC_NOTIFICATION_ID, buildSyncNotification(context))215    }216}217218/**219 * Every sync path asks for this service first, so a throw here is a sync that220 * never happened — and it used to take the caller with it: a crash from the221 * pairing and unlock screens, nothing at all from the fire-and-forget222 * coroutines. Returns false when the start was refused, having said why.223 *224 * [IllegalStateException] rather than API 31's225 * `ForegroundServiceStartNotAllowedException` is deliberate: that class is a226 * subclass of this one and does not exist on this app's minSdk, and 26..30227 * throws the plain one for the same background start. Catching the supertype228 * covers both without an SDK_INT guard around a class that may not be there.229 */230internal fun startOrReportBlocked(231    report: (SyncOutcomeSummary) -> Unit,232    start: () -> Unit,233): Boolean = try {234    start()235    true236} catch (blocked: IllegalStateException) {237    report(238        SyncOutcomeSummary(239            reason = SyncOutcomeReason.FOREGROUND_START_BLOCKED,240            detail = blocked.message,241        ),242    )243    false244} catch (error: Exception) {245    // Nothing about asking for a service is worth crashing the app over; the246    // reason is the only part of this a person can act on.247    report(SyncOutcomeSummary(reason = SyncOutcomeReason.RUN_FAILED, detail = error.message))248    false249}250251/**252 * [PeachSyncService.start] is called from five screens and coordinators that253 * hold no injector of their own, so the store is fetched here rather than254 * threaded through every one of them. Wrapped because a store that cannot even255 * be opened must not become the crash the guard above exists to prevent.256 */257private fun Context.reportSyncOutcome(summary: SyncOutcomeSummary) {258    runCatching {259        EntryPointAccessors260            .fromApplication(applicationContext, SyncOutcomeEntryPoint::class.java)261            .syncOutcomes()262            .report(summary)263    }264}265266@EntryPoint267@InstallIn(SingletonComponent::class)268internal interface SyncOutcomeEntryPoint {269    fun syncOutcomes(): SyncOutcomeStore270}