Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / SignalDatabase.kt
SignalDatabase.kt755 lines · 28.9 KiBRaw
| 1 | package com.vayunmathur.communicate.data.signal |
| 2 | |
| 3 | import android.content.Context |
| 4 | import androidx.room3.ColumnInfo |
| 5 | import androidx.room3.ColumnTypeConverter |
| 6 | import androidx.room3.ColumnTypeConverters |
| 7 | import androidx.room3.Dao |
| 8 | import androidx.room3.Database |
| 9 | import androidx.room3.Entity |
| 10 | import androidx.room3.Index |
| 11 | import androidx.room3.Insert |
| 12 | import androidx.room3.OnConflictStrategy |
| 13 | import androidx.room3.PrimaryKey |
| 14 | import androidx.room3.Query |
| 15 | import androidx.room3.RoomDatabase |
| 16 | import androidx.sqlite.SQLiteConnection |
| 17 | import androidx.sqlite.execSQL |
| 18 | import com.vayunmathur.library.util.DatabaseMigrations |
| 19 | |
| 20 | /** |
| 21 | * Room database for Signal-specific data. |
| 22 | * Mirrors [com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase] but for Signal. |
| 23 | * |
| 24 | * Entities/DAOs mirror WhatsApp's structure: conversations, cached messages/reactions, |
| 25 | * contacts, E2E session/identity/prekey/sender-key stores, and call log. |
| 26 | */ |
| 27 | @Database( |
| 28 | entities = [ |
| 29 | SignalDevice::class, |
| 30 | SignalSession::class, |
| 31 | SignalConversation::class, |
| 32 | SignalCachedMessage::class, |
| 33 | SignalCachedReaction::class, |
| 34 | SignalContact::class, |
| 35 | SignalE2ESession::class, |
| 36 | SignalE2EIdentity::class, |
| 37 | SignalE2EPreKey::class, |
| 38 | SignalE2ESignedPreKey::class, |
| 39 | SignalE2EKyberPreKey::class, |
| 40 | SignalE2EKyberUsedBaseKey::class, |
| 41 | SignalE2ESenderKey::class, |
| 42 | SignalSenderCertificate::class, |
| 43 | SignalProfileKey::class, |
| 44 | SignalCallLog::class, |
| 45 | ], |
| 46 | version = 6, |
| 47 | exportSchema = true |
| 48 | ) |
| 49 | @ColumnTypeConverters(SignalTypeConverters::class) |
| 50 | abstract class SignalDatabase : RoomDatabase() { |
| 51 | abstract fun deviceDao(): SignalDeviceDao |
| 52 | abstract fun sessionDao(): SignalSessionDao |
| 53 | abstract fun conversationDao(): SignalConversationDao |
| 54 | abstract fun cachedMessageDao(): SignalCachedMessageDao |
| 55 | abstract fun cachedReactionDao(): SignalCachedReactionDao |
| 56 | abstract fun contactDao(): SignalContactDao |
| 57 | abstract fun e2eSessionDao(): SignalE2ESessionDao |
| 58 | abstract fun e2eIdentityDao(): SignalE2EIdentityDao |
| 59 | abstract fun e2ePreKeyDao(): SignalE2EPreKeyDao |
| 60 | abstract fun e2eSignedPreKeyDao(): SignalE2ESignedPreKeyDao |
| 61 | abstract fun e2eKyberPreKeyDao(): SignalE2EKyberPreKeyDao |
| 62 | abstract fun e2eKyberUsedBaseKeyDao(): SignalE2EKyberUsedBaseKeyDao |
| 63 | abstract fun e2eSenderKeyDao(): SignalE2ESenderKeyDao |
| 64 | abstract fun senderCertificateDao(): SignalSenderCertificateDao |
| 65 | abstract fun profileKeyDao(): SignalProfileKeyDao |
| 66 | abstract fun callLogDao(): SignalCallLogDao |
| 67 | |
| 68 | /** Schema migrations and the singleton accessor for [SignalDatabase]. */ |
| 69 | companion object : DatabaseMigrations { |
| 70 | /** |
| 71 | * v1 → v2: Kyber pre-key storage. The protocol store needs somewhere to keep our own Kyber |
| 72 | * pre-keys, plus the (kyberPreKeyId, signedPreKeyId, baseKey) tuples that make last-resort |
| 73 | * keys single-use — reusing one is what `ReusedBaseKeyException` guards against. |
| 74 | */ |
| 75 | private val MIGRATION_1_2 = object : androidx.room3.migration.Migration(1, 2) { |
| 76 | override suspend fun migrate(connection: SQLiteConnection) { |
| 77 | // Must match Room's generated createAllTables statements byte for byte, including the |
| 78 | // absence of column defaults — TableInfo validation compares them and throws on a |
| 79 | // mismatch. Both tables are new, so there is nothing to backfill. |
| 80 | connection.execSQL( |
| 81 | "CREATE TABLE IF NOT EXISTS `signal_e2e_kyber_pre_keys` (" + |
| 82 | "`id` INTEGER NOT NULL, `record` BLOB NOT NULL, " + |
| 83 | "`lastResort` INTEGER NOT NULL, `uploaded` INTEGER NOT NULL, " + |
| 84 | "PRIMARY KEY(`id`))", |
| 85 | ) |
| 86 | connection.execSQL( |
| 87 | "CREATE TABLE IF NOT EXISTS `signal_e2e_kyber_used_base_keys` (" + |
| 88 | "`kyberPreKeyId` INTEGER NOT NULL, `signedPreKeyId` INTEGER NOT NULL, " + |
| 89 | "`baseKeyB64` TEXT NOT NULL, " + |
| 90 | "PRIMARY KEY(`kyberPreKeyId`, `signedPreKeyId`, `baseKeyB64`))", |
| 91 | ) |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | /** |
| 96 | * v2 → v3: sealed sender. The delivery certificate is a rotating credential, and recipient |
| 97 | * profile keys are secret material used to derive unidentified-access keys — both belong in the |
| 98 | * encrypted database rather than the plaintext preferences blob. |
| 99 | */ |
| 100 | private val MIGRATION_2_3 = object : androidx.room3.migration.Migration(2, 3) { |
| 101 | override suspend fun migrate(connection: SQLiteConnection) { |
| 102 | connection.execSQL( |
| 103 | "CREATE TABLE IF NOT EXISTS `signal_sender_certificate` (" + |
| 104 | "`id` INTEGER NOT NULL, `record` BLOB NOT NULL, " + |
| 105 | "`expiration` INTEGER NOT NULL, `includesE164` INTEGER NOT NULL, " + |
| 106 | "PRIMARY KEY(`id`))", |
| 107 | ) |
| 108 | connection.execSQL( |
| 109 | "CREATE TABLE IF NOT EXISTS `signal_profile_keys` (" + |
| 110 | "`address` TEXT NOT NULL, `profileKey` BLOB NOT NULL, " + |
| 111 | "PRIMARY KEY(`address`))", |
| 112 | ) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /** |
| 117 | * v3 → v4: store the group master key in its own column. |
| 118 | * |
| 119 | * Conversation ids used to be the hex of the master key's first 8 bytes, which both leaked secret |
| 120 | * material and was not the identifier the protocol uses. They are now the derived 32-byte |
| 121 | * `GroupIdentifier`. Existing group rows cannot be converted — the full master key was never |
| 122 | * stored, so the new id is not recoverable from the old one — so they are dropped and will be |
| 123 | * recreated from inbound traffic. |
| 124 | */ |
| 125 | private val MIGRATION_3_4 = object : androidx.room3.migration.Migration(3, 4) { |
| 126 | override suspend fun migrate(connection: SQLiteConnection) { |
| 127 | connection.execSQL("ALTER TABLE signal_conversation ADD COLUMN groupMasterKey BLOB") |
| 128 | connection.execSQL( |
| 129 | "ALTER TABLE signal_conversation ADD COLUMN groupRevision INTEGER NOT NULL DEFAULT 0", |
| 130 | ) |
| 131 | connection.execSQL("DELETE FROM signal_cached_message WHERE conversationId LIKE 'group:%'") |
| 132 | connection.execSQL("DELETE FROM signal_conversation WHERE chatId LIKE 'group:%'") |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | /** v4 → v5: keep the PNI from contact discovery, which is how a new contact is addressed. */ |
| 137 | private val MIGRATION_4_5 = object : androidx.room3.migration.Migration(4, 5) { |
| 138 | override suspend fun migrate(connection: SQLiteConnection) { |
| 139 | connection.execSQL("ALTER TABLE signal_contact ADD COLUMN pni TEXT NOT NULL DEFAULT ''") |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | /** v5 → v6: (conversationId, timestamp) index for keyset conversation windows. */ |
| 144 | private val MIGRATION_5_6 = object : androidx.room3.migration.Migration(5, 6) { |
| 145 | override suspend fun migrate(connection: SQLiteConnection) { |
| 146 | connection.execSQL( |
| 147 | "CREATE INDEX IF NOT EXISTS `index_signal_cached_message_conversationId_timestamp` " + |
| 148 | "ON `signal_cached_message` (`conversationId`, `timestamp`)", |
| 149 | ) |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | override val migrations = listOf<androidx.room3.migration.Migration>( |
| 154 | MIGRATION_1_2, |
| 155 | MIGRATION_2_3, |
| 156 | MIGRATION_3_4, |
| 157 | MIGRATION_4_5, |
| 158 | MIGRATION_5_6) |
| 159 | |
| 160 | /** |
| 161 | * Test seam: when set, [getDatabase] returns this instance instead |
| 162 | * of the SQLCipher-backed singleton (whose native library cannot |
| 163 | * load on a JVM test host). Production code never sets it. |
| 164 | */ |
| 165 | @Volatile |
| 166 | var overrideForTest: SignalDatabase? = null |
| 167 | |
| 168 | fun getDatabase(context: Context): SignalDatabase = |
| 169 | overrideForTest ?: SignalRepository.get(context).database() |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | /** Room column converters for Signal entities; string lists are stored as CSV. */ |
| 174 | class SignalTypeConverters { |
| 175 | @ColumnTypeConverter |
| 176 | fun fromStringList(value: List<String>): String = value.joinToString(",") |
| 177 | |
| 178 | @ColumnTypeConverter |
| 179 | fun toStringList(value: String): List<String> = |
| 180 | if (value.isEmpty()) emptyList() else value.split(",") |
| 181 | } |
| 182 | |
| 183 | // -- Device / session (transport) -- |
| 184 | |
| 185 | /** A linked Signal device: its device id, phone number, platform and last-seen time. */ |
| 186 | @Entity(tableName = "signal_devices") |
| 187 | data class SignalDevice( |
| 188 | @PrimaryKey val deviceId: String, |
| 189 | val phoneNumber: String, |
| 190 | val pushName: String, |
| 191 | val platform: String, |
| 192 | val lastSeen: Long, |
| 193 | val jid: String = "", |
| 194 | val timezone: String = "", |
| 195 | val loggedInAt: Long = 0L, |
| 196 | ) |
| 197 | |
| 198 | /** A stored Signal protocol session record for one peer address (legacy transport table). */ |
| 199 | @Entity(tableName = "signal_sessions") |
| 200 | data class SignalSession( |
| 201 | @PrimaryKey val jid: String, |
| 202 | val sessionData: ByteArray, |
| 203 | val timestamp: Long, |
| 204 | val isPreKey: Boolean = false, |
| 205 | ) { |
| 206 | override fun equals(other: Any?): Boolean { |
| 207 | if (this === other) return true |
| 208 | if (javaClass != other?.javaClass) return false |
| 209 | other as SignalSession |
| 210 | return jid == other.jid && sessionData.contentEquals(other.sessionData) && timestamp == other.timestamp |
| 211 | } |
| 212 | override fun hashCode(): Int { |
| 213 | var result = jid.hashCode() |
| 214 | result = 31 * result + sessionData.contentHashCode() |
| 215 | result = 31 * result + timestamp.hashCode() |
| 216 | return result |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | /** Queries for linked Signal devices. */ |
| 221 | @Dao |
| 222 | interface SignalDeviceDao { |
| 223 | @Query("SELECT * FROM signal_devices WHERE deviceId = :deviceId") |
| 224 | suspend fun getDevice(deviceId: String): SignalDevice? |
| 225 | |
| 226 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 227 | suspend fun insertDevice(device: SignalDevice) |
| 228 | |
| 229 | @Query("DELETE FROM signal_devices WHERE deviceId = :deviceId") |
| 230 | suspend fun deleteDevice(deviceId: String) |
| 231 | } |
| 232 | |
| 233 | /** Queries for stored Signal protocol sessions. */ |
| 234 | @Dao |
| 235 | interface SignalSessionDao { |
| 236 | @Query("SELECT * FROM signal_sessions WHERE jid = :jid") |
| 237 | suspend fun getSession(jid: String): SignalSession? |
| 238 | |
| 239 | @Query("SELECT EXISTS(SELECT 1 FROM signal_sessions WHERE jid = :jid)") |
| 240 | suspend fun containsSession(jid: String): Boolean |
| 241 | |
| 242 | @Query("SELECT * FROM signal_sessions") |
| 243 | suspend fun getAllSessions(): List<SignalSession> |
| 244 | |
| 245 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 246 | suspend fun insertSession(session: SignalSession) |
| 247 | |
| 248 | @Query("DELETE FROM signal_sessions WHERE jid = :jid") |
| 249 | suspend fun deleteSession(jid: String) |
| 250 | |
| 251 | @Query("DELETE FROM signal_sessions") |
| 252 | suspend fun clearAllSessions() |
| 253 | } |
| 254 | |
| 255 | // -- Conversation -- |
| 256 | |
| 257 | /** A Signal conversation row: a 1:1 chat keyed by address or a group keyed by its derived group id. */ |
| 258 | @Entity(tableName = "signal_conversation") |
| 259 | data class SignalConversation( |
| 260 | @PrimaryKey val chatId: String, |
| 261 | val isGroup: Boolean = false, |
| 262 | val name: String? = null, |
| 263 | /** CSV of participant identifiers (ACIs/phone numbers) for groups. */ |
| 264 | val participants: String = "", |
| 265 | val unreadCount: Int = 0, |
| 266 | val lastMessageTimestamp: Long = 0L, |
| 267 | val archived: Boolean = false, |
| 268 | val pinned: Boolean = false, |
| 269 | /** |
| 270 | * The group's 32-byte master key. Secret material: it encrypts the group's attributes and |
| 271 | * membership, so it is stored here rather than being folded into [chatId], which is the derived |
| 272 | * public identifier. |
| 273 | */ |
| 274 | val groupMasterKey: ByteArray? = null, |
| 275 | // Declared here so the ALTER TABLE default in MIGRATION_3_4 matches what Room expects; adding a |
| 276 | // NOT NULL column requires a default, and TableInfo validation compares them. |
| 277 | @ColumnInfo(defaultValue = "0") val groupRevision: Int = 0, |
| 278 | ) |
| 279 | |
| 280 | /** Queries for Signal conversations. */ |
| 281 | @Dao |
| 282 | interface SignalConversationDao { |
| 283 | @Query("SELECT * FROM signal_conversation WHERE chatId = :chatId") |
| 284 | suspend fun getConversation(chatId: String): SignalConversation? |
| 285 | |
| 286 | @Query("SELECT * FROM signal_conversation ORDER BY lastMessageTimestamp DESC LIMIT :limit") |
| 287 | suspend fun getRecent(limit: Int): List<SignalConversation> |
| 288 | |
| 289 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 290 | suspend fun upsert(conversation: SignalConversation) |
| 291 | |
| 292 | @Query("DELETE FROM signal_conversation WHERE chatId = :chatId") |
| 293 | suspend fun delete(chatId: String) |
| 294 | |
| 295 | @Query("DELETE FROM signal_conversation") |
| 296 | suspend fun deleteAll() |
| 297 | |
| 298 | @Query("UPDATE signal_conversation SET pinned = :pinned WHERE chatId = :chatId") |
| 299 | suspend fun updatePinned(chatId: String, pinned: Boolean) |
| 300 | |
| 301 | @Query("UPDATE signal_conversation SET archived = :archived WHERE chatId = :chatId") |
| 302 | suspend fun updateArchived(chatId: String, archived: Boolean) |
| 303 | } |
| 304 | |
| 305 | // -- Cached messages -- |
| 306 | |
| 307 | /** A cached Signal message row, including edit/revoke state, media pointer and delivery status. */ |
| 308 | @Entity(tableName = "signal_cached_message", indices = [Index(value = ["conversationId", "timestamp"])]) |
| 309 | data class SignalCachedMessage( |
| 310 | @PrimaryKey val messageId: String, |
| 311 | val conversationId: String, |
| 312 | val body: String, |
| 313 | val timestamp: Long, |
| 314 | val outgoing: Boolean, |
| 315 | val senderId: String = "", |
| 316 | val isEdited: Boolean = false, |
| 317 | val isRevoked: Boolean = false, |
| 318 | val mediaUrl: String? = null, |
| 319 | val mediaMime: String? = null, |
| 320 | val serviceData: String? = null, |
| 321 | /** Outgoing delivery status ordinal (MessageStatus ordinal). */ |
| 322 | val status: Int = 0, |
| 323 | ) |
| 324 | |
| 325 | /** Queries for cached Signal messages. */ |
| 326 | @Dao |
| 327 | interface SignalCachedMessageDao { |
| 328 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 329 | suspend fun upsert(message: SignalCachedMessage) |
| 330 | |
| 331 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 332 | suspend fun upsertAll(messages: List<SignalCachedMessage>) |
| 333 | |
| 334 | @Query("SELECT * FROM signal_cached_message WHERE conversationId = :id ORDER BY timestamp ASC") |
| 335 | suspend fun getForConversation(id: String): List<SignalCachedMessage> |
| 336 | |
| 337 | /** |
| 338 | * Keyset window: the newest [limit] messages before [before] (exclusive), |
| 339 | * newest first. Callers that render chronologically reverse the result. |
| 340 | * Served by index_signal_cached_message_conversationId_timestamp. |
| 341 | */ |
| 342 | @Query( |
| 343 | "SELECT * FROM signal_cached_message WHERE conversationId = :id AND timestamp < :before " + |
| 344 | "ORDER BY timestamp DESC LIMIT :limit", |
| 345 | ) |
| 346 | suspend fun getForConversationBefore( |
| 347 | id: String, |
| 348 | before: Long = Long.MAX_VALUE, |
| 349 | limit: Int = 100, |
| 350 | ): List<SignalCachedMessage> |
| 351 | |
| 352 | @Query("SELECT * FROM signal_cached_message WHERE messageId = :messageId LIMIT 1") |
| 353 | suspend fun get(messageId: String): SignalCachedMessage? |
| 354 | |
| 355 | /** |
| 356 | * Find an outgoing message by its sent timestamp, which is how receipts identify it. Not scoped to a |
| 357 | * conversation on purpose: a receipt has to resolve regardless of which id the message was filed |
| 358 | * under, and the timestamp is the message's protocol-level identity. |
| 359 | */ |
| 360 | @Query("SELECT * FROM signal_cached_message WHERE timestamp = :timestamp AND outgoing = 1 LIMIT 1") |
| 361 | suspend fun getOutgoingByTimestamp(timestamp: Long): SignalCachedMessage? |
| 362 | |
| 363 | /** As [getOutgoingByTimestamp], but either direction — for read syncs from our own other devices. */ |
| 364 | @Query("SELECT * FROM signal_cached_message WHERE timestamp = :timestamp LIMIT 1") |
| 365 | suspend fun getByTimestamp(timestamp: Long): SignalCachedMessage? |
| 366 | |
| 367 | /** Most-recent message per conversation, newest first (for the thread list). */ |
| 368 | @Query( |
| 369 | "SELECT * FROM signal_cached_message AS m WHERE m.messageId = " + |
| 370 | "(SELECT i.messageId FROM signal_cached_message AS i " + |
| 371 | "WHERE i.conversationId = m.conversationId " + |
| 372 | "ORDER BY i.timestamp DESC, i.messageId DESC LIMIT 1) " + |
| 373 | "ORDER BY m.timestamp DESC, m.messageId DESC", |
| 374 | ) |
| 375 | suspend fun getLatestPerConversation(): List<SignalCachedMessage> |
| 376 | |
| 377 | @Query("UPDATE signal_cached_message SET body = :body, isEdited = 1 WHERE messageId = :messageId") |
| 378 | suspend fun markEdited(messageId: String, body: String) |
| 379 | |
| 380 | @Query("UPDATE signal_cached_message SET isRevoked = 1, body = '' WHERE messageId = :messageId") |
| 381 | suspend fun markRevoked(messageId: String) |
| 382 | |
| 383 | @Query("UPDATE signal_cached_message SET serviceData = :serviceData WHERE messageId = :messageId") |
| 384 | suspend fun updateServiceData(messageId: String, serviceData: String?) |
| 385 | |
| 386 | /** Advance to Delivered (2) only from a lower state. */ |
| 387 | @Query("UPDATE signal_cached_message SET status = 2 WHERE messageId = :messageId AND status < 2") |
| 388 | suspend fun markDelivered(messageId: String) |
| 389 | |
| 390 | /** Advance to Read (3) only from a lower state. */ |
| 391 | @Query("UPDATE signal_cached_message SET status = 3 WHERE messageId = :messageId AND status < 3") |
| 392 | suspend fun markReadStatus(messageId: String) |
| 393 | |
| 394 | @Query("DELETE FROM signal_cached_message WHERE conversationId = :id") |
| 395 | suspend fun deleteConversation(id: String) |
| 396 | |
| 397 | @Query("DELETE FROM signal_cached_message") |
| 398 | suspend fun deleteAll() |
| 399 | } |
| 400 | |
| 401 | // -- Reactions -- |
| 402 | |
| 403 | /** One emoji reaction on a cached Signal message, keyed by message and sender. */ |
| 404 | @Entity(tableName = "signal_cached_reaction", primaryKeys = ["messageId", "senderId"]) |
| 405 | data class SignalCachedReaction( |
| 406 | val messageId: String, |
| 407 | val emoji: String, |
| 408 | val senderId: String, |
| 409 | val timestamp: Long, |
| 410 | ) |
| 411 | |
| 412 | /** Queries for cached Signal message reactions. */ |
| 413 | @Dao |
| 414 | interface SignalCachedReactionDao { |
| 415 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 416 | suspend fun upsert(reaction: SignalCachedReaction) |
| 417 | |
| 418 | @Query("SELECT * FROM signal_cached_reaction WHERE messageId = :messageId") |
| 419 | suspend fun getForMessage(messageId: String): List<SignalCachedReaction> |
| 420 | |
| 421 | @Query("DELETE FROM signal_cached_reaction WHERE messageId = :messageId AND senderId = :senderId") |
| 422 | suspend fun remove(messageId: String, senderId: String) |
| 423 | |
| 424 | @Query("DELETE FROM signal_cached_reaction WHERE messageId = :messageId") |
| 425 | suspend fun clearForMessage(messageId: String) |
| 426 | } |
| 427 | |
| 428 | // -- Contacts -- |
| 429 | |
| 430 | /** A Signal contact discovered via CDSi, keyed by ACI with its phone number and PNI. */ |
| 431 | @Entity(tableName = "signal_contact") |
| 432 | data class SignalContact( |
| 433 | @PrimaryKey val aci: String, |
| 434 | val phoneE164: String = "", |
| 435 | val displayName: String = "", |
| 436 | val onSignal: Boolean = false, |
| 437 | val updatedAt: Long = 0L, |
| 438 | /** |
| 439 | * The phone-number identity. Contact discovery returns this, not the ACI — an ACI only comes back |
| 440 | * when we already hold the contact's profile key — so this is what addresses a contact we have never |
| 441 | * exchanged messages with. |
| 442 | */ |
| 443 | @ColumnInfo(defaultValue = "''") val pni: String = "", |
| 444 | ) |
| 445 | |
| 446 | /** Queries for Signal contacts. */ |
| 447 | @Dao |
| 448 | interface SignalContactDao { |
| 449 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 450 | suspend fun upsert(contact: SignalContact) |
| 451 | |
| 452 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 453 | suspend fun upsertAll(contacts: List<SignalContact>) |
| 454 | |
| 455 | @Query("SELECT * FROM signal_contact WHERE aci = :aci LIMIT 1") |
| 456 | suspend fun get(aci: String): SignalContact? |
| 457 | |
| 458 | @Query("SELECT * FROM signal_contact WHERE phoneE164 = :phone LIMIT 1") |
| 459 | suspend fun getByPhone(phone: String): SignalContact? |
| 460 | |
| 461 | @Query("SELECT * FROM signal_contact WHERE pni = :pni AND pni != '' LIMIT 1") |
| 462 | suspend fun getByPni(pni: String): SignalContact? |
| 463 | |
| 464 | @Query("DELETE FROM signal_contact WHERE phoneE164 = :phone") |
| 465 | suspend fun deleteByPhone(phone: String) |
| 466 | |
| 467 | @Query("SELECT * FROM signal_contact WHERE onSignal = 1 ORDER BY displayName COLLATE NOCASE ASC") |
| 468 | suspend fun getOnSignal(): List<SignalContact> |
| 469 | |
| 470 | @Query("SELECT * FROM signal_contact") |
| 471 | suspend fun getAll(): List<SignalContact> |
| 472 | |
| 473 | @Query("DELETE FROM signal_contact") |
| 474 | suspend fun deleteAll() |
| 475 | } |
| 476 | |
| 477 | // -- E2E stores -- |
| 478 | |
| 479 | /** A Signal protocol (double-ratchet) session record for one peer device. */ |
| 480 | @Entity(tableName = "signal_e2e_sessions", primaryKeys = ["address", "deviceId"]) |
| 481 | data class SignalE2ESession( |
| 482 | val address: String, |
| 483 | val deviceId: Int, |
| 484 | val record: ByteArray, |
| 485 | ) |
| 486 | |
| 487 | /** A peer identity key for one Signal address, used for trust-on-first-use checks. */ |
| 488 | @Entity(tableName = "signal_e2e_identities") |
| 489 | data class SignalE2EIdentity( |
| 490 | @PrimaryKey val address: String, |
| 491 | val identityKey: ByteArray, |
| 492 | ) |
| 493 | |
| 494 | /** One of our one-time EC pre-keys, with whether it has been uploaded to the service. */ |
| 495 | @Entity(tableName = "signal_e2e_pre_keys") |
| 496 | data class SignalE2EPreKey( |
| 497 | @PrimaryKey val id: Int, |
| 498 | val record: ByteArray, |
| 499 | val uploaded: Boolean = false, |
| 500 | ) |
| 501 | |
| 502 | /** One of our signed EC pre-keys (the serialized protocol record). */ |
| 503 | @Entity(tableName = "signal_e2e_signed_pre_keys") |
| 504 | data class SignalE2ESignedPreKey( |
| 505 | @PrimaryKey val id: Int, |
| 506 | val record: ByteArray, |
| 507 | ) |
| 508 | |
| 509 | /** One of our Kyber (post-quantum) pre-keys; the last-resort key is the reusable fallback. */ |
| 510 | @Entity(tableName = "signal_e2e_kyber_pre_keys") |
| 511 | data class SignalE2EKyberPreKey( |
| 512 | @PrimaryKey val id: Int, |
| 513 | val record: ByteArray, |
| 514 | val lastResort: Boolean = false, |
| 515 | val uploaded: Boolean = false, |
| 516 | ) |
| 517 | |
| 518 | /** |
| 519 | * Records that a last-resort Kyber pre-key has already been used with a given signed pre-key and |
| 520 | * sender base key. Re-seeing a tuple means a replayed pre-key message. |
| 521 | */ |
| 522 | @Entity( |
| 523 | tableName = "signal_e2e_kyber_used_base_keys", |
| 524 | primaryKeys = ["kyberPreKeyId", "signedPreKeyId", "baseKeyB64"], |
| 525 | ) |
| 526 | data class SignalE2EKyberUsedBaseKey( |
| 527 | val kyberPreKeyId: Int, |
| 528 | val signedPreKeyId: Int, |
| 529 | val baseKeyB64: String, |
| 530 | ) |
| 531 | |
| 532 | /** A group sender-key record for one (address, device, distribution) triple. */ |
| 533 | @Entity(tableName = "signal_e2e_sender_keys", primaryKeys = ["address", "deviceId", "distributionId"]) |
| 534 | data class SignalE2ESenderKey( |
| 535 | val address: String, |
| 536 | val deviceId: Int, |
| 537 | val distributionId: String, |
| 538 | val record: ByteArray, |
| 539 | ) |
| 540 | |
| 541 | /** Queries for Signal protocol session records. */ |
| 542 | @Dao |
| 543 | interface SignalE2ESessionDao { |
| 544 | @Query("SELECT * FROM signal_e2e_sessions WHERE address = :address AND deviceId = :deviceId LIMIT 1") |
| 545 | suspend fun get(address: String, deviceId: Int): SignalE2ESession? |
| 546 | |
| 547 | @Query("SELECT deviceId FROM signal_e2e_sessions WHERE address = :address") |
| 548 | suspend fun getSubDeviceIds(address: String): List<Int> |
| 549 | |
| 550 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 551 | suspend fun insert(entity: SignalE2ESession) |
| 552 | |
| 553 | @Query("SELECT COUNT(*) > 0 FROM signal_e2e_sessions WHERE address = :address AND deviceId = :deviceId") |
| 554 | suspend fun exists(address: String, deviceId: Int): Boolean |
| 555 | |
| 556 | @Query("DELETE FROM signal_e2e_sessions WHERE address = :address AND deviceId = :deviceId") |
| 557 | suspend fun delete(address: String, deviceId: Int) |
| 558 | |
| 559 | @Query("DELETE FROM signal_e2e_sessions WHERE address = :address") |
| 560 | suspend fun deleteAll(address: String) |
| 561 | } |
| 562 | |
| 563 | /** Queries for peer identity keys. */ |
| 564 | @Dao |
| 565 | interface SignalE2EIdentityDao { |
| 566 | @Query("SELECT * FROM signal_e2e_identities WHERE address = :address LIMIT 1") |
| 567 | suspend fun get(address: String): SignalE2EIdentity? |
| 568 | |
| 569 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 570 | suspend fun insert(entity: SignalE2EIdentity) |
| 571 | |
| 572 | @Query("DELETE FROM signal_e2e_identities WHERE address = :address") |
| 573 | suspend fun delete(address: String) |
| 574 | } |
| 575 | |
| 576 | /** Queries for our one-time EC pre-keys. */ |
| 577 | @Dao |
| 578 | interface SignalE2EPreKeyDao { |
| 579 | @Query("SELECT * FROM signal_e2e_pre_keys WHERE id = :id LIMIT 1") |
| 580 | suspend fun get(id: Int): SignalE2EPreKey? |
| 581 | |
| 582 | @Query("SELECT * FROM signal_e2e_pre_keys") |
| 583 | suspend fun getAll(): List<SignalE2EPreKey> |
| 584 | |
| 585 | @Query("SELECT * FROM signal_e2e_pre_keys WHERE uploaded = 0") |
| 586 | suspend fun getUnuploaded(): List<SignalE2EPreKey> |
| 587 | |
| 588 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 589 | suspend fun insert(entity: SignalE2EPreKey) |
| 590 | |
| 591 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 592 | suspend fun insertAll(entities: List<SignalE2EPreKey>) |
| 593 | |
| 594 | @Query("UPDATE signal_e2e_pre_keys SET uploaded = 1 WHERE id <= :maxId") |
| 595 | suspend fun markUploadedUpTo(maxId: Int) |
| 596 | |
| 597 | @Query("SELECT COUNT(*) > 0 FROM signal_e2e_pre_keys WHERE id = :id") |
| 598 | suspend fun exists(id: Int): Boolean |
| 599 | |
| 600 | @Query("DELETE FROM signal_e2e_pre_keys WHERE id = :id") |
| 601 | suspend fun delete(id: Int) |
| 602 | |
| 603 | @Query("SELECT COUNT(*) FROM signal_e2e_pre_keys") |
| 604 | suspend fun getCount(): Int |
| 605 | |
| 606 | @Query("SELECT COALESCE(MAX(id), 0) FROM signal_e2e_pre_keys") |
| 607 | suspend fun getMaxId(): Int |
| 608 | } |
| 609 | |
| 610 | /** Queries for our signed EC pre-keys. */ |
| 611 | @Dao |
| 612 | interface SignalE2ESignedPreKeyDao { |
| 613 | @Query("SELECT * FROM signal_e2e_signed_pre_keys WHERE id = :id LIMIT 1") |
| 614 | suspend fun get(id: Int): SignalE2ESignedPreKey? |
| 615 | |
| 616 | @Query("SELECT * FROM signal_e2e_signed_pre_keys") |
| 617 | suspend fun getAll(): List<SignalE2ESignedPreKey> |
| 618 | |
| 619 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 620 | suspend fun insert(entity: SignalE2ESignedPreKey) |
| 621 | |
| 622 | @Query("SELECT COUNT(*) > 0 FROM signal_e2e_signed_pre_keys WHERE id = :id") |
| 623 | suspend fun exists(id: Int): Boolean |
| 624 | |
| 625 | @Query("DELETE FROM signal_e2e_signed_pre_keys WHERE id = :id") |
| 626 | suspend fun delete(id: Int) |
| 627 | } |
| 628 | |
| 629 | /** Queries for our Kyber pre-keys. */ |
| 630 | @Dao |
| 631 | interface SignalE2EKyberPreKeyDao { |
| 632 | @Query("SELECT * FROM signal_e2e_kyber_pre_keys WHERE id = :id LIMIT 1") |
| 633 | suspend fun get(id: Int): SignalE2EKyberPreKey? |
| 634 | |
| 635 | @Query("SELECT * FROM signal_e2e_kyber_pre_keys") |
| 636 | suspend fun getAll(): List<SignalE2EKyberPreKey> |
| 637 | |
| 638 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 639 | suspend fun insert(entity: SignalE2EKyberPreKey) |
| 640 | |
| 641 | @Query("SELECT COUNT(*) > 0 FROM signal_e2e_kyber_pre_keys WHERE id = :id") |
| 642 | suspend fun exists(id: Int): Boolean |
| 643 | |
| 644 | @Query("DELETE FROM signal_e2e_kyber_pre_keys WHERE id = :id") |
| 645 | suspend fun delete(id: Int) |
| 646 | } |
| 647 | |
| 648 | /** Queries for used last-resort Kyber base keys (replay detection). */ |
| 649 | @Dao |
| 650 | interface SignalE2EKyberUsedBaseKeyDao { |
| 651 | @Query( |
| 652 | "SELECT COUNT(*) > 0 FROM signal_e2e_kyber_used_base_keys " + |
| 653 | "WHERE kyberPreKeyId = :kyberPreKeyId AND signedPreKeyId = :signedPreKeyId AND baseKeyB64 = :baseKeyB64", |
| 654 | ) |
| 655 | suspend fun exists(kyberPreKeyId: Int, signedPreKeyId: Int, baseKeyB64: String): Boolean |
| 656 | |
| 657 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 658 | suspend fun insert(entity: SignalE2EKyberUsedBaseKey) |
| 659 | |
| 660 | @Query("DELETE FROM signal_e2e_kyber_used_base_keys WHERE kyberPreKeyId = :kyberPreKeyId") |
| 661 | suspend fun deleteForKyberPreKey(kyberPreKeyId: Int) |
| 662 | } |
| 663 | |
| 664 | /** Queries for group sender-key records. */ |
| 665 | @Dao |
| 666 | interface SignalE2ESenderKeyDao { |
| 667 | @Query("SELECT * FROM signal_e2e_sender_keys WHERE address = :address AND " + |
| 668 | "deviceId = :deviceId AND distributionId = :distributionId LIMIT 1") |
| 669 | suspend fun get(address: String, deviceId: Int, distributionId: String): SignalE2ESenderKey? |
| 670 | |
| 671 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 672 | suspend fun insert(entity: SignalE2ESenderKey) |
| 673 | |
| 674 | @Query("DELETE FROM signal_e2e_sender_keys WHERE address = :address " + |
| 675 | "AND deviceId = :deviceId AND distributionId = :distributionId") |
| 676 | suspend fun delete(address: String, deviceId: Int, distributionId: String) |
| 677 | } |
| 678 | |
| 679 | // -- Sealed sender -- |
| 680 | |
| 681 | /** |
| 682 | * The delivery certificate, a single rotating row. [expiration] is the certificate's own expiry, used |
| 683 | * to refresh it before it lapses. |
| 684 | */ |
| 685 | @Entity(tableName = "signal_sender_certificate") |
| 686 | data class SignalSenderCertificate( |
| 687 | @PrimaryKey val id: Int = 0, |
| 688 | val record: ByteArray, |
| 689 | val expiration: Long, |
| 690 | val includesE164: Boolean, |
| 691 | ) |
| 692 | |
| 693 | /** |
| 694 | * A recipient's profile key, from which their unidentified-access key is derived. Secret material — |
| 695 | * this table lives in the encrypted database. |
| 696 | */ |
| 697 | @Entity(tableName = "signal_profile_keys") |
| 698 | data class SignalProfileKey( |
| 699 | @PrimaryKey val address: String, |
| 700 | val profileKey: ByteArray, |
| 701 | ) |
| 702 | |
| 703 | /** Queries for the sealed-sender delivery certificate row. */ |
| 704 | @Dao |
| 705 | interface SignalSenderCertificateDao { |
| 706 | @Query("SELECT * FROM signal_sender_certificate WHERE id = 0 LIMIT 1") |
| 707 | suspend fun get(): SignalSenderCertificate? |
| 708 | |
| 709 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 710 | suspend fun upsert(entity: SignalSenderCertificate) |
| 711 | |
| 712 | @Query("DELETE FROM signal_sender_certificate") |
| 713 | suspend fun clear() |
| 714 | } |
| 715 | |
| 716 | /** Queries for recipient profile keys. */ |
| 717 | @Dao |
| 718 | interface SignalProfileKeyDao { |
| 719 | @Query("SELECT * FROM signal_profile_keys WHERE address = :address LIMIT 1") |
| 720 | suspend fun get(address: String): SignalProfileKey? |
| 721 | |
| 722 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 723 | suspend fun upsert(entity: SignalProfileKey) |
| 724 | } |
| 725 | |
| 726 | // -- Call log -- |
| 727 | |
| 728 | /** One Signal voice/video call in the call log, with peer, direction and outcome. */ |
| 729 | @Entity(tableName = "signal_call_log") |
| 730 | data class SignalCallLog( |
| 731 | @PrimaryKey val callId: String, |
| 732 | val peerId: String = "", |
| 733 | val peerName: String = "", |
| 734 | val outgoing: Boolean = false, |
| 735 | val video: Boolean = false, |
| 736 | val startTime: Long = 0L, |
| 737 | val durationSeconds: Long = 0L, |
| 738 | val outcome: String = "", |
| 739 | ) |
| 740 | |
| 741 | /** Queries for the Signal call log. */ |
| 742 | @Dao |
| 743 | interface SignalCallLogDao { |
| 744 | @Insert(onConflict = OnConflictStrategy.REPLACE) |
| 745 | suspend fun upsert(entry: SignalCallLog) |
| 746 | |
| 747 | @Query("SELECT * FROM signal_call_log ORDER BY startTime DESC LIMIT :limit") |
| 748 | suspend fun getRecent(limit: Int = 200): List<SignalCallLog> |
| 749 | |
| 750 | @Query("SELECT * FROM signal_call_log WHERE callId = :callId LIMIT 1") |
| 751 | suspend fun get(callId: String): SignalCallLog? |
| 752 | |
| 753 | @Query("DELETE FROM signal_call_log") |
| 754 | suspend fun deleteAll() |
| 755 | } |