Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / e2e / RcsPeerKeys.kt

RcsPeerKeys.kt55 lines · 2.0 KiBRaw
1package com.vayunmathur.communicate.data.rcs.e2e
2
3import android.content.Context
4import com.vayunmathur.communicate.data.rcs.RcsDatabase
5import com.vayunmathur.communicate.data.rcs.RcsFeature
6import kotlinx.coroutines.Dispatchers
7import kotlinx.coroutines.withContext
8
9/**
10 * Peer key-package cache for E2EE group creation.
11 *
12 * Key packages arrive as unencrypted publications on 1:1 threads
13 * ([RcsKeyDirectory]). The latest package per peer E.164 is kept in memory
14 * with a receive timestamp; packages older than [PACKAGE_TTL_MS] are treated
15 * as expired (§5.1 — single-use init keys go stale, and a stale add fails
16 * closed at the crate layer, so expiry here just skips the doomed attempt
17 * and triggers a fresh request instead).
18 *
19 * In-memory only: packages are single-use and republished on demand, so a
20 * process restart simply re-requests.
21 */
22object RcsPeerKeys {
23 /** Peer key-package TTL (7 days, matching the outbox window). */
24 const val PACKAGE_TTL_MS = 7L * 24 * 3600 * 1000
25
26 private data class Entry(val packageTls: ByteArray, val receivedAt: Long)
27
28 private val cache = java.util.concurrent.ConcurrentHashMap<String, Entry>()
29
30 fun store(peerE164: String, keyPackage: ByteArray) {
31 if (!RcsFeature.enabled || peerE164.isBlank() || keyPackage.isEmpty()) return
32 cache[peerE164] = Entry(keyPackage, System.currentTimeMillis())
33 }
34
35 fun get(peerE164: String): ByteArray? {
36 if (!RcsFeature.enabled) return null
37 val entry = cache[peerE164] ?: return null
38 if (System.currentTimeMillis() - entry.receivedAt > PACKAGE_TTL_MS) {
39 cache.remove(peerE164)
40 return null
41 }
42 return entry.packageTls
43 }
44
45 fun consume(peerE164: String): ByteArray? {
46 if (!RcsFeature.enabled) return null
47 val entry = cache.remove(peerE164) ?: return null
48 if (System.currentTimeMillis() - entry.receivedAt > PACKAGE_TTL_MS) return null
49 return entry.packageTls
50 }
51
52 fun clear() {
53 cache.clear()
54 }
55}