Harden BLE ingress, media bounds, DM read-state/notifications, and storage/URL safety (#1914)

* Require signature verification for self-addressed public messages

* Reject fragmented and foreign-directed REQUEST_SYNC packets

* Gate DM read receipts on app active state and notify delayed Nostr DMs

* Cap media deflate ratio and protect private media from public quota eviction

* Use background-accessible file protection and allowlist message URL schemes

* Track macOS active/inactive transitions for DM read-receipt gating

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
This commit is contained in:
jackandjack authored and GitHub committed 2026-11-27 09:42:29 -10:00
1 parent f464331202
commit 0047ba008f
27 files changed
+443 -46

No files matched your search

+11 -1
View File
@@ -202,6 +202,7 @@ final class AppRuntime: ObservableObject {
#if os(macOS)
func handleMacDidBecomeActiveNotification() {
chatViewModel.setAppActive(true)
guard chatViewModel.networkActivationAllowed else { return }
chatViewModel.handleDidBecomeActive()
checkForSharedContent()
@@ -212,6 +213,7 @@ final class AppRuntime: ObservableObject {
func handleScenePhaseChange(_ newPhase: ScenePhase) {
switch newPhase {
case .background:
chatViewModel.setAppActive(false)
TorManager.shared.setAppForeground(false)
TorManager.shared.goDormantOnBackground()
LocationStateManager.shared.endLiveRefresh()
@@ -220,6 +222,7 @@ final class AppRuntime: ObservableObject {
didEnterBackground = true
case .active:
chatViewModel.setAppActive(true)
guard chatViewModel.networkActivationAllowed else { return }
chatViewModel.meshService.startServices()
TorManager.shared.setAppForeground(true)
@@ -249,7 +252,7 @@ final class AppRuntime: ObservableObject {
checkForSharedContent()
case .inactive:
break
chatViewModel.setAppActive(false)
@unknown default:
break
@@ -374,6 +377,13 @@ private extension AppRuntime {
self?.handleScreenshotCaptured()
}
.store(in: &cancellables)
#elseif os(macOS)
NotificationCenter.default.publisher(for: NSApplication.didResignActiveNotification)
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.chatViewModel.setAppActive(false)
}
.store(in: &cancellables)
#endif
}
@@ -11,15 +11,12 @@ import BitLogger
import Foundation
enum AppSupportFileProtection {
case complete
case untilFirstUserAuthentication
var writingOptions: Data.WritingOptions {
var options: Data.WritingOptions = [.atomic]
#if os(iOS)
switch self {
case .complete:
options.insert(.completeFileProtection)
case .untilFirstUserAuthentication:
options.insert(.completeFileProtectionUntilFirstUserAuthentication)
}
@@ -30,8 +27,6 @@ enum AppSupportFileProtection {
#if os(iOS)
var fileProtectionType: FileProtectionType {
switch self {
case .complete:
return .complete
case .untilFirstUserAuthentication:
return .completeUntilFirstUserAuthentication
}
@@ -23,7 +23,7 @@ struct BLEFileTransferHandlerEnvironment {
/// Tracks the broadcast file packet for gossip sync.
let trackPacketSeen: (BitchatPacket) -> Void
/// Enforces the incoming-media storage quota before saving (BCH-01-002).
let enforceStorageQuota: (_ reservingBytes: Int) -> Void
let enforceStorageQuota: (_ reservingBytes: Int, _ isPrivate: Bool) -> Void
/// Persists the validated file to the incoming-media store; returns the destination URL.
let saveIncomingFile: (
_ data: Data,
@@ -336,7 +336,7 @@ final class BLEFileTransferHandler {
}
// BCH-01-002: Enforce storage quota before saving
env.enforceStorageQuota(filePacket.content.count)
env.enforceStorageQuota(filePacket.content.count, isPrivate)
guard let destination = env.saveIncomingFile(
filePacket.content,
@@ -36,6 +36,14 @@ final class BLEFragmentHandler {
let env = environment
guard let header = BLEFragmentHeader(packet: packet) else { return false }
// REQUEST_SYNC is strictly link-local (ttl == 0) and never fragmented.
// Rejecting it here stops a relayed fragment from zeroing TTL on
// reassembly and triggering a mesh-wide gossip store replay.
if header.originalType == MessageType.requestSync.rawValue {
SecureLogger.warning("🚫 Dropping fragmented REQUEST_SYNC from \(peerID.id.prefix(8))…", category: .security)
return false
}
// Sync replay legitimately hands us our own fragments back (the RSR
// ttl=0 restore path): after a relaunch the fragment store starts
// empty, so our sync filter doesn't cover them and peers re-offer
@@ -77,6 +85,9 @@ final class BLEFragmentHandler {
category: .security
)
return false
} else if originalPacket.type == MessageType.requestSync.rawValue {
SecureLogger.warning("🚫 Dropping reassembled REQUEST_SYNC from \(peerID.id.prefix(8))…", category: .security)
return false
} else if !env.isAcceptedIngressPayload(originalPacket, innerSender) {
return false
} else {
@@ -406,12 +406,16 @@ struct BLEIncomingFileStore: @unchecked Sendable {
}
/// Frees least-recently-modified incoming files until `reservingBytes`
/// fits under the quota. In-flight `voice_live_*` captures are never evicted
/// but still count toward usage.
func enforceQuota(reservingBytes: Int) {
/// fits under the quota. In-flight `voice_live_*` captures and files
/// awaiting UI delivery are never evicted but still count toward usage.
///
/// Public arrivals (`isPrivate == false`) can never evict committed private
/// media received from contacts; private arrivals evict public files first
/// before touching older private files.
func enforceQuota(reservingBytes: Int, isPrivate: Bool = false) {
do {
let base = try filesDirectory()
var allFiles: [(url: URL, size: Int64, modified: Date)] = []
var allFiles: [(url: URL, size: Int64, modified: Date, isPrivateOwned: Bool)] = []
for subdirectory in Self.incomingSubdirectories {
let dir = base.appendingPathComponent(subdirectory, isDirectory: true)
@@ -426,7 +430,11 @@ struct BLEIncomingFileStore: @unchecked Sendable {
guard let attrs = try? fileURL.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]),
let size = attrs.fileSize,
let modified = attrs.contentModificationDate else { continue }
allFiles.append((url: fileURL, size: Int64(size), modified: modified))
let relativePath = "\(subdirectory)/\(fileURL.lastPathComponent)"
// Fail closed if the receipt ledger is temporarily unreadable so
// public arrivals cannot evict committed private media.
let isPrivateOwned = privateMediaReceipts.isPayloadOwned(relativePath: relativePath) ?? true
allFiles.append((url: fileURL, size: Int64(size), modified: modified, isPrivateOwned: isPrivateOwned))
}
}
@@ -436,8 +444,16 @@ struct BLEIncomingFileStore: @unchecked Sendable {
let needToFree = currentUsage - targetUsage
let protectedPaths = directoryCache.pendingDeliveryPathsSnapshot()
let candidates = allFiles
.filter { isPrivate || !$0.isPrivateOwned }
.sorted { lhs, rhs in
if lhs.isPrivateOwned != rhs.isPrivateOwned {
return !lhs.isPrivateOwned
}
return lhs.modified < rhs.modified
}
var freedSpace: Int64 = 0
for file in allFiles.sorted(by: { $0.modified < $1.modified }) {
for file in candidates {
guard freedSpace < needToFree else { break }
guard !file.url.lastPathComponent.hasPrefix(Self.liveCapturePrefix),
!protectedPaths.contains(file.url.standardizedFileURL.path) else { continue }
@@ -20,6 +20,7 @@ struct BLEIngressLinkRecord: Equatable {
enum BLEIngressRejection: Error, Equatable {
case selfLoopback(packetType: UInt8)
case directSenderMismatch(boundPeerID: PeerID, claimedSenderID: PeerID)
case foreignRequestSync(recipientID: PeerID)
}
struct BLEIngressLinkRegistry {
@@ -97,6 +98,18 @@ struct BLEIngressLinkRegistry {
return .failure(.selfLoopback(packetType: packet.type))
}
// A directed REQUEST_SYNC is link-local to its intended recipient.
// Drop requests addressed to another peer at ingress before dedup or
// sync processing.
if packet.type == MessageType.requestSync.rawValue,
let recipientID = packet.recipientID,
!BLEPacketFreshnessPolicy.isBroadcastRecipient(recipientID) {
let targetPeer = PeerID(hexData: recipientID)
if targetPeer != localPeerID {
return .failure(.foreignRequestSync(recipientID: targetPeer))
}
}
if let boundPeerID, boundPeerID != claimedSenderID {
if requiresDirectSenderBinding(packet) {
return .failure(.directSenderMismatch(boundPeerID: boundPeerID, claimedSenderID: claimedSenderID))
@@ -151,6 +164,7 @@ enum BLEIngressPacketGuard {
enum Rejection: Error, Equatable {
case selfLoopback(packetType: UInt8)
case directSenderMismatch(boundPeerID: PeerID, claimedSenderID: PeerID)
case foreignRequestSync(recipientID: PeerID)
case invalidRSR(peerID: PeerID)
case timestampSkew(peerID: PeerID, skewMs: UInt64, maxSkewMs: UInt64)
}
@@ -181,6 +195,8 @@ enum BLEIngressPacketGuard {
return .failure(.selfLoopback(packetType: packetType))
case .failure(.directSenderMismatch(let boundPeerID, let claimedSenderID)):
return .failure(.directSenderMismatch(boundPeerID: boundPeerID, claimedSenderID: claimedSenderID))
case .failure(.foreignRequestSync(let recipientID)):
return .failure(.foreignRequestSync(recipientID: recipientID))
}
switch validatePayload(
@@ -10,6 +10,8 @@ import Foundation
struct BLEPublicMessageHandlerEnvironment {
/// Local peer identity at the time the message is handled.
let localPeerID: () -> PeerID
/// Local Ed25519 signing public key used to authenticate self-authored sync replays.
let localSigningPublicKey: () -> Data?
/// Local nickname used for sender resolution and collision checks.
let localNickname: () -> String
/// Current time source.
@@ -85,11 +87,13 @@ final class BLEPublicMessageHandler {
// cache. Fall back to that persisted-identity lookup for peers not (yet)
// in the registry.
let isSelf = peerID == env.localPeerID()
let verifiedSelf = isSelf
&& (env.localSigningPublicKey().map { env.verifyPacketSignature(packet, $0) } ?? false)
let registrySigningKey = peersSnapshot[peerID]?.signingPublicKey
let verifiedViaRegistry = !isSelf
&& (registrySigningKey.map { env.verifyPacketSignature(packet, $0) } ?? false)
let signedDisplayName = (isSelf || verifiedViaRegistry) ? nil : env.signedSenderDisplayName(packet, peerID)
guard isSelf || verifiedViaRegistry || signedDisplayName != nil else {
guard verifiedSelf || verifiedViaRegistry || signedDisplayName != nil else {
SecureLogger.warning("🚫 Dropping public message with missing/invalid signature for claimed sender \(peerID.id.prefix(8))…", category: .security)
return false
}
+13 -3
View File
@@ -1962,6 +1962,8 @@ final class BLEService: NSObject {
case .failure(.directSenderMismatch(let boundPeerID, let claimedSenderID)):
SecureLogger.warning("🚫 SECURITY: Sender ID spoofing attempt detected! \(linkDescription) claimed to be \(claimedSenderID.id.prefix(8))… but is bound to \(boundPeerID.id.prefix(8))…", category: .security)
return nil
case .failure(.foreignRequestSync):
return nil
case .failure(.invalidRSR(let peerID)):
SecureLogger.warning("Invalid or unsolicited RSR packet from \(peerID.id.prefix(8))… - rejecting", category: .security)
return nil
@@ -1990,7 +1992,7 @@ final class BLEService: NSObject {
case .failure(.timestampSkew(let peerID, let skewMs, let maxSkewMs)):
SecureLogger.warning("Packet timestamp skewed by \(skewMs)ms (max \(maxSkewMs)ms) from \(peerID.id.prefix(8))…", category: .security)
return false
case .failure(.selfLoopback), .failure(.directSenderMismatch):
case .failure(.selfLoopback), .failure(.directSenderMismatch), .failure(.foreignRequestSync):
return false
}
}
@@ -2695,8 +2697,8 @@ final class BLEService: NSObject {
trackPacketSeen: { [weak self] packet in
self?.gossipSyncManager?.onPublicPacketSeen(packet)
},
enforceStorageQuota: { [weak self] reservingBytes in
self?.incomingFileStore.enforceQuota(reservingBytes: reservingBytes)
enforceStorageQuota: { [weak self] reservingBytes, isPrivate in
self?.incomingFileStore.enforceQuota(reservingBytes: reservingBytes, isPrivate: isPrivate)
},
saveIncomingFile: { [weak self] data, preferredName, subdirectory, fallbackExtension, defaultPrefix in
self?.incomingFileStore.save(
@@ -5085,6 +5087,11 @@ extension BLEService {
// Handle REQUEST_SYNC: decode payload and respond with missing packets via sync manager
private func handleRequestSync(_ packet: BitchatPacket, from peerID: PeerID) {
if let recipientID = packet.recipientID,
!BLEPacketFreshnessPolicy.isBroadcastRecipient(recipientID),
recipientID != myPeerIDData {
return
}
// REQUEST_SYNC is link-local by design (always sent with ttl 0): a
// nonzero TTL means a crafted or relayed request, and answering one
// would let a single small packet fan a full store replay out of
@@ -5126,6 +5133,9 @@ extension BLEService {
localPeerID: { [weak self] in
self?.myPeerID ?? PeerID(str: "")
},
localSigningPublicKey: { [weak self] in
self?.noiseService.getSigningPublicKeyData()
},
localNickname: { [weak self] in
self?.myNickname ?? ""
},
+1 -1
View File
@@ -103,7 +103,7 @@ final class BoardStore {
fileURL: fileURL,
subdirectory: "board",
fileName: "posts.json",
protection: .complete
protection: .untilFirstUserAuthentication
)
if self.fileStore.fileURL != nil {
// Restore off the calling thread (cold launch on MainActor) on the
+1 -1
View File
@@ -34,7 +34,7 @@ final class GroupStore: ObservableObject {
fileURL: fileURL,
subdirectory: "groups",
fileName: "groups.json",
protection: .complete
protection: .untilFirstUserAuthentication
)
loadFromDisk()
}
@@ -75,7 +75,7 @@ final class PrekeyBundleStore {
fileURL: fileURL,
subdirectory: "prekeys",
fileName: "bundles.json",
protection: .complete
protection: .untilFirstUserAuthentication
)
loadFromDisk()
}
+1 -1
View File
@@ -48,7 +48,7 @@ final class GossipMessageArchive {
let data = try JSONEncoder().encode(packets)
var options: Data.WritingOptions = [.atomic]
#if os(iOS)
options.insert(.completeFileProtection)
options.insert(.completeFileProtectionUntilFirstUserAuthentication)
#endif
try data.write(to: fileURL, options: options)
} catch {
@@ -17,6 +17,10 @@ protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageS
var privateChats: [PeerID: [BitchatMessage]] { get }
var sentReadReceipts: Set<String> { get }
var selectedPrivateChatPeer: PeerID? { get }
/// Whether the app is currently active in the foreground. A DM left open
/// while the app is backgrounded or the phone is locked must not emit
/// instant read receipts or suppress notifications.
var isAppActive: Bool { get }
var nostrKeyMapping: [PeerID: String] { get }
// MARK: Conversation store intents
@@ -563,10 +567,9 @@ final class ChatPrivateConversationCoordinator {
context.appendPrivateMessage(message, to: conversationPeerID)
let isViewing = context.selectedPrivateChatPeer == conversationPeerID
let isViewing = context.isAppActive && context.selectedPrivateChatPeer == conversationPeerID
let wasReadBefore = context.sentReadReceipts.contains(messageId)
let isRecentMessage = Date().timeIntervalSince(messageTimestamp) < 30
let shouldMarkUnread = !wasReadBefore && !isViewing && isRecentMessage
let shouldMarkUnread = !wasReadBefore && !isViewing
if shouldMarkUnread {
context.markPrivateChatUnread(conversationPeerID)
}
@@ -701,7 +704,7 @@ final class ChatPrivateConversationCoordinator {
let noiseKey = peerID.noiseKey ?? context.noisePublicKey(for: peerID)
mirrorToEphemeralIfNeeded(message, targetPeerID: peerID, key: noiseKey)
let isViewing = context.selectedPrivateChatPeer == peerID
let isViewing = context.isAppActive && context.selectedPrivateChatPeer == peerID
if isViewing {
let receipt = ReadReceipt(
originalMessageID: message.id,
+11
View File
@@ -1599,8 +1599,19 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
// MARK: - App Lifecycle
/// Tracks whether the app is currently active in the foreground so an open
/// DM does not emit read receipts or suppress alerts while backgrounded or
/// locked. Defaults to `true` for headless tests and foreground launch.
private(set) var isAppActive: Bool = true
@MainActor
func setAppActive(_ active: Bool) {
isAppActive = active
}
@MainActor
func handleDidBecomeActive() {
isAppActive = true
lifecycleCoordinator.handleDidBecomeActive()
}
+15 -1
View File
@@ -479,7 +479,10 @@ private struct MessageListContentView: View {
}
}
.environment(\.openURL, OpenURLAction { url in
// Intercept custom cashu: links created in attributed text
guard MessageListExternalURLPolicy.isAllowed(url) else {
return .discarded
}
// Intercept custom cashu:/lightning: links created in attributed text
if let scheme = url.scheme?.lowercased(), scheme == "cashu" || scheme == "lightning" {
#if os(iOS)
UIApplication.shared.open(url)
@@ -494,6 +497,17 @@ private struct MessageListContentView: View {
}
}
enum MessageListExternalURLPolicy {
static func isAllowed(_ url: URL) -> Bool {
guard let scheme = url.scheme?.lowercased() else { return false }
return scheme == "https"
|| scheme == "http"
|| scheme == "cashu"
|| scheme == "lightning"
|| scheme == "bitchat"
}
}
private extension MessageListContentView {
/// Returns the window to its initial size once the reader is back at the
/// bottom (the newest row has appeared): whatever it grew by while they
@@ -24,6 +24,7 @@ private final class MockChatPrivateConversationContext: ChatPrivateConversationC
var sentGeoDeliveryAcks: Set<String> = []
var unreadPrivateMessages: Set<PeerID> = []
var selectedPrivateChatPeer: PeerID?
var isAppActive = true
var nickname = "me"
var activeChannel: ChannelID = .mesh
var nostrKeyMapping: [PeerID: String] = [:]
@@ -443,15 +444,16 @@ struct ChatPrivateConversationCoordinatorContextTests {
context.displayNamesByPubkey[senderPubkey] = "bob#5678"
let payloadData = PrivateMessagePacket(messageID: "geo-1", content: "hi there").encode()!
let payload = NoisePayload(type: .privateMessage, data: payloadData)
// Old timestamp: not "recent", so no unread marking (and no notification).
let oldTimestamp = Date().addingTimeInterval(-120)
// Delayed Nostr/offline DM (>30s old): still newly received, so it must
// mark unread and post a notification when the thread is not open.
let delayedTimestamp = Date().addingTimeInterval(-3600)
coordinator.handlePrivateMessage(
payload,
senderPubkey: senderPubkey,
convKey: convKey,
id: MockChatPrivateConversationContext.dummyIdentity,
messageTimestamp: oldTimestamp
messageTimestamp: delayedTimestamp
)
#expect(context.geoDeliveryAcks.map(\.messageID) == ["geo-1"])
@@ -459,7 +461,8 @@ struct ChatPrivateConversationCoordinatorContextTests {
#expect(context.sentGeoDeliveryAcks == ["geo-1"])
#expect(context.privateChats[convKey]?.map(\.id) == ["geo-1"])
#expect(context.privateChats[convKey]?.first?.sender == "bob#5678")
#expect(context.unreadPrivateMessages.isEmpty)
#expect(context.unreadPrivateMessages == [convKey])
#expect(context.privateMessageNotifications.count == 1)
// Redelivery: ack is deduplicated and the message is not appended twice.
coordinator.handlePrivateMessage(
@@ -467,10 +470,11 @@ struct ChatPrivateConversationCoordinatorContextTests {
senderPubkey: senderPubkey,
convKey: convKey,
id: MockChatPrivateConversationContext.dummyIdentity,
messageTimestamp: oldTimestamp
messageTimestamp: delayedTimestamp
)
#expect(context.geoDeliveryAcks.count == 1)
#expect(context.privateChats[convKey]?.count == 1)
#expect(context.privateMessageNotifications.count == 1)
}
@Test @MainActor
@@ -1078,6 +1082,40 @@ struct ChatPrivateConversationCoordinatorContextTests {
#expect(context.privateMessageNotifications.count == 1)
}
@Test @MainActor
func handlePrivateMessage_backgroundedOpenChatMarksUnreadAndSkipsReadReceipt() async {
let context = MockChatPrivateConversationContext()
let coordinator = ChatPrivateConversationCoordinator(context: context)
let meshPeerID = PeerID(str: "0102030405060708")
let geoConvKey = PeerID(str: "nostr_abcdef12")
let senderPubkey = "feedface00112233"
context.displayNamesByPubkey[senderPubkey] = "bob#5678"
// BLE path: chat is selected, but app is backgrounded/inactive.
context.selectedPrivateChatPeer = meshPeerID
context.isAppActive = false
coordinator.handlePrivateMessage(
makeIncomingMessage(id: "bg-mesh-1", content: "ping while locked", senderPeerID: meshPeerID)
)
#expect(context.meshReadReceipts.isEmpty)
#expect(context.unreadPrivateMessages.contains(meshPeerID))
#expect(context.privateMessageNotifications.count == 1)
// Nostr/GeoDM path: chat is selected, app is backgrounded/inactive.
context.selectedPrivateChatPeer = geoConvKey
let payloadData = PrivateMessagePacket(messageID: "bg-geo-1", content: "nostr while locked").encode()!
coordinator.handlePrivateMessage(
NoisePayload(type: .privateMessage, data: payloadData),
senderPubkey: senderPubkey,
convKey: geoConvKey,
id: MockChatPrivateConversationContext.dummyIdentity,
messageTimestamp: Date()
)
#expect(context.geoReadReceipts.isEmpty)
#expect(context.unreadPrivateMessages.contains(geoConvKey))
#expect(context.privateMessageNotifications.count == 2)
}
@Test @MainActor
func handleFavoriteNotification_persistsAndAnnouncesTransitionsOnly() async {
let context = MockChatPrivateConversationContext()
@@ -122,8 +122,17 @@ struct NotificationStreamAssemblerTests {
func testAssemblesCompressedLargeFrame() throws {
var assembler = NotificationStreamAssembler()
// Keep the fixture below FileTransferLimits.maxPayloadBytes so encoding succeeds while still exercising compression.
let largeContent = Data(repeating: 0x41, count: 600_000)
// Keep the fixture below FileTransferLimits.maxPayloadBytes with realistic
// compressibility (bounded byte alphabet, ~2-4x ratio) so it compresses
// without tripping the media decompression-bomb ratio cap.
var rng: UInt64 = 0x5EED_CAFE_1234_5678
let largeContent = Data((0..<600_000).map { i in
if i % 4 == 0 {
rng = rng &* 6364136223846793005 &+ 1442695040888963407
return UInt8((rng >> 33) & 0x3F)
}
return 0x41
})
let filePacket = BitchatFilePacket(
fileName: "large.bin",
fileSize: UInt64(largeContent.count),
@@ -127,10 +127,19 @@ struct PacketPayloadCapInteropTests {
}
@Test func largeFileTransfersStillDecode() throws {
// A 1 MiB image whose bytes compress well: the largest legitimate
// inflation a broadcast file can ask for.
// A 1 MiB file with realistic compressibility (~3-5x ratio): compresses
// on wire without resembling a ~1000x decompression bomb.
var content = Data([0xFF, 0xD8, 0xFF, 0xE0])
content.append(Data(count: FileTransferLimits.maxPayloadBytes - content.count))
var rng: UInt64 = 0x1234_5678_9ABC_DEF0
content.reserveCapacity(FileTransferLimits.maxPayloadBytes)
for i in content.count..<FileTransferLimits.maxPayloadBytes {
if i % 4 == 0 {
rng = rng &* 6364136223846793005 &+ 1442695040888963407
content.append(UInt8((rng >> 33) & 0x3F))
} else {
content.append(0)
}
}
let file = BitchatFilePacket(fileName: "photo.jpg", fileSize: nil, mimeType: "image/jpeg", content: content)
let payload = try #require(file.encode())
let packet = makePacket(type: .fileTransfer, payload: payload, version: 2)
@@ -61,7 +61,7 @@ struct BLEFileTransferHandlerTests {
trackPacketSeen: { packet in
recorder.trackedPackets.append(packet)
},
enforceStorageQuota: { reservingBytes in
enforceStorageQuota: { reservingBytes, _ in
recorder.quotaReservations.append(reservingBytes)
},
saveIncomingFile: { data, preferredName, subdirectory, fallbackExtension, defaultPrefix in
@@ -271,6 +271,56 @@ struct BLEFragmentHandlerTests {
#expect(recorder.reinjectedPackets.isEmpty)
}
@Test
func fragmentedRequestSyncIsRejectedBeforeAssembly() {
let recorder = Recorder()
let handler = makeHandler(recorder: recorder)
let packet = makeFragmentPacket(
sender: remotePeerID,
index: 0,
total: 2,
originalType: MessageType.requestSync.rawValue
)
handler.handle(packet, from: remotePeerID)
#expect(recorder.trackedPackets.isEmpty)
#expect(recorder.appendedHeaders.isEmpty)
#expect(recorder.ingressChecks.isEmpty)
#expect(recorder.reinjectedPackets.isEmpty)
}
@Test
func reassembledRequestSyncDisguisedAsAnotherTypeIsDropped() throws {
let innerPacket = BitchatPacket(
type: MessageType.requestSync.rawValue,
senderID: Data(hexString: remotePeerID.id) ?? Data(),
recipientID: nil,
timestamp: 900_000,
payload: Data([0x01, 0x02]),
signature: nil,
ttl: 0
)
let reassembled = try #require(innerPacket.toBinaryData())
let recorder = Recorder()
recorder.appendResult = { header in
.complete(header: header, reassembledData: reassembled, started: false)
}
let handler = makeHandler(recorder: recorder)
let packet = makeFragmentPacket(
sender: remotePeerID,
index: 1,
total: 2,
originalType: MessageType.message.rawValue
)
handler.handle(packet, from: remotePeerID)
#expect(recorder.ingressChecks.isEmpty)
#expect(recorder.reinjectedPackets.isEmpty)
}
/// Every byte value once, then zeros: the encoder leaves the inner
/// payload uncompressed (100% byte diversity), while the zero chunks
/// compress inside their fragments.
@@ -217,16 +217,78 @@ struct BLEIngressPacketGuardTests {
#expect(result == .failure(.invalidRSR(peerID: bound)))
}
@Test("directed request-sync for another peer is rejected while local and broadcast are accepted")
func foreignDirectedRequestSyncIsRejected() throws {
let local = PeerID(str: "0011223344556677")
let sender = PeerID(str: "1122334455667788")
let other = PeerID(str: "8899aabbccddeeff")
let foreignPacket = makePacket(
type: .requestSync,
sender: sender,
recipient: other,
timestamp: 1_000,
ttl: 0
)
let localPacket = makePacket(
type: .requestSync,
sender: sender,
recipient: local,
timestamp: 1_000,
ttl: 0
)
let broadcastPacket = makePacket(
type: .requestSync,
sender: sender,
recipient: nil,
timestamp: 1_000,
ttl: 0
)
let foreignResult = BLEIngressPacketGuard.evaluate(
packet: foreignPacket,
claimedSenderID: sender,
boundPeerID: sender,
localPeerID: local,
directAnnounceTTL: 7,
nowMs: 1_000,
isValidSyncResponse: { _ in false }
)
let localContext = try #require(success(BLEIngressPacketGuard.evaluate(
packet: localPacket,
claimedSenderID: sender,
boundPeerID: sender,
localPeerID: local,
directAnnounceTTL: 7,
nowMs: 1_000,
isValidSyncResponse: { _ in false }
)))
let broadcastContext = try #require(success(BLEIngressPacketGuard.evaluate(
packet: broadcastPacket,
claimedSenderID: sender,
boundPeerID: sender,
localPeerID: local,
directAnnounceTTL: 7,
nowMs: 1_000,
isValidSyncResponse: { _ in false }
)))
#expect(foreignResult == .failure(.foreignRequestSync(recipientID: other)))
#expect(localContext.receivedFromPeerID == sender)
#expect(broadcastContext.receivedFromPeerID == sender)
}
private func makePacket(
type: MessageType = .message,
sender: PeerID,
recipient: PeerID? = nil,
timestamp: UInt64,
ttl: UInt8 = 3
) -> BitchatPacket {
BitchatPacket(
type: type.rawValue,
senderID: Data(hexString: sender.id) ?? Data(),
recipientID: nil,
recipientID: recipient.flatMap { Data(hexString: $0.id) },
timestamp: timestamp,
payload: Data([0x01, 0x02, 0x03]),
signature: nil,
@@ -20,6 +20,7 @@ struct BLEPublicMessageHandlerTests {
}
private let localPeerID = PeerID(str: "0102030405060708")
private let localSigningKey = Data(repeating: 0x11, count: 32)
private let remotePeerID = PeerID(str: "1122334455667788")
private func makeHandler(
@@ -30,6 +31,7 @@ struct BLEPublicMessageHandlerTests {
let resolvedLocalPeerID = localPeerID ?? self.localPeerID
let environment = BLEPublicMessageHandlerEnvironment(
localPeerID: { resolvedLocalPeerID },
localSigningPublicKey: { self.localSigningKey },
localNickname: { recorder.localNickname },
now: { now },
peersSnapshot: {
@@ -262,6 +264,7 @@ struct BLEPublicMessageHandlerTests {
func selfSyncReplayResolvesOriginalMessageID() {
let now = Date(timeIntervalSince1970: 1_000)
let recorder = Recorder()
recorder.verifyPacketSignatureResult = true
recorder.selfBroadcastMessageID = "original-id"
let handler = makeHandler(recorder: recorder, now: now)
// TTL 0 marks a sync replay of our own broadcast, not a self echo.
@@ -269,6 +272,7 @@ struct BLEPublicMessageHandlerTests {
handler.handle(packet, from: localPeerID)
#expect(recorder.verifyPacketSignatureQueries == [localPeerID])
#expect(recorder.selfBroadcastTakes.count == 1)
#expect(recorder.deliveries.count == 1)
#expect(recorder.deliveries.first?.peerID == localPeerID)
@@ -276,6 +280,22 @@ struct BLEPublicMessageHandlerTests {
#expect(recorder.deliveries.first?.messageID == "original-id")
}
@Test
func spoofedSelfSenderWithInvalidSignatureIsDropped() {
let now = Date(timeIntervalSince1970: 1_000)
let recorder = Recorder()
recorder.verifyPacketSignatureResult = false
let handler = makeHandler(recorder: recorder, now: now)
// An attacker spoofing our own senderID with TTL 0 must not bypass signature verification.
let packet = makeMessagePacket(sender: localPeerID, content: "forged self", timestamp: timestamp(now), ttl: 0)
#expect(!handler.handle(packet, from: localPeerID))
#expect(recorder.verifyPacketSignatureQueries == [localPeerID])
#expect(recorder.trackedPackets.isEmpty)
#expect(recorder.deliveries.isEmpty)
}
@Test
func directedMessageIsDeliveredWithoutSyncTracking() {
let now = Date(timeIntervalSince1970: 1_000)
@@ -1,3 +1,4 @@
import BitFoundation
import Foundation
import Testing
@testable import bitchat
@@ -140,6 +141,47 @@ struct MediaRetentionTests {
#expect(!FileManager.default.fileExists(atPath: pending.path))
}
@Test
func publicQuotaEvictionNeverDeletesCommittedPrivateMedia() throws {
let root = makeRoot()
defer { try? FileManager.default.removeItem(at: root) }
let store = BLEIncomingFileStore(baseDirectory: root, quotaBytes: 25)
let privateFileName = "img_\(UUID().uuidString).jpg"
let privateFile = try #require(store.save(
data: Data(repeating: 0x11, count: 15),
preferredName: privateFileName,
subdirectory: "images/incoming",
fallbackExtension: "jpg",
defaultPrefix: "img"
))
let stableID = try #require(PrivateMediaMessageIdentity.stableID(
senderPeerID: PeerID(str: "1122334455667788"),
recipientPeerID: PeerID(str: "aabbccddeeff0011"),
fileName: privateFileName
))
#expect(store.commitPrivateMediaFile(messageID: stableID, storedURL: privateFile))
let publicFile = try #require(store.save(
data: Data(repeating: 0x22, count: 10),
preferredName: "pub.jpg",
subdirectory: "images/incoming",
fallbackExtension: "jpg",
defaultPrefix: "img"
))
// Public broadcast flood under tight quota evicts old public media
// but leaves committed private media intact.
store.enforceQuota(reservingBytes: 20, isPrivate: false)
#expect(FileManager.default.fileExists(atPath: privateFile.path))
#expect(!FileManager.default.fileExists(atPath: publicFile.path))
// Private arrivals may still reclaim oldest private media once no
// public files remain to satisfy the quota.
store.enforceQuota(reservingBytes: 20, isPrivate: true)
#expect(!FileManager.default.fileExists(atPath: privateFile.path))
}
#if os(iOS)
/// Media was the one persistence layer that never stated a protection
/// class at its write site, so payloads inherited the container
+29
View File
@@ -916,4 +916,33 @@ struct ViewSmokeTests {
window.isHidden = true
}
#endif
@Test("Message list external URL allowlist permits only safe schemes")
func messageListExternalURLAllowlist() throws {
let allowed = [
"https://bitchat.free",
"http://example.com",
"HTTPS://EXAMPLE.COM/path",
"cashu:cashuA_test",
"lightning:lnbc1test",
"bitchat://verify?name=alice"
]
for raw in allowed {
let url = try #require(URL(string: raw))
#expect(MessageListExternalURLPolicy.isAllowed(url), "Expected \(raw) to be allowed")
}
let blocked = [
"tel:+15551234567",
"sms:+15551234567",
"mailto:alice@example.com",
"file:///etc/passwd",
"javascript:alert(1)",
"itms-services://?action=download-manifest"
]
for raw in blocked {
let url = try #require(URL(string: raw))
#expect(!MessageListExternalURLPolicy.isAllowed(url), "Expected \(raw) to be blocked")
}
}
}
@@ -199,12 +199,18 @@ public struct BinaryProtocol {
var originalPayloadSize: Int?
if CompressionUtil.shouldCompress(payload) {
// Only compress when we can represent the original length in the outbound frame
// and the compressed ratio stays within the decoder's per-type deflate cap.
let maxRepresentable = version == 2 ? Int(UInt32.max) : Int(UInt16.max)
let maxDeflateRatio = PacketPayloadLimits.maxDeflateRatio(forType: packet.type)
if payload.count <= maxRepresentable,
let compressedPayload = CompressionUtil.compress(payload) {
originalPayloadSize = payload.count
payload = compressedPayload
isCompressed = true
let compressedPayload = CompressionUtil.compress(payload),
!compressedPayload.isEmpty {
let (maxAllowed, overflow) = compressedPayload.count.multipliedReportingOverflow(by: maxDeflateRatio)
if overflow || payload.count <= maxAllowed {
originalPayloadSize = payload.count
payload = compressedPayload
isCompressed = true
}
}
}
@@ -432,7 +438,8 @@ public struct BinaryProtocol {
let compressedSize = payloadLength - lengthFieldBytes
guard compressedSize > 0, let compressed = readData(compressedSize) else { return nil }
guard originalSize <= compressedSize * PacketPayloadLimits.maxDeflateRatio else {
let ratioCap = PacketPayloadLimits.maxDeflateRatio(forType: type)
guard originalSize <= compressedSize * ratioCap else {
SecureLogger.debug("🚫 Impossible compression ratio: \(originalSize) bytes from \(compressedSize)", category: .security)
return nil
}
@@ -54,6 +54,23 @@ public enum PacketPayloadLimits {
/// produced by any stream, so it is rejected before the output buffer is
/// allocated.
static let maxDeflateRatio = 1032
/// Tighter expansion ceiling for media-class frames (`fileTransfer`,
/// `noiseEncrypted`): legitimate media is already compressed and Noise
/// ciphertext is incompressible, so capping expansion blocks ~1 KB -> 1 MiB
/// broadcast decompression bombs without breaking normal payloads.
static let maxMediaDeflateRatio = 32
static func maxDeflateRatio(forType type: UInt8) -> Int {
guard let messageType = MessageType(rawValue: type) else {
return maxDeflateRatio
}
switch messageType {
case .fileTransfer, .noiseEncrypted:
return maxMediaDeflateRatio
default:
return maxDeflateRatio
}
}
private static let fragmentBytes = 1_280
private static let controlBytes = 4 * 1024
@@ -58,8 +58,11 @@ struct PacketPayloadLimitsTests {
@Test func onlyMediaTypesReachTheFramedFileCeiling() throws {
let size = FileTransferLimits.maxFramedFileBytes
for mediaType in [MessageType.fileTransfer, .noiseEncrypted] {
let frame = try encodeCompressed(type: mediaType.rawValue, payloadSize: size, version: 2)
#expect(BinaryProtocol.decode(frame)?.payload.count == size)
// High-ratio (~1000x) crafted compressed bombs are rejected for
// media-class frames before allocation/decompression.
let bomb = try craftCompressedBombFrame(type: mediaType.rawValue, payloadSize: size)
#expect(BinaryProtocol.decode(bomb) == nil)
// Uncompressed media frames still reach the full framed-file ceiling.
let raw = try encodeUncompressed(type: mediaType.rawValue, payloadSize: size, version: 2)
#expect(BinaryProtocol.decode(raw)?.payload.count == size)
}
@@ -161,4 +164,25 @@ struct PacketPayloadLimitsTests {
#expect(frame[BinaryProtocol.Offsets.flags] & BinaryProtocol.Flags.isCompressed != 0)
return frame
}
/// Manually builds a v2 compressed frame whose compressed ratio far exceeds
/// the media deflate cap (simulating an attacker-crafted ~1 KB -> 1.18 MiB bomb).
private func craftCompressedBombFrame(type: UInt8, payloadSize: Int) throws -> Data {
let compressed = try #require(CompressionUtil.compress(Data(repeating: 0x41, count: payloadSize)))
#expect(compressed.count < payloadSize / 100)
var frame = Data()
frame.append(2) // version 2
frame.append(type)
frame.append(7) // ttl
var tsBE = UInt64(1_740_000_000_000).bigEndian
withUnsafeBytes(of: &tsBE) { frame.append($0.bindMemory(to: UInt8.self)) }
frame.append(BinaryProtocol.Flags.isCompressed)
var payloadLenBE = UInt32(compressed.count + 4).bigEndian
withUnsafeBytes(of: &payloadLenBE) { frame.append($0.bindMemory(to: UInt8.self)) }
frame.append(Data(repeating: 0x11, count: BinaryProtocol.senderIDSize))
var origSizeBE = UInt32(payloadSize).bigEndian
withUnsafeBytes(of: &origSizeBE) { frame.append($0.bindMemory(to: UInt8.self)) }
frame.append(compressed)
return frame
}
}