feat(marmot): leaving, removal, disbanding, and captions derived from the state (v2 Phase 7)

The lifecycle of a current-profile room, through the publish gate. docs/marmot-v2.md,
Phase 7.

Leaving used to be a local flag and a "Left group" chat line: the group never
learned of it, and the leaf stayed in the tree holding the group's keys. A
current-profile room is now left the way v2 leaves: a standalone SelfRemove
proposal on the wire as a kind:445, the LEAVING gate raised first and durably,
the local state dropped, the room closed on this device with its own line. It
is not a commit, so it waits on no relay -- there is no state of ours it would
make canonical. An admin's device that receives the proposal commits it on
receipt, as the library expects, so a leaver is out of the tree without anyone
pressing anything; the commit goes through the gate like every other. The
library refuses a SelfRemove from an admin outright -- an admin self-demotes
first -- so an admin's leave is refused here before anything is raised or
dropped, in words a person can act on: hand over admin, or, for the only
admin, disband. Legacy rooms leave the way they always did.

An admin removes a member with stageRemoveMember through the gate; the library's
admin-depletion guard refuses a commit that would leave no admin. An admin
disbands with stageEnableDisbanding and stageDisband -- two commits when the
group predates the lifecycle component, one otherwise -- under the DISBANDING
gate, which is durable so a crash between raising it and publishing does not
lose the request; the second step is taken by continueDisband when the first
is accepted. Both are on the room detail screen, for a device that administers
a current-profile room: a remove action on every member row but its own, and a
disband button beside leave, with an explainer that says nobody rejoins. A
disbanded room says so and hides every write entrance.

The captions are derived, never received. v2 spells them as kind-1210 system
rows and is explicit that a row arriving over the wire is one member's
assertion, not a fact; here they are written by processGroupMembershipChanges
from the difference between the room's members before a commit and after it --
"X joined the group", "X left the group", "The group was disbanded", "You were
removed from the group" -- on every device that applies the commit, including
the one that made it, which is why an admin's own removal no longer writes a
line of its own: every device says the same thing at the same point. A commit
that removed our own leaf, or disbanded the group, closes the room here as well.
A commit this device made is applied at the relay's OK, where the room now
follows the state it gained. MarmotCommitResult.NO_INVITEE marks a commit that
invites nobody, so the OK sends no Welcome for it.

Tests: GroupLifecycleJvmTest, with quartz's own managers standing in for the
other member, covers an admin committing a member's leave on receipt and the
room saying they left; a removal applied on both sides once the commit lands; a
disband ending the group for everyone, closing the room and refusing what
follows; an admin's leave refused with its reason; and a member's leave sending
the proposal the other side stages, dropping the state and closing the room.
The stand-in is now one fixture, MarmotStandIn, shared with the interop test.
Full JVM suite: 1,182 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5 committed 2026-09-13 23:43:11 +02:00
1 parent f617560cf9
commit c4a46e892f
16 files changed
+966 -164

No files matched your search

@@ -123,6 +123,11 @@
<string name="language">Language</string>
<string name="learn_more">Learn more</string>
<string name="leave_group">Leave group</string>
<string name="remove_from_group">Remove from group</string>
<string name="disband_group">Disband group</string>
<string name="group_disbanded">This group was disbanded. Nothing more can be sent into it, and nobody can rejoin.</string>
<string name="disband_group_explainer">Ends the group for everyone. Nobody can rejoin; a new conversation is a new group.</string>
<string name="member_removal_requested">Removal sent; it takes effect once a relay accepts it</string>
<string name="library">Library</string>
<string name="lightning_invoice">Lightning invoice</string>
<string name="live">LIVE</string>
@@ -34,6 +34,10 @@ import to.curare.compose.nostr.MarmotDirectMessage
import to.curare.compose.nostr.Relays
import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.marmot.foundation.appEvents.MarmotAppEvent
import com.vitorpamplona.quartz.marmot.appComponents.AppComponentIds
import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupManager
import com.vitorpamplona.quartz.marmot.mls.messages.CommitResult
import com.vitorpamplona.quartz.marmot.protocolCore.LocalOutboundGate
import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageUtils
import com.vitorpamplona.quartz.marmot.mip01Groups.MarmotGroupData
import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent
@@ -659,70 +663,317 @@ abstract class MarmotOutboundDao(
)
}
} else {
// CommitEvent...
val encryptedContent = encryptedCommitEvent(
mlsGroup,
commitBytes = commitResult.framedCommitBytes,
exporterKey = commitResult.preCommitExporterSecret
publishCommit(
chatRoomId = chatRoomId,
routingId = routingId,
userPublicKey = userPublicKey,
commitResult = commitResult,
peerKeyPackageEventId = peerKeyPackage.id,
obligationId = obligationId,
relays = relays,
)
}
}
val template = GroupEvent.build(
encryptedContentBase64 = encryptedContent,
nostrGroupId = routingId
/**
* Puts a commit this device made on the wire: the kind:445, its rows, the
* [MarmotCommitResult] a relay's OK is keyed on, and the broadcast requests.
*
* [obligationId] is the publish obligation the commit is the outbound half of
* (null for a legacy room's, which is already applied), and
* [peerKeyPackageEventId] the invitee's package, or [MarmotCommitResult.NO_INVITEE]
* for a commit that invites nobody. Outer-encrypted with the pre-commit exporter
* secret in [commitResult], the key the members still at that epoch hold.
*/
private suspend fun publishCommit(
chatRoomId: HexKey,
routingId: HexKey,
userPublicKey: HexKey,
commitResult: CommitResult,
peerKeyPackageEventId: HexKey,
obligationId: HexKey?,
relays: List<String>,
): GroupEvent {
val encryptedContent = GroupEventEncryption.encrypt(
commitResult.framedCommitBytes,
commitResult.preCommitExporterSecret,
)
val template = GroupEvent.build(
encryptedContentBase64 = encryptedContent,
nostrGroupId = routingId
)
val ephemeralSigner = NostrSignerInternal(KeyPair())
val commitEvent: GroupEvent = ephemeralSigner.sign(template)
database.nostrEventDao().upsert(
NostrEvent(
id = commitEvent.id,
createdAt = Instant.fromEpochSeconds(commitEvent.createdAt),
content = commitEvent.content,
sig = commitEvent.sig,
tags = commitEvent.tags,
kind = commitEvent.kind,
pubKey = commitEvent.pubKey
)
)
val ephemeralSigner = NostrSignerInternal(KeyPair())
val commitEvent: GroupEvent = ephemeralSigner.sign(template)
database.marmotGroupEventDao().upsert(
MarmotGroupEvent(
id = commitEvent.id,
createdAt = Instant.fromEpochSeconds(commitEvent.createdAt),
encryptedContent = commitEvent.encryptedContent(),
publicKey = commitEvent.pubKey,
userPublicKey = userPublicKey,
expiresAt = commitEvent.expiration()?.let { Instant.fromEpochSeconds(it) },
chatRoomId = chatRoomId,
signature = commitEvent.sig
)
)
database.nostrEventDao().upsert(
NostrEvent(
id = commitEvent.id,
createdAt = Instant.fromEpochSeconds(commitEvent.createdAt),
content = commitEvent.content,
sig = commitEvent.sig,
tags = commitEvent.tags,
kind = commitEvent.kind,
pubKey = commitEvent.pubKey
// Save commitResult... in case we need to broadcast welcomeEvent after relay acknowledgement...
database.marmotCommitResultDao().upsert(
MarmotCommitResult.from(
commitEventId = commitEvent.id,
commitResult = commitResult,
chatRoomId = chatRoomId,
userPublicKey = userPublicKey,
peerKeyPackageEventId = peerKeyPackageEventId,
isOneMemberInitialGroupCreation = false,
createdAt = Instant.fromEpochSeconds(commitEvent.createdAt),
obligationId = obligationId,
)
)
// Broadcast commitment so other members get it...
database.broadcastNostrEventRequestDao().insert(
relays.map {
BroadcastNostrEventRequest(
nostrEventId = commitEvent.id,
relayURL = it
)
)
}
)
database.marmotGroupEventDao().upsert(
MarmotGroupEvent(
id = commitEvent.id,
createdAt = Instant.fromEpochSeconds(commitEvent.createdAt),
encryptedContent = commitEvent.encryptedContent(),
publicKey = commitEvent.pubKey,
userPublicKey = userPublicKey,
expiresAt = commitEvent.expiration()?.let { Instant.fromEpochSeconds(it) },
chatRoomId = chatRoomId,
signature = commitEvent.sig
)
)
return commitEvent
}
// Save commitResult... in case we need to broadcast welcomeEvent after relay acknowledgement...
database.marmotCommitResultDao().upsert(
MarmotCommitResult.from(
commitEventId = commitEvent.id,
commitResult = commitResult,
chatRoomId = chatRoomId,
userPublicKey = userPublicKey,
peerKeyPackageEventId = peerKeyPackage.id,
isOneMemberInitialGroupCreation = isOneMemberInitialGroupCreation,
createdAt = Instant.fromEpochSeconds(commitEvent.createdAt),
obligationId = obligationId,
)
/**
* A commit into an established current-profile room, prepared on a clone,
* recorded as an obligation and put on the wire; applied when a relay accepts
* it. The shape every governance change below shares. See docs/marmot-v2.md,
* Phase 6.
*
* @param stage the change, prepared by the manager on a clone.
*/
private suspend fun publishGatedCommit(
localChatRoom: LocalChatRoom,
relays: List<String> = Relays.DefaultDMRelayList.map { it.url },
stage: suspend (MlsGroupManager, HexKey) -> MlsGroupManager.StagedCommit,
): GroupEvent {
val engine = database.marmotEngine
val routingId = localChatRoom.routingId
engine.groupFor(routingId)
?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
if (!engine.gate.canPrepareLocalCommit(routingId)) {
throw MarmotCommitPendingException(
"An earlier change to this room is still waiting for a relay to accept it; try again in a moment"
)
}
val staged = stage(engine.groupManager, routingId)
val obligation = engine.gate.prepare(
groupId = routingId,
staged = staged,
outboundBytes = staged.result.framedCommitBytes,
recipientScope = relays,
)
return publishCommit(
chatRoomId = localChatRoom.chatRoom.id,
routingId = routingId,
userPublicKey = localChatRoom.chatRoom.userPublicKey,
commitResult = staged.result,
peerKeyPackageEventId = MarmotCommitResult.NO_INVITEE,
obligationId = obligation.obligationId,
relays = relays,
)
}
// Broadcast commitment so other members get it...
database.broadcastNostrEventRequestDao().insert(
relays.map {
BroadcastNostrEventRequest(
nostrEventId = commitEvent.id,
relayURL = it
)
}
/**
* Commits whatever proposals are staged in a current-profile room -- a member's
* `SelfRemove`, typically -- if this device is an admin and one is pending. An
* admin's device does this on receipt, as the library expects, so a leaver is
* out of the tree without anyone pressing anything. Nothing to do otherwise.
*/
open suspend fun commitStagedProposals(localChatRoom: LocalChatRoom) {
if (localChatRoom.chatRoom.marmotProfile() != MarmotProfile.CURRENT) return
val engine = database.marmotEngine
val routingId = localChatRoom.routingId
val group = engine.groupFor(routingId) ?: return
if (!group.isLocalAdmin() || !engine.groupManager.hasPendingProposals(routingId)) return
if (!engine.gate.canPrepareLocalCommit(routingId)) return
publishGatedCommit(localChatRoom) { manager, id -> manager.stageCommit(id) }
}
/**
* Removes [memberPublicKey] from a current-profile room, as an admin.
*
* Nothing is captioned here: the member's row goes, and the line saying they
* left is written, when the commit is applied -- on this device from the OK, on
* every other from the commit -- so every device says the same thing at the
* same point. The library's admin-depletion guard refuses a commit that would
* leave no admin in the tree.
*/
@Transaction
open suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) {
require(localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { "Only a current-profile room can remove a member" }
val group = database.marmotEngine.groupFor(localChatRoom.routingId)
?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
val leafIndex = group.members()
.firstOrNull { (_, leaf) -> (leaf.credential as? Credential.Basic)?.identity?.toHexKey() == memberPublicKey }
?.first
?: throw IllegalArgumentException("$memberPublicKey is not in the group")
publishGatedCommit(localChatRoom) { manager, id -> manager.stageRemoveMember(id, leafIndex) }
}
/**
* Disbands a current-profile room, as an admin.
*
* Two commits when the group predates the lifecycle component -- one that
* enables disbanding, then the disband itself -- and one otherwise. The gate is
* raised first and is durable: a disband that is only in memory is lost by the
* crash between raising it and publishing the commit. The second step, where
* there is one, is taken by [continueDisband] when the first is accepted.
*/
@Transaction
open suspend fun disband(localChatRoom: LocalChatRoom) {
require(localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { "Only a current-profile room can be disbanded" }
val engine = database.marmotEngine
val routingId = localChatRoom.routingId
val group = engine.groupFor(routingId)
?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
require(group.isLocalAdmin()) { "Only an admin can disband the group" }
if (!engine.gate.canPrepareLocalCommit(routingId)) {
throw MarmotCommitPendingException(
"An earlier change to this room is still waiting for a relay to accept it; try again in a moment"
)
}
engine.gate.raiseGate(routingId, LocalOutboundGate.DISBANDING)
continueDisband(localChatRoom)
}
/**
* The next disband commit for a room under the `DISBANDING` gate, or nothing
* when the group is disbanded already or a commit is still in flight.
*/
open suspend fun continueDisband(localChatRoom: LocalChatRoom) {
val engine = database.marmotEngine
val routingId = localChatRoom.routingId
val group = engine.groupFor(routingId) ?: return
if (engine.gate.outboundGate(routingId) != LocalOutboundGate.DISBANDING) return
if (group.currentGroupState().isDisbanded) return
// The gate this device raised is the one it is acting under, so it is the
// one exception to "no commit while gated".
if (!engine.gate.canPrepareLocalCommit(routingId, ignoringGate = LocalOutboundGate.DISBANDING)) return
val lifecycleRequired = group.currentGroupState().requires(AppComponentIds.GROUP_LIFECYCLE_V1)
publishGatedCommitIgnoringGate(localChatRoom) { manager, id ->
if (lifecycleRequired) manager.stageDisband(id) else manager.stageEnableDisbanding(id)
}
}
/** [publishGatedCommit] for the device acting under a gate it raised itself. */
private suspend fun publishGatedCommitIgnoringGate(
localChatRoom: LocalChatRoom,
relays: List<String> = Relays.DefaultDMRelayList.map { it.url },
stage: suspend (MlsGroupManager, HexKey) -> MlsGroupManager.StagedCommit,
): GroupEvent {
val engine = database.marmotEngine
val routingId = localChatRoom.routingId
val staged = stage(engine.groupManager, routingId)
val obligation = engine.gate.prepare(
groupId = routingId,
staged = staged,
outboundBytes = staged.result.framedCommitBytes,
recipientScope = relays,
)
return publishCommit(
chatRoomId = localChatRoom.chatRoom.id,
routingId = routingId,
userPublicKey = localChatRoom.chatRoom.userPublicKey,
commitResult = staged.result,
peerKeyPackageEventId = MarmotCommitResult.NO_INVITEE,
obligationId = obligation.obligationId,
relays = relays,
)
}
/**
* Leaves a current-profile room: a standalone `SelfRemove` proposal on the wire
* for an admin to commit, the local state dropped, the gate raised, and the
* room closed on this device.
*
* One-way. The proposal is a `PublicMessage` outer-encrypted with the epoch's
* exporter secret, which the manager hands back with the bytes; it is not a
* commit, so it waits on no relay -- there is no state of ours it would make
* canonical. A legacy room has no such proposal to send: its leave is the
* local flag and the line it always was.
*/
@Transaction
open suspend fun leave(localChatRoom: LocalChatRoom, relays: List<String> = Relays.DefaultDMRelayList.map { it.url }) {
require(localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { "Only a current-profile room leaves by proposal" }
val engine = database.marmotEngine
val routingId = localChatRoom.routingId
val group = engine.groupFor(routingId)
?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
// The library refuses an admin's SelfRemove -- an admin self-demotes first --
// and the only admin cannot even do that without leaving the group ungoverned.
// Said here, before anything is raised or dropped, in words a person can act on.
if (group.isLocalAdmin()) {
throw IllegalStateException(
if (group.currentAdminIdentities().size > 1) "An admin cannot leave; hand over admin first"
else "The only admin cannot leave; make another member an admin, or disband the group"
)
}
engine.gate.raiseGate(routingId, LocalOutboundGate.LEAVING)
val (framedProposal, exporterSecret) = engine.groupManager.leaveGroup(routingId)
val template = GroupEvent.build(
encryptedContentBase64 = GroupEventEncryption.encrypt(framedProposal, exporterSecret),
nostrGroupId = routingId,
)
val proposalEvent: GroupEvent = NostrSignerInternal(KeyPair()).sign(template)
database.nostrEventDao().upsert(
NostrEvent(
id = proposalEvent.id,
createdAt = Instant.fromEpochSeconds(proposalEvent.createdAt),
content = proposalEvent.content,
sig = proposalEvent.sig,
tags = proposalEvent.tags,
kind = proposalEvent.kind,
pubKey = proposalEvent.pubKey,
)
)
database.broadcastNostrEventRequestDao().insert(
relays.map { BroadcastNostrEventRequest(nostrEventId = proposalEvent.id, relayURL = it) }
)
announceMembership(
chatRoomId = localChatRoom.chatRoom.id,
userPublicKey = localChatRoom.chatRoom.userPublicKey,
messageType = ChatMessage.TYPE_MEMBER_LEFT,
content = "You left the group",
)
// Re-read rather than copied: `leaveGroup` dropped the room's state through
// the store, and the row this function was handed still carries it.
database.chatRoomDao().findChatRoomById(localChatRoom.chatRoom.id)?.let { fresh ->
database.chatRoomDao().upsert(fresh.chatRoom.copy(leftGroupAt = Clock.System.now()))
}
}
/**
@@ -840,16 +1091,6 @@ abstract class MarmotOutboundDao(
}
}
private fun encryptedCommitEvent(
mlsGroup: MlsGroup,
commitBytes: ByteArray,
exporterKey: ByteArray? = null,
): String {
val outerKey = exporterKey ?: mlsGroup.exporterSecret()
return GroupEventEncryption.encrypt(commitBytes, outerKey)
}
@Transaction
open suspend fun encryptAndSendMarmotInnerEvent(
localChatRoom: LocalChatRoom,
@@ -1525,6 +1525,12 @@ abstract class NostrDao(
localChatRoom = localChatRoom
)
}
// A member's standalone proposal -- their SelfRemove -- sits in the
// pool until an admin commits it. An admin's device does so on
// receipt; on any other device this does nothing.
is GroupEventResult.ProposalStaged -> {
database.marmotOutboundDao().commitStagedProposals(localChatRoom)
}
else -> {
logger.i("No app logic to handle: $groupEventResult")
}
@@ -520,6 +520,26 @@ data class ChatMessage(
const val TYPE_MEMBER_INVITE_SENT = "memberInviteSent"
const val TYPE_MEMBER_INVITE_FAILED = "memberInviteFailed"
/**
* What the group's state said changed, as lines in the group's chat.
*
* Derived, never received. v2 spells these as kind `1210` system rows and
* is explicit that a row which arrives over the wire is one member's
* assertion, not a fact; a row derived from the commit this device applied
* cannot be forged by one member, and every device applying that commit
* derives the same one. So these are written by `processGroupMembershipChanges`
* from the difference between the room's members before a commit and after
* it, on every device that applies it -- and by the device that made the
* change, for what it did. See docs/marmot-v2.md, Phase 7.
*
* [TYPE_MEMBER_LEFT] covers a member who left and one an admin removed
* alike: the tree does not say which, and a line that guessed would be a
* caption no other device writes.
*/
const val TYPE_MEMBER_ADDED = "memberAdded"
const val TYPE_MEMBER_LEFT = "memberLeft"
const val TYPE_GROUP_DISBANDED = "groupDisbanded"
/**
* Every membership line, for the one check the transcript dispatches on.
*
@@ -530,6 +550,9 @@ data class ChatMessage(
TYPE_MEMBER_INVITED,
TYPE_MEMBER_INVITE_SENT,
TYPE_MEMBER_INVITE_FAILED,
TYPE_MEMBER_ADDED,
TYPE_MEMBER_LEFT,
TYPE_GROUP_DISBANDED,
)
const val TYPE_UNDECRYPTABLE_OUTER_LAYER = "undecryptableOuterLayer"
@@ -82,6 +82,15 @@ data class MarmotCommitResult( // TODO: Rename this to GiftWrapPayload...
companion object {
const val TAG = "MarmotCommitResult"
/**
* The `peerKeyPackageEventId` of a commit that invites nobody -- a removal, a
* committed leave, a disband. Such a commit still waits for a relay's OK to
* be applied, which is what this row is keyed for, and has no Welcome to
* send afterwards. The column is not nullable, and a blank is the one value
* no event id can be.
*/
const val NO_INVITEE: HexKey = ""
/**
* The persisted record of a commit, built from the [CommitResult] that produced it.
*
@@ -687,6 +687,16 @@ class DatabaseChatRepository(
localChatRoom: LocalChatRoom,
onCompletion: () -> Unit
) {
// A current-profile room is left by a SelfRemove proposal the admins commit,
// the local state dropped and the room closed here -- see MarmotOutboundDao.leave.
// A legacy room, or one this device holds no state for, is left the way it
// always was: the flag, and a line.
if (localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT && localChatRoom.chatRoom.leftGroupAt == null) {
database.marmotOutboundDao().leave(localChatRoom)
onCompletion.invoke()
return
}
database.chatRoomDao().upsert(
chatRoom = localChatRoom.chatRoom.copy(
leftGroupAt = Clock.System.now()
@@ -703,6 +713,14 @@ class DatabaseChatRepository(
onCompletion.invoke()
}
override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) {
database.marmotOutboundDao().removeMember(localChatRoom, memberPublicKey)
}
override suspend fun disbandChatRoom(localChatRoom: LocalChatRoom) {
database.marmotOutboundDao().disband(localChatRoom)
}
override suspend fun softDeleteChatRoom(
chatRoom: ChatRoom,
onCompletion: () -> Unit
@@ -1,5 +1,6 @@
package to.curare.compose.database.repository
import to.curare.compose.database.model.MarmotCommitResult
import to.curare.compose.database.GENESIS_AT
import to.curare.compose.database.model.BroadcastNostrEventRequest
import to.curare.compose.database.model.NostrEvent
@@ -515,6 +516,10 @@ class DatabaseNostrRepository(
database.marmotEngine.confirmPublished(obligationId)
}
// A removal, a committed leave or a disband invites nobody, and so
// has no Welcome to send once it is applied.
if (marmotCommitResult.peerKeyPackageEventId == MarmotCommitResult.NO_INVITEE) return@let
if (marmotCommitResult.isOneMemberInitialGroupCreation.not()) {
logger.d("Deliver Welcome")
database.chatRoomDao().findChatRoomById(marmotCommitResult.chatRoomId)?.let { localChatRoom ->
@@ -124,6 +124,15 @@ class MarmotEngine(
preState = obligation.priorState,
)
logger.i("Commit ${obligationId.take(8)}… confirmed; ${obligation.groupId.take(8)}… is at epoch ${obligation.pendingState.groupContext.epoch}")
// The room follows the state it just gained -- a member removed, a group
// disbanded -- without a caption for what this device asked for itself,
// which was written when it asked. A disband that has a step left takes it.
val chatRoomId = database.marmotRoutingDao().chatRoomIdFor(obligation.groupId)
val localChatRoom = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return
val group = groupManager.getGroup(obligation.groupId) ?: return
MarmotInboundManager.processGroupMembershipChanges(database, localChatRoom, group, announceAdditions = false)
database.marmotOutboundDao().continueDisband(localChatRoom)
}
/**
@@ -1,6 +1,7 @@
package to.curare.compose.managers
import to.curare.compose.database.CurareDatabase
import to.curare.compose.database.model.ChatMessage
import to.curare.compose.database.model.Participant
import to.curare.compose.database.model.intermdiate.LocalChatRoom
import to.curare.compose.exceptions.MarmotMissingChatGroupException
@@ -109,10 +110,28 @@ object MarmotInboundManager {
return null
}
/**
* Brings the room's members into line with the group's tree after a commit, and
* says what changed.
*
* The lines are derived from the difference, never received -- see
* [ChatMessage.TYPE_MEMBER_ADDED]. [announceAdditions] is false for a commit this
* device made itself, whose invite lines were written when the invites were
* made. Departures are always captioned, on every device including the one that
* committed them: the caption is the state's, not the actor's.
*
* Two changes are about this device rather than the room. A commit that removed
* our own leaf, or that disbanded the group, ends the room for us: the line says
* so and `leftGroupAt` is set, which is what stops the subscriptions and greys
* the room out. Both are a terminal state on the other side too -- a removed
* member cannot decrypt the next epoch, and a disbanded group refuses every
* later event -- so nothing is lost by closing here.
*/
suspend fun processGroupMembershipChanges(
database: CurareDatabase,
localChatRoom: LocalChatRoom,
mlsGroup: MlsGroup,
announceAdditions: Boolean = true,
) {
logger.d("processGroupMembershipChanges")
val adminPublicKeys = mlsGroup.currentAdminIdentities()
@@ -229,6 +248,58 @@ object MarmotInboundManager {
database.participantDao().delete(excludedParticipants)
database.participantDao().upsert(newParticipants)
database.participantDao().upsert(graduatedAdmins)
val userPublicKey = localChatRoom.chatRoom.userPublicKey
val disbanded = mlsGroup.currentGroupState().isDisbanded
val removedUs = !mlsGroup.isLocalMember()
if (announceAdditions) {
newParticipants.forEach { participant ->
announceLine(database, localChatRoom, ChatMessage.TYPE_MEMBER_ADDED,
"${memberName(database, participant.participantPublicKey)} joined the group")
}
}
excludedParticipants
.filterNot { it.participantPublicKey == userPublicKey }
// A disband removes everyone; one line for it below, not one per member.
.takeUnless { disbanded }
?.forEach { participant ->
announceLine(database, localChatRoom, ChatMessage.TYPE_MEMBER_LEFT,
"${memberName(database, participant.participantPublicKey)} left the group")
}
when {
disbanded -> announceLine(database, localChatRoom, ChatMessage.TYPE_GROUP_DISBANDED, "The group was disbanded")
removedUs -> announceLine(database, localChatRoom, ChatMessage.TYPE_MEMBER_LEFT, "You were removed from the group")
}
if ((disbanded || removedUs) && localChatRoom.chatRoom.leftGroupAt == null) {
database.chatRoomDao().upsert(localChatRoom.chatRoom.copy(leftGroupAt = Clock.System.now()))
}
}
private suspend fun memberName(database: CurareDatabase, publicKey: HexKey): String =
database.profileDao().getProfileByPublicKey(publicKey)?.humanReadableNameOrPubkey()
?: publicKey.take(8)
/** A membership caption, this device's own account of what the group's state said. */
private suspend fun announceLine(
database: CurareDatabase,
localChatRoom: LocalChatRoom,
messageType: String,
content: String,
) {
database.chatMessageDao().upsert(
ChatMessage(
content = content,
messageType = messageType,
chatRoomId = localChatRoom.chatRoom.id,
senderPublicKey = localChatRoom.chatRoom.userPublicKey,
isUserMessage = true,
giftWrapPayloadId = null,
marmotGroupEventId = null,
marmotInnerEventId = null,
)
)
}
suspend fun processGroupEvent(
@@ -322,6 +322,20 @@ interface ChatRepository {
onCompletion: () -> Unit
)
/**
* Removes [memberPublicKey] from a current-profile room this device administers:
* a commit through the publish gate, applied when a relay accepts it. See
* docs/marmot-v2.md, Phase 7.
*/
suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey)
/**
* Disbands a current-profile room this device administers. Absorbing: once the
* disband commit is applied nobody rejoins, and a replacement conversation is a
* new group.
*/
suspend fun disbandChatRoom(localChatRoom: LocalChatRoom)
suspend fun softDeleteChatRoom(
chatRoom: ChatRoom,
onCompletion: () -> Unit
@@ -521,6 +535,10 @@ interface ChatRepository {
TODO("Not yet implemented")
}
override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit
override suspend fun disbandChatRoom(localChatRoom: LocalChatRoom) = Unit
override suspend fun softDeleteChatRoom(
chatRoom: ChatRoom,
onCompletion: () -> Unit
@@ -18,7 +18,9 @@ import androidx.compose.material.icons.filled.Autorenew
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material.icons.filled.Checklist
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.DeleteForever
import androidx.compose.material.icons.filled.PersonRemove
import androidx.compose.material.icons.filled.Badge
import androidx.compose.material.icons.filled.Ballot
import androidx.compose.material.icons.filled.Campaign
@@ -36,6 +38,7 @@ import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
@@ -134,6 +137,11 @@ import curare.composeapp.generated.resources.direct_message_detail
import curare.composeapp.generated.resources.direct_message_functionality_will_be_here
import curare.composeapp.generated.resources.invite_new_member
import curare.composeapp.generated.resources.leave_group
import curare.composeapp.generated.resources.remove_from_group
import curare.composeapp.generated.resources.disband_group
import curare.composeapp.generated.resources.disband_group_explainer
import curare.composeapp.generated.resources.group_disbanded
import curare.composeapp.generated.resources.member_removal_requested
import curare.composeapp.generated.resources.members_2
import curare.composeapp.generated.resources.proposals
import curare.composeapp.generated.resources.reindex_events
@@ -186,6 +194,11 @@ fun ChatRoomDetailScreen(
)
)
// Read outside the click handlers: stringResource and rememberNotifier are both
// composable, and a lambda passed to onClick is not.
val notify = rememberNotifier(rememberCoroutineScope())
val removalRequested = stringResource(Res.string.member_removal_requested)
ScreenStateTransition(chatRoomDetailViewModel.chatRoomDetailUIState) { uiState ->
when (val chatRoomDetailUIState = uiState) {
is ChatRoomDetailUIState.Error -> {
@@ -753,10 +766,30 @@ fun ChatRoomDetailScreen(
)
},
trailingContent = {
Icon(
Icons.Default.ChevronRight,
contentDescription = "View profile"
)
val memberPublicKey = localParticipant.participant.participantPublicKey
if (chatRoomDetailUIState.canGovern && memberPublicKey != activeUserPublicKey) {
// An admin's removal of a member: a commit through the
// publish gate, applied when a relay accepts it, which is
// why the row stays until then. See docs/marmot-v2.md, Phase 7.
IconButton(
onClick = {
chatRoomDetailViewModel.removeMember(
localChatRoom = chatRoomDetailUIState.localChatRoom,
memberPublicKey = memberPublicKey,
) { failure -> notify(failure ?: removalRequested) }
}
) {
Icon(
Icons.Default.PersonRemove,
contentDescription = stringResource(Res.string.remove_from_group)
)
}
} else {
Icon(
Icons.Default.ChevronRight,
contentDescription = "View profile"
)
}
},
headlineContent = {
Text(
@@ -781,13 +814,67 @@ fun ChatRoomDetailScreen(
HorizontalDivider()
}
if (chatRoomDetailUIState.isDisbanded) {
item {
Text(
text = stringResource(Res.string.group_disbanded),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(
horizontal = MaterialTheme.spacing.containerPadding,
vertical = MaterialTheme.spacing.compactPadding,
)
)
}
}
if (chatRoomDetailUIState.canGovern) {
item {
TextButton(
colors = ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.error
),
onClick = {
chatRoomDetailViewModel.disbandGroup(
localChatRoom = chatRoomDetailUIState.localChatRoom,
onPopBackToRoute = onPopBackToRoute,
onFailed = { failure -> notify(failure ?: "Couldn't disband the group") },
)
}
) {
Icon(
Icons.Default.Delete,
contentDescription = stringResource(Res.string.disband_group)
)
Spacer(
modifier = Modifier.width(MaterialTheme.spacing.space125)
)
Text(stringResource(Res.string.disband_group))
}
Text(
text = stringResource(Res.string.disband_group_explainer),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(
start = MaterialTheme.spacing.space600,
end = MaterialTheme.spacing.containerPadding,
bottom = MaterialTheme.spacing.compactPadding,
)
)
}
}
item {
TextButton(
colors = ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.secondary
),
enabled = chatRoomDetailUIState.localChatRoom.chatRoom.leftGroupAt == null, // Disable after we leave group...
// Disabled after we leave, and after the group ends.
enabled = chatRoomDetailUIState.localChatRoom.chatRoom.leftGroupAt == null && !chatRoomDetailUIState.isDisbanded,
onClick = {
chatRoomDetailViewModel.leaveGroup(
localChatRoom = chatRoomDetailUIState.localChatRoom,
@@ -1,5 +1,6 @@
package to.curare.compose.ui.view.model
import to.curare.compose.nostr.MarmotProfile
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -80,6 +81,12 @@ class ChatRoomDetailViewModel(
val canSign = localChatRoom.chatRoom.mlsGroupState != null &&
chatRepository.canSign(chatRoomId)
// Governance is the current profile's: a leaf the group's admin policy
// names, in a room still open. Read off the stored state once.
val group = localChatRoom.chatRoom.takeIf { it.marmotProfile() == MarmotProfile.CURRENT }?.toMlsGroup()
val isDisbanded = group?.currentGroupState()?.isDisbanded == true
val canGovern = group != null && group.isLocalAdmin() && !isDisbanded && localChatRoom.chatRoom.leftGroupAt == null
ChatRoomDetailUIState.Loaded(
localChatRoom = localChatRoom,
groupKeyState = chatRepository.groupKeyState(chatRoomId),
@@ -93,11 +100,41 @@ class ChatRoomDetailViewModel(
groupCuratedEntries = chatRepository.groupCuratedEntries(chatRoomId),
canEditNostrProfile = canSign,
canAddSubgroup = canSign,
canGovern = canGovern,
isDisbanded = isDisbanded,
)
}
}
}
/**
* Removes [memberPublicKey] as an admin, and reloads the screen. The commit is
* applied when a relay accepts it, so the member's row stays until then; the
* line saying they were removed is there at once.
*/
fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey, onDone: (String?) -> Unit = {}) {
viewModelScope.launch(Dispatchers.IO) {
val failure = runCatching { chatRepository.removeMember(localChatRoom, memberPublicKey) }
.exceptionOrNull()
initiateChatRoomDetail()
viewModelScope.launch(Dispatchers.Main) { onDone(failure?.message) }
}
}
/** Disbands the group as an admin, then leaves the screen: there is nothing left to show. */
fun disbandGroup(localChatRoom: LocalChatRoom, onPopBackToRoute: (Route) -> Unit, onFailed: (String?) -> Unit = {}) {
viewModelScope.launch(Dispatchers.IO) {
val failure = runCatching { chatRepository.disbandChatRoom(localChatRoom) }.exceptionOrNull()
viewModelScope.launch(Dispatchers.Main) {
if (failure == null) {
onPopBackToRoute.invoke(HomeRoute(activeUserPublicKey = activeUserPublicKey))
} else {
onFailed(failure.message)
}
}
}
}
fun leaveGroup(
localChatRoom: LocalChatRoom,
onPopBackToRoute: (Route) -> Unit
@@ -137,6 +137,18 @@ sealed interface ChatRoomDetailUIState {
* missing and what to do about it.
*/
val canAddSubgroup: Boolean = false,
/**
* Whether this device administers a current-profile room: it may remove a
* member and disband the group, both commits through the publish gate. A
* legacy room has neither action, and a member who is not an admin has
* neither either. See docs/marmot-v2.md, Phase 7.
*/
val canGovern: Boolean = false,
/**
* The group's lifecycle says it is over. Absorbing: nothing is sent into it
* and nobody rejoins, so every write entrance is hidden and the room says so.
*/
val isDisbanded: Boolean = false,
): ChatRoomDetailUIState
data class Error(
@@ -2,28 +2,15 @@ package to.curare.compose.managers
import androidx.room3.Room
import com.vitorpamplona.quartz.marmot.GroupEventResult
import com.vitorpamplona.quartz.marmot.MarmotInboundProcessor
import com.vitorpamplona.quartz.marmot.MarmotOutboundProcessor
import com.vitorpamplona.quartz.marmot.appComponents.CurrentProfileGroupFactory
import com.vitorpamplona.quartz.marmot.appComponents.GroupProfileV1
import com.vitorpamplona.quartz.marmot.foundation.appEvents.MarmotAppEvent
import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageEvent
import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageRotationManager
import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageUtils
import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent
import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupManager
import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupStateStore
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler
import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealedRumorEvent
import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
import com.vitorpamplona.quartz.nipC7Chats.ChatEvent
import com.vitorpamplona.quartz.utils.RandomInstance
import com.vitorpamplona.quartz.utils.TimeUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -32,11 +19,7 @@ import to.curare.compose.database.CurareDatabase
import to.curare.compose.database.builder.getRoomDatabase
import to.curare.compose.database.model.MarmotInnerEvent
import to.curare.compose.database.model.NostrEvent
import to.curare.compose.database.model.Profile
import to.curare.compose.database.repository.DatabaseMarmotRepository
import to.curare.compose.nostr.MarmotProfile
import to.curare.compose.nostr.Relays
import kotlin.io.encoding.Base64
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
@@ -71,90 +54,17 @@ class CurrentProfileInteropJvmTest {
private val userHex = user.pubKey.toHexKey()
private val relay = "wss://relay.example"
/** Amethyst: quartz's own managers over a store that forgets nothing while the test runs. */
private class StandIn(val keyPair: KeyPair) {
val hex = keyPair.pubKey.toHexKey()
val signer = NostrSignerInternal(keyPair)
private val store = object : MlsGroupStateStore {
private val states = mutableMapOf<String, ByteArray>()
private val retained = mutableMapOf<String, List<ByteArray>>()
override suspend fun save(nostrGroupId: String, state: ByteArray) { states[nostrGroupId] = state }
override suspend fun load(nostrGroupId: String): ByteArray? = states[nostrGroupId]
override suspend fun delete(nostrGroupId: String) { states.remove(nostrGroupId); retained.remove(nostrGroupId) }
override suspend fun listGroups(): List<String> = states.keys.toList()
override suspend fun saveRetainedEpochs(nostrGroupId: String, retainedSecrets: List<ByteArray>) { retained[nostrGroupId] = retainedSecrets }
override suspend fun loadRetainedEpochs(nostrGroupId: String): List<ByteArray> = retained[nostrGroupId].orEmpty()
}
val manager = MlsGroupManager(store)
val inbound = MarmotInboundProcessor(manager, KeyPackageRotationManager())
val outbound = MarmotOutboundProcessor(manager)
}
private val amethyst = StandIn(KeyPair())
private suspend fun seedProfile(publicKey: String, name: String) {
val eventId = publicKey.take(32).padEnd(64, 'e')
db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
db.profileDao().upsert(Profile(publicKey = publicKey, userName = name, nostrEventId = eventId))
}
private suspend fun store(event: Event) = db.nostrDao().storeNostrEvent(
nostrEvent = NostrEvent(
id = event.id, pubKey = event.pubKey, kind = event.kind, tags = event.tags,
content = event.content, sig = event.sig, createdAt = Instant.fromEpochSeconds(event.createdAt),
),
relayURL = relay,
synchronizationRelayURLs = listOf(relay),
level = 0,
activeKeyPair = user,
)
/** The app's own published current-profile package, signed as the notary would. */
private suspend fun ourKeyPackageEvent(): KeyPackageEvent {
marmotRepository.publishMarmotKeyPackageBundle(user, setOf(MarmotProfile.CURRENT))
val unsigned = db.unsignedNostrEventDao().getAllUnprocessedUnsignedNostrEvents()
.single { it.kind == KeyPackageEvent.KIND && it.pubKey == userHex }
return NostrSignerSync(user).signNormal(
createdAt = unsigned.createdAt.epochSeconds, kind = unsigned.kind, tags = unsigned.tags, content = unsigned.content,
)
}
private val amethyst = MarmotStandIn()
/** The stand-in makes its group, adds us, and we join from the gift-wrapped Welcome. */
private suspend fun joinedRoom(): String {
seedProfile(userHex, "us")
val ourEvent = ourKeyPackageEvent()
val ourKeyPackage = KeyPackageUtils.decodeKeyPackage(Base64.decode(ourEvent.content))
val routingId = RandomInstance.bytes(32)
val routingHex = routingId.toHexKey()
val group = CurrentProfileGroupFactory.createGroup(
signer = amethyst.signer,
nostrGroupId = routingId,
relays = Relays.DefaultDMRelayList.map { it.url },
profile = GroupProfileV1(name = "interop", description = ""),
)
amethyst.manager.adoptGroup(routingHex, group)
amethyst.inbound.trackGroup(routingHex)
val commit = amethyst.manager.addMember(routingHex, ourKeyPackage.toTlsBytes())
val welcomeTemplate = WelcomeEvent.build(
welcomeBase64 = Base64.encode(assertNotNull(commit.welcomeBytes)),
keyPackageEventId = ourEvent.id,
relays = Relays.DefaultDMRelayList,
nostrGroupId = routingHex,
)
val inviterSigner = NostrSignerSync(amethyst.keyPair)
val rumor = RumorAssembler.assembleRumor<WelcomeEvent>(pubKey = amethyst.hex, ev = welcomeTemplate)
val seal = inviterSigner.signNormal<SealedRumorEvent>(
createdAt = rumor.createdAt, kind = SealedRumorEvent.KIND, tags = emptyArray(),
content = inviterSigner.nip44Encrypt(rumor.toJson(), userHex),
)
store(GiftWrapEvent.create(event = seal, recipientPubKey = userHex, createdAt = rumor.createdAt))
assertNotNull(db.chatRoomDao().findChatRoomById(routingHex), "the app did not join")
return routingHex
MarmotStandIn.seedProfile(db, userHex, "us")
val routingId = amethyst.createGroup("interop")
return amethyst.inviteApp(db, marmotRepository, user, routingId)
}
private suspend fun store(event: Event) = MarmotStandIn.storeInApp(db, user, event, relay)
private suspend fun theirMessage(routingHex: String, text: String): GroupEvent =
amethyst.outbound.buildAppEvent(
routingHex,
@@ -209,7 +119,7 @@ class CurrentProfileInteropJvmTest {
fun `a commit from the other implementation moves the room and its membership`() = runBlocking {
val roomId = joinedRoom()
val third = KeyPair()
seedProfile(third.pubKey.toHexKey(), "third")
MarmotStandIn.seedProfile(db, third.pubKey.toHexKey(), "third")
val thirdPackage = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(third)).keyPackage
val commit = amethyst.manager.addMember(roomId, thirdPackage.toTlsBytes())
@@ -0,0 +1,220 @@
package to.curare.compose.managers
import androidx.room3.Room
import com.vitorpamplona.quartz.marmot.GroupEventResult
import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent
import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEventEncryption
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import to.curare.compose.database.CurareDatabase
import to.curare.compose.database.builder.getRoomDatabase
import to.curare.compose.database.model.ChatMessage
import to.curare.compose.database.model.MarmotKeyPackage
import to.curare.compose.database.model.NostrEvent
import to.curare.compose.database.model.Profile
import to.curare.compose.database.repository.DatabaseChatRepository
import to.curare.compose.database.repository.DatabaseMarmotRepository
import to.curare.compose.database.repository.DatabaseNostrRepository
import to.curare.compose.nostr.MarmotProfile
import kotlin.io.encoding.Base64
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.time.Instant
/**
* Leaving, removing and disbanding a current-profile room, with quartz's own
* managers standing in for the other member. docs/marmot-v2.md, Phase 7.
*
* The app administers the room in every case: it creates the room, invites the
* stand-in (the founding Add, installed at once), and the stand-in joins from the
* Welcome bytes the app queued. Every governance commit then goes through the
* publish gate, and the relay's OK is played by hand.
*/
class GroupLifecycleJvmTest {
private val db: CurareDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<CurareDatabase>())
private val scope = CoroutineScope(Dispatchers.Default)
private val chatRepository = DatabaseChatRepository(db, scope)
private val nostrRepository = DatabaseNostrRepository(db, scope)
@AfterTest
fun closeDb() = db.close()
private val keyPair = KeyPair()
private val user = keyPair.pubKey.toHexKey()
private val roomId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey())
private val relay = "wss://relay.example"
private val member = MarmotStandIn()
private suspend fun seedProfile(publicKey: String) {
val eventId = publicKey.take(32).padEnd(64, 'f')
db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
db.profileDao().upsert(Profile(publicKey = publicKey, userName = publicKey.take(8), nostrEventId = eventId))
}
private suspend fun store(event: Event) = db.nostrDao().storeNostrEvent(
nostrEvent = NostrEvent(
id = event.id, pubKey = event.pubKey, kind = event.kind, tags = event.tags,
content = event.content, sig = event.sig, createdAt = Instant.fromEpochSeconds(event.createdAt),
),
relayURL = relay, synchronizationRelayURLs = listOf(relay), level = 0, activeKeyPair = keyPair,
)
private suspend fun room() = db.chatRoomDao().findChatRoomById(roomId)!!
private suspend fun transcript() = db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage }
/** The app's room with the stand-in in it, both sides at epoch 1. */
private suspend fun roomWithMember(): String {
seedProfile(user)
seedProfile(member.hex)
assertIs<MarmotGroupCreation.Outcome.Created>(
MarmotGroupCreation.create(
database = db, chatRepository = chatRepository, groupId = roomId, name = "#room",
purpose = "Admins.", adminPublicKeys = setOf(user), userPublicKey = user, keyPair = keyPair,
profile = MarmotProfile.CURRENT,
)
)
member.makeBundle()
val memberPackage = MarmotKeyPackage(
id = member.hex, publicKey = member.hex,
tlsEncodedMarmotKeyPackage = member.bundle.keyPackage.toTlsBytes(), profile = MarmotProfile.CURRENT.wireName,
)
chatRepository.inviteMember(room(), member.hex, memberPackage)
// The Welcome the app queued, read by the stand-in directly.
val welcome = db.giftWrapPayloadDao().getAllGiftWrapUnsigned().single { it.kind == WelcomeEvent.KIND }
val welcomeEvent = WelcomeEvent(id = welcome.id, pubKey = user, createdAt = welcome.createdAt.epochSeconds, tags = welcome.tags, content = welcome.content, sig = "")
val (_, routingId) = member.manager.processWelcome(Base64.decode(welcomeEvent.welcomeBase64()), member.bundle)
member.inbound.trackGroup(routingId)
assertEquals(routingId, db.marmotRoutingDao().activeRoutingIdFor(roomId))
assertEquals(1L, member.manager.getGroup(routingId)!!.epoch)
return routingId
}
/** The relay's OK on the newest commit this device put on the wire. */
private suspend fun okTheLatestCommit(): GroupEvent {
val event = db.nostrEventDao().getMLSGroupEvents(since = Instant.fromEpochSeconds(0), limit = 20)
.filter { it.kind == GroupEvent.KIND }
.last { db.marmotCommitResultDao().getMarmotCommitRequestById(it.id) != null }
val request = db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(event.id)!!
nostrRepository.broadcastProcessed(request, "published")
return event.toGroupEvent(user)!!
}
@Test
fun `an admin commits a member's leave on receipt, and the room says they left`() = runBlocking {
val routingId = roomWithMember()
// The stand-in leaves: a standalone SelfRemove on the wire.
val (framedProposal, exporterSecret) = member.manager.leaveGroup(routingId)
val proposalEvent = NostrSignerInternal(KeyPair()).sign(
GroupEvent.build(encryptedContentBase64 = GroupEventEncryption.encrypt(framedProposal, exporterSecret), nostrGroupId = routingId)
)
store(proposalEvent)
// Staged, and committed by the admin's device without anyone pressing anything.
assertEquals(1, db.marmotPublishObligationDao().getAll().size, "the admin did not commit the proposal")
assertTrue(room().localParticipants.any { it.participant.participantPublicKey == member.hex }, "the row went before the commit was accepted")
okTheLatestCommit()
val group = db.marmotEngine.groupManager.getGroup(routingId)!!
assertEquals(2L, group.epoch)
assertEquals(setOf(user), group.currentMemberIdentities())
assertFalse(room().localParticipants.any { it.participant.participantPublicKey == member.hex })
assertTrue(transcript().any { it.messageType == ChatMessage.TYPE_MEMBER_LEFT && it.content.endsWith("left the group") })
}
@Test
fun `an admin removes a member, and every device sees them gone once the commit lands`() = runBlocking {
val routingId = roomWithMember()
chatRepository.removeMember(room(), member.hex)
assertEquals(1L, db.marmotEngine.groupManager.getGroup(routingId)!!.epoch, "applied before any relay accepted it")
val commitEvent = okTheLatestCommit()
assertEquals(setOf(user), db.marmotEngine.groupManager.getGroup(routingId)!!.currentMemberIdentities())
assertFalse(room().localParticipants.any { it.participant.participantPublicKey == member.hex })
assertTrue(transcript().any { it.messageType == ChatMessage.TYPE_MEMBER_LEFT })
// The other side applies the same commit and is out.
assertIs<GroupEventResult.CommitProcessed>(member.inbound.processGroupEvent(commitEvent))
assertFalse(member.manager.isMember(routingId))
}
@Test
fun `disbanding ends the group for everyone, and nothing goes in afterwards`() = runBlocking {
val routingId = roomWithMember()
chatRepository.disbandChatRoom(room())
val commitEvent = okTheLatestCommit()
val group = db.marmotEngine.groupManager.getGroup(routingId)!!
assertTrue(group.currentGroupState().isDisbanded, "the disband did not land")
assertNotNull(room().chatRoom.leftGroupAt, "a disbanded room is not closed")
assertTrue(transcript().any { it.messageType == ChatMessage.TYPE_GROUP_DISBANDED })
assertNull(db.marmotPublishObligationDao().getAll().firstOrNull())
// The member applies it, is removed by it, and is refused afterwards.
assertIs<GroupEventResult.CommitProcessed>(member.inbound.processGroupEvent(commitEvent))
assertTrue(member.manager.getGroup(routingId)!!.currentGroupState().isDisbanded)
assertFalse(member.manager.isMember(routingId))
}
@Test
fun `an admin cannot leave, and is told why`() = runBlocking<Unit> {
roomWithMember()
val failure = runCatching { chatRepository.leaveChatRoom(room()) {} }.exceptionOrNull()
assertIs<IllegalStateException>(failure)
assertTrue(failure.message!!.contains("admin"))
assertNull(room().chatRoom.leftGroupAt, "the room was closed although nothing left it")
}
/**
* The member's side: the app in a room the stand-in administers. Its leave puts a
* SelfRemove on the wire, drops its state and closes the room here; the admin's
* device stages it.
*/
@Test
fun `leaving a current-profile room sends the proposal and closes the room here`() = runBlocking {
val admin = MarmotStandIn()
MarmotStandIn.seedProfile(db, user)
val routingId = admin.createGroup("theirs")
admin.inviteApp(db, DatabaseMarmotRepository(db, scope), keyPair, routingId)
val theirRoom = db.chatRoomDao().findChatRoomById(routingId)!!
chatRepository.leaveChatRoom(theirRoom) {}
val closed = db.chatRoomDao().findChatRoomById(routingId)!!
assertNotNull(closed.chatRoom.leftGroupAt)
assertNull(closed.chatRoom.mlsGroupState, "the state was not dropped")
assertTrue(
db.chatMessageDao().getChatMessagesByChatRoomId(routingId)
.any { it.chatMessage.messageType == ChatMessage.TYPE_MEMBER_LEFT && it.chatMessage.content == "You left the group" }
)
// A SelfRemove the admin's side stages.
val proposalEvent = db.nostrEventDao().getMLSGroupEvents(since = Instant.fromEpochSeconds(0), limit = 20)
.filter { it.kind == GroupEvent.KIND }
.last()
.toGroupEvent(user)!!
assertNotNull(db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(proposalEvent.id))
assertIs<GroupEventResult.ProposalStaged>(admin.inbound.processGroupEvent(proposalEvent))
assertTrue(admin.manager.hasPendingProposals(routingId))
}
}
@@ -0,0 +1,131 @@
package to.curare.compose.managers
import com.vitorpamplona.quartz.marmot.MarmotInboundProcessor
import com.vitorpamplona.quartz.marmot.MarmotOutboundProcessor
import com.vitorpamplona.quartz.marmot.appComponents.CurrentProfileGroupFactory
import com.vitorpamplona.quartz.marmot.appComponents.GroupProfileV1
import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageEvent
import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageRotationManager
import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageUtils
import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent
import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupManager
import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupStateStore
import com.vitorpamplona.quartz.marmot.mls.messages.KeyPackageBundle
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler
import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealedRumorEvent
import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
import com.vitorpamplona.quartz.utils.RandomInstance
import to.curare.compose.database.CurareDatabase
import to.curare.compose.database.model.NostrEvent
import to.curare.compose.database.model.Profile
import to.curare.compose.database.repository.DatabaseMarmotRepository
import to.curare.compose.nostr.MarmotProfile
import to.curare.compose.nostr.Relays
import kotlin.io.encoding.Base64
import kotlin.test.assertNotNull
import kotlin.time.Instant
/**
* Another Marmot client, played by quartz's own managers over a store that forgets
* nothing while a test runs: what Amethyst is, minus Amethyst. The other side of
* every two-implementation test in this package.
*/
internal class MarmotStandIn(val keyPair: KeyPair = KeyPair()) {
val hex = keyPair.pubKey.toHexKey()
val signer = NostrSignerInternal(keyPair)
private val store = object : MlsGroupStateStore {
private val states = mutableMapOf<String, ByteArray>()
private val retained = mutableMapOf<String, List<ByteArray>>()
override suspend fun save(nostrGroupId: String, state: ByteArray) { states[nostrGroupId] = state }
override suspend fun load(nostrGroupId: String): ByteArray? = states[nostrGroupId]
override suspend fun delete(nostrGroupId: String) { states.remove(nostrGroupId); retained.remove(nostrGroupId) }
override suspend fun listGroups(): List<String> = states.keys.toList()
override suspend fun saveRetainedEpochs(nostrGroupId: String, retainedSecrets: List<ByteArray>) { retained[nostrGroupId] = retainedSecrets }
override suspend fun loadRetainedEpochs(nostrGroupId: String): List<ByteArray> = retained[nostrGroupId].orEmpty()
}
val manager = MlsGroupManager(store)
val inbound = MarmotInboundProcessor(manager, KeyPackageRotationManager())
val outbound = MarmotOutboundProcessor(manager)
/** This client's own KeyPackage bundle, once one has been made. */
lateinit var bundle: KeyPackageBundle
suspend fun makeBundle(): KeyPackageBundle =
CurrentProfileGroupFactory.createKeyPackage(signer).also { bundle = it }
/** A current-profile group of this client's own, tracked. Returns its routing id. */
suspend fun createGroup(name: String): String {
val routingId = RandomInstance.bytes(32)
val group = CurrentProfileGroupFactory.createGroup(
signer = signer,
nostrGroupId = routingId,
relays = Relays.DefaultDMRelayList.map { it.url },
profile = GroupProfileV1(name = name, description = ""),
)
val hex = routingId.toHexKey()
manager.adoptGroup(hex, group)
inbound.trackGroup(hex)
return hex
}
/**
* Invites the app -- [user], over [db] -- into [routingId], delivering the Welcome
* the way it arrives: a kind:444 rumor, sealed by this client, wrapped by a
* throwaway key and p-tagged to the app, through the sync funnel. The app's
* current-profile package is published first. Returns the app's room id.
*/
suspend fun inviteApp(db: CurareDatabase, marmotRepository: DatabaseMarmotRepository, user: KeyPair, routingId: String): String {
val userHex = user.pubKey.toHexKey()
marmotRepository.publishMarmotKeyPackageBundle(user, setOf(MarmotProfile.CURRENT))
val unsigned = db.unsignedNostrEventDao().getAllUnprocessedUnsignedNostrEvents()
.single { it.kind == KeyPackageEvent.KIND && it.pubKey == userHex }
val ourEvent = NostrSignerSync(user).signNormal<KeyPackageEvent>(
createdAt = unsigned.createdAt.epochSeconds, kind = unsigned.kind, tags = unsigned.tags, content = unsigned.content,
)
val ourKeyPackage = KeyPackageUtils.decodeKeyPackage(Base64.decode(ourEvent.content))
val commit = manager.addMember(routingId, ourKeyPackage.toTlsBytes())
val welcomeTemplate = WelcomeEvent.build(
welcomeBase64 = Base64.encode(assertNotNull(commit.welcomeBytes)),
keyPackageEventId = ourEvent.id,
relays = Relays.DefaultDMRelayList,
nostrGroupId = routingId,
)
val sync = NostrSignerSync(keyPair)
val rumor = RumorAssembler.assembleRumor<WelcomeEvent>(pubKey = hex, ev = welcomeTemplate)
val seal = sync.signNormal<SealedRumorEvent>(
createdAt = rumor.createdAt, kind = SealedRumorEvent.KIND, tags = emptyArray(),
content = sync.nip44Encrypt(rumor.toJson(), userHex),
)
val wrap = GiftWrapEvent.create(event = seal, recipientPubKey = userHex, createdAt = rumor.createdAt)
storeInApp(db, user, wrap)
assertNotNull(db.chatRoomDao().findChatRoomById(routingId), "the app did not join")
return routingId
}
companion object {
/** Seeds the profile rows a member needs before the app can hold one as a participant. */
suspend fun seedProfile(db: CurareDatabase, publicKey: String, name: String = publicKey.take(8)) {
val eventId = publicKey.take(32).padEnd(64, 'e')
db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
db.profileDao().upsert(Profile(publicKey = publicKey, userName = name, nostrEventId = eventId))
}
/** [event] as the sync funnel hands it to the app. */
suspend fun storeInApp(db: CurareDatabase, user: KeyPair, event: Event, relay: String = "wss://relay.example") =
db.nostrDao().storeNostrEvent(
nostrEvent = NostrEvent(
id = event.id, pubKey = event.pubKey, kind = event.kind, tags = event.tags,
content = event.content, sig = event.sig, createdAt = Instant.fromEpochSeconds(event.createdAt),
),
relayURL = relay, synchronizationRelayURLs = listOf(relay), level = 0, activeKeyPair = user,
)
}
}