From b9164dbf5a7aaa13fbb65df921f92ef0b27783dc Mon Sep 17 00:00:00 2001 From: jack <212554440+jackjackbits@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:13:00 -1000 Subject: [PATCH] Address Codex review findings from #1967: authenticate group Nostr routes, wire contact invites, and track outbox retries per member (#1968) Co-authored-by: jack --- .../Services/Groups/GroupOutboxStore.swift | 88 +++++++++-- bitchat/Services/Groups/GroupProtocol.swift | 141 ++++++++++++++++-- bitchat/ViewModels/ChatGroupCoordinator.swift | 87 ++++++++--- .../ChatGroupCoordinatorContextTests.swift | 114 ++++++++++++-- .../Services/GroupProtocolTests.swift | 73 ++++++++- 5 files changed, 447 insertions(+), 56 deletions(-) diff --git a/bitchat/Services/Groups/GroupOutboxStore.swift b/bitchat/Services/Groups/GroupOutboxStore.swift index d0a654e4..7d5ac54d 100644 --- a/bitchat/Services/Groups/GroupOutboxStore.swift +++ b/bitchat/Services/Groups/GroupOutboxStore.swift @@ -30,8 +30,21 @@ final class GroupOutboxStore { /// True once at least one Nostr relay confirmed `OK` for any member. var hadAnyNostrConfirmation: Bool let createdAt: Date - /// Delivery attempts made while a DM relay was connected. - var sendAttempts: Int + /// Delivery attempts made per pending member while a DM relay was connected. + var attemptsByMember: [String: Int] + + private enum CodingKeys: String, CodingKey { + case groupID + case messageID + case payload + case pendingMemberFingerprints + case hadMeshDeliveryAtSend + case hadAnyNostrConfirmation + case createdAt + case attemptsByMember + /// Legacy entry-wide attempt counter decoded for backwards compatibility. + case sendAttempts + } init( groupID: Data, @@ -41,7 +54,7 @@ final class GroupOutboxStore { hadMeshDeliveryAtSend: Bool, hadAnyNostrConfirmation: Bool = false, createdAt: Date, - sendAttempts: Int = 0 + attemptsByMember: [String: Int] = [:] ) { self.groupID = groupID self.messageID = messageID @@ -50,7 +63,40 @@ final class GroupOutboxStore { self.hadMeshDeliveryAtSend = hadMeshDeliveryAtSend self.hadAnyNostrConfirmation = hadAnyNostrConfirmation self.createdAt = createdAt - self.sendAttempts = sendAttempts + self.attemptsByMember = attemptsByMember + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + groupID = try container.decode(Data.self, forKey: .groupID) + messageID = try container.decode(String.self, forKey: .messageID) + payload = try container.decode(Data.self, forKey: .payload) + pendingMemberFingerprints = try container.decode(Set.self, forKey: .pendingMemberFingerprints) + hadMeshDeliveryAtSend = try container.decode(Bool.self, forKey: .hadMeshDeliveryAtSend) + hadAnyNostrConfirmation = try container.decode(Bool.self, forKey: .hadAnyNostrConfirmation) + createdAt = try container.decode(Date.self, forKey: .createdAt) + if let perMember = try container.decodeIfPresent([String: Int].self, forKey: .attemptsByMember) { + attemptsByMember = perMember + } else if let legacyAttempts = try container.decodeIfPresent(Int.self, forKey: .sendAttempts), + legacyAttempts > 0 { + attemptsByMember = Dictionary( + uniqueKeysWithValues: pendingMemberFingerprints.map { ($0, legacyAttempts) } + ) + } else { + attemptsByMember = [:] + } + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(groupID, forKey: .groupID) + try container.encode(messageID, forKey: .messageID) + try container.encode(payload, forKey: .payload) + try container.encode(pendingMemberFingerprints, forKey: .pendingMemberFingerprints) + try container.encode(hadMeshDeliveryAtSend, forKey: .hadMeshDeliveryAtSend) + try container.encode(hadAnyNostrConfirmation, forKey: .hadAnyNostrConfirmation) + try container.encode(createdAt, forKey: .createdAt) + try container.encode(attemptsByMember, forKey: .attemptsByMember) } } @@ -131,6 +177,7 @@ final class GroupOutboxStore { guard entry.pendingMemberFingerprints.remove(memberFingerprint) != nil else { return (entry, false) } + entry.attemptsByMember.removeValue(forKey: memberFingerprint) let wasFirstNostrConfirm = !entry.hadAnyNostrConfirmation entry.hadAnyNostrConfirmation = true let remaining: Entry? @@ -145,18 +192,32 @@ final class GroupOutboxStore { return (remaining, wasFirstNostrConfirm) } - /// Increments `sendAttempts` for a confirmed-relay attempt. Drops and - /// returns the entry if it reached `maxSendAttempts`. + /// Increments the confirmed-relay failure count for `memberFingerprint`. + /// Removes that member from `pendingMemberFingerprints` once they reach + /// `maxSendAttempts`, and drops/returns the whole entry only when no + /// pending recipients remain so a single transient relay failure never + /// exhausts the retry budget for a large group. @discardableResult - func recordRelayAttemptFailure(messageID: String, groupID: Data) -> Entry? { - guard let idx = entries.firstIndex(where: { $0.groupID == groupID && $0.messageID == messageID }) else { + func recordRelayAttemptFailure( + messageID: String, + groupID: Data, + memberFingerprint: String + ) -> Entry? { + guard let idx = entries.firstIndex(where: { $0.groupID == groupID && $0.messageID == messageID }), + entries[idx].pendingMemberFingerprints.contains(memberFingerprint) else { return nil } - entries[idx].sendAttempts += 1 - if entries[idx].sendAttempts >= Self.maxSendAttempts { - let dropped = entries.remove(at: idx) - persist() - return dropped + let nextAttempts = (entries[idx].attemptsByMember[memberFingerprint] ?? 0) + 1 + if nextAttempts >= Self.maxSendAttempts { + entries[idx].pendingMemberFingerprints.remove(memberFingerprint) + entries[idx].attemptsByMember.removeValue(forKey: memberFingerprint) + if entries[idx].pendingMemberFingerprints.isEmpty { + let dropped = entries.remove(at: idx) + persist() + return dropped + } + } else { + entries[idx].attemptsByMember[memberFingerprint] = nextAttempts } persist() return nil @@ -187,6 +248,7 @@ final class GroupOutboxStore { if filteredMembers.count != entry.pendingMemberFingerprints.count { changed = true entry.pendingMemberFingerprints = filteredMembers + entry.attemptsByMember = entry.attemptsByMember.filter { filteredMembers.contains($0.key) } } if entry.pendingMemberFingerprints.isEmpty { changed = true diff --git a/bitchat/Services/Groups/GroupProtocol.swift b/bitchat/Services/Groups/GroupProtocol.swift index 143c3dca..31c31117 100644 --- a/bitchat/Services/Groups/GroupProtocol.swift +++ b/bitchat/Services/Groups/GroupProtocol.swift @@ -11,8 +11,10 @@ // import BitFoundation +import BitSecp256k1 import CryptoKit import Foundation +import Security // MARK: - Models @@ -520,6 +522,24 @@ enum GroupCryptoError: Error, Equatable { enum GroupCrypto { static let messageSigningDomain = Data("bitchat-group-msg-v1".utf8) + static let nostrBindingDomain = Data("bitchat-group-nostr-bind-v1".utf8) + + /// Bidirectional cryptographic proof binding a group member's pinned Ed25519 + /// `senderSigningKey` to their x-only Nostr public key: + /// - `ed25519Signature` (by `senderSigningKey`): stops any other group member + /// who knows the shared epoch key from tampering with or injecting a route + /// into a decrypted message. + /// - `schnorrSignature` (by `nostrPubkey`): stops a malicious member from + /// claiming another user's Nostr public key under their own signing key. + struct SignedNostrBinding: Equatable { + let nostrPubkey: Data + let ed25519Signature: Data + let schnorrSignature: Data + + var nostrPubkeyHex: String { + nostrPubkey.hexEncodedString().lowercased() + } + } private enum InnerField: UInt8 { case messageID = 0x01 @@ -529,7 +549,83 @@ enum GroupCrypto { case content = 0x05 case signature = 0x06 /// Optional 32-byte raw x-only Nostr public key (ignored by legacy clients). + /// Accepted on open only when paired with valid `0x08` + `0x09` proofs. case senderNostrPubkey = 0x07 + /// 64-byte Ed25519 signature by `senderSigningKey` over `nostrBindingContent`. + case senderNostrSigningSig = 0x08 + /// 64-byte BIP-340 Schnorr signature by `senderNostrPubkey` over `SHA256(nostrBindingContent)`. + case senderNostrSchnorrSig = 0x09 + } + + /// Domain-separated preimage proving a bidirectional binding between a + /// member's Ed25519 group signing key and their x-only Nostr public key. + static func nostrBindingContent(senderSigningKey: Data, nostrPubkey: Data) -> Data { + var data = nostrBindingDomain + data.append(senderSigningKey) + data.append(nostrPubkey) + return data + } + + /// Creates a bidirectional Ed25519 + BIP-340 Schnorr binding proof for + /// embedding in sealed group messages. + static func makeSignedNostrBinding( + senderSigningKey: Data, + nostrIdentity: NostrIdentity, + signWithEd25519: (Data) -> Data? + ) -> SignedNostrBinding? { + guard senderSigningKey.count == 32, + let nostrPubkey = Data(hexString: nostrIdentity.publicKeyHex), + nostrPubkey.count == 32, + let schnorrKey = try? nostrIdentity.schnorrSigningKey() else { + return nil + } + let bindingContent = nostrBindingContent( + senderSigningKey: senderSigningKey, + nostrPubkey: nostrPubkey + ) + guard let ed25519Sig = signWithEd25519(bindingContent), ed25519Sig.count == 64 else { + return nil + } + var auxRand = [UInt8](repeating: 0, count: 32) + guard SecRandomCopyBytes(kSecRandomDefault, auxRand.count, &auxRand) == errSecSuccess else { + return nil + } + let digest = Data(SHA256.hash(data: bindingContent)) + guard let schnorrSig = try? schnorrKey.sign(message: Array(digest), auxiliaryRand: auxRand), + schnorrSig.count == 64 else { + return nil + } + return SignedNostrBinding( + nostrPubkey: nostrPubkey, + ed25519Signature: ed25519Sig, + schnorrSignature: schnorrSig + ) + } + + /// Verifies both directions of a group sender's Nostr binding proof. + static func verifySignedNostrBinding( + _ binding: SignedNostrBinding, + senderSigningKey: Data + ) -> Bool { + guard senderSigningKey.count == 32, + binding.nostrPubkey.count == 32, + binding.ed25519Signature.count == 64, + binding.schnorrSignature.count == 64 else { + return false + } + let bindingContent = nostrBindingContent( + senderSigningKey: senderSigningKey, + nostrPubkey: binding.nostrPubkey + ) + guard verify(signature: binding.ed25519Signature, for: bindingContent, publicKey: senderSigningKey) else { + return false + } + let digest = Data(SHA256.hash(data: bindingContent)) + return BitSecp256k1.verifySchnorr( + signature: binding.schnorrSignature, + message: Array(digest), + xonlyPublicKey: binding.nostrPubkey + ) } /// Bytes the sender signs: domain | groupID | epoch | messageID | timestamp | content. @@ -560,7 +656,7 @@ enum GroupCrypto { messageID: String, senderNickname: String, senderSigningKey: Data, - senderNostrPubkeyHex: String? = nil, + senderNostrBinding: SignedNostrBinding? = nil, timestampMs: UInt64, groupID: Data, epoch: UInt32, @@ -585,11 +681,13 @@ enum GroupCrypto { try GroupTLV.put(InnerField.timestamp.rawValue, GroupTLV.timestampData(timestampMs), into: &inner) try GroupTLV.put(InnerField.content.rawValue, Data(content.utf8), into: &inner) try GroupTLV.put(InnerField.signature.rawValue, signature, into: &inner) - if let hex = senderNostrPubkeyHex?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(), - hex.count == 64, - let nostrKeyBytes = Data(hexString: hex), - nostrKeyBytes.count == 32 { - try GroupTLV.put(InnerField.senderNostrPubkey.rawValue, nostrKeyBytes, into: &inner) + if let binding = senderNostrBinding, + binding.nostrPubkey.count == 32, + binding.ed25519Signature.count == 64, + binding.schnorrSignature.count == 64 { + try GroupTLV.put(InnerField.senderNostrPubkey.rawValue, binding.nostrPubkey, into: &inner) + try GroupTLV.put(InnerField.senderNostrSigningSig.rawValue, binding.ed25519Signature, into: &inner) + try GroupTLV.put(InnerField.senderNostrSchnorrSig.rawValue, binding.schnorrSignature, into: &inner) } do { @@ -638,7 +736,9 @@ enum GroupCrypto { var timestampMs: UInt64? var content: String? var signature: Data? - var senderNostrPubkeyHex: String? + var senderNostrPubkeyBytes: Data? + var senderNostrSigningSig: Data? + var senderNostrSchnorrSig: Data? for (type, value) in fields { switch InnerField(rawValue: type) { case .messageID: @@ -654,7 +754,11 @@ enum GroupCrypto { case .signature where value.count == 64: signature = value case .senderNostrPubkey where value.count == 32: - senderNostrPubkeyHex = value.hexEncodedString().lowercased() + senderNostrPubkeyBytes = value + case .senderNostrSigningSig where value.count == 64: + senderNostrSigningSig = value + case .senderNostrSchnorrSig where value.count == 64: + senderNostrSchnorrSig = value default: break } @@ -677,13 +781,32 @@ enum GroupCrypto { throw GroupCryptoError.badSenderSignature } + // Only expose a learned Nostr route when backed by a valid bidirectional + // Ed25519 + BIP-340 Schnorr proof so another group member who knows the + // epoch key cannot inject or substitute a Nostr pubkey. + let verifiedNostrPubkeyHex: String? + if let nostrBytes = senderNostrPubkeyBytes, + let edSig = senderNostrSigningSig, + let schnorrSig = senderNostrSchnorrSig { + let binding = SignedNostrBinding( + nostrPubkey: nostrBytes, + ed25519Signature: edSig, + schnorrSignature: schnorrSig + ) + verifiedNostrPubkeyHex = verifySignedNostrBinding(binding, senderSigningKey: senderSigningKey) + ? binding.nostrPubkeyHex + : nil + } else { + verifiedNostrPubkeyHex = nil + } + return GroupMessagePlaintext( messageID: messageID, senderSigningKey: senderSigningKey, senderNickname: senderNickname, timestampMs: timestampMs, content: content, - senderNostrPubkeyHex: senderNostrPubkeyHex + senderNostrPubkeyHex: verifiedNostrPubkeyHex ) } } diff --git a/bitchat/ViewModels/ChatGroupCoordinator.swift b/bitchat/ViewModels/ChatGroupCoordinator.swift index f81be645..47cfa190 100644 --- a/bitchat/ViewModels/ChatGroupCoordinator.swift +++ b/bitchat/ViewModels/ChatGroupCoordinator.swift @@ -43,6 +43,8 @@ protocol ChatGroupContext: AnyObject { func nostrReachablePeerID(forFingerprint fingerprint: String) -> PeerID? /// Our own 64-hex x-only Nostr public key, if initialized. func myNostrPubkeyHex() -> String? + /// Our own Nostr identity (used to sign bidirectional group Nostr route proofs). + func currentNostrIdentity() -> NostrIdentity? /// Known 64-hex x-only Nostr public key for a peer fingerprint, if any. func nostrPubkeyHex(forFingerprint fingerprint: String) -> String? /// Whether the user has blocked the identity with this Noise fingerprint. @@ -83,6 +85,7 @@ extension ChatGroupContext { func senderNostrPubkeyHex(for peerID: PeerID) -> String? { nil } func nostrReachablePeerID(forFingerprint fingerprint: String) -> PeerID? { nil } func myNostrPubkeyHex() -> String? { nil } + func currentNostrIdentity() -> NostrIdentity? { nil } func nostrPubkeyHex(forFingerprint fingerprint: String) -> String? { nil } func isNostrDMRelayConnected() -> Bool { true } func sendGroupInviteViaNostr(_ payload: Data, to peerID: PeerID) {} @@ -162,6 +165,11 @@ extension ChatViewModel: ChatGroupContext { noiseKey.sha256Fingerprint() == fingerprint else { continue } return PeerID(hexData: noiseKey) } + for (noiseKey, route) in nostrPeerRouteStore.routes where noiseKey.sha256Fingerprint() == fingerprint { + guard !identityManager.isBlocked(fingerprint: fingerprint), + !identityManager.isNostrBlocked(pubkeyHexLowercased: route.nostrPubkeyHex) else { continue } + return PeerID(hexData: noiseKey) + } return nil } @@ -173,8 +181,8 @@ extension ChatViewModel: ChatGroupContext { if fingerprint == myNoiseFingerprint() { return myNostrPubkeyHex() } - // Prefer mutual favorites, then fall back to any stored favorite with - // a validated Nostr pubkey (e.g. one-sided favorite / friend invite). + // Prefer mutual favorites, then verified mutual-DM contact routes, then + // any stored favorite with a validated Nostr pubkey (e.g. friend invite). var fallbackHex: String? for (noiseKey, rel) in FavoritesPersistenceService.shared.favorites { guard noiseKey.sha256Fingerprint() == fingerprint, @@ -184,6 +192,11 @@ extension ChatViewModel: ChatGroupContext { } fallbackHex = fallbackHex ?? hex } + for (noiseKey, route) in nostrPeerRouteStore.routes where noiseKey.sha256Fingerprint() == fingerprint { + guard !identityManager.isBlocked(fingerprint: fingerprint), + !identityManager.isNostrBlocked(pubkeyHexLowercased: route.nostrPubkeyHex) else { continue } + return route.nostrPubkeyHex + } return fallbackHex } @@ -299,6 +312,9 @@ final class ChatGroupCoordinator { private var inFlightDeliveries: Set = [] private var retryTask: Task? private var wipeGeneration: UInt64 = 0 + /// Cached bidirectional Ed25519 + BIP-340 Schnorr proof binding our current + /// signing key and Nostr identity, regenerated whenever either key changes. + private var cachedSignedNostrBinding: (signingKey: Data, nostrPubkeyHex: String, binding: GroupCrypto.SignedNostrBinding)? init(context: any ChatGroupContext) { self.context = context @@ -313,6 +329,7 @@ final class ChatGroupCoordinator { retryTask?.cancel() retryTask = nil inFlightDeliveries.removeAll() + cachedSignedNostrBinding = nil context.groupOutboxStore?.wipe() } @@ -379,7 +396,8 @@ final class ChatGroupCoordinator { } let meshReachable = context.isPeerConnected(peerID) let nostrPeerID = context.nostrReachablePeerID(forFingerprint: identity.fingerprint) - guard meshReachable || nostrPeerID != nil else { + let nostrPubkeyHex = context.nostrPubkeyHex(forFingerprint: identity.fingerprint) + guard meshReachable || nostrPeerID != nil || nostrPubkeyHex != nil else { return .error(message: String( format: String(localized: "system.group.peer_not_connected", comment: "Error when the invitee is not connected over mesh; placeholder is the nickname"), locale: .current, @@ -405,7 +423,7 @@ final class ChatGroupCoordinator { fingerprint: identity.fingerprint, signingKey: identity.signingKey, nickname: context.peerNickname(for: peerID) ?? nickname, - nostrPubkeyHex: context.nostrPubkeyHex(forFingerprint: identity.fingerprint) + nostrPubkeyHex: nostrPubkeyHex ) // Rotate the key (epoch + 1) on every roster change, not just removals. // A monotonically increasing epoch per roster gives the receiver a @@ -422,6 +440,8 @@ final class ChatGroupCoordinator { } if let nostrPeerID { context.sendGroupInviteViaNostr(payload, to: nostrPeerID) + } else if let nostrPubkeyHex { + context.sendGroupInviteViaNostr(payload, toPubkeyHex: nostrPubkeyHex) } distributeState(payload, group: updated, excluding: [identity.fingerprint], type: .keyUpdate) @@ -530,7 +550,7 @@ final class ChatGroupCoordinator { messageID: messageID, senderNickname: context.nickname, senderSigningKey: context.mySigningPublicKey(), - senderNostrPubkeyHex: context.myNostrPubkeyHex(), + senderNostrBinding: currentSignedNostrBinding(), timestampMs: UInt64(timestamp.timeIntervalSince1970 * 1000), groupID: group.groupID, epoch: group.epoch, @@ -655,7 +675,8 @@ final class ChatGroupCoordinator { // the entry intact for reconnect. if let dropped = outboxStore.recordRelayAttemptFailure( messageID: entry.messageID, - groupID: entry.groupID + groupID: entry.groupID, + memberFingerprint: memberFingerprint ) { if !dropped.hadMeshDeliveryAtSend && !dropped.hadAnyNostrConfirmation { self.markGroupMessageFailed(dropped.messageID) @@ -738,7 +759,8 @@ final class ChatGroupCoordinator { } let meshPeerID = context.connectedPeerID(forFingerprint: identity.fingerprint) let nostrPeerID = context.nostrReachablePeerID(forFingerprint: identity.fingerprint) - guard meshPeerID != nil || nostrPeerID != nil else { + let nostrPubkeyHex = context.nostrPubkeyHex(forFingerprint: identity.fingerprint) + guard meshPeerID != nil || nostrPeerID != nil || nostrPubkeyHex != nil else { return .error(message: String( format: String(localized: "system.group.peer_not_connected", comment: "Error when the invitee is not connected over mesh; placeholder is the nickname"), locale: .current, @@ -764,7 +786,7 @@ final class ChatGroupCoordinator { fingerprint: identity.fingerprint, signingKey: identity.signingKey, nickname: displayName, - nostrPubkeyHex: context.nostrPubkeyHex(forFingerprint: identity.fingerprint) + nostrPubkeyHex: nostrPubkeyHex ) let members = enrichedRoutingMembers(group.members + [newMember]) guard let (updated, key) = context.groupStore.rotateKey(groupID: group.groupID, members: members), @@ -777,6 +799,8 @@ final class ChatGroupCoordinator { } if let nostrPeerID { context.sendGroupInviteViaNostr(payload, to: nostrPeerID) + } else if let nostrPubkeyHex { + context.sendGroupInviteViaNostr(payload, toPubkeyHex: nostrPubkeyHex) } distributeState(payload, group: updated, excluding: [identity.fingerprint], type: .keyUpdate) return .success(message: String( @@ -868,16 +892,23 @@ final class ChatGroupCoordinator { return } - // Learn the sender's Nostr pubkey from inside the encrypted group - // envelope so BLE-formed groups seamlessly gain Nostr delivery without - // requiring manual 1:1 mutual favoriting. - if let learnedNostrHex = plaintext.senderNostrPubkeyHex, - context.groupStore.updateMemberNostrPubkeys( - groupID: group.groupID, - updates: [member.fingerprint: learnedNostrHex], - overwriteExisting: false - ) { - flushPendingNostrDeliveries() + // Learn the sender's cryptographically bound Nostr pubkey from inside + // the encrypted group envelope so BLE-formed groups seamlessly gain + // Nostr delivery without allowing another group member to substitute + // or hijack routes. + if let learnedNostrHex = plaintext.senderNostrPubkeyHex { + let claimedByAnotherMember = group.members.contains { + $0.fingerprint != member.fingerprint + && FavoritesPersistenceService.nostrPubkeyHex(from: $0.nostrPubkeyHex) == learnedNostrHex + } + if !claimedByAnotherMember, + context.groupStore.updateMemberNostrPubkeys( + groupID: group.groupID, + updates: [member.fingerprint: learnedNostrHex], + overwriteExisting: false + ) { + flushPendingNostrDeliveries() + } } let groupPeerID = group.peerID @@ -949,6 +980,26 @@ private extension ChatGroupCoordinator { return FavoritesPersistenceService.nostrPubkeyHex(from: member.nostrPubkeyHex) } + func currentSignedNostrBinding() -> GroupCrypto.SignedNostrBinding? { + guard let identity = context.currentNostrIdentity() else { return nil } + let signingKey = context.mySigningPublicKey() + let normalizedHex = identity.publicKeyHex.lowercased() + if let cached = cachedSignedNostrBinding, + cached.signingKey == signingKey, + cached.nostrPubkeyHex == normalizedHex { + return cached.binding + } + guard let binding = GroupCrypto.makeSignedNostrBinding( + senderSigningKey: signingKey, + nostrIdentity: identity, + signWithEd25519: { [weak context] data in context?.signWithNoiseKey(data) } + ) else { + return nil + } + cachedSignedNostrBinding = (signingKey, normalizedHex, binding) + return binding + } + func markGroupMessageFailed(_ messageID: String) { context.setPrivateMessageDeliveryStatus( .failed(reason: String(localized: "content.delivery.reason.not_delivered", comment: "Failure reason shown when the router gave up delivering a message")), diff --git a/bitchatTests/ChatGroupCoordinatorContextTests.swift b/bitchatTests/ChatGroupCoordinatorContextTests.swift index 24203f7e..92c35ab2 100644 --- a/bitchatTests/ChatGroupCoordinatorContextTests.swift +++ b/bitchatTests/ChatGroupCoordinatorContextTests.swift @@ -43,29 +43,36 @@ private final class MockChatGroupContext: ChatGroupContext { var fingerprintsByPeerID: [PeerID: String] = [:] var senderNostrPubkeysByPeerID: [PeerID: String] = [:] var nostrPubkeyHexByFingerprint: [String: String] = [:] - var ownNostrPubkeyHex: String? + var cryptoIdentitiesByPeerID: [PeerID: (fingerprint: String, signingKey: Data)] = [:] + var peerNicknamesByPeerID: [PeerID: String] = [:] + var ownNostrIdentity: NostrIdentity? var blockedFingerprints: Set = [] var dmRelayConnected = true func getPeerIDForNickname(_ nickname: String) -> PeerID? { nil } func isPeerConnected(_ peerID: PeerID) -> Bool { false } - func peerNickname(for peerID: PeerID) -> String? { nil } + func peerNickname(for peerID: PeerID) -> String? { peerNicknamesByPeerID[peerID] } func meshFingerprint(for peerID: PeerID) -> String? { fingerprintsByPeerID[peerID] } func senderNostrPubkeyHex(for peerID: PeerID) -> String? { senderNostrPubkeysByPeerID[peerID] } - func cryptoIdentity(for peerID: PeerID) -> (fingerprint: String, signingKey: Data)? { nil } + func cryptoIdentity(for peerID: PeerID) -> (fingerprint: String, signingKey: Data)? { cryptoIdentitiesByPeerID[peerID] } func connectedPeerID(forFingerprint fingerprint: String) -> PeerID? { nil } - func myNostrPubkeyHex() -> String? { ownNostrPubkeyHex } + func myNostrPubkeyHex() -> String? { ownNostrIdentity?.publicKeyHex } + func currentNostrIdentity() -> NostrIdentity? { ownNostrIdentity } func nostrPubkeyHex(forFingerprint fingerprint: String) -> String? { nostrPubkeyHexByFingerprint[fingerprint] } func isFingerprintBlocked(_ fingerprint: String) -> Bool { blockedFingerprints.contains(fingerprint) } func isNostrDMRelayConnected() -> Bool { dmRelayConnected } // Transport + private(set) var sentNostrInvitesByPubkey: [(payload: Data, pubkeyHex: String)] = [] private(set) var confirmedNostrSends: [(payload: Data, pubkeyHex: String)] = [] var confirmedNostrHandler: ((Data, String, @escaping @MainActor (Bool) -> Void) -> Void)? func sendGroupInvitePayload(_ payload: Data, to peerID: PeerID) {} func sendGroupKeyUpdatePayload(_ payload: Data, to peerID: PeerID) {} func broadcastGroupMessagePayload(_ payload: Data) {} + func sendGroupInviteViaNostr(_ payload: Data, toPubkeyHex pubkeyHex: String) { + sentNostrInvitesByPubkey.append((payload, pubkeyHex)) + } func sendGroupMessageViaNostrConfirmed( _ payload: Data, toPubkeyHex pubkeyHex: String, @@ -98,7 +105,7 @@ private final class MockChatGroupContext: ChatGroupContext { } func markPrivateChatUnread(_ peerID: PeerID) { unreadMarkedPeers.append(peerID) } func removePrivateChat(_ peerID: PeerID) { removedPrivateChats.append(peerID) } - func startPrivateChat(with peerID: PeerID) {} + func startPrivateChat(with peerID: PeerID) { selectedPrivateChatPeer = peerID } func endPrivateChat() { endPrivateChatCount += 1 } func addSystemMessage(_ content: String) { systemMessages.append(content) } func addLocalPrivateSystemMessage(_ content: String, to peerID: PeerID) {} @@ -430,8 +437,9 @@ struct ChatGroupCoordinatorContextTests { let creatorNostrHex = String(repeating: "11", count: 32) let memberNostrHex = String(repeating: "22", count: 32) + let ownNostr = try NostrIdentity.generate() let context = MockChatGroupContext(identity: me) - context.ownNostrPubkeyHex = String(repeating: "33", count: 32) + context.ownNostrIdentity = ownNostr context.groupOutboxStore = GroupOutboxStore(keychain: outboxKeychain, persistsToDisk: true, fileURL: outboxURL) context.dmRelayConnected = false @@ -472,11 +480,11 @@ struct ChatGroupCoordinatorContextTests { #expect(reloadedOutbox.entries.isEmpty) #expect(context.deliveryStatusUpdates.contains { $0.messageID == echoed.id && $0.status == .sent }) - // Sealed payload also carries our own Nostr pubkey for automatic discovery. + // Sealed payload also carries our bidirectionally signed Nostr binding for automatic discovery. let sentPayload = try #require(context.confirmedNostrSends.first?.payload) let sentEnvelope = try #require(GroupMessageEnvelope.decode(sentPayload)) let opened = try GroupCrypto.openMessage(sentEnvelope, key: groupKey) - #expect(opened.senderNostrPubkeyHex == context.ownNostrPubkeyHex) + #expect(opened.senderNostrPubkeyHex == ownNostr.publicKeyHex.lowercased()) } @Test @@ -490,14 +498,20 @@ struct ChatGroupCoordinatorContextTests { #expect(context.confirmedNostrSends.isEmpty) #expect(context.groupOutboxStore?.entries.count == 1) - // Member sends a message containing their Nostr pubkey inside the encrypted group payload. - let learnedMemberHex = String(repeating: "aa", count: 32) + // Member sends a message containing their bidirectionally signed Nostr binding. + let memberNostr = try NostrIdentity.generate() + let learnedMemberHex = memberNostr.publicKeyHex.lowercased() + let memberBinding = try #require(GroupCrypto.makeSignedNostrBinding( + senderSigningKey: member.member.signingKey, + nostrIdentity: memberNostr, + signWithEd25519: member.sign + )) let incomingPayload = try GroupCrypto.sealMessage( content: "hey!", messageID: "member-hello-1", senderNickname: member.nickname, senderSigningKey: member.member.signingKey, - senderNostrPubkeyHex: learnedMemberHex, + senderNostrBinding: memberBinding, timestampMs: UInt64(Date().timeIntervalSince1970 * 1000), groupID: joined.groupID, epoch: joined.epoch, @@ -551,4 +565,82 @@ struct ChatGroupCoordinatorContextTests { #expect(context.groupStore.key(forGroupID: groupID) == rotatedKey) #expect(updated.members.first(where: { $0.fingerprint == member.fingerprint })?.nostrPubkeyHex == learnedMemberHex) } + + @Test + func inviteMember_usesLearnedNostrContactRouteWhenPeerIsOfflineAndNotFavorite() throws { + let context = MockChatGroupContext(identity: creator) + let coordinator = ChatGroupCoordinator(context: context) + let contactNostrHex = String(repeating: "ef", count: 32) + let contactPeerID = PeerID(str: String(member.fingerprint.prefix(16))) + + // Contact is offline on BLE and NOT a mutual favorite (`nostrReachablePeerID` is nil), + // only known via learned contact route (`nostrPubkeyHex(forFingerprint:)`). + context.cryptoIdentitiesByPeerID[contactPeerID] = (member.fingerprint, member.member.signingKey) + context.peerNicknamesByPeerID[contactPeerID] = member.nickname + context.nostrPubkeyHexByFingerprint[member.fingerprint] = contactNostrHex + + let result = coordinator.createGroup(named: "offline-crew", initialMemberPeerIDs: [contactPeerID]) + if case .error(let msg) = result { + Issue.record("Expected createGroup with learned Nostr contact to succeed, got error: \(msg)") + } + + let created = try #require(context.groupStore.groups.first) + #expect(created.members.contains { $0.fingerprint == member.fingerprint && $0.nostrPubkeyHex == contactNostrHex }) + #expect(context.sentNostrInvitesByPubkey.map(\.pubkeyHex) == [contactNostrHex]) + } + + @Test + func groupOutbox_countsFailuresPerRecipientSoLargeGroupSurvivesTransientRelayOutage() throws { + let context = MockChatGroupContext(identity: me) + let outbox = GroupOutboxStore(keychain: MockKeychain(), persistsToDisk: false) + context.groupOutboxStore = outbox + context.dmRelayConnected = true + + // 10 offline Nostr recipients (> maxSendAttempts == 8). + var rosterMembers: [GroupMember] = [me.member] + for idx in 1...10 { + let fp = String(format: "%064x", idx) + let pubkeyHex = String(format: "%064x", 0x100 + idx) + let signingKey = Curve25519.Signing.PrivateKey().publicKey.rawRepresentation + rosterMembers.append(GroupMember( + fingerprint: fp, + signingKey: signingKey, + nickname: "peer\(idx)", + nostrPubkeyHex: pubkeyHex + )) + } + let largeGroup = BitchatGroup( + groupID: groupID, + name: "big-crew", + epoch: 1, + members: rosterMembers, + creatorFingerprint: me.fingerprint + ) + #expect(context.groupStore.upsert(largeGroup, key: groupKey)) + + // First fan-out transiently fails for all 10 recipients. + var relayAccepts = false + context.confirmedNostrHandler = { _, _, completion in + completion(relayAccepts) + } + + let coordinator = ChatGroupCoordinator(context: context) + coordinator.sendGroupMessage("hello all ten!", to: largeGroup.peerID) + + // All 10 attempted once -> NONE dropped (previously the 8th failure dropped the entire entry!). + #expect(context.confirmedNostrSends.count == 10) + let remaining = try #require(outbox.entries.first) + #expect(remaining.pendingMemberFingerprints.count == 10) + #expect(remaining.attemptsByMember.values.allSatisfy { $0 == 1 }) + #expect(!context.deliveryStatusUpdates.contains { + if case .failed = $0.status { return true } + return false + }) + + // Next retry succeeds -> all 10 confirm and entry clears cleanly. + relayAccepts = true + coordinator.flushPendingNostrDeliveries() + #expect(outbox.entries.isEmpty) + #expect(context.deliveryStatusUpdates.contains { $0.status == .sent }) + } } diff --git a/bitchatTests/Services/GroupProtocolTests.swift b/bitchatTests/Services/GroupProtocolTests.swift index a964abd7..517dd50b 100644 --- a/bitchatTests/Services/GroupProtocolTests.swift +++ b/bitchatTests/Services/GroupProtocolTests.swift @@ -372,14 +372,21 @@ struct GroupProtocolTests { #expect(atEpoch1 != atEpoch2) } - @Test func sealedMessageRoundTripsOptionalSenderNostrPubkey() throws { - let nostrHex = String(repeating: "ab", count: 32) + @Test func sealedMessageRoundTripsSignedSenderNostrBindingAndRejectsTampering() throws { + let aliceNostr = try NostrIdentity.generate() + let eveNostr = try NostrIdentity.generate() + let validBinding = try #require(GroupCrypto.makeSignedNostrBinding( + senderSigningKey: creator.member.signingKey, + nostrIdentity: aliceNostr, + signWithEd25519: creator.sign + )) + let payloadWithNostr = try GroupCrypto.sealMessage( content: "hello hybrid", messageID: "msg-nostr-1", senderNickname: "alice", senderSigningKey: creator.member.signingKey, - senderNostrPubkeyHex: nostrHex, + senderNostrBinding: validBinding, timestampMs: 1_700_000_000_000, groupID: groupID, epoch: 1, @@ -389,9 +396,65 @@ struct GroupProtocolTests { let envelopeWithNostr = try #require(GroupMessageEnvelope.decode(payloadWithNostr)) let openedWithNostr = try GroupCrypto.openMessage(envelopeWithNostr, key: key) #expect(openedWithNostr.content == "hello hybrid") - #expect(openedWithNostr.senderNostrPubkeyHex == nostrHex) + #expect(openedWithNostr.senderNostrPubkeyHex == aliceNostr.publicKeyHex.lowercased()) - // Legacy messages without senderNostrPubkey still open cleanly with nil. + // Attack 1 (Codex P1): Eve has the epoch key and splices her own valid + // signed binding onto Alice's message -> Ed25519 binding fails against + // Alice's senderSigningKey, so senderNostrPubkeyHex MUST be nil. + let eveBinding = try #require(GroupCrypto.makeSignedNostrBinding( + senderSigningKey: member.member.signingKey, + nostrIdentity: eveNostr, + signWithEd25519: member.sign + )) + let splicedPayload = try GroupCrypto.sealMessage( + content: "hello hybrid", + messageID: "msg-nostr-spliced", + senderNickname: "alice", + senderSigningKey: creator.member.signingKey, + senderNostrBinding: eveBinding, + timestampMs: 1_700_000_000_000, + groupID: groupID, + epoch: 1, + key: key, + sign: creator.sign + ) + let splicedEnvelope = try #require(GroupMessageEnvelope.decode(splicedPayload)) + let openedSpliced = try GroupCrypto.openMessage(splicedEnvelope, key: key) + #expect(openedSpliced.content == "hello hybrid") + #expect(openedSpliced.senderNostrPubkeyHex == nil) + + // Attack 2: Eve signs Ed25519 claiming Alice's Nostr pubkey without + // Alice's Schnorr proof -> Schnorr verification fails -> nil. + let aliceNostrBytes = try #require(Data(hexString: aliceNostr.publicKeyHex)) + let forgedEd25519Sig = try #require(member.sign( + GroupCrypto.nostrBindingContent( + senderSigningKey: member.member.signingKey, + nostrPubkey: aliceNostrBytes + ) + )) + let forgedBinding = GroupCrypto.SignedNostrBinding( + nostrPubkey: aliceNostrBytes, + ed25519Signature: forgedEd25519Sig, + schnorrSignature: eveBinding.schnorrSignature + ) + let forgedPayload = try GroupCrypto.sealMessage( + content: "claiming victim nostr", + messageID: "msg-nostr-forged", + senderNickname: "eve", + senderSigningKey: member.member.signingKey, + senderNostrBinding: forgedBinding, + timestampMs: 1_700_000_000_002, + groupID: groupID, + epoch: 1, + key: key, + sign: member.sign + ) + let forgedEnvelope = try #require(GroupMessageEnvelope.decode(forgedPayload)) + let openedForged = try GroupCrypto.openMessage(forgedEnvelope, key: key) + #expect(openedForged.content == "claiming victim nostr") + #expect(openedForged.senderNostrPubkeyHex == nil) + + // Legacy messages without senderNostrBinding still open cleanly with nil. let payloadLegacy = try GroupCrypto.sealMessage( content: "hello legacy", messageID: "msg-legacy-1",