Reject oversized private messages before routing

Mark oversized mesh and geohash DMs as failed before handing them to a
transport. Keep the private payment success fixture within the wire limit.
This commit is contained in:
Taksh 2026-11-07 17:03:24 +05:30
parent 03861ed9ad
commit b00939b03d
4 changed files with 45 additions and 39 deletions

View File

@ -260,7 +260,6 @@ final class NostrTransport: Transport, @unchecked Sendable {
SecureLogger.debug("NostrTransport: preparing PM to \(recipientNpub.prefix(16))… id=\(messageID.prefix(8))…", category: .session)
guard let embedded = NostrEmbeddedBitChat.encodePMForNostr(content: content, messageID: messageID, recipientPeerID: peerID, senderPeerID: senderPeerID) else {
SecureLogger.error("NostrTransport: failed to embed PM packet", category: .session)
reportPrivateMessageSendFailure(messageID)
return
}
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity)
@ -319,7 +318,6 @@ extension NostrTransport {
SecureLogger.debug("GeoDM: send PM mid=\(messageID.prefix(8))…", category: .session)
guard let embedded = NostrEmbeddedBitChat.encodePMForNostrNoRecipient(content: content, messageID: messageID) else {
SecureLogger.error("NostrTransport: failed to embed geohash PM packet", category: .session)
reportPrivateMessageSendFailure(messageID)
return
}
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
@ -330,21 +328,6 @@ extension NostrTransport {
// MARK: - Private Helpers
extension NostrTransport {
/// A private message that cannot be embedded never leaves, so the bubble
/// must leave "sending". Same reason string the mesh path uses.
@MainActor
fileprivate func reportPrivateMessageSendFailure(_ messageID: String) {
let event = TransportEvent.messageDeliveryStatusUpdated(
messageID: messageID,
status: .failed(reason: String(localized: "content.delivery.reason.send_error", comment: "Failure reason for a generic send error"))
)
if let eventDelegate {
eventDelegate.didReceiveTransportEvent(event)
} else {
delegate?.receiveTransportEvent(event)
}
}
/// Converts npub bech32 string to hex pubkey
@MainActor
private func npubToHex(_ npub: String) -> String? {

View File

@ -355,6 +355,7 @@ final class ChatPrivateConversationCoordinator {
?? "anon"
let messageID = UUID().uuidString
let status = initialDeliveryStatus(for: content)
let message = BitchatMessage(
id: messageID,
sender: context.nickname,
@ -366,11 +367,12 @@ final class ChatPrivateConversationCoordinator {
recipientNickname: recipientNickname,
senderPeerID: context.myPeerID,
mentions: nil,
deliveryStatus: .sending
deliveryStatus: status
)
context.appendPrivateMessage(message, to: peerID)
context.notifyUIChanged()
guard status == .sending else { return }
// Always hand the message to the router — it owns delivery. A live
// link sends now; an unreachable peer gets the retained-outbox path
@ -393,6 +395,13 @@ final class ChatPrivateConversationCoordinator {
// acks, or failed when the outbox TTL expires.
}
private func initialDeliveryStatus(for content: String) -> DeliveryStatus {
guard PrivateMessagePacket.contentFitsOnWire(content) else {
return .failed(reason: String(localized: "content.delivery.reason.send_error", comment: "Failure reason for a generic send error"))
}
return .sending
}
func sendGeohashDM(_ content: String, to peerID: PeerID) {
guard case .location(let channel) = context.activeChannel else {
// The failure happened inside a geoDM thread — surface it there,
@ -406,6 +415,7 @@ final class ChatPrivateConversationCoordinator {
}
let messageID = UUID().uuidString
let status = initialDeliveryStatus(for: content)
let message = BitchatMessage(
id: messageID,
sender: context.nickname,
@ -415,11 +425,12 @@ final class ChatPrivateConversationCoordinator {
isPrivate: true,
recipientNickname: context.nickname,
senderPeerID: context.myPeerID,
deliveryStatus: .sending
deliveryStatus: status
)
context.appendPrivateMessage(message, to: peerID)
context.notifyUIChanged()
guard status == .sending else { return }
guard let recipientHex = context.nostrKeyMapping[peerID] else {
context.setPrivateDeliveryStatus(

View File

@ -1233,4 +1233,28 @@ struct ChatPrivateConversationCoordinatorContextTests {
#expect(context.routedPrivateMessages.map(\.content) == ["hello?"])
#expect(context.privateChats[peerID]?.first?.deliveryStatus == .sending)
}
@Test(arguments: [false, true]) @MainActor
func oversizedPrivateMessageFailsWithoutRouting(isGeohash: Bool) {
let context = MockChatPrivateConversationContext()
let coordinator = ChatPrivateConversationCoordinator(context: context)
let peerID: PeerID
if isGeohash {
let pubkey = String(repeating: "a", count: 64)
peerID = PeerID(str: "nostr_" + String(pubkey.prefix(16)))
context.activeChannel = .location(GeohashChannel(level: .region, geohash: "0000"))
context.nostrKeyMapping[peerID] = pubkey
} else {
// An unreachable mesh peer would normally cause the router to retain the message.
peerID = PeerID(str: "abcd1234abcd1234")
}
let content = String(repeating: "é", count: 128)
coordinator.sendPrivateMessage(content, to: peerID)
#expect(context.privateChats[peerID]?.map(\.content) == [content])
#expect(context.privateChats[peerID]?.first?.deliveryStatus == .failed(reason: "send error"))
#expect(context.routedPrivateMessages.isEmpty)
#expect(context.geoPrivateMessages.isEmpty)
}
}

View File

@ -410,16 +410,18 @@ struct CommandProcessorTests {
let peerID = PeerID(str: "abcd1234abcd1234")
context.selectedPrivateChatPeer = peerID
let processor = makePayProcessor(context: context)
let token = Self.cashuV3Token(mint: "https://mint.example.com", amounts: [16])
#expect(token.utf8.count <= PrivateMessagePacket.maxContentUTF8Bytes)
// cashu: URI form must be normalized to the bare token before sending
switch processor.process("/pay cashu:\(Self.validV3Token)") {
switch processor.process("/pay cashu:\(token)") {
case .success(let message):
#expect(message?.contains("21 sat") == true)
#expect(message?.contains("16 sat") == true)
default:
Issue.record("Expected success result")
}
#expect(context.sentPrivateMessages.count == 1)
#expect(context.sentPrivateMessages.first?.content == Self.validV3Token)
#expect(context.sentPrivateMessages.first?.content == token)
#expect(context.sentPrivateMessages.first?.peerID == peerID)
#expect(context.sentPublicMessages.isEmpty)
}
@ -504,27 +506,13 @@ struct CommandProcessorTests {
}
/// 21-sat single-mint V3 token (proofs of 1+4+16).
private static let validV3Token: String = {
let json: [String: Any] = [
"token": [[
"mint": "https://mint.example.com",
"proofs": [1, 4, 16].map { ["amount": $0, "id": "009a1f293253e41e", "secret": "s", "C": "02c"] }
]],
"unit": "sat"
]
let data = try! JSONSerialization.data(withJSONObject: json)
let b64 = data.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
return "cashuA" + b64
}()
private static let validV3Token = cashuV3Token(mint: "https://mint.example.com")
private static func cashuV3Token(mint: String) -> String {
private static func cashuV3Token(mint: String, amounts: [Int] = [1, 4, 16]) -> String {
let json: [String: Any] = [
"token": [[
"mint": mint,
"proofs": [1, 4, 16].map { ["amount": $0, "id": "009a1f293253e41e", "secret": "s", "C": "02c"] }
"proofs": amounts.map { ["amount": $0, "id": "009a1f293253e41e", "secret": "s", "C": "02c"] }
]],
"unit": "sat"
]