From d21d6ecd05c8994d673e7731a89dc57152693a75 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 02:05:46 +0200 Subject: [PATCH] feat: the group answers from its inbox, once its quorum has read and signed the reply (group-inbox, Phase 8) InboxReplies builds a reply as one rumor authored by the group, sealed from the announced inbox key to each recipient's announced key (or their identity) and once to the group itself, per nostr-protocol/nips#2361, and proposes the seals as one batch with the manifest beside them, sealed to the inbox key, so a member who is not an admin learns how many seals there are and nothing else. Every signer reads the reply before signing it: InboxRefusal opens the manifest and every seal, and declines out loud a copy that says something else, a seal to a key its recipient did not announce, a forged 10044, a recipient the reply does not name, a blank reply, a seal dated outside two days, or anything it cannot read -- including on a device that holds no inbox key. The manifest rides a resend, and the signing screen says the reply's words, its recipients, and who has announced no key. Once signed, the proposer's device wraps each seal for its recipient's relays and the group's copy for the group's, owed through GroupInboxPublisher, and files the copy at once; other admins file it when it arrives. A reply not yet on a relay offers Send again. The conversation screen gets the composer, which warns about a recipient whose app may not open a message from a group. A seal draws nothing in the room's transcript. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 8 + .../compose/database/model/ChatMessage.kt | 6 + .../DatabaseFrostSigningRepository.kt | 8 +- .../DatabaseGroupInboxRepository.kt | 15 + .../compose/managers/FrostSigningManager.kt | 18 +- .../giza/compose/managers/InboxRefusal.kt | 116 +++++++- .../giza/compose/managers/InboxReplies.kt | 221 +++++++++++++++ .../repository/FrostSigningRepository.kt | 7 +- .../repository/GroupInboxRepository.kt | 15 + .../mobi/giza/compose/text/ProposedEvent.kt | 8 + .../ui/composable/FrostSigningScreen.kt | 2 +- .../GroupInboxConversationScreen.kt | 93 ++++++- .../ui/view/model/FrostSigningViewModel.kt | 4 +- .../ui/view/model/GroupInboxViewModel.kt | 24 ++ .../ui/view/state/FrostSigningUIState.kt | 8 +- .../ui/view/state/GroupInboxUIState.kt | 6 + .../giza/compose/text/ProposedEventTest.kt | 6 +- .../managers/GroupInboxTodayJvmTest.kt | 16 +- .../compose/managers/InboxReplyJvmTest.kt | 259 ++++++++++++++++++ 19 files changed, 812 insertions(+), 28 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxReplyJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 97a00b66..86a0f19a 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -773,4 +773,12 @@ Couldn't start the ceremony The inbox key ceremony started None of those is a relay a stranger could reach + Reply as the group + Ask the group to sign this reply + The group's quorum has to sign this before it is sent. It goes out in the group's name, not yours, and can't be taken back once signed. + %1$s has announced no inbox key, so their app may not be able to open a message from a group. + Couldn't ask the group to sign this reply. + Not yet on a relay + Send again + Sent again 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 e393cb76..338d20da 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 @@ -1302,6 +1302,12 @@ data class ChatMessage( // `InboxKeyRitualManager` files them and writes its own lines. in InboxKeyRitualEvents.ALL -> null + // A reply's seals, signed by the group (docs/group-inbox.md, D10). The + // signing session's own lines say the group signed something; a line naming + // the reply would reach members who are not admins, who must learn nothing of + // the inbox (D9). + com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent.KIND -> null + ChatEvent.KIND -> { ChatMessage( giftWrapPayloadId = null, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt index 70797caf..764db422 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt @@ -27,8 +27,12 @@ class DatabaseFrostSigningRepository( ): FrostSigningRepository { private val logger = Logger.withTag(TAG) - override suspend fun confederationNotes(chatRoomId: String, sessionId: String, events: List): List = - runCatching { ConfederationRefusal.notes(database, chatRoomId, sessionId, events) }.getOrDefault(emptyList()) + override suspend fun proposalNotes(chatRoomId: String, sessionId: String, events: List): List = + runCatching { ConfederationRefusal.notes(database, chatRoomId, sessionId, events) }.getOrDefault(emptyList()) + + runCatching { + val user = database.frostSigningSessionDao().getSessionById(sessionId)?.userPublicKey ?: return@runCatching emptyList() + mobi.giza.compose.managers.InboxRefusal.notes(database, chatRoomId, user, sessionId, events) + }.getOrDefault(emptyList()) override fun observeSessionById(sessionId: String): Flow = database.frostSigningSessionDao().observeSessionById(sessionId) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt index 0f6db750..d4bc3727 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt @@ -21,6 +21,7 @@ import mobi.giza.compose.identity.Identity import mobi.giza.compose.managers.GroupInboxManager import mobi.giza.compose.managers.InboxAnnouncements import mobi.giza.compose.managers.InboxKeyRitualManager +import mobi.giza.compose.managers.InboxReplies import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents import mobi.giza.compose.repository.GroupInboxRepository @@ -112,4 +113,18 @@ class DatabaseGroupInboxRepository( override suspend fun abandon(localChatRoom: LocalChatRoom, ceremonyId: String): Boolean = InboxKeyRitualManager.abandon(database, localChatRoom, ceremonyId) + + override suspend fun proposeReply(localChatRoom: LocalChatRoom, conversationId: String, text: String): String = + InboxReplies.propose(database, localChatRoom, localChatRoom.chatRoom.userPublicKey, conversationId, text).id + + override suspend fun withoutAnnouncedKey(publicKeys: List): List = + publicKeys.filterNot { InboxReplies.hasAnnouncedKey(database, it) } + + override suspend fun unsentReplies(chatRoomId: String): Set = + database.groupInboxDao().getMessages(chatRoomId) + .mapNotNull { it.signingSessionId } + .filter { session -> database.groupInboxDao().getPublicationsFor(session).any { it.publishedAt == null } } + .toSet() + + override suspend fun sendAgain(sessionId: String): Boolean = InboxReplies.sendAgain(database, sessionId) } 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 720eb208..0b8336a4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -45,6 +45,7 @@ import mobi.giza.compose.database.model.types.ShareGenerationState import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.inbox.InboxReplyManifest import mobi.giza.compose.nostr.frost.GovernanceStatementEvent import mobi.giza.compose.nostr.frost.GroupKeyStateEvent @@ -723,14 +724,17 @@ object FrostSigningManager { // The group's inbox: an announcement of a key its admins did not make together, or // of one since replaced, or relays a stranger could not reach, is declined before // anybody is asked. docs/group-inbox.md, D5. + // A reply from the group's inbox carries its manifest beside the seals (D11), kept so + // approval can read the reply again and the signed seals can be sent. + val inboxManifest = InboxReplyManifest.sealedIn(innerEvent.tags) if (InboxRefusal.involves(unsignedEvents)) { - InboxRefusal.of(database, localChatRoom, userPublicKey, unsignedEvents)?.let { why -> + InboxRefusal.of(database, localChatRoom, userPublicKey, unsignedEvents, inboxManifest)?.let { why -> logger.w("Signing proposal $sessionId: $why") 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)) - InboxRefusal.remember(database, sessionId, localChatRoom.chatRoom.id, why) + InboxRefusal.remember(database, sessionId, localChatRoom.chatRoom.id, why, inboxManifest) announceStarted(database, declined) return declined } @@ -779,6 +783,9 @@ object FrostSigningManager { database.frostSigningSessionDao().upsert(session) database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) confederation?.let { ConfederationRefusal.remember(database, sessionId, it, null) } + if (inboxManifest != null && InboxRefusal.involves(unsignedEvents)) { + InboxRefusal.remember(database, sessionId, localChatRoom.chatRoom.id, null, inboxManifest) + } announceStarted(database, session) logger.i( @@ -1081,7 +1088,7 @@ object FrostSigningManager { if (session.subject != FrostSigningSubject.EVENTS) return null val events = items.mapNotNull { Event.fromJsonOrNull(it.unsignedEventJson) } if (!InboxRefusal.involves(events)) return null - return InboxRefusal.of(database, localChatRoom, session.userPublicKey, events) + return InboxRefusal.of(database, localChatRoom, session.userPublicKey, events, database.groupInboxDao().getSigning(session.id)?.manifest) } /** Whether [session] is waiting on this device and is a wallet's to sign. */ @@ -1464,6 +1471,7 @@ object FrostSigningManager { // proposed the announcement owes it to relays. docs/group-inbox.md, D7. try { InboxAnnouncements.onSigned(database, session, signedEvents) + InboxReplies.onSigned(database, session, signedEvents) } catch (e: Throwable) { logger.e("Signed session ${session.id} but could not file its inbox announcement", e) } @@ -2526,7 +2534,9 @@ object FrostSigningManager { FrostSigningEvents.PROPOSAL, FrostSigningEvents.encodeProposal(unsigned), // What a confederation event is checked with goes again with it. - ConfederationRefusal.carriedTagsFor(database, sessionId) + ConfederationRefusal.carriedTagsFor(database, sessionId) + + // And a reply's manifest (docs/group-inbox.md, D11). + InboxRefusal.carriedTagsFor(database, sessionId) ) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt index 12914330..e21aab0e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt @@ -9,6 +9,13 @@ import mobi.giza.compose.database.model.InboxKeyCeremony import mobi.giza.compose.database.model.InboxSigning import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.nostr.inbox.InboxAnnouncement +import mobi.giza.compose.nostr.inbox.InboxReplyManifest +import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.nostr.inbox.InboxWire +import mobi.giza.compose.database.model.InboxKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.verify +import kotlin.time.Clock /** * What a device declines, out loud, when the group is asked to sign something about its inbox @@ -31,9 +38,20 @@ object InboxRefusal { const val KEY_SHAPE = "Giza doesn't sign an inbox key announcement it would not write" const val RELAYS_SHAPE = "Giza doesn't sign a list of inbox relays a stranger could not reach" + // A reply (D12): every signer reads it before signing it. + const val REPLY_UNREADABLE = "Giza doesn't sign a sealed message it can't read" + const val REPLY_NO_KEY = "This device holds no inbox key for this group" + const val REPLY_MISMATCH = "Giza doesn't sign a reply whose copies don't all say the same thing to the people it names" + const val REPLY_WRONG_KEY = "Giza doesn't sign a reply sealed to a key its recipient didn't announce" + const val REPLY_BLANK = "Giza doesn't sign a reply with nothing in it" + const val REPLY_TIME = "Giza doesn't sign a reply dated outside the last two days" + + private const val TWO_DAYS = 2 * 24 * 60 * 60L + private const val CLOCK_SLACK = 10 * 60L + /** Whether any of [events] is one this refusal is about. */ fun involves(events: List): Boolean = - events.any { it.kind == InboxAnnouncement.KEY_KIND || it.kind == InboxAnnouncement.RELAYS_KIND } + events.any { it.kind == InboxAnnouncement.KEY_KIND || it.kind == InboxAnnouncement.RELAYS_KIND || it.kind == InboxSeal.KIND } /** * Why this device declines to sign [events] in [localChatRoom] as [userPublicKey] sees it, or @@ -44,7 +62,13 @@ object InboxRefusal { localChatRoom: LocalChatRoom, userPublicKey: HexKey, events: List, + /** A reply's sealed manifest, as its proposal carried it (D11). */ + manifest: String? = null, + now: Long = Clock.System.now().epochSeconds, ): String? { + if (events.any { it.kind == InboxSeal.KIND }) { + return replyRefusal(database, localChatRoom.chatRoom.id, userPublicKey, events, manifest, now) + } for (event in events) { when (event.kind) { InboxAnnouncement.RELAYS_KIND -> @@ -80,6 +104,96 @@ object InboxRefusal { return null } + /** What a signer reads a reply with: the key that opened its manifest, the manifest, and the one rumor. */ + data class ReadReply(val key: InboxKey, val manifest: InboxReplyManifest, val rumor: Event) + + /** + * D12's checks on a batch of seals. A signer reads the reply before signing it: it opens + * the manifest, checks every seal is sealed from the announced generation to the key its + * recipient announced (or their identity), opens every one, and refuses unless they all hold + * the same rumor, written by the group to exactly the people the manifest names. + */ + private suspend fun replyRefusal(database: GizaDatabase, roomId: HexKey, userPublicKey: HexKey, events: List, manifest: String?, now: Long): String? { + if (events.any { it.kind != InboxSeal.KIND }) return REPLY_UNREADABLE + val read = when (val result = readReply(database, roomId, userPublicKey, events, manifest)) { + is Read.Refused -> return result.reason + is Read.Ok -> result.reply + } + if (read.rumor.content.isBlank()) return REPLY_BLANK + if (events.any { it.createdAt < now - TWO_DAYS - CLOCK_SLACK || it.createdAt > now + CLOCK_SLACK }) return REPLY_TIME + return null + } + + private sealed interface Read { + data class Ok(val reply: ReadReply) : Read + data class Refused(val reason: String) : Read + } + + private suspend fun readReply(database: GizaDatabase, roomId: HexKey, userPublicKey: HexKey, events: List, manifest: String?): Read { + val sealed = manifest ?: return Read.Refused(REPLY_UNREADABLE) + val keys = database.inboxKeyDao().getKeys(roomId, userPublicKey).filter { it.secretKey != null } + val (key, opened) = keys.firstNotNullOfOrNull { k -> + InboxReplyManifest.open(sealed, k.secretKey!!.hexToByteArray())?.let { k to it } + } ?: return Read.Refused(REPLY_NO_KEY) + if (opened.generation != key.generation || opened.seals.size != events.size) return Read.Refused(REPLY_UNREADABLE) + events.forEach { seal -> + if (!seal.pubKey.equals(roomId, ignoreCase = true) || seal.tags.size != 1 || InboxSeal.encryptionKeyOf(seal.tags) != key.publicKey) { + return Read.Refused(REPLY_UNREADABLE) + } + } + opened.seals.forEachIndexed { index, entry -> + val keyIsRight = if (index == opened.groupCopy) { + entry.recipient.equals(roomId, ignoreCase = true) && entry.key == key.publicKey && entry.announcement == null + } else { + !entry.recipient.equals(roomId, ignoreCase = true) && when (val json = entry.announcement) { + null -> entry.key == entry.recipient + else -> Event.fromJsonOrNull(json)?.let { announcement -> + announcement.verify() && announcement.pubKey == entry.recipient && InboxAnnouncement.announcedKeyOf(announcement) == entry.key + } == true + } + } + if (!keyIsRight) return Read.Refused(REPLY_WRONG_KEY) + } + val secret = key.secretKey!!.hexToByteArray() + val rumors = events.mapIndexed { index, seal -> + InboxSeal.rumorInside(seal.content, InboxWire.conversationKey(secret, opened.seals[index].key), roomId) + ?: return Read.Refused(REPLY_MISMATCH) + } + if (rumors.map { it.id }.distinct().size != 1) return Read.Refused(REPLY_MISMATCH) + val rumor = rumors.first() + if (rumor.kind != 14) return Read.Refused(REPLY_UNREADABLE) + val named = rumor.tags.filter { it.size >= 2 && it[0] == "p" }.map { it[1].lowercase() }.distinct().sorted() + val manifestRecipients = opened.seals.filterIndexed { index, _ -> index != opened.groupCopy }.map { it.recipient.lowercase() }.distinct().sorted() + if (named != manifestRecipients || opened.seals.size != manifestRecipients.size + 1) return Read.Refused(REPLY_MISMATCH) + return Read.Ok(ReadReply(key, opened, rumor)) + } + + /** + * What the approval screen says about a reply (D12): its words, who it goes to, and what this + * device could not check -- a recipient who has announced no key may have an app that cannot + * open a message from a group (D13). + */ + suspend fun notes(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey, sessionId: String, events: List): List { + if (events.none { it.kind == InboxSeal.KIND }) return emptyList() + val manifest = database.groupInboxDao().getSigning(sessionId)?.manifest + val reply = (readReply(database, chatRoomId, userPublicKey, events, manifest) as? Read.Ok)?.reply + ?: return listOf("A private reply from the group's inbox, which this device cannot read") + val recipients = reply.manifest.seals.filterIndexed { index, _ -> index != reply.manifest.groupCopy } + val names = database.profileDao().getProfileByPublicKeys(recipients.map { it.recipient }) + .associate { it.publicKey to it.humanReadableNameOrPubkey() } + return buildList { + add("The group would say: " + reply.rumor.content) + add("To " + recipients.joinToString(", ") { names[it.recipient] ?: it.recipient.take(8) }) + recipients.filter { it.announcement == null }.forEach { + add((names[it.recipient] ?: it.recipient.take(8)) + " has announced no inbox key, so their app may not be able to open a message from a group") + } + } + } + + /** The manifest a resent proposal has to carry again, as it came. */ + suspend fun carriedTagsFor(database: GizaDatabase, sessionId: String): Array> = + database.groupInboxDao().getSigning(sessionId)?.manifest?.let { arrayOf(InboxReplyManifest.tag(it)) } ?: emptyArray() + /** The key [ceremony] made, recomputing it on a watcher's device that missed it at the time. */ private suspend fun keyOf(database: GizaDatabase, ceremony: InboxKeyCeremony): HexKey? = ceremony.inboxPublicKey ?: InboxKeyRitualManager.keyWatched(database, ceremony) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt new file mode 100644 index 00000000..ecdbe61a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt @@ -0,0 +1,221 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.verify +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import com.vitorpamplona.quartz.utils.TimeUtils +import kotlin.time.Clock +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.GroupInboxMessage +import mobi.giza.compose.database.model.GroupInboxPublication +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.nostr.inbox.InboxAnnouncement +import mobi.giza.compose.nostr.inbox.InboxConversation +import mobi.giza.compose.nostr.inbox.InboxReplyManifest +import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.nostr.inbox.InboxWire +import mobi.giza.compose.nostr.inbox.InboxWrap + +/** + * The group answering from its inbox (docs/group-inbox.md, D10 to D13). + * + * A reply is one rumor, authored by the group, sealed once per recipient and once to the group + * itself, from the inbox key the group announced. The seals are what the quorum signs; nothing + * leaves until it has. Then the device that proposed it wraps each signed seal and owes the + * wraps to the recipients' relays, and the group's copy to the group's, which is how every + * admin sees the reply. + */ +object InboxReplies { + private val logger = Logger.withTag("InboxReplies") + + /** Who a seal is to and the key it is sealed with, and the 10044 that says so. */ + data class Recipient(val publicKey: HexKey, val encryptionKey: HexKey, val announcement: Event?) + + /** A reply ready to propose: the seals to sign, in order, and the manifest that explains them. */ + data class Built(val rumor: Event, val seals: List>, val manifest: InboxReplyManifest) + + /** + * Builds a reply from the group of [roomId] to [recipients], answering [replyTo], from the + * inbox key [inboxSecret] of [generation]. + */ + fun build( + roomId: HexKey, + recipients: List, + text: String, + replyTo: HexKey?, + inboxSecret: ByteArray, + generation: Int, + now: Long = TimeUtils.now(), + sealTime: () -> Long = { TimeUtils.randomWithTwoDays() }, + ): Built { + require(text.isNotBlank()) { "A reply needs something to say" } + require(recipients.isNotEmpty()) { "A reply needs someone to go to" } + val ordered = recipients.distinctBy { it.publicKey }.sortedBy { it.publicKey } + val tags = buildList { + ordered.forEach { add(arrayOf("p", it.publicKey)) } + replyTo?.let { add(arrayOf("e", it, "", "reply")) } + }.toTypedArray() + val rumor = RumorAssembler.assembleRumor(pubKey = roomId, ev = EventTemplate(now, 14, tags, text)) + + val inboxKey = InboxWire.publicKeyOf(inboxSecret) + val entries = ordered.map { InboxReplyManifest.Entry(it.publicKey, it.encryptionKey, it.announcement?.toJson()) } + + InboxReplyManifest.Entry(roomId, inboxKey, null) + val seals = entries.map { InboxSeal.template(rumor, inboxSecret, it.key, sealTime()) } + return Built(rumor, seals, InboxReplyManifest(generation, entries, groupCopy = entries.lastIndex)) + } + + /** The key a person reads encrypted mail with, as this device last heard: their 10044, or their identity. */ + suspend fun recipientOf(database: GizaDatabase, publicKey: HexKey): Recipient { + val announcement = database.nostrEventDao().getNostrEventByPublicKeyAndKind(publicKey, InboxAnnouncement.KEY_KIND) + ?.toEvent()?.takeIf { it.verify() } + val key = announcement?.let { InboxAnnouncement.announcedKeyOf(it) } + return Recipient(publicKey, key ?: publicKey, announcement.takeIf { key != null }) + } + + /** Whether [publicKey] has said, with a 10044, which key reads their mail (D13's warning when not). */ + suspend fun hasAnnouncedKey(database: GizaDatabase, publicKey: HexKey): Boolean = + recipientOf(database, publicKey).announcement != null + + /** + * Proposes a reply in [localChatRoom]'s conversation [conversationId], answering its newest + * message, from the key the group has announced. Throws with a reason a person can read when + * there is nothing to answer, or no announced key this device holds. + */ + suspend fun propose( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + conversationId: String, + text: String, + ): FrostSigningSession { + val roomId = localChatRoom.chatRoom.id + val conversation = database.groupInboxDao().getConversation(roomId, conversationId) + val newest = conversation.lastOrNull() ?: throw IllegalStateException("There is nothing here to reply to") + // D14: sealed from the key the group announced, never a newer one it has not. + val key = database.inboxKeyDao().getKeys(roomId, userPublicKey) + .firstOrNull { it.state == InboxKeyState.ANNOUNCED && it.secretKey != null } + ?: throw IllegalStateException("The group has announced no inbox key this device holds") + val recipients = newest.participantList().map { recipientOf(database, it) } + val built = build( + roomId = roomId, + recipients = recipients, + text = text, + replyTo = conversation.lastOrNull { !it.outgoing }?.rumorId, + inboxSecret = key.secretKey!!.hexToByteArray(), + generation = key.generation, + ) + val sealed = built.manifest.seal(key.secretKey.hexToByteArray()) + val session = FrostSigningManager.proposeSigningBatch( + database, localChatRoom, userPublicKey, + events = built.seals, + proposalTags = arrayOf(InboxReplyManifest.tag(sealed)), + ) + InboxRefusal.remember(database, session.id, roomId, refusal = null, manifest = sealed) + logger.i("Proposed a reply to ${recipients.size} in ${roomId.take(8)} as session ${session.id.take(8)}") + return session + } + + /** + * What a signed reply leaves (D10), on every device that took part: on the device that + * proposed it, a wrap per seal owed to its recipient's relays and the group's copy filed as + * an outgoing message at once. Every other admin's device files the copy when it arrives. + */ + suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, signedEvents: List) { + val seals = signedEvents.filter { it.kind == InboxSeal.KIND && it.pubKey.equals(session.chatRoomId, ignoreCase = true) } + if (seals.isEmpty() || !session.isCoordinator()) return + wrapAndOwe(database, session, seals) + } + + /** + * Wraps [seals] again and owes them to relays: what a person does from the conversation when + * the device that proposed a reply never got it out. New wraps of the same seals; the group's + * side files them as the one message they are. + */ + suspend fun sendAgain(database: GizaDatabase, sessionId: String): Boolean { + val session = database.frostSigningSessionDao().getSessionById(sessionId) ?: return false + val seals = database.groupSignedEventDao().getByChatRoomIdAndKind(session.chatRoomId, InboxSeal.KIND) + .filter { it.frostSigningSessionId == sessionId } + .map { it.toEvent() } + if (seals.isEmpty()) return false + wrapAndOwe(database, session, seals) + return true + } + + private suspend fun wrapAndOwe(database: GizaDatabase, session: FrostSigningSession, seals: List) { + val roomId = session.chatRoomId + val signing = database.groupInboxDao().getSigning(session.id) ?: run { + logger.w("Signed reply ${session.id.take(8)} has no manifest here; not sending it") + return + } + val keys = database.inboxKeyDao().getKeys(roomId, session.userPublicKey).filter { it.secretKey != null } + val opened = keys.firstNotNullOfOrNull { key -> + signing.manifest?.let { InboxReplyManifest.open(it, key.secretKey!!.hexToByteArray()) }?.let { key to it } + } ?: run { + logger.w("Signed reply ${session.id.take(8)}: no key here opens its manifest; not sending it") + return + } + val (key, manifest) = opened + // In the order the proposal fixed, which is the manifest's. + val signedById = seals.associateBy { it.id } + val ordered = database.frostSigningSessionDao().getItems(session.id).sortedBy { it.itemIndex }.map { signedById[it.eventId] } + if (ordered.size != manifest.seals.size) return + + manifest.seals.forEachIndexed { index, entry -> + val seal = ordered[index] ?: return@forEachIndexed + val relays = if (index == manifest.groupCopy) { + InboxAnnouncements.relaysOf(database, roomId) + } else { + relaysOf(database, entry.recipient) + } + val wrap = InboxWrap.wrap(seal, entry.recipient, entry.key, relays.firstOrNull()) + database.groupInboxDao().upsertPublication( + GroupInboxPublication( + eventId = wrap.id, + chatRoomId = roomId, + kind = wrap.kind, + eventJson = wrap.toJson(), + relays = relays.joinToString(",") { it.url }, + signingSessionId = session.id, + recipientPublicKey = entry.recipient, + ) + ) + } + + // The group's copy, filed now so the reply is in the conversation before it comes back. + val copy = ordered[manifest.groupCopy] ?: return + val rumor = InboxSeal.rumorInside(copy.content, InboxReplyManifest.selfConversationKey(key.secretKey!!.hexToByteArray()), roomId) ?: return + val participants = InboxConversation.participantsOf(rumor, roomId) + database.groupInboxDao().insertMessage( + GroupInboxMessage( + chatRoomId = roomId, + rumorId = rumor.id, + wrapId = null, + conversationId = InboxConversation.idOf(participants), + participants = participants.joinToString(","), + senderPublicKey = roomId, + kind = rumor.kind, + rumorJson = InboxSeal.rumorJson(rumor), + createdAt = rumor.createdAt, + generation = manifest.generation, + outgoing = true, + signingSessionId = session.id, + readAt = Clock.System.now(), + ) + ) + } + + /** Where [publicKey] reads private mail: their 10050, as this device last heard it. */ + private suspend fun relaysOf(database: GizaDatabase, publicKey: HexKey): List = + database.nostrEventDao().getNostrEventByPublicKeyAndKind(publicKey, InboxAnnouncement.RELAYS_KIND) + ?.toEvent()?.let { InboxAnnouncement.announcedRelaysOf(it) } + ?.ifEmpty { null } + ?: Relays.DefaultDMRelayList +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt index 8f7e9022..1df371cc 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt @@ -82,7 +82,12 @@ interface FrostSigningRepository { suspend fun canSign(chatRoomId: String): Boolean /** What to read before approving a confederation event in [sessionId] (docs/confederation.md, D6). */ - suspend fun confederationNotes(chatRoomId: String, sessionId: String, events: List): List = emptyList() + /** + * What the signing screen says beside a proposal: for a confederation event, what it names + * and discloses (docs/confederation.md, D6); for a reply from the group's inbox, its words, + * who it goes to and what could not be checked (docs/group-inbox.md, D12). + */ + suspend fun proposalNotes(chatRoomId: String, sessionId: String, events: List): List = emptyList() /** * Opens a session asking the group to sign an event with these fields. The diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt index 4fb6a9a7..14aac74c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt @@ -81,6 +81,21 @@ interface GroupInboxRepository { suspend fun abandon(localChatRoom: LocalChatRoom, ceremonyId: String): Boolean = false + // ---- replying (Phase 8) ------------------------------------------------------------------- + + /** Asks the group to sign a reply to [conversationId]; the signing session's id. */ + suspend fun proposeReply(localChatRoom: LocalChatRoom, conversationId: String, text: String): String = + throw UnsupportedOperationException() + + /** Of [publicKeys], those who have announced no inbox key (D13's warning). */ + suspend fun withoutAnnouncedKey(publicKeys: List): List = emptyList() + + /** The reply sessions in [chatRoomId] whose wraps no relay has taken yet. */ + suspend fun unsentReplies(chatRoomId: String): Set = emptySet() + + /** Wraps a signed reply again and owes it to relays. */ + suspend fun sendAgain(sessionId: String): Boolean = false + companion object { val NO_OP = object : GroupInboxRepository { override fun observeUnpublished(): Flow> = flowOf(emptyList()) 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 6a064943..9b94c86a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -11,6 +11,7 @@ import mobi.giza.compose.managers.WalletRefusal import mobi.giza.compose.nostr.RetiredKinds import mobi.giza.compose.nostr.frost.GovernanceStatementEvent import mobi.giza.compose.nostr.inbox.InboxAnnouncement +import mobi.giza.compose.nostr.inbox.InboxSeal import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent @@ -101,6 +102,13 @@ object ProposedEvent { detail = InboxAnnouncement.announcedKeyOf(event)?.let { "Key ${it.take(8)}…${it.takeLast(8)}" } ?: "Names no key", ) + // A reply from the group's inbox: sealed, so said for what it is. The signing screen + // reads it out for a device that holds the inbox key (docs/group-inbox.md, D12), and a + // member without one sees only that it exists (D11). + InboxSeal.KIND -> Summary( + label = "A private reply from the group's inbox", + detail = "Sealed: only the group's inbox key opens it", + ) InboxAnnouncement.RELAYS_KIND -> Summary( label = "Where the group receives private messages", detail = InboxAnnouncement.announcedRelaysOf(event).joinToString(", ") { it.url.removePrefix("wss://").trimEnd('/') } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt index 0a68b174..0bde2306 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt @@ -210,7 +210,7 @@ fun FrostSigningScreen( // A confederation event's terms and what this device could not check // about it, for the member to weigh. docs/confederation.md, D6. - state.confederationNotes.forEach { note -> + state.proposalNotes.forEach { note -> Text(text = note, style = MaterialTheme.typography.bodySmall) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt index d6bab16a..f3c4af0a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt @@ -10,7 +10,26 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items +import androidx.compose.material3.Button import androidx.compose.material3.Card +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.TextButton +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import mobi.giza.compose.resources.ask_the_group_to_sign_this_reply +import mobi.giza.compose.resources.could_not_ask_the_group_to_sign_this_reply +import mobi.giza.compose.resources.has_announced_no_inbox_key +import mobi.giza.compose.resources.not_yet_on_a_relay +import mobi.giza.compose.resources.reply_as_the_group +import mobi.giza.compose.resources.send_reply_again +import mobi.giza.compose.resources.sent_again +import mobi.giza.compose.resources.the_group_signs_a_reply +import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.rememberNotifier import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme @@ -69,8 +88,6 @@ fun GroupInboxConversationScreen( inboxRepository: GroupInboxRepository, onNavigateToRoute: (Route) -> Unit, onNavigateBack: () -> Unit, - /** Below the conversation: the way to reply, when there is one (Phase 8). */ - composer: @Composable (GroupInboxConversationUIState.Loaded) -> Unit = {}, ) { val viewModel: GroupInboxConversationViewModel = viewModel( factory = GroupInboxConversationViewModel.factory(chatRoomId, conversationId, initialUIState, chatRepository, inboxRepository) @@ -78,6 +95,11 @@ fun GroupInboxConversationScreen( LaunchedEffect(true) { if (initialUIState == GroupInboxConversationUIState.Loading) viewModel.initiate() } + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_this_reply) + val sentAgain = stringResource(Res.string.sent_again) + val canSign = LocalCanSign.current + var draft by rememberSaveable { mutableStateOf("") } val title = (viewModel.uiState as? GroupInboxConversationUIState.Loaded)?.names?.joinToString(", ") ?.let { stringResource(Res.string.you_and_the_group, it) } ?: stringResource(Res.string.the_group) @@ -122,19 +144,76 @@ fun GroupInboxConversationScreen( modifier = Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), ) { - items(state.lines, key = { it.rumorId }) { line -> MessageCard(line) } + items(state.lines, key = { it.rumorId }) { line -> + MessageCard(line, onSendAgain = { session -> viewModel.sendAgain(session) { if (it) notify(sentAgain) } }) + } } } - composer(state) + if (canSign && state.lines.isNotEmpty()) { + Composer( + draft = draft, + onDraft = { draft = it }, + withoutKey = state.withoutKey, + proposing = state.proposing, + onPropose = { + viewModel.propose(draft) { session -> + if (session == null) { + notify(couldNotPropose) + } else { + draft = "" + onNavigateToRoute(FrostSigningRoute(activeUserPublicKey, chatRoomId, session)) + } + } + }, + ) + } } } } } } +/** + * The way to answer (D10, D13): the words, what signing it means, a warning for every recipient + * whose app may not open a message from a group, and the button that asks the quorum. + */ +@Composable +private fun Composer( + draft: String, + onDraft: (String) -> Unit, + withoutKey: List, + proposing: Boolean, + onPropose: () -> Unit, +) { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { + withoutKey.forEach { name -> + Text( + stringResource(Res.string.has_announced_no_inbox_key, name), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + value = draft, + onValueChange = onDraft, + label = { Text(stringResource(Res.string.reply_as_the_group)) }, + minLines = 2, + ) + Text( + stringResource(Res.string.the_group_signs_a_reply), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Button(onClick = onPropose, enabled = draft.isNotBlank() && !proposing) { + Text(stringResource(Res.string.ask_the_group_to_sign_this_reply)) + } + } +} + /** One message: theirs on the leading edge, the group's on the trailing one, in its own colours. */ @Composable -private fun MessageCard(line: GroupInboxConversationUIState.Line) { +private fun MessageCard(line: GroupInboxConversationUIState.Line, onSendAgain: (String) -> Unit) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = if (line.outgoing) Alignment.End else Alignment.Start, @@ -163,6 +242,10 @@ private fun MessageCard(line: GroupInboxConversationUIState.Line) { text = Instant.fromEpochSeconds(line.createdAt).toFormattedTimeAndDateString(), style = MaterialTheme.typography.labelSmall, ) + line.unsentSessionId?.let { session -> + Text(stringResource(Res.string.not_yet_on_a_relay), style = MaterialTheme.typography.labelSmall) + TextButton(onClick = { onSendAgain(session) }) { Text(stringResource(Res.string.send_reply_again)) } + } } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt index ba42a39f..76835ff5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt @@ -81,7 +81,7 @@ class FrostSigningViewModel( ) { session, messages, items, holders -> Observed(session, messages, items, holders) } .collect { (session, messages, items, holders) -> if (notes == null && items.isNotEmpty()) { - notes = frostSigningRepository.confederationNotes(chatRoomId, sessionId, proposedEvents(items)) + notes = frostSigningRepository.proposalNotes(chatRoomId, sessionId, proposedEvents(items)) } // Read per emission rather than derived from `messages`: who // the session is waiting on is the manager's rule, and it is @@ -107,7 +107,7 @@ class FrostSigningViewModel( .map { it.signerPublicKey } .toSet(), silent = owed, - confederationNotes = notes.orEmpty(), + proposalNotes = notes.orEmpty(), ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt index 5effbc10..78349c1c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt @@ -80,9 +80,13 @@ class GroupInboxConversationViewModel( inboxRepository.observeConversation(chatRoomId, conversationId).collect { messages -> val participants = messages.lastOrNull()?.participantList().orEmpty() val names = inboxRepository.namesOf(participants) + val unsent = inboxRepository.unsentReplies(chatRoomId) + val withoutKey = inboxRepository.withoutAnnouncedKey(participants) uiState = GroupInboxConversationUIState.Loaded( localChatRoom = room, names = participants.map { names[it] ?: it.take(8) }, + withoutKey = withoutKey.map { names[it] ?: it.take(8) }, + proposing = (uiState as? GroupInboxConversationUIState.Loaded)?.proposing ?: false, lines = messages.map { message -> GroupInboxConversationUIState.Line( rumorId = message.rumorId, @@ -90,6 +94,7 @@ class GroupInboxConversationViewModel( createdAt = message.createdAt, outgoing = message.outgoing, senderName = if (message.outgoing) "" else names[message.senderPublicKey] ?: message.senderPublicKey.take(8), + unsentSessionId = message.signingSessionId?.takeIf { it in unsent }, ) }, ) @@ -98,6 +103,25 @@ class GroupInboxConversationViewModel( } } + /** + * Asks the group to sign [text] as a reply. [onDone] gets the signing session's id, or null + * when it could not be asked. + */ + fun propose(text: String, onDone: (String?) -> Unit) { + val loaded = uiState as? GroupInboxConversationUIState.Loaded ?: return + if (loaded.proposing || text.isBlank()) return + uiState = loaded.copy(proposing = true) + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { inboxRepository.proposeReply(loaded.localChatRoom, conversationId, text.trim()) }.getOrNull() + (uiState as? GroupInboxConversationUIState.Loaded)?.let { uiState = it.copy(proposing = false) } + onDone(session) + } + } + + fun sendAgain(sessionId: String, onDone: (Boolean) -> Unit) { + viewModelScope.launch(Dispatchers.IO) { onDone(inboxRepository.sendAgain(sessionId)) } + } + companion object { fun factory( chatRoomId: String, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt index 4244db04..f9d0c3e8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt @@ -24,8 +24,12 @@ sealed interface FrostSigningUIState { */ val items: List = emptyList(), - /** For a confederation event: who it names, what it discloses, what could not be checked. docs/confederation.md, D6. */ - val confederationNotes: List = emptyList(), + /** + * What the screen says beside the events: for a confederation event, who it names, what it + * discloses and what could not be checked (docs/confederation.md, D6); for a reply from the + * group's inbox, its words and recipients (docs/group-inbox.md, D12). + */ + val proposalNotes: List = emptyList(), /** Who has offered a nonce, so the screen can name who it is waiting on. */ val offeredNonce: Set = emptySet(), diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt index 84ba89a9..ba226b95 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt @@ -26,12 +26,18 @@ sealed interface GroupInboxConversationUIState { val createdAt: Long, val outgoing: Boolean, val senderName: String, + /** For a reply this device proposed: its signing session, while no relay has taken it. */ + val unsentSessionId: String? = null, ) data class Loaded( val localChatRoom: LocalChatRoom, val names: List, val lines: List, + /** Recipients who have announced no inbox key (D13): their app may not open the reply. */ + val withoutKey: List = emptyList(), + /** Whether a reply this screen asked for is still on its way to the signing session. */ + val proposing: Boolean = false, ): GroupInboxConversationUIState data class Error(val message: String): GroupInboxConversationUIState diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt index 162fda95..76d84077 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt @@ -113,10 +113,10 @@ class ProposedEventTest { /** * docs/group-inbox.md: the group's inbox key and its relays are said by what they are - * (Phase 5). A seal is still said by its number until Phase 8 gives it words. + * (Phase 5), and a seal as the sealed reply it is (Phase 8). */ @Test - fun `an inbox key and its relays are named, and a seal is still a number`() { + fun `an inbox key, its relays and a sealed reply are named`() { val key = "e".repeat(64) val announcement = ProposedEvent.summarize(event(10044, tags = arrayOf(arrayOf("n", key)))) assertEquals("The group's inbox key", announcement.label) @@ -124,7 +124,7 @@ class ProposedEventTest { val relays = ProposedEvent.summarize(event(10050, tags = arrayOf(arrayOf("relay", "wss://inbox.example.com/")))) assertEquals("Where the group receives private messages", relays.label) assertEquals("inbox.example.com", relays.detail) - assertEquals("Event of kind 13", ProposedEvent.summarize(event(13)).label) + assertEquals("A private reply from the group's inbox", ProposedEvent.summarize(event(13)).label) } private fun event( diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt index a7d7152b..5f85f351 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt @@ -16,9 +16,9 @@ import mobi.giza.compose.text.ProposedEvent * What Giza does today with the events a group's inbox is made of (docs/group-inbox.md, * Phase 1). Written to pass now and flipped on purpose by the phase that changes each: * - * - a peer's proposal to sign a kind 13 (a NIP-17 seal) reaches the member as a bare number, - * and nothing declines it. Phase 8 puts a refusal in front of it, as Phase 5 did for a kind - * 10044 (an encryption key), which this pins declined now; + * - a peer's proposal to sign a kind 10044 (an encryption key) nobody made, or a kind 13 (a + * NIP-17 seal) with no manifest to read it by, is declined out loud: Phases 5 and 8 put a + * refusal in front of each; * - the identity's own gift wraps are asked for on their own subscription, beside the * group's that Phase 6 added. */ @@ -62,11 +62,13 @@ class GroupInboxTodayJvmTest { } @Test - fun `a peer's sealed ciphertext reaches the member as a number, and can be signed`() { - // The member is asked to sign bytes it cannot read: the rubber stamp - // docs/giza-wallet-removal.md says a Giza device must not be. Phase 8 declines it. + fun `a peer's sealed ciphertext with nothing to read it by is declined out loud`() = runBlocking { + // Flipped by Phase 8: a member asked to sign bytes it cannot read would be the rubber + // stamp docs/giza-wallet-removal.md says a Giza device must not be (docs/group-inbox.md, D12). val sent = proposeAndDeliver(13, arrayOf(arrayOf("n", "e".repeat(64))), "AnOpaqueCiphertext") - assertPutToTheMemberByNumber(sent, 13) + val session = assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id)) + assertNotNull(session.signDeclinedAt) + assertEquals(listOf(InboxRefusal.REPLY_UNREADABLE), harness.queued(FrostSigningEvents.DECLINE).map { it.content }) } @Test diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxReplyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxReplyJvmTest.kt new file mode 100644 index 00000000..76aae9ae --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxReplyJvmTest.kt @@ -0,0 +1,259 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.crypto.verify +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent +import fr.acinq.bitcoin.Crypto +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.runBlocking +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.types.FrostSigningStage +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.inbox.InboxAnnouncement +import mobi.giza.compose.nostr.inbox.InboxReplyManifest +import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.nostr.inbox.InboxWire +import mobi.giza.compose.nostr.inbox.InboxWrap +import mobi.giza.compose.text.ProposedEvent +import kotlin.time.Instant + +/** + * The group answering from its inbox (docs/group-inbox.md, Phase 8): a reply is proposed by one + * admin, read and signed by the quorum, and reaches its recipient as a NIP-17 message from the + * group; a wrong one is declined out loud; and a member who is not an admin learns nothing of it. + */ +class InboxReplyJvmTest { + private val harness = GroupInboxHarness(watchers = listOf("dineo")) + private val zola = KeyPair(Crypto.sha256("zola, who writes to the group".encodeToByteArray())) + private val zolaKey = zola.pubKey.toHexKey() + private val zolaEncryption = Crypto.sha256("zola's decoupled key".encodeToByteArray()) + private val zolaEncryptionKey = InboxWire.publicKeyOf(zolaEncryption) + private val now get() = kotlin.time.Clock.System.now().epochSeconds + + @AfterTest + fun close() = harness.close() + + private lateinit var alice: GroupInboxHarness.Device + private lateinit var bob: GroupInboxHarness.Device + private lateinit var carol: GroupInboxHarness.Device + private lateinit var dineo: GroupInboxHarness.Device + + /** Three admins with an announced inbox, Zola's message in Alice's, and a member who is not an admin. */ + private suspend fun announced() { + val devices = listOf("alice", "bob", "carol", "dineo").map { harness.device(it) } + alice = devices[0]; bob = devices[1]; carol = devices[2]; dineo = devices[3] + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.pump() + val announcement = alice.db.frostSigningSessionDao().getSessionsForChatRoom(harness.roomId).single() + FrostSigningManager.approve(bob.db, bob.room(), announcement.id) + harness.pump() + + val e = alice.keys().single().publicKey + val message = RumorAssembler.assembleRumor(zolaKey, EventTemplate(now - 60, 14, arrayOf(arrayOf("p", harness.roomId)), "Can I join?")) + val seal = NostrSignerSync(zola).sign(now - 60, 13, emptyArray(), + InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(zola.privKey!!, e))) + assertNotNull(GroupInboxManager.receive(alice.db, InboxWrap.wrap(seal, harness.roomId, e), alice.publicKey)) + } + + private suspend fun conversationId(): String = alice.db.groupInboxDao().getMessages(harness.roomId).first { !it.outgoing }.conversationId + + private suspend fun session(on: GroupInboxHarness.Device, id: String): FrostSigningSession = + assertNotNull(on.db.frostSigningSessionDao().getSessionById(id)) + + /** Zola announces a decoupled key, and Alice's device has heard it. */ + private suspend fun zolaAnnounces(on: GroupInboxHarness.Device) { + val signed = NostrSignerSync(zola).sign(InboxAnnouncement.keyTemplate(zolaEncryptionKey, now - 3600)) + on.db.nostrEventDao().upsert( + NostrEvent(id = signed.id, pubKey = signed.pubKey, kind = signed.kind, tags = signed.tags, content = signed.content, sig = signed.sig, createdAt = Instant.fromEpochSeconds(signed.createdAt)) + ) + } + + /** The wrap Alice's device owes Zola, opened with [secret]. */ + private suspend fun zolaOpens(secret: ByteArray, sessionId: String): Event { + val owed = alice.db.groupInboxDao().getPublicationsFor(sessionId).single { it.recipientPublicKey == zolaKey } + val wrap = Event.fromJson(owed.eventJson) + assertEquals(zolaKey, InboxWrap.recipientOf(wrap), "tagged with Zola's identity, as #2361 has it") + val (_, seal) = assertNotNull(InboxWrap.open(wrap, listOf(secret)), "Zola's key opens the wrap") + assertTrue(seal.verify(), "the seal is signed") + assertEquals(harness.roomId, seal.pubKey, "by the group") + return assertNotNull(InboxSeal.open(seal, secret)).rumor + } + + @Test + fun `a reply signed by the quorum reaches Zola from the group`() = runBlocking { + announced() + val sessionId = InboxReplies.propose(alice.db, alice.room(), alice.publicKey, conversationId(), "Yes, on Thursday.").id + harness.pump() + assertTrue(FrostSigningManager.isAwaitingApproval(session(bob, sessionId), bob.db.frostSigningSessionDao().getItems(sessionId)), "Bob is asked") + FrostSigningManager.approve(bob.db, bob.room(), sessionId) + harness.pump() + assertEquals(FrostSigningStage.COMPLETE, session(alice, sessionId).stage) + + val reply = zolaOpens(zola.privKey!!, sessionId) + assertEquals("Yes, on Thursday.", reply.content) + assertEquals(harness.roomId, reply.pubKey) + assertTrue(reply.tags.any { it[0] == "p" && it[1] == zolaKey }) + + // Alice's device filed the group's copy at once, in the same conversation. + val filed = alice.db.groupInboxDao().getConversation(harness.roomId, conversationId()) + assertEquals(listOf(false, true), filed.map { it.outgoing }) + // Only the proposer sends. + assertEquals(emptyList(), bob.db.groupInboxDao().getPublicationsFor(sessionId)) + } + + @Test + fun `a reply to someone who decoupled opens with their encryption key`() = runBlocking { + announced() + zolaAnnounces(alice) + val sessionId = InboxReplies.propose(alice.db, alice.room(), alice.publicKey, conversationId(), "To your new key").id + harness.pump() + FrostSigningManager.approve(bob.db, bob.room(), sessionId) + harness.pump() + assertEquals("To your new key", zolaOpens(zolaEncryption, sessionId).content) + } + + @Test + fun `the group's copy comes back to every admin as an outgoing message`() = runBlocking { + announced() + val sessionId = InboxReplies.propose(alice.db, alice.room(), alice.publicKey, conversationId(), "For the record").id + harness.pump() + FrostSigningManager.approve(bob.db, bob.room(), sessionId) + harness.pump() + + val copy = alice.db.groupInboxDao().getPublicationsFor(sessionId).single { it.recipientPublicKey == harness.roomId } + val filed = assertNotNull(GroupInboxManager.receive(carol.db, Event.fromJson(copy.eventJson), carol.publicKey)) + assertTrue(filed.outgoing) + assertEquals("For the record", Event.fromJson(filed.rumorJson).content) + assertNull(GroupInboxManager.receive(dineo.db, Event.fromJson(copy.eventJson), dineo.publicKey), "nothing for a member who is not an admin") + } + + @Test + fun `a reply proposed after its relays never took it can be sent again`() = runBlocking { + announced() + val sessionId = InboxReplies.propose(alice.db, alice.room(), alice.publicKey, conversationId(), "Again").id + harness.pump() + FrostSigningManager.approve(bob.db, bob.room(), sessionId) + harness.pump() + val first = alice.db.groupInboxDao().getPublicationsFor(sessionId).map { it.eventId }.toSet() + assertTrue(InboxReplies.sendAgain(alice.db, sessionId)) + val all = alice.db.groupInboxDao().getPublicationsFor(sessionId).map { it.eventId }.toSet() + assertEquals(4, all.size, "new wraps of the same seals") + assertTrue(all.containsAll(first)) + assertEquals(1, alice.db.groupInboxDao().getConversation(harness.roomId, conversationId()).count { it.outgoing }, "still one message") + } + + // ---- what a signer refuses (D12) --------------------------------------------------------- + + /** Proposes [seals] with [manifest] by hand, from Alice, and returns what Bob's device says. */ + private suspend fun bobSays(seals: List>, manifest: InboxReplyManifest, sealWith: ByteArray? = null): String? { + val secret = sealWith ?: alice.keys().first().secretKey!!.hexToByteArray() + val session = FrostSigningManager.proposeSigningBatch(alice.db, alice.room(), alice.publicKey, events = seals, + proposalTags = arrayOf(InboxReplyManifest.tag(manifest.seal(secret)))) + harness.pump() + val onBob = session(bob, session.id) + if (onBob.signDeclinedAt == null) return null + return bob.db.marmotInnerEventDao().getByChatRoomAndKinds(harness.roomId, listOf(FrostSigningEvents.DECLINE)) + .firstOrNull { it.publicKey == bob.publicKey }?.content + } + + private suspend fun built(text: String = "Fine", recipients: List = listOf(InboxReplies.Recipient(zolaKey, zolaKey, null))): InboxReplies.Built { + val key = alice.keys().first() + return InboxReplies.build(harness.roomId, recipients, text, null, key.secretKey!!.hexToByteArray(), key.generation, now = now, sealTime = { now - 30 }) + } + + @Test + fun `a well-made reply is put to the member, not declined`() = runBlocking { + announced() + val reply = built() + assertNull(bobSays(reply.seals, reply.manifest)) + } + + @Test + fun `a group copy that says something else is declined`() = runBlocking { + announced() + val reply = built("What Zola reads") + val other = built("What the admins read") + val seals = reply.seals.toMutableList().also { it[reply.manifest.groupCopy] = other.seals[other.manifest.groupCopy] } + assertEquals(InboxRefusal.REPLY_MISMATCH, bobSays(seals, reply.manifest)) + } + + @Test + fun `a seal to a key the recipient never announced is declined`() = runBlocking { + announced() + val stranger = InboxWire.publicKeyOf(Crypto.sha256("someone else's key".encodeToByteArray())) + val reply = built(recipients = listOf(InboxReplies.Recipient(zolaKey, stranger, null))) + assertEquals(InboxRefusal.REPLY_WRONG_KEY, bobSays(reply.seals, reply.manifest)) + } + + @Test + fun `a 10044 signed by someone else is declined`() = runBlocking { + announced() + val forger = KeyPair(Crypto.sha256("a forger".encodeToByteArray())) + val forged = NostrSignerSync(forger).sign(InboxAnnouncement.keyTemplate(zolaEncryptionKey, now)) + val reply = built(recipients = listOf(InboxReplies.Recipient(zolaKey, zolaEncryptionKey, forged))) + assertEquals(InboxRefusal.REPLY_WRONG_KEY, bobSays(reply.seals, reply.manifest)) + } + + @Test + fun `a recipient the reply does not name is declined`() = runBlocking { + announced() + val yusuf = KeyPair(Crypto.sha256("yusuf".encodeToByteArray())).pubKey.toHexKey() + val toZola = built() + val toBoth = built(recipients = listOf(InboxReplies.Recipient(zolaKey, zolaKey, null), InboxReplies.Recipient(yusuf, yusuf, null))) + // Yusuf's seal holds a rumor naming only Zola: a reply sent to someone it does not address. + val key = alice.keys().first().secretKey!!.hexToByteArray() + val yusufIndex = toBoth.manifest.seals.indexOfFirst { it.recipient == yusuf } + val seals = toBoth.manifest.seals.map { InboxSeal.template(toZola.rumor, key, it.key, now - 30) } + assertEquals(yusufIndex >= 0, true) + assertEquals(InboxRefusal.REPLY_MISMATCH, bobSays(seals, toBoth.manifest)) + } + + @Test + fun `a blank reply is declined`() = runBlocking { + announced() + val key = alice.keys().first() + val blank = RumorAssembler.assembleRumor(harness.roomId, EventTemplate(now, 14, arrayOf(arrayOf("p", zolaKey)), " ")) + val manifest = built().manifest + val seals = manifest.seals.map { InboxSeal.template(blank, key.secretKey!!.hexToByteArray(), it.key, now - 30) } + assertEquals(InboxRefusal.REPLY_BLANK, bobSays(seals, manifest)) + } + + @Test + fun `a signer whose device holds no inbox key declines, rather than sign what it cannot read`() = runBlocking { + announced() + bob.db.inboxKeyDao().wipeKeys(harness.roomId, bob.publicKey, kotlin.time.Clock.System.now()) + val reply = built() + assertEquals(InboxRefusal.REPLY_NO_KEY, bobSays(reply.seals, reply.manifest)) + } + + @Test + fun `a member who is not an admin learns no text and no recipient`() = runBlocking { + announced() + val sessionId = InboxReplies.propose(alice.db, alice.room(), alice.publicKey, conversationId(), "Private words").id + harness.pump() + val sealed = assertNotNull(alice.db.groupInboxDao().getSigning(sessionId)?.manifest) + assertNull(InboxReplyManifest.open(sealed, Crypto.sha256("any key dineo could have".encodeToByteArray()))) + + val items = alice.db.frostSigningSessionDao().getItems(sessionId).map { Event.fromJson(it.unsignedEventJson) } + assertEquals("A private reply from the group's inbox", ProposedEvent.summarize(items.first()).label) + items.forEach { seal -> + assertTrue("Private words" !in seal.content && zolaKey !in seal.content && seal.tags.none { zolaKey in it }) + } + // Bob, who holds the key, reads it on the signing screen. + val notes = InboxRefusal.notes(bob.db, harness.roomId, bob.publicKey, sessionId, items) + assertEquals("The group would say: Private words", notes.first()) + } +}