feat: every NIP-17 payload is stamped with its expiry (disappearing-messages, Phase 3)

sendChatMessage and the DKG, signing, confederation-ceremony and Welcome
producers stamp the rumor's expiry before hashing its id. The wrap asks
relays to drop it by quartz's formula; the seal stays untagged; a
payload that expired before it could be sent is not sealed; the rumor's
plaintext is no longer logged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-22 23:14:07 +02:00
1 parent b7f6df0c3b
commit ae0468bb2f
7 files changed
+246 -28

No files matched your search

@@ -1,5 +1,6 @@
package mobi.giza.compose.database.dao
import mobi.giza.compose.database.repository.DisappearingSettingsStore
import androidx.room3.Dao
import androidx.room3.Transaction
import co.touchlab.kermit.Logger
@@ -1273,11 +1274,17 @@ abstract class MarmotOutboundDao(
// the room's address, not its id.
nostrGroupId = database.marmotRoutingDao().activeRoutingIdFor(chatRoomId),
)
// A Welcome travels as a NIP-17 wrap, and expires like one: after at least the
// ceremony floor, since the invitee may not open the app for days
// (docs/disappearing-messages.md, D2). Stamped before the id is hashed.
val welcomeTags = DisappearingSettingsStore(database).stamp(
chatRoomId, userPublicKey, welcomeEvent.kind, welcomeEvent.createdAt, welcomeEvent.tags,
)
// Compute welcomeEventId
val welcomeEventId = EventHasher.hashId(
pubKey = userPublicKey,
kind = welcomeEvent.kind,
tags = welcomeEvent.tags,
tags = welcomeTags,
createdAt = welcomeEvent.createdAt,
content = welcomeEvent.content
)
@@ -1291,7 +1298,7 @@ abstract class MarmotOutboundDao(
publicKey = userPublicKey,
chatRoomId = chatRoomId,
kind = welcomeEvent.kind,
tags = welcomeEvent.tags,
tags = welcomeTags,
content = welcomeEvent.content,
createdAt = Instant.fromEpochSeconds(welcomeEvent.createdAt)
)
@@ -252,7 +252,11 @@ abstract class NostrNip17Dao(
publicKey = giftWrapEvent.pubKey,
kind = giftWrapEvent.kind,
receiverPublicKey = receiverPublicKey.pubKey,
receiverRelayHit = receiverPublicKey.relayHint?.url
receiverRelayHit = receiverPublicKey.relayHint?.url,
// Linked to what it carries, so the sweeper deletes this wrap with its payload and
// never before it; dropped here when the payload is (docs/disappearing-messages.md, D6).
giftWrapPayloadId = giftWrapPayload.id,
expiresAt = giftWrapPayload.expiresAt,
)
)
@@ -1,5 +1,6 @@
package mobi.giza.compose.database.repository
import mobi.giza.compose.nostr.DisappearingMessages
import mobi.giza.compose.nostr.GroupPost
import mobi.giza.compose.nostr.GroupNostrProfile
import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent
@@ -665,25 +666,33 @@ class DatabaseChatRepository(
}
val createdAt = Clock.System.now().epochSeconds
// The expiry is one of the rumor's tags, so it goes on before the id is hashed: the
// payload id is the id the recipient arrives at. docs/disappearing-messages.md, D4.
val tags = DisappearingSettingsStore(database).stamp(
chatRoomId = localChatRoom.chatRoom.id,
userPublicKey = localChatRoom.chatRoom.userPublicKey,
kind = messageType,
createdAt = createdAt,
tags = receiverTags.toTypedArray(),
)
val giftWrapPayloadId = EventHasher.hashId(
pubKey = localChatRoom.chatRoom.userPublicKey,
createdAt = createdAt,
tags = receiverTags.toTypedArray(),
tags = tags,
content = text,
kind = messageType
)
database.giftWrapPayloadDao().upsert(
GiftWrapPayload(
id = giftWrapPayloadId,
kind = messageType,
tags = receiverTags.toTypedArray(),
createdAt = Instant.fromEpochSeconds(createdAt),
content = text,
chatRoomId = localChatRoom.chatRoom.id,
publicKey = localChatRoom.chatRoom.userPublicKey
)
val payload = GiftWrapPayload(
id = giftWrapPayloadId,
kind = messageType,
tags = tags,
createdAt = Instant.fromEpochSeconds(createdAt),
content = text,
chatRoomId = localChatRoom.chatRoom.id,
publicKey = localChatRoom.chatRoom.userPublicKey
)
database.giftWrapPayloadDao().upsert(payload)
database.chatMessageDao().upsert(
ChatMessage(
@@ -693,7 +702,8 @@ class DatabaseChatRepository(
isUserMessage = true,
giftWrapPayloadId = giftWrapPayloadId,
marmotGroupEventId = null,
marmotInnerEventId = null
marmotInnerEventId = null,
expiresAt = payload.expiresAt,
)
)
}
@@ -743,6 +753,16 @@ class DatabaseChatRepository(
}
}
// Sending it late would publish something its own tag says should already be gone: a
// relay is meant to drop it on arrival and a recipient to ignore it. It stays unsealed and
// the sweeper deletes it -- a person's message at once, a ceremony's round once its
// session has finished with it. docs/disappearing-messages.md, Phase 3.
val rumorExpiry = DisappearingMessages.expirationOf(giftWrapPayload.tags, giftWrapPayload.createdAt.epochSeconds)
if (rumorExpiry != null && DisappearingMessages.isExpired(rumorExpiry, Clock.System.now().epochSeconds)) {
logger.w("Not sealing payload ${giftWrapPayload.id}: it expired before it could be sent")
return
}
database.participantDao().findParticipantsByChatRoomId(giftWrapPayload.chatRoomId).forEach { participant ->
if (giftWrapPayload.kind == WelcomeEvent.KIND) {
logger.i("Only giftWrap welcomeEvent payload (${giftWrapPayload.id}) to the participant who published the related keyPackage")
@@ -787,11 +807,14 @@ class DatabaseChatRepository(
content = giftWrapPayload.content
)
)
logger.d("GiftWrap Payload Rumor: ${giftWrapPayloadRumor.toJson()}")
logger.d("Seal to $participant")
// The rumor is the plaintext of somebody's words, so it is not logged: a log line would
// outlive the message (docs/disappearing-messages.md, Phase 0, check 7).
logger.d("Seal ${giftWrapPayload.id} to ${participant.participantPublicKey}")
val payload = giftWrapPayloadRumor.toJson()
// The seal stays untagged, as NIP-59 says it MUST: Giza's group-seal refusals reject
// a tagged one, and quartz's `mergeWith` would append its tag to every rumor it opens
// (docs/disappearing-messages.md, D5).
val sealedRumorEvent = nostrSignerSync.signNormal<SealEvent>(
createdAt = TimeUtils.randomWithTwoDays(),
kind = SealEvent.KIND,
@@ -801,14 +824,20 @@ class DatabaseChatRepository(
toPublicKey = participant.participantPublicKey
)
)
logger.d("SealEvent: ${sealedRumorEvent.toJson()}")
logger.d("SealEvent: ${sealedRumorEvent.id}")
// The wrap asks relays to drop it, by quartz's formula: its own randomized
// `created_at` plus the rumor's lifetime plus two days, which lands after the rumor's
// expiry and never gives away when the rumor was written (D5).
val wrapCreatedAt = TimeUtils.randomWithTwoDays()
val wrapExpiry = DisappearingMessages.wrapExpiration(rumorExpiry, giftWrapPayload.createdAt.epochSeconds, wrapCreatedAt)
val giftWrapEvent = wrapperSigner.signNormal<GiftWrapEvent>(
createdAt = TimeUtils.randomWithTwoDays(),
createdAt = wrapCreatedAt,
kind = GiftWrapEvent.KIND,
tags = arrayOf(
PTag.assemble(participant.participantPublicKey, participant.relayHint?.let { NormalizedRelayUrl(it) })
),
tags = listOfNotNull(
PTag.assemble(participant.participantPublicKey, participant.relayHint?.let { NormalizedRelayUrl(it) }),
wrapExpiry?.let { arrayOf(DisappearingMessages.TAG, it.toString()) },
).toTypedArray(),
content = wrapperSigner.nip44Encrypt(
plaintext = sealedRumorEvent.toJson(),
toPublicKey = participant.participantPublicKey
@@ -1,5 +1,6 @@
package mobi.giza.compose.managers
import mobi.giza.compose.database.repository.DisappearingSettingsStore
import mobi.giza.compose.database.model.isGuardedSubgroup
import co.touchlab.kermit.Logger
@@ -1519,7 +1520,7 @@ object ChillDkgRitualManager {
)
}
val tags = receiverTags.toTypedArray() + DkgRitualEvents.assembleTags(
val baseTags = receiverTags.toTypedArray() + DkgRitualEvents.assembleTags(
sessionId = session.id,
threshold = if (includeThreshold) session.threshold else null,
parentChatRoomId = if (includeParent) session.parentChatRoomId else null,
@@ -1528,6 +1529,15 @@ object ChillDkgRitualManager {
val createdAt = Clock.System.now().epochSeconds
// A NIP-17 round expires like everything else in a wrap, after at least the ceremony
// floor (docs/disappearing-messages.md, D2). The tag is part of the rumor, so it goes on
// before the id is hashed. A Marmot room's rounds follow the group's own retention.
val tags = if (localChatRoom.chatRoom.mlsGroupState == null) {
DisappearingSettingsStore(database).stamp(localChatRoom.chatRoom.id, session.userPublicKey, kind, createdAt, baseTags)
} else {
baseTags
}
// The rumor id the outbound pipeline will recompute from these same
// fields when it assembles the event to encrypt, on either transport.
val id = EventHasher.hashId(
@@ -1,5 +1,6 @@
package mobi.giza.compose.managers
import mobi.giza.compose.database.repository.DisappearingSettingsStore
import co.touchlab.kermit.Logger
import com.vitorpamplona.crypto.random.RandomInstance
import com.vitorpamplona.quartz.nip01Core.core.Event
@@ -577,12 +578,15 @@ object ConfederationRitualManager {
) {
val people = plan?.people
?: (localChatRoom.localParticipants.map { it.participant.participantPublicKey } + localChatRoom.chatRoom.userPublicKey)
val tags = people.filter { it != ceremony.userPublicKey }.sorted().map { arrayOf("p", it) }.toTypedArray() + arrayOf(
val baseTags = people.filter { it != ceremony.userPublicKey }.sorted().map { arrayOf("p", it) }.toTypedArray() + arrayOf(
ConfederationRitualEvents.sessionTag(ceremony.id),
arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, ceremony.proposalId),
arrayOf(ConfederationRitualEvents.ATTEMPT_TAG, ceremony.attempt.toString()),
)
val createdAt = Clock.System.now().epochSeconds
// Expires after at least the ceremony floor, stamped before the id is hashed
// (docs/disappearing-messages.md, D2).
val tags = DisappearingSettingsStore(database).stamp(localChatRoom.chatRoom.id, ceremony.userPublicKey, kind, createdAt, baseTags)
val id = EventHasher.hashId(pubKey = ceremony.userPublicKey, createdAt = createdAt, kind = kind, tags = tags, content = content)
database.giftWrapPayloadDao().upsert(
GiftWrapPayload(
@@ -1,5 +1,6 @@
package mobi.giza.compose.managers
import mobi.giza.compose.database.repository.DisappearingSettingsStore
import co.touchlab.kermit.Logger
import com.vitorpamplona.crypto.random.RandomInstance
import com.vitorpamplona.quartz.nip01Core.core.Event
@@ -3168,11 +3169,21 @@ object FrostSigningManager {
// the store is stepped past rather than written over. One second of drift
// per collision is nothing a protocol message reads, and no caller
// publishes faster than [MAX_ID_SEARCH] identical messages a second.
//
// On the NIP-17 transport the rumor also carries its expiry, after at least the signing
// floor (docs/disappearing-messages.md, D2). It is worked out from `created_at`, so it is
// stamped again each time the search steps the second on. A Marmot room's messages
// follow the group's own retention instead.
val store = DisappearingSettingsStore(database)
suspend fun stamped(at: Long): Array<Array<String>> =
if (isMarmotRoom) tags else store.stamp(localChatRoom.chatRoom.id, session.userPublicKey, kind, at, tags)
var createdAt = Clock.System.now().epochSeconds
var rumorTags = stamped(createdAt)
var id = EventHasher.hashId(
pubKey = session.userPublicKey,
createdAt = createdAt,
tags = tags,
tags = rumorTags,
content = content,
kind = kind
)
@@ -3180,10 +3191,11 @@ object FrostSigningManager {
while (attempts < MAX_ID_SEARCH && isQueued(database, isMarmotRoom, id)) {
createdAt += 1
rumorTags = stamped(createdAt)
id = EventHasher.hashId(
pubKey = session.userPublicKey,
createdAt = createdAt,
tags = tags,
tags = rumorTags,
content = content,
kind = kind
)
@@ -3220,7 +3232,7 @@ object FrostSigningManager {
publicKey = session.userPublicKey,
kind = kind,
createdAt = Instant.fromEpochSeconds(createdAt),
tags = tags,
tags = rumorTags,
content = content,
chatRoomId = localChatRoom.chatRoom.id
)
@@ -0,0 +1,152 @@
package mobi.giza.compose.database.repository
import androidx.room3.Room
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
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 kotlin.time.Clock
import kotlin.time.Instant
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.GiftWrapPayload
import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.database.model.Profile
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.nostr.DisappearingMessages
import mobi.giza.compose.nostr.DisappearingMessages.DAY
import mobi.giza.compose.nostr.frost.FrostSigningEvents
/**
* docs/disappearing-messages.md, Phase 3: what a NIP-17 send writes, and what the wrap carries.
*
* Real keys throughout: the room id is derived over the members by secp256k1 point work, and the
* seal is opened again as the recipient to see the rumor they would see.
*/
class DisappearingSendJvmTest {
private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>())
@AfterTest
fun closeDb() = db.close()
private val userKeys = KeyPair()
private val aliceKeys = KeyPair()
private val user = userKeys.pubKey.toHexKey()
private val alice = aliceKeys.pubKey.toHexKey()
private val repository = DatabaseChatRepository(database = db, scope = CoroutineScope(Dispatchers.Unconfined))
private val store = DisappearingSettingsStore(db)
private suspend fun seedProfile(publicKey: String) {
val nostrEventId = publicKey.take(63) + "f"
db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
db.profileDao().upsert(Profile(publicKey = publicKey, userName = "member", nostrEventId = nostrEventId))
}
private suspend fun room(): LocalChatRoom {
seedProfile(user)
seedProfile(alice)
return assertNotNull(db.nostrNip17Dao().createNip17ChatRoom(user, listOf(alice)))
}
private suspend fun onlyPayload(room: LocalChatRoom): GiftWrapPayload =
db.giftWrapPayloadDao().getByChatRoomAndKinds(room.chatRoom.id, listOf(14)).single()
@Test
fun `a message is stamped a day out by default, and its id covers the tag`() = runBlocking {
val room = room()
repository.sendChatMessage(text = "hello", localChatRoom = room)
val payload = onlyPayload(room)
val expiry = assertNotNull(DisappearingMessages.expirationOf(payload.tags, payload.createdAt.epochSeconds))
assertEquals(payload.createdAt.epochSeconds + DAY, expiry)
assertEquals(Instant.fromEpochSeconds(expiry), payload.expiresAt)
assertEquals(
EventHasher.hashId(user, payload.createdAt.epochSeconds, payload.kind, payload.tags, payload.content),
payload.id,
"the payload id is not the id of the rumor the recipient will see",
)
val line = assertNotNull(db.chatMessageDao().getChatMessagesByGiftWrapPayloadId(payload.id))
assertEquals(payload.expiresAt, line.expiresAt)
}
@Test
fun `the conversation's override wins, and Off stamps nothing`() = runBlocking {
val room = room()
store.saveDefault(user, DisappearingMessages.HOUR)
store.saveOverride(room.chatRoom.id, DisappearingMessages.OFF)
repository.sendChatMessage(text = "kept", localChatRoom = room)
val payload = onlyPayload(room)
assertNull(DisappearingMessages.expirationOf(payload.tags))
assertNull(payload.expiresAt)
assertNull(assertNotNull(db.chatMessageDao().getChatMessagesByGiftWrapPayloadId(payload.id)).expiresAt)
}
@Test
fun `a protocol round expires at its floor even with the policy Off`() = runBlocking {
val room = room()
store.saveDefault(user, DisappearingMessages.OFF)
val createdAt = 1_800_000_000L
val tags = store.stamp(room.chatRoom.id, user, FrostSigningEvents.NONCE, createdAt, arrayOf(arrayOf("p", alice)))
assertEquals(createdAt + DisappearingMessages.SIGNING_FLOOR, DisappearingMessages.expirationOf(tags, createdAt))
}
@Test
fun `every wrap asks relays to drop it after the rumor, and every seal stays untagged`() = runBlocking {
val room = room()
repository.sendChatMessage(text = "hello", localChatRoom = room)
val payload = onlyPayload(room)
val rumorExpiry = assertNotNull(payload.expiresAt).epochSeconds
repository.sealGiftWrapPayload(payload, NostrSignerSync(userKeys))
val seals = db.giftWrapSealDao().getAllGiftWrapSeals()
assertEquals(2, seals.size, "one seal for alice and one for the sender's own copy")
seals.forEach { seal ->
assertTrue(seal.tags.isEmpty(), "a seal was tagged: ${seal.tags.map { it.toList() }}")
val wrap = assertNotNull(db.nostrEventDao().getNostrEventById(assertNotNull(seal.giftWrapMessageId)))
val wrapExpiry = assertNotNull(DisappearingMessages.expirationOf(wrap.tags), "a wrap carries no expiration")
assertTrue(wrapExpiry >= rumorExpiry, "the wrap would be dropped before the rumor expires")
assertTrue(wrapExpiry <= rumorExpiry + 2 * DAY, "the wrap outlives the rumor by more than two days")
}
// What alice reads: the rumor, carrying the sender's expiry and nothing merged in from the seal.
val opened = seals.firstNotNullOfOrNull { it.decryptGiftWrapPayload(aliceKeys.privKey!!) }
val rumor = assertNotNull(opened, "alice could not open her seal")
assertEquals(1, rumor.tags.count { it[0] == DisappearingMessages.TAG })
assertEquals(Instant.fromEpochSeconds(rumorExpiry), rumor.expiresAt)
}
@Test
fun `a message that expired before it could be sent is not sealed`() = runBlocking {
val room = room()
val createdAt = Clock.System.now().epochSeconds - 2 * DAY
val tags = arrayOf(arrayOf("p", alice), arrayOf(DisappearingMessages.TAG, (createdAt + DAY).toString()))
val payload = GiftWrapPayload(
id = EventHasher.hashId(user, createdAt, 14, tags, "late"),
publicKey = user,
chatRoomId = room.chatRoom.id,
kind = 14,
tags = tags,
content = "late",
createdAt = Instant.fromEpochSeconds(createdAt),
)
db.giftWrapPayloadDao().upsert(payload)
repository.sealGiftWrapPayload(payload, NostrSignerSync(userKeys))
assertEquals(0, db.giftWrapSealDao().getAllGiftWrapSeals().size, "an expired message was sealed for relays")
assertNull(assertNotNull(db.giftWrapPayloadDao().getById(payload.id)).giftWrapSealId)
}
}