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.Inject3031323334353637383940@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 57 58 if (vault.isUnlocked.value && vault.syncVaultId() == null) {59 stopSelf()60 return START_NOT_STICKY61 }62 63 64 65 66 67 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 80 81 82 83 84 85 86 cloudRelayListener.requestReconcile(87 refreshExisting = shouldRefreshExistingWaiters(listenerStarted),88 )89 90 91 92 return START_STICKY93 }9495 override fun onDestroy() {96 cloudRelayListener.stop()97 scope.cancel()98 super.onDestroy()99 }100101 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 125 126 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 237 238 239 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 && backgroundSyncEnabled246247248249250251252253class 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}267268269270271272273274275276277278279280internal 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 296 297 report(SyncOutcomeSummary(reason = SyncOutcomeReason.RUN_FAILED, detail = error.message))298 false299}300301302303304305306307private 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}