From 6aae56520b37ed4a5ab2eacf64c32cef1921d73f Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 09:01:14 +0200 Subject: [PATCH 1/4] fix: a member invited into a keyed room says it follows signed commits on joining An invited member of a robust group could never be made an admin. Making one needs the room to require the group's signature, which waits until every member's device has said it follows signed commits. A device said so when the room's screen was opened, or back when it heard another say it -- but the founders said it before the invite, at an epoch the new member cannot read, so it heard nothing, nobody said it again, and the room waited on a screen the member had no reason to open. A device now says it on joining (the Welcome path) and once each start (GovernanceSupport.announceAll), for members who joined before this. The waiting notice names who the room waits on and what for, instead of "X need to update Giza". Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 2 +- .../giza/compose/database/dao/NostrDao.kt | 9 +++++ .../repository/DatabaseChatRepository.kt | 2 + .../compose/managers/GovernanceSupport.kt | 37 +++++++++++++++++-- .../giza/compose/repository/ChatRepository.kt | 9 +++++ .../ui/view/model/SynchronizationViewModel.kt | 6 +++ .../compose/managers/GovernanceGateJvmTest.kt | 30 ++++++++++++++- docs/remove-convenient-groups.md | 35 ++++++++++++++++++ 8 files changed, 125 insertions(+), 5 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index f350245c..07484a99 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -127,7 +127,7 @@ Changes to who is in this group need the group's signature. It always keeps at least %1$d admins. Require the group's signature for changes From then on, adding or removing a member, or changing who the admins are, is proposed and has to be signed by the group before it happens. - Before changes can need the group's signature, %1$s need to update Giza. + Waiting for %1$s to open an up-to-date Giza. Until then, this group can't require its signature on changes, and nobody else can be made an admin. They'll be asked to accept, then the group signs it, and they'll hold a share of the group's key and be asked to approve its changes. Once the group signs it, they stay in the group as a member and their share of the group's key is rotated away. Asked; they become an admin once they accept and the group signs it diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index 54941a19..85a6da10 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -921,6 +921,15 @@ abstract class NostrDao( mlsGroup = group, ) + // That this device follows signed commits, said on + // joining. It cannot read the others saying it -- that + // was before its epoch -- so it would never answer, and + // the room would wait on it until its screen was opened. + // docs/remove-convenient-groups.md, "After the build". + if (group.currentGroupState().isCurrentProfile) { + GovernanceSupport.announce(database, nostrGroupId, group, userPublicKey) + } + // Save ChatRoom Relays... participants.filter { it.participantPublicKey != userPublicKey }.forEach { participant -> val publicKey = participant.participantPublicKey diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index d1bd0264..42c577aa 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -145,6 +145,8 @@ class DatabaseChatRepository( override suspend fun reconcileAdminFlags(): Int = AdminFlags.reconcileAll(database) + override suspend fun announceGovernanceSupport(): Int = GovernanceSupport.announceAll(database) + override suspend fun followThroughCeremonies(keyPair: KeyPair) = kotlinx.coroutines.coroutineScope { launch { CeremonyFollowThrough.observe(database = database, chatRepository = this@DatabaseChatRepository, keyPair = keyPair) } // What a governed room's signed changes need after they land: a rotation diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt index 88b4469e..b3f09f1f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt @@ -1,11 +1,13 @@ package mobi.giza.compose.managers +import co.touchlab.kermit.Logger import com.vitorpamplona.mls.group.MlsGroup import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import kotlin.time.Clock import kotlin.time.Instant import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.nostr.MarmotProfile import mobi.giza.compose.database.model.MarmotInnerEvent import mobi.giza.compose.nostr.frost.GovernanceSupportEvent @@ -16,9 +18,15 @@ import mobi.giza.compose.nostr.frost.GovernanceSupportEvent * The rule cannot be switched on while anybody in the room would be left behind * by it: a device that does not know it applies the bare commits Giza drops and * reads none of the envelopes, and is in a different group from the first change. - * So each device says, once per room, that it can follow -- and says it back when - * it hears another say it, which is how a member who never opens the room's screen - * still gets counted. + * So each device says, once per room, that it can follow: when it is welcomed in, + * when it starts, when the room's screen is opened, and back when it hears another + * say it. + * + * Joining has to be one of them. A member invited after the others said it cannot + * read what they said -- it was sent at an epoch before theirs -- so it never hears + * anybody to answer, and nobody says it again. Until it opened the room's screen + * the room waited on it, and nobody could be made an admin. See + * docs/remove-convenient-groups.md, "After the build". */ object GovernanceSupport { @@ -59,4 +67,27 @@ object GovernanceSupport { ) return true } + + /** + * [announce] for every room this device is in, for the members who joined + * before joining was one of the times it is said. Once per start, and a read + * with no write for a room that has it already. One room that will not open is + * logged and passed over. + * + * @return how many rooms it was said in now. + */ + suspend fun announceAll(database: GizaDatabase): Int = + database.chatRoomDao().getChatRoomIdsWithMlsState().count { chatRoomId -> + runCatching { + val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return@runCatching false + if (room.chatRoom.leftGroupAt != null || room.chatRoom.marmotProfile() != MarmotProfile.CURRENT) return@runCatching false + val group = database.marmotEngine.groupFor(room.routingId) ?: return@runCatching false + announce(database, chatRoomId, group, room.chatRoom.userPublicKey) + }.getOrElse { + logger.e("Could not say $chatRoomId follows signed commits", it) + false + } + } + + private val logger = Logger.withTag("GovernanceSupport") } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index e2eb7a0e..ce1e3d83 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -256,6 +256,13 @@ interface ChatRepository { */ suspend fun reconcileAdminFlags(): Int + /** + * Says, in every keyed room this device is in, that it follows signed commits, + * for the rooms joined before joining said it. Once per start. See + * `GovernanceSupport.announceAll`. + */ + suspend fun announceGovernanceSupport(): Int + /** * Takes every key ceremony [keyPair] coordinated from a key to a working room, * until cancelled: asks the group to sign its key state (a subgroup's parent to @@ -588,6 +595,8 @@ interface ChatRepository { override suspend fun reconcileAdminFlags(): Int = 0 + override suspend fun announceGovernanceSupport(): Int = 0 + override suspend fun sendChatMessage( text: String, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt index 0cb4d9b5..ec8383ce 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt @@ -255,6 +255,12 @@ class SynchronizationViewModel( // written. docs/robust-group-admins.md, Phase 6. runCatching { chatRepository.reconcileAdminFlags() } .onFailure { logger.e("Could not bring admin flags in line", it) } + // A member who joined a keyed room before joining said it + // follows signed commits, and never opened its screen, holds + // the room back from requiring them -- and so from making + // anyone an admin. docs/remove-convenient-groups.md. + runCatching { chatRepository.announceGovernanceSupport() } + .onFailure { logger.e("Could not say which rooms this device follows", it) } launch(Dispatchers.IO) { observePendingBroadcastNostrEventRequests(keyPair) } // Runs until cancelled rather than draining a queue, but it // belongs here for the same reason the pumps do: it needs the diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt index 6117e5ef..a07c52b2 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt @@ -264,10 +264,38 @@ class GovernanceGateJvmTest { return event.toGroupEvent(userHex)!! } + /** Takes back what this device said, as a device that joined before joining said it. */ + private suspend fun forgetOurSupport() { + db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(GovernanceSupportEvent.KIND)) + .filter { it.publicKey == userHex } + .forEach { db.marmotInnerEventDao().deleteById(it.id) } + assertFalse(userHex in GovernanceSupport.supporters(db, roomId)) + } + + @Test + fun `a member welcomed into a keyed room says it on joining`() = runBlocking { + // Nobody else says anything after the Welcome: what the others said before it + // is at an epoch this device cannot read. docs/remove-convenient-groups.md. + governedRoom(governed = false) + + assertTrue(userHex in GovernanceSupport.supporters(db, roomId), "joining did not say it") + assertEquals(setOf(dana.hex), GovernanceSupport.missing(db, roomId, appGroup())) + } + + @Test + fun `a device that joined before joining said it says it when it starts`() = runBlocking { + governedRoom(governed = false) + forgetOurSupport() + + assertEquals(1, chatRepository.announceGovernanceSupport()) + assertTrue(userHex in GovernanceSupport.supporters(db, roomId)) + assertEquals(0, chatRepository.announceGovernanceSupport(), "said twice") + } + @Test fun `hearing another member say it, this device says it back`() = runBlocking { governedRoom(governed = false) - assertFalse(userHex in GovernanceSupport.supporters(db, roomId)) + forgetOurSupport() says(dana) diff --git a/docs/remove-convenient-groups.md b/docs/remove-convenient-groups.md index 7384ff09..00f11b7d 100644 --- a/docs/remove-convenient-groups.md +++ b/docs/remove-convenient-groups.md @@ -389,6 +389,41 @@ detail screen, and a Bennu peer's convenient group still reaches them. they were written. Add a parenthetical saying it was removed here. - [README.md](./README.md): the table row, which this commit adds, says "built". +### After the build: an invited member holds the group back + +Found on a device, with this plan merged alongside member-admin-promotion. A robust +group's founders were admins holding shares; a member invited afterwards (D7 lets a +keyed room take one) was a plain member, as designed. But nobody could make them an +admin: the ⋮ on their row offered only **Remove from group**, and the room said it was +waiting for them to update Giza when they already had. + +Making a member of a keyed room an admin needs the room to require the group's +signature (`AdminGovernance.keyedChangesAllowed`), and that can be switched on only +once every member's device has said it follows signed commits +(`GovernanceSupport.missing`). A device said it when its room's screen was opened, and +back when it heard another member say it. The founders had all said it before the +invite, and an invited member cannot read anything sent at an epoch before its own -- +so it never heard one to answer, nobody said it again, and the room waited on a +screen the member had no reason to open. + +- **A device says it on joining.** The Welcome path in `NostrDao`, beside + `AdminFlags.reconcile`, for a current-profile room. +- **And once each start** (`GovernanceSupport.announceAll`, from + `SynchronizationViewModel` beside `reconcileAdminFlags`), for the members who joined + before joining said it. A room that has it already is a read and no write. +- **The notice** (`governance_waiting`) names who the room is waiting on and what for -- + "Waiting for Alice to open an up-to-date Giza. Until then, this group can't require + its signature on changes, and nobody else can be made an admin." -- instead of + telling them to update, which they often had, with a verb that did not agree with + one name. + +Pinned in `GovernanceGateJvmTest`: a welcomed member has said it before anybody else +speaks, and a device whose saying is taken back says it again at start, once. + +Once nobody is outstanding an admin still taps **Require the group's signature for +changes**, and the room's share rotation has to be on (a development build). Then the +member's row offers **Make admin**, and the member accepts on their own device. + ## Out of scope - **One-to-one chats** (D1). If they are to become robust, that needs its own plan. From 950ed247567a5ecd38bfbc01c065ae7479f520a2 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 09:16:22 +0200 Subject: [PATCH 2/4] feat: a keyed room switches on the group's signature by itself Requiring the group's signature for changes was a button an admin had to find on the room's screen. Nothing about it was a decision: the two conditions it waits on -- every member's device can follow, enough of them are admins -- were already checked in code. The button is gone. One device switches it on: the admin in the room's lowest leaf, which in a room as made is its creator (GovernanceSupport.switcherOf). Not every admin's, because two commits at one epoch are not settled for their authors (docs/marmot-v2.md, Phase 8); every device reads the same leaf, so they agree on one without talking. GovernanceFollowThrough runs the switch whenever a member says it follows signed commits, and on start. Not at creation: a Bennu or older-Giza founder would be cut off without anyone knowing, and a founding invite finished later is a bare commit a governed room refuses. The room switches seconds after its founders join instead. The screen names whose device it is waiting on. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 4 +- .../compose/database/dao/MarmotOutboundDao.kt | 2 +- .../repository/DatabaseChatRepository.kt | 2 +- .../managers/GovernanceFollowThrough.kt | 12 ++- .../compose/managers/GovernanceSupport.kt | 78 +++++++++++++++++++ .../ui/composable/ChatRoomDetailScreen.kt | 8 +- .../ui/composable/MemberAdminControls.kt | 31 +++++--- .../ui/view/model/ChatRoomDetailViewModel.kt | 4 - .../compose/ui/view/state/GovernanceStatus.kt | 8 +- .../compose/managers/GovernanceGateJvmTest.kt | 69 +++++++++++++++- docs/member-admin-promotion.md | 5 +- docs/remove-convenient-groups.md | 47 ++++++++++- 12 files changed, 236 insertions(+), 34 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 07484a99..9d7d98ca 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -125,7 +125,8 @@ Make admin and leave Disband group instead Changes to who is in this group need the group's signature. It always keeps at least %1$d admins. - Require the group's signature for changes + Turning on the group's signature for changes. + Changes will need the group's signature as soon as %1$s's Giza is next online. From then on, adding or removing a member, or changing who the admins are, is proposed and has to be signed by the group before it happens. Waiting for %1$s to open an up-to-date Giza. Until then, this group can't require its signature on changes, and nobody else can be made an admin. They'll be asked to accept, then the group signs it, and they'll hold a share of the group's key and be asked to approve its changes. @@ -135,7 +136,6 @@ Accept Accepted; the group signs it next Proposed; it happens once the group signs it - Sent; changes will need the group's signature once a relay accepts it Stepping down; you'll leave once a relay accepts it Remove from group Disband group diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt index 7f2378a7..46479132 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt @@ -1079,7 +1079,7 @@ abstract class MarmotOutboundDao( if (GovernanceGate.isGoverned(group)) return val missing = GovernanceSupport.missing(database, roomId, group) if (missing.isNotEmpty()) { - throw IllegalStateException("Waiting for ${missing.map { memberName(it) }.sorted().joinToString()} to update Giza") + throw IllegalStateException("Waiting for ${missing.map { memberName(it) }.sorted().joinToString()} to open an up-to-date Giza") } val floor = AdminGovernance.adminFloor(database, roomId, group) val admins = group.currentAdminIdentities() intersect AdminGovernance.members(group) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 42c577aa..c97a2c1a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -723,7 +723,7 @@ class DatabaseChatRepository( GovernanceGate.minimumAdmins(group)?.let { return GovernanceStatus.Governed(it) } if (room.chatRoom.leftGroupAt == null) GovernanceSupport.announce(database, chatRoomId, group, room.chatRoom.userPublicKey) val missing = GovernanceSupport.missing(database, chatRoomId, group) - return if (missing.isEmpty()) GovernanceStatus.Ready(AdminGovernance.adminFloor(database, chatRoomId, group)) + return if (missing.isEmpty()) GovernanceStatus.Ready(AdminGovernance.adminFloor(database, chatRoomId, group), GovernanceSupport.switcherOf(group)) else GovernanceStatus.Waiting(missing) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt index 9bdf87a7..d04e75aa 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt @@ -11,6 +11,7 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.conflate import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.nostr.frost.GroupKeyStateEvent +import mobi.giza.compose.nostr.frost.GovernanceSupportEvent import mobi.giza.compose.nostr.frost.PromotionEvents import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock @@ -37,7 +38,11 @@ object GovernanceFollowThrough { suspend fun observe(database: GizaDatabase, keyPair: KeyPair) { combine( database.governanceProposalDao().observeAll(), - database.marmotInnerEventDao().observeCountByKinds(listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER)), + // A member saying their device follows signed commits may be the last one + // a room was waiting on before its rule can be switched on. + database.marmotInnerEventDao().observeCountByKinds( + listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER, GovernanceSupportEvent.KIND) + ), database.groupSignedEventDao().observeByKind(GroupKeyStateEvent.KIND), ) { _, _, _ -> Unit } .conflate() @@ -55,8 +60,11 @@ object GovernanceFollowThrough { /** One pass over everything owed. */ suspend fun pass(database: GizaDatabase, keyPair: KeyPair) = mutex.withLock { rotationsOwed(database).forEach { proposal -> rotateAway(database, keyPair, proposal) } - if (!ExperimentalFeatures.shareRefresh) return@withLock val me = keyPair.pubKey.toHexKey() + // A keyed room's rule, switched on once every member can follow it, by the one + // device whose it is to switch. docs/remove-convenient-groups.md, "After the build". + GovernanceSupport.switchWhereOwed(database, me) + if (!ExperimentalFeatures.shareRefresh) return@withLock val privateKey = keyPair.privKey ?: return@withLock // Phase 8, the device that offered: an accepted offer is proposed for the diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt index b3f09f1f..5dbe3d24 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt @@ -1,14 +1,20 @@ package mobi.giza.compose.managers import co.touchlab.kermit.Logger +import com.vitorpamplona.marmot.groups.currentAdminIdentities +import com.vitorpamplona.marmot.groups.currentGroupState import com.vitorpamplona.mls.group.MlsGroup +import com.vitorpamplona.mls.tree.Credential import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import kotlinx.coroutines.CancellationException import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import kotlin.time.Clock import kotlin.time.Instant import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.nostr.MarmotProfile import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.nostr.frost.GovernanceSupportEvent /** @@ -18,6 +24,9 @@ import mobi.giza.compose.nostr.frost.GovernanceSupportEvent * The rule cannot be switched on while anybody in the room would be left behind * by it: a device that does not know it applies the bare commits Giza drops and * reads none of the envelopes, and is in a different group from the first change. + * Once everybody has, one device switches the rule on by itself ([switchWhereOwed]); + * nobody opens a screen or presses anything. + * * So each device says, once per room, that it can follow: when it is welcomed in, * when it starts, when the room's screen is opened, and back when it hears another * say it. @@ -89,5 +98,74 @@ object GovernanceSupport { } } + /** + * The one device that switches [group]'s rule on: the admin in its lowest leaf -- + * in a room as it was made, its creator. Null when no admin holds a leaf. + * + * One, because the library settles two commits made at the same epoch for every + * device that only watched them, but not for the two that made them: those swap + * branches and stay apart (docs/marmot-v2.md, Phase 8). Every admin switching the + * moment the last member said it would be exactly that race. The lowest leaf is + * read off the group's state, so every device names the same one without a word + * between them. + */ + fun switcherOf(group: MlsGroup): HexKey? { + val admins = group.currentAdminIdentities() + return group.members() + .sortedBy { (leafIndex, _) -> leafIndex } + .firstNotNullOfOrNull { (_, leaf) -> + (leaf.credential as? Credential.Basic)?.identity?.toHexKey()?.takeIf { it in admins } + } + } + + /** + * Whether this device owes [room] the switch now: a keyed room on the current + * profile, open, not yet requiring the group's signature, whose [switcherOf] is + * this device's account, where every member has said they follow signed commits + * and enough of them are admins. The checks `requireSignatures` makes, read first + * so a room that is not ready is passed over rather than refused. + */ + suspend fun switchOwed(database: GizaDatabase, room: LocalChatRoom, group: MlsGroup): Boolean { + val me = room.chatRoom.userPublicKey + if (room.chatRoom.leftGroupAt != null || room.chatRoom.marmotProfile() != MarmotProfile.CURRENT) return false + if (!AdminGovernance.isKeyedRoom(group) || GovernanceGate.isGoverned(group)) return false + if (group.currentGroupState().isDisbanded) return false + if (switcherOf(group) != me) return false + if (missing(database, room.chatRoom.id, group).isNotEmpty()) return false + val admins = group.currentAdminIdentities() intersect AdminGovernance.members(group) + return admins.size >= AdminGovernance.adminFloor(database, room.chatRoom.id, group) + } + + /** + * Switches the rule on in every room of [me]'s that is owed it -- [switchOwed] -- + * saying first, where it has not, that this device follows signed commits, since + * it is a member too. Run by `GovernanceFollowThrough` whenever a member says it, + * and when it starts, so the switch needs nobody to open a screen or press + * anything. A switch still waiting for a relay is not sent twice; one that fails + * is logged and tried again on the next pass. + * + * @return how many rooms a switch was sent in. + */ + suspend fun switchWhereOwed(database: GizaDatabase, me: HexKey): Int = + database.chatRoomDao().getChatRoomIdsWithMlsState().count { chatRoomId -> + runCatching { + val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return@runCatching false + if (room.chatRoom.userPublicKey != me) return@runCatching false + val engine = database.marmotEngine + val group = engine.groupFor(room.routingId) ?: return@runCatching false + if (switcherOf(group) != me) return@runCatching false + announce(database, chatRoomId, group, me) + if (!switchOwed(database, room, group)) return@runCatching false + if (!engine.gate.canPrepareLocalCommit(room.routingId)) return@runCatching false + database.marmotOutboundDao().requireSignatures(room) + logger.i("Switched on the group's signature for changes in $chatRoomId") + true + }.getOrElse { + if (it is CancellationException) throw it + logger.w("Couldn't switch on the group's signature in $chatRoomId: ${it.message}") + false + } + } + private val logger = Logger.withTag("GovernanceSupport") } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index bd8af3ab..319166fe 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -88,7 +88,6 @@ import mobi.giza.compose.ui.theme.spacing import mobi.giza.compose.resources.couldn_t_leave_the_group import mobi.giza.compose.resources.admin_change_requested import mobi.giza.compose.resources.stepping_down_to_leave -import mobi.giza.compose.resources.require_signatures_sent import mobi.giza.compose.resources.change_proposed import mobi.giza.compose.resources.admin_offer_sent import mobi.giza.compose.resources.promotion_accepted @@ -244,7 +243,6 @@ fun ChatRoomDetailScreen( val couldNotLeave = stringResource(Res.string.couldn_t_leave_the_group) val adminChangeRequested = stringResource(Res.string.admin_change_requested) val steppingDownToLeave = stringResource(Res.string.stepping_down_to_leave) - val requireSignaturesSent = stringResource(Res.string.require_signatures_sent) val changeProposed = stringResource(Res.string.change_proposed) val adminOfferSent = stringResource(Res.string.admin_offer_sent) val promotionAccepted = stringResource(Res.string.promotion_accepted) @@ -1188,11 +1186,7 @@ fun ChatRoomDetailScreen( governance = governance, canGovern = chatRoomDetailUIState.canGovern, nameOf = nameOf, - onRequireSignatures = { - chatRoomDetailViewModel.requireSignatures(chatRoomDetailUIState.localChatRoom) { failure -> - notify(failure ?: requireSignaturesSent) - } - }, + me = chatRoomDetailUIState.localChatRoom.chatRoom.userPublicKey, ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt index 0a15f180..6b9abaf1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt @@ -34,7 +34,8 @@ import mobi.giza.compose.resources.cancel import mobi.giza.compose.resources.disband_group_instead import mobi.giza.compose.resources.governance_on import mobi.giza.compose.resources.governance_waiting -import mobi.giza.compose.resources.require_signatures +import mobi.giza.compose.resources.governance_switch_waits_for +import mobi.giza.compose.resources.governance_switching import mobi.giza.compose.resources.require_signatures_explainer import mobi.giza.compose.resources.make_admin import mobi.giza.compose.resources.make_admin_and_leave @@ -203,16 +204,20 @@ internal fun LeaveAsAdminDialog( /** * Whether a keyed room's changes need the group's signature. Once they do, a line - * saying so; before, for an admin, the switch -- or who it is still waiting on, - * since switching it on with a member whose device cannot follow would leave them - * in a different group from the first change. docs/member-admin-promotion.md, Phase 4b. + * saying so; before, for an admin, whose device is switching it on -- or who it is + * still waiting on, since switching it on with a member whose device cannot follow + * would leave them in a different group from the first change. + * docs/member-admin-promotion.md, Phase 4b. + * + * Nothing to press: one device switches it on by itself once everybody can follow. + * docs/remove-convenient-groups.md, "After the build". */ @Composable internal fun GovernanceSection( governance: GovernanceStatus, canGovern: Boolean, nameOf: (HexKey) -> String, - onRequireSignatures: () -> Unit, + me: HexKey, ) { val explainer = Modifier.padding( horizontal = MaterialTheme.spacing.containerPadding, @@ -226,11 +231,17 @@ internal fun GovernanceSection( color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = explainer, ) - is GovernanceStatus.Ready -> if (canGovern) { - TextButton(onClick = onRequireSignatures) { - Icon(Icons.Default.Verified, contentDescription = Decorative) - Text(stringResource(Res.string.require_signatures), modifier = Modifier.padding(start = MaterialTheme.spacing.relatedGap)) - } + is GovernanceStatus.Ready -> if (canGovern && governance.switcher != null) { + Text( + text = if (governance.switcher == me) { + stringResource(Res.string.governance_switching) + } else { + stringResource(Res.string.governance_switch_waits_for, nameOf(governance.switcher)) + }, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = explainer, + ) Text( text = stringResource(Res.string.require_signatures_explainer), style = MaterialTheme.typography.bodySmall, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 21fc93d2..a82e252c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -266,10 +266,6 @@ class ChatRoomDetailViewModel( } } - /** Makes the room's changes need the group's signature. docs/member-admin-promotion.md, Phase 4b. */ - fun requireSignatures(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) = - adminAction(onDone) { chatRepository.requireSignatures(localChatRoom) } - /** Accepts becoming an admin of a keyed room. docs/member-admin-promotion.md, Phase 8. */ fun acceptPromotion(localChatRoom: LocalChatRoom, offerId: HexKey, onDone: (String?) -> Unit) = adminAction(onDone) { chatRepository.acceptPromotion(localChatRoom, offerId)?.let { throw IllegalStateException(it) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt index cc6f0897..412024ce 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt @@ -10,8 +10,12 @@ sealed interface GovernanceStatus { /** It does: every change is proposed, signed by the group, and only then applied. */ data class Governed(val minimumAdmins: Int) : GovernanceStatus - /** It does not yet, and every member's device could follow if it were switched on. */ - data class Ready(val minimumAdmins: Int) : GovernanceStatus + /** + * It does not yet, and every member's device could follow: [switcher]'s device + * switches it on by itself, the next time it is online. Null [switcher] when no + * admin holds a leaf. docs/remove-convenient-groups.md, "After the build". + */ + data class Ready(val minimumAdmins: Int, val switcher: HexKey?) : GovernanceStatus /** It does not yet, and these members have not said their device could follow. */ data class Waiting(val missing: Set) : GovernanceStatus diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt index a07c52b2..240f8138 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt @@ -292,6 +292,73 @@ class GovernanceGateJvmTest { assertEquals(0, chatRepository.announceGovernanceSupport(), "said twice") } + private val frank = MarmotStandIn() + + /** Frank joins Dana's room after Erin, by Dana's bare commit; Erin and the app apply it. */ + private suspend fun frankJoins() { + MarmotStandIn.seedProfile(db, frank.hex, "Frank") + frank.makeBundle() + val add = dana.commitLocally(routingId) { dana.manager.addMember(routingId, frank.bundle.keyPackage.toTlsBytes()) } + frank.manager.processWelcome(assertNotNull(add.welcomeBytes), frank.bundle) + frank.inbound.trackGroup(routingId) + val event = commitEvent(add) + erin.inbound.processGroupEvent(event) + MarmotStandIn.storeInApp(db, user, event) + } + + @Test + fun `the first admin's device switches the rule on by itself once everyone has said it`() = runBlocking { + // Dana made the room and holds its first leaf; once she is no admin, the app's + // leaf is the lowest an admin holds, and the switch is the app's to make. + governedRoom(governed = false) + erinJoins() + frankJoins() + val admins = listOf(userHex, erin.hex, frank.hex) + val commit = dana.commitLocally(routingId) { + val staged = dana.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins).encode()) + dana.manager.installState(routingId, staged.pendingState) + staged.result + } + val event = commitEvent(commit) + erin.inbound.processGroupEvent(event) + frank.inbound.processGroupEvent(event) + MarmotStandIn.storeInApp(db, user, event) + assertEquals(userHex, GovernanceSupport.switcherOf(appGroup())) + + says(dana) + says(erin) + GovernanceFollowThrough.pass(db, user) + assertFalse(GovernanceGate.isGoverned(appGroup()), "switched on before Frank said it") + + says(frank) + GovernanceFollowThrough.pass(db, user) + okTheLatestCommit() + + assertTrue(GovernanceGate.isGoverned(appGroup()), "nobody pressed anything, and nothing happened") + assertEquals(0, GovernanceSupport.switchWhereOwed(db, userHex), "switched twice") + } + + @Test + fun `a device that is not the first admin leaves the switch to it`() = runBlocking { + // Every admin's device switching the moment the last member said it would be two + // commits at one epoch, which the library cannot settle for their authors. + governedRoom(governed = false) + erinJoins() + danaSetsAdminsBare(listOf(dana.hex, userHex, erin.hex)) + says(dana) + says(erin) + assertEquals(GovernanceStatus.Ready(minimumAdmins = 3, switcher = dana.hex), chatRepository.governanceStatus(roomId)) + + GovernanceFollowThrough.pass(db, user) + + assertEquals(0, GovernanceSupport.switchWhereOwed(db, userHex)) + assertFalse(GovernanceGate.isGoverned(appGroup())) + assertTrue(db.marmotCommitResultDao().let { dao -> + db.nostrEventDao().getMLSGroupEvents(since = kotlin.time.Instant.fromEpochSeconds(0), limit = 50) + .none { it.kind == GroupEvent.KIND && dao.getMarmotCommitRequestById(it.id) != null } + }, "the app sent a commit of its own") + } + @Test fun `hearing another member say it, this device says it back`() = runBlocking { governedRoom(governed = false) @@ -316,7 +383,7 @@ class GovernanceGateJvmTest { assertTrue("Erin" in refusal.message.orEmpty(), refusal.message) says(erin) - assertEquals(GovernanceStatus.Ready(minimumAdmins = 3), chatRepository.governanceStatus(roomId)) + assertEquals(GovernanceStatus.Ready(minimumAdmins = 3, switcher = dana.hex), chatRepository.governanceStatus(roomId)) chatRepository.requireSignatures(room()) val switch = okTheLatestCommit() diff --git a/docs/member-admin-promotion.md b/docs/member-admin-promotion.md index 9926cad8..2baea9e3 100644 --- a/docs/member-admin-promotion.md +++ b/docs/member-admin-promotion.md @@ -460,7 +460,10 @@ does not; nothing changes in a room without the marker. records who has said it. - **Require signatures for changes**, on a keyed room's detail screen, for an admin, once every current member has said it. It is one bare commit adding the marker line to the - profile description. Until every member has, the screen names who has not. + profile description. Until every member has, the screen names who has not. (Since + made automatic -- one device, the admin in the lowest leaf, sends it once everybody has + said it, and the button is gone; [remove-convenient-groups.md](./remove-convenient-groups.md), + "After the build".) - An invite into a governed room is refused for an account that has not said it, with words that say why, once it is in the room (it says so from its own device on joining). diff --git a/docs/remove-convenient-groups.md b/docs/remove-convenient-groups.md index 00f11b7d..d004c08a 100644 --- a/docs/remove-convenient-groups.md +++ b/docs/remove-convenient-groups.md @@ -420,9 +420,50 @@ screen the member had no reason to open. Pinned in `GovernanceGateJvmTest`: a welcomed member has said it before anybody else speaks, and a device whose saying is taken back says it again at start, once. -Once nobody is outstanding an admin still taps **Require the group's signature for -changes**, and the room's share rotation has to be on (a development build). Then the -member's row offers **Make admin**, and the member accepts on their own device. +#### The switch is nobody's to press + +Even then an admin had to find **Require the group's signature for changes** on the +room's screen and tap it. Nothing about the switch is a decision: the two conditions it +waits on -- every member can follow, enough of them are admins -- are already checked in +code, and a group whose point is a key its members hold together is a group that means +to sign its changes. So the button is gone, and one device switches the rule on by +itself. + +- **Which device.** The admin in the room's lowest leaf (`GovernanceSupport.switcherOf`) + -- in a room as it was made, its creator. Not every admin's: two commits at one epoch + are settled for every device that watched them but not for the two that made them, + which swap branches and stay apart ([marmot-v2.md](./marmot-v2.md), Phase 8). Every + device reads the same leaf off the same state, so they agree on one without a word + between them. +- **When.** `GovernanceFollowThrough`, which already runs while the app is open and + reads everything again on each pass, now passes whenever a member says it follows + signed commits, and on start. A room that is owed the switch (`switchOwed`) gets the + commit `requireSignatures` always sent; one still waiting for a relay is not sent + twice. +- **The screen** says which device it is waiting on: "Turning on the group's signature + for changes." on that device, "Changes will need the group's signature as soon as + Bob's Giza is next online." on the others. + +*Not at creation*, though that was the first preference. A room born governed -- +the marker in its epoch-0 description -- would need no switch, but: + +- a Bennu founder, or one on an older Giza build, takes part in the ceremony like + anyone else, and would apply the bare commits Giza drops: in a different group from + the first change, with nobody told. The support check is the only thing that knows, + and it can only be asked once the room exists; +- a founder whose founding invite has to be finished later (robust-group-admins, + Phase 4) is added by a bare commit, which the founders already in a governed room + would refuse. + +Switching once everybody has joined and said it costs the seconds it takes the +founders' devices to process their Welcomes, and costs nothing when one of them cannot +follow -- the room simply stays as it is. + +Pinned in `GovernanceGateJvmTest`: the first admin's device switches by itself once the +last member says it, and not before; any other admin's device sends nothing. + +Then the member's row offers **Make admin** -- with the room's share rotation on, which +is a development build for now -- and the member accepts on their own device. ## Out of scope From 1ccd8c7f0958a7e34202a6b707b849999ae403aa Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 09:28:47 +0200 Subject: [PATCH 3/4] feat: a keyed room is born needing the group's signature; the switch is gone The rule that a keyed room's changes need the group's signature was switched on after founding, once every member's device had said it could follow signed commits. That protected Bennu members and older Giza builds from being left behind by the first signed change. Giza is in development and keeps compatibility with neither, so the switch protected nobody, and it kept an invited member from ever being made an admin. MarmotGroupCreation.createFor now writes GovernanceMarker's line, with the floor the ceremony's quorum sets, into the room's epoch-0 description. Founding still needs no signature: the founding invite is the creator's commit while it is the only member, which no other device processes. Removed: GovernanceSupport and its event (30372), the announcements on joining, at start and in answer, the automatic switch and requireSignatures, and the screen's waiting and ready states. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 4 - .../compose/database/dao/MarmotOutboundDao.kt | 37 ---- .../giza/compose/database/dao/NostrDao.kt | 21 --- .../repository/DatabaseChatRepository.kt | 13 +- .../managers/GovernanceFollowThrough.kt | 12 +- .../giza/compose/managers/GovernanceMarker.kt | 8 +- .../compose/managers/GovernanceSupport.kt | 171 ----------------- .../compose/managers/MarmotGroupCreation.kt | 13 ++ .../compose/nostr/frost/GovernanceEvents.kt | 20 +- .../giza/compose/repository/ChatRepository.kt | 12 -- .../ui/composable/ChatRoomDetailScreen.kt | 7 +- .../ui/composable/MemberAdminControls.kt | 72 ++------ .../ui/view/model/SynchronizationViewModel.kt | 6 - .../compose/ui/view/state/GovernanceStatus.kt | 20 +- .../compose/managers/AdminChangesJvmTest.kt | 8 +- .../compose/managers/GovernanceGateJvmTest.kt | 174 ------------------ .../compose/managers/GroupLifecycleJvmTest.kt | 2 +- .../managers/MarmotGroupCreationJvmTest.kt | 17 +- .../managers/PublishBeforeApplyJvmTest.kt | 2 +- .../managers/RobustGroupAdminsJvmTest.kt | 33 ++++ docs/member-admin-promotion.md | 8 +- docs/remove-convenient-groups.md | 102 ++++------ 22 files changed, 138 insertions(+), 624 deletions(-) delete mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 9d7d98ca..20f55003 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -125,10 +125,6 @@ Make admin and leave Disband group instead Changes to who is in this group need the group's signature. It always keeps at least %1$d admins. - Turning on the group's signature for changes. - Changes will need the group's signature as soon as %1$s's Giza is next online. - From then on, adding or removing a member, or changing who the admins are, is proposed and has to be signed by the group before it happens. - Waiting for %1$s to open an up-to-date Giza. Until then, this group can't require its signature on changes, and nobody else can be made an admin. They'll be asked to accept, then the group signs it, and they'll hold a share of the group's key and be asked to approve its changes. Once the group signs it, they stay in the group as a member and their share of the group's key is rotated away. Asked; they become an admin once they accept and the group signs it diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt index 46479132..4ff8f458 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt @@ -69,7 +69,6 @@ import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.managers.GovernanceGate import mobi.giza.compose.managers.GovernanceManager import mobi.giza.compose.managers.GovernanceMarker -import mobi.giza.compose.managers.GovernanceSupport import mobi.giza.compose.managers.ChronicleManager import mobi.giza.compose.managers.MarmotGroupFactory import mobi.giza.compose.managers.MarmotInboundManager @@ -1060,42 +1059,6 @@ abstract class MarmotOutboundDao( } } - /** - * Makes a keyed room's changes need the group's signature from the next epoch: - * one ordinary commit adding [GovernanceMarker]'s line to the profile - * description, with the floor the room's quorum sets. It is the room's last bare - * commit, and every device that applies it enforces the rule from the state it - * just applied. docs/member-admin-promotion.md, D4 and Phase 4b. - * - * Refused while any member has not said their device can follow signed commits - * -- they would be left in a different group by the first change -- and while - * the room has fewer admins than the floor it would set. - */ - @Transaction - open suspend fun requireSignatures(localChatRoom: LocalChatRoom) { - val group = governedGroup(localChatRoom) - val roomId = localChatRoom.chatRoom.id - check(AdminGovernance.isKeyedRoom(group)) { "Only a group with a shared key can require its signature" } - if (GovernanceGate.isGoverned(group)) return - val missing = GovernanceSupport.missing(database, roomId, group) - if (missing.isNotEmpty()) { - throw IllegalStateException("Waiting for ${missing.map { memberName(it) }.sorted().joinToString()} to open an up-to-date Giza") - } - val floor = AdminGovernance.adminFloor(database, roomId, group) - val admins = group.currentAdminIdentities() intersect AdminGovernance.members(group) - check(admins.size >= floor) { "A group with a shared key needs at least $floor admins first" } - - publishGatedCommit(localChatRoom) { manager, id -> - val live = manager.getGroup(id) ?: throw MarmotMissingChatGroupException("No live group for $id") - val profile = live.currentGroupState().profile ?: throw IllegalStateException("The group has no profile to record the rule in") - manager.stageAppDataUpdate( - id, - GroupProfileV1.COMPONENT_ID, - GroupProfileV1(profile.name, GovernanceMarker.describe(profile.description, floor)).encode(), - ) - } - } - /** Whether [memberPublicKey] holds a live share of the room's key, with rotation on. */ private suspend fun holdsLiveShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean = ExperimentalFeatures.shareRefresh && diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index 85a6da10..b18d349a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -7,8 +7,6 @@ import com.vitorpamplona.marmot.GroupEventResult import com.vitorpamplona.marmot.groups.MarmotGroupPolicy import com.vitorpamplona.marmot.groups.currentAdminIdentities import mobi.giza.compose.managers.GovernanceGate -import mobi.giza.compose.managers.GovernanceSupport -import mobi.giza.compose.nostr.frost.GovernanceSupportEvent import mobi.giza.compose.nostr.frost.GovernanceEvents import mobi.giza.compose.nostr.frost.GovernanceCarrierEvent import mobi.giza.compose.nostr.frost.OwnCommitEvent @@ -921,15 +919,6 @@ abstract class NostrDao( mlsGroup = group, ) - // That this device follows signed commits, said on - // joining. It cannot read the others saying it -- that - // was before its epoch -- so it would never answer, and - // the room would wait on it until its screen was opened. - // docs/remove-convenient-groups.md, "After the build". - if (group.currentGroupState().isCurrentProfile) { - GovernanceSupport.announce(database, nostrGroupId, group, userPublicKey) - } - // Save ChatRoom Relays... participants.filter { it.participantPublicKey != userPublicKey }.forEach { participant -> val publicKey = participant.participantPublicKey @@ -1705,16 +1694,6 @@ abstract class NostrDao( // A change to a governed room, inside the group's signature or, // for a member's own leave, its committer's. Checked, and its // commit applied, only here (docs/member-admin-promotion.md). - // Another member says their device follows signed commits: - // this one says so back, once, so that a member who never - // opens the room's screen is still counted (Phase 4b). - innerEvent.kind == GovernanceSupportEvent.KIND -> - if (localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { - database.marmotEngine.groupFor(localChatRoom.routingId)?.let { group -> - GovernanceSupport.announce(database, localChatRoom.chatRoom.id, group, activeKeyPair.pubKey.toHex()) - } - } - innerEvent.kind == OwnCommitEvent.KIND -> admitEnvelopedCommit(localChatRoom, innerEvent, activeKeyPair) innerEvent.kind == GovernanceCarrierEvent.KIND -> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index c97a2c1a..0ecce1c0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -14,7 +14,6 @@ import mobi.giza.compose.managers.AdminGovernance import mobi.giza.compose.managers.GovernanceGate import mobi.giza.compose.managers.PromotionManager import mobi.giza.compose.managers.GovernanceFollowThrough -import mobi.giza.compose.managers.GovernanceSupport import mobi.giza.compose.managers.MarmotInboundManager import mobi.giza.compose.managers.AdminFlags import mobi.giza.compose.managers.FoundingAdmins @@ -145,8 +144,6 @@ class DatabaseChatRepository( override suspend fun reconcileAdminFlags(): Int = AdminFlags.reconcileAll(database) - override suspend fun announceGovernanceSupport(): Int = GovernanceSupport.announceAll(database) - override suspend fun followThroughCeremonies(keyPair: KeyPair) = kotlinx.coroutines.coroutineScope { launch { CeremonyFollowThrough.observe(database = database, chatRepository = this@DatabaseChatRepository, keyPair = keyPair) } // What a governed room's signed changes need after they land: a rotation @@ -720,15 +717,7 @@ class DatabaseChatRepository( if (room.chatRoom.marmotProfile() != MarmotProfile.CURRENT) return null val group = database.marmotEngine.groupFor(room.routingId) ?: return null if (!AdminGovernance.isKeyedRoom(group)) return null - GovernanceGate.minimumAdmins(group)?.let { return GovernanceStatus.Governed(it) } - if (room.chatRoom.leftGroupAt == null) GovernanceSupport.announce(database, chatRoomId, group, room.chatRoom.userPublicKey) - val missing = GovernanceSupport.missing(database, chatRoomId, group) - return if (missing.isEmpty()) GovernanceStatus.Ready(AdminGovernance.adminFloor(database, chatRoomId, group), GovernanceSupport.switcherOf(group)) - else GovernanceStatus.Waiting(missing) - } - - override suspend fun requireSignatures(localChatRoom: LocalChatRoom) { - database.marmotOutboundDao().requireSignatures(localChatRoom) + return GovernanceGate.minimumAdmins(group)?.let { GovernanceStatus.Governed(it) } } override suspend fun promoteMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt index d04e75aa..9bdf87a7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt @@ -11,7 +11,6 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.conflate import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.nostr.frost.GroupKeyStateEvent -import mobi.giza.compose.nostr.frost.GovernanceSupportEvent import mobi.giza.compose.nostr.frost.PromotionEvents import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock @@ -38,11 +37,7 @@ object GovernanceFollowThrough { suspend fun observe(database: GizaDatabase, keyPair: KeyPair) { combine( database.governanceProposalDao().observeAll(), - // A member saying their device follows signed commits may be the last one - // a room was waiting on before its rule can be switched on. - database.marmotInnerEventDao().observeCountByKinds( - listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER, GovernanceSupportEvent.KIND) - ), + database.marmotInnerEventDao().observeCountByKinds(listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER)), database.groupSignedEventDao().observeByKind(GroupKeyStateEvent.KIND), ) { _, _, _ -> Unit } .conflate() @@ -60,11 +55,8 @@ object GovernanceFollowThrough { /** One pass over everything owed. */ suspend fun pass(database: GizaDatabase, keyPair: KeyPair) = mutex.withLock { rotationsOwed(database).forEach { proposal -> rotateAway(database, keyPair, proposal) } - val me = keyPair.pubKey.toHexKey() - // A keyed room's rule, switched on once every member can follow it, by the one - // device whose it is to switch. docs/remove-convenient-groups.md, "After the build". - GovernanceSupport.switchWhereOwed(database, me) if (!ExperimentalFeatures.shareRefresh) return@withLock + val me = keyPair.pubKey.toHexKey() val privateKey = keyPair.privKey ?: return@withLock // Phase 8, the device that offered: an accepted offer is proposed for the diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceMarker.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceMarker.kt index 90453b3a..3c3c0ef9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceMarker.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceMarker.kt @@ -5,8 +5,12 @@ package mobi.giza.compose.managers * group's signature, and how few admins it may ever have. docs/member-admin-promotion.md, * D4 and D8. * - * In the group's state, so every device that applies the commit adding it enforces - * the rule from the same epoch, and reads the same floor: a floor each device worked + * Written into a keyed room's epoch-0 description when it is made + * (`MarmotGroupCreation.createFor`), so there is no later moment it is switched on + * and nobody it waits for; docs/remove-convenient-groups.md, "After the build". + * + * In the group's state, so every device enforces the rule from the same epoch, and + * reads the same floor: a floor each device worked * out for itself from the ceremony it happens to hold would differ between a founder * and a member welcomed later, and the two would disagree about a commit. The * description is the one free text the current profile offers, which is why diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt deleted file mode 100644 index 5dbe3d24..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt +++ /dev/null @@ -1,171 +0,0 @@ -package mobi.giza.compose.managers - -import co.touchlab.kermit.Logger -import com.vitorpamplona.marmot.groups.currentAdminIdentities -import com.vitorpamplona.marmot.groups.currentGroupState -import com.vitorpamplona.mls.group.MlsGroup -import com.vitorpamplona.mls.tree.Credential -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import kotlinx.coroutines.CancellationException -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import kotlin.time.Clock -import kotlin.time.Instant -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.nostr.MarmotProfile -import mobi.giza.compose.database.model.MarmotInnerEvent -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.nostr.frost.GovernanceSupportEvent - -/** - * Who in a keyed room has said their device follows signed commits, and this - * device saying it. docs/member-admin-promotion.md, D4 and Phase 4b. - * - * The rule cannot be switched on while anybody in the room would be left behind - * by it: a device that does not know it applies the bare commits Giza drops and - * reads none of the envelopes, and is in a different group from the first change. - * Once everybody has, one device switches the rule on by itself ([switchWhereOwed]); - * nobody opens a screen or presses anything. - * - * So each device says, once per room, that it can follow: when it is welcomed in, - * when it starts, when the room's screen is opened, and back when it hears another - * say it. - * - * Joining has to be one of them. A member invited after the others said it cannot - * read what they said -- it was sent at an epoch before theirs -- so it never hears - * anybody to answer, and nobody says it again. Until it opened the room's screen - * the room waited on it, and nobody could be made an admin. See - * docs/remove-convenient-groups.md, "After the build". - */ -object GovernanceSupport { - - /** The accounts that have said, in [chatRoomId], that they follow signed commits. */ - suspend fun supporters(database: GizaDatabase, chatRoomId: String): Set = - database.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(GovernanceSupportEvent.KIND)) - .filter { row -> row.tags.any { it.size >= 2 && it[0] == GovernanceSupportEvent.VERSION_TAG && it[1] == GovernanceSupportEvent.VERSION } } - .map { it.publicKey } - .toSet() - - /** The members of [group] who have not said it yet. */ - suspend fun missing(database: GizaDatabase, chatRoomId: String, group: MlsGroup): Set = - AdminGovernance.members(group) - supporters(database, chatRoomId) - - /** - * Says, for [me], that this device follows signed commits in [chatRoomId] -- once: - * nothing happens when it already has. Only in a keyed room, which is the only - * kind the rule can be switched on in. Returns whether it said it now. - */ - suspend fun announce(database: GizaDatabase, chatRoomId: String, group: MlsGroup, me: HexKey): Boolean { - if (!AdminGovernance.isKeyedRoom(group)) return false - if (me in supporters(database, chatRoomId)) return false - val tags = GovernanceSupportEvent.assembleTags(chatRoomId) - val createdAt = Clock.System.now().epochSeconds - val id = EventHasher.hashId(pubKey = me, createdAt = createdAt, kind = GovernanceSupportEvent.KIND, tags = tags, content = "") - // Unsent: the outbound worker puts an inner event with no group event behind - // it into the room, as it does for every manager's messages. - database.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = id, - publicKey = me, - kind = GovernanceSupportEvent.KIND, - createdAt = Instant.fromEpochSeconds(createdAt), - tags = tags, - content = "", - chatRoomId = chatRoomId, - ) - ) - return true - } - - /** - * [announce] for every room this device is in, for the members who joined - * before joining was one of the times it is said. Once per start, and a read - * with no write for a room that has it already. One room that will not open is - * logged and passed over. - * - * @return how many rooms it was said in now. - */ - suspend fun announceAll(database: GizaDatabase): Int = - database.chatRoomDao().getChatRoomIdsWithMlsState().count { chatRoomId -> - runCatching { - val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return@runCatching false - if (room.chatRoom.leftGroupAt != null || room.chatRoom.marmotProfile() != MarmotProfile.CURRENT) return@runCatching false - val group = database.marmotEngine.groupFor(room.routingId) ?: return@runCatching false - announce(database, chatRoomId, group, room.chatRoom.userPublicKey) - }.getOrElse { - logger.e("Could not say $chatRoomId follows signed commits", it) - false - } - } - - /** - * The one device that switches [group]'s rule on: the admin in its lowest leaf -- - * in a room as it was made, its creator. Null when no admin holds a leaf. - * - * One, because the library settles two commits made at the same epoch for every - * device that only watched them, but not for the two that made them: those swap - * branches and stay apart (docs/marmot-v2.md, Phase 8). Every admin switching the - * moment the last member said it would be exactly that race. The lowest leaf is - * read off the group's state, so every device names the same one without a word - * between them. - */ - fun switcherOf(group: MlsGroup): HexKey? { - val admins = group.currentAdminIdentities() - return group.members() - .sortedBy { (leafIndex, _) -> leafIndex } - .firstNotNullOfOrNull { (_, leaf) -> - (leaf.credential as? Credential.Basic)?.identity?.toHexKey()?.takeIf { it in admins } - } - } - - /** - * Whether this device owes [room] the switch now: a keyed room on the current - * profile, open, not yet requiring the group's signature, whose [switcherOf] is - * this device's account, where every member has said they follow signed commits - * and enough of them are admins. The checks `requireSignatures` makes, read first - * so a room that is not ready is passed over rather than refused. - */ - suspend fun switchOwed(database: GizaDatabase, room: LocalChatRoom, group: MlsGroup): Boolean { - val me = room.chatRoom.userPublicKey - if (room.chatRoom.leftGroupAt != null || room.chatRoom.marmotProfile() != MarmotProfile.CURRENT) return false - if (!AdminGovernance.isKeyedRoom(group) || GovernanceGate.isGoverned(group)) return false - if (group.currentGroupState().isDisbanded) return false - if (switcherOf(group) != me) return false - if (missing(database, room.chatRoom.id, group).isNotEmpty()) return false - val admins = group.currentAdminIdentities() intersect AdminGovernance.members(group) - return admins.size >= AdminGovernance.adminFloor(database, room.chatRoom.id, group) - } - - /** - * Switches the rule on in every room of [me]'s that is owed it -- [switchOwed] -- - * saying first, where it has not, that this device follows signed commits, since - * it is a member too. Run by `GovernanceFollowThrough` whenever a member says it, - * and when it starts, so the switch needs nobody to open a screen or press - * anything. A switch still waiting for a relay is not sent twice; one that fails - * is logged and tried again on the next pass. - * - * @return how many rooms a switch was sent in. - */ - suspend fun switchWhereOwed(database: GizaDatabase, me: HexKey): Int = - database.chatRoomDao().getChatRoomIdsWithMlsState().count { chatRoomId -> - runCatching { - val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return@runCatching false - if (room.chatRoom.userPublicKey != me) return@runCatching false - val engine = database.marmotEngine - val group = engine.groupFor(room.routingId) ?: return@runCatching false - if (switcherOf(group) != me) return@runCatching false - announce(database, chatRoomId, group, me) - if (!switchOwed(database, room, group)) return@runCatching false - if (!engine.gate.canPrepareLocalCommit(room.routingId)) return@runCatching false - database.marmotOutboundDao().requireSignatures(room) - logger.i("Switched on the group's signature for changes in $chatRoomId") - true - }.getOrElse { - if (it is CancellationException) throw it - logger.w("Couldn't switch on the group's signature in $chatRoomId: ${it.message}") - false - } - } - - private val logger = Logger.withTag("GovernanceSupport") -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt index 08663efc..77b933e3 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt @@ -109,6 +109,7 @@ object MarmotGroupCreation { name: String, purpose: String, adminPublicKeys: Set, + minimumAdmins: Int?, userPublicKey: HexKey, keyPair: KeyPair, path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH, @@ -133,7 +134,18 @@ object MarmotGroupCreation { keyPackage?.let { publicKey to it } } + // Born needing the group's signature for every change, with the floor of + // admins it may never go under: there is no later moment to switch the rule + // on, and nobody it waits for. Founding comes before it in effect -- the + // founding invite is the creator's commit while it is the room's only member, + // which no other device ever processes. docs/remove-convenient-groups.md, + // "After the build", and docs/member-admin-promotion.md, D7 and D8. + // + // [minimumAdmins] null is a room without the rule: one made before every keyed + // room was born with it, which tests of a group's mechanics still model. + // [createFor], the app's one caller, always passes the ceremony's. val description = SharedKeyDerivation.describe(purpose = purpose, path = path) + .let { if (minimumAdmins == null) it else GovernanceMarker.describe(it, minimumAdmins) } // On whichever profile new rooms are on. The room id is the derived key // either way; on the current profile the group's routing address is minted @@ -259,6 +271,7 @@ object MarmotGroupCreation { name = CeremonyFollowThrough.roomName(ceremony), purpose = CeremonyFollowThrough.roomPurpose(ceremony), adminPublicKeys = founders, + minimumAdmins = Quorum.minimumAdmins(ceremony.threshold), userPublicKey = ceremony.userPublicKey, keyPair = keyPair, parentChatRoomId = parentChatRoomId, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt index f3b6dae0..b6b16dfe 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt @@ -27,7 +27,7 @@ import com.vitorpamplona.quartz.nip01Core.tags.dTag.DTag */ object GovernanceEvents { val ALL: Set = setOf( - GovernanceStatementEvent.KIND, OwnCommitEvent.KIND, GovernanceSupportEvent.KIND, GovernanceCarrierEvent.KIND, + GovernanceStatementEvent.KIND, OwnCommitEvent.KIND, GovernanceCarrierEvent.KIND, PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER, ) @@ -66,24 +66,6 @@ object OwnCommitEvent { arrayOf(DTag.assemble(chatRoomId), arrayOf(GovernanceEvents.EPOCH_TAG, epoch.toString())) } -/** - * A member's word that their device applies signed commits, said once per room so - * the room can tell when the rule can be switched on without leaving anybody behind. - * Signed by the member's account. docs/member-admin-promotion.md, Phase 4b. - */ -object GovernanceSupportEvent { - val KIND: Kind = 30372 - - const val VERSION_TAG = "governance" - const val VERSION = "signed-commits/v1" - - fun assembleTags(chatRoomId: HexKey): Array> = - arrayOf(DTag.assemble(chatRoomId), arrayOf(VERSION_TAG, VERSION)) - - fun supports(event: Event): Boolean = - event.kind == KIND && event.tags.any { it.size >= 2 && it[0] == VERSION_TAG && it[1] == VERSION } -} - /** * A member sending the group's signed statement into the room: its content is the * statement, as signed. The carrier vouches for nothing -- the statement inside is diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index ce1e3d83..e77a08d1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -256,13 +256,6 @@ interface ChatRepository { */ suspend fun reconcileAdminFlags(): Int - /** - * Says, in every keyed room this device is in, that it follows signed commits, - * for the rooms joined before joining said it. Once per start. See - * `GovernanceSupport.announceAll`. - */ - suspend fun announceGovernanceSupport(): Int - /** * Takes every key ceremony [keyPair] coordinated from a key to a working room, * until cancelled: asks the group to sign its key state (a subgroup's parent to @@ -325,8 +318,6 @@ interface ChatRepository { */ suspend fun governanceStatus(chatRoomId: String): GovernanceStatus? - /** Makes a keyed room's changes need the group's signature. Throws with words a person can act on. */ - suspend fun requireSignatures(localChatRoom: LocalChatRoom) /** * Removes [memberPublicKey] from a current-profile room this device administers: @@ -595,8 +586,6 @@ interface ChatRepository { override suspend fun reconcileAdminFlags(): Int = 0 - override suspend fun announceGovernanceSupport(): Int = 0 - override suspend fun sendChatMessage( text: String, @@ -635,7 +624,6 @@ interface ChatRepository { override suspend fun governanceStatus(chatRoomId: String): GovernanceStatus? = null - override suspend fun requireSignatures(localChatRoom: LocalChatRoom) = Unit override suspend fun promoteMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 319166fe..4cabda03 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -1182,12 +1182,7 @@ fun ChatRoomDetailScreen( chatRoomDetailUIState.governance?.let { governance -> item { - GovernanceSection( - governance = governance, - canGovern = chatRoomDetailUIState.canGovern, - nameOf = nameOf, - me = chatRoomDetailUIState.localChatRoom.chatRoom.userPublicKey, - ) + GovernanceSection(governance = governance) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt index 6b9abaf1..45bf54ba 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt @@ -33,10 +33,6 @@ import mobi.giza.compose.resources.Res import mobi.giza.compose.resources.cancel import mobi.giza.compose.resources.disband_group_instead import mobi.giza.compose.resources.governance_on -import mobi.giza.compose.resources.governance_waiting -import mobi.giza.compose.resources.governance_switch_waits_for -import mobi.giza.compose.resources.governance_switching -import mobi.giza.compose.resources.require_signatures_explainer import mobi.giza.compose.resources.make_admin import mobi.giza.compose.resources.make_admin_and_leave import mobi.giza.compose.resources.make_admin_body @@ -203,61 +199,25 @@ internal fun LeaveAsAdminDialog( } /** - * Whether a keyed room's changes need the group's signature. Once they do, a line - * saying so; before, for an admin, whose device is switching it on -- or who it is - * still waiting on, since switching it on with a member whose device cannot follow - * would leave them in a different group from the first change. - * docs/member-admin-promotion.md, Phase 4b. - * - * Nothing to press: one device switches it on by itself once everybody can follow. + * That a keyed room's changes need the group's signature, and how few admins it may + * have. Every keyed room is born that way, so there is nothing to switch on and + * nobody to wait for. docs/member-admin-promotion.md, R2 and D8, and * docs/remove-convenient-groups.md, "After the build". */ @Composable -internal fun GovernanceSection( - governance: GovernanceStatus, - canGovern: Boolean, - nameOf: (HexKey) -> String, - me: HexKey, -) { - val explainer = Modifier.padding( - horizontal = MaterialTheme.spacing.containerPadding, - vertical = MaterialTheme.spacing.compactPadding, - ) - Column(modifier = Modifier.fillMaxWidth()) { - when (governance) { - is GovernanceStatus.Governed -> Text( - text = stringResource(Res.string.governance_on, governance.minimumAdmins), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = explainer, - ) - is GovernanceStatus.Ready -> if (canGovern && governance.switcher != null) { - Text( - text = if (governance.switcher == me) { - stringResource(Res.string.governance_switching) - } else { - stringResource(Res.string.governance_switch_waits_for, nameOf(governance.switcher)) - }, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = explainer, - ) - Text( - text = stringResource(Res.string.require_signatures_explainer), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = explainer, - ) - } - is GovernanceStatus.Waiting -> if (canGovern) { - Text( - text = stringResource(Res.string.governance_waiting, governance.missing.map(nameOf).sorted().joinToString()), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = explainer, - ) - } - } +internal fun GovernanceSection(governance: GovernanceStatus) { + when (governance) { + is GovernanceStatus.Governed -> Text( + text = stringResource(Res.string.governance_on, governance.minimumAdmins), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .fillMaxWidth() + .padding( + horizontal = MaterialTheme.spacing.containerPadding, + vertical = MaterialTheme.spacing.compactPadding, + ), + ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt index ec8383ce..0cb4d9b5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt @@ -255,12 +255,6 @@ class SynchronizationViewModel( // written. docs/robust-group-admins.md, Phase 6. runCatching { chatRepository.reconcileAdminFlags() } .onFailure { logger.e("Could not bring admin flags in line", it) } - // A member who joined a keyed room before joining said it - // follows signed commits, and never opened its screen, holds - // the room back from requiring them -- and so from making - // anyone an admin. docs/remove-convenient-groups.md. - runCatching { chatRepository.announceGovernanceSupport() } - .onFailure { logger.e("Could not say which rooms this device follows", it) } launch(Dispatchers.IO) { observePendingBroadcastNostrEventRequests(keyPair) } // Runs until cancelled rather than draining a queue, but it // belongs here for the same reason the pumps do: it needs the diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt index 412024ce..cee24d8d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt @@ -1,22 +1,12 @@ package mobi.giza.compose.ui.view.state -import com.vitorpamplona.quartz.nip01Core.core.HexKey - /** - * Where a keyed room stands on needing the group's signature for its changes. - * docs/member-admin-promotion.md, R2 and Phase 4b. + * How a keyed room needs the group's signature for its changes. Every keyed room + * Giza makes is born needing it (docs/remove-convenient-groups.md, "After the + * build"); a room with no state saying so -- one made before that -- has none. + * docs/member-admin-promotion.md, R2. */ sealed interface GovernanceStatus { - /** It does: every change is proposed, signed by the group, and only then applied. */ + /** Every change is proposed, signed by the group, and only then applied. */ data class Governed(val minimumAdmins: Int) : GovernanceStatus - - /** - * It does not yet, and every member's device could follow: [switcher]'s device - * switches it on by itself, the next time it is online. Null [switcher] when no - * admin holds a leaf. docs/remove-convenient-groups.md, "After the build". - */ - data class Ready(val minimumAdmins: Int, val switcher: HexKey?) : GovernanceStatus - - /** It does not yet, and these members have not said their device could follow. */ - data class Waiting(val missing: Set) : GovernanceStatus } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt index 9d0c2aaf..7774fea7 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt @@ -308,14 +308,16 @@ class AdminChangesJvmTest { assertIs( MarmotGroupCreation.create( database = db, chatRepository = chatRepository, groupId = keyedRoomId, name = "#keyed", - purpose = "Admins.", adminPublicKeys = setOf(user), userPublicKey = user, keyPair = keyPair, - profile = MarmotProfile.CURRENT, + purpose = "Admins.", adminPublicKeys = setOf(user), minimumAdmins = Quorum.MINIMUM_GROUP_SIZE, + userPublicKey = user, keyPair = keyPair, profile = MarmotProfile.CURRENT, ) ) val keyedRoom = db.chatRoomDao().findChatRoomById(keyedRoomId)!! + // Born needing the group's signature, so an admin's own step-down is refused + // outright: another admin proposes it, and the group signs. val refusal = assertFailsWith { chatRepository.demoteMember(keyedRoom, user) } - assertEquals(mobi.giza.compose.database.dao.MarmotOutboundDao.KEYED_ROOM_REFUSAL, refusal.message) + assertTrue("another admin removes you as admin" in refusal.message.orEmpty(), refusal.message) assertTrue(db.marmotPublishObligationDao().getAll().isEmpty()) val keyedGroup = db.marmotEngine.groupFor(keyedRoom.routingId)!! assertEquals(AdminLeave.CANNOT, AdminGovernance.adminLeave(keyedGroup, user)) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt index 240f8138..ba61c85b 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt @@ -14,7 +14,6 @@ import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync import kotlin.test.AfterTest import mobi.giza.compose.extensions.toHex import mobi.giza.compose.ui.view.state.GovernanceStatus -import mobi.giza.compose.nostr.frost.GovernanceSupportEvent import mobi.giza.compose.database.repository.DatabaseNostrRepository import mobi.giza.compose.database.repository.DatabaseChatRepository import kotlin.test.assertIs @@ -217,41 +216,8 @@ class GovernanceGateJvmTest { assertEquals(setOf(dana.hex, userHex), appGroup().currentAdminIdentities()) } - // --- Phase 4b: who can follow, and the switch --------------------------------- - private val erin = MarmotStandIn() - /** Erin joins Dana's room, by Dana's bare commit; the app applies it. */ - private suspend fun erinJoins() { - MarmotStandIn.seedProfile(db, erin.hex, "Erin") - erin.makeBundle() - val add = dana.commitLocally(routingId) { dana.manager.addMember(routingId, erin.bundle.keyPackage.toTlsBytes()) } - erin.manager.processWelcome(assertNotNull(add.welcomeBytes), erin.bundle) - erin.inbound.trackGroup(routingId) - MarmotStandIn.storeInApp(db, user, commitEvent(add)) - } - - /** Dana makes [admins] the admin list by a bare commit, which Erin and the app apply. */ - private suspend fun danaSetsAdminsBare(admins: List) { - val commit = dana.commitLocally(routingId) { - val staged = dana.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins).encode()) - dana.manager.installState(routingId, staged.pendingState) - staged.result - } - val event = commitEvent(commit) - erin.inbound.processGroupEvent(event) - MarmotStandIn.storeInApp(db, user, event) - } - - /** [member] says, in the room, that their device follows signed commits. */ - private suspend fun says(member: MarmotStandIn) { - val payload = MarmotAppEvent.build( - pubKey = member.hex, kind = GovernanceSupportEvent.KIND, content = "", createdAt = 1_700_000_002, - tags = GovernanceSupportEvent.assembleTags(roomId), - ).encodeToPayload() - MarmotStandIn.storeInApp(db, user, member.outbound.buildGroupEventFromBytes(routingId, payload).signedEvent) - } - private suspend fun room() = db.chatRoomDao().findChatRoomById(roomId)!! /** The relay's OK on the newest commit this device put on the wire. */ @@ -264,146 +230,6 @@ class GovernanceGateJvmTest { return event.toGroupEvent(userHex)!! } - /** Takes back what this device said, as a device that joined before joining said it. */ - private suspend fun forgetOurSupport() { - db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(GovernanceSupportEvent.KIND)) - .filter { it.publicKey == userHex } - .forEach { db.marmotInnerEventDao().deleteById(it.id) } - assertFalse(userHex in GovernanceSupport.supporters(db, roomId)) - } - - @Test - fun `a member welcomed into a keyed room says it on joining`() = runBlocking { - // Nobody else says anything after the Welcome: what the others said before it - // is at an epoch this device cannot read. docs/remove-convenient-groups.md. - governedRoom(governed = false) - - assertTrue(userHex in GovernanceSupport.supporters(db, roomId), "joining did not say it") - assertEquals(setOf(dana.hex), GovernanceSupport.missing(db, roomId, appGroup())) - } - - @Test - fun `a device that joined before joining said it says it when it starts`() = runBlocking { - governedRoom(governed = false) - forgetOurSupport() - - assertEquals(1, chatRepository.announceGovernanceSupport()) - assertTrue(userHex in GovernanceSupport.supporters(db, roomId)) - assertEquals(0, chatRepository.announceGovernanceSupport(), "said twice") - } - - private val frank = MarmotStandIn() - - /** Frank joins Dana's room after Erin, by Dana's bare commit; Erin and the app apply it. */ - private suspend fun frankJoins() { - MarmotStandIn.seedProfile(db, frank.hex, "Frank") - frank.makeBundle() - val add = dana.commitLocally(routingId) { dana.manager.addMember(routingId, frank.bundle.keyPackage.toTlsBytes()) } - frank.manager.processWelcome(assertNotNull(add.welcomeBytes), frank.bundle) - frank.inbound.trackGroup(routingId) - val event = commitEvent(add) - erin.inbound.processGroupEvent(event) - MarmotStandIn.storeInApp(db, user, event) - } - - @Test - fun `the first admin's device switches the rule on by itself once everyone has said it`() = runBlocking { - // Dana made the room and holds its first leaf; once she is no admin, the app's - // leaf is the lowest an admin holds, and the switch is the app's to make. - governedRoom(governed = false) - erinJoins() - frankJoins() - val admins = listOf(userHex, erin.hex, frank.hex) - val commit = dana.commitLocally(routingId) { - val staged = dana.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins).encode()) - dana.manager.installState(routingId, staged.pendingState) - staged.result - } - val event = commitEvent(commit) - erin.inbound.processGroupEvent(event) - frank.inbound.processGroupEvent(event) - MarmotStandIn.storeInApp(db, user, event) - assertEquals(userHex, GovernanceSupport.switcherOf(appGroup())) - - says(dana) - says(erin) - GovernanceFollowThrough.pass(db, user) - assertFalse(GovernanceGate.isGoverned(appGroup()), "switched on before Frank said it") - - says(frank) - GovernanceFollowThrough.pass(db, user) - okTheLatestCommit() - - assertTrue(GovernanceGate.isGoverned(appGroup()), "nobody pressed anything, and nothing happened") - assertEquals(0, GovernanceSupport.switchWhereOwed(db, userHex), "switched twice") - } - - @Test - fun `a device that is not the first admin leaves the switch to it`() = runBlocking { - // Every admin's device switching the moment the last member said it would be two - // commits at one epoch, which the library cannot settle for their authors. - governedRoom(governed = false) - erinJoins() - danaSetsAdminsBare(listOf(dana.hex, userHex, erin.hex)) - says(dana) - says(erin) - assertEquals(GovernanceStatus.Ready(minimumAdmins = 3, switcher = dana.hex), chatRepository.governanceStatus(roomId)) - - GovernanceFollowThrough.pass(db, user) - - assertEquals(0, GovernanceSupport.switchWhereOwed(db, userHex)) - assertFalse(GovernanceGate.isGoverned(appGroup())) - assertTrue(db.marmotCommitResultDao().let { dao -> - db.nostrEventDao().getMLSGroupEvents(since = kotlin.time.Instant.fromEpochSeconds(0), limit = 50) - .none { it.kind == GroupEvent.KIND && dao.getMarmotCommitRequestById(it.id) != null } - }, "the app sent a commit of its own") - } - - @Test - fun `hearing another member say it, this device says it back`() = runBlocking { - governedRoom(governed = false) - forgetOurSupport() - - says(dana) - - assertTrue(userHex in GovernanceSupport.supporters(db, roomId), "the app did not answer") - assertTrue(dana.hex in GovernanceSupport.supporters(db, roomId)) - } - - @Test - fun `the switch waits for every member, then turns the rule on for everyone`() = runBlocking { - governedRoom(governed = false) - erinJoins() - danaSetsAdminsBare(listOf(dana.hex, userHex, erin.hex)) - says(dana) - - val waiting = assertIs(chatRepository.governanceStatus(roomId)) - assertEquals(setOf(erin.hex), waiting.missing) - val refusal = assertFailsWith { chatRepository.requireSignatures(room()) } - assertTrue("Erin" in refusal.message.orEmpty(), refusal.message) - - says(erin) - assertEquals(GovernanceStatus.Ready(minimumAdmins = 3, switcher = dana.hex), chatRepository.governanceStatus(roomId)) - - chatRepository.requireSignatures(room()) - val switch = okTheLatestCommit() - - assertEquals(3, GovernanceGate.minimumAdmins(appGroup()), "the rule is not on here") - dana.inbound.processGroupEvent(switch) - assertEquals(3, GovernanceMarker.minimumAdmins(dana.manager.getGroup(routingId)!!.roomDescription()), "the rule did not reach Dana") - assertEquals(GovernanceStatus.Governed(3), chatRepository.governanceStatus(roomId)) - - // And from here, Dana's bare commit is refused. - val epoch = appGroup().epoch - val bare = dana.commitLocally(routingId) { - val staged = dana.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(listOf(dana.hex, userHex)).encode()) - dana.manager.installState(routingId, staged.pendingState) - staged.result - } - MarmotStandIn.storeInApp(db, user, commitEvent(bare)) - assertEquals(epoch, appGroup().epoch, "a bare commit landed after the switch") - } - // --- Phase 5: this device proposes, the group signs, this device publishes ------ /** The app made an admin beside Dana, inside the group's signature. */ diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLifecycleJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLifecycleJvmTest.kt index 90cfeba2..3fb25f99 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLifecycleJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLifecycleJvmTest.kt @@ -84,7 +84,7 @@ class GroupLifecycleJvmTest { assertIs( MarmotGroupCreation.create( database = db, chatRepository = chatRepository, groupId = roomId, name = "#room", - purpose = "Admins.", adminPublicKeys = setOf(user), userPublicKey = user, keyPair = keyPair, + purpose = "Admins.", adminPublicKeys = setOf(user), minimumAdmins = null, userPublicKey = user, keyPair = keyPair, profile = MarmotProfile.CURRENT, ) ) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt index 3fc1c19d..2b2dacb0 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt @@ -83,7 +83,7 @@ class MarmotGroupCreationJvmTest { purpose = "Admins of Ekklesia.", // A group of one, so nothing has to be invited and no key package has // to be found. The flag is the whole of what is being tested. - adminPublicKeys = setOf(user), + adminPublicKeys = setOf(user), minimumAdmins = Quorum.MINIMUM_GROUP_SIZE, userPublicKey = user, keyPair = keyPair, ) @@ -112,7 +112,7 @@ class MarmotGroupCreationJvmTest { groupId = groupId, name = "#Ekklesia", purpose = "Admins of Ekklesia.", - adminPublicKeys = setOf(user), + adminPublicKeys = setOf(user), minimumAdmins = Quorum.MINIMUM_GROUP_SIZE, userPublicKey = user, keyPair = keyPair, ) @@ -148,7 +148,7 @@ class MarmotGroupCreationJvmTest { // so a caller that forgot would mark the room on no device at all. name = "Ekklesia", purpose = "Admins of Ekklesia.", - adminPublicKeys = setOf(user), + adminPublicKeys = setOf(user), minimumAdmins = Quorum.MINIMUM_GROUP_SIZE, userPublicKey = user, keyPair = keyPair, ) @@ -176,7 +176,7 @@ class MarmotGroupCreationJvmTest { groupId = groupId, name = "#Ekklesia", purpose = "Admins of Ekklesia.", - adminPublicKeys = setOf(user), + adminPublicKeys = setOf(user), minimumAdmins = Quorum.MINIMUM_GROUP_SIZE, userPublicKey = user, keyPair = keyPair, ) @@ -274,6 +274,9 @@ class MarmotGroupCreationJvmTest { val group = assertNotNull(created.room.chatRoom.toMlsGroup()) assertEquals(founders, group.currentAdminIdentities(), "${owner.pubKey.toHexKey().take(8)}'s room") + // Born needing the group's signature, with the floor its 2-of-3 quorum + // sets: nothing to switch on later. docs/remove-convenient-groups.md. + assertEquals(Quorum.minimumAdmins(threshold = 2), GovernanceGate.minimumAdmins(group), "the room was born without the rule") } } finally { alicesDb.close() @@ -332,7 +335,7 @@ class MarmotGroupCreationJvmTest { groupId = groupId, name = "#Ekklesia", purpose = "Admins of Ekklesia.", - adminPublicKeys = setOf(user), + adminPublicKeys = setOf(user), minimumAdmins = Quorum.MINIMUM_GROUP_SIZE, userPublicKey = user, keyPair = keyPair, profile = MarmotProfile.CURRENT, @@ -368,7 +371,7 @@ class MarmotGroupCreationJvmTest { groupId = groupId, name = "#Ekklesia", purpose = "Admins of Ekklesia.", - adminPublicKeys = setOf(user), + adminPublicKeys = setOf(user), minimumAdmins = Quorum.MINIMUM_GROUP_SIZE, userPublicKey = user, keyPair = keyPair, profile = MarmotProfile.LEGACY, @@ -396,7 +399,7 @@ class MarmotGroupCreationJvmTest { groupId = groupId, name = "#Ekklesia", purpose = "Admins of Ekklesia.", - adminPublicKeys = setOf(user), + adminPublicKeys = setOf(user), minimumAdmins = Quorum.MINIMUM_GROUP_SIZE, userPublicKey = user, keyPair = keyPair, profile = MarmotProfile.CURRENT, diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/PublishBeforeApplyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/PublishBeforeApplyJvmTest.kt index b1eaafda..cb66e7be 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/PublishBeforeApplyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/PublishBeforeApplyJvmTest.kt @@ -73,7 +73,7 @@ class PublishBeforeApplyJvmTest { seedProfile(user) val outcome = MarmotGroupCreation.create( database = db, chatRepository = chatRepository, groupId = roomId, name = "#room", - purpose = "Admins.", adminPublicKeys = setOf(user), userPublicKey = user, keyPair = keyPair, + purpose = "Admins.", adminPublicKeys = setOf(user), minimumAdmins = null, userPublicKey = user, keyPair = keyPair, profile = MarmotProfile.CURRENT, ) assertIs(outcome) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt index c48ec120..ab4888af 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.managers +import mobi.giza.compose.ui.view.state.GovernanceStatus import androidx.room3.Room import com.vitorpamplona.marmot.groups.currentAdminIdentities import com.vitorpamplona.marmot.groups.isLocalAdmin @@ -14,6 +15,7 @@ import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent import kotlin.test.Test +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertEquals import kotlin.test.assertIs @@ -115,6 +117,7 @@ class RobustGroupAdminsJvmTest { name = "Ekklesia", purpose = "Admins of Ekklesia.", adminPublicKeys = phones.map { it.publicKey }.toSet(), + minimumAdmins = Quorum.MINIMUM_GROUP_SIZE, userPublicKey = creator.publicKey, keyPair = creator.keyPair, keyPackageLookupTimeout = 2_000L, @@ -217,6 +220,18 @@ class RobustGroupAdminsJvmTest { later.ready() (phones + later).forEach { phone -> (phones + later).forEach { MarmotStandIn.seedProfile(phone.db, it.publicKey) } } + if (profile == MarmotProfile.CURRENT) { + // Born needing the group's signature: a later invite is a proposal the + // group signs, never a commit of the creator's own -- which is also what + // proves it did not take the founding path. These phones hold no share + // of a real key, so it stops there. docs/remove-convenient-groups.md. + val refusal = assertFailsWith { + creator.chatRepository.inviteMember(creator.room(), later.publicKey, later.keyPackage) + } + assertEquals("This group has no shared key to sign with", refusal.message) + assertTrue(creator.db.marmotPublishObligationDao().getAll().isEmpty(), "a bare commit went out") + return@use + } creator.chatRepository.inviteMember(creator.room(), later.publicKey, later.keyPackage) creator.okTheLatestCommit() welcome(from = creator, to = later) @@ -400,6 +415,23 @@ class RobustGroupAdminsJvmTest { // ---- A group run by one person ------------------------------------------------ + /** + * The rule is in the state the founders are welcomed into, so a joiner's phone + * enforces it from its first epoch -- there is no switch for anybody to wait on, + * press, or miss. docs/remove-convenient-groups.md, "After the build". + */ + @Test + fun `a group is born needing its signature, on every founder's phone`() = + onEveryProfile(listOf(MarmotProfile.CURRENT)) { _, phones -> + phones.forEach { phone -> + assertEquals( + GovernanceStatus.Governed(minimumAdmins = Quorum.MINIMUM_GROUP_SIZE), + phone.chatRepository.governanceStatus(roomId), + "$phone's room", + ) + } + } + /** * Giza stops making groups its creator runs alone, and does not stop joining * them. docs/remove-convenient-groups.md, D4: a Bennu member still makes them, @@ -426,6 +458,7 @@ class RobustGroupAdminsJvmTest { name = "Checkers", purpose = "Run by its creator.", adminPublicKeys = setOf(creator.publicKey), + minimumAdmins = 1, userPublicKey = creator.publicKey, keyPair = creator.keyPair, keyPackageLookupTimeout = 2_000L, diff --git a/docs/member-admin-promotion.md b/docs/member-admin-promotion.md index 2baea9e3..1e67c2d2 100644 --- a/docs/member-admin-promotion.md +++ b/docs/member-admin-promotion.md @@ -196,6 +196,9 @@ being invited. ### D4. The commit rides inside the signature, and the rule lives in the group's state (R2) +*Since built further: the rule is no longer switched on. A keyed room is born with it +([remove-convenient-groups.md](./remove-convenient-groups.md), "After the build").* + Two choices here decide whether R2 holds at all. **The commit inside the signature, not beside it.** The group signs an event whose @@ -461,8 +464,9 @@ does not; nothing changes in a room without the marker. - **Require signatures for changes**, on a keyed room's detail screen, for an admin, once every current member has said it. It is one bare commit adding the marker line to the profile description. Until every member has, the screen names who has not. (Since - made automatic -- one device, the admin in the lowest leaf, sends it once everybody has - said it, and the button is gone; [remove-convenient-groups.md](./remove-convenient-groups.md), + removed, with the support event: a keyed room is born governed, its floor in its + epoch-0 description, because Giza no longer keeps compatibility with Bennu or older + builds, which were all the switch protected; [remove-convenient-groups.md](./remove-convenient-groups.md), "After the build".) - An invite into a governed room is refused for an account that has not said it, with words that say why, once it is in the room (it says so from its own device on joining). diff --git a/docs/remove-convenient-groups.md b/docs/remove-convenient-groups.md index d004c08a..29baf335 100644 --- a/docs/remove-convenient-groups.md +++ b/docs/remove-convenient-groups.md @@ -389,81 +389,53 @@ detail screen, and a Bennu peer's convenient group still reaches them. they were written. Add a parenthetical saying it was removed here. - [README.md](./README.md): the table row, which this commit adds, says "built". -### After the build: an invited member holds the group back +### After the build: a group is born needing its signature Found on a device, with this plan merged alongside member-admin-promotion. A robust group's founders were admins holding shares; a member invited afterwards (D7 lets a -keyed room take one) was a plain member, as designed. But nobody could make them an -admin: the ⋮ on their row offered only **Remove from group**, and the room said it was -waiting for them to update Giza when they already had. +keyed room take one) was a plain member, as designed -- but nobody could make them an +admin. The ⋮ on their row offered only **Remove from group**. Making a member of a keyed room an admin needs the room to require the group's -signature (`AdminGovernance.keyedChangesAllowed`), and that can be switched on only -once every member's device has said it follows signed commits -(`GovernanceSupport.missing`). A device said it when its room's screen was opened, and -back when it heard another member say it. The founders had all said it before the -invite, and an invited member cannot read anything sent at an epoch before its own -- -so it never heard one to answer, nobody said it again, and the room waited on a -screen the member had no reason to open. +signature for its changes (`AdminGovernance.keyedChangesAllowed`). That rule was +switched on after founding by an admin pressing **Require the group's signature for +changes**, and only once every member's device had said, in the room, that it could +follow signed commits (member-admin-promotion, D4 and Phase 4b). The founders said it +before the invite, at an epoch the new member could not read, so the new member's +device never heard anybody to answer and the room waited on it for good. -- **A device says it on joining.** The Welcome path in `NostrDao`, beside - `AdminFlags.reconcile`, for a current-profile room. -- **And once each start** (`GovernanceSupport.announceAll`, from - `SynchronizationViewModel` beside `reconcileAdminFlags`), for the members who joined - before joining said it. A room that has it already is a read and no write. -- **The notice** (`governance_waiting`) names who the room is waiting on and what for -- - "Waiting for Alice to open an up-to-date Giza. Until then, this group can't require - its signature on changes, and nobody else can be made an admin." -- instead of - telling them to update, which they often had, with a verb that did not agree with - one name. +That was fixed twice over -- a device said it on joining and at each start, then the +switch was made by one device on its own -- before the question underneath was asked: +what was the switch for? Only to keep a Bennu member, or one on an older Giza, from +being left in a different group by the first signed change. Giza is in development and +keeps compatibility with neither, so the switch protected nobody. It is gone, and so is +everything that fed it: -Pinned in `GovernanceGateJvmTest`: a welcomed member has said it before anybody else -speaks, and a device whose saying is taken back says it again at start, once. +- **A keyed room is born governed.** `MarmotGroupCreation.createFor` writes + `GovernanceMarker`'s line into the room's epoch-0 description, with the floor its + ceremony's quorum sets (`Quorum.minimumAdmins`). Every founder is welcomed into a + state that already enforces the rule; a member added later is added by the group's + signature, like every other change. +- **Founding still needs no signature.** The founding invite, and finishing one that + failed (robust-group-admins, Phase 4), are the creator's commits while it is the + room's only member. No other device ever processes them -- joiners start from the + Welcome -- so there is nobody to refuse them. member-admin-promotion's D7 holds as + written. +- **Removed:** `GovernanceSupport` and its event (kind 30372), the announcement on + joining, at start and in answer to another member, the switch and + `requireSignatures`, the button, and the screen's *waiting* and *ready* states. The + room's details say only that changes need the group's signature, and the floor. -#### The switch is nobody's to press +Pinned by `MarmotGroupCreationJvmTest` (the room `createFor` makes carries the floor its +2-of-3 ceremony sets) and `RobustGroupAdminsJvmTest` (every founder's phone, after a +real Welcome, reads the room as governed with three admins at least; a later invite is +a proposal for the group to sign, never the creator's own commit). -Even then an admin had to find **Require the group's signature for changes** on the -room's screen and tap it. Nothing about the switch is a decision: the two conditions it -waits on -- every member can follow, enough of them are admins -- are already checked in -code, and a group whose point is a key its members hold together is a group that means -to sign its changes. So the button is gone, and one device switches the rule on by -itself. +A keyed room made before this has no marker, and nothing will ever add one: its +admins cannot be changed. Make the group again. -- **Which device.** The admin in the room's lowest leaf (`GovernanceSupport.switcherOf`) - -- in a room as it was made, its creator. Not every admin's: two commits at one epoch - are settled for every device that watched them but not for the two that made them, - which swap branches and stay apart ([marmot-v2.md](./marmot-v2.md), Phase 8). Every - device reads the same leaf off the same state, so they agree on one without a word - between them. -- **When.** `GovernanceFollowThrough`, which already runs while the app is open and - reads everything again on each pass, now passes whenever a member says it follows - signed commits, and on start. A room that is owed the switch (`switchOwed`) gets the - commit `requireSignatures` always sent; one still waiting for a relay is not sent - twice. -- **The screen** says which device it is waiting on: "Turning on the group's signature - for changes." on that device, "Changes will need the group's signature as soon as - Bob's Giza is next online." on the others. - -*Not at creation*, though that was the first preference. A room born governed -- -the marker in its epoch-0 description -- would need no switch, but: - -- a Bennu founder, or one on an older Giza build, takes part in the ceremony like - anyone else, and would apply the bare commits Giza drops: in a different group from - the first change, with nobody told. The support check is the only thing that knows, - and it can only be asked once the room exists; -- a founder whose founding invite has to be finished later (robust-group-admins, - Phase 4) is added by a bare commit, which the founders already in a governed room - would refuse. - -Switching once everybody has joined and said it costs the seconds it takes the -founders' devices to process their Welcomes, and costs nothing when one of them cannot -follow -- the room simply stays as it is. - -Pinned in `GovernanceGateJvmTest`: the first admin's device switches by itself once the -last member says it, and not before; any other admin's device sends nothing. - -Then the member's row offers **Make admin** -- with the room's share rotation on, which -is a development build for now -- and the member accepts on their own device. +Promoting a member still needs the room's share rotation on -- a development build, +for now -- and the member accepts on their own device. ## Out of scope From bb35d73c286730bb576d3c09834c1a77e9114bb3 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 09:44:26 +0200 Subject: [PATCH 4/4] feat: an admin of a keyed room steps down by asking another admin An admin's own row had no menu in a keyed room: stepping down was not offered, because a demotion's proposer starts the rotation that takes the demoted admin's share away, and a rotation's proposer has to keep a share. Step down as admin now sends a request into the room (PromotionEvents.STEP_DOWN, 30377) and commits nothing. The remaining admin in the lowest leaf (AdminGovernance.stepDownProposer) -- one device, named the same everywhere, so two never propose at one epoch -- takes it up in GovernanceFollowThrough and runs the same demote its own Remove as admin would. A request is used once, and dropped by every device once its requester is no longer an admin. Offered only above the floor and while another admin is there to ask. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 2 + .../compose/database/dao/MarmotOutboundDao.kt | 9 ++- .../giza/compose/managers/AdminGovernance.kt | 33 ++++++++- .../managers/GovernanceFollowThrough.kt | 5 +- .../giza/compose/managers/PromotionManager.kt | 63 ++++++++++++++++ .../compose/nostr/frost/GovernanceEvents.kt | 13 +++- .../ui/composable/ChatRoomDetailScreen.kt | 3 + .../ui/composable/MemberAdminControls.kt | 3 +- .../compose/managers/AdminChangesJvmTest.kt | 7 +- .../compose/managers/GovernanceGateJvmTest.kt | 71 ++++++++++++++++++- docs/member-admin-promotion.md | 2 +- docs/remove-convenient-groups.md | 21 ++++++ 12 files changed, 218 insertions(+), 14 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 20f55003..ae269105 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -117,6 +117,8 @@ Step down as admin? You stay in the group as a member. Only an admin can make you one again. Step down + You stay in the group as a member. Another admin's Giza proposes it for the group to sign, and your share of the group's key is rotated away once it's done. + Asked the other admins; it happens once the group signs it Sent; it takes effect once a relay accepts it Leave the group? You're an admin, so you'll step down first, then leave once a relay accepts it. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt index 4ff8f458..25955812 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt @@ -983,13 +983,16 @@ abstract class MarmotOutboundDao( // away once it lands (docs/member-admin-promotion.md, Phase 9). if (AdminGovernance.isKeyedRoom(group)) { check(AdminGovernance.keyedChangesAllowed(group)) { KEYED_ROOM_REFUSAL } - check(adminPublicKey != localChatRoom.chatRoom.userPublicKey) { - "In a group with a shared key, another admin removes you as admin, so the group can rotate your share away" - } val floor = AdminGovernance.adminFloor(database, localChatRoom.chatRoom.id, group) if (!AdminGovernance.keepsFloor(group, adminPublicKey, floor)) { throw IllegalStateException("A group with a shared key needs at least $floor admins. Make someone else an admin first") } + // Your own: asked of another admin, whose device proposes it and then + // rotates your share away -- a rotation's proposer has to keep a share. + if (adminPublicKey == localChatRoom.chatRoom.userPublicKey) { + PromotionManager.requestStepDown(database, localChatRoom, adminPublicKey) + return + } val admins = group.currentAdminIdentities() GovernanceManager.propose( database, localChatRoom, localChatRoom.chatRoom.userPublicKey, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt index 5529384c..2ee5a000 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt @@ -3,7 +3,9 @@ package mobi.giza.compose.managers import com.vitorpamplona.marmot.groups.MarmotGroupPermissions import com.vitorpamplona.marmot.groups.currentAdminIdentities import com.vitorpamplona.mls.group.MlsGroup +import com.vitorpamplona.mls.tree.Credential import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.toHexKey import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.types.DkgRitualStage @@ -96,6 +98,35 @@ object AdminGovernance { fun keyedChangesAllowed(group: MlsGroup): Boolean = isKeyedRoom(group) && GovernanceGate.isGoverned(group) && ExperimentalFeatures.shareRefresh + /** + * Whether [me] may ask to stop being an admin of keyed room [group]. They cannot + * demote themselves: a demotion's proposer starts the rotation that takes their + * share away, and the proposer has to keep a share. So they ask, and + * [stepDownProposer]'s device proposes it. Never below [floor], and only while + * another admin is there to ask. + */ + fun canAskToStepDown(group: MlsGroup, me: HexKey, floor: Int): Boolean = + keyedChangesAllowed(group) && + me in group.currentAdminIdentities() && + keepsFloor(group, me, floor) && + stepDownProposer(group, me) != null + + /** + * The admin whose device proposes [requester]'s step-down: the one in the lowest + * leaf, [requester] apart. Read off the group's state, so every device names the + * same one and only one of them proposes -- two proposals at one epoch would be + * two commits the library cannot settle for their authors (docs/marmot-v2.md, + * Phase 8). Null when nobody else is an admin. + */ + fun stepDownProposer(group: MlsGroup, requester: HexKey): HexKey? { + val admins = group.currentAdminIdentities() - requester + return group.members() + .sortedBy { (leafIndex, _) -> leafIndex } + .firstNotNullOfOrNull { (_, leaf) -> + (leaf.credential as? Credential.Basic)?.identity?.toHexKey()?.takeIf { it in admins } + } + } + /** * What [me] may do to each member of [group], for the member rows' menus. Empty * when [me] does not govern the room. Removal stays offered in a keyed room, @@ -107,7 +138,7 @@ object AdminGovernance { return members(group).associateWith { member -> buildSet { if (member == me) { - if (canDemote(group, me, me)) add(MemberAction.STEP_DOWN) + if (canDemote(group, me, me) || canAskToStepDown(group, me, floor)) add(MemberAction.STEP_DOWN) } else { if (canPromote(group, me, member)) add(MemberAction.MAKE_ADMIN) if (canDemote(group, me, member) && keepsFloor(group, member, floor)) add(MemberAction.REMOVE_AS_ADMIN) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt index 9bdf87a7..f832f01f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt @@ -37,7 +37,7 @@ object GovernanceFollowThrough { suspend fun observe(database: GizaDatabase, keyPair: KeyPair) { combine( database.governanceProposalDao().observeAll(), - database.marmotInnerEventDao().observeCountByKinds(listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER)), + database.marmotInnerEventDao().observeCountByKinds(listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER, PromotionEvents.STEP_DOWN)), database.groupSignedEventDao().observeByKind(GroupKeyStateEvent.KIND), ) { _, _, _ -> Unit } .conflate() @@ -71,6 +71,9 @@ object GovernanceFollowThrough { announce(database, offer.chatRoomId, me, "Couldn't ask the group to make them an admin: ${it.message}") } } + // An admin who asked to step down, when this device is the one to propose it. + PromotionManager.followStepDowns(database, me) + PromotionManager.handoversOwed(database).forEach { proposal -> runCatching { PromotionManager.handover(database, proposal, me) }.onFailure { if (it is CancellationException) throw it diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt index 5fb0c155..aa471037 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt @@ -162,6 +162,69 @@ object PromotionManager { announce(database, localChatRoom.chatRoom.id, me, ChatMessage.TYPE_ADMIN_OFFERED, "You accepted becoming an admin. The group signs it next") } + // ---- stepping down, asked of another admin --------------------------------------------------------------------- + + /** + * Asks, as [me], to stop being an admin of keyed room [localChatRoom]. An admin + * cannot propose their own demotion there: the rotation that takes their share + * away is started by the demotion's proposer, who has to keep a share. So the + * request goes into the room, and [followStepDowns] on + * [AdminGovernance.stepDownProposer]'s device proposes it, as that admin pressing + * **Remove as admin** would. Nothing is committed here. + */ + suspend fun requestStepDown(database: GizaDatabase, localChatRoom: LocalChatRoom, me: HexKey): HexKey { + val group = database.marmotEngine.groupFor(localChatRoom.routingId) + ?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}") + check(me in group.currentAdminIdentities()) { "You're not an admin of this group" } + check(AdminGovernance.stepDownProposer(group, me) != null) { "You're the only admin. Make someone else an admin first" } + val id = send(database, localChatRoom.chatRoom.id, me, PromotionEvents.STEP_DOWN, "", PromotionEvents.stepDownTags(localChatRoom.chatRoom.id)) + announce(database, localChatRoom.chatRoom.id, me, ChatMessage.TYPE_ADMIN_OFFERED, "You asked to step down as admin. The group signs it next") + return id + } + + /** + * Takes up the step-down requests whose [AdminGovernance.stepDownProposer] is + * [me]: proposes each one's demotion for the group's signature, through the same + * `demote` an admin's own **Remove as admin** runs, so its rotation follows the + * same way. Run by `GovernanceFollowThrough` whenever a request arrives, and on + * start. + * + * A request is used once. The proposer's device drops it after proposing, or + * after saying in the room why it could not; every device drops one whose + * requester is no longer an admin, so a member made an admin again later is not + * stepped down by what they asked the first time. + * + * @return how many demotions were proposed. + */ + suspend fun followStepDowns(database: GizaDatabase, me: HexKey): Int { + var proposed = 0 + database.marmotInnerEventDao().getByKinds(listOf(PromotionEvents.STEP_DOWN)).forEach { request -> + val requester = request.publicKey + val room = database.chatRoomDao().findChatRoomById(request.chatRoomId) + val group = room?.let { database.marmotEngine.groupFor(it.routingId) } + if (room == null || group == null || requester !in group.currentAdminIdentities()) { + database.marmotInnerEventDao().deleteById(request.id) + return@forEach + } + if (room.chatRoom.userPublicKey != me || AdminGovernance.stepDownProposer(group, requester) != me) return@forEach + + val failure = runCatching { database.marmotOutboundDao().demote(room, requester) }.exceptionOrNull() + if (failure is kotlinx.coroutines.CancellationException) throw failure + database.marmotInnerEventDao().deleteById(request.id) + if (failure == null) { + proposed++ + logger.i("Proposed ${requester.take(8)}…'s step-down in ${room.chatRoom.id}") + } else { + logger.w("Couldn't propose ${requester.take(8)}…'s step-down: ${failure.message}") + announce( + database, room.chatRoom.id, me, ChatMessage.TYPE_CHANGE_NOT_APPLIED, + "Couldn't ask the group to remove ${nameOf(database, requester)} as admin, as they asked: ${failure.message}", + ) + } + } + return proposed + } + // ---- 3. the proposal, by the device that offered --------------------------------------------------------------- /** This device's offers that have been accepted and not yet proposed, with their acceptance. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt index b6b16dfe..f41e5e5d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt @@ -28,7 +28,7 @@ import com.vitorpamplona.quartz.nip01Core.tags.dTag.DTag object GovernanceEvents { val ALL: Set = setOf( GovernanceStatementEvent.KIND, OwnCommitEvent.KIND, GovernanceCarrierEvent.KIND, - PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER, + PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER, PromotionEvents.STEP_DOWN, ) /** The epoch tag every envelope names: the epoch its commit is built at. */ @@ -104,6 +104,15 @@ object PromotionEvents { val ACCEPT: Kind = 30375 val HANDOVER: Kind = 30376 + /** + * An admin of a keyed room asking to be removed as one. They cannot propose it + * themselves: the rotation that follows a demotion is started by its proposer, + * and has to be started by somebody who keeps a share. So one remaining admin's + * device proposes it for them (`PromotionManager.followStepDowns`). Signed by the + * admin stepping down, whom MLS authenticates as its sender. + */ + val STEP_DOWN: Kind = 30377 + const val TARGET_TAG = "target" const val OFFER_TAG = "offer" const val HOST_KEY_TAG = "host" @@ -117,5 +126,7 @@ object PromotionEvents { fun handoverTags(chatRoomId: HexKey, target: HexKey): Array> = arrayOf(DTag.assemble(chatRoomId), arrayOf(TARGET_TAG, target)) + fun stepDownTags(chatRoomId: HexKey): Array> = arrayOf(DTag.assemble(chatRoomId)) + fun value(tags: Array>, name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 4cabda03..b9083cdd 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -89,6 +89,7 @@ import mobi.giza.compose.resources.couldn_t_leave_the_group import mobi.giza.compose.resources.admin_change_requested import mobi.giza.compose.resources.stepping_down_to_leave import mobi.giza.compose.resources.change_proposed +import mobi.giza.compose.resources.step_down_requested import mobi.giza.compose.resources.admin_offer_sent import mobi.giza.compose.resources.promotion_accepted import mobi.giza.compose.ui.view.state.GovernanceStatus @@ -244,6 +245,7 @@ fun ChatRoomDetailScreen( val adminChangeRequested = stringResource(Res.string.admin_change_requested) val steppingDownToLeave = stringResource(Res.string.stepping_down_to_leave) val changeProposed = stringResource(Res.string.change_proposed) + val stepDownRequested = stringResource(Res.string.step_down_requested) val adminOfferSent = stringResource(Res.string.admin_offer_sent) val promotionAccepted = stringResource(Res.string.promotion_accepted) val adminLabel = stringResource(Res.string.admin) @@ -390,6 +392,7 @@ fun ChatRoomDetailScreen( notify( failure ?: when { governed && action == MemberAction.MAKE_ADMIN -> adminOfferSent + governed && action == MemberAction.STEP_DOWN -> stepDownRequested governed -> changeProposed else -> adminChangeRequested } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt index 45bf54ba..21b3e040 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt @@ -53,6 +53,7 @@ import mobi.giza.compose.resources.step_down_and_leave import mobi.giza.compose.resources.step_down_and_leave_body import mobi.giza.compose.resources.step_down_as_admin import mobi.giza.compose.resources.step_down_body +import mobi.giza.compose.resources.step_down_body_keyed import mobi.giza.compose.resources.step_down_title import mobi.giza.compose.ui.theme.spacing import mobi.giza.compose.ui.composable.widgets.Decorative @@ -125,7 +126,7 @@ internal fun ConfirmAdminChangeDialog( ) MemberAction.STEP_DOWN -> Triple( stringResource(Res.string.step_down_title), - stringResource(Res.string.step_down_body), + stringResource(if (keyed) Res.string.step_down_body_keyed else Res.string.step_down_body), stringResource(Res.string.step_down), ) // Removal keeps the immediate action it always had. diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt index 7774fea7..eeb88776 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt @@ -314,10 +314,11 @@ class AdminChangesJvmTest { ) val keyedRoom = db.chatRoomDao().findChatRoomById(keyedRoomId)!! - // Born needing the group's signature, so an admin's own step-down is refused - // outright: another admin proposes it, and the group signs. + // Born needing the group's signature. Its only admin stepping down would take + // it under its floor, so it is refused before anything is asked or committed. val refusal = assertFailsWith { chatRepository.demoteMember(keyedRoom, user) } - assertTrue("another admin removes you as admin" in refusal.message.orEmpty(), refusal.message) + assertTrue("at least 3 admins" in refusal.message.orEmpty(), refusal.message) + assertTrue(db.marmotInnerEventDao().getByKinds(listOf(mobi.giza.compose.nostr.frost.PromotionEvents.STEP_DOWN)).isEmpty()) assertTrue(db.marmotPublishObligationDao().getAll().isEmpty()) val keyedGroup = db.marmotEngine.groupFor(keyedRoom.routingId)!! assertEquals(AdminLeave.CANNOT, AdminGovernance.adminLeave(keyedGroup, user)) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt index ba61c85b..feb0b41d 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt @@ -30,6 +30,7 @@ import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase import mobi.giza.compose.database.model.ChatMessage import mobi.giza.compose.database.repository.DatabaseMarmotRepository +import mobi.giza.compose.nostr.frost.PromotionEvents import mobi.giza.compose.nostr.frost.GovernanceCarrierEvent import mobi.giza.compose.nostr.frost.GovernanceChange import mobi.giza.compose.nostr.frost.GovernanceStatementEvent @@ -434,20 +435,84 @@ class GovernanceGateJvmTest { // --- Phase 9: demotion and removal in a keyed room, then a rotation ------------ @Test - fun `in a governed keyed room an admin is offered demoting another, never stepping down`() = runBlocking { + fun `in a governed keyed room an admin is offered demoting another, and stepping down`() = runBlocking { governedRoom() appIsAdmin() mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true try { val actions = AdminGovernance.memberActions(appGroup(), userHex, floor = 1) assertTrue(mobi.giza.compose.ui.view.state.MemberAction.REMOVE_AS_ADMIN in actions[dana.hex].orEmpty()) - assertFalse(mobi.giza.compose.ui.view.state.MemberAction.STEP_DOWN in actions[userHex].orEmpty(), "an admin was offered stepping down from a keyed room") - assertFalse(mobi.giza.compose.ui.view.state.MemberAction.REMOVE_AS_ADMIN in AdminGovernance.memberActions(appGroup(), userHex, floor = 2)[dana.hex].orEmpty(), "the floor was ignored") + assertTrue(mobi.giza.compose.ui.view.state.MemberAction.STEP_DOWN in actions[userHex].orEmpty(), "an admin's own row offered no step-down") + val atTheFloor = AdminGovernance.memberActions(appGroup(), userHex, floor = 2) + assertFalse(mobi.giza.compose.ui.view.state.MemberAction.REMOVE_AS_ADMIN in atTheFloor[dana.hex].orEmpty(), "the floor was ignored") + assertFalse(mobi.giza.compose.ui.view.state.MemberAction.STEP_DOWN in atTheFloor[userHex].orEmpty(), "the floor was ignored for a step-down") } finally { mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = null } } + @Test + fun `a step-down is proposed by the admin in the lowest leaf, never the one stepping down`() = runBlocking { + governedRoom() + appIsAdmin() + // Dana made the room and holds leaf 0; the app holds leaf 1. + assertEquals(dana.hex, AdminGovernance.stepDownProposer(appGroup(), userHex)) + assertEquals(userHex, AdminGovernance.stepDownProposer(appGroup(), dana.hex)) + } + + @Test + fun `stepping down from a keyed room asks the other admins, and commits nothing`() = runBlocking { + governedRoom() + appIsAdmin() + + PromotionManager.requestStepDown(db, room(), userHex) + + val requests = db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(PromotionEvents.STEP_DOWN)) + assertEquals(listOf(userHex), requests.map { it.publicKey }) + assertTrue(db.marmotPublishObligationDao().getAll().isEmpty(), "a commit went out") + assertTrue(db.governanceProposalDao().getAll().isEmpty(), "the one stepping down proposed it") + assertTrue(userHex in appGroup().currentAdminIdentities()) + // Not this device's to take up: Dana's is the one that proposes it. + assertEquals(0, PromotionManager.followStepDowns(db, userHex)) + assertEquals(1, db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(PromotionEvents.STEP_DOWN)).size) + } + + @Test + fun `the admin whose it is to propose a step-down takes the request up`() = runBlocking { + governedRoom() + appIsAdmin() + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true + try { + danaSays(PromotionEvents.STEP_DOWN, "", PromotionEvents.stepDownTags(roomId)) + + // Dana's request reaches `demote` on this device, which is the one to + // propose it. This room has two admins under a floor of three, so the + // demotion is refused there and the room says why; the request is used. + assertEquals(0, PromotionManager.followStepDowns(db, userHex)) + assertTrue(lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).any { "as they asked" in it.content && "at least 3 admins" in it.content }) + assertTrue(db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(PromotionEvents.STEP_DOWN)).isEmpty(), "the request was kept") + } finally { + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = null + } + } + + @Test + fun `a request from someone who is no longer an admin is dropped`() = runBlocking { + governedRoom() + // A request the app sent while it was an admin, filed after it stopped being one. + db.marmotInnerEventDao().upsert( + mobi.giza.compose.database.model.MarmotInnerEvent( + id = "ab".repeat(32), publicKey = userHex, kind = PromotionEvents.STEP_DOWN, + createdAt = kotlin.time.Instant.fromEpochSeconds(1_700_000_000), + tags = PromotionEvents.stepDownTags(roomId), content = "", chatRoomId = roomId, + ) + ) + + PromotionManager.followStepDowns(db, dana.hex) + + assertTrue(db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(PromotionEvents.STEP_DOWN)).isEmpty()) + } + @Test fun `a signed demotion that lands owes a rotation without the member, and asks for one`() = runBlocking { governedRoom() diff --git a/docs/member-admin-promotion.md b/docs/member-admin-promotion.md index 1e67c2d2..1639211e 100644 --- a/docs/member-admin-promotion.md +++ b/docs/member-admin-promotion.md @@ -51,7 +51,7 @@ Where the build chose differently: | Phase 8: enrollment as `ShareRepairManager` generalised | the repair protocol unchanged but for its `n`: a request names the `n` it runs with (the new id, the table's size before it), helpers check that against their own table, and an enrollment asks no helper for approval -- the signed binding was everyone's chance to say no | | Phase 8: `n` grows in "the stored key" | a signing session's and a repair's `n` is the generation's table size, which the enrollment grew; the ceremony's `participantCount` is left as the ceremony made it | | Phase 9: every remaining holder's deal and confirm made automatic | the rotation is started by the proposer's device once the change lands (`GovernanceFollowThrough`), and each holder is asked once to take part, as every rotation now asks (rotate-shares-single-approval). A rotation that cannot start is said in the room and offered from the Shares section | -| Phase 9: an admin can step down in a keyed room | not offered. The rotation that has to follow is the remaining holders', so another admin proposes the demotion | +| Phase 9: an admin can step down in a keyed room | not offered at first: the rotation that has to follow is the remaining holders', so another admin proposes the demotion. Since offered as a request -- **Step down as admin** sends `PromotionEvents.STEP_DOWN` (30377), and the remaining admin in the lowest leaf (`AdminGovernance.stepDownProposer`) proposes the demotion for them, then rotates their share away as after any demotion it proposed. Leaving as an admin of a keyed room is still not offered | | Phase 11's dialogs for every action | removal keeps the immediate action it had; promotion, demotion and stepping down ask first | Read [marmot-v2.md](./marmot-v2.md) Phase 7 first. Removing a member, disbanding and diff --git a/docs/remove-convenient-groups.md b/docs/remove-convenient-groups.md index 29baf335..45b6a3b2 100644 --- a/docs/remove-convenient-groups.md +++ b/docs/remove-convenient-groups.md @@ -437,6 +437,27 @@ admins cannot be changed. Make the group again. Promoting a member still needs the room's share rotation on -- a development build, for now -- and the member accepts on their own device. +#### Stepping down, asked of another admin + +With every keyed room governed, an admin's own row had no menu: an admin of a keyed +room could not step down (member-admin-promotion, Phase 9). A demotion's proposer starts +the rotation that takes the demoted admin's share away, and a rotation's proposer has to +keep a share -- so the admin stepping down cannot propose it. + +They ask instead. **Step down as admin** on their own row sends a request into the room +(`PromotionEvents.STEP_DOWN`, 30377) and commits nothing. The remaining admin in the +lowest leaf (`AdminGovernance.stepDownProposer`) -- one device, named the same on every +device, so that two admins never both propose it -- two commits at one epoch the library cannot settle for their authors -- takes it up in +`GovernanceFollowThrough` and runs the same `demote` its own **Remove as admin** would: +proposed, signed by the group, then the share rotated away. The request is used once: +dropped after it is proposed or refused out loud, and by every device once its requester +is no longer an admin. It is offered only above the floor and while another admin is +there to ask. + +Pinned in `GovernanceGateJvmTest`: the menu offers it, and not at the floor; asking +commits nothing and is not the asker's to take up; the lowest-leaf admin's device takes +it to `demote`; a request from someone no longer an admin is dropped. + ## Out of scope - **One-to-one chats** (D1). If they are to become robust, that needs its own plan.