feat: the inbox key changes with the group's admins (group-inbox, Phase 9)

InboxRotation reads what every admin's device already holds: the key
was made over one set of admins and the room's policy now names
another. That covers a removal, a demotion, a step-down and a promotion
alike, and a change that landed while the app was closed. The admin
whose key sorts first starts the new ceremony, asking nobody, after any
share rotation the same change owes; the rotated key's announcement is
vouched for and signed unasked; the removed admin's device has already
let go. Run by the governance follow-through and the sweep, and offered
by hand in the settings, which say when the admins have changed since
the key was made.

Two admins who start a rotation at once end in one ceremony on every
device: each keeps the one whose session id sorts first and ends the
other out loud. A proposal for a generation a device already has is
dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-22 02:09:01 +02:00
1 parent 6b59282ebe
commit 8bc7ab3e33
9 files changed
+280

No files matched your search

@@ -781,4 +781,5 @@
<string name="not_yet_on_a_relay">Not yet on a relay</string>
<string name="send_reply_again">Send again</string>
<string name="sent_again">Sent again</string>
<string name="the_admins_have_changed_since_this_key_was_made">The group's admins have changed since this key was made. It changes on its own once an admin's device starts a new ceremony, or you can rotate it now.</string>
</resources>
@@ -22,6 +22,7 @@ import mobi.giza.compose.managers.GroupInboxManager
import mobi.giza.compose.managers.InboxAnnouncements
import mobi.giza.compose.managers.InboxKeyRitualManager
import mobi.giza.compose.managers.InboxReplies
import mobi.giza.compose.managers.InboxRotation
import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents
import mobi.giza.compose.repository.GroupInboxRepository
@@ -83,6 +84,7 @@ class DatabaseGroupInboxRepository(
relays = InboxAnnouncements.relaysOf(database, roomId),
setUpRefusal = InboxKeyRitualManager.refusal(database, localChatRoom, userPublicKey),
waitingOn = ceremony?.takeIf { it.isRunning }?.let { waitingOn(it) }.orEmpty(),
rotationOwed = InboxRotation.isOwed(database, localChatRoom, userPublicKey),
)
}
}
@@ -62,6 +62,7 @@ import mobi.giza.compose.managers.ChillDkgRitualManager
import mobi.giza.compose.managers.FrostSigningManager
import mobi.giza.compose.managers.ShareRefreshManager
import mobi.giza.compose.managers.InboxKeyRitualManager
import mobi.giza.compose.managers.InboxRotation
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import mobi.giza.compose.identity.Identity
@@ -163,6 +164,10 @@ class DatabaseNostrRepository(
database = database,
userPublicKey = userPublicKey,
nostrPrivateKey = privateKey
) + InboxRotation.pass(
database = database,
userPublicKey = userPublicKey,
nostrPrivateKey = privateKey
)
}
}
@@ -58,6 +58,12 @@ object GovernanceFollowThrough {
/** One pass over everything owed. */
suspend fun pass(database: GizaDatabase, keyPair: KeyPair) = mutex.withLock {
rotationsOwed(database).forEach { proposal -> rotateAway(database, keyPair, proposal) }
// The group's inbox key, made over admins the room no longer has (docs/group-inbox.md,
// D14). After the share rotation above, which its refusal waits on.
keyPair.privKey?.let { secret ->
runCatching { InboxRotation.pass(database, keyPair.pubKey.toHexKey(), secret) }
.onFailure { if (it is CancellationException) throw it; logger.w("An inbox rotation pass failed: ${it.message}") }
}
if (!ExperimentalFeatures.shareRefresh) return@withLock
val me = keyPair.pubKey.toHexKey()
val privateKey = keyPair.privKey ?: return@withLock
@@ -67,6 +67,9 @@ object InboxKeyRitualManager {
const val ABANDONED = "Abandoned by an admin"
/** Why one of two crossing ceremonies ends: the other went on. */
const val CROSSED = "Another admin started the same ceremony at the same time, and that one went on"
fun deriveHostSecretKey(nostrPrivateKey: ByteArray, chatRoomId: String): PrivateKey =
PrivateKey(Crypto.sha256(HOST_KEY_TAG.encodeToByteArray() + nostrPrivateKey + chatRoomId.hexToByteArray()))
@@ -225,6 +228,13 @@ object InboxKeyRitualManager {
}
val participants = (named + innerEvent.pubKey).distinct().sorted()
// A generation this device already finished is not made twice: a late or replayed
// proposal for it opens nothing.
if (database.inboxKeyDao().getCompletedCeremonies(roomId, userPublicKey).any { it.generation >= generation }) {
logger.w("Inbox key proposal ${sessionId.take(8)} is for generation $generation, which this device has; dropping")
return null
}
val base = InboxKeyCeremony(
id = sessionId,
chatRoomId = roomId,
@@ -264,6 +274,19 @@ object InboxKeyRitualManager {
return database.inboxKeyDao().getCeremony(sessionId)
}
// Two admins who each started a rotation before hearing the other's: every device keeps
// the one whose session id sorts first and ends the other out loud, so all of them end
// up in the same ceremony and nobody holds a key the others do not.
val crossing = database.inboxKeyDao().getRunningCeremoniesIn(roomId)
.filter { it.userPublicKey == userPublicKey && it.id != sessionId }
crossing.forEach { other ->
val loser = if (other.id < sessionId) mine else other
val reason = CROSSED
fail(database, loser, reason, loser.coordinatorPublicKey)
if (loser.isParticipant()) broadcast(database, localChatRoom, loser, InboxKeyRitualEvents.FAILURE, reason)
}
if (database.inboxKeyDao().getCeremony(sessionId)?.isRunning != true) return database.inboxKeyDao().getCeremony(sessionId)
replayStored(database, localChatRoom, mine)
return database.inboxKeyDao().getCeremony(sessionId)
}
@@ -0,0 +1,70 @@
package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.CancellationException
import mobi.giza.compose.ExperimentalFeatures
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.InboxKeyState
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
/**
* When the group's inbox key has to change because its admins have (docs/group-inbox.md, D14).
*
* The rule is read off what every admin's device already holds, rather than off the change that
* caused it: the key was made by a ceremony over some set of admins, and the room's admin policy
* now names another. That covers a removal, a demotion, a step-down and a promotion the same way,
* and a change that landed while the app was closed.
*
* One admin starts it, so the devices do not race: the one whose key sorts first among the
* admins now. Nobody is asked -- the group's signature on the admin change was the decision --
* and if that admin's device is away, any admin can rotate by hand from the inbox's settings.
* It waits for whatever share rotation the same change owes ([InboxKeyRitualManager.refusal]
* reads the same hold), so the two run in turn.
*/
object InboxRotation {
private val logger = Logger.withTag("InboxRotation")
/**
* Whether [localChatRoom]'s inbox key was made over admins the room no longer has, as
* [userPublicKey]'s device sees it. False where there is no key, or the admins cannot be read.
*/
suspend fun isOwed(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey): Boolean {
val roomId = localChatRoom.chatRoom.id
val keys = database.inboxKeyDao().getKeys(roomId, userPublicKey).filter { it.state != InboxKeyState.WIPED }
if (keys.isEmpty()) return false
val newest = database.inboxKeyDao().getCompletedCeremonies(roomId, userPublicKey).firstOrNull() ?: return false
val admins = RoomAdmins.of(database, roomId)?.admins ?: return false
return admins != newest.participants().toSet()
}
/** Whether [userPublicKey] is the admin whose device starts an owed rotation in [chatRoomId]. */
suspend fun startsIt(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey): Boolean =
RoomAdmins.of(database, chatRoomId)?.admins?.minOrNull() == userPublicKey
/**
* Starts every rotation [userPublicKey]'s device owes. Run by the governance follow-through and
* the sweep; repeats nothing, since a running ceremony is not started twice. Returns how many it
* started.
*/
suspend fun pass(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Int {
if (!ExperimentalFeatures.groupInbox) return 0
var started = 0
database.inboxKeyDao().getHeldKeys(userPublicKey).map { it.chatRoomId }.distinct().forEach { roomId ->
val room = database.chatRoomDao().findChatRoomById(roomId) ?: return@forEach
if (!isOwed(database, room, userPublicKey) || !startsIt(database, roomId, userPublicKey)) return@forEach
if (database.inboxKeyDao().getRunningCeremoniesIn(roomId).any { it.userPublicKey == userPublicKey }) return@forEach
if (InboxKeyRitualManager.refusal(database, room, userPublicKey) != null) return@forEach
try {
InboxKeyRitualManager.propose(database, room, userPublicKey, nostrPrivateKey)
started += 1
logger.i("The admins of ${roomId.take(8)} changed; rotating its inbox key")
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
logger.w("Could not rotate the inbox key of ${roomId.take(8)}: ${e.message}")
}
}
return started
}
}
@@ -56,6 +56,8 @@ interface GroupInboxRepository {
val setUpRefusal: String?,
/** The admins a running ceremony waits on, by name. */
val waitingOn: List<String>,
/** The key was made over admins the room no longer has (D14). */
val rotationOwed: Boolean = false,
) {
val heldKey: InboxKey? get() = keys.firstOrNull { it.secretKey != null }
}
@@ -65,6 +65,7 @@ import mobi.giza.compose.resources.rotate_the_inbox_key
import mobi.giza.compose.resources.set_up_an_inbox
import mobi.giza.compose.resources.the_admins_are_making_the_inbox_key
import mobi.giza.compose.resources.the_ceremony_ended
import mobi.giza.compose.resources.the_admins_have_changed_since_this_key_was_made
import mobi.giza.compose.resources.the_inbox_key_ceremony_started
import mobi.giza.compose.resources.try_again
import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_announcement
@@ -222,6 +223,13 @@ fun GroupInboxSettingsScreen(
if (visibleKeys.isNotEmpty() && !running) {
Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) {
if (status.rotationOwed) {
Text(
stringResource(Res.string.the_admins_have_changed_since_this_key_was_made),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.error,
)
}
Text(stringResource(Res.string.rotate_explainer), style = MaterialTheme.typography.bodyMedium)
status.setUpRefusal?.let {
Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)