mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-26 14:05:22 +00:00
Relabel private Nostr envelopes honestly
This commit is contained in:
@@ -265,10 +265,10 @@ final class PrivateConversationModel: ObservableObject {
|
||||
let headerPeerID = chatViewModel.getShortIDForNoiseKey(conversationPeerID)
|
||||
let peer = chatViewModel.getPeer(byID: headerPeerID)
|
||||
let displayName = resolveDisplayName(for: conversationPeerID, headerPeerID: headerPeerID, peer: peer)
|
||||
// Geo DMs are always routed over Nostr (NIP-17); their nostr_ keys
|
||||
// never resolve to a reachable mesh peer, so resolveAvailability would
|
||||
// report .offline. Report .nostrAvailable so the header shows the
|
||||
// globe instead of a misleading "offline" tag.
|
||||
// Geo DMs are always routed through BitChat private envelopes over
|
||||
// Nostr; their nostr_ keys never resolve to a reachable mesh peer, so
|
||||
// resolveAvailability would report .offline. Report .nostrAvailable
|
||||
// so the header shows the globe instead of a misleading "offline" tag.
|
||||
let availability = conversationPeerID.isGeoDM
|
||||
? .nostrAvailable
|
||||
: resolveAvailability(for: headerPeerID, peer: peer)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import Foundation
|
||||
import P256K
|
||||
|
||||
/// Manages Nostr identity (secp256k1 keypair) for NIP-17 private messaging
|
||||
/// Manages the secp256k1 identity used by BitChat's Nostr relay features,
|
||||
/// including the proprietary private-envelope transport.
|
||||
struct NostrIdentity: Codable {
|
||||
let privateKey: Data
|
||||
let publicKey: Data
|
||||
|
||||
+404
-230
@@ -1,4 +1,3 @@
|
||||
import BitLogger
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import P256K
|
||||
@@ -7,16 +6,30 @@ import Security
|
||||
// Note: This file depends on Data extension from BinaryEncodingUtils.swift
|
||||
// Make sure BinaryEncodingUtils.swift is included in the target
|
||||
|
||||
/// NIP-17 Protocol Implementation for Private Direct Messages
|
||||
/// BitChat's private-envelope protocol transported over Nostr relays.
|
||||
///
|
||||
/// This is deliberately BitChat-specific and is not NIP-17, NIP-44, or NIP-59.
|
||||
/// It uses Nostr events and secp256k1 identities, but its XChaCha20-Poly1305
|
||||
/// payload layout is proprietary and interoperates only with BitChat clients.
|
||||
struct NostrProtocol {
|
||||
|
||||
/// Nostr event kinds
|
||||
enum EventKind: Int {
|
||||
case metadata = 0
|
||||
case textNote = 1
|
||||
case dm = 14 // NIP-17 DM rumor kind
|
||||
case seal = 13 // NIP-17 sealed event
|
||||
case giftWrap = 1059 // NIP-59 gift wrap
|
||||
// Bounded compatibility for BitChat releases that incorrectly emitted
|
||||
// the proprietary payload under standard NIP kinds. Only kind 1059 is
|
||||
// temporarily published during migration; all three remain readable.
|
||||
case legacyNIP59Seal = 13
|
||||
case legacyNIP17DirectMessage = 14
|
||||
case legacyNIP59GiftWrap = 1059
|
||||
// Provisional BitChat-specific regular event kinds. These are not
|
||||
// formally reserved by the Nostr kind registry. Only
|
||||
// `privateEnvelope` is published; message and seal exist solely
|
||||
// inside ciphertext.
|
||||
case privateEnvelope = 1402
|
||||
case privateSeal = 1403
|
||||
case privateMessage = 1404
|
||||
case ephemeralEvent = 20000
|
||||
case geohashPresence = 20001
|
||||
case deletion = 5 // NIP-09 event deletion request
|
||||
@@ -25,145 +38,272 @@ struct NostrProtocol {
|
||||
/// its NIP-40 expiration — the whole point is store-and-forward.
|
||||
case courierDrop = 1401
|
||||
}
|
||||
|
||||
/// Prefix for BitChat private-envelope ciphertext. The suffix is
|
||||
/// base64url(nonce24 || ciphertext || poly1305Tag).
|
||||
static let privateEnvelopeContentPrefix = "bitchat-pm-v1:"
|
||||
|
||||
/// Bound work before Base64 decoding either encrypted layer. Current
|
||||
/// private messages are normally only a few KiB; 64 KiB leaves ample
|
||||
/// migration headroom without allowing an addressed relay event to drive
|
||||
/// unbounded allocation.
|
||||
static let maximumPrivateEnvelopeCiphertextBytes = 64 * 1024
|
||||
|
||||
/// Bound the inner authenticated message JSON before allocation/parsing.
|
||||
static let maximumPrivateEnvelopePlaintextBytes = 32 * 1024
|
||||
|
||||
/// The outer authenticated seal JSON contains a Base64-encoded encrypted
|
||||
/// copy of the inner JSON, so it needs expansion headroom of its own. Keep
|
||||
/// the layer-specific cap below the public ciphertext ceiling.
|
||||
private static let maximumPrivateEnvelopeSealPlaintextBytes = 48 * 1024
|
||||
|
||||
/// Compatibility-only publication stops at this instant. New-format kind
|
||||
/// 1402 remains first/primary throughout the window; the legacy kind-1059
|
||||
/// copy exists solely so pre-migration BitChat clients can receive it.
|
||||
static let legacyPrivateEnvelopePublicationDeadline = Date(
|
||||
timeIntervalSince1970: 1_792_022_400 // 2026-10-15T00:00:00Z
|
||||
)
|
||||
|
||||
/// New clients subscribe to the provisional BitChat-specific kind and the
|
||||
/// compatibility-only legacy kind so both sides of a rolling rollout can
|
||||
/// recover stored messages.
|
||||
static let acceptedPrivateEnvelopeKinds = [
|
||||
EventKind.privateEnvelope.rawValue,
|
||||
EventKind.legacyNIP59GiftWrap.rawValue
|
||||
]
|
||||
|
||||
private enum PrivateEnvelopeWireFormat {
|
||||
case bitchatV1
|
||||
case legacyMislabelledV2
|
||||
|
||||
init?(outerKind: Int) {
|
||||
switch outerKind {
|
||||
case EventKind.privateEnvelope.rawValue:
|
||||
self = .bitchatV1
|
||||
case EventKind.legacyNIP59GiftWrap.rawValue:
|
||||
self = .legacyMislabelledV2
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
var messageKind: EventKind {
|
||||
switch self {
|
||||
case .bitchatV1: .privateMessage
|
||||
case .legacyMislabelledV2: .legacyNIP17DirectMessage
|
||||
}
|
||||
}
|
||||
|
||||
var sealKind: EventKind {
|
||||
switch self {
|
||||
case .bitchatV1: .privateSeal
|
||||
case .legacyMislabelledV2: .legacyNIP59Seal
|
||||
}
|
||||
}
|
||||
|
||||
var envelopeKind: EventKind {
|
||||
switch self {
|
||||
case .bitchatV1: .privateEnvelope
|
||||
case .legacyMislabelledV2: .legacyNIP59GiftWrap
|
||||
}
|
||||
}
|
||||
|
||||
var contentPrefix: String {
|
||||
switch self {
|
||||
case .bitchatV1: NostrProtocol.privateEnvelopeContentPrefix
|
||||
case .legacyMislabelledV2: "v2:"
|
||||
}
|
||||
}
|
||||
|
||||
var hkdfSalt: Data {
|
||||
switch self {
|
||||
case .bitchatV1: Data("bitchat-private-envelope-v1".utf8)
|
||||
case .legacyMislabelledV2: Data()
|
||||
}
|
||||
}
|
||||
|
||||
var hkdfInfo: Data {
|
||||
switch self {
|
||||
case .bitchatV1: Data()
|
||||
case .legacyMislabelledV2: Data("nip44-v2".utf8)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a NIP-17 private message
|
||||
static func createPrivateMessage(
|
||||
/// Create a BitChat private envelope for relay transport.
|
||||
static func createPrivateEnvelope(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity
|
||||
) throws -> NostrEvent {
|
||||
|
||||
// Creating private message
|
||||
|
||||
// 1. Create the rumor (unsigned event)
|
||||
let rumor = NostrEvent(
|
||||
try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity,
|
||||
format: .bitchatV1
|
||||
)
|
||||
}
|
||||
|
||||
/// Events to publish for one logical private payload. The primary
|
||||
/// BitChat-specific format is always first. Until the explicit migration
|
||||
/// deadline, a legacy copy follows for clients that still subscribe only
|
||||
/// to kind 1059. Both encrypt the exact same embedded BitChat payload, so
|
||||
/// receive-side logical-payload dedup collapses the pair.
|
||||
static func createPrivateEnvelopePublicationBatch(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity,
|
||||
now: Date = Date()
|
||||
) throws -> [NostrEvent] {
|
||||
let primary = try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity
|
||||
)
|
||||
guard now < legacyPrivateEnvelopePublicationDeadline else {
|
||||
return [primary]
|
||||
}
|
||||
let compatibilityCopy = try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity,
|
||||
format: .legacyMislabelledV2
|
||||
)
|
||||
return [primary, compatibilityCopy]
|
||||
}
|
||||
|
||||
private static func createPrivateEnvelope(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity,
|
||||
format: PrivateEnvelopeWireFormat
|
||||
) throws -> NostrEvent {
|
||||
// 1. Create the unsigned inner BitChat message.
|
||||
let message = NostrEvent(
|
||||
pubkey: senderIdentity.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .dm, // NIP-17: DM rumor kind 14
|
||||
kind: format.messageKind,
|
||||
tags: [],
|
||||
content: content
|
||||
)
|
||||
|
||||
// 2. Seal the rumor (encrypt to recipient) and sign it with the SENDER'S
|
||||
// real identity key. NIP-17 requires the seal be signed by the sender
|
||||
// so the recipient can authenticate who sent the message; signing with
|
||||
// a throwaway key leaves DMs forgeable/impersonatable.
|
||||
// 2. Encrypt the message to the recipient and sign the private seal
|
||||
// with the sender's stable Nostr identity for sender authentication.
|
||||
let senderKey = try senderIdentity.schnorrSigningKey()
|
||||
let sealedEvent = try createSeal(
|
||||
rumor: rumor,
|
||||
let sealedEvent = try createPrivateSeal(
|
||||
message: message,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: senderKey
|
||||
senderKey: senderKey,
|
||||
format: format
|
||||
)
|
||||
|
||||
// 3. Gift wrap the sealed event with a throwaway ephemeral key (the wrap
|
||||
// layer hides the sender's identity from relays; createGiftWrap mints
|
||||
// its own ephemeral key internally).
|
||||
let giftWrap = try createGiftWrap(
|
||||
// 3. Encrypt the seal under a one-time key so the public envelope does
|
||||
// not reveal the stable sender identity.
|
||||
return try createPrivateEnvelopeEvent(
|
||||
seal: sealedEvent,
|
||||
recipientPubkey: recipientPubkey
|
||||
recipientPubkey: recipientPubkey,
|
||||
format: format
|
||||
)
|
||||
|
||||
// Created gift wrap
|
||||
|
||||
return giftWrap
|
||||
}
|
||||
|
||||
/// Decrypt a received NIP-17 message
|
||||
/// Returns the content, sender pubkey, and the actual message timestamp (not the randomized gift wrap timestamp)
|
||||
static func decryptPrivateMessage(
|
||||
giftWrap: NostrEvent,
|
||||
/// Decrypt a BitChat private envelope. Legacy proprietary envelopes that
|
||||
/// older BitChat releases placed under kinds 1059/13/14 are accepted only
|
||||
/// through the format-isolated receive path.
|
||||
static func decryptPrivateEnvelope(
|
||||
envelope: NostrEvent,
|
||||
recipientIdentity: NostrIdentity
|
||||
) throws -> (content: String, senderPubkey: String, timestamp: Int) {
|
||||
|
||||
// Starting decryption
|
||||
|
||||
// 1. Unwrap the gift wrap
|
||||
let seal: NostrEvent
|
||||
do {
|
||||
seal = try unwrapGiftWrap(
|
||||
giftWrap: giftWrap,
|
||||
recipientKey: recipientIdentity.schnorrSigningKey()
|
||||
)
|
||||
// Successfully unwrapped gift wrap
|
||||
} catch {
|
||||
SecureLogger.error("❌ Failed to unwrap gift wrap: \(error)", category: .session)
|
||||
throw error
|
||||
}
|
||||
|
||||
// 2. Authenticate the seal. The seal MUST be signed by the sender's real
|
||||
// identity key (NIP-17); without this check a DM is forgeable by anyone
|
||||
// who knows the recipient's npub. Verify the seal's own signature.
|
||||
guard seal.isValidSignature() else {
|
||||
SecureLogger.error("❌ Rejecting DM: seal signature is missing or invalid", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
// 3. Open the seal
|
||||
let rumor: NostrEvent
|
||||
do {
|
||||
rumor = try openSeal(
|
||||
seal: seal,
|
||||
recipientKey: recipientIdentity.schnorrSigningKey()
|
||||
)
|
||||
// Successfully opened seal
|
||||
} catch {
|
||||
SecureLogger.error("❌ Failed to open seal: \(error)", category: .session)
|
||||
throw error
|
||||
}
|
||||
|
||||
// 4. The sender claimed inside the rumor must match the key that actually
|
||||
// signed the seal, otherwise the sender field is unauthenticated and
|
||||
// spoofable.
|
||||
guard seal.pubkey == rumor.pubkey else {
|
||||
SecureLogger.error("❌ Rejecting DM: rumor pubkey does not match seal signer", category: .session)
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
// Return the seal signer's pubkey as the authenticated sender.
|
||||
return (content: rumor.content, senderPubkey: seal.pubkey, timestamp: rumor.created_at)
|
||||
let layers = try decodePrivateEnvelopeLayers(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipientIdentity
|
||||
)
|
||||
return (
|
||||
content: layers.message.content,
|
||||
senderPubkey: layers.seal.pubkey,
|
||||
timestamp: layers.message.created_at
|
||||
)
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
static func createPrivateMessageWithInvalidSealSignatureForTesting(
|
||||
static func createPrivateEnvelopeWithInvalidSealSignatureForTesting(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity
|
||||
) throws -> NostrEvent {
|
||||
let rumor = NostrEvent(
|
||||
let format = PrivateEnvelopeWireFormat.bitchatV1
|
||||
let message = NostrEvent(
|
||||
pubkey: senderIdentity.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .dm,
|
||||
kind: format.messageKind,
|
||||
tags: [],
|
||||
content: content
|
||||
)
|
||||
var seal = try createSeal(
|
||||
rumor: rumor,
|
||||
var seal = try createPrivateSeal(
|
||||
message: message,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: senderIdentity.schnorrSigningKey()
|
||||
senderKey: senderIdentity.schnorrSigningKey(),
|
||||
format: format
|
||||
)
|
||||
seal.sig = String(repeating: "0", count: 128)
|
||||
return try createGiftWrap(seal: seal, recipientPubkey: recipientPubkey)
|
||||
return try createPrivateEnvelopeEvent(
|
||||
seal: seal,
|
||||
recipientPubkey: recipientPubkey,
|
||||
format: format
|
||||
)
|
||||
}
|
||||
|
||||
static func createPrivateMessageWithMismatchedSealRumorPubkeyForTesting(
|
||||
static func createPrivateEnvelopeWithMismatchedSealMessagePubkeyForTesting(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
rumorIdentity: NostrIdentity,
|
||||
messageIdentity: NostrIdentity,
|
||||
sealSignerIdentity: NostrIdentity
|
||||
) throws -> NostrEvent {
|
||||
let rumor = NostrEvent(
|
||||
pubkey: rumorIdentity.publicKeyHex,
|
||||
let format = PrivateEnvelopeWireFormat.bitchatV1
|
||||
let message = NostrEvent(
|
||||
pubkey: messageIdentity.publicKeyHex,
|
||||
createdAt: Date(),
|
||||
kind: .dm,
|
||||
kind: format.messageKind,
|
||||
tags: [],
|
||||
content: content
|
||||
)
|
||||
let seal = try createSeal(
|
||||
rumor: rumor,
|
||||
let seal = try createPrivateSeal(
|
||||
message: message,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: sealSignerIdentity.schnorrSigningKey()
|
||||
senderKey: sealSignerIdentity.schnorrSigningKey(),
|
||||
format: format
|
||||
)
|
||||
return try createGiftWrap(seal: seal, recipientPubkey: recipientPubkey)
|
||||
return try createPrivateEnvelopeEvent(
|
||||
seal: seal,
|
||||
recipientPubkey: recipientPubkey,
|
||||
format: format
|
||||
)
|
||||
}
|
||||
|
||||
static func createLegacyPrivateEnvelopeForTesting(
|
||||
content: String,
|
||||
recipientPubkey: String,
|
||||
senderIdentity: NostrIdentity
|
||||
) throws -> NostrEvent {
|
||||
try createPrivateEnvelope(
|
||||
content: content,
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderIdentity: senderIdentity,
|
||||
format: .legacyMislabelledV2
|
||||
)
|
||||
}
|
||||
|
||||
static func decodePrivateEnvelopeLayersForTesting(
|
||||
envelope: NostrEvent,
|
||||
recipientIdentity: NostrIdentity
|
||||
) throws -> (seal: NostrEvent, message: NostrEvent) {
|
||||
try decodePrivateEnvelopeLayers(
|
||||
envelope: envelope,
|
||||
recipientIdentity: recipientIdentity
|
||||
)
|
||||
}
|
||||
|
||||
static func decodePrivateEnvelopeEventJSONForTesting(_ json: String) throws -> NostrEvent {
|
||||
try decodePrivateEnvelopeEventJSON(json)
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -400,151 +540,186 @@ struct NostrProtocol {
|
||||
|
||||
// MARK: - Private Methods
|
||||
|
||||
private static func createSeal(
|
||||
rumor: NostrEvent,
|
||||
private static func createPrivateSeal(
|
||||
message: NostrEvent,
|
||||
recipientPubkey: String,
|
||||
senderKey: P256K.Schnorr.PrivateKey
|
||||
senderKey: P256K.Schnorr.PrivateKey,
|
||||
format: PrivateEnvelopeWireFormat
|
||||
) throws -> NostrEvent {
|
||||
|
||||
let rumorJSON = try rumor.jsonString()
|
||||
let encrypted = try encrypt(
|
||||
plaintext: rumorJSON,
|
||||
plaintext: message.jsonString(),
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: senderKey
|
||||
senderKey: senderKey,
|
||||
format: format,
|
||||
maximumPlaintextBytes: maximumPrivateEnvelopePlaintextBytes
|
||||
)
|
||||
|
||||
|
||||
let seal = NostrEvent(
|
||||
pubkey: Data(senderKey.xonly.bytes).hexEncodedString(),
|
||||
createdAt: randomizedTimestamp(),
|
||||
kind: .seal,
|
||||
createdAt: randomizedPastTimestamp(),
|
||||
kind: format.sealKind,
|
||||
tags: [],
|
||||
content: encrypted
|
||||
)
|
||||
|
||||
// Sign the seal with the sender's Schnorr private key
|
||||
return try seal.sign(with: senderKey)
|
||||
}
|
||||
|
||||
private static func createGiftWrap(
|
||||
seal: NostrEvent,
|
||||
recipientPubkey: String
|
||||
) throws -> NostrEvent {
|
||||
|
||||
let sealJSON = try seal.jsonString()
|
||||
|
||||
// Create new ephemeral key for gift wrap
|
||||
let wrapKey = try P256K.Schnorr.PrivateKey()
|
||||
// Creating gift wrap with ephemeral key
|
||||
|
||||
// Encrypt the seal with the new ephemeral key (not the seal's key)
|
||||
private static func createPrivateEnvelopeEvent(
|
||||
seal: NostrEvent,
|
||||
recipientPubkey: String,
|
||||
format: PrivateEnvelopeWireFormat
|
||||
) throws -> NostrEvent {
|
||||
// A fresh signing/encryption key for every public envelope keeps the
|
||||
// stable sender identity inside ciphertext.
|
||||
let envelopeKey = try P256K.Schnorr.PrivateKey()
|
||||
let encrypted = try encrypt(
|
||||
plaintext: sealJSON,
|
||||
plaintext: seal.jsonString(),
|
||||
recipientPubkey: recipientPubkey,
|
||||
senderKey: wrapKey // Use the gift wrap ephemeral key
|
||||
senderKey: envelopeKey,
|
||||
format: format,
|
||||
maximumPlaintextBytes: maximumPrivateEnvelopeSealPlaintextBytes
|
||||
)
|
||||
|
||||
let giftWrap = NostrEvent(
|
||||
pubkey: Data(wrapKey.xonly.bytes).hexEncodedString(),
|
||||
createdAt: randomizedTimestamp(),
|
||||
kind: .giftWrap,
|
||||
tags: [["p", recipientPubkey]], // Tag recipient
|
||||
|
||||
let envelope = NostrEvent(
|
||||
pubkey: Data(envelopeKey.xonly.bytes).hexEncodedString(),
|
||||
createdAt: randomizedPastTimestamp(),
|
||||
kind: format.envelopeKind,
|
||||
tags: [["p", recipientPubkey]],
|
||||
content: encrypted
|
||||
)
|
||||
|
||||
// Sign the gift wrap with the wrap Schnorr private key
|
||||
return try giftWrap.sign(with: wrapKey)
|
||||
return try envelope.sign(with: envelopeKey)
|
||||
}
|
||||
|
||||
private static func unwrapGiftWrap(
|
||||
giftWrap: NostrEvent,
|
||||
recipientKey: P256K.Schnorr.PrivateKey
|
||||
) throws -> NostrEvent {
|
||||
|
||||
// Unwrapping gift wrap
|
||||
|
||||
let decrypted = try decrypt(
|
||||
ciphertext: giftWrap.content,
|
||||
senderPubkey: giftWrap.pubkey,
|
||||
recipientKey: recipientKey
|
||||
)
|
||||
|
||||
guard let data = decrypted.data(using: .utf8),
|
||||
let sealDict = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
|
||||
private static func decodePrivateEnvelopeLayers(
|
||||
envelope: NostrEvent,
|
||||
recipientIdentity: NostrIdentity
|
||||
) throws -> (seal: NostrEvent, message: NostrEvent) {
|
||||
guard envelope.content.utf8.count <= maximumPrivateEnvelopeCiphertextBytes else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
guard let format = PrivateEnvelopeWireFormat(outerKind: envelope.kind),
|
||||
envelope.tags == [["p", recipientIdentity.publicKeyHex]],
|
||||
envelope.isValidSignature() else {
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
let seal = try NostrEvent(from: sealDict)
|
||||
// Unwrapped seal
|
||||
|
||||
return seal
|
||||
}
|
||||
|
||||
private static func openSeal(
|
||||
seal: NostrEvent,
|
||||
recipientKey: P256K.Schnorr.PrivateKey
|
||||
) throws -> NostrEvent {
|
||||
|
||||
let decrypted = try decrypt(
|
||||
|
||||
let recipientKey = try recipientIdentity.schnorrSigningKey()
|
||||
let sealJSON = try decrypt(
|
||||
ciphertext: envelope.content,
|
||||
senderPubkey: envelope.pubkey,
|
||||
recipientKey: recipientKey,
|
||||
format: format,
|
||||
maximumPlaintextBytes: maximumPrivateEnvelopeSealPlaintextBytes
|
||||
)
|
||||
let seal = try decodePrivateEnvelopeEventJSON(
|
||||
sealJSON,
|
||||
maximumBytes: maximumPrivateEnvelopeSealPlaintextBytes
|
||||
)
|
||||
guard seal.kind == format.sealKind.rawValue,
|
||||
seal.tags.isEmpty,
|
||||
seal.isValidSignature() else {
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
let messageJSON = try decrypt(
|
||||
ciphertext: seal.content,
|
||||
senderPubkey: seal.pubkey,
|
||||
recipientKey: recipientKey
|
||||
recipientKey: recipientKey,
|
||||
format: format,
|
||||
maximumPlaintextBytes: maximumPrivateEnvelopePlaintextBytes
|
||||
)
|
||||
|
||||
guard let data = decrypted.data(using: .utf8),
|
||||
let rumorDict = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
let message = try decodePrivateEnvelopeEventJSON(
|
||||
messageJSON,
|
||||
maximumBytes: maximumPrivateEnvelopePlaintextBytes
|
||||
)
|
||||
|
||||
// The inner message is intentionally unsigned; sender authentication
|
||||
// comes from the seal. Bind its claimed sender and custom kind to that
|
||||
// authenticated layer before exposing content.
|
||||
guard message.kind == format.messageKind.rawValue,
|
||||
message.tags.isEmpty,
|
||||
message.sig == nil,
|
||||
seal.pubkey == message.pubkey else {
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
|
||||
return try NostrEvent(from: rumorDict)
|
||||
|
||||
return (seal, message)
|
||||
}
|
||||
|
||||
// MARK: - Encryption (NIP-44 v2)
|
||||
|
||||
|
||||
private static func decodePrivateEnvelopeEventJSON(
|
||||
_ json: String,
|
||||
maximumBytes: Int = maximumPrivateEnvelopePlaintextBytes
|
||||
) throws -> NostrEvent {
|
||||
// Check UTF-8 size before allocating Data or invoking the general JSON
|
||||
// parser. `decrypt` enforces the same cap on authenticated bytes; this
|
||||
// local guard keeps the parser boundary explicit and independently
|
||||
// testable.
|
||||
guard json.utf8.count <= maximumBytes else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
guard let data = json.data(using: .utf8),
|
||||
let dictionary = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
throw NostrError.invalidEvent
|
||||
}
|
||||
return try NostrEvent(from: dictionary)
|
||||
}
|
||||
|
||||
// MARK: - BitChat private-envelope encryption
|
||||
|
||||
private static func encrypt(
|
||||
plaintext: String,
|
||||
recipientPubkey: String,
|
||||
senderKey: P256K.Schnorr.PrivateKey
|
||||
senderKey: P256K.Schnorr.PrivateKey,
|
||||
format: PrivateEnvelopeWireFormat,
|
||||
maximumPlaintextBytes: Int
|
||||
) throws -> String {
|
||||
|
||||
guard let recipientPubkeyData = Data(hexString: recipientPubkey) else {
|
||||
throw NostrError.invalidPublicKey
|
||||
}
|
||||
|
||||
// Encrypting message (NIP-44 v2: XChaCha20-Poly1305, versioned)
|
||||
|
||||
// Derive shared secret
|
||||
|
||||
let sharedSecret = try deriveSharedSecret(
|
||||
privateKey: senderKey,
|
||||
publicKey: recipientPubkeyData
|
||||
)
|
||||
// Derive NIP-44 v2 symmetric key (HKDF-SHA256 with label in info)
|
||||
let key = try deriveNIP44V2Key(from: sharedSecret)
|
||||
|
||||
// 24-byte random nonce for XChaCha20-Poly1305
|
||||
let key = derivePrivateEnvelopeKey(from: sharedSecret, format: format)
|
||||
|
||||
var nonce24 = Data(count: 24)
|
||||
_ = nonce24.withUnsafeMutableBytes { ptr in
|
||||
let randomStatus = nonce24.withUnsafeMutableBytes { ptr in
|
||||
SecRandomCopyBytes(kSecRandomDefault, 24, ptr.baseAddress!)
|
||||
}
|
||||
|
||||
let pt = Data(plaintext.utf8)
|
||||
let sealed = try XChaCha20Poly1305Compat.seal(plaintext: pt, key: key, nonce24: nonce24)
|
||||
|
||||
// v2: base64url(nonce24 || ciphertext || tag)
|
||||
guard randomStatus == errSecSuccess else {
|
||||
throw NostrError.cryptographicFailure
|
||||
}
|
||||
|
||||
let plaintextData = Data(plaintext.utf8)
|
||||
guard plaintextData.count <= maximumPlaintextBytes else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
let sealed = try XChaCha20Poly1305Compat.seal(
|
||||
plaintext: plaintextData,
|
||||
key: key,
|
||||
nonce24: nonce24
|
||||
)
|
||||
|
||||
var combined = Data()
|
||||
combined.append(nonce24)
|
||||
combined.append(sealed.ciphertext)
|
||||
combined.append(sealed.tag)
|
||||
return "v2:" + Base64URLCoding.encode(combined)
|
||||
return format.contentPrefix + Base64URLCoding.encode(combined)
|
||||
}
|
||||
|
||||
|
||||
private static func decrypt(
|
||||
ciphertext: String,
|
||||
senderPubkey: String,
|
||||
recipientKey: P256K.Schnorr.PrivateKey
|
||||
recipientKey: P256K.Schnorr.PrivateKey,
|
||||
format: PrivateEnvelopeWireFormat,
|
||||
maximumPlaintextBytes: Int
|
||||
) throws -> String {
|
||||
// Expect NIP-44 v2 format
|
||||
guard ciphertext.hasPrefix("v2:") else { throw NostrError.invalidCiphertext }
|
||||
let encoded = String(ciphertext.dropFirst(3))
|
||||
guard ciphertext.utf8.count <= maximumPrivateEnvelopeCiphertextBytes,
|
||||
ciphertext.hasPrefix(format.contentPrefix) else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
let encoded = String(ciphertext.dropFirst(format.contentPrefix.count))
|
||||
guard let data = Base64URLCoding.decode(encoded),
|
||||
data.count > (24 + 16),
|
||||
let senderPubkeyData = Data(hexString: senderPubkey) else {
|
||||
@@ -554,33 +729,40 @@ struct NostrProtocol {
|
||||
let nonce24 = data.prefix(24)
|
||||
let rest = data.dropFirst(24)
|
||||
let tag = rest.suffix(16)
|
||||
let ct = rest.dropLast(16)
|
||||
let ciphertextBytes = rest.dropLast(16)
|
||||
|
||||
// Try decryption with even-Y then odd-Y when sender pubkey is x-only
|
||||
func attemptDecrypt(using pubKeyData: Data) throws -> Data {
|
||||
let ss = try deriveSharedSecret(privateKey: recipientKey, publicKey: pubKeyData)
|
||||
let key = try deriveNIP44V2Key(from: ss)
|
||||
func attemptDecrypt(using publicKeyData: Data) throws -> Data {
|
||||
let sharedSecret = try deriveSharedSecret(
|
||||
privateKey: recipientKey,
|
||||
publicKey: publicKeyData
|
||||
)
|
||||
let key = derivePrivateEnvelopeKey(from: sharedSecret, format: format)
|
||||
return try XChaCha20Poly1305Compat.open(
|
||||
ciphertext: Data(ct),
|
||||
ciphertext: Data(ciphertextBytes),
|
||||
tag: Data(tag),
|
||||
key: key,
|
||||
nonce24: Data(nonce24)
|
||||
)
|
||||
}
|
||||
|
||||
// If 32 bytes (x-only) try both parities, otherwise single try
|
||||
let plaintext: Data
|
||||
if senderPubkeyData.count == 32 {
|
||||
let even = Data([0x02]) + senderPubkeyData
|
||||
if let pt = try? attemptDecrypt(using: even) {
|
||||
return String(data: pt, encoding: .utf8) ?? ""
|
||||
let evenKey = Data([0x02]) + senderPubkeyData
|
||||
if let opened = try? attemptDecrypt(using: evenKey) {
|
||||
plaintext = opened
|
||||
} else {
|
||||
let oddKey = Data([0x03]) + senderPubkeyData
|
||||
plaintext = try attemptDecrypt(using: oddKey)
|
||||
}
|
||||
let odd = Data([0x03]) + senderPubkeyData
|
||||
let pt = try attemptDecrypt(using: odd)
|
||||
return String(data: pt, encoding: .utf8) ?? ""
|
||||
} else {
|
||||
let pt = try attemptDecrypt(using: senderPubkeyData)
|
||||
return String(data: pt, encoding: .utf8) ?? ""
|
||||
plaintext = try attemptDecrypt(using: senderPubkeyData)
|
||||
}
|
||||
|
||||
guard plaintext.count <= maximumPlaintextBytes,
|
||||
let decoded = String(data: plaintext, encoding: .utf8) else {
|
||||
throw NostrError.invalidCiphertext
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
|
||||
private static func deriveSharedSecret(
|
||||
@@ -640,29 +822,17 @@ struct NostrProtocol {
|
||||
let sharedSecretData = sharedSecret.withUnsafeBytes { Data($0) }
|
||||
// ECDH shared secret derived
|
||||
|
||||
// Return raw ECDH shared secret; HKDF is applied by deriveNIP44V2Key
|
||||
// Return raw ECDH shared secret; the wire-format-specific HKDF is
|
||||
// applied by derivePrivateEnvelopeKey.
|
||||
return sharedSecretData
|
||||
}
|
||||
|
||||
private static func randomizedTimestamp() -> Date {
|
||||
// Add random offset to current time for privacy
|
||||
// This prevents timing correlation attacks while the actual message timestamp
|
||||
// is preserved in the encrypted rumor
|
||||
let offset = TimeInterval.random(in: -900...900) // +/- 15 minutes
|
||||
let now = Date()
|
||||
let randomized = now.addingTimeInterval(offset)
|
||||
|
||||
// Log with explicit UTC and local time for debugging
|
||||
let formatter = DateFormatter()
|
||||
//
|
||||
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
|
||||
formatter.timeZone = TimeZone(abbreviation: "UTC")
|
||||
|
||||
formatter.timeZone = TimeZone.current
|
||||
|
||||
// Timestamp randomized for privacy
|
||||
|
||||
return randomized
|
||||
private static func randomizedPastTimestamp() -> Date {
|
||||
// Keep public timestamps in the past: future-dated events are rejected
|
||||
// by some relays. The actual message timestamp remains encrypted.
|
||||
Date().addingTimeInterval(
|
||||
-TimeInterval.random(in: 0...TransportConfig.nostrPrivateEnvelopeTimestampFuzzSeconds)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -794,16 +964,20 @@ enum NostrError: Error {
|
||||
case invalidPublicKey
|
||||
case invalidEvent
|
||||
case invalidCiphertext
|
||||
case cryptographicFailure
|
||||
}
|
||||
|
||||
// MARK: - NIP-44 v2 helpers (XChaCha20-Poly1305)
|
||||
// MARK: - BitChat private-envelope key derivation
|
||||
|
||||
private extension NostrProtocol {
|
||||
static func deriveNIP44V2Key(from sharedSecretData: Data) throws -> Data {
|
||||
private static func derivePrivateEnvelopeKey(
|
||||
from sharedSecretData: Data,
|
||||
format: PrivateEnvelopeWireFormat
|
||||
) -> Data {
|
||||
let derivedKey = HKDF<CryptoKit.SHA256>.deriveKey(
|
||||
inputKeyMaterial: SymmetricKey(data: sharedSecretData),
|
||||
salt: Data(),
|
||||
info: Data("nip44-v2".utf8),
|
||||
salt: format.hkdfSalt,
|
||||
info: format.hkdfInfo,
|
||||
outputByteCount: 32
|
||||
)
|
||||
return derivedKey.withUnsafeBytes { Data($0) }
|
||||
|
||||
@@ -106,10 +106,11 @@ private extension NostrRelayManagerDependencies {
|
||||
@MainActor
|
||||
final class NostrRelayManager: ObservableObject {
|
||||
static let shared = NostrRelayManager()
|
||||
// Track gift-wraps (kind 1059) we initiated so we can log OK acks at info
|
||||
private(set) static var pendingGiftWrapIDs = Set<String>()
|
||||
static func registerPendingGiftWrap(id: String) {
|
||||
pendingGiftWrapIDs.insert(id)
|
||||
// Track BitChat private envelopes we initiated so relay rejections can be
|
||||
// reported without misclassifying ordinary public-event failures.
|
||||
private(set) static var pendingPrivateEnvelopeIDs = Set<String>()
|
||||
static func registerPendingPrivateEnvelope(id: String) {
|
||||
pendingPrivateEnvelopeIDs.insert(id)
|
||||
}
|
||||
|
||||
struct Relay: Identifiable {
|
||||
@@ -124,7 +125,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
var nextReconnectTime: Date?
|
||||
}
|
||||
|
||||
// Default relays carry NIP-17 gift wraps, so avoid relays known to reject kind 1059.
|
||||
// Default relays carry persisted BitChat private-envelope events.
|
||||
private static let defaultRelays = [
|
||||
"wss://relay.damus.io",
|
||||
"wss://nos.lol",
|
||||
@@ -137,7 +138,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
@Published private(set) var relays: [Relay] = []
|
||||
@Published private(set) var isConnected = false
|
||||
/// Whether a relay that carries private messages is connected. DMs
|
||||
/// target the default (gift-wrap-capable) relay set, so a connected
|
||||
/// target the default private-envelope relay set, so a connected
|
||||
/// geohash/custom relay alone must not count — sends would still queue.
|
||||
@Published private(set) var isDMRelayConnected = false
|
||||
|
||||
@@ -217,7 +218,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
private var messageQueue: [PendingSend] = []
|
||||
private let messageQueueLock = NSLock()
|
||||
/// Non-queued sends whose callers require relay durability. A WebSocket
|
||||
/// write only proves bytes left this process; NIP-20 OK is the relay's
|
||||
/// write only proves bytes left this process; NIP-01 `OK` is the relay's
|
||||
/// accept/reject acknowledgment.
|
||||
private struct ConfirmedSendState {
|
||||
let token: UUID
|
||||
@@ -356,7 +357,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
duplicateInboundEventDropCount = 0
|
||||
duplicateInboundEventDropCountBySubscription.removeAll()
|
||||
inboundEventLogCount = 0
|
||||
Self.pendingGiftWrapIDs.removeAll()
|
||||
Self.pendingPrivateEnvelopeIDs.removeAll()
|
||||
confirmedSends.removeAll()
|
||||
|
||||
messageQueueLock.lock()
|
||||
@@ -433,8 +434,8 @@ final class NostrRelayManager: ObservableObject {
|
||||
}
|
||||
|
||||
/// Attempts an event only on currently connected target relays and
|
||||
/// reports whether at least one relay explicitly accepted it via NIP-20
|
||||
/// OK. A successful WebSocket write alone is not durable acceptance.
|
||||
/// reports whether at least one relay explicitly accepted it via NIP-01
|
||||
/// `OK`. A successful WebSocket write alone is not durable acceptance.
|
||||
/// Unlike `sendEvent`, this never enters the process-local pending queue;
|
||||
/// callers use it when success unlocks durable state or user-visible
|
||||
/// delivery progress.
|
||||
@@ -1139,7 +1140,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
guard shouldDeliverInboundEvent(subscriptionID: subId, eventID: event.id) else {
|
||||
return
|
||||
}
|
||||
if event.kind != 1059 {
|
||||
if !NostrProtocol.acceptedPrivateEnvelopeKinds.contains(event.kind) {
|
||||
// Per-event logging floods dev builds in busy geohashes; sample it.
|
||||
inboundEventLogCount += 1
|
||||
if inboundEventLogCount == 1 || inboundEventLogCount.isMultiple(of: TransportConfig.nostrInboundEventLogInterval) {
|
||||
@@ -1168,11 +1169,11 @@ final class NostrRelayManager: ObservableObject {
|
||||
case .ok(let eventId, let success, let reason):
|
||||
resolveConfirmedSend(eventID: eventId, relayURL: relayUrl, accepted: success)
|
||||
if success {
|
||||
_ = Self.pendingGiftWrapIDs.remove(eventId)
|
||||
_ = Self.pendingPrivateEnvelopeIDs.remove(eventId)
|
||||
SecureLogger.debug("✅ Accepted id=\(eventId.prefix(16))… relay=\(relayUrl)", category: .session)
|
||||
} else {
|
||||
let isGiftWrap = Self.pendingGiftWrapIDs.remove(eventId) != nil
|
||||
if isGiftWrap {
|
||||
let isPrivateEnvelope = Self.pendingPrivateEnvelopeIDs.remove(eventId) != nil
|
||||
if isPrivateEnvelope {
|
||||
SecureLogger.warning("📮 Rejected id=\(eventId.prefix(16))… relay=\(relayUrl) reason=\(reason)", category: .session)
|
||||
} else {
|
||||
SecureLogger.error("📮 Rejected id=\(eventId.prefix(16))… relay=\(relayUrl) reason=\(reason)", category: .session)
|
||||
@@ -1610,13 +1611,19 @@ struct NostrFilter: Encodable {
|
||||
}
|
||||
}
|
||||
|
||||
// For NIP-17 gift wraps
|
||||
static func giftWrapsFor(pubkey: String, since: Date? = nil) -> NostrFilter {
|
||||
// BitChat private envelopes, plus compatibility legacy envelopes emitted
|
||||
// during the bounded migration and stored by older releases as kind 1059.
|
||||
static func privateEnvelopesFor(pubkey: String, since: Date? = nil) -> NostrFilter {
|
||||
var filter = NostrFilter()
|
||||
filter.kinds = [1059] // Gift wrap kind
|
||||
filter.kinds = NostrProtocol.acceptedPrivateEnvelopeKinds
|
||||
filter.since = since?.timeIntervalSince1970.toInt()
|
||||
filter.tagFilters = ["p": [pubkey]]
|
||||
filter.limit = TransportConfig.nostrRelayDefaultFetchLimit // reasonable limit
|
||||
// Before the migration deadline each logical payload is stored once
|
||||
// per accepted wire kind. Scale the combined filter so compatibility
|
||||
// copies do not halve the number of logical messages/acks recovered
|
||||
// after a reconnect.
|
||||
filter.limit = TransportConfig.nostrRelayDefaultFetchLimit
|
||||
* NostrProtocol.acceptedPrivateEnvelopeKinds.count
|
||||
return filter
|
||||
}
|
||||
|
||||
|
||||
@@ -322,7 +322,7 @@ final class CourierStore {
|
||||
|
||||
/// Envelopes eligible to park on relays as bridge courier drops. Merely
|
||||
/// offering one does not start its cooldown: the caller commits that only
|
||||
/// after a relay explicitly accepts the event via NIP-20 OK.
|
||||
/// after a relay explicitly accepts the event via NIP-01 `OK`.
|
||||
func envelopesForBridgePublish(cooldown: TimeInterval) -> [CourierEnvelope] {
|
||||
let date = now()
|
||||
return queue.sync {
|
||||
|
||||
@@ -67,7 +67,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
var relaysConnected: (@MainActor () -> Bool)?
|
||||
/// Publishes a signed drop event directly to connected default (DM)
|
||||
/// relays. Completion is true only after at least one relay explicitly
|
||||
/// accepts the event via NIP-20 OK; this must never mean "queued in RAM"
|
||||
/// accepts the event via NIP-01 `OK`; this must never mean "queued in RAM"
|
||||
/// or merely "written to a socket".
|
||||
var publishEvent: (@MainActor (NostrEvent, @escaping @MainActor (Bool) -> Void) -> Void)?
|
||||
/// (Re)opens the drop subscription for the given hex tags.
|
||||
@@ -129,7 +129,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
/// a newer attempt for the same message.
|
||||
private var activeDropOperations: [String: ActiveDropOperation] = [:]
|
||||
/// Held-envelope publishes have no sender message ID, but still need an
|
||||
/// in-flight identity: repeated refreshes inside the NIP-20 wait window
|
||||
/// in-flight identity: repeated refreshes inside the relay-OK wait window
|
||||
/// must not mint duplicate relay events for the same opaque envelope.
|
||||
private var heldDropOperations: [Data: UUID] = [:]
|
||||
/// Deterministically invalid envelopes are suppressed for this process,
|
||||
@@ -275,7 +275,7 @@ final class BridgeCourierService: ObservableObject {
|
||||
/// Publishes a drop, or queues it when relays are down. `messageID` is the
|
||||
/// sender-side dedup key (nil for held/relayed envelopes we don't track);
|
||||
/// it rides the pending queue so an evicted or failed drop can release its
|
||||
/// in-flight slot. Completion reports actual NIP-20 relay acceptance.
|
||||
/// in-flight slot. Completion reports actual NIP-01 relay acceptance.
|
||||
private func publishDrop(
|
||||
_ envelope: CourierEnvelope,
|
||||
messageID: String? = nil,
|
||||
|
||||
@@ -172,11 +172,11 @@ final class MessageDeduplicationService {
|
||||
/// Cache for Nostr ACK deduplication (messageId:ackType:senderPubkey format)
|
||||
private let nostrAckCache: LRUDeduplicationCache<Bool>
|
||||
|
||||
/// Optional cross-launch persistence for the Nostr event cache. NIP-59
|
||||
/// randomizes gift-wrap timestamps, so DM subscriptions look back 24h and
|
||||
/// relays redeliver the same events on every launch; without this record
|
||||
/// each relaunch reprocesses old PMs and acks. Nil (tests, macOS callers
|
||||
/// that don't opt in) keeps the cache purely in-memory.
|
||||
/// Optional cross-launch persistence for the Nostr event cache. BitChat
|
||||
/// randomizes private-envelope timestamps, so DM subscriptions look back
|
||||
/// 24h and relays redeliver the same events on every launch; without this
|
||||
/// record each relaunch reprocesses old PMs and acks. Nil (tests, macOS
|
||||
/// callers that don't opt in) keeps the cache purely in-memory.
|
||||
private let nostrEventStore: NostrProcessedEventStore?
|
||||
private let nostrEventCapacity: Int
|
||||
private var persistScheduled = false
|
||||
@@ -314,7 +314,7 @@ final class MessageDeduplicationService {
|
||||
// MARK: - Clear
|
||||
|
||||
/// Clears all caches. This is the wipe/panic path: the persisted
|
||||
/// gift-wrap record goes with everything else.
|
||||
/// private-envelope record goes with everything else.
|
||||
func clearAll() {
|
||||
contentCache.clear()
|
||||
nostrEventCache.clear()
|
||||
@@ -325,7 +325,7 @@ final class MessageDeduplicationService {
|
||||
|
||||
/// Clears only the in-memory Nostr caches (events and ACKs). Runs on
|
||||
/// every geohash channel switch, so the disk record deliberately
|
||||
/// survives — wiping it here would forfeit cross-launch gift-wrap dedup
|
||||
/// survives — wiping it here would forfeit cross-launch private-envelope dedup
|
||||
/// each time the user changes channels (flagged by Codex on #1398).
|
||||
func clearNostrCaches() {
|
||||
nostrEventCache.clear()
|
||||
|
||||
@@ -9,10 +9,10 @@
|
||||
import BitLogger
|
||||
import Foundation
|
||||
|
||||
/// Disk persistence for processed gift-wrap event IDs. NIP-59 randomizes
|
||||
/// gift-wrap timestamps, so DM subscriptions must look back generously (24h)
|
||||
/// and relays redeliver the same events on every launch — without a
|
||||
/// cross-launch record, each relaunch reprocesses old PMs and acks
|
||||
/// Disk persistence for processed private-envelope event IDs. BitChat
|
||||
/// randomizes envelope timestamps, so DM subscriptions must look back
|
||||
/// generously (24h) and relays redeliver the same events on every launch —
|
||||
/// without a cross-launch record, each relaunch reprocesses old PMs and acks
|
||||
/// (re-sent DELIVERED bursts, "delivered ack for unknown mid" noise).
|
||||
///
|
||||
/// Contents are event IDs already visible to every relay, so
|
||||
|
||||
@@ -11,8 +11,9 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
let favoriteStatusForNoiseKey: @MainActor (Data) -> FavoritesPersistenceService.FavoriteRelationship?
|
||||
let favoriteStatusForPeerID: @MainActor (PeerID) -> FavoritesPersistenceService.FavoriteRelationship?
|
||||
let currentIdentity: @MainActor () throws -> NostrIdentity?
|
||||
let registerPendingGiftWrap: @MainActor (String) -> Void
|
||||
let registerPendingPrivateEnvelope: @MainActor (String) -> Void
|
||||
let sendEvent: @MainActor (NostrEvent) -> Void
|
||||
let now: @MainActor () -> Date
|
||||
/// Emits whether a relay that carries private messages is up
|
||||
/// (fail-closed behind Tor). A connected geohash/custom relay alone
|
||||
/// doesn't count: DM sends target the default relay set and would
|
||||
@@ -28,19 +29,21 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
favoriteStatusForNoiseKey: @escaping @MainActor (Data) -> FavoritesPersistenceService.FavoriteRelationship?,
|
||||
favoriteStatusForPeerID: @escaping @MainActor (PeerID) -> FavoritesPersistenceService.FavoriteRelationship?,
|
||||
currentIdentity: @escaping @MainActor () throws -> NostrIdentity?,
|
||||
registerPendingGiftWrap: @escaping @MainActor (String) -> Void,
|
||||
registerPendingPrivateEnvelope: @escaping @MainActor (String) -> Void,
|
||||
sendEvent: @escaping @MainActor (NostrEvent) -> Void,
|
||||
scheduleAfter: @escaping @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void,
|
||||
relayConnectivity: @escaping @MainActor () -> AnyPublisher<Bool, Never>,
|
||||
ackPacer: AckPacer? = nil
|
||||
ackPacer: AckPacer? = nil,
|
||||
now: @escaping @MainActor () -> Date = Date.init
|
||||
) {
|
||||
self.notificationCenter = notificationCenter
|
||||
self.loadFavorites = loadFavorites
|
||||
self.favoriteStatusForNoiseKey = favoriteStatusForNoiseKey
|
||||
self.favoriteStatusForPeerID = favoriteStatusForPeerID
|
||||
self.currentIdentity = currentIdentity
|
||||
self.registerPendingGiftWrap = registerPendingGiftWrap
|
||||
self.registerPendingPrivateEnvelope = registerPendingPrivateEnvelope
|
||||
self.sendEvent = sendEvent
|
||||
self.now = now
|
||||
self.relayConnectivity = relayConnectivity
|
||||
// Default pacer drives its throttle through the same injected
|
||||
// scheduler, so tests that step scheduleAfter manually keep
|
||||
@@ -56,7 +59,7 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
favoriteStatusForNoiseKey: { FavoritesPersistenceService.shared.getFavoriteStatus(for: $0) },
|
||||
favoriteStatusForPeerID: { FavoritesPersistenceService.shared.getFavoriteStatus(forPeerID: $0) },
|
||||
currentIdentity: { try idBridge.getCurrentNostrIdentity() },
|
||||
registerPendingGiftWrap: { NostrRelayManager.registerPendingGiftWrap(id: $0) },
|
||||
registerPendingPrivateEnvelope: { NostrRelayManager.registerPendingPrivateEnvelope(id: $0) },
|
||||
sendEvent: { NostrRelayManager.shared.sendEvent($0) },
|
||||
scheduleAfter: { delay, action in
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: action)
|
||||
@@ -261,7 +264,7 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
SecureLogger.error("NostrTransport: failed to embed PM packet", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendPrivateEnvelope(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,7 +290,7 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
SecureLogger.error("NostrTransport: failed to embed favorite notification", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendPrivateEnvelope(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,7 +322,7 @@ extension NostrTransport {
|
||||
SecureLogger.error("NostrTransport: failed to embed geohash PM packet", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
sendPrivateEnvelope(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -340,17 +343,24 @@ extension NostrTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates and sends a gift-wrapped private message event
|
||||
/// Creates and sends a BitChat private-envelope event over Nostr.
|
||||
@MainActor
|
||||
private func sendWrappedMessage(content: String, recipientHex: String, senderIdentity: NostrIdentity, registerPending: Bool = false) {
|
||||
guard let event = try? NostrProtocol.createPrivateMessage(content: content, recipientPubkey: recipientHex, senderIdentity: senderIdentity) else {
|
||||
SecureLogger.error("NostrTransport: failed to build Nostr event", category: .session)
|
||||
private func sendPrivateEnvelope(content: String, recipientHex: String, senderIdentity: NostrIdentity, registerPending: Bool = false) {
|
||||
guard let events = try? NostrProtocol.createPrivateEnvelopePublicationBatch(
|
||||
content: content,
|
||||
recipientPubkey: recipientHex,
|
||||
senderIdentity: senderIdentity,
|
||||
now: dependencies.now()
|
||||
) else {
|
||||
SecureLogger.error("NostrTransport: failed to build Nostr private-envelope batch", category: .session)
|
||||
return
|
||||
}
|
||||
if registerPending {
|
||||
dependencies.registerPendingGiftWrap(event.id)
|
||||
for event in events {
|
||||
if registerPending {
|
||||
dependencies.registerPendingPrivateEnvelope(event.id)
|
||||
}
|
||||
dependencies.sendEvent(event)
|
||||
}
|
||||
dependencies.sendEvent(event)
|
||||
}
|
||||
|
||||
|
||||
@@ -367,7 +377,7 @@ extension NostrTransport {
|
||||
SecureLogger.error("NostrTransport: failed to embed READ ack", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendPrivateEnvelope(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
|
||||
case .deliveredDirect(let messageID, let peerID):
|
||||
guard let recipientNpub = resolveRecipientNpub(for: peerID),
|
||||
@@ -378,17 +388,17 @@ extension NostrTransport {
|
||||
SecureLogger.error("NostrTransport: failed to embed DELIVERED ack", category: .session)
|
||||
return
|
||||
}
|
||||
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
sendPrivateEnvelope(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity)
|
||||
|
||||
case .deliveredGeohash(let messageID, let recipientHex, let identity):
|
||||
SecureLogger.debug("GeoDM: send DELIVERED mid=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .delivered, messageID: messageID, senderPeerID: senderPeerID) else { return }
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
sendPrivateEnvelope(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
|
||||
case .readGeohash(let messageID, let recipientHex, let identity):
|
||||
SecureLogger.debug("GeoDM: send READ mid=\(messageID.prefix(8))…", category: .session)
|
||||
guard let embedded = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .readReceipt, messageID: messageID, senderPeerID: senderPeerID) else { return }
|
||||
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
sendPrivateEnvelope(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,7 +196,13 @@ enum TransportConfig {
|
||||
static let nostrGeoRelayCount: Int = 5
|
||||
static let nostrGeohashSampleLookbackSeconds: TimeInterval = 300
|
||||
static let nostrGeohashSampleLimit: Int = 100
|
||||
static let nostrDMSubscribeLookbackSeconds: TimeInterval = 86400
|
||||
/// Public envelope timestamps are deliberately shifted into the past for
|
||||
/// privacy and relay compatibility. Mailbox queries must add the complete
|
||||
/// shift to the 24-hour delivery window or boundary messages disappear
|
||||
/// from `since` filters early.
|
||||
static let nostrPrivateEnvelopeTimestampFuzzSeconds: TimeInterval = 15 * 60
|
||||
static let nostrDMSubscribeLookbackSeconds: TimeInterval = (24 * 60 * 60)
|
||||
+ nostrPrivateEnvelopeTimestampFuzzSeconds
|
||||
// A sampled chat message this recent means "a conversation is happening
|
||||
// there" for the empty-timeline nearby-activity hint.
|
||||
static let uiGeohashChatActivityWindowSeconds: TimeInterval = 900
|
||||
@@ -240,7 +246,7 @@ enum TransportConfig {
|
||||
// Fallback deadline for treating a subscription's initial fetch as complete
|
||||
// when a relay never sends EOSE (generous to cover Tor circuit setup).
|
||||
static let nostrSubscriptionEOSEFallbackSeconds: TimeInterval = 10.0
|
||||
// A bridge drop is durable only after NIP-20 OK. Relays that omit OK must
|
||||
// A bridge drop is durable only after NIP-01 `OK`. Relays that omit `OK` must
|
||||
// not pin the router's in-flight state indefinitely.
|
||||
static let nostrConfirmedSendAckTimeoutSeconds: TimeInterval = 10.0
|
||||
// After this long, a relay marked permanently failed gets another chance.
|
||||
|
||||
@@ -227,7 +227,7 @@ extension ChatViewModel: ChatPrivateConversationContext {
|
||||
final class ChatPrivateConversationCoordinator {
|
||||
private unowned let context: any ChatPrivateConversationContext
|
||||
|
||||
// Outbox retries re-wrap the same message in fresh gift-wrap events, so
|
||||
// Outbox retries re-envelope the same message in fresh private events, so
|
||||
// relay-level event-ID dedup can't catch them; track inbound GeoDM
|
||||
// message IDs so each copy past the first costs one (already-deduped)
|
||||
// ack check and nothing else.
|
||||
|
||||
@@ -41,7 +41,7 @@ struct ChatViewModelServiceBundle {
|
||||
self.privateChatManager = privateChatManager
|
||||
self.unifiedPeerService = unifiedPeerService
|
||||
self.autocompleteService = AutocompleteService()
|
||||
// Persist processed gift-wrap event IDs: NIP-59 randomizes their
|
||||
// Persist processed private-envelope event IDs: BitChat randomizes their
|
||||
// timestamps, so the 24h-lookback DM subscriptions redeliver the same
|
||||
// events on every launch and only a cross-launch record stops the
|
||||
// reprocessing (re-sent DELIVERED bursts, phantom-ack noise).
|
||||
@@ -558,7 +558,7 @@ private extension ChatViewModelBootstrapper {
|
||||
// Default (DM) relays: drops need the standing global relay set,
|
||||
// not geo relays — sender and recipient share no cell.
|
||||
// This confirmed path never falls back to the volatile relay
|
||||
// queue; bridge dedup is committed only after NIP-20 OK.
|
||||
// queue; bridge dedup is committed only after NIP-01 `OK`.
|
||||
NostrRelayManager.shared.sendEventImmediately(event, completion: completion)
|
||||
}
|
||||
courier.openSubscription = { tagsHex in
|
||||
|
||||
@@ -21,8 +21,8 @@ extension ChatViewModel {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func subscribeGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
nostrCoordinator.inbound.subscribeGiftWrap(giftWrap, id: id)
|
||||
func subscribePrivateEnvelope(_ envelope: NostrEvent, id: NostrIdentity) {
|
||||
nostrCoordinator.inbound.subscribePrivateEnvelope(envelope, id: id)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@@ -36,8 +36,8 @@ extension ChatViewModel {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func handleGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
nostrCoordinator.inbound.handleGiftWrap(giftWrap, id: id)
|
||||
func handlePrivateEnvelope(_ envelope: NostrEvent, id: NostrIdentity) {
|
||||
nostrCoordinator.inbound.handlePrivateEnvelope(envelope, id: id)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
|
||||
@@ -108,7 +108,7 @@ extension ChatViewModel: GeohashSubscriptionContext {
|
||||
}
|
||||
|
||||
/// Owns subscription IDs and relay lifecycle for geohash channels, geohash
|
||||
/// DMs, the account gift-wrap mailbox, and background geohash sampling. The
|
||||
/// DMs, the account private-envelope mailbox, and background geohash sampling. The
|
||||
/// only component that talks to `NostrRelayManager`; inbound events are
|
||||
/// forwarded to `NostrInboundPipeline` / `GeoPresenceTracker`.
|
||||
final class GeohashSubscriptionManager {
|
||||
@@ -162,13 +162,13 @@ final class GeohashSubscriptionManager {
|
||||
if let identity = try? context.deriveNostrIdentity(forGeohash: channel.geohash) {
|
||||
let dmSub = "geo-dm-\(channel.geohash)"
|
||||
context.setGeoDmSubscriptionID(dmSub)
|
||||
let dmFilter = NostrFilter.giftWrapsFor(
|
||||
let dmFilter = NostrFilter.privateEnvelopesFor(
|
||||
pubkey: identity.publicKeyHex,
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
)
|
||||
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in
|
||||
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] envelope in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.inbound.subscribeGiftWrap(giftWrap, id: identity)
|
||||
self?.inbound.subscribePrivateEnvelope(envelope, id: identity)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,13 +260,13 @@ final class GeohashSubscriptionManager {
|
||||
if TorManager.shared.isReady {
|
||||
SecureLogger.debug("GeoDM: subscribing DMs pub=\(identity.publicKeyHex.prefix(8))… sub=\(dmSub)", category: .session)
|
||||
}
|
||||
let dmFilter = NostrFilter.giftWrapsFor(
|
||||
let dmFilter = NostrFilter.privateEnvelopesFor(
|
||||
pubkey: identity.publicKeyHex,
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
)
|
||||
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in
|
||||
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] envelope in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.inbound.handleGiftWrap(giftWrap, id: identity)
|
||||
self?.inbound.handlePrivateEnvelope(envelope, id: identity)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -388,14 +388,14 @@ final class GeohashSubscriptionManager {
|
||||
category: .session
|
||||
)
|
||||
|
||||
let filter = NostrFilter.giftWrapsFor(
|
||||
let filter = NostrFilter.privateEnvelopesFor(
|
||||
pubkey: currentIdentity.publicKeyHex,
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
)
|
||||
|
||||
context.nostrRelayManager?.subscribe(filter: filter, id: "chat-messages") { [weak self] event in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.inbound.handleNostrMessage(event)
|
||||
self?.inbound.handleAccountPrivateEnvelope(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,13 +84,21 @@ extension ChatViewModel: NostrInboundPipelineContext {
|
||||
/// Ordering is deliberate and performance-critical: cheap rejects (kind,
|
||||
/// dedup lookup) run BEFORE Schnorr signature verification because duplicates
|
||||
/// dominate real relay traffic; events are recorded only AFTER verification so
|
||||
/// a forged-signature copy can never poison the dedup set; gift-wrap
|
||||
/// a forged-signature copy can never poison the dedup set; private-envelope
|
||||
/// verification for the account mailbox runs off-main with an atomic
|
||||
/// main-actor check-and-record.
|
||||
final class NostrInboundPipeline {
|
||||
private weak var context: (any NostrInboundPipelineContext)?
|
||||
private let presence: GeoPresenceTracker
|
||||
private var geoEventLogCount = 0
|
||||
// During the bounded wire-format migration, one logical private payload
|
||||
// is published under both the primary and compatibility formats. Outer
|
||||
// event IDs differ, so collapse the authenticated embedded payload before
|
||||
// invoking message/ack side effects. Keep this bounded like the outer-ID
|
||||
// caches; the recipient and authenticated sender are part of the key.
|
||||
private var recentPrivatePayloadFormats: [String: UInt8] = [:]
|
||||
private var recentPrivatePayloadKeyOrder: [String] = []
|
||||
private static let privatePayloadDedupCapacity = 2_048
|
||||
|
||||
init(context: any NostrInboundPipelineContext, presence: GeoPresenceTracker) {
|
||||
self.context = context
|
||||
@@ -271,15 +279,16 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func subscribeGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
func subscribePrivateEnvelope(_ envelope: NostrEvent, id: NostrIdentity) {
|
||||
guard let context else { return }
|
||||
// Dedup lookup before Schnorr verification; record only after it passes.
|
||||
guard !context.hasProcessedNostrEvent(giftWrap.id) else { return }
|
||||
guard giftWrap.isValidSignature() else { return }
|
||||
context.recordProcessedNostrEvent(giftWrap.id)
|
||||
guard !context.hasProcessedNostrEvent(envelope.id) else { return }
|
||||
guard envelope.content.utf8.count <= NostrProtocol.maximumPrivateEnvelopeCiphertextBytes else { return }
|
||||
guard envelope.isValidSignature() else { return }
|
||||
context.recordProcessedNostrEvent(envelope.id)
|
||||
|
||||
guard let (content, senderPubkey, rumorTs) = try? NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
guard let (content, senderPubkey, messageTs) = try? NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: id
|
||||
),
|
||||
let packet = Self.decodeEmbeddedBitChatPacket(from: content),
|
||||
@@ -288,8 +297,14 @@ final class NostrInboundPipeline {
|
||||
else {
|
||||
return
|
||||
}
|
||||
guard shouldProcessPrivatePayload(
|
||||
noisePayload,
|
||||
senderPubkey: senderPubkey,
|
||||
recipientPubkey: id.publicKeyHex,
|
||||
envelopeKind: envelope.kind
|
||||
) else { return }
|
||||
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(rumorTs))
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(messageTs))
|
||||
let convKey = PeerID(nostr_: senderPubkey)
|
||||
context.registerNostrKeyMapping(senderPubkey, for: convKey)
|
||||
|
||||
@@ -316,25 +331,26 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func handleGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
|
||||
func handlePrivateEnvelope(_ envelope: NostrEvent, id: NostrIdentity) {
|
||||
guard let context else { return }
|
||||
// Dedup lookup before Schnorr verification; record only after it passes.
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) {
|
||||
if context.hasProcessedNostrEvent(envelope.id) {
|
||||
return
|
||||
}
|
||||
guard giftWrap.isValidSignature() else { return }
|
||||
context.recordProcessedNostrEvent(giftWrap.id)
|
||||
guard envelope.content.utf8.count <= NostrProtocol.maximumPrivateEnvelopeCiphertextBytes else { return }
|
||||
guard envelope.isValidSignature() else { return }
|
||||
context.recordProcessedNostrEvent(envelope.id)
|
||||
|
||||
guard let (content, senderPubkey, rumorTs) = try? NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
guard let (content, senderPubkey, messageTs) = try? NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: id
|
||||
) else {
|
||||
SecureLogger.warning("GeoDM: failed decrypt giftWrap id=\(giftWrap.id.prefix(8))…", category: .session)
|
||||
SecureLogger.warning("GeoDM: failed decrypt private envelope id=\(envelope.id.prefix(8))…", category: .session)
|
||||
return
|
||||
}
|
||||
|
||||
SecureLogger.debug(
|
||||
"GeoDM: decrypted gift-wrap id=\(giftWrap.id.prefix(16))... from=\(senderPubkey.prefix(8))...",
|
||||
"GeoDM: decrypted private envelope id=\(envelope.id.prefix(16))... from=\(senderPubkey.prefix(8))...",
|
||||
category: .session
|
||||
)
|
||||
|
||||
@@ -344,13 +360,19 @@ final class NostrInboundPipeline {
|
||||
else {
|
||||
return
|
||||
}
|
||||
guard shouldProcessPrivatePayload(
|
||||
payload,
|
||||
senderPubkey: senderPubkey,
|
||||
recipientPubkey: id.publicKeyHex,
|
||||
envelopeKind: envelope.kind
|
||||
) else { return }
|
||||
|
||||
let convKey = PeerID(nostr_: senderPubkey)
|
||||
context.registerNostrKeyMapping(senderPubkey, for: convKey)
|
||||
|
||||
switch payload.type {
|
||||
case .privateMessage:
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(rumorTs))
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(messageTs))
|
||||
context.handlePrivateMessage(
|
||||
payload,
|
||||
senderPubkey: senderPubkey,
|
||||
@@ -372,28 +394,29 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func handleNostrMessage(_ giftWrap: NostrEvent) {
|
||||
func handleAccountPrivateEnvelope(_ envelope: NostrEvent) {
|
||||
guard let context else { return }
|
||||
// Cheap dedup pre-check only; Schnorr verification runs off-main in
|
||||
// processNostrMessage, which then does the authoritative
|
||||
// processAccountPrivateEnvelope, which then does the authoritative
|
||||
// check-and-record. Recording stays after verification so a
|
||||
// forged-signature copy can never poison the dedup set and suppress
|
||||
// the genuine event.
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) { return }
|
||||
if context.hasProcessedNostrEvent(envelope.id) { return }
|
||||
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
await self?.processNostrMessage(giftWrap)
|
||||
await self?.processAccountPrivateEnvelope(envelope)
|
||||
}
|
||||
}
|
||||
|
||||
func processNostrMessage(_ giftWrap: NostrEvent) async {
|
||||
guard giftWrap.isValidSignature() else { return }
|
||||
func processAccountPrivateEnvelope(_ envelope: NostrEvent) async {
|
||||
guard envelope.content.utf8.count <= NostrProtocol.maximumPrivateEnvelopeCiphertextBytes else { return }
|
||||
guard envelope.isValidSignature() else { return }
|
||||
guard let context else { return }
|
||||
// Authoritative check-and-record, atomic on the main actor so two
|
||||
// concurrent detached tasks can't both process the same event.
|
||||
let alreadyProcessed: Bool = await MainActor.run {
|
||||
if context.hasProcessedNostrEvent(giftWrap.id) { return true }
|
||||
context.recordProcessedNostrEvent(giftWrap.id)
|
||||
if context.hasProcessedNostrEvent(envelope.id) { return true }
|
||||
context.recordProcessedNostrEvent(envelope.id)
|
||||
return false
|
||||
}
|
||||
if alreadyProcessed { return }
|
||||
@@ -403,8 +426,8 @@ final class NostrInboundPipeline {
|
||||
guard let currentIdentity else { return }
|
||||
|
||||
do {
|
||||
let (content, senderPubkey, rumorTimestamp) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
let (content, senderPubkey, messageTimestampSeconds) = try NostrProtocol.decryptPrivateEnvelope(
|
||||
envelope: envelope,
|
||||
recipientIdentity: currentIdentity
|
||||
)
|
||||
|
||||
@@ -428,8 +451,14 @@ final class NostrInboundPipeline {
|
||||
|
||||
if packet.type == MessageType.noiseEncrypted.rawValue,
|
||||
let payload = NoisePayload.decode(packet.payload) {
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(rumorTimestamp))
|
||||
let messageTimestamp = Date(timeIntervalSince1970: TimeInterval(messageTimestampSeconds))
|
||||
await MainActor.run {
|
||||
guard self.shouldProcessPrivatePayload(
|
||||
payload,
|
||||
senderPubkey: senderPubkey,
|
||||
recipientPubkey: currentIdentity.publicKeyHex,
|
||||
envelopeKind: envelope.kind
|
||||
) else { return }
|
||||
context.registerNostrKeyMapping(senderPubkey, for: targetPeerID)
|
||||
|
||||
switch payload.type {
|
||||
@@ -503,6 +532,47 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
|
||||
private extension NostrInboundPipeline {
|
||||
@MainActor
|
||||
func shouldProcessPrivatePayload(
|
||||
_ payload: NoisePayload,
|
||||
senderPubkey: String,
|
||||
recipientPubkey: String,
|
||||
envelopeKind: Int
|
||||
) -> Bool {
|
||||
let digest = payload.encode().sha256Fingerprint()
|
||||
let key = "\(recipientPubkey.lowercased()):\(senderPubkey.lowercased()):\(digest)"
|
||||
let formatBit: UInt8
|
||||
switch envelopeKind {
|
||||
case NostrProtocol.EventKind.privateEnvelope.rawValue:
|
||||
formatBit = 1 << 0
|
||||
case NostrProtocol.EventKind.legacyNIP59GiftWrap.rawValue:
|
||||
formatBit = 1 << 1
|
||||
default:
|
||||
return true
|
||||
}
|
||||
|
||||
if let observedFormats = recentPrivatePayloadFormats[key] {
|
||||
if observedFormats & formatBit != 0 {
|
||||
// A same-format re-envelope is a delivery retry. Let it reach
|
||||
// the coordinator so a lost DELIVERED acknowledgement can be
|
||||
// sent again; downstream message-ID dedup prevents rerendering.
|
||||
return true
|
||||
}
|
||||
// The same authenticated payload under the other migration format
|
||||
// is the compatibility twin, not a new message or acknowledgement.
|
||||
recentPrivatePayloadFormats[key] = observedFormats | formatBit
|
||||
return false
|
||||
}
|
||||
|
||||
recentPrivatePayloadFormats[key] = formatBit
|
||||
recentPrivatePayloadKeyOrder.append(key)
|
||||
if recentPrivatePayloadKeyOrder.count > Self.privatePayloadDedupCapacity {
|
||||
let evicted = recentPrivatePayloadKeyOrder.removeFirst()
|
||||
recentPrivatePayloadFormats.removeValue(forKey: evicted)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@MainActor
|
||||
static func decodeEmbeddedBitChatPacket(from content: String) -> BitchatPacket? {
|
||||
guard content.hasPrefix("bitchat1:") else { return nil }
|
||||
|
||||
@@ -504,7 +504,8 @@ private struct ContentPrivateChatSheetView: View {
|
||||
if privateConversationModel.selectedPeerID?.isGroup == true {
|
||||
return String(localized: "content.private.caption_group", comment: "Caption above the group chat composer noting messages are encrypted to group members")
|
||||
}
|
||||
// Geohash DMs are NIP-17 gift-wrapped — always end-to-end encrypted,
|
||||
// Geohash DMs use BitChat's private-envelope transport over Nostr —
|
||||
// always end-to-end encrypted,
|
||||
// even though they carry no Noise session status. Mesh DMs earn the
|
||||
// "encrypted" claim only once the Noise handshake has secured.
|
||||
let isGeoDM = privateConversationModel.selectedPeerID?.isGeoDM == true
|
||||
|
||||
Reference in New Issue
Block a user