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.Inject2930313233343536373839@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 56 57 58 59 60 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 73 74 75 76 77 78 79 cloudRelayListener.requestReconcile(80 refreshExisting = shouldRefreshExistingWaiters(listenerStarted),81 )82 83 84 85 return START_STICKY86 }8788 override fun onDestroy() {89 cloudRelayListener.stop()90 scope.cancel()91 super.onDestroy()92 }9394 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 223 224 225 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 && backgroundSyncEnabled232233234235236237238239class 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}253254255256257258259260261262263264265266internal 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 282 283 report(SyncOutcomeSummary(reason = SyncOutcomeReason.RUN_FAILED, detail = error.message))284 false285}286287288289290291292293private 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}