diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 3a7bdb21..c7e5814d 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -772,4 +772,16 @@ Declined by the group Send again Only the group's current admins see its messages. + The group's quorum has to sign before anything is sent. + Write a message + Send + Preparing: the admins are working out how to write to them + Nothing signed by this person is on this device yet, so the group can't write to them + Couldn't ask the group to send this. + Asked the group to sign this message + New message + Their npub + That isn't a nostr key + Write to them + Sending again 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 8763946d..138cf92f 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 @@ -98,6 +98,9 @@ abstract class GroupDmDao { @Query("SELECT * FROM GroupDmMessage WHERE rumorId = :rumorId") abstract suspend fun getMessage(rumorId: HexKey): GroupDmMessage? + @Query("SELECT * FROM GroupDmMessage WHERE signingSessionId = :signingSessionId LIMIT 1") + abstract suspend fun getMessageBySigningSession(signingSessionId: String): GroupDmMessage? + @Query("SELECT * FROM GroupDmMessage WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") abstract fun observeMessages(chatRoomId: HexKey): Flow> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index a89d7220..34607898 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -1123,7 +1123,8 @@ abstract class NostrDao( content = decryptedGiftWrapPayload.content, sig = "" ), - userPublicKey = activeKeyPair.pubKey.toHex() + userPublicKey = activeKeyPair.pubKey.toHex(), + nostrPrivateKey = activeKeyPair.privKey, ) } } else { @@ -1691,7 +1692,8 @@ abstract class NostrDao( database = database, localChatRoom = localChatRoom, innerEvent = innerEvent, - userPublicKey = activeKeyPair.pubKey.toHex() + userPublicKey = activeKeyPair.pubKey.toHex(), + nostrPrivateKey = activeKeyPair.privKey, ) DkgRitualEvents.isDkgRitualKind(innerEvent.kind) -> 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 64b19026..c45323fc 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 @@ -1397,6 +1397,12 @@ data class ChatMessage( ) } + // A message the group signed to someone: a seal, ciphertext. The session's + // own lines already say the group signed, and naming the message here would + // tell members who are not admins (docs/group-threshold-ecdh.md, D12). + com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent.KIND -> + if (event.pubKey.equals(groupId, ignoreCase = true)) null else unsupported() + // 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. 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..7548b714 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 @@ -28,7 +28,31 @@ class DatabaseFrostSigningRepository( 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()) + runCatching { ConfederationRefusal.notes(database, chatRoomId, sessionId, events) }.getOrDefault(emptyList()) + + runCatching { groupDmNotes(sessionId, events) }.getOrDefault(emptyList()) + + /** + * A message from the group, as an admin's device read it from the manifest: its words, + * who it goes to and what it answers (docs/group-threshold-ecdh.md, D13). A device that + * could not read it says only what the seals are. + */ + private suspend fun groupDmNotes(sessionId: String, events: List): List { + if (events.none { it.kind == com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent.KIND }) return emptyList() + val message = database.groupDmDao().getMessageBySigningSession(sessionId) ?: return emptyList() + val rumor = Event.fromJsonOrNull(message.rumorJson) ?: return emptyList() + val names = rumor.tags.filter { it.size >= 2 && it[0] == "p" }.map { tag -> + database.profileDao().getProfileByPublicKey(tag[1])?.let { it.displayName?.takeIf { n -> n.isNotBlank() } ?: it.userName } + ?: tag[1].take(8) + } + val answering = rumor.tags.firstOrNull { it.size >= 2 && it[0] == "e" }?.get(1) + ?.let { database.groupDmDao().getMessage(it) } + ?.let { Event.fromJsonOrNull(it.rumorJson)?.content } + return listOfNotNull( + "A message from the group: ${rumor.content}", + "To ${names.joinToString(", ")}", + answering?.let { "Answering: $it" }, + ) + } override fun observeSessionById(sessionId: String): Flow = database.frostSigningSessionDao().observeSessionById(sessionId) 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 index 496f8077..7eb57cc9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt @@ -15,7 +15,24 @@ 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 { +class DatabaseGroupDmRepository( + private val database: GizaDatabase, + private val activeIdentity: kotlinx.coroutines.flow.StateFlow = kotlinx.coroutines.flow.MutableStateFlow(null), +) : GroupDmRepository { + override suspend fun send( + localChatRoom: LocalChatRoom, + recipients: List, + text: String, + replyTo: HexKey?, + ): mobi.giza.compose.managers.GroupDmSender.Outcome { + val identity = activeIdentity.value ?: throw IllegalStateException("No identity is open") + val secret = identity.nostrPrivateKey ?: throw IllegalStateException("This identity cannot sign") + return mobi.giza.compose.managers.GroupDmSender.send(database, localChatRoom, identity.nostrPublicKey, secret.value.toByteArray(), recipients, text, replyTo) + } + + override suspend fun sendAgain(signingSessionId: String): Boolean = + mobi.giza.compose.managers.GroupDmSender.sendAgain(database, signingSessionId) + override fun observeOwed(): Flow> = database.groupDmDao().observeOwed() override suspend fun markPublished(outbound: GroupDmOutbound, at: Instant) = 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 3bf331b4..a0400237 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -407,7 +407,13 @@ object FrostSigningManager { database: GizaDatabase, localChatRoom: LocalChatRoom, innerEvent: Event, - userPublicKey: HexKey + userPublicKey: HexKey, + /** + * This device's nostr key, for the one check that needs it: opening a message's + * manifest with the host key it derives (docs/group-threshold-ecdh.md, D13). Without + * it a batch of seals is held rather than asked about. + */ + nostrPrivateKey: ByteArray? = null, ) { val sessionId = FrostSigningEvents.parseSessionId(innerEvent.tags) if (sessionId == null) { @@ -421,7 +427,8 @@ object FrostSigningManager { localChatRoom = localChatRoom, innerEvent = innerEvent, sessionId = sessionId, - userPublicKey = userPublicKey + userPublicKey = userPublicKey, + nostrPrivateKey = nostrPrivateKey, ) } else if (innerEvent.kind == FrostSigningEvents.TRANSACTION_PROPOSAL) { declineWalletProposal( @@ -558,7 +565,8 @@ object FrostSigningManager { localChatRoom: LocalChatRoom, innerEvent: Event, sessionId: String, - userPublicKey: HexKey + userPublicKey: HexKey, + nostrPrivateKey: ByteArray? = null, ): FrostSigningSession? { database.frostSigningSessionDao().getSessionById(sessionId)?.let { existing -> // The events a session signs are fixed at creation. A second proposal @@ -696,6 +704,30 @@ object FrostSigningManager { return declined } + // A message the group would send: every signer reads it first, and declines one + // it cannot read or that says different things to different people. One still + // waiting on a recipient's key is held, stored, and asked once the key is made. + // docs/group-threshold-ecdh.md, D13. + var groupDm: GroupDmRefusal.Verdict.Readable? = null + if (GroupDmRefusal.involves(unsignedEvents)) { + when (val verdict = GroupDmRefusal.check(database, localChatRoom, innerEvent.pubKey, unsignedEvents, innerEvent.tags, userPublicKey, nostrPrivateKey)) { + is GroupDmRefusal.Verdict.Declined -> { + logger.w("Signing proposal $sessionId: a message from the group ${verdict.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 + } + GroupDmRefusal.Verdict.Waiting -> { + logger.i("Signing proposal $sessionId: waiting on a recipient's key before asking") + return null + } + is GroupDmRefusal.Verdict.Readable -> groupDm = verdict + } + } + // 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 @@ -777,6 +809,8 @@ object FrostSigningManager { database.frostSigningSessionDao().upsert(session) database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) confederation?.let { ConfederationRefusal.remember(database, sessionId, it, null) } + // Read, so filed: every admin's device sees what the group is sending (D12). + groupDm?.let { GroupDmSender.record(database, session, localChatRoom.chatRoom.id, it.rumor, it.manifest) } announceStarted(database, session) logger.i( @@ -1445,6 +1479,14 @@ object FrostSigningManager { logger.e("Signed session ${session.id} but could not file its confederation event", e) } + // A message from the group: wrapped for each recipient by the device that + // proposed it, and owed to their relays. docs/group-threshold-ecdh.md, D10. + try { + GroupDmSender.onSigned(database, session, signedEvents) + } catch (e: Throwable) { + logger.e("Signed session ${session.id} but could not wrap its message", e) + } + // Where the group receives messages: owed to relays by the device that // proposed it. docs/group-threshold-ecdh.md, D8. try { @@ -2248,6 +2290,18 @@ object FrostSigningManager { return } + // A message from the group this device did not read on arrival -- filed by an + // older build, or reached here some other way -- is declined, never signed blind. + // Read means filed: GroupDmSender.record wrote it as outgoing. D13. + if (session.subject == FrostSigningSubject.EVENTS && GroupDmRefusal.involvesItems(items) && + database.groupDmDao().getMessageBySigningSession(sessionId) == null + ) { + logger.w("Session $sessionId signs a message from the group this device has not read; declining") + update(database, session) { it.copy(signDeclinedAt = Clock.System.now()) } + advance(database, localChatRoom, sessionId) + 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") @@ -2758,6 +2812,8 @@ object FrostSigningManager { isWalletSession(session, items) -> WalletRefusal.REASON isUnshowableSession(session, items) -> GroupStatementRefusal.REASON isRefusedRelayList(session, items) -> GroupDmRelayRefusal.REASON + session.subject == FrostSigningSubject.EVENTS && GroupDmRefusal.involvesItems(items) -> + GroupDmRefusal.reasonFor(database, session.chatRoomId, session.userPublicKey) !holdsShareFor(database, session) -> GENERATION_REFUSAL else -> "Declined to sign" } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRefusal.kt new file mode 100644 index 00000000..b2d97392 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRefusal.kt @@ -0,0 +1,143 @@ +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.nip59Giftwrap.seals.SealEvent +import kotlin.time.Clock +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.FrostSigningItem +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.groupdm.AdminSeal +import mobi.giza.compose.nostr.groupdm.EcdhPurpose +import mobi.giza.compose.nostr.groupdm.Evidence +import mobi.giza.compose.nostr.groupdm.GroupDmManifest +import mobi.giza.compose.nostr.groupdm.GroupDmSeal + +/** + * Every signer reads a message before the group sends it (D13 of docs/group-threshold-ecdh.md). + * + * A seal is ciphertext, and a device that signs one it cannot read is the rubber stamp + * docs/giza-wallet-removal.md says a Giza device must never be. So a batch of kind 13s is + * checked on arrival, again at approval, and declined out loud with a reason when it fails: + * + * 1. the manifest opens with this device's host key, from a proposer who is a current admin; + * 2. every event is a kind 13 by the room, with no tags; + * 3. every recipient's evidence is signed by that recipient, and is not the group; + * 4. this device holds `conv(group, R)` for each, or it *waits* -- joins the round and asks + * nothing yet -- rather than declining; + * 5. every seal opens to the **same** rumor: kind 14, by the room, unsigned, words in it, and + * `p` tags exactly the manifest's recipients; + * 6. every `created_at` is within two days before now and not ahead of it. + * + * With the feature off, every batch of seals is declined: a release build cannot read one. + */ +object GroupDmRefusal { + const val REASON = "Giza doesn't sign a private message unless it can read it, and it says the same thing to everyone" + const val CANNOT_READ = "This device can't read what the group would be sending" + const val FEATURE_OFF = "Giza doesn't sign a private message it can't read" + + /** How far a seal's `created_at` may be from now: NIP-59's two days back, and a little skew forward. */ + private const val TWO_DAYS = 2L * 24 * 60 * 60 + private const val SKEW = 10L * 60 + + sealed interface Verdict { + /** The message every seal carries, and the manifest it was read from. */ + data class Readable(val rumor: Event, val manifest: GroupDmManifest) : Verdict + + /** Declined, with the reason sent to the group. */ + data class Declined(val reason: String, val why: String) : Verdict + + /** This device is still computing a recipient's key; nothing is asked until it has. */ + data object Waiting : Verdict + } + + fun involves(events: List): Boolean = events.any { it.kind == SealEvent.KIND } + + fun involvesItems(items: List): Boolean = + items.any { Event.fromJsonOrNull(it.unsignedEventJson)?.kind == SealEvent.KIND } + + suspend fun check( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + proposer: HexKey, + events: List, + proposalTags: Array>, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray?, + now: Long = Clock.System.now().epochSeconds, + ): Verdict { + if (!ExperimentalFeatures.groupDirectMessages) return Verdict.Declined(FEATURE_OFF, "the feature is off") + val roomId = localChatRoom.chatRoom.id + // A batch of seals with nothing to read them by is no message any device could check. + val sealed = GroupDmManifest.sealedIn(proposalTags) ?: return Verdict.Declined(CANNOT_READ, "there is no manifest") + val secret = nostrPrivateKey ?: return Verdict.Waiting + + // 1. The manifest, addressed to this device's host key by a current admin. + val context = GroupEcdhManager.contextFor(database, localChatRoom, userPublicKey, secret) + ?: return Verdict.Declined(CANNOT_READ, "this device's member is not a current admin holding a share") + val proposerHost = context.admins[proposer]?.second + ?: return Verdict.Declined(CANNOT_READ, "the proposer is not a current admin") + val manifest = AdminSeal.open(sealed, ChillDkgRitualManager.deriveHostSecretKey(secret), context.myHostKey, proposerHost) + ?.let(GroupDmManifest::decode) + ?: return Verdict.Declined(CANNOT_READ, "the manifest has no slot this device can open") + + // 2. Seals by the room, with nothing a recipient's app would not expect. + if (events.isEmpty() || events.size != manifest.seals.size) return Verdict.Declined(REASON, "the manifest names ${manifest.seals.size} recipients for ${events.size} seals") + events.forEach { seal -> + if (seal.kind != SealEvent.KIND || !seal.pubKey.equals(roomId, ignoreCase = true) || seal.tags.isNotEmpty()) { + return Verdict.Declined(REASON, "an item is not a bare kind 13 by the group") + } + } + + // 3. Each recipient's evidence, as D5 asks of anyone a device multiplies by. + val recipients = manifest.seals.map { it.recipient.lowercase() } + if (recipients.toSet().size != recipients.size) return Verdict.Declined(REASON, "a recipient repeats") + manifest.seals.forEach { seal -> + Evidence.check(EcdhPurpose.RECIPIENT, seal.recipient, seal.evidence, roomId)?.let { + return Verdict.Declined(REASON, "a recipient's evidence was refused: $it") + } + } + + // 4. The conversation keys, or a round for each missing one, and wait. + val keys = recipients.map { database.groupDmDao().getConversationKey(roomId, it) } + if (keys.any { it == null }) { + manifest.seals.filterIndexed { i, _ -> keys[i] == null }.forEach { seal -> + GroupEcdhManager.ensureRound(database, context, seal.recipient, EcdhPurpose.RECIPIENT, evidence = seal.evidence) + } + GroupEcdhManager.flush(database, context) + return Verdict.Waiting + } + + // 5. One message, the same to everyone, to exactly the recipients named. + val rumors = events.mapIndexed { i, seal -> + GroupDmSeal.open(seal, keys[i]!!.conversationKey.hexToByteArray()) + ?: return Verdict.Declined(REASON, "a seal does not open with its recipient's key") + } + val rumor = rumors.first() + if (rumors.any { it.id != rumor.id || it.toJson() != rumor.toJson() }) return Verdict.Declined(REASON, "the seals do not hold the same message") + if (rumor.kind != 14 || !rumor.pubKey.equals(roomId, ignoreCase = true) || rumor.content.isBlank()) { + return Verdict.Declined(REASON, "the message is not a kind 14 by the group with words in it") + } + val tagged = rumor.tags.filter { it.size >= 2 && it[0] == "p" }.map { it[1].lowercase() } + if (tagged.toSet() != recipients.toSet() || tagged.size != recipients.size) { + return Verdict.Declined(REASON, "the message names other recipients than the manifest") + } + + // 6. Back-dated as NIP-59 does, and not from the future. + events.forEach { seal -> + if (seal.createdAt > now + SKEW || seal.createdAt < now - TWO_DAYS - SKEW) { + return Verdict.Declined(REASON, "a seal's time is outside NIP-59's two days") + } + } + return Verdict.Readable(rumor, manifest) + } + + /** The reason a decline of [items] says, on a device without its key to hand. */ + suspend fun reasonFor(database: GizaDatabase, chatRoomId: HexKey, userPublicKey: HexKey): String { + if (!ExperimentalFeatures.groupDirectMessages) return FEATURE_OFF + val admins = RoomAdmins.of(database, chatRoomId)?.admins.orEmpty() + return if (userPublicKey in admins) REASON else CANNOT_READ + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmSender.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmSender.kt new file mode 100644 index 00000000..0ad71d94 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmSender.kt @@ -0,0 +1,231 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.crypto.random.RandomInstance +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.nip59Giftwrap.seals.SealEvent +import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent +import kotlin.time.Clock +import kotlin.time.Instant +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.GroupDmMessage +import mobi.giza.compose.database.model.GroupDmOutbound +import mobi.giza.compose.database.model.GroupDmWrapState +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.groupdm.EcdhPurpose +import mobi.giza.compose.nostr.groupdm.Evidence +import mobi.giza.compose.nostr.groupdm.GroupDmConversation +import mobi.giza.compose.nostr.groupdm.GroupDmManifest +import mobi.giza.compose.nostr.groupdm.GroupDmSeal + +/** + * The group writing to someone (D10 and D12 of docs/group-threshold-ecdh.md): one rumor, one + * seal per recipient under the kept `conv(group, R)`, signed by the group in one batch, then + * wrapped by the proposer's device under a key of its own and sent to each recipient's 10050. + * + * There is no copy to the group itself: that would be ECDH with the group's own npub, which D5 + * forbids. Every admin's device files the message as outgoing from the manifest instead. + */ +object GroupDmSender { + private val logger = Logger.withTag("GroupDmSender") + + private const val TWO_DAYS = 2L * 24 * 60 * 60 + + sealed interface Outcome { + /** Proposed: the group's quorum signs it next. */ + data class Proposed(val sessionId: String) : Outcome + + /** A recipient's key is still being computed by the admins; try again when it is. */ + data class Preparing(val recipients: List) : Outcome + + /** Nothing signed by [recipient] is on this device, so no device may multiply by their key (D5). */ + data class NoEvidence(val recipient: HexKey) : Outcome + + /** This device's member is not a current admin holding a share. */ + data object NotAnAdmin : Outcome + } + + /** + * Something [recipient] signed that this device can check: a seal they sent the group, or + * any event of theirs it holds. The smallest of them, since the manifest carries it. + */ + suspend fun evidenceFor(database: GizaDatabase, roomId: HexKey, recipient: HexKey): Event? { + val r = recipient.lowercase() + val seals = database.groupDmDao().getWrapsInState(roomId, GroupDmWrapState.OPENED.name) + .mapNotNull { it.sealJson?.let { json -> runCatching { Event.fromJson(json) }.getOrNull() } } + .filter { it.pubKey == r } + val own = listOf(10050, 0, 10002, 1).mapNotNull { kind -> + database.nostrEventDao().getNostrEventByPublicKeyAndKind(r, kind)?.takeIf { it.sig.length == 128 }?.toEvent() + } + return (own + seals) + .filter { Evidence.allows(EcdhPurpose.RECIPIENT, r, it, roomId) } + .minByOrNull { it.toJson().length } + } + + /** Where [recipient] receives messages: their 10050, or the publish set and the app's DM relays. */ + suspend fun relaysFor(database: GizaDatabase, recipient: HexKey): List { + val listed = database.nostrEventDao().getNostrEventByPublicKeyAndKind(recipient.lowercase(), GroupDmRelays.KIND) + ?.let { GroupDmRelays.relaysIn(it.tags) } + return listed?.takeIf { it.isNotEmpty() } + ?: (Relays.eventPublishRelaySet.map { it.url } + Relays.DefaultDMRelayList.map { it.url }).distinct() + } + + /** + * Asks the group to send [text] to [recipients], answering [replyTo] if given. A recipient + * whose key the admins have not computed yet has a round opened, and the answer is + * [Outcome.Preparing]; the composer tries again once the round combines. + */ + suspend fun send( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + recipients: List, + text: String, + replyTo: HexKey? = null, + now: Long = Clock.System.now().epochSeconds, + ): Outcome { + require(text.isNotBlank()) { "A message has words in it" } + val to = recipients.map { it.lowercase() }.distinct() + require(to.isNotEmpty()) { "A message has a recipient" } + val context = GroupEcdhManager.contextFor(database, localChatRoom, userPublicKey, nostrPrivateKey) ?: return Outcome.NotAnAdmin + val roomId = context.roomId + require(to.none { it == roomId }) { "The group does not write to itself (D5)" } + + val evidence = to.associateWith { r -> evidenceFor(database, roomId, r) ?: return Outcome.NoEvidence(r) } + val keys = to.associateWith { database.groupDmDao().getConversationKey(roomId, it) } + val missing = to.filter { keys[it] == null } + if (missing.isNotEmpty()) { + missing.forEach { r -> GroupEcdhManager.ensureRound(database, context, r, EcdhPurpose.RECIPIENT, evidence = evidence.getValue(r)) } + GroupEcdhManager.advance(database, context) + val still = missing.filter { database.groupDmDao().getConversationKey(roomId, it) == null } + if (still.isNotEmpty()) return Outcome.Preparing(still) + } + + val tags = to.map { arrayOf("p", it) } + listOfNotNull(replyTo?.let { arrayOf("e", it, "", "reply") }) + val rumor = GroupDmSeal.rumor(roomId, now, 14, tags.toTypedArray(), text) + val seals = to.map { r -> + val key = database.groupDmDao().getConversationKey(roomId, r)!!.conversationKey.hexToByteArray() + GroupDmSeal.build(rumor, key, createdAt = now - randomBackdate()) + } + val manifest = GroupDmManifest(to.map { GroupDmManifest.Seal(it, evidence.getValue(it)) }, replyTo) + val session = FrostSigningManager.proposeSigningBatch( + database = database, + localChatRoom = localChatRoom, + userPublicKey = userPublicKey, + events = seals, + key = context.key, + proposalTags = manifest.toTags(context.sealToAdmins(manifest.encode())), + ) + record(database, session, roomId, rumor, manifest) + return Outcome.Proposed(session.id) + } + + /** NIP-59's back-dating: up to two days, at random. */ + private fun randomBackdate(): Long { + val bytes = RandomInstance.bytes(4) + val v = ((bytes[0].toLong() and 0xff) shl 24) or ((bytes[1].toLong() and 0xff) shl 16) or + ((bytes[2].toLong() and 0xff) shl 8) or (bytes[3].toLong() and 0xff) + return v % TWO_DAYS + } + + /** + * Files a message the group is being asked to send, on any admin's device that has read it: + * outgoing in its conversation, and one owed wrap per recipient, keyed by the seal's id, + * waiting for the signature. Idempotent. + */ + suspend fun record(database: GizaDatabase, session: FrostSigningSession, roomId: HexKey, rumor: Event, manifest: GroupDmManifest) { + val dao = database.groupDmDao() + dao.insertMessage( + GroupDmMessage( + rumorId = rumor.id, + chatRoomId = roomId, + conversationId = GroupDmConversation.idOf(rumor, roomId), + senderPublicKey = roomId, + rumorJson = rumor.toJson(), + createdAt = Instant.fromEpochSeconds(rumor.createdAt), + outgoing = true, + signingSessionId = session.id, + readAt = Clock.System.now(), + ) + ) + val items = database.frostSigningSessionDao().getItems(session.id).sortedBy { it.itemIndex } + items.forEachIndexed { i, item -> + val recipient = manifest.seals.getOrNull(i)?.recipient ?: return@forEachIndexed + dao.insertOutbound( + GroupDmOutbound( + signingSessionId = session.id, + sealId = item.eventId, + chatRoomId = roomId, + recipient = recipient, + relays = relaysFor(database, recipient).joinToString(","), + ) + ) + } + } + + /** + * A batch of seals the group just signed: the proposer's device wraps each for its recipient + * and owes it to their relays. Other devices hold the same rows unwrapped, for Send again. + */ + suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, signedEvents: List) { + if (signedEvents.none { it.kind == SealEvent.KIND }) return + if (!session.isCoordinator()) return + wrapOwed(database, session.id, signedEvents) + } + + /** + * Send again, from any admin's device: wraps whatever this device has not wrapped, from the + * signed seals every signer holds, and owes them again. Whether there was anything to send. + */ + suspend fun sendAgain(database: GizaDatabase, signingSessionId: String): Boolean { + val signed = database.groupDmDao().getOutbound(signingSessionId).mapNotNull { row -> + database.groupSignedEventDao().getById(row.sealId)?.toEvent() + } + val rows = wrapOwed(database, signingSessionId, signed) + database.groupDmDao().getOutbound(signingSessionId).filter { it.publishedAt == null && it.wrapJson != null }.forEach { + database.groupDmDao().upsertOutbound(it.copy(attempts = 0, nextAttemptAt = null)) + } + return rows > 0 || database.groupDmDao().getOutbound(signingSessionId).any { it.publishedAt == null } + } + + private suspend fun wrapOwed(database: GizaDatabase, signingSessionId: String, signedEvents: List): Int { + val dao = database.groupDmDao() + var wrapped = 0 + dao.getOutbound(signingSessionId).filter { it.wrapJson == null }.forEach { row -> + val signed = signedEvents.firstOrNull { it.id == row.sealId }?.takeIf { it.verify() } ?: return@forEach + // Ordinary NIP-59: a fresh key of this device's, no group secret involved. + val wrap = GiftWrapEvent.create(event = signed, recipientPubKey = row.recipient) + dao.upsertOutbound(row.copy(wrapJson = wrap.toJson())) + wrapped += 1 + } + if (wrapped > 0) logger.i { "Wrapped $wrapped seal(s) of $signingSessionId for their recipients" } + return wrapped + } + + /** + * Proposals of the group's messages this device held back while it computed a recipient's + * key (D13, check 4): handed to the signing manager again now that a round has combined. + */ + suspend fun retryHeld(database: GizaDatabase, context: GroupEcdhManager.RoomContext, nostrPrivateKey: ByteArray) { + database.marmotInnerEventDao().getByChatRoomAndKinds(context.roomId, listOf(FrostSigningEvents.PROPOSAL)) + .filter { GroupDmManifest.isCarriedBy(it.tags) } + .forEach { stored -> + val sessionId = FrostSigningEvents.parseSessionId(stored.tags) ?: return@forEach + if (database.frostSigningSessionDao().getSessionById(sessionId) != null) return@forEach + FrostSigningManager.processSigningPayload( + database = database, + localChatRoom = context.room, + innerEvent = Event(stored.id, stored.publicKey, stored.createdAt.epochSeconds, stored.kind, stored.tags, stored.content, ""), + userPublicKey = context.userPublicKey, + nostrPrivateKey = nostrPrivateKey, + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupEcdhManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupEcdhManager.kt index 7bb3bb66..9387e538 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupEcdhManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupEcdhManager.kt @@ -69,6 +69,8 @@ object GroupEcdhManager { val tweak: NpubTweak, private val hostSecret: PrivateKey, val myHostKey: HexKey, + /** For the one caller that hands a held proposal back to the signing manager ([GroupDmSender.retryHeld]). */ + internal val nostrPrivateKey: ByteArray, /** Current admins holding a share of [generation], this device's member included: member to (id, host key). */ val admins: Map>, ) { @@ -82,6 +84,9 @@ object GroupEcdhManager { internal fun seal(plaintext: String): AdminSeal.Sealed = AdminSeal.seal(plaintext, hostSecret, admins.filterKeys { it != userPublicKey }.values.map { it.second }) + /** [plaintext] for the other current admins: a message's manifest (D12). */ + internal fun sealToAdmins(plaintext: String): AdminSeal.Sealed = seal(plaintext) + internal fun open(sealed: AdminSeal.Sealed, senderHostKey: HexKey): String? = AdminSeal.open(sealed, hostSecret, myHostKey, senderHostKey) @@ -113,7 +118,7 @@ object GroupEcdhManager { return RoomContext( room = room, userPublicKey = userPublicKey, key = key, generation = shares.generation, myId = myId, secretShare = secretShare, publicShares = publicShares, threshold = key.threshold, tweak = tweak, - hostSecret = hostSecret, myHostKey = myHostKey, admins = admins, + hostSecret = hostSecret, myHostKey = myHostKey, nostrPrivateKey = nostrPrivateKey, admins = admins, ) } @@ -273,6 +278,8 @@ object GroupEcdhManager { val stepped = GroupDmReceiver.step(database, context) val sent = flush(database, context) val combined = combine(database, context) + // A recipient's key just made: a message held back for it can be read now (D13). + if (combined.any { it.purpose == EcdhPurpose.RECIPIENT }) GroupDmSender.retryHeld(database, context, context.nostrPrivateKey) if (!stepped && sent == 0 && combined.isEmpty()) return } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt index 0863856c..ef922b23 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt @@ -51,6 +51,12 @@ interface GroupDmRepository { /** How a screen names a person: their profile's name, or the start of their key. */ suspend fun nameOf(publicKey: HexKey): String + /** Asks the group to send [text] to [recipients] (D10), as the active identity. */ + suspend fun send(localChatRoom: LocalChatRoom, recipients: List, text: String, replyTo: HexKey?): mobi.giza.compose.managers.GroupDmSender.Outcome + + /** Wraps and sends again what a signed message still owes its recipients. */ + suspend fun sendAgain(signingSessionId: String): 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 ddeb8f1f..bff1b69a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -134,6 +134,14 @@ object ProposedEvent { ConfederationKinds.WITHDRAWAL -> Summary(label = "Withdrawing a confederation proposal", detail = event.content) + // A message from the group, sealed to one recipient: ciphertext. What it says is + // on the signing screen of an admin's device, read from the manifest; to anyone + // else this is all there is to say. docs/group-threshold-ecdh.md, D12. + com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent.KIND -> Summary( + label = "A private message from the group", + detail = "Sealed to its recipient", + ) + // 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( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmScreens.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmScreens.kt index 54788074..3ff52ef8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmScreens.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmScreens.kt @@ -25,6 +25,39 @@ import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.clearText +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.FilledIconButton +import androidx.compose.material3.OutlinedTextField +import mobi.giza.compose.extensions.bech32ToHexOrThrow +import mobi.giza.compose.resources.asked_the_group_to_sign_this_message +import mobi.giza.compose.resources.cancel +import mobi.giza.compose.resources.could_not_ask_the_group_to_send_this +import mobi.giza.compose.resources.new_message +import mobi.giza.compose.resources.nothing_signed_by_this_person_is_on_this_device_yet +import mobi.giza.compose.resources.preparing_the_admins_are_working_out_how_to_write_to_them +import mobi.giza.compose.resources.send +import mobi.giza.compose.resources.sending_again +import mobi.giza.compose.resources.that_is_not_a_nostr_key +import mobi.giza.compose.resources.the_groups_quorum_has_to_sign_before_anything_is_sent +import mobi.giza.compose.resources.their_npub +import mobi.giza.compose.resources.write_a_message +import mobi.giza.compose.resources.write_to_them +import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.buttons.ExtendedFab +import mobi.giza.compose.ui.composable.widgets.rememberNotifier import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow @@ -86,11 +119,21 @@ fun GroupDmListScreen( groupDmRepository: GroupDmRepository, onNavigateToRoute: (Route) -> Unit, onNavigateBack: () -> Unit, - composer: (@Composable () -> Unit)? = null, ) { val viewModel: GroupDmListViewModel = viewModel( factory = GroupDmListViewModel.factory(chatRoomId, activeUserPublicKey, chatRepository, groupDmRepository) ) + var writing by remember { mutableStateOf(false) } + val canWrite = (viewModel.uiState as? GroupDmListUIState.Loaded)?.isAdmin == true && LocalCanSign.current + if (writing) { + NewMessageDialog( + onDismiss = { writing = false }, + onRecipient = { recipient -> + writing = false + onNavigateToRoute(GroupDmConversationRoute(activeUserPublicKey, chatRoomId, conversationId = null, recipients = listOf(recipient))) + }, + ) + } Scaffold( snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, @@ -100,7 +143,15 @@ fun GroupDmListScreen( navigationIcon = { NavigateBackButton(onNavigateBack) }, ) }, - floatingActionButton = { composer?.invoke() }, + floatingActionButton = { + if (canWrite) { + ExtendedFab( + label = stringResource(Res.string.new_message), + icon = { Icon(Icons.Default.Edit, contentDescription = Decorative) }, + onClick = { writing = true }, + ) + } + }, ) { padding -> ScreenStateTransition(viewModel.uiState) { uiState -> when (val state = uiState) { @@ -197,9 +248,14 @@ fun GroupDmConversationScreen( chatRepository: ChatRepository, groupDmRepository: GroupDmRepository, onNavigateBack: () -> Unit, - onSendAgain: ((signingSessionId: String) -> Unit)? = null, - composer: (@Composable (participants: List, replyTo: GroupDmLine?) -> Unit)? = null, + onNavigateToRoute: (Route) -> Unit = {}, ) { + val notify = rememberNotifier(rememberCoroutineScope()) + val proposed = stringResource(Res.string.asked_the_group_to_sign_this_message) + val noEvidence = stringResource(Res.string.nothing_signed_by_this_person_is_on_this_device_yet) + val couldNotSend = stringResource(Res.string.could_not_ask_the_group_to_send_this) + val sendingAgain = stringResource(Res.string.sending_again) + val canSign = LocalCanSign.current val viewModel: GroupDmConversationViewModel = viewModel( key = "$chatRoomId/$conversationId/${recipients.joinToString(",")}", factory = GroupDmConversationViewModel.factory(chatRoomId, activeUserPublicKey, conversationId, recipients, chatRepository, groupDmRepository) @@ -218,7 +274,24 @@ fun GroupDmConversationScreen( ) }, bottomBar = { - if (state.isAdmin) composer?.invoke(state.participants, state.lines.lastOrNull { !it.outgoing }) + if (state.isAdmin && canSign) { + Composer( + composing = viewModel.composing, + onSend = { text, clear -> + viewModel.send( + text = text, + replyTo = state.lines.lastOrNull { !it.outgoing }?.id, + onProposed = { sessionId -> + clear() + notify(proposed) + onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) + }, + onNoEvidence = { notify(noEvidence) }, + onFailure = { notify(couldNotSend) }, + ) + }, + ) + } }, ) { padding -> LazyColumn( @@ -230,7 +303,9 @@ fun GroupDmConversationScreen( item { EmptyState(message = stringResource(Res.string.only_current_admins_see_the_groups_messages), icon = Icons.Default.Mail) } return@LazyColumn } - items(items = state.lines, key = { it.id }) { line -> GroupDmBubble(line, onSendAgain) } + items(items = state.lines, key = { it.id }) { line -> + GroupDmBubble(line, onSendAgain = { sessionId -> viewModel.sendAgain(sessionId) { notify(sendingAgain) } }) + } } } } @@ -269,7 +344,8 @@ private fun GroupDmBubble(line: GroupDmLine, onSendAgain: ((String) -> Unit)?) { color = MaterialTheme.colorScheme.onSurfaceVariant, ) val sessionId = line.signingSessionId - if (state == GroupDmOutgoingState.NOT_SENT && sessionId != null && onSendAgain != null) { + val owes = state == GroupDmOutgoingState.NOT_SENT || state == GroupDmOutgoingState.SIGNED + if (owes && sessionId != null && onSendAgain != null) { TextButton(onClick = { onSendAgain(sessionId) }) { Text(stringResource(Res.string.send_again)) } } } @@ -277,3 +353,75 @@ private fun GroupDmBubble(line: GroupDmLine, onSendAgain: ((String) -> Unit)?) { } } } + +/** + * What an admin writes as the group, with what sending means said above the button: nothing + * goes until the group's quorum has signed (D10). + */ +@Composable +private fun Composer(composing: GroupDmConversationViewModel.Composing, onSend: (String, clear: () -> Unit) -> Unit) { + val field = rememberTextFieldState() + Column( + modifier = Modifier.fillMaxWidth().imePadding().padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Text( + text = when (composing) { + GroupDmConversationViewModel.Composing.Preparing -> stringResource(Res.string.preparing_the_admins_are_working_out_how_to_write_to_them) + else -> stringResource(Res.string.the_groups_quorum_has_to_sign_before_anything_is_sent) + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + OutlinedTextField( + state = field, + modifier = Modifier.weight(1f), + placeholder = { Text(stringResource(Res.string.write_a_message)) }, + lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 5), + ) + FilledIconButton( + enabled = composing == GroupDmConversationViewModel.Composing.Idle && field.text.isNotBlank(), + onClick = { onSend(field.text.toString()) { field.clearText() } }, + ) { + Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(Res.string.send)) + } + } + } +} + +/** Starts a conversation: an npub, pasted. */ +@Composable +internal fun NewMessageDialog(onDismiss: () -> Unit, onRecipient: (HexKey) -> Unit) { + val field = rememberTextFieldState() + val key = recipientKeyOf(field.text.toString()) + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(Res.string.new_message)) }, + text = { + OutlinedTextField( + state = field, + label = { Text(stringResource(Res.string.their_npub)) }, + isError = field.text.isNotBlank() && key == null, + supportingText = if (field.text.isNotBlank() && key == null) { + { Text(stringResource(Res.string.that_is_not_a_nostr_key)) } + } else null, + lineLimits = TextFieldLineLimits.SingleLine, + ) + }, + confirmButton = { + TextButton(enabled = key != null, onClick = { key?.let(onRecipient) }) { Text(stringResource(Res.string.write_to_them)) } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.cancel)) } }, + ) +} + +/** An npub or 64 hex characters, as a key; null for anything else. */ +internal fun recipientKeyOf(text: String): HexKey? { + val trimmed = text.trim().removePrefix("nostr:") + val hex = when { + trimmed.startsWith("npub1") -> runCatching { trimmed.bech32ToHexOrThrow() }.getOrNull() + else -> trimmed.lowercase() + } ?: return null + return hex.takeIf { it.length == 64 && it.all { c -> c in "0123456789abcdef" } && mobi.giza.compose.cryptography.threshold.ThresholdEcdh.pointOf(it) != null } +} 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 b81fe02d..7091824a 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 @@ -224,7 +224,10 @@ fun GizaNavHost( ) } val databaseGroupDmRepository = remember { - mobi.giza.compose.database.repository.DatabaseGroupDmRepository(database = auxDatabaseManager.auxDatabase) + mobi.giza.compose.database.repository.DatabaseGroupDmRepository( + database = auxDatabaseManager.auxDatabase, + activeIdentity = sovereignWalletViewModel.activeIdentity, + ) } val databaseMarmotRepository = remember { DatabaseMarmotRepository( @@ -1337,7 +1340,8 @@ fun GizaNavHost( recipients = route.recipients, chatRepository = databaseChatRepository, groupDmRepository = databaseGroupDmRepository, - onNavigateBack = { navController.popBackStack() } + onNavigateBack = { navController.popBackStack() }, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, ) } // A group's confederations: docs/confederation.md. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmConversationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmConversationViewModel.kt index e2f2c987..fa59b2db 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmConversationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmConversationViewModel.kt @@ -12,6 +12,9 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.launch +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import mobi.giza.compose.managers.GroupDmSender import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.GroupDmRepository import mobi.giza.compose.ui.view.state.GroupDmConversationUIState @@ -41,15 +44,61 @@ class GroupDmConversationViewModel( val isAdmin = groupDmRepository.isCurrentAdmin(chatRoomId, activeUserPublicKey) val participants = conversationId?.let { groupDmRepository.participantsOf(chatRoomId, it) }?.takeIf { it.isNotEmpty() } ?: recipients val names = participants.map { groupDmRepository.nameOf(it) } - val lines = if (isAdmin && conversationId != null) groupDmRepository.observeConversation(chatRoomId, conversationId) else flowOf(emptyList()) + // A new conversation is the one its recipients make: the same id the first message files under. + val id = conversationId ?: mobi.giza.compose.nostr.groupdm.GroupDmConversation.idOf(recipients) + val lines = if (isAdmin) groupDmRepository.observeConversation(chatRoomId, id) else flowOf(emptyList()) lines.collect { current -> - if (isAdmin && conversationId != null) groupDmRepository.markRead(chatRoomId, conversationId) + if (isAdmin) groupDmRepository.markRead(chatRoomId, id) uiState = GroupDmConversationUIState.Loaded(room, participants, names, current, isAdmin) } } } + /** Where the composer is: idle, preparing a recipient's key, or sending. */ + var composing: Composing by mutableStateOf(Composing.Idle) + private set + + enum class Composing { Idle, Preparing, Sending } + + /** + * Asks the group to send [text] (D10). A recipient whose key is still being computed has + * the composer wait and try again, for a few minutes, while the admins' apps answer. + */ + fun send(text: String, replyTo: HexKey?, onProposed: (sessionId: String) -> Unit, onNoEvidence: () -> Unit, onFailure: () -> Unit) { + val loaded = uiState as? GroupDmConversationUIState.Loaded ?: return + if (composing != Composing.Idle || text.isBlank()) return + composing = Composing.Sending + viewModelScope.launch(Dispatchers.IO) { + var outcome = runCatching { groupDmRepository.send(loaded.localChatRoom, loaded.participants, text, replyTo) }.getOrNull() + var tries = 0 + while (outcome is GroupDmSender.Outcome.Preparing && tries < PREPARING_TRIES) { + composing = Composing.Preparing + delay(PREPARING_INTERVAL) + outcome = runCatching { groupDmRepository.send(loaded.localChatRoom, loaded.participants, text, replyTo) }.getOrNull() + tries += 1 + } + withContext(Dispatchers.Main) { + composing = Composing.Idle + when (outcome) { + is GroupDmSender.Outcome.Proposed -> onProposed(outcome.sessionId) + is GroupDmSender.Outcome.NoEvidence -> onNoEvidence() + else -> onFailure() + } + } + } + } + + fun sendAgain(signingSessionId: String, onDone: () -> Unit) { + viewModelScope.launch(Dispatchers.IO) { + runCatching { groupDmRepository.sendAgain(signingSessionId) } + withContext(Dispatchers.Main) { onDone() } + } + } + companion object { + private const val PREPARING_TRIES = 60 + private val PREPARING_INTERVAL = kotlin.time.Duration.parse("3s") + fun factory( chatRoomId: String, activeUserPublicKey: HexKey, diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmNetwork.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmNetwork.kt index 02239081..167fb902 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmNetwork.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmNetwork.kt @@ -145,7 +145,7 @@ class GroupDmNetwork(n: Int = 4, val t: Int = 2, secret: String = "6d0000".padEn if (event.kind in GroupEcdhEvents.ALL) { GroupEcdhManager.process(to.db, to.room, event, to.publicKey, to.privateKey) } else { - FrostSigningManager.processSigningPayload(to.db, to.room, event, to.publicKey) + FrostSigningManager.processSigningPayload(to.db, to.room, event, to.publicKey, to.privateKey) } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmSendJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmSendJvmTest.kt new file mode 100644 index 00000000..5c6bcdcf --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmSendJvmTest.kt @@ -0,0 +1,275 @@ +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.signers.EventTemplate +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import com.vitorpamplona.quartz.nip44Encryption.Nip44v2 +import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.ExperimentalFeatures +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.nostr.groupdm.AdminSeal +import mobi.giza.compose.nostr.groupdm.EcdhPurpose +import mobi.giza.compose.nostr.groupdm.GroupDmManifest +import mobi.giza.compose.nostr.groupdm.GroupDmSeal +import mobi.giza.compose.text.ProposedEvent +import mobi.giza.compose.ui.view.state.GroupDmOutgoingState + +/** + * Phase 9 of docs/group-threshold-ecdh.md: the group writing to someone. A proposed by A and + * signed by B reaches the recipient as stock NIP-17, every admin sees it as outgoing, and every + * way a proposal could say something other than what the signers read is declined. + */ +class GroupDmSendJvmTest { + private val net = GroupDmNetwork(n = 4, t = 2) + private val a get() = net.devices[0] + private val b get() = net.devices[1] + private val c get() = net.devices[2] + private val d get() = net.devices[3] + + private val recipient = KeyPair() + private val other = KeyPair() + private val r get() = recipient.pubKey.toHexKey() + private val r2 get() = other.pubKey.toHexKey() + + @BeforeTest + fun setUp() = runBlocking { + ExperimentalFeatures.groupDirectMessagesOverride = true + net.admins = net.members.take(3).toSet() + net.install() + net.all() + net.openMessages() + // What every admin's device holds of the people it writes to: their profile, and R's 10050. + listOf(recipient, other).forEach { person -> + val profile = NostrSignerSync(person).sign(1_700_000_000, 0, emptyArray(), """{"name":"someone"}""") + net.devices.forEach { it.db.nostrEventDao().upsert(rowOf(profile)) } + } + val inbox = NostrSignerSync(recipient).sign(1_700_000_000, 10050, arrayOf(arrayOf("relay", "wss://r.example")), "") + net.devices.forEach { it.db.nostrEventDao().upsert(rowOf(inbox)) } + } + + @AfterTest + fun tearDown() { + net.close() + ExperimentalFeatures.groupDirectMessagesOverride = null + } + + private fun rowOf(e: Event) = NostrEvent(id = e.id, pubKey = e.pubKey, kind = e.kind, tags = e.tags, content = e.content, sig = e.sig, createdAt = Instant.fromEpochSeconds(e.createdAt)) + + private suspend fun send(to: List, text: String) = GroupDmSender.send(a.db, a.room, a.publicKey, a.privateKey, to, text) + + /** Sends, letting the admins compute any key it waits on first. */ + private suspend fun sendWhenReady(to: List, text: String): String { + var outcome = send(to, text) + if (outcome is GroupDmSender.Outcome.Preparing) { + net.pump() + outcome = send(to, text) + } + return assertIs(outcome).sessionId + } + + 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()) + } + } + + @Test + fun `a message proposed by A and signed by B reaches the recipient as stock NIP-17`(): Unit = runBlocking { + assertIs(send(listOf(r), "hello from the group"), "the admins compute R's key first") + net.pump() + val sessionId = sendWhenReady(listOf(r), "hello from the group") + net.pump() + FrostSigningManager.approve(b.db, b.room, sessionId) + net.pump() + assertEquals(FrostSigningStage.COMPLETE, a.db.frostSigningSessionDao().getSessionById(sessionId)?.stage) + + // The proposer wrapped it, ordinary NIP-59, and owes it to R's relays. + val owed = a.db.groupDmDao().getOutbound(sessionId).single() + val wrap = Event.fromJson(assertNotNull(owed.wrapJson)) as GiftWrapEvent + val opened = assertNotNull(wrap.unwrapAndUnsealOrNull(NostrSignerInternal(recipient)), "a stock client opens it") + assertEquals("hello from the group", opened.content) + assertEquals(net.roomId, opened.pubKey) + + val transport = Transport() + assertTrue(GroupDmPublisher(DatabaseGroupDmRepository(a.db), transport).publish(owed)) + assertTrue("wss://r.example/" in transport.sent.single().second) + + // C did not sign, and sees it as outgoing. + val onC = assertNotNull(c.db.groupDmDao().getMessageBySigningSession(sessionId)) + assertTrue(onC.outgoing) + assertEquals("hello from the group", Event.fromJson(onC.rumorJson).content) + val lineOnA = DatabaseGroupDmRepository(a.db).observeConversation(net.roomId, onC.conversationId).first().single() + assertEquals(GroupDmOutgoingState.SENT, lineOnA.outgoingState) + + // A recipient written to before needs no round: the next message is proposed at once. + val roundsBefore = a.db.groupDmDao().getAllOpenRounds().size + assertIs(send(listOf(r), "and again")) + assertEquals(roundsBefore, a.db.groupDmDao().getAllOpenRounds().size) + + // R can answer: the reply opens on the admins' devices like any message to the group. + val reply = GiftWrapEvent.create( + com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent.create( + Event("", r, 1_700_000_100, 14, arrayOf(arrayOf("p", net.roomId)), "thanks", ""), net.roomId, NostrSignerInternal(recipient) + ), + net.roomId, + ) + net.receive(reply, a, b) + net.pump(between = listOf(a, b)) + assertTrue(a.db.groupDmDao().getMessages(net.roomId).any { Event.fromJson(it.rumorJson).content == "thanks" }) + } + + @Test + fun `send again wraps from any signer's device`(): Unit = runBlocking { + send(listOf(r), "x"); net.pump() + val sessionId = sendWhenReady(listOf(r), "x") + net.pump() + FrostSigningManager.approve(b.db, b.room, sessionId) + net.pump() + val onB = b.db.groupDmDao().getOutbound(sessionId).single() + assertNull(onB.wrapJson, "only the proposer wraps on its own") + assertTrue(GroupDmSender.sendAgain(b.db, sessionId)) + val wrap = Event.fromJson(assertNotNull(b.db.groupDmDao().getOutbound(sessionId).single().wrapJson)) as GiftWrapEvent + assertEquals("x", wrap.unwrapAndUnsealOrNull(NostrSignerInternal(recipient))?.content) + } + + // --- every refusal on its own + + /** The keys for R and R2, computed honestly first, so a dishonest seal is the only thing wrong. */ + private suspend fun keysReady() { + send(listOf(r, r2), "warm up"); net.pump() + listOf(a, b).forEach { device -> + assertNotNull(device.db.groupDmDao().getConversationKey(net.roomId, r)) + assertNotNull(device.db.groupDmDao().getConversationKey(net.roomId, r2)) + } + } + + private suspend fun keyOf(recipient: HexKey) = a.db.groupDmDao().getConversationKey(net.roomId, recipient)!!.conversationKey.hexToByteArray() + + private suspend fun evidenceOf(person: KeyPair): Event = NostrSignerSync(person).sign(1_700_000_000, 0, emptyArray(), "{}") + + private val now get() = Clock.System.now().epochSeconds + + private fun rumorTo(vararg to: HexKey, text: String = "the words") = + GroupDmSeal.rumor(net.roomId, now, 14, to.map { arrayOf("p", it) }.toTypedArray(), text) + + /** A proposal from A, built by hand, sealed to the other admins as A's device would. */ + private suspend fun proposeRaw(seals: List>, manifest: GroupDmManifest, slotsFor: List = listOf(b, c)): String { + val sealed = AdminSeal.seal(manifest.encode(), ChillDkgRitualManager.deriveHostSecretKey(a.privateKey), slotsFor.map { net.hostKeys[it.index] }) + return FrostSigningManager.proposeSigningBatch(a.db, a.room, a.publicKey, seals, proposalTags = manifest.toTags(sealed)).id + } + + private suspend fun assertDeclinedBy(device: GroupDmNetwork.Device, sessionId: String, reason: String = GroupDmRefusal.REASON) { + net.pump(between = listOf(a, device)) + val session = assertNotNull(device.db.frostSigningSessionDao().getSessionById(sessionId), "filed on $device") + assertNotNull(session.signDeclinedAt, "declined on $device") + assertNull(device.db.groupDmDao().getMessageBySigningSession(sessionId), "and not filed as the group's") + val declines = a.db.frostSigningSessionDao().getMessagesByKind(sessionId, FrostSigningEvents.DECLINE) + assertTrue(declines.any { it.signerPublicKey == device.publicKey }, "the proposer's device shows the decline") + val sent = net.outbox(device, listOf(FrostSigningEvents.DECLINE)).map { it.content } + assertTrue(reason in sent, "said with its reason: $sent") + } + + private fun manifestOf(vararg people: Pair) = GroupDmManifest(people.map { GroupDmManifest.Seal(it.first, it.second) }, null) + + @Test + fun `seals that say different things to different people are declined`(): Unit = runBlocking { + keysReady() + val one = rumorTo(r, r2, text = "the truth") + val two = rumorTo(r, r2, text = "something else") + val id = proposeRaw( + listOf(GroupDmSeal.build(one, keyOf(r), now - 60), GroupDmSeal.build(two, keyOf(r2), now - 60)), + manifestOf(r to evidenceOf(recipient), r2 to evidenceOf(other)), + ) + assertDeclinedBy(b, id) + } + + @Test + fun `a seal to the wrong key is declined`(): Unit = runBlocking { + keysReady() + val rumor = rumorTo(r) + val id = proposeRaw(listOf(GroupDmSeal.build(rumor, keyOf(r2), now - 60)), manifestOf(r to evidenceOf(recipient))) + assertDeclinedBy(b, id) + } + + @Test + fun `a message naming a recipient the manifest does not is declined`(): Unit = runBlocking { + keysReady() + val rumor = rumorTo(r, r2) + val id = proposeRaw(listOf(GroupDmSeal.build(rumor, keyOf(r), now - 60)), manifestOf(r to evidenceOf(recipient))) + assertDeclinedBy(b, id) + } + + @Test + fun `forged evidence is declined`(): Unit = runBlocking { + keysReady() + val rumor = rumorTo(r) + val id = proposeRaw(listOf(GroupDmSeal.build(rumor, keyOf(r), now - 60)), manifestOf(r to evidenceOf(KeyPair()))) + assertDeclinedBy(b, id) + } + + @Test + fun `a blank message is declined`(): Unit = runBlocking { + keysReady() + val rumor = rumorTo(r, text = " ") + val id = proposeRaw(listOf(GroupDmSeal.build(rumor, keyOf(r), now - 60)), manifestOf(r to evidenceOf(recipient))) + assertDeclinedBy(b, id) + } + + @Test + fun `a seal with tags is declined`(): Unit = runBlocking { + keysReady() + val honest = GroupDmSeal.build(rumorTo(r), keyOf(r), now - 60) + val tagged = EventTemplate(honest.createdAt, honest.kind, arrayOf(arrayOf("expiration", "${now + 99}")), honest.content) + val id = proposeRaw(listOf(tagged), manifestOf(r to evidenceOf(recipient))) + assertDeclinedBy(b, id) + } + + @Test + fun `a signer outside the current admins declines, and reads it only as a private message from the group`(): Unit = runBlocking { + keysReady() + val id = proposeRaw(listOf(GroupDmSeal.build(rumorTo(r), keyOf(r), now - 60)), manifestOf(r to evidenceOf(recipient))) + assertDeclinedBy(d, id, GroupDmRefusal.CANNOT_READ) + val item = d.db.frostSigningSessionDao().getItems(id).single() + assertEquals("A private message from the group", ProposedEvent.summarize(Event.fromJson(item.unsignedEventJson)).label) + assertEquals(emptyList(), d.db.groupDmDao().getMessages(net.roomId), "and learns nothing more") + } + + @Test + fun `an honest message is put to the signer, who sees its words`(): Unit = runBlocking { + keysReady() + val id = proposeRaw(listOf(GroupDmSeal.build(rumorTo(r, text = "fine"), keyOf(r), now - 60)), manifestOf(r to evidenceOf(recipient))) + net.pump(between = listOf(a, b)) + val session = assertNotNull(b.db.frostSigningSessionDao().getSessionById(id)) + assertNull(session.signDeclinedAt) + assertTrue(FrostSigningManager.isAwaitingApproval(session, b.db.frostSigningSessionDao().getItems(id))) + assertEquals("fine", Event.fromJson(assertNotNull(b.db.groupDmDao().getMessageBySigningSession(id)).rumorJson).content) + } +} 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 341bd2b1..d94d2407 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmTodayJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmTodayJvmTest.kt @@ -90,10 +90,22 @@ class GroupDmTodayJvmTest { assertEquals("Event of kind $kind", ProposedEvent.summarize(event).label) } - /** Phase 9 flips this: a seal no signer can read is declined unless D13's checks pass. */ + /** Flipped by Phase 9: a seal no signer can read is declined out loud (D13, GroupDmSendJvmTest). */ @Test - fun `a peer's kind 13 is asked as a raw kind, and can be signed blind`() { - assertAskedBlind(proposeKind(SealEvent.KIND, "AqH1ciphertext"), SealEvent.KIND) + fun `a peer's kind 13 is no longer signed blind`() = runBlocking { + val sent = proposeKind(SealEvent.KIND, "AqH1ciphertext") + harness.deliver(sent, bob) + val session = assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id)) + assertNotNull(session.signDeclinedAt) + val reason = harness.queued(FrostSigningEvents.DECLINE).single().content + assertTrue( + reason in setOf( + mobi.giza.compose.managers.GroupDmRefusal.REASON, + mobi.giza.compose.managers.GroupDmRefusal.CANNOT_READ, + mobi.giza.compose.managers.GroupDmRefusal.FEATURE_OFF, + ), + reason, + ) } /** Flipped by Phase 6: a 10050 is named for what it is, and declined unless its relays are public (GroupDmRelaysJvmTest). */