From b2cb0aaa8589e937a6622bd61f1fc980f209d24e Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 11:37:16 +0200 Subject: [PATCH] feat: where the group receives direct messages (group-threshold-ecdh, Phase 6) A kind 10050 the group signs is its decision to receive: proposed from a setup screen, named on the signing screen, a transcript line when signed, owed to relays by the proposer's device through GroupDmPublisher with backoff, and broadcastable again by anyone. GroupDmRelayRefusal declines a list with a relay that is not public wss:// in the four places. The group's screen gains its messages row. Phase 1's 10050 pin flips. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 17 ++ .../giza/compose/database/dao/GroupDmDao.kt | 13 ++ .../compose/database/model/ChatMessage.kt | 31 ++++ .../repository/DatabaseChatRepository.kt | 16 ++ .../repository/DatabaseGroupDmRepository.kt | 45 +++++ .../compose/managers/FrostSigningManager.kt | 36 ++++ .../giza/compose/managers/GroupDmPublisher.kt | 90 ++++++++++ .../giza/compose/managers/GroupDmRelays.kt | 109 ++++++++++++ .../giza/compose/repository/ChatRepository.kt | 3 + .../compose/repository/GroupDmRepository.kt | 30 ++++ .../mobi/giza/compose/text/ProposedEvent.kt | 9 + .../ui/composable/ChatRoomDetailScreen.kt | 63 +++++++ .../ui/composable/GroupDmSetupScreen.kt | 165 ++++++++++++++++++ .../ui/composable/navigation/GizaNavHost.kt | 21 +++ .../navigation/routes/GroupDmSetupRoute.kt | 10 ++ .../BroadcastGroupSignedEventViewModel.kt | 2 +- .../ui/view/model/ChatRoomDetailViewModel.kt | 3 + .../ui/view/model/GroupDmSetupViewModel.kt | 90 ++++++++++ .../ui/view/model/SynchronizationViewModel.kt | 19 ++ .../ui/view/state/ChatRoomDetailUIState.kt | 2 + .../giza/compose/ui/view/state/GroupDmRow.kt | 16 ++ .../ui/view/state/GroupDmSetupUIState.kt | 15 ++ .../compose/managers/GroupDmRelaysJvmTest.kt | 145 +++++++++++++++ .../compose/managers/GroupDmTodayJvmTest.kt | 12 +- 24 files changed, 955 insertions(+), 7 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmPublisher.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRelays.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmSetupScreen.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmSetupRoute.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmSetupViewModel.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmRow.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmSetupUIState.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmRelaysJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index b9b806df..7b557fd8 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -740,4 +740,21 @@ %1$s: %2$d of %3$d admins to sign Formed This is the room of the confederation %1$s. Its key is held by the admins of its groups together. Until the confederation can sign, who is in this room cannot change. + + Open the group's messages + Nobody can write to the group yet + Messages + Nothing unread + %1$d unread + This group receives direct messages + Only its admins read them + Anyone on nostr will be able to write to the group, and every admin will be able to read what it is sent. + The group signs where it receives messages, so it takes a quorum. Nothing is opened until it has. + Message relays + One wss:// address per line + Every relay has to be a public wss:// address + Senders' apps deliver to these relays. Choose ones that turn away spam: they are the group's first line against being flooded. + Ask the group to sign + Couldn't ask the group to sign where it receives messages. + Only a current admin holding a share can open the group's messages. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupDmDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupDmDao.kt index bacab31d..fb6bf0b1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupDmDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupDmDao.kt @@ -106,6 +106,9 @@ abstract class GroupDmDao { @Query("SELECT COUNT(*) FROM GroupDmMessage WHERE chatRoomId = :chatRoomId AND outgoing = 0 AND readAt IS NULL") abstract fun observeUnreadCount(chatRoomId: HexKey): Flow + @Query("SELECT COUNT(*) FROM GroupDmMessage WHERE chatRoomId = :chatRoomId AND outgoing = 0 AND readAt IS NULL") + abstract suspend fun countUnread(chatRoomId: HexKey): Int + @Query("UPDATE GroupDmMessage SET readAt = :at WHERE chatRoomId = :chatRoomId AND conversationId = :conversationId AND readAt IS NULL") abstract suspend fun markRead(chatRoomId: HexKey, conversationId: HexKey, at: Instant) @@ -118,6 +121,16 @@ abstract class GroupDmDao { @Query("SELECT * FROM GroupDmOutbound WHERE publishedAt IS NULL") abstract suspend fun getOwed(): List + /** What this device owes relays and has the event for: what [mobi.giza.compose.managers.GroupDmPublisher] sends. */ + @Query("SELECT * FROM GroupDmOutbound WHERE publishedAt IS NULL AND wrapJson IS NOT NULL") + abstract fun observeOwed(): Flow> + + @Query("UPDATE GroupDmOutbound SET publishedAt = :at WHERE signingSessionId = :signingSessionId AND sealId = :sealId") + abstract suspend fun markPublished(signingSessionId: String, sealId: HexKey, at: Instant) + + @Query("UPDATE GroupDmOutbound SET attempts = attempts + 1, nextAttemptAt = :next WHERE signingSessionId = :signingSessionId AND sealId = :sealId") + abstract suspend fun markAttempt(signingSessionId: String, sealId: HexKey, next: Instant) + @Query("SELECT * FROM GroupDmOutbound WHERE signingSessionId = :signingSessionId") abstract suspend fun getOutbound(signingSessionId: String): List diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index 17f57486..64b19026 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -45,6 +45,7 @@ import mobi.giza.compose.nostr.frost.GovernanceEvents import mobi.giza.compose.nostr.frost.ShareRefreshEvents import mobi.giza.compose.nostr.frost.ShareRepairEvents import mobi.giza.compose.nostr.groupdm.GroupEcdhEvents +import mobi.giza.compose.managers.GroupDmRelays import mobi.giza.compose.nostr.frost.FrostSigningEvents import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent @@ -520,6 +521,12 @@ data class ChatMessage( */ private const val TYPE_LEGACY_GROUP_RELAYS_SIGNED = "groupRelaysSigned" + /** + * The group signed where it receives direct messages: the first time, its decision + * to receive them at all. docs/group-threshold-ecdh.md, D8. + */ + const val TYPE_GROUP_DM_RELAYS_SIGNED = "groupDmRelaysSigned" + /** * Every line the group signed, for the one check the transcript * dispatches on. A type missing from here renders as a chat bubble, @@ -560,6 +567,7 @@ data class ChatMessage( TYPE_GROUP_PROFILE_SIGNED, TYPE_LEGACY_GROUP_RELAYS_SIGNED, TYPE_GROUP_POST_SIGNED, + TYPE_GROUP_DM_RELAYS_SIGNED, TYPE_LEGACY_GROUP_SCHEMA_SIGNED, TYPE_LEGACY_GROUP_ENTRY_CURATED, TYPE_WALLET_NOT_TAKEN_PART_IN, @@ -1389,6 +1397,29 @@ data class ChatMessage( ) } + // Where the group receives direct messages, signed by the room's own key. + // Verified, as a post is: a rumor's pubkey is whatever its sender wrote. + // docs/group-threshold-ecdh.md, D8. + GroupDmRelays.KIND -> { + val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) + if (!event.pubKey.equals(groupId, ignoreCase = true) || !signed.verifies()) return null + val earlier = database.groupSignedEventDao().getByChatRoomIdAndKind(groupId, GroupDmRelays.KIND) + .any { it.id != event.id && it.createdAt <= signed.createdAt } + + ChatMessage( + giftWrapPayloadId = null, + messageType = TYPE_GROUP_DM_RELAYS_SIGNED, + marmotGroupEventId = marmotGroupEventId, + marmotInnerEventId = marmotInnerEventId, + senderPublicKey = senderPublicKey, + isUserMessage = isUserMessage, + chatRoomId = groupId, + createdAt = createdAt, + content = if (earlier) "The group changed where it receives messages" + else "The group can now receive messages" + ) + } + // The group saying something publicly, in its own name -- a // different thing from a member saying something in the room. A // room's messages are `ChatEvent`s; this is a kind:1 authored by 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 4133f210..8db71d63 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 @@ -285,6 +285,22 @@ class DatabaseChatRepository( null } + override suspend fun groupDmRow(chatRoomId: String, userPublicKey: HexKey): mobi.giza.compose.ui.view.state.GroupDmRow? { + if (!ExperimentalFeatures.groupDirectMessages) return null + val key = FrostSigningManager.completedKey(database, chatRoomId) ?: return null + val receives = mobi.giza.compose.managers.GroupDmRelays.relaysOf(database, chatRoomId) != null + val admin = RoomAdmins.of(database, chatRoomId)?.admins?.contains(userPublicKey) == true && + ShareGenerations.active(database, key).signerIds.containsKey(userPublicKey) + return when { + admin && receives -> mobi.giza.compose.ui.view.state.GroupDmRow.Messages( + unread = database.groupDmDao().countUnread(chatRoomId) + ) + admin -> mobi.giza.compose.ui.view.state.GroupDmRow.OpenMessages + receives -> mobi.giza.compose.ui.view.state.GroupDmRow.ReceivesMessages + else -> null + } + } + override suspend fun confederationProposalCount(chatRoomId: String): Int = database.confederationDao().getProposalsNaming(chatRoomId).size diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt new file mode 100644 index 00000000..b5cd184d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt @@ -0,0 +1,45 @@ +package mobi.giza.compose.database.repository + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.GroupDmOutbound +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.managers.FrostSigningManager +import mobi.giza.compose.managers.GroupDmRelays +import mobi.giza.compose.managers.RoomAdmins +import mobi.giza.compose.managers.ShareGenerations +import mobi.giza.compose.repository.GroupDmRepository + +class DatabaseGroupDmRepository(private val database: GizaDatabase) : GroupDmRepository { + override fun observeOwed(): Flow> = database.groupDmDao().observeOwed() + + override suspend fun markPublished(outbound: GroupDmOutbound, at: Instant) = + database.groupDmDao().markPublished(outbound.signingSessionId, outbound.sealId, at) + + override suspend fun markAttempt(outbound: GroupDmOutbound, next: Instant) = + database.groupDmDao().markAttempt(outbound.signingSessionId, outbound.sealId, next) + + override fun observeRelays(chatRoomId: HexKey): Flow?> = + database.groupSignedEventDao().observeByKind(GroupDmRelays.KIND) + .map { rows -> + rows.filter { it.chatRoomId == chatRoomId && it.publicKey.equals(chatRoomId, ignoreCase = true) } + .maxByOrNull { it.createdAt } + ?.let { GroupDmRelays.relaysIn(it.tags) } + } + .distinctUntilChanged() + + override suspend fun isCurrentAdmin(chatRoomId: HexKey, userPublicKey: HexKey): Boolean { + val admins = RoomAdmins.of(database, chatRoomId)?.admins ?: return false + if (userPublicKey !in admins) return false + val key = FrostSigningManager.completedKey(database, chatRoomId) ?: return false + return ShareGenerations.active(database, key).signerIds.containsKey(userPublicKey) + } + + override suspend fun proposeRelays(localChatRoom: LocalChatRoom, userPublicKey: HexKey, relays: List): FrostSigningSession = + GroupDmRelays.propose(database, localChatRoom, userPublicKey, relays) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt index 9d03ff40..3bf331b4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -682,6 +682,20 @@ object FrostSigningManager { return declined } + // Where the group receives direct messages, listing a relay that is not a + // public wss:// address: declined on arrival for the same reason, so the + // group's decision to receive is never spent on relays nobody can reach. + // docs/group-threshold-ecdh.md, D8. + GroupDmRelayRefusal.of(unsignedEvents)?.let { why -> + logger.w("Signing proposal $sessionId $why; declining") + val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n) + .copy(signDeclinedAt = Clock.System.now()) + database.frostSigningSessionDao().upsert(declined) + database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) + announceStarted(database, declined) + return declined + } + // A change to a governed room whose commit does not say what its statement // says -- or that the group's door would refuse anyway -- is declined before // anybody is asked, for the wallet's reason: a device that signs what it @@ -1064,6 +1078,11 @@ object FrostSigningManager { session.subject == FrostSigningSubject.EVENTS && items.any { item -> Event.fromJsonOrNull(item.unsignedEventJson)?.let(GroupStatementRefusal::of) != null } + /** A 10050 [GroupDmRelayRefusal] declines. docs/group-threshold-ecdh.md, D8. */ + private fun isRefusedRelayList(session: FrostSigningSession, items: List): Boolean = + session.subject == FrostSigningSubject.EVENTS && + items.any { item -> Event.fromJsonOrNull(item.unsignedEventJson)?.let(GroupDmRelayRefusal::of) != null } + /** * The confederation refusal that applies to [session] now, read again from what it * carried when it arrived. docs/confederation.md, D6. @@ -1426,6 +1445,14 @@ object FrostSigningManager { logger.e("Signed session ${session.id} but could not file its confederation event", e) } + // Where the group receives messages: owed to relays by the device that + // proposed it. docs/group-threshold-ecdh.md, D8. + try { + GroupDmRelays.onSigned(database, session, signedEvents) + } catch (e: Throwable) { + logger.e("Signed session ${session.id} but could not file its message relays", e) + } + announce( database = database, session = session, @@ -2221,6 +2248,14 @@ object FrostSigningManager { return } + // And for a relay list a member could not have been asked about. + if (isRefusedRelayList(session, items)) { + logger.w("Session $sessionId signs a message relay list with a relay nobody can reach; declining") + update(database, session) { it.copy(signDeclinedAt = Clock.System.now()) } + advance(database, localChatRoom, sessionId) + return + } + // Checked again rather than trusted from arrival: the group's admins can change // while a member decides, and the seal has to hold the ones it has when it signs. // docs/confederation.md, D6. @@ -2722,6 +2757,7 @@ object FrostSigningManager { confederationReason != null -> confederationReason isWalletSession(session, items) -> WalletRefusal.REASON isUnshowableSession(session, items) -> GroupStatementRefusal.REASON + isRefusedRelayList(session, items) -> GroupDmRelayRefusal.REASON !holdsShareFor(database, session) -> GENERATION_REFUSAL else -> "Declined to sign" } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmPublisher.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmPublisher.kt new file mode 100644 index 00000000..06352eb5 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmPublisher.kt @@ -0,0 +1,90 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.Event +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.minutes +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.withTimeout +import mobi.giza.compose.database.model.GroupDmOutbound +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.network.dto.RelayDTO +import mobi.giza.compose.network.relays.EventPublishTransport +import mobi.giza.compose.network.relays.RelayPool +import mobi.giza.compose.network.sockets.NostrIncomingMessage +import mobi.giza.compose.repository.GroupDmRepository + +/** + * Sends what a group's direct messages owe relays, and keeps trying until one takes each + * (docs/group-threshold-ecdh.md, D8 and D10): the group's signed 10050 from the device that + * proposed it, and the gift wraps of a message the group signed. + * + * Not through the `BroadcastNostrEventRequest` queue, for the confederation's reason: that + * hangs off a `NostrEvent` row, and a group-signed event or a wrap is not one this app's + * feed should hold. The owed rows are [GroupDmOutbound], marked published once a relay + * accepts them, so a restart picks up where it left off. + */ +class GroupDmPublisher( + private val repository: GroupDmRepository, + private val transport: EventPublishTransport, + private val firstRetry: Duration = 1.minutes, + private val lastRetry: Duration = 30.minutes, +) { + private val logger = Logger.withTag("GroupDmPublisher") + + /** Runs until cancelled. */ + suspend fun run() { + repository.observeOwed().collectLatest { owed -> + var wait = firstRetry + var remaining = owed + while (remaining.isNotEmpty()) { + remaining = remaining.filterNot { publish(it) } + if (remaining.isEmpty()) break + logger.w("${remaining.size} direct message event(s) not yet taken by any relay; trying again in $wait") + remaining.forEach { repository.markAttempt(it, Clock.System.now() + wait) } + delay(wait) + wait = minOf(wait * 2, lastRetry) + } + } + } + + /** Sends [outbound] to every relay it names. Whether any accepted it. */ + suspend fun publish(outbound: GroupDmOutbound): Boolean { + val event = outbound.wrapJson?.let { runCatching { Event.fromJson(it) }.getOrNull() } ?: return false + val targets = outbound.relays.split(",").map { it.trim() }.filter { it.startsWith("wss://") }.distinct() + if (targets.isEmpty()) return false + var accepted = false + try { + withTimeout((RelayPool.PUBLISH_TIMEOUT * 2).milliseconds) { + transport.publishEvent( + nostrEvent = NostrEvent( + id = event.id, pubKey = event.pubKey, kind = event.kind, tags = event.tags, + content = event.content, sig = event.sig, + createdAt = kotlin.time.Instant.fromEpochSeconds(event.createdAt), + ), + relays = targets.map { RelayDTO(url = it, read = false, write = true) }.toSet(), + ).take(targets.size).collect { result -> + val ok = result.result as? NostrIncomingMessage.OkMessage + if (result.error == null && ok?.success == true) accepted = true + } + } + } catch (_: TimeoutCancellationException) { + // A relay that never answers. Whatever answered in time counts. + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + logger.e("Could not send ${event.id.take(8)} of kind ${event.kind}", e) + } + if (accepted) { + repository.markPublished(outbound, Clock.System.now()) + logger.i("${event.id.take(8)} of kind ${event.kind} is on a relay") + } + return accepted + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRelays.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRelays.kt new file mode 100644 index 00000000..2be72c92 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRelays.kt @@ -0,0 +1,109 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.GroupDmOutbound +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.RelayUrlInput +import mobi.giza.compose.nostr.Relays + +/** + * Where the group receives direct messages: a kind 10050 the group signs (D8 of + * docs/group-threshold-ecdh.md). + * + * A sender's app sends NIP-17 to the recipient's 10050 relays, and many send nothing when + * there are none, so signing one is the group's decision to receive. Until it has, no device + * subscribes for its mail. The signed list is a [GroupSignedEvent] row on every signer's + * device, read back by [relaysOf]; the proposer's device owes it to relays ([onSigned]). + */ +object GroupDmRelays { + const val KIND = 10050 + private const val RELAY_TAG = "relay" + + /** The relays a 10050's tags list, normalised, or null when any is not a public `wss://` relay or none is. */ + fun relaysIn(tags: Array>): List? { + val raw = tags.filter { it.size >= 2 && it[0] == RELAY_TAG }.map { it[1] } + if (raw.isEmpty()) return null + return raw.map { RelayUrlInput.relayUrlOrNull(it)?.url ?: return null }.distinct() + } + + fun tagsFor(relays: List): Array> = relays.map { arrayOf(RELAY_TAG, it) }.toTypedArray() + + /** What the setup screen starts from. */ + val defaultRelays: List get() = Relays.DefaultDMRelayList.map { it.url } + + /** + * Asks the group to sign [relays] as where it receives messages. + * + * @throws IllegalArgumentException when a relay is not one [RelayUrlInput] accepts: the + * signers would decline it ([GroupDmRelayRefusal]), so it is not proposed. + */ + suspend fun propose(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, relays: List): FrostSigningSession { + val normalised = relaysIn(tagsFor(relays)) ?: throw IllegalArgumentException("Every relay has to be a public wss:// address") + return FrostSigningManager.proposeSigning( + database = database, + localChatRoom = localChatRoom, + userPublicKey = userPublicKey, + kind = KIND, + tags = tagsFor(normalised), + content = "", + ) + } + + /** The newest 10050 the group signed in [chatRoomId], if it has signed one. */ + suspend fun signedListOf(database: GizaDatabase, chatRoomId: HexKey): GroupSignedEvent? = + database.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, KIND) + .filter { it.publicKey.equals(chatRoomId, ignoreCase = true) } + .maxByOrNull { it.createdAt } + + /** Where the group receives messages, or null while it has not opened them. */ + suspend fun relaysOf(database: GizaDatabase, chatRoomId: HexKey): List? = + signedListOf(database, chatRoomId)?.let { relaysIn(it.tags) } + + /** The relays a signed 10050 is sent to: the publish set, and the relays it names. */ + fun publishTargets(listed: List): List = + (Relays.eventPublishRelaySet.map { it.url } + listed).distinct() + + /** + * A 10050 the group just signed: owed to relays by the device that proposed it, through + * [GroupDmPublisher], with backoff. Any member can send it again from the broadcast screen. + */ + suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, signedEvents: List) { + if (!session.isCoordinator()) return + signedEvents.filter { it.kind == KIND && it.pubKey.equals(session.chatRoomId, ignoreCase = true) }.forEach { signed -> + val listed = relaysIn(signed.tags) ?: return@forEach + database.groupDmDao().insertOutbound( + GroupDmOutbound( + signingSessionId = session.id, + sealId = signed.id, + chatRoomId = session.chatRoomId, + recipient = session.chatRoomId, + relays = publishTargets(listed).joinToString(","), + wrapJson = signed.toJson(), + ) + ) + } + } +} + +/** + * A 10050 the group is asked to sign whose relays are not all public `wss://` addresses + * (D8 of docs/group-threshold-ecdh.md). Declined out loud, in the four places every refusal + * sits, for the reason a wallet's is: a device signs only what it can check, and a relay + * list senders cannot reach is the group's mail going nowhere. + */ +object GroupDmRelayRefusal { + const val REASON = "Giza doesn't sign a list of message relays that are not public wss:// addresses" + + fun of(event: Event): String? = + if (event.kind == GroupDmRelays.KIND && GroupDmRelays.relaysIn(event.tags) == null) { + "lists a message relay that is not a public wss:// address" + } else { + null + } + + fun of(events: List): String? = events.firstNotNullOfOrNull(::of) +} 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 a43e518e..3a1794e6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -138,6 +138,9 @@ interface ChatRepository { /** The confederation whose room [chatRoomId] is, by name, if its record verifies here. docs/confederation.md, Phase 13. */ suspend fun confederationOfRoom(chatRoomId: String): String? = null + /** What [chatRoomId]'s screen says about its direct messages, to [userPublicKey]. docs/group-threshold-ecdh.md. */ + suspend fun groupDmRow(chatRoomId: String, userPublicKey: HexKey): mobi.giza.compose.ui.view.state.GroupDmRow? = null + /** * Why these members cannot hold a subgroup ceremony together, or null when * they can. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt new file mode 100644 index 00000000..841d9d0f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt @@ -0,0 +1,30 @@ +package mobi.giza.compose.repository + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant +import kotlinx.coroutines.flow.Flow +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.GroupDmOutbound +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom + +/** + * A group's direct messages on this device, for the relay layer and the screens + * (docs/group-threshold-ecdh.md). + */ +interface GroupDmRepository { + /** What this device owes relays: a signed 10050, or a wrap of a message the group signed. */ + fun observeOwed(): Flow> + + suspend fun markPublished(outbound: GroupDmOutbound, at: Instant) + + suspend fun markAttempt(outbound: GroupDmOutbound, next: Instant) + + /** Where [chatRoomId] receives messages, as it changes; null while it has not opened them. */ + fun observeRelays(chatRoomId: HexKey): Flow?> + + /** Whether [userPublicKey] is a current admin of [chatRoomId] holding a share: who sees the group's mail (D4, D12). */ + suspend fun isCurrentAdmin(chatRoomId: HexKey, userPublicKey: HexKey): Boolean + + /** Asks the group to sign [relays] as where it receives messages (D8). */ + suspend fun proposeRelays(localChatRoom: LocalChatRoom, userPublicKey: HexKey, relays: List): FrostSigningSession +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt index 4fb9f820..ddeb8f1f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -8,6 +8,7 @@ import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.WalletRefusal +import mobi.giza.compose.managers.GroupDmRelays import mobi.giza.compose.nostr.RetiredKinds import mobi.giza.compose.nostr.frost.GovernanceStatementEvent import mobi.giza.compose.nostr.frost.GroupKeyStateEvent @@ -133,6 +134,14 @@ object ProposedEvent { ConfederationKinds.WITHDRAWAL -> Summary(label = "Withdrawing a confederation proposal", detail = event.content) + // Where the group receives direct messages: the group's decision to be written + // to at all, said as that, with the relays it names. docs/group-threshold-ecdh.md, D8. + GroupDmRelays.KIND -> Summary( + label = "Where the group receives messages", + detail = GroupDmRelays.relaysIn(event.tags)?.joinToString(" ยท ") + ?: "A relay that is not a public wss:// address", + ) + // A Bennu wallet's: declined on arrival, and said as what it is rather than // as a number. docs/giza-wallet-removal.md. in RetiredKinds.WALLET, in RetiredKinds.GROUP_LIGHTNING -> WALLET 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 79fb2290..4590cd5b 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 @@ -10,6 +10,16 @@ import mobi.giza.compose.resources.no_posts_yet import mobi.giza.compose.resources.posts import mobi.giza.compose.ui.composable.navigation.routes.GroupPostsRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupDmSetupRoute +import mobi.giza.compose.ui.view.state.GroupDmRow +import androidx.compose.material.icons.filled.Mail +import mobi.giza.compose.resources.open_the_groups_messages +import mobi.giza.compose.resources.group_messages +import mobi.giza.compose.resources.this_group_receives_direct_messages +import mobi.giza.compose.resources.nobody_can_write_to_the_group_yet +import mobi.giza.compose.resources.nothing_unread +import mobi.giza.compose.resources.n_unread +import mobi.giza.compose.resources.only_its_admins_read_them import mobi.giza.compose.ExperimentalFeatures import androidx.compose.material.icons.filled.Hub import mobi.giza.compose.resources.confederations @@ -746,6 +756,25 @@ fun ChatRoomDetailScreen( } } + // The group's direct messages: the way to open them for an + // admin, the way in once open, and for anyone else only that + // the group receives them. docs/group-threshold-ecdh.md. + chatRoomDetailUIState.groupDmRow?.let { row -> + item { + GroupDmRowCard( + row = row, + onClick = { + onNavigateToRoute.invoke( + GroupDmSetupRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + ) + ) + } + ) + } + } + // The untyped way in: an unsigned event, pasted. It // lands on its kind's screen above once the quorum // signs. Behind the same gate as the editors, and the @@ -2180,3 +2209,37 @@ private fun ConfederationsRow( ) } } + +/** A group's direct messages, on its screen (docs/group-threshold-ecdh.md, Phases 6 and 8). */ +@Composable +private fun GroupDmRowCard( + row: GroupDmRow, + onClick: () -> Unit, +) { + val headline = when (row) { + GroupDmRow.OpenMessages -> stringResource(Res.string.open_the_groups_messages) + is GroupDmRow.Messages -> stringResource(Res.string.group_messages) + GroupDmRow.ReceivesMessages -> stringResource(Res.string.this_group_receives_direct_messages) + } + val supporting = when (row) { + GroupDmRow.OpenMessages -> stringResource(Res.string.nobody_can_write_to_the_group_yet) + is GroupDmRow.Messages -> + if (row.unread == 0) stringResource(Res.string.nothing_unread) else stringResource(Res.string.n_unread, row.unread) + GroupDmRow.ReceivesMessages -> stringResource(Res.string.only_its_admins_read_them) + } + val content: @Composable () -> Unit = { + ListItem( + leadingContent = { Icon(Icons.Default.Mail, contentDescription = Decorative) }, + trailingContent = if (row == GroupDmRow.ReceivesMessages) null else { + { Icon(Icons.Default.ChevronRight, contentDescription = Decorative) } + }, + headlineContent = { Text(text = headline) }, + supportingContent = { Text(text = supporting) }, + ) + } + if (row == GroupDmRow.ReceivesMessages) { + Card(modifier = Modifier.fillMaxWidth()) { content() } + } else { + Card(modifier = Modifier.fillMaxWidth(), onClick = onClick) { content() } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmSetupScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmSetupScreen.kt new file mode 100644 index 00000000..b05344da --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmSetupScreen.kt @@ -0,0 +1,165 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Draw +import androidx.compose.material3.BottomAppBar +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Modifier +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupDmRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.anyone_on_nostr_will_be_able_to_write_to_the_group +import mobi.giza.compose.resources.ask_the_group_to_sign +import mobi.giza.compose.resources.could_not_ask_the_group_to_sign_its_message_relays +import mobi.giza.compose.resources.every_relay_has_to_be_a_public_wss_address +import mobi.giza.compose.resources.message_relays +import mobi.giza.compose.resources.one_wss_address_per_line +import mobi.giza.compose.resources.only_a_current_admin_can_open_the_groups_messages +import mobi.giza.compose.resources.open_the_groups_messages +import mobi.giza.compose.resources.senders_apps_deliver_to_these_relays +import mobi.giza.compose.resources.the_group_signs_where_it_receives_messages +import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.buttons.ExtendedFab +import mobi.giza.compose.ui.composable.widgets.rememberNotifier +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.GroupDmSetupViewModel +import mobi.giza.compose.ui.view.state.GroupDmSetupUIState +import org.jetbrains.compose.resources.stringResource + +/** + * Where a group decides to receive direct messages (D8 of docs/group-threshold-ecdh.md): the + * relays senders deliver to, and what signing them means, said before the button. The button + * proposes; the group's messages open when a quorum has signed, so the screen hands over to + * the signing session rather than going back. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupDmSetupScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + chatRepository: ChatRepository, + groupDmRepository: GroupDmRepository, + onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: GroupDmSetupViewModel = viewModel( + factory = GroupDmSetupViewModel.factory(chatRoomId, activeUserPublicKey, chatRepository, groupDmRepository) + ) + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_its_message_relays) + val canSign = LocalCanSign.current + + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + is GroupDmSetupUIState.Loading -> LoadingDataIndicator() + // The room came from a navigation argument; reading it again fails the same way. + is GroupDmSetupUIState.Error -> ErrorState(message = state.message, onRetry = null) + is GroupDmSetupUIState.Loaded -> { + val relaysField = rememberTextFieldState(state.relays.joinToString("\n")) + val relays = viewModel.relaysOf(relaysField.text.toString()) + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + modifier = Modifier.imePadding(), + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.open_the_groups_messages)) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + bottomBar = { + BottomAppBar( + actions = {}, + floatingActionButton = { + ExtendedFab( + label = stringResource(Res.string.ask_the_group_to_sign), + icon = { Icon(Icons.Default.Draw, contentDescription = Decorative) }, + enabled = state.canPropose && canSign && relays != null && !viewModel.isActionPending, + onClick = { + viewModel.propose( + text = relaysField.text.toString(), + onSuccess = { sessionId -> + onNavigateToRouteAndPopUpInclusive( + FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId) + ) + }, + onFailure = { notify(couldNotPropose) }, + ) + }, + ) + }, + ) + }, + ) { innerPadding -> + Column( + modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + Text( + text = stringResource(Res.string.anyone_on_nostr_will_be_able_to_write_to_the_group), + style = MaterialTheme.typography.bodyLarge, + ) + Text( + text = stringResource(Res.string.the_group_signs_where_it_receives_messages), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + if (!state.canPropose) { + Text( + text = stringResource(Res.string.only_a_current_admin_can_open_the_groups_messages), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } + OutlinedTextField( + state = relaysField, + modifier = Modifier.fillMaxWidth(), + label = { Text(stringResource(Res.string.message_relays)) }, + placeholder = { Text(stringResource(Res.string.one_wss_address_per_line)) }, + lineLimits = TextFieldLineLimits.MultiLine(minHeightInLines = 3), + isError = relays == null, + supportingText = { + Text( + stringResource( + if (relays == null) Res.string.every_relay_has_to_be_a_public_wss_address + else Res.string.senders_apps_deliver_to_these_relays + ) + ) + }, + ) + } + } + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 66e2df5b..136ecc7f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -223,6 +223,9 @@ fun GizaNavHost( activeIdentity = sovereignWalletViewModel.activeIdentity, ) } + val databaseGroupDmRepository = remember { + mobi.giza.compose.database.repository.DatabaseGroupDmRepository(database = auxDatabaseManager.auxDatabase) + } val databaseMarmotRepository = remember { DatabaseMarmotRepository( database = auxDatabaseManager.auxDatabase, @@ -264,6 +267,7 @@ fun GizaNavHost( relayRepository = databaseNostrRepository, scope = applicationIOScope, confederationRepository = databaseConfederationRepository, + groupDmRepository = databaseGroupDmRepository, ) ) @@ -1293,6 +1297,23 @@ fun GizaNavHost( } ) } + // Where a group receives direct messages: docs/group-threshold-ecdh.md, D8. + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + mobi.giza.compose.ui.composable.GroupDmSetupScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + chatRepository = databaseChatRepository, + groupDmRepository = databaseGroupDmRepository, + onNavigateToRouteAndPopUpInclusive = { signingRoute -> + navController.navigate(route = signingRoute) { + popUpTo(route) { inclusive = true } + } + }, + onNavigateBack = { navController.popBackStack() } + ) + } // A group's confederations: docs/confederation.md. composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmSetupRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmSetupRoute.kt new file mode 100644 index 00000000..0bcd6651 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmSetupRoute.kt @@ -0,0 +1,10 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** Where a group chooses the relays it receives messages on. docs/group-threshold-ecdh.md, D8. */ +@Serializable +data class GroupDmSetupRoute( + val activeUserPublicKey: String, + val chatRoomId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt index 7af1e335..3ef5d611 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt @@ -300,7 +300,7 @@ class BroadcastGroupSignedEventViewModel( * confederation events, which a member sends again by hand when the device that * signed for them never got them out (docs/confederation.md, D9). */ - val BROADCASTABLE_KINDS: Set = setOf(MetadataEvent.KIND, TextNoteEvent.KIND) + ConfederationKinds.ALL + val BROADCASTABLE_KINDS: Set = setOf(MetadataEvent.KIND, TextNoteEvent.KIND, mobi.giza.compose.managers.GroupDmRelays.KIND) + ConfederationKinds.ALL /** * Sends [signedEvent] to [targets] and says what each relay answered. 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 d048388b..96f22602 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 @@ -134,6 +134,9 @@ class ChatRoomDetailViewModel( groupPosts = chatRepository.groupPosts(chatRoomId), confederationProposalCount = chatRepository.confederationProposalCount(chatRoomId), confederationName = chatRepository.confederationOfRoom(chatRoomId), + groupDmRow = runCatching { chatRepository.groupDmRow(chatRoomId, localChatRoom.chatRoom.userPublicKey) } + .onFailure { if (it is CancellationException) throw it else logger.w(throwable = it) { "Couldn't read $chatRoomId's messages row" } } + .getOrNull(), canProposeAsGroup = canSign && roomIsOpen, subgroupsNeedAWallet = canSign && subgroupsNeedAWallet, canGovern = canGovern, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmSetupViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmSetupViewModel.kt new file mode 100644 index 00000000..1835b240 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmSetupViewModel.kt @@ -0,0 +1,90 @@ +package mobi.giza.compose.ui.view.model + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import mobi.giza.compose.managers.GroupDmRelays +import mobi.giza.compose.nostr.RelayUrlInput +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupDmRepository +import mobi.giza.compose.ui.view.state.GroupDmSetupUIState + +/** + * Asks the group to sign where it receives direct messages (D8 of + * docs/group-threshold-ecdh.md). Proposing is the whole of it: the group opens its messages + * when a quorum signs, not when the button is pressed. + */ +class GroupDmSetupViewModel( + val chatRoomId: String, + val activeUserPublicKey: HexKey, + val chatRepository: ChatRepository, + val groupDmRepository: GroupDmRepository, +) : ViewModel() { + private val logger = Logger.withTag("GroupDmSetupViewModel") + + var uiState: GroupDmSetupUIState by mutableStateOf(GroupDmSetupUIState.Loading) + private set + + var isActionPending: Boolean by mutableStateOf(false) + private set + + init { + viewModelScope.launch(Dispatchers.IO) { + val room = chatRepository.getChatRoomByIdentifier(chatRoomId) + uiState = if (room == null) { + GroupDmSetupUIState.Error("Couldn't find the chat room") + } else { + GroupDmSetupUIState.Loaded( + localChatRoom = room, + relays = groupDmRepository.observeRelays(chatRoomId).first() ?: GroupDmRelays.defaultRelays, + canPropose = groupDmRepository.isCurrentAdmin(chatRoomId, activeUserPublicKey), + ) + } + } + } + + /** The lines of [text] as relays, or null when any is not a public `wss://` address or there are none. */ + fun relaysOf(text: String): List? { + val lines = text.lines().map { it.trim() }.filter { it.isNotEmpty() } + if (lines.isEmpty()) return null + return lines.map { RelayUrlInput.relayUrlOrNull(it)?.url ?: return null }.distinct() + } + + fun propose(text: String, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + val loaded = uiState as? GroupDmSetupUIState.Loaded ?: return + val relays = relaysOf(text) ?: return onFailure() + if (isActionPending) return + isActionPending = true + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { groupDmRepository.proposeRelays(loaded.localChatRoom, activeUserPublicKey, relays) } + .onFailure { logger.e("Couldn't propose the group's message relays", it) } + .getOrNull() + withContext(Dispatchers.Main) { + isActionPending = false + if (session != null) onSuccess(session.id) else onFailure() + } + } + } + + companion object { + fun factory( + chatRoomId: String, + activeUserPublicKey: HexKey, + chatRepository: ChatRepository, + groupDmRepository: GroupDmRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { GroupDmSetupViewModel(chatRoomId, activeUserPublicKey, chatRepository, groupDmRepository) } + } + } +} 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 b4a7e072..69296839 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 @@ -72,6 +72,7 @@ class SynchronizationViewModel( val relayRepository: RelayRepository, val scope: CoroutineScope, val confederationRepository: ConfederationRepository? = null, + val groupDmRepository: mobi.giza.compose.repository.GroupDmRepository? = null, ): ViewModel() { val relaysSocketManager = RelaysSocketManager( @@ -99,6 +100,11 @@ class SynchronizationViewModel( ConfederationPublisher(repository = it, transport = relaysSocketManager) } + /** Sends the group's signed 10050s and message wraps (docs/group-threshold-ecdh.md, D8 and D10). */ + private val groupDmPublisher = groupDmRepository?.let { + mobi.giza.compose.managers.GroupDmPublisher(repository = it, transport = relaysSocketManager) + } + companion object { private const val TAG = "SynchronizationViewModel" @@ -150,6 +156,7 @@ class SynchronizationViewModel( relayRepository: RelayRepository, scope: CoroutineScope, confederationRepository: ConfederationRepository? = null, + groupDmRepository: mobi.giza.compose.repository.GroupDmRepository? = null, ): ViewModelProvider.Factory = viewModelFactory { initializer { SynchronizationViewModel( @@ -159,6 +166,7 @@ class SynchronizationViewModel( relayRepository = relayRepository, scope = scope, confederationRepository = confederationRepository, + groupDmRepository = groupDmRepository, ) } } @@ -283,6 +291,17 @@ class SynchronizationViewModel( } } } + // What the group's direct messages owe relays. + // docs/group-threshold-ecdh.md, D8 and D10. + groupDmPublisher?.takeIf { ExperimentalFeatures.groupDirectMessages }?.let { publisher -> + launch(Dispatchers.IO) { + runCatching { publisher.run() } + .onFailure { + if (it is CancellationException) throw it + logger.e("Publishing the group's direct messages stopped", it) + } + } + } // A key ceremony this profile opened, taken from a key to a // working room without anybody pressing a button: the key // state proposed, a subgroup's certificate asked for, the diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 03a951bd..c4961a65 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -76,6 +76,8 @@ sealed interface ChatRoomDetailUIState { val confederationProposalCount: Int = 0, /** The confederation whose room this is, by name: its membership is fixed until it can sign. */ val confederationName: String? = null, + /** What the group's direct messages show here, or nothing. docs/group-threshold-ecdh.md. */ + val groupDmRow: GroupDmRow? = null, /** * Whether this device could put a profile or a post to the group's quorum: * a Marmot room it has not left, not disbanded, where it holds a share of diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmRow.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmRow.kt new file mode 100644 index 00000000..d1c2c238 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmRow.kt @@ -0,0 +1,16 @@ +package mobi.giza.compose.ui.view.state + +/** + * What a group's screen says about its direct messages (docs/group-threshold-ecdh.md, + * Phases 6 and 8). Null when there is nothing to say: the feature off, or no key. + */ +sealed interface GroupDmRow { + /** A current admin, and the group has not signed where it receives messages. */ + data object OpenMessages : GroupDmRow + + /** A current admin of a group that receives messages: the way in, with what is unread. */ + data class Messages(val unread: Int) : GroupDmRow + + /** Anyone else, where the group's 10050 is signed: it is public, and nothing more is. */ + data object ReceivesMessages : GroupDmRow +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmSetupUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmSetupUIState.kt new file mode 100644 index 00000000..15e17e59 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmSetupUIState.kt @@ -0,0 +1,15 @@ +package mobi.giza.compose.ui.view.state + +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom + +sealed interface GroupDmSetupUIState { + data object Loading : GroupDmSetupUIState + data class Error(val message: String) : GroupDmSetupUIState + data class Loaded( + val localChatRoom: LocalChatRoom, + /** What the field starts from: what the group signed, or the app's DM relays. */ + val relays: List, + /** A current admin holding a share: who may ask. */ + val canPropose: Boolean, + ) : GroupDmSetupUIState +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmRelaysJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmRelaysJvmTest.kt new file mode 100644 index 00000000..915ceb37 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmRelaysJvmTest.kt @@ -0,0 +1,145 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.crypto.verify +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.types.FrostSigningStage +import mobi.giza.compose.database.repository.DatabaseGroupDmRepository +import mobi.giza.compose.network.dto.RelayDTO +import mobi.giza.compose.network.relays.EventPublishTransport +import mobi.giza.compose.network.relays.NostrPublishResult +import mobi.giza.compose.network.sockets.NostrIncomingMessage +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.text.ProposedEvent + +/** + * Phase 6 of docs/group-threshold-ecdh.md: the group's decision to receive direct messages, a + * kind 10050 it signs, published unchanged by the proposer's device, and refused when it lists + * a relay nobody can reach. + */ +class GroupDmRelaysJvmTest { + private val net = GroupDmNetwork(n = 3, t = 2) + + @AfterTest + fun tearDown() = net.close() + + private class Transport : EventPublishTransport { + val sent = mutableListOf>>() + override suspend fun publishEvent(nostrEvent: NostrEvent, relays: Set): Flow { + sent += nostrEvent to relays.map { it.url }.toSet() + return flowOf(*relays.map { NostrPublishResult(result = NostrIncomingMessage.OkMessage(eventId = nostrEvent.id, success = true), relayUrl = it.url) }.toTypedArray()) + } + } + + private suspend fun signRelays(relays: List): String { + val a = net.devices[0] + val b = net.devices[1] + val session = GroupDmRelays.propose(a.db, a.room, a.publicKey, relays) + net.pump() + FrostSigningManager.approve(b.db, b.room, session.id) + net.pump() + assertEquals(FrostSigningStage.COMPLETE, a.db.frostSigningSessionDao().getSessionById(session.id)?.stage) + return session.id + } + + @Test + fun `a signed 10050 is published unchanged by its proposer, and writes no NostrEvent row`(): Unit = runBlocking { + net.install() + net.all() + val a = net.devices[0] + val sessionId = signRelays(listOf("wss://dm.example.com/", "wss://inbox.example.org")) + + val owed = a.db.groupDmDao().getOutbound(sessionId).single() + val signed = Event.fromJson(assertNotNull(owed.wrapJson)) + assertEquals(GroupDmRelays.KIND, signed.kind) + assertEquals(net.roomId, signed.pubKey) + assertTrue(signed.verify(), "the group's own signature") + assertEquals(listOf("wss://dm.example.com/", "wss://inbox.example.org/"), GroupDmRelays.relaysIn(signed.tags)) + // Only the proposer owes it. + assertEquals(emptyList(), net.devices[1].db.groupDmDao().getOutbound(sessionId)) + + val transport = Transport() + assertTrue(GroupDmPublisher(DatabaseGroupDmRepository(a.db), transport).publish(owed)) + val (sent, to) = transport.sent.single() + assertEquals(signed.id, sent.id) + assertEquals(signed.sig, sent.sig) + assertTrue("wss://dm.example.com/" in to && "wss://inbox.example.org/" in to) + assertNotNull(a.db.groupDmDao().getOutbound(sessionId).single().publishedAt) + + net.devices.forEach { device -> + assertNull(device.db.nostrEventDao().getNostrEventById(signed.id), "no NostrEvent row on $device") + assertEquals(listOf("wss://dm.example.com/", "wss://inbox.example.org/"), GroupDmRelays.relaysOf(device.db, net.roomId)) + } + } + + @Test + fun `the transcript says the group can receive messages, and then that it changed where`(): Unit = runBlocking { + net.install() + net.all() + signRelays(listOf("wss://dm.example.com")) + Thread.sleep(1100) // a second 10050 needs a later created_at to be the newer list + signRelays(listOf("wss://other.example.com")) + + net.devices.forEach { device -> + val lines = device.db.chatMessageDao().getChatMessagesByChatRoomId(net.roomId) + .map { it.chatMessage } + .filter { it.messageType == ChatMessage.TYPE_GROUP_DM_RELAYS_SIGNED } + .sortedBy { it.createdAt } + .map { it.content } + assertEquals(listOf("The group can now receive messages", "The group changed where it receives messages"), lines, "$device") + assertEquals(listOf("wss://other.example.com/"), GroupDmRelays.relaysOf(device.db, net.roomId)) + } + } + + // --- the refusal, on the proposal harness + + private val harness = SigningProposalHarness() + + @AfterTest + fun closeHarness() { + RoomAdmins.override = null + harness.close() + } + + private fun proposeRelayList(relays: List) = runBlocking { + harness.propose(harness.members[0]) { db, room -> + FrostSigningManager.proposeSigning(db, room, harness.members[0], kind = GroupDmRelays.KIND, tags = relays.map { arrayOf("relay", it) }.toTypedArray(), content = "") + } + } + + @Test + fun `a 10050 listing a relay that is not public wss is declined with its reason`(): Unit = runBlocking { + val sent = proposeRelayList(listOf("wss://fine.example.com", "ws://plain.example.com")) + harness.deliver(sent, harness.members[1]) + val session = assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id)) + assertNotNull(session.signDeclinedAt) + assertEquals(listOf(GroupDmRelayRefusal.REASON), harness.queued(FrostSigningEvents.DECLINE).map { it.content }) + + val localhost = proposeRelayList(listOf("wss://localhost:7777")) + harness.deliver(localhost, harness.members[1]) + assertEquals(listOf(GroupDmRelayRefusal.REASON), harness.queued(FrostSigningEvents.DECLINE).map { it.content }) + } + + @Test + fun `a 10050 of public relays is put to the member, named for what it is`(): Unit = runBlocking { + val sent = proposeRelayList(listOf("wss://fine.example.com")) + harness.deliver(sent, harness.members[1]) + val session = assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id)) + assertNull(session.signDeclinedAt) + val items = harness.db.frostSigningSessionDao().getItems(session.id) + assertTrue(FrostSigningManager.isAwaitingApproval(session, items)) + val summary = ProposedEvent.summarize(Event.fromJson(items.single().unsignedEventJson)) + assertEquals("Where the group receives messages", summary.label) + assertEquals("wss://fine.example.com/", summary.detail) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmTodayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmTodayJvmTest.kt index 1d0ea4e9..048f7f5a 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmTodayJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmTodayJvmTest.kt @@ -96,13 +96,13 @@ class GroupDmTodayJvmTest { assertAskedBlind(proposeKind(SealEvent.KIND, "AqH1ciphertext"), SealEvent.KIND) } - /** Phase 6 flips this: a 10050 is named, and declined unless its relays are public. */ + /** Flipped by Phase 6: a 10050 is named for what it is, and declined unless its relays are public (GroupDmRelaysJvmTest). */ @Test - fun `a peer's kind 10050 is asked as a raw kind`() { - assertAskedBlind( - proposeKind(10050, "", arrayOf(arrayOf("relay", "wss://relay.example"))), - 10050, - ) + fun `a peer's kind 10050 is no longer asked as a raw kind`() = runBlocking { + val sent = proposeKind(10050, "", arrayOf(arrayOf("relay", "wss://relay.example"))) + harness.deliver(sent, bob) + val items = harness.db.frostSigningSessionDao().getItems(sent.session.id) + assertEquals("Where the group receives messages", ProposedEvent.summarize(Event.fromJson(items.single().unsignedEventJson)).label) } /** Phase 7 flips this. */