feat: build the envelope a direct message travels in

A one-to-one message inside a Marmot group is a stock NIP-59 gift wrap
carried as the MLS application payload: a throwaway-keyed kind:1059 around
a sender-signed kind:13 seal around the kind:14 rumor holding the words.
Every member decrypts the MLS layer and sees the wrap; only the recipient
can open it. See docs/marmot-direct-messages.md.

This is the crypto on its own, with no database and no MLS state, because
the outbound path (the notary) and the inbound path (the kind switch in
ChatMessage) both need it and neither can be unit-tested -- there is no
sqlite driver on the JVM test classpath. Extracting it first is what makes
the ten tests here possible; real secp256k1 does load under
testDebugUnitTest, so none of this is mocked.

Three choices worth stating, all of them consequences of the wrap using a
throwaway key rather than the sender's own:

Nothing in the wrap names the sender. GiftWrapEvent.create mints and
discards its own random key, so who sent a message comes from the MLS
frame around it -- authenticated to a leaf, and unforgeable -- rather than
from a self-asserted pubkey field. The seal inside is the only layer the
sender signs, which is what the inbound path will bind to the MLS sender
identity before it renders a word.

The sender cannot reopen their own message. The throwaway key is gone at
send time and nothing reconstructs it. `the sender cannot reopen their own
message` asserts that rather than leaving it to be discovered, because the
obvious fix -- persisting the throwaway private key -- would be strictly
worse than the identity-keyed wrap this was chosen over, and would
reintroduce the attribution the throwaway key exists to remove.

No layer is fuzzed. NIP-59 randomises the wrap and the seal by up to two
days to frustrate correlation at a relay, and both GiftWrapEvent.create
and SealedRumorEvent.create default to it. There is no relay at this layer
and the kind:445 already carries the true time, so fuzzing would only
scatter the "sent a private message" line up to two days out of position
in every other member's transcript.

open() returns null rather than throwing on every way a wrap can fail to
open -- somebody else's message, a malformed payload, a layer that is not
the kind it claims. Its caller is midway through processing a kind:445
that may carry a perfectly good message for somebody else, and an
exception would abandon all of it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso Ngako
2026-09-05 18:57:11 +02:00
parent 907dba3c3b
commit 79e99ae702
2 changed files with 349 additions and 0 deletions

View File

@@ -0,0 +1,164 @@
package press.mantra.compose.nostr
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.Kind
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
import com.vitorpamplona.quartz.nip44Encryption.Nip44
import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler
import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealedRumorEvent
import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
/**
* A one-to-one message carried inside a Marmot group, as the application payload of a
* kind:445 group event. See docs/marmot-direct-messages.md.
*
* The payload is a stock NIP-59 gift wrap: a throwaway-keyed kind:1059 around a
* sender-signed kind:13 seal around the kind:14 rumor that holds the words. Every member
* of the group decrypts the MLS layer and sees the wrap; only the recipient can open it.
*
* Everything here is a pure function of its arguments, with no database and no MLS state,
* which is what makes it testable — Room-backed code cannot be unit-tested in this project.
*
* **Nothing built here may ever be broadcast.** It is a genuine, correctly signed NIP-59
* gift wrap, indistinguishable from one the NIP-17 path would be right to publish, so the
* only thing keeping it off a relay is the tables it is kept out of: a Marmot direct
* message lives in `MarmotInnerEvent`, never in `GiftWrapPayload` or `GiftWrapMessage`.
*/
object MarmotDirectMessage {
/**
* A wrap that opened, both layers of it.
*
* The seal is returned alongside the rumor because it is the only layer that names
* the sender, and the caller has to bind it to the MLS sender identity before it
* believes a word — see [MarmotDirectMessage] and the inbound path.
*/
data class Opened(
val seal: Event,
val rumor: Event,
)
/**
* Builds the payload for a direct message to [recipientPublicKey].
*
* [createdAt] is used unfuzzed on all three layers. NIP-59 randomises the wrap and
* the seal by up to two days to frustrate correlation at a relay, and both
* `GiftWrapEvent.create` and `SealedRumorEvent.create` default to that; there is no
* relay at this layer, the kind:445 around it already carries the true time, and
* fuzzing would only scatter the "sent a private message" line up to two days out of
* position in every other member's transcript.
*
* The rumor is assembled from exactly the fields the caller queued, so its id is the
* one the recipient computes after unwrapping — and, on the way out, the one the
* outbound path uses to find the chat message to link and broadcast.
*/
fun wrap(
signer: NostrSignerSync,
recipientPublicKey: HexKey,
kind: Kind,
createdAt: Long,
tags: Array<Array<String>>,
content: String,
recipientRelayHint: NormalizedRelayUrl? = null,
): GiftWrapEvent {
val rumor = rumor(signer.pubKey, kind, createdAt, tags, content)
// The only layer that names the sender, and the only one they sign. Everything
// the recipient believes about who wrote this rests on this signature.
//
// Built by hand rather than through SealedRumorEvent.create, which is suspend,
// takes a NostrSigner rather than the sync signer the outbound path holds, and
// defaults createdAt to the two-day fuzz.
val seal =
signer.signNormal<SealedRumorEvent>(
createdAt = createdAt,
kind = SealedRumorEvent.KIND,
tags = emptyArray(),
content = signer.nip44Encrypt(rumor.toJson(), recipientPublicKey),
)
// create() mints and discards its own random key -- "GiftWrap is always a random
// key" -- which is the point: nothing in the wrap names the sender. Who sent it
// comes from the MLS frame instead, which is authenticated and cannot be forged.
return GiftWrapEvent.create(
event = seal,
recipientPubKey = recipientPublicKey,
createdAt = createdAt,
recipientRelayHint = recipientRelayHint,
)
}
/**
* The rumor a direct message carries, unsigned and unencrypted.
*
* Exposed so the outbound queue can compute a row id before it has a signer, and so
* tests can assert that the id the recipient arrives at is the id the sender queued.
*/
fun rumor(
senderPublicKey: HexKey,
kind: Kind,
createdAt: Long,
tags: Array<Array<String>>,
content: String,
): Event =
RumorAssembler.assembleRumor<Event>(
pubKey = senderPublicKey,
ev =
EventTemplate(
createdAt = createdAt,
kind = kind,
tags = tags,
content = content,
),
)
/**
* Opens [wrap] with [me]'s key, or returns null if it was not addressed to them.
*
* Trying is the test: the `p` tag is a routing hint, not the authority, and the wrap
* either decrypts with our key or it does not. Null covers every way that can fail --
* somebody else's message, a malformed payload, a layer that is not the kind it
* claims -- because the caller is inside inbound processing for a kind:445 that may
* carry a perfectly good message for somebody, and a throw would abandon all of it.
*
* **The sender cannot open their own wrap.** The throwaway key is discarded at send
* time and nothing can reconstruct it, so a sender's own message returns null here
* too. That is a property, not a defect: see docs/marmot-direct-messages.md. Do not
* "fix" it by storing the throwaway private key.
*/
fun open(
wrap: Event,
me: KeyPair,
): Opened? {
if (wrap.kind != GiftWrapEvent.KIND) return null
val privateKey = me.privKey ?: return null
val seal = decryptEvent(wrap.content, privateKey, wrap.pubKey) ?: return null
if (seal.kind != SealedRumorEvent.KIND) return null
val rumor = decryptEvent(seal.content, privateKey, seal.pubKey) ?: return null
return Opened(seal = seal, rumor = rumor)
}
private fun decryptEvent(
ciphertext: String,
privateKey: ByteArray,
fromPublicKey: HexKey,
): Event? =
try {
Event.fromJsonOrNull(
Nip44.decrypt(
payload = ciphertext,
privateKey = privateKey,
pubKey = fromPublicKey.hexToByteArray(),
),
)
} catch (_: Exception) {
null
}
}