mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-26 05:25:20 +00:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f8af04821 | ||
|
|
78083bd773 | ||
|
|
a8201b3958 | ||
|
|
01ce054238 | ||
|
|
b6c7c77080 | ||
|
|
55ee1df0bc | ||
|
|
b255355fed | ||
|
|
6e026c2c22 | ||
|
|
c8e330777a | ||
|
|
91aba8b597 | ||
|
|
d9a6dbfca8 | ||
|
|
68f8f03ad8 | ||
|
|
48026991b2 | ||
|
|
ec795520ee | ||
|
|
40238c5e43 | ||
|
|
a31cd80027 |
@@ -12,6 +12,7 @@ final class ConversationUIModel: ObservableObject {
|
||||
@Published private(set) var currentNickname: String
|
||||
@Published private(set) var isBatchingPublic = false
|
||||
@Published private(set) var canSendMediaInCurrentContext = true
|
||||
@Published private(set) var legacyPrivateMediaConsentRequest: LegacyPrivateMediaConsentRequest?
|
||||
/// Who is talking live in the public mesh channel right now (floor
|
||||
/// courtesy: the composer mic tints "busy" while someone holds the floor).
|
||||
@Published private(set) var activeLiveVoiceTalker: String?
|
||||
@@ -153,6 +154,13 @@ final class ConversationUIModel: ObservableObject {
|
||||
chatViewModel.sendVoiceNote(at: url)
|
||||
}
|
||||
|
||||
func resolveLegacyPrivateMediaConsent(requestID: UUID, approved: Bool) {
|
||||
chatViewModel.resolveLegacyPrivateMediaConsent(
|
||||
requestID: requestID,
|
||||
approved: approved
|
||||
)
|
||||
}
|
||||
|
||||
/// Capture backend for the mic gesture: live PTT when the current DM
|
||||
/// peer can hear it now, classic voice note otherwise.
|
||||
func makeVoiceCaptureSession() -> VoiceCaptureSession {
|
||||
@@ -193,6 +201,10 @@ final class ConversationUIModel: ObservableObject {
|
||||
.receive(on: DispatchQueue.main)
|
||||
.assign(to: &$activeLiveVoiceTalker)
|
||||
|
||||
chatViewModel.$legacyPrivateMediaConsentRequest
|
||||
.receive(on: DispatchQueue.main)
|
||||
.assign(to: &$legacyPrivateMediaConsentRequest)
|
||||
|
||||
conversations.$activeChannel
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] channel in
|
||||
|
||||
@@ -189,6 +189,18 @@ struct IdentityCache: Codable {
|
||||
// Fingerprint -> when we verified it (orders outgoing vouch batches;
|
||||
// entries verified before this field exists sort as oldest)
|
||||
var verifiedAt: [String: Date]? = nil
|
||||
|
||||
// Stable Noise fingerprints that proved encrypted private-media support
|
||||
// inside an authenticated Noise session. Optional for decoding caches
|
||||
// written before this migration. Entries are monotonic until a panic wipe
|
||||
// so an old/replayed announce cannot silently downgrade a peer.
|
||||
var privateMediaCapableFingerprints: Set<String>? = nil
|
||||
|
||||
// Noise-fingerprint -> Ed25519 announcement key, learned only from the
|
||||
// authenticated peer-state payload. This prevents a self-signed announce
|
||||
// containing a copied public Noise key from replacing a previously bound
|
||||
// public-message signing identity. Optional for old cache compatibility.
|
||||
var authenticatedSigningKeysByFingerprint: [String: Data]? = nil
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@@ -140,6 +140,14 @@ protocol SecureIdentityStateManagerProtocol {
|
||||
func markVouchBatchSent(to fingerprint: String, at date: Date)
|
||||
func signingPublicKey(forFingerprint fingerprint: String) -> Data?
|
||||
func mostRecentlyVerifiedFingerprints(limit: Int, excluding fingerprint: String) -> [String]
|
||||
|
||||
// MARK: Noise-authenticated announcement identity
|
||||
func bindAuthenticatedSigningPublicKey(_ signingPublicKey: Data, fingerprint: String)
|
||||
func authenticatedSigningPublicKey(forFingerprint fingerprint: String) -> Data?
|
||||
|
||||
// MARK: Private-media downgrade protection
|
||||
func markPrivateMediaCapable(fingerprint: String)
|
||||
func hasObservedPrivateMediaCapability(fingerprint: String) -> Bool
|
||||
}
|
||||
|
||||
/// Singleton manager for secure identity state persistence and retrieval.
|
||||
@@ -157,6 +165,7 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol {
|
||||
|
||||
// Thread safety
|
||||
private let queue = DispatchQueue(label: "bitchat.identity.state", attributes: .concurrent)
|
||||
private let queueSpecificKey = DispatchSpecificKey<UInt8>()
|
||||
|
||||
// Pending-save coalescing flag. Reads/writes are serialized on `queue`.
|
||||
// Persistence is done with a fire-and-forget `queue.async(.barrier)` rather
|
||||
@@ -214,6 +223,7 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol {
|
||||
|
||||
self.encryptionKey = loadedKey
|
||||
self.encryptionKeyIsEphemeral = keyIsEphemeral
|
||||
queue.setSpecific(key: queueSpecificKey, value: 1)
|
||||
|
||||
// Only read the persisted cache when we hold the real key; with an
|
||||
// ephemeral key the decrypt would fail and discard the real cache.
|
||||
@@ -370,6 +380,66 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol {
|
||||
return cryptographicIdentities.values.filter { $0.fingerprint.hasPrefix(peerID.id) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private-media downgrade protection
|
||||
|
||||
func markPrivateMediaCapable(fingerprint: String) {
|
||||
guard !fingerprint.isEmpty else { return }
|
||||
let insertAndPersist = {
|
||||
var pinned = self.cache.privateMediaCapableFingerprints ?? []
|
||||
guard pinned.insert(fingerprint).inserted else { return }
|
||||
self.cache.privateMediaCapableFingerprints = pinned
|
||||
self.saveIdentityCache()
|
||||
}
|
||||
// Downgrade decisions can run immediately after an authenticated
|
||||
// announce. Make the pin visible before returning; merely enqueueing a
|
||||
// barrier leaves a cross-queue window where a replay can look legacy.
|
||||
// The queue-specific fast path prevents self-deadlock if a future
|
||||
// identity-state mutation records the capability from inside `queue`.
|
||||
if DispatchQueue.getSpecific(key: queueSpecificKey) != nil {
|
||||
insertAndPersist()
|
||||
} else {
|
||||
queue.sync(flags: .barrier, execute: insertAndPersist)
|
||||
}
|
||||
}
|
||||
|
||||
func hasObservedPrivateMediaCapability(fingerprint: String) -> Bool {
|
||||
guard !fingerprint.isEmpty else { return false }
|
||||
return queue.sync {
|
||||
cache.privateMediaCapableFingerprints?.contains(fingerprint) == true
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Noise-authenticated announcement identity
|
||||
|
||||
func bindAuthenticatedSigningPublicKey(_ signingPublicKey: Data, fingerprint: String) {
|
||||
guard signingPublicKey.count == AuthenticatedPeerStatePacket.signingPublicKeyLength,
|
||||
!fingerprint.isEmpty else { return }
|
||||
let bindAndPersist = {
|
||||
var bindings = self.cache.authenticatedSigningKeysByFingerprint ?? [:]
|
||||
let bindingChanged = bindings[fingerprint] != signingPublicKey
|
||||
bindings[fingerprint] = signingPublicKey
|
||||
self.cache.authenticatedSigningKeysByFingerprint = bindings
|
||||
if var cryptoIdentity = self.cryptographicIdentities[fingerprint] {
|
||||
cryptoIdentity.signingPublicKey = signingPublicKey
|
||||
self.cryptographicIdentities[fingerprint] = cryptoIdentity
|
||||
}
|
||||
guard bindingChanged else { return }
|
||||
self.saveIdentityCache()
|
||||
}
|
||||
if DispatchQueue.getSpecific(key: queueSpecificKey) != nil {
|
||||
bindAndPersist()
|
||||
} else {
|
||||
queue.sync(flags: .barrier, execute: bindAndPersist)
|
||||
}
|
||||
}
|
||||
|
||||
func authenticatedSigningPublicKey(forFingerprint fingerprint: String) -> Data? {
|
||||
guard !fingerprint.isEmpty else { return nil }
|
||||
return queue.sync {
|
||||
cache.authenticatedSigningKeysByFingerprint?[fingerprint]
|
||||
}
|
||||
}
|
||||
|
||||
func updateSocialIdentity(_ identity: SocialIdentity) {
|
||||
queue.async(flags: .barrier) {
|
||||
|
||||
@@ -30,7 +30,7 @@ struct NoisePayload {
|
||||
|
||||
// Safely get the first byte
|
||||
let firstByte = data[data.startIndex]
|
||||
guard let type = NoisePayloadType(rawValue: firstByte) else {
|
||||
guard let type = NoisePayloadType.decoded(rawValue: firstByte) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -6,17 +6,60 @@
|
||||
// For more information, see <https://unlicense.org>
|
||||
//
|
||||
|
||||
import BitFoundation
|
||||
import Foundation
|
||||
|
||||
enum NoiseSecurityConstants {
|
||||
// Maximum message size to prevent memory exhaustion
|
||||
static let maxMessageSize = 65535 // 64KB as per Noise spec
|
||||
|
||||
/// The extracted transport nonce (4 bytes) and Poly1305 tag (16 bytes)
|
||||
/// added by `NoiseCipherState` around every transport plaintext.
|
||||
static let transportCiphertextOverhead = 20
|
||||
|
||||
/// Private files are an explicit BitChat extension to the ordinary Noise
|
||||
/// message-size ceiling. They remain bounded by the same framed-file cap
|
||||
/// used by the binary and fragment decoders. Only the `.privateFile`
|
||||
/// typed-payload path is allowed to use this larger budget.
|
||||
private static let privateFileOuterPacketOverhead =
|
||||
(BinaryProtocol.v1HeaderSize + 2) // v2 adds two length bytes
|
||||
+ BinaryProtocol.senderIDSize
|
||||
+ BinaryProtocol.recipientIDSize
|
||||
static let maxPrivateFilePlaintextSize = FileTransferLimits.maxFramedFileBytes
|
||||
- privateFileOuterPacketOverhead
|
||||
- transportCiphertextOverhead
|
||||
static let maxPrivateFileCiphertextSize =
|
||||
maxPrivateFilePlaintextSize + transportCiphertextOverhead
|
||||
|
||||
// Maximum handshake message size
|
||||
static let maxHandshakeMessageSize = 2048 // 2KB to accommodate XX pattern
|
||||
|
||||
// Noise XX message 1 contains only the initiator's 32-byte ephemeral key.
|
||||
static let xxInitialMessageSize = 32
|
||||
|
||||
// Bounds an ordinary initiator whose message 1 or 2 is lost.
|
||||
static let ordinaryHandshakeTimeout: TimeInterval = 10
|
||||
|
||||
// Bounds the receive-only rollback quarantine created by an unauthenticated
|
||||
// inbound message 1. A lost message 3 must not strand outbound traffic.
|
||||
static let ordinaryResponderHandshakeTimeout: TimeInterval = 20
|
||||
|
||||
// A released client may immediately retry after both crossed initiators
|
||||
// yielded. Give that unilateral retry a brief head start before the
|
||||
// patched side spends its one bounded recovery.
|
||||
static let handshakeCollisionRecoveryDelay: TimeInterval = 0.2
|
||||
|
||||
// Rate-limited recovery remains actionable without spinning.
|
||||
static let handshakeRateLimitRecoveryDelay: TimeInterval = 60
|
||||
|
||||
// Covers only reordering between a winning message 3 and the losing
|
||||
// crossed message 1.
|
||||
static let recentInitiatorCompletionGracePeriod: TimeInterval = 1
|
||||
|
||||
// After unauthenticated responder rollback, reject another attempt long
|
||||
// enough that paced message 1 traffic cannot keep outbound paused. A
|
||||
// legitimate peer converges through the one manager-owned local retry.
|
||||
static let ordinaryReconnectRollbackCooldown: TimeInterval = 60
|
||||
|
||||
// Session timeout - sessions older than this should be renegotiated
|
||||
static let sessionTimeout: TimeInterval = 86400 // 24 hours
|
||||
|
||||
@@ -14,6 +14,19 @@ struct NoiseSecurityValidator {
|
||||
static func validateMessageSize(_ data: Data) -> Bool {
|
||||
return data.count <= NoiseSecurityConstants.maxMessageSize
|
||||
}
|
||||
|
||||
static func validateCiphertextSize(_ data: Data) -> Bool {
|
||||
data.count <= NoiseSecurityConstants.maxMessageSize
|
||||
+ NoiseSecurityConstants.transportCiphertextOverhead
|
||||
}
|
||||
|
||||
static func validatePrivateFileMessageSize(_ data: Data) -> Bool {
|
||||
data.count <= NoiseSecurityConstants.maxPrivateFilePlaintextSize
|
||||
}
|
||||
|
||||
static func validatePrivateFileCiphertextSize(_ data: Data) -> Bool {
|
||||
data.count <= NoiseSecurityConstants.maxPrivateFileCiphertextSize
|
||||
}
|
||||
|
||||
/// Validate handshake message size
|
||||
static func validateHandshakeMessageSize(_ data: Data) -> Bool {
|
||||
|
||||
@@ -13,3 +13,9 @@ enum NoiseSessionError: Error, Equatable {
|
||||
case alreadyEstablished
|
||||
case peerIdentityMismatch
|
||||
}
|
||||
|
||||
/// The manager owns the exact attempt's one bounded recovery. Packet handling
|
||||
/// must not launch its historical second, immediate restart for this failure.
|
||||
struct NoiseManagedHandshakeFailure: Error {
|
||||
let underlying: Error
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -24,8 +24,12 @@ final class SecureNoiseSession: NoiseSession {
|
||||
throw NoiseSecurityError.sessionExhausted
|
||||
}
|
||||
|
||||
// Validate message size
|
||||
guard NoiseSecurityValidator.validateMessageSize(plaintext) else {
|
||||
// Ordinary Noise messages keep the protocol ceiling. Finalized media
|
||||
// is the sole typed-payload extension and remains under the framed-file
|
||||
// cap enforced again at the service and file-decoder layers.
|
||||
let isPrivateFile = NoisePayloadType.isPrivateFile(rawValue: plaintext.first)
|
||||
&& NoiseSecurityValidator.validatePrivateFileMessageSize(plaintext)
|
||||
guard NoiseSecurityValidator.validateMessageSize(plaintext) || isPrivateFile else {
|
||||
throw NoiseSecurityError.messageTooLarge
|
||||
}
|
||||
|
||||
@@ -42,8 +46,11 @@ final class SecureNoiseSession: NoiseSession {
|
||||
throw NoiseSecurityError.sessionExpired
|
||||
}
|
||||
|
||||
// Validate message size
|
||||
guard NoiseSecurityValidator.validateMessageSize(ciphertext) else {
|
||||
// The payload type is encrypted, so a large candidate can only be
|
||||
// bounded here; `NoiseEncryptionService.decrypt` authenticates it and
|
||||
// then requires the resulting type to be `.privateFile`.
|
||||
guard NoiseSecurityValidator.validateCiphertextSize(ciphertext)
|
||||
|| NoiseSecurityValidator.validatePrivateFileCiphertextSize(ciphertext) else {
|
||||
throw NoiseSecurityError.messageTooLarge
|
||||
}
|
||||
|
||||
|
||||
@@ -154,3 +154,90 @@ struct BitchatFilePacket {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Wire-compatible identity for private media exchanged by clients using the
|
||||
/// current iOS entropy-bearing filenames, without extending the deployed file
|
||||
/// TLV. Android clients reject unknown file tags, so eligible senders and
|
||||
/// receivers derive the receipt key from fields already on the wire.
|
||||
///
|
||||
/// Locally-created image and voice-note filenames contain a UUID or live-voice
|
||||
/// burst ID. Including the normalized direction keeps a reused filename
|
||||
/// distinct across chats while allowing short and full Noise-key peer IDs to
|
||||
/// converge. Android and older-iOS timestamp-only names remain ineligible and
|
||||
/// retain their legacy random local IDs (transfer-compatible, no receipts).
|
||||
enum PrivateMediaMessageIdentity {
|
||||
private static let domain = Data("bitchat-private-media-message-v1".utf8)
|
||||
private static let idPrefix = "media-"
|
||||
private static let digestHexLength = 32
|
||||
|
||||
static func isStableID(_ candidate: String) -> Bool {
|
||||
guard candidate.hasPrefix(idPrefix) else { return false }
|
||||
let digest = candidate.dropFirst(idPrefix.count)
|
||||
guard digest.utf8.count == digestHexLength else { return false }
|
||||
return digest.utf8.allSatisfy { byte in
|
||||
(UInt8(ascii: "0")...UInt8(ascii: "9")).contains(byte)
|
||||
|| (UInt8(ascii: "a")...UInt8(ascii: "f")).contains(byte)
|
||||
}
|
||||
}
|
||||
|
||||
static func stableID(
|
||||
senderPeerID: PeerID,
|
||||
recipientPeerID: PeerID,
|
||||
fileName: String?
|
||||
) -> String? {
|
||||
guard let fileName, !fileName.isEmpty else { return nil }
|
||||
let leafName = (fileName as NSString).lastPathComponent
|
||||
guard leafName == fileName else { return nil }
|
||||
|
||||
let path = leafName as NSString
|
||||
let stem = path.deletingPathExtension
|
||||
let fileExtension = path.pathExtension.lowercased()
|
||||
switch true {
|
||||
case stem.hasPrefix("img_"):
|
||||
guard fileExtension == "jpg" || fileExtension == "jpeg" else { return nil }
|
||||
case stem.hasPrefix("voice_"):
|
||||
guard fileExtension == "m4a" else { return nil }
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
let entropyToken = stem.split(separator: "_").last.map(String.init)
|
||||
let hasUUIDEntropy = entropyToken.flatMap(UUID.init(uuidString:)) != nil
|
||||
let voiceBurstID = stem.hasPrefix("voice_")
|
||||
? String(stem.dropFirst("voice_".count))
|
||||
: ""
|
||||
let hasBurstEntropy = voiceBurstID.count == 16
|
||||
&& voiceBurstID.allSatisfy(\.isHexDigit)
|
||||
guard hasUUIDEntropy || hasBurstEntropy else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let fields = [
|
||||
Data(senderPeerID.toShort().bare.utf8),
|
||||
Data(recipientPeerID.toShort().bare.utf8),
|
||||
Data(leafName.utf8)
|
||||
]
|
||||
var input = domain
|
||||
for field in fields {
|
||||
guard let length = UInt32(exactly: field.count) else { return nil }
|
||||
var bigEndianLength = length.bigEndian
|
||||
withUnsafeBytes(of: &bigEndianLength) {
|
||||
input.append(contentsOf: $0)
|
||||
}
|
||||
input.append(field)
|
||||
}
|
||||
|
||||
return "\(idPrefix)\(input.sha256Hex().prefix(digestHexLength))"
|
||||
}
|
||||
|
||||
static func stableID(
|
||||
for packet: BitchatFilePacket,
|
||||
senderPeerID: PeerID,
|
||||
recipientPeerID: PeerID
|
||||
) -> String? {
|
||||
stableID(
|
||||
senderPeerID: senderPeerID,
|
||||
recipientPeerID: recipientPeerID,
|
||||
fileName: packet.fileName
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,12 +79,35 @@ enum NoisePayloadType: UInt8 {
|
||||
case groupKeyUpdate = 0x07 // Creator-signed group state (key rotation / roster update)
|
||||
// Live voice (push-to-talk)
|
||||
case voiceFrame = 0x08 // One live voice-burst packet (see VoiceBurstPacket)
|
||||
// Finalized private media. `0x20` is the value already deployed by the
|
||||
// Android client. The complete BitchatFilePacket is encrypted inside
|
||||
// Noise before the outer noiseEncrypted packet is fragmented.
|
||||
case privateFile = 0x20
|
||||
// Versioned peer state authenticated by the surrounding Noise session.
|
||||
// This is intentionally distinct from the public announce: announce
|
||||
// capabilities are discovery hints, while this payload proves possession
|
||||
// of the advertised Noise static key before downgrade state is pinned.
|
||||
case authenticatedPeerState = 0x21
|
||||
// Verification (QR-based OOB binding)
|
||||
case verifyChallenge = 0x10 // Verification challenge
|
||||
case verifyResponse = 0x11 // Verification response
|
||||
// Transitive verification (web of trust)
|
||||
case vouch = 0x12 // Batch of vouch attestations
|
||||
|
||||
/// #1434 briefly used 0x09 before release. Accept it while prerelease
|
||||
/// builds age out, but never emit it. Decoders canonicalize both values to
|
||||
/// `.privateFile` so the compatibility alias cannot leak into app logic.
|
||||
static let prereleasePrivateFileRawValue: UInt8 = 0x09
|
||||
|
||||
static func decoded(rawValue: UInt8) -> NoisePayloadType? {
|
||||
rawValue == prereleasePrivateFileRawValue ? .privateFile : Self(rawValue: rawValue)
|
||||
}
|
||||
|
||||
static func isPrivateFile(rawValue: UInt8?) -> Bool {
|
||||
guard let rawValue else { return false }
|
||||
return rawValue == privateFile.rawValue || rawValue == prereleasePrivateFileRawValue
|
||||
}
|
||||
|
||||
var description: String {
|
||||
switch self {
|
||||
case .privateMessage: return "privateMessage"
|
||||
@@ -93,6 +116,8 @@ enum NoisePayloadType: UInt8 {
|
||||
case .groupInvite: return "groupInvite"
|
||||
case .groupKeyUpdate: return "groupKeyUpdate"
|
||||
case .voiceFrame: return "voiceFrame"
|
||||
case .privateFile: return "privateFile"
|
||||
case .authenticatedPeerState: return "authenticatedPeerState"
|
||||
case .verifyChallenge: return "verifyChallenge"
|
||||
case .verifyResponse: return "verifyResponse"
|
||||
case .vouch: return "vouch"
|
||||
|
||||
@@ -156,6 +156,89 @@ struct AnnouncementPacket {
|
||||
}
|
||||
}
|
||||
|
||||
/// State that is authoritative only because it is carried inside an
|
||||
/// established Noise session. The public announce remains useful for
|
||||
/// discovery, but its self-signature cannot prove possession of the copied
|
||||
/// Noise public key it contains.
|
||||
///
|
||||
/// Wire format (v1):
|
||||
/// `[version=0x01][type][length][value]...`
|
||||
/// - TLV `0x01`: canonical minimal little-endian `PeerCapabilities`
|
||||
/// - TLV `0x02`: 32-byte Ed25519 signing public key
|
||||
///
|
||||
/// Unknown TLVs are skipped for forward compatibility. Unknown versions,
|
||||
/// duplicates, non-canonical capability fields, and malformed lengths are
|
||||
/// rejected without changing authenticated state.
|
||||
struct AuthenticatedPeerStatePacket: Equatable {
|
||||
static let currentVersion: UInt8 = 1
|
||||
static let signingPublicKeyLength = 32
|
||||
|
||||
let capabilities: PeerCapabilities
|
||||
let signingPublicKey: Data
|
||||
|
||||
private enum TLVType: UInt8 {
|
||||
case capabilities = 0x01
|
||||
case signingPublicKey = 0x02
|
||||
}
|
||||
|
||||
func encode() -> Data? {
|
||||
guard signingPublicKey.count == Self.signingPublicKeyLength else { return nil }
|
||||
let capabilityBytes = capabilities.encoded()
|
||||
guard !capabilityBytes.isEmpty, capabilityBytes.count <= 8 else { return nil }
|
||||
|
||||
var data = Data([Self.currentVersion])
|
||||
data.append(TLVType.capabilities.rawValue)
|
||||
data.append(UInt8(capabilityBytes.count))
|
||||
data.append(capabilityBytes)
|
||||
data.append(TLVType.signingPublicKey.rawValue)
|
||||
data.append(UInt8(signingPublicKey.count))
|
||||
data.append(signingPublicKey)
|
||||
return data
|
||||
}
|
||||
|
||||
static func decode(from data: Data) -> AuthenticatedPeerStatePacket? {
|
||||
guard data.first == Self.currentVersion else { return nil }
|
||||
|
||||
var offset = 1
|
||||
var capabilities: PeerCapabilities?
|
||||
var signingPublicKey: Data?
|
||||
|
||||
while offset < data.count {
|
||||
guard offset + 2 <= data.count else { return nil }
|
||||
let typeRaw = data[offset]
|
||||
let length = Int(data[offset + 1])
|
||||
offset += 2
|
||||
guard offset + length <= data.count else { return nil }
|
||||
let value = Data(data[offset..<(offset + length)])
|
||||
offset += length
|
||||
|
||||
guard let type = TLVType(rawValue: typeRaw) else {
|
||||
continue
|
||||
}
|
||||
switch type {
|
||||
case .capabilities:
|
||||
guard capabilities == nil,
|
||||
!value.isEmpty,
|
||||
value.count <= 8 else { return nil }
|
||||
let decoded = PeerCapabilities(encoded: value)
|
||||
guard decoded.encoded() == value else { return nil }
|
||||
capabilities = decoded
|
||||
|
||||
case .signingPublicKey:
|
||||
guard signingPublicKey == nil,
|
||||
value.count == Self.signingPublicKeyLength else { return nil }
|
||||
signingPublicKey = value
|
||||
}
|
||||
}
|
||||
|
||||
guard let capabilities, let signingPublicKey else { return nil }
|
||||
return AuthenticatedPeerStatePacket(
|
||||
capabilities: capabilities,
|
||||
signingPublicKey: signingPublicKey
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct PrivateMessagePacket {
|
||||
let messageID: String
|
||||
let content: String
|
||||
|
||||
@@ -3,5 +3,11 @@ import BitFoundation
|
||||
extension PeerCapabilities {
|
||||
/// Capabilities this build advertises in its announce packets.
|
||||
/// Each feature adds its bit here when it ships.
|
||||
static let localSupported: PeerCapabilities = [.vouch, .prekeys, .groups]
|
||||
static let localSupported: PeerCapabilities = [
|
||||
.vouch,
|
||||
.prekeys,
|
||||
.groups,
|
||||
.privateMedia,
|
||||
.privateMediaReceipts
|
||||
]
|
||||
}
|
||||
|
||||
@@ -16,6 +16,9 @@ struct BLEAnnounceHandlerEnvironment {
|
||||
let now: () -> Date
|
||||
/// Noise public key already recorded for the peer, if any (registry read).
|
||||
let existingNoisePublicKey: (PeerID) -> Data?
|
||||
/// Ed25519 key previously bound to this Noise identity by an authenticated
|
||||
/// peer-state payload, if any (persistent identity-state read).
|
||||
let authenticatedSigningPublicKey: (_ noisePublicKey: Data) -> Data?
|
||||
/// Verifies the packet signature against the announced signing key.
|
||||
let verifySignature: (_ packet: BitchatPacket, _ signingPublicKey: Data) -> Bool
|
||||
/// Direct link state for the peer (BLE-queue read).
|
||||
@@ -130,11 +133,21 @@ final class BLEAnnounceHandler {
|
||||
hasSignature: hasSignature,
|
||||
signatureValid: signatureValid,
|
||||
existingNoisePublicKey: existingNoisePublicKey,
|
||||
announcedNoisePublicKey: announcement.noisePublicKey
|
||||
announcedNoisePublicKey: announcement.noisePublicKey,
|
||||
authenticatedSigningPublicKey: env.authenticatedSigningPublicKey(
|
||||
announcement.noisePublicKey
|
||||
),
|
||||
announcedSigningPublicKey: announcement.signingPublicKey
|
||||
)
|
||||
if case .reject(.keyMismatch) = trustDecision {
|
||||
SecureLogger.warning("⚠️ Announce key mismatch for \(peerID.id.prefix(8))… — keeping unverified", category: .security)
|
||||
}
|
||||
if case .reject(.authenticatedSigningKeyMismatch) = trustDecision {
|
||||
SecureLogger.warning(
|
||||
"⚠️ Announce signing-key replacement rejected for Noise-authenticated peer \(peerID.id.prefix(8))…",
|
||||
category: .security
|
||||
)
|
||||
}
|
||||
let verifiedAnnounce = trustDecision.isVerified
|
||||
|
||||
var isNewPeer = false
|
||||
|
||||
@@ -56,6 +56,7 @@ enum BLEAnnounceTrustRejection: Equatable {
|
||||
case missingSignature
|
||||
case invalidSignature
|
||||
case keyMismatch
|
||||
case authenticatedSigningKeyMismatch
|
||||
}
|
||||
|
||||
enum BLEAnnounceTrustDecision: Equatable {
|
||||
@@ -72,12 +73,19 @@ enum BLEAnnounceTrustPolicy {
|
||||
hasSignature: Bool,
|
||||
signatureValid: Bool,
|
||||
existingNoisePublicKey: Data?,
|
||||
announcedNoisePublicKey: Data
|
||||
announcedNoisePublicKey: Data,
|
||||
authenticatedSigningPublicKey: Data? = nil,
|
||||
announcedSigningPublicKey: Data? = nil
|
||||
) -> BLEAnnounceTrustDecision {
|
||||
if let existingNoisePublicKey, existingNoisePublicKey != announcedNoisePublicKey {
|
||||
return .reject(.keyMismatch)
|
||||
}
|
||||
|
||||
if let authenticatedSigningPublicKey,
|
||||
announcedSigningPublicKey != authenticatedSigningPublicKey {
|
||||
return .reject(.authenticatedSigningKeyMismatch)
|
||||
}
|
||||
|
||||
guard hasSignature else {
|
||||
return .reject(.missingSignature)
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ struct BLEFileTransferHandlerEnvironment {
|
||||
let peersSnapshot: () -> [PeerID: BLEPeerInfo]
|
||||
/// Verifies a packet's signature against a candidate signing key (registry path).
|
||||
let verifyPacketSignature: (_ packet: BitchatPacket, _ signingPublicKey: Data) -> Bool
|
||||
/// Local signing key used to authenticate our own gossip-sync replays.
|
||||
let localSigningPublicKey: () -> Data
|
||||
/// Resolves a display name from a verified packet signature for peers missing from the registry.
|
||||
let signedSenderDisplayName: (_ packet: BitchatPacket, _ peerID: PeerID) -> String?
|
||||
/// Tracks the broadcast file packet for gossip sync.
|
||||
@@ -30,10 +32,79 @@ struct BLEFileTransferHandlerEnvironment {
|
||||
_ fallbackExtension: String?,
|
||||
_ defaultPrefix: String
|
||||
) -> URL?
|
||||
/// Resolves the durable receiver decision for a stable private-media ID.
|
||||
let privateMediaReceiptState: (
|
||||
_ messageID: String
|
||||
) -> BLEPrivateMediaReceiptState
|
||||
/// Atomically records a stable private-media ID after the payload save.
|
||||
let commitPrivateMediaFile: (_ messageID: String, _ storedURL: URL) -> Bool
|
||||
/// Rolls back a saved payload when its durable receipt commit fails.
|
||||
let removeIncomingFile: (_ storedURL: URL) -> Void
|
||||
/// Checks the authenticated sender before any private-media disk work.
|
||||
let isPrivateMediaSenderBlocked: (PeerID) -> Bool
|
||||
/// Updates the registry last-seen timestamp for the peer (async barrier write).
|
||||
let updatePeerLastSeen: (PeerID) -> Void
|
||||
/// Delivers `.messageReceived` to the UI as one main-actor hop.
|
||||
let deliverMessage: (BitchatMessage) -> Void
|
||||
/// Acknowledges stable private media only after its synchronous
|
||||
/// conversation delivery has completed.
|
||||
let acknowledgePrivateMedia: (_ messageID: String, _ peerID: PeerID) -> Void
|
||||
/// Delivers `.messageReceived` as one main-actor hop while
|
||||
/// `shouldDeliver` remains true before and after the synchronous sink.
|
||||
/// The completion authorizes the stable-media ACK.
|
||||
let deliverMessage: (
|
||||
_ message: BitchatMessage,
|
||||
_ shouldDeliver: @escaping () -> Bool,
|
||||
_ completion: @escaping () -> Void
|
||||
) -> Void
|
||||
}
|
||||
|
||||
/// Process-lifetime reservation cache for stable private-media IDs.
|
||||
///
|
||||
/// The first arrival reserves its ID before quota enforcement. Concurrent
|
||||
/// arrivals remain coalesced in memory, while accepted state is resolved from
|
||||
/// the durable ID-to-file ledger so it survives relaunch and becomes retryable
|
||||
/// if quota cleanup removed the file.
|
||||
private final class PrivateMediaArrivalDeduplicator {
|
||||
enum Reservation {
|
||||
case reserved
|
||||
case pending
|
||||
case accepted(URL)
|
||||
case tombstoned
|
||||
case unavailable
|
||||
}
|
||||
|
||||
private let lock = NSLock()
|
||||
private var pending: Set<String> = []
|
||||
|
||||
func reserve(
|
||||
_ messageID: String,
|
||||
receiptState: () -> BLEPrivateMediaReceiptState
|
||||
) -> Reservation {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
if pending.contains(messageID) {
|
||||
return .pending
|
||||
}
|
||||
|
||||
switch receiptState() {
|
||||
case .accepted(let existingURL):
|
||||
return .accepted(existingURL)
|
||||
case .tombstoned:
|
||||
return .tombstoned
|
||||
case .unavailable:
|
||||
return .unavailable
|
||||
case .absent:
|
||||
break
|
||||
}
|
||||
|
||||
pending.insert(messageID)
|
||||
return .reserved
|
||||
}
|
||||
|
||||
func finish(_ messageID: String) {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
pending.remove(messageID)
|
||||
}
|
||||
}
|
||||
|
||||
/// Orchestrates inbound file transfers: self-echo policy, sender display-name
|
||||
@@ -41,61 +112,204 @@ struct BLEFileTransferHandlerEnvironment {
|
||||
/// and UI delivery.
|
||||
final class BLEFileTransferHandler {
|
||||
private let environment: BLEFileTransferHandlerEnvironment
|
||||
private let privateMediaArrivals = PrivateMediaArrivalDeduplicator()
|
||||
|
||||
init(environment: BLEFileTransferHandlerEnvironment) {
|
||||
self.environment = environment
|
||||
}
|
||||
|
||||
/// Returns `false` when the packet fails sender authentication and must
|
||||
/// not be relayed onward. Every other outcome returns `true`: files
|
||||
/// directed to another peer are forwarded untouched, and local-only drops
|
||||
/// (malformed payload, quota, save failure) don't affect multi-hop
|
||||
/// delivery to nodes that may handle them fine.
|
||||
/// Returns `false` when the raw packet fails sender authentication (or is
|
||||
/// a live self-echo) and must not be relayed onward. Authentication runs
|
||||
/// before the routing decision, so a forged directed packet cannot use a
|
||||
/// node that is not its recipient as an unsigned forwarding hop.
|
||||
@discardableResult
|
||||
func handle(_ packet: BitchatPacket, from peerID: PeerID) -> Bool {
|
||||
let env = environment
|
||||
if BLEFileTransferPolicy.isSelfEcho(packet: packet, from: peerID, localPeerID: env.localPeerID()) { return true }
|
||||
|
||||
guard let deliveryPlan = BLEFileTransferPolicy.deliveryPlan(packet: packet, localPeerID: env.localPeerID()) else {
|
||||
return true
|
||||
}
|
||||
|
||||
let localPeerID = env.localPeerID()
|
||||
let peersSnapshot = env.peersSnapshot()
|
||||
guard let senderNickname = resolveSenderNickname(
|
||||
|
||||
guard let senderNickname = authenticatedRawSenderNickname(
|
||||
packet: packet,
|
||||
from: peerID,
|
||||
isBroadcast: !deliveryPlan.isPrivateMessage,
|
||||
peers: peersSnapshot,
|
||||
env: env
|
||||
) else {
|
||||
SecureLogger.warning("🚫 Dropping file transfer from unverified or unknown peer \(peerID.id.prefix(8))…", category: .security)
|
||||
SecureLogger.warning("🚫 Dropping raw file transfer with missing/invalid signature from \(peerID.id.prefix(8))…", category: .security)
|
||||
return false
|
||||
}
|
||||
|
||||
if BLEFileTransferPolicy.isSelfEcho(packet: packet, from: peerID, localPeerID: localPeerID) {
|
||||
return false
|
||||
}
|
||||
|
||||
guard let deliveryPlan = BLEFileTransferPolicy.deliveryPlan(packet: packet, localPeerID: localPeerID) else {
|
||||
return true
|
||||
}
|
||||
|
||||
if deliveryPlan.shouldTrackForSync {
|
||||
env.trackPacketSeen(packet)
|
||||
}
|
||||
|
||||
_ = storeIncomingPayload(
|
||||
packet.payload,
|
||||
from: peerID,
|
||||
senderNickname: senderNickname,
|
||||
timestamp: Date(timeIntervalSince1970: Double(packet.timestamp) / 1000),
|
||||
isPrivate: deliveryPlan.isPrivateMessage,
|
||||
usesDurableReceipts: false,
|
||||
env: env
|
||||
)
|
||||
// Once authenticated, a local decode/quota/save failure is not proof
|
||||
// that downstream nodes should be denied the valid signed packet.
|
||||
return true
|
||||
}
|
||||
|
||||
/// Accepts a file packet only after it has been authenticated and
|
||||
/// decrypted by the peer's Noise session. The inner packet deliberately
|
||||
/// has no redundant signature: Noise supplies sender authentication and
|
||||
/// confidentiality, while this handler retains the same validation,
|
||||
/// quota, persistence, and UI-delivery behavior as public files.
|
||||
@discardableResult
|
||||
func handlePrivatePayload(_ payload: Data, from peerID: PeerID, timestamp: Date) -> Bool {
|
||||
let env = environment
|
||||
let peers = env.peersSnapshot()
|
||||
let senderNickname = BLEPeerSenderDisplayName.resolveKnownPeer(
|
||||
peerID: peerID,
|
||||
localPeerID: env.localPeerID(),
|
||||
localNickname: env.localNickname(),
|
||||
peers: peers,
|
||||
allowConnectedUnverified: true
|
||||
) ?? BLEPeerSenderDisplayName.anonymousNickname(for: peerID)
|
||||
|
||||
return storeIncomingPayload(
|
||||
payload,
|
||||
from: peerID,
|
||||
senderNickname: senderNickname,
|
||||
timestamp: timestamp,
|
||||
isPrivate: true,
|
||||
// Every authenticated Noise private-file keeps the stable ID/ACK
|
||||
// contract introduced with capability bit 8. Bit 9 advertises
|
||||
// sender-side automatic retry support; it must not downgrade
|
||||
// prior iOS clients to random IDs or single-check delivery.
|
||||
usesDurableReceipts: true,
|
||||
env: env
|
||||
)
|
||||
}
|
||||
|
||||
private func storeIncomingPayload(
|
||||
_ payload: Data,
|
||||
from peerID: PeerID,
|
||||
senderNickname: String,
|
||||
timestamp: Date,
|
||||
isPrivate: Bool,
|
||||
usesDurableReceipts: Bool,
|
||||
env: BLEFileTransferHandlerEnvironment
|
||||
) -> Bool {
|
||||
|
||||
let localPeerID = env.localPeerID()
|
||||
let filePacket: BitchatFilePacket
|
||||
let mime: MimeType
|
||||
switch BLEIncomingFileValidator.validate(payload: packet.payload) {
|
||||
switch BLEIncomingFileValidator.validate(payload: payload) {
|
||||
case .success(let acceptance):
|
||||
filePacket = acceptance.filePacket
|
||||
mime = acceptance.mime
|
||||
case .failure(.malformedPayload):
|
||||
SecureLogger.error("❌ Failed to decode file transfer payload", category: .session)
|
||||
return true
|
||||
return false
|
||||
case .failure(.payloadTooLarge(let bytes)):
|
||||
SecureLogger.warning("🚫 Dropping file transfer exceeding size cap (\(bytes) bytes)", category: .security)
|
||||
return true
|
||||
return false
|
||||
case .failure(.unsupportedMime(let mimeType, let bytes)):
|
||||
SecureLogger.warning("🚫 MIME REJECT: '\(mimeType ?? "<empty>")' not supported. Size=\(bytes)b from \(peerID.id.prefix(8))...", category: .security)
|
||||
return true
|
||||
return false
|
||||
case .failure(.magicMismatch(let mime, let bytes, let prefixHex)):
|
||||
SecureLogger.warning("🚫 MAGIC REJECT: MIME='\(mime)' size=\(bytes)b prefix=[\(prefixHex)] from \(peerID.id.prefix(8))...", category: .security)
|
||||
return false
|
||||
}
|
||||
|
||||
if isPrivate, env.isPrivateMediaSenderBlocked(peerID) {
|
||||
SecureLogger.debug(
|
||||
"🚫 Dropping private media from blocked peer \(peerID.id.prefix(8))… before disk write",
|
||||
category: .security
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
let messageID = usesDurableReceipts
|
||||
? PrivateMediaMessageIdentity.stableID(
|
||||
for: filePacket,
|
||||
senderPeerID: peerID,
|
||||
recipientPeerID: localPeerID
|
||||
)
|
||||
: nil
|
||||
if let messageID {
|
||||
switch privateMediaArrivals.reserve(
|
||||
messageID,
|
||||
receiptState: { env.privateMediaReceiptState(messageID) }
|
||||
) {
|
||||
case .reserved:
|
||||
break
|
||||
case .pending:
|
||||
// The first arrival has not reached durable storage yet.
|
||||
// Coalesce this retry without ACKing so a failed first save
|
||||
// remains retryable by the sender.
|
||||
SecureLogger.debug(
|
||||
"📁 Coalesced in-flight private media id=\(messageID.prefix(12))… from \(peerID.id.prefix(8))…",
|
||||
category: .session
|
||||
)
|
||||
return true
|
||||
case .accepted(let existingFile):
|
||||
env.updatePeerLastSeen(peerID)
|
||||
let message = incomingMessage(
|
||||
messageID: messageID,
|
||||
senderNickname: senderNickname,
|
||||
timestamp: timestamp,
|
||||
isPrivate: true,
|
||||
peerID: peerID,
|
||||
destination: existingFile,
|
||||
category: storedMediaCategory(
|
||||
for: existingFile,
|
||||
fallback: mime.category
|
||||
),
|
||||
env: env
|
||||
)
|
||||
SecureLogger.debug(
|
||||
"📁 Restored durable private media duplicate id=\(messageID.prefix(12))… from \(peerID.id.prefix(8))… -> \(existingFile.lastPathComponent)",
|
||||
category: .session
|
||||
)
|
||||
deliverStableMessage(
|
||||
message,
|
||||
messageID: messageID,
|
||||
peerID: peerID,
|
||||
expectedURL: existingFile,
|
||||
env: env
|
||||
)
|
||||
return true
|
||||
case .tombstoned:
|
||||
// Explicit deletion is a durable terminal receiver decision.
|
||||
env.updatePeerLastSeen(peerID)
|
||||
env.acknowledgePrivateMedia(messageID, peerID)
|
||||
SecureLogger.debug(
|
||||
"📁 Dropped explicitly deleted private media id=\(messageID.prefix(12))… from \(peerID.id.prefix(8))…",
|
||||
category: .session
|
||||
)
|
||||
return true
|
||||
case .unavailable:
|
||||
// Never turn an unreadable ledger into an empty ledger. The
|
||||
// sender can retry after the transient storage failure clears.
|
||||
SecureLogger.warning(
|
||||
"📁 Withholding private media id=\(messageID.prefix(12))… while durable receipt state is unavailable",
|
||||
category: .session
|
||||
)
|
||||
return true
|
||||
}
|
||||
}
|
||||
defer {
|
||||
if let messageID {
|
||||
privateMediaArrivals.finish(messageID)
|
||||
}
|
||||
}
|
||||
|
||||
// BCH-01-002: Enforce storage quota before saving
|
||||
env.enforceStorageQuota(filePacket.content.count)
|
||||
|
||||
@@ -106,82 +320,155 @@ final class BLEFileTransferHandler {
|
||||
mime.defaultExtension,
|
||||
mime.category.rawValue
|
||||
) else {
|
||||
return true
|
||||
return false
|
||||
}
|
||||
|
||||
if deliveryPlan.isPrivateMessage {
|
||||
if let messageID,
|
||||
!env.commitPrivateMediaFile(messageID, destination) {
|
||||
// A payload without its durable ID mapping cannot safely suppress
|
||||
// a retry after relaunch. Roll it back and withhold UI/ACK.
|
||||
env.removeIncomingFile(destination)
|
||||
return false
|
||||
}
|
||||
|
||||
if isPrivate {
|
||||
env.updatePeerLastSeen(peerID)
|
||||
}
|
||||
|
||||
let ts = Date(timeIntervalSince1970: Double(packet.timestamp) / 1000)
|
||||
let message = BitchatMessage(
|
||||
sender: senderNickname,
|
||||
content: "\(mime.category.messagePrefix)\(destination.lastPathComponent)",
|
||||
timestamp: ts,
|
||||
isRelay: false,
|
||||
originalSender: nil,
|
||||
isPrivate: deliveryPlan.isPrivateMessage,
|
||||
recipientNickname: nil,
|
||||
senderPeerID: peerID,
|
||||
// Received messages need an explicit status: BitchatMessage
|
||||
// defaults private messages to .sending, which the media views
|
||||
// render as an in-flight send (empty reveal mask, disabled tap).
|
||||
deliveryStatus: deliveryPlan.isPrivateMessage
|
||||
? .delivered(to: env.localNickname(), at: ts)
|
||||
: nil
|
||||
let message = incomingMessage(
|
||||
messageID: messageID,
|
||||
senderNickname: senderNickname,
|
||||
timestamp: timestamp,
|
||||
isPrivate: isPrivate,
|
||||
peerID: peerID,
|
||||
destination: destination,
|
||||
category: mime.category,
|
||||
env: env
|
||||
)
|
||||
|
||||
SecureLogger.debug("📁 Stored incoming media from \(peerID.id.prefix(8))… -> \(destination.lastPathComponent)", category: .session)
|
||||
|
||||
env.deliverMessage(message)
|
||||
if let messageID {
|
||||
deliverStableMessage(
|
||||
message,
|
||||
messageID: messageID,
|
||||
peerID: peerID,
|
||||
expectedURL: destination,
|
||||
env: env
|
||||
)
|
||||
} else {
|
||||
env.deliverMessage(message, { true }, {})
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// Resolves the authenticated display name for a file transfer's sender.
|
||||
///
|
||||
/// Directed (private) transfers are addressed to us specifically and keep
|
||||
/// the lenient connected-peer path. Broadcast transfers carry an
|
||||
/// attacker-controllable `senderID` exactly like public messages and public
|
||||
/// voice frames — registry membership alone is NOT proof of identity, so a
|
||||
/// valid packet signature from the claimed sender is required before we
|
||||
/// trust it. Without this, a peer that observed a public voice burst could
|
||||
/// spoof a broadcast `voice_<burstID>.m4a` note under the talker's ID and
|
||||
/// overwrite the signature-verified live bubble with attacker audio.
|
||||
private func resolveSenderNickname(
|
||||
private func deliverStableMessage(
|
||||
_ message: BitchatMessage,
|
||||
messageID: String,
|
||||
peerID: PeerID,
|
||||
expectedURL: URL,
|
||||
env: BLEFileTransferHandlerEnvironment
|
||||
) {
|
||||
env.deliverMessage(
|
||||
message,
|
||||
{
|
||||
guard case .accepted(let resolvedURL) =
|
||||
env.privateMediaReceiptState(messageID) else {
|
||||
return false
|
||||
}
|
||||
return resolvedURL.standardizedFileURL
|
||||
== expectedURL.standardizedFileURL
|
||||
},
|
||||
{
|
||||
env.acknowledgePrivateMedia(messageID, peerID)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private func incomingMessage(
|
||||
messageID: String?,
|
||||
senderNickname: String,
|
||||
timestamp: Date,
|
||||
isPrivate: Bool,
|
||||
peerID: PeerID,
|
||||
destination: URL,
|
||||
category: MimeType.Category,
|
||||
env: BLEFileTransferHandlerEnvironment
|
||||
) -> BitchatMessage {
|
||||
BitchatMessage(
|
||||
id: messageID,
|
||||
sender: senderNickname,
|
||||
content: "\(category.messagePrefix)\(destination.lastPathComponent)",
|
||||
timestamp: timestamp,
|
||||
isRelay: false,
|
||||
originalSender: nil,
|
||||
isPrivate: isPrivate,
|
||||
recipientNickname: nil,
|
||||
senderPeerID: peerID,
|
||||
// Received messages need an explicit status: BitchatMessage
|
||||
// defaults private messages to .sending, which media views render
|
||||
// as an in-flight send.
|
||||
deliveryStatus: isPrivate
|
||||
? .delivered(to: env.localNickname(), at: timestamp)
|
||||
: nil
|
||||
)
|
||||
}
|
||||
|
||||
/// The durable URL is authoritative during reconstruction. A sender that
|
||||
/// reuses a stable filename with a different MIME type must not change how
|
||||
/// the already-stored payload renders.
|
||||
private func storedMediaCategory(
|
||||
for url: URL,
|
||||
fallback: MimeType.Category
|
||||
) -> MimeType.Category {
|
||||
let mediaDirectory = url
|
||||
.deletingLastPathComponent()
|
||||
.deletingLastPathComponent()
|
||||
.lastPathComponent
|
||||
switch mediaDirectory {
|
||||
case MimeType.Category.audio.mediaDir:
|
||||
return .audio
|
||||
case MimeType.Category.image.mediaDir:
|
||||
return .image
|
||||
case MimeType.Category.file.mediaDir:
|
||||
return .file
|
||||
default:
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
/// Every remaining raw file transfer is signed, regardless of whether it
|
||||
/// is broadcast, addressed to us, or merely passing through. Registry
|
||||
/// signing keys are preferred; persisted identities cover peers that have
|
||||
/// rotated or are not currently present in the registry.
|
||||
private func authenticatedRawSenderNickname(
|
||||
packet: BitchatPacket,
|
||||
from peerID: PeerID,
|
||||
isBroadcast: Bool,
|
||||
peers: [PeerID: BLEPeerInfo],
|
||||
env: BLEFileTransferHandlerEnvironment
|
||||
) -> String? {
|
||||
guard isBroadcast else {
|
||||
return BLEPeerSenderDisplayName.resolveKnownPeer(
|
||||
peerID: peerID,
|
||||
localPeerID: env.localPeerID(),
|
||||
localNickname: env.localNickname(),
|
||||
peers: peers,
|
||||
allowConnectedUnverified: true
|
||||
) ?? env.signedSenderDisplayName(packet, peerID)
|
||||
}
|
||||
guard packet.signature != nil else { return nil }
|
||||
|
||||
// Our own broadcasts replayed back via gossip sync (ttl==0) are
|
||||
// trivially authentic and cannot be verified against the peer registry
|
||||
// or identity cache, so exempt self exactly as `BLEPublicMessageHandler`
|
||||
// does. Verify against the signing key already in the
|
||||
// (synchronously-updated) registry first, then fall back to the
|
||||
// persisted-identity signature lookup for peers not yet cached there.
|
||||
let isSelf = peerID == env.localPeerID()
|
||||
let registrySigningKey = peers[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 { return nil }
|
||||
let localPeerID = env.localPeerID()
|
||||
let candidateKey = peerID == localPeerID
|
||||
? env.localSigningPublicKey()
|
||||
: peers[peerID]?.signingPublicKey
|
||||
let verifiedWithKnownKey = candidateKey.map {
|
||||
env.verifyPacketSignature(packet, $0)
|
||||
} ?? false
|
||||
let signedDisplayName = verifiedWithKnownKey
|
||||
? nil
|
||||
: env.signedSenderDisplayName(packet, peerID)
|
||||
guard verifiedWithKnownKey || signedDisplayName != nil else { return nil }
|
||||
|
||||
return BLEPeerSenderDisplayName.resolveKnownPeer(
|
||||
peerID: peerID,
|
||||
localPeerID: env.localPeerID(),
|
||||
localPeerID: localPeerID,
|
||||
localNickname: env.localNickname(),
|
||||
peers: peers,
|
||||
allowConnectedUnverified: false
|
||||
) ?? signedDisplayName
|
||||
// The packet signature authenticates the announced peer; the old
|
||||
// connected-but-unsigned leniency is not involved.
|
||||
allowConnectedUnverified: true
|
||||
) ?? signedDisplayName ?? BLEPeerSenderDisplayName.anonymousNickname(for: peerID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,8 +201,11 @@ struct BLEFragmentAssemblyBuffer {
|
||||
}
|
||||
|
||||
private static func assemblyLimit(for originalType: UInt8) -> Int {
|
||||
if originalType == MessageType.fileTransfer.rawValue {
|
||||
if originalType == MessageType.fileTransfer.rawValue
|
||||
|| originalType == MessageType.noiseEncrypted.rawValue {
|
||||
// Allow headroom for TLV metadata and binary framing overhead.
|
||||
// A large noiseEncrypted packet can be an E2E-encrypted private
|
||||
// file; its authenticated plaintext is validated after decrypt.
|
||||
return FileTransferLimits.maxFramedFileBytes
|
||||
}
|
||||
|
||||
|
||||
@@ -134,6 +134,7 @@ struct BLEIncomingFileStore {
|
||||
private let baseDirectory: URL?
|
||||
private let dateProvider: () -> Date
|
||||
private let panicMarkerWriter: (Data, URL) throws -> Void
|
||||
private let privateMediaReceipts: BLEPrivateMediaReceiptStore
|
||||
|
||||
init(
|
||||
fileManager: FileManager = .default,
|
||||
@@ -147,6 +148,11 @@ struct BLEIncomingFileStore {
|
||||
self.baseDirectory = baseDirectory
|
||||
self.dateProvider = dateProvider
|
||||
self.panicMarkerWriter = panicMarkerWriter
|
||||
self.privateMediaReceipts = BLEPrivateMediaReceiptStore(
|
||||
fileManager: fileManager,
|
||||
baseDirectory: baseDirectory,
|
||||
now: dateProvider
|
||||
)
|
||||
}
|
||||
|
||||
/// Panic-wipe every managed incoming and outgoing media artifact before
|
||||
@@ -159,6 +165,11 @@ struct BLEIncomingFileStore {
|
||||
func panicWipe(
|
||||
hasDurablePendingMarker: Bool = false
|
||||
) throws {
|
||||
// The receipt index caches tombstones as well as accepted payloads.
|
||||
// Always invalidate it on return, including partial-failure paths, so
|
||||
// no pre-panic receiver decision survives after identity reset.
|
||||
defer { privateMediaReceipts.resetForPanic() }
|
||||
|
||||
let markerError: Error?
|
||||
do {
|
||||
try markPanicRecoveryPending()
|
||||
@@ -257,6 +268,35 @@ struct BLEIncomingFileStore {
|
||||
}
|
||||
}
|
||||
|
||||
func privateMediaReceiptState(
|
||||
messageID: String
|
||||
) -> BLEPrivateMediaReceiptState {
|
||||
privateMediaReceipts.state(for: messageID)
|
||||
}
|
||||
|
||||
func commitPrivateMediaFile(
|
||||
messageID: String,
|
||||
storedURL: URL
|
||||
) -> Bool {
|
||||
privateMediaReceipts.commitAccepted(
|
||||
messageID: messageID,
|
||||
storedURL: storedURL
|
||||
)
|
||||
}
|
||||
|
||||
/// Best-effort rollback for a payload whose durable receipt commit failed.
|
||||
func removeIncomingFile(at storedURL: URL) {
|
||||
guard isURLInsideFilesDirectory(storedURL) else { return }
|
||||
do {
|
||||
try fileManager.removeItem(at: storedURL)
|
||||
} catch {
|
||||
SecureLogger.warning(
|
||||
"⚠️ Failed to roll back uncommitted incoming media: \(error)",
|
||||
category: .session
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees least-recently-modified incoming files until `reservingBytes`
|
||||
/// fits under the quota. Files named `voice_live_*` (in-flight live
|
||||
/// captures) are never evicted regardless of who triggers enforcement —
|
||||
@@ -349,6 +389,13 @@ struct BLEIncomingFileStore {
|
||||
]
|
||||
}
|
||||
|
||||
private func isURLInsideFilesDirectory(_ url: URL) -> Bool {
|
||||
guard let filesDirectory = try? filesDirectory().standardizedFileURL else {
|
||||
return false
|
||||
}
|
||||
return url.standardizedFileURL.path.hasPrefix(filesDirectory.path + "/")
|
||||
}
|
||||
|
||||
private func sanitizedFileName(_ name: String?, defaultName: String, fallbackExtension: String?) -> String {
|
||||
var candidate = (name ?? "")
|
||||
.replacingOccurrences(of: "\0", with: "")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import BitFoundation
|
||||
import BitLogger
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
|
||||
struct BLENoiseHandshakeHandlingResult {
|
||||
@@ -7,6 +8,11 @@ struct BLENoiseHandshakeHandlingResult {
|
||||
let didEstablishAuthenticatedSession: Bool
|
||||
}
|
||||
|
||||
struct BLENoiseDecryptionResult {
|
||||
let plaintext: Data
|
||||
let sessionGeneration: UUID
|
||||
}
|
||||
|
||||
/// Narrow environment for `BLENoisePacketHandler`.
|
||||
///
|
||||
/// All queue hops (collections barrier writes, main-actor UI notification)
|
||||
@@ -28,6 +34,8 @@ struct BLENoisePacketHandlerEnvironment {
|
||||
-> NoiseHandshakeProcessingResult
|
||||
/// Whether any Noise session (established or pending) exists for the peer (crypto).
|
||||
let hasNoiseSession: (PeerID) -> Bool
|
||||
/// Whether an inbound ordinary XX responder is waiting for message 3.
|
||||
let isAwaitingResponderHandshakeCompletion: (PeerID) -> Bool
|
||||
/// Initiates a fresh Noise handshake with the peer (crypto + send).
|
||||
let initiateHandshake: (PeerID) -> Void
|
||||
/// Broadcasts a packet on the mesh (caller is already on the message queue).
|
||||
@@ -35,9 +43,16 @@ struct BLENoisePacketHandlerEnvironment {
|
||||
/// Updates the registry last-seen timestamp for the peer (async barrier write).
|
||||
let updatePeerLastSeen: (PeerID) -> Void
|
||||
/// Decrypts an encrypted payload from the peer (crypto).
|
||||
let decrypt: (_ payload: Data, _ peerID: PeerID) throws -> Data
|
||||
let decrypt: (_ payload: Data, _ peerID: PeerID) throws -> BLENoiseDecryptionResult
|
||||
/// Clears the peer's Noise session after an unrecoverable decrypt failure (crypto).
|
||||
let clearSession: (PeerID) -> Void
|
||||
/// Consumes session-authenticated protocol state inside the transport. It
|
||||
/// must never escape to UI or Nostr payload dispatch.
|
||||
let handleAuthenticatedPeerState: (
|
||||
_ peerID: PeerID,
|
||||
_ payload: Data,
|
||||
_ sessionGeneration: UUID
|
||||
) -> Void
|
||||
/// Delivers `.noisePayloadReceived` to the UI as one main-actor hop.
|
||||
let deliverNoisePayload: (
|
||||
_ peerID: PeerID,
|
||||
@@ -51,15 +66,36 @@ struct BLENoisePacketHandlerEnvironment {
|
||||
/// processing (with response), encrypted payload decryption and dispatch,
|
||||
/// and session recovery on decrypt failure.
|
||||
final class BLENoisePacketHandler {
|
||||
private struct DeferredCiphertext {
|
||||
let packet: BitchatPacket
|
||||
let receivedAt: Date
|
||||
}
|
||||
|
||||
/// Early post-handshake packets are normally tiny control messages or
|
||||
/// queued DMs. Keep the recovery surface deliberately small so an
|
||||
/// unauthenticated half-handshake cannot create an unbounded memory queue.
|
||||
private static let maxDeferredPacketsPerPeer = 4
|
||||
private static let maxDeferredPacketsGlobal = 32
|
||||
/// One legacy sender can immediately follow message 3 with the largest
|
||||
/// valid private-file ciphertext and has no application-level retry. Keep
|
||||
/// room for that packet plus a small control-message budget.
|
||||
private static let maxDeferredBytes =
|
||||
NoiseSecurityConstants.maxPrivateFileCiphertextSize + 256 * 1024
|
||||
private static let deferredLifetime =
|
||||
NoiseSecurityConstants.ordinaryResponderHandshakeTimeout
|
||||
|
||||
private let environment: BLENoisePacketHandlerEnvironment
|
||||
private let deferredLock = NSLock()
|
||||
private var deferredCiphertexts: [PeerID: [DeferredCiphertext]] = [:]
|
||||
private var deferredCiphertextBytes = 0
|
||||
|
||||
init(environment: BLENoisePacketHandlerEnvironment) {
|
||||
self.environment = environment
|
||||
}
|
||||
|
||||
/// Returns true when the handshake message was processed successfully.
|
||||
/// Callers use this to distinguish an authenticated replacement completion
|
||||
/// from a rejected candidate while an older session remains established.
|
||||
/// Callers use this to distinguish an authenticated reconnect completion
|
||||
/// from a rejected ordinary responder while rollback state is restored.
|
||||
@discardableResult
|
||||
func handleHandshake(_ packet: BitchatPacket, from peerID: PeerID) -> Bool {
|
||||
handleHandshakeWithResult(packet, from: peerID).processed
|
||||
@@ -93,15 +129,23 @@ final class BLENoisePacketHandler {
|
||||
env.broadcastPacket(responsePacket)
|
||||
}
|
||||
|
||||
// Session establishment will trigger onPeerAuthenticated callback
|
||||
// which will send any pending messages at the right time
|
||||
// The serialized authentication callback installs transport
|
||||
// state before it drains any bounded early ciphertext.
|
||||
return BLENoiseHandshakeHandlingResult(
|
||||
processed: true,
|
||||
didEstablishAuthenticatedSession:
|
||||
result.didEstablishAuthenticatedSession
|
||||
)
|
||||
} catch let managedFailure as NoiseManagedHandshakeFailure {
|
||||
SecureLogger.error(
|
||||
"Failed to process handshake; manager owns recovery: \(managedFailure.underlying)"
|
||||
)
|
||||
return BLENoiseHandshakeHandlingResult(
|
||||
processed: false,
|
||||
didEstablishAuthenticatedSession: false
|
||||
)
|
||||
} catch NoiseSessionError.peerIdentityMismatch {
|
||||
// The candidate was already discarded by the session manager.
|
||||
// The responder was already discarded by the session manager.
|
||||
// Do not let a spoofed claimed ID trigger a fresh outbound
|
||||
// handshake or recreate state for the attacker-selected ID.
|
||||
SecureLogger.warning(
|
||||
@@ -131,6 +175,30 @@ final class BLENoisePacketHandler {
|
||||
}
|
||||
|
||||
func handleEncrypted(_ packet: BitchatPacket, from peerID: PeerID) {
|
||||
handleEncrypted(packet, from: peerID, isDeferredRetry: false)
|
||||
}
|
||||
|
||||
/// Called by the transport's serialized authentication callback after it
|
||||
/// has installed state for the promoted or restored session generation.
|
||||
func handleSessionAuthenticated(_ peerID: PeerID) {
|
||||
drainDeferredCiphertextsIfReady(for: peerID)
|
||||
}
|
||||
|
||||
/// Synchronously discards ciphertext retained for a pre-panic Noise
|
||||
/// generation. The handler survives the service's identity replacement,
|
||||
/// so keeping this queue would replay old bytes after post-panic auth.
|
||||
func resetForPanic() {
|
||||
deferredLock.lock()
|
||||
deferredCiphertexts.removeAll(keepingCapacity: false)
|
||||
deferredCiphertextBytes = 0
|
||||
deferredLock.unlock()
|
||||
}
|
||||
|
||||
private func handleEncrypted(
|
||||
_ packet: BitchatPacket,
|
||||
from peerID: PeerID,
|
||||
isDeferredRetry: Bool
|
||||
) {
|
||||
let env = environment
|
||||
guard let recipientID = PeerID(hexData: packet.recipientID) else {
|
||||
SecureLogger.warning("⚠️ Encrypted message has no recipient ID", category: .session)
|
||||
@@ -146,35 +214,231 @@ final class BLENoisePacketHandler {
|
||||
env.updatePeerLastSeen(peerID)
|
||||
|
||||
do {
|
||||
let decrypted = try env.decrypt(packet.payload, peerID)
|
||||
let decryption = try env.decrypt(packet.payload, peerID)
|
||||
let decrypted = decryption.plaintext
|
||||
guard decrypted.count > 0 else { return }
|
||||
|
||||
// First byte indicates the payload type
|
||||
let payloadType = decrypted[0]
|
||||
let payloadData = decrypted.dropFirst()
|
||||
|
||||
guard let noisePayloadType = NoisePayloadType(rawValue: payloadType) else {
|
||||
guard let noisePayloadType = NoisePayloadType.decoded(rawValue: payloadType) else {
|
||||
SecureLogger.warning("⚠️ Unknown noise payload type: \(payloadType)")
|
||||
return
|
||||
}
|
||||
|
||||
SecureLogger.debug("🔐 Decrypted noise payload type \(noisePayloadType.description) from \(peerID.id.prefix(8))…", category: .session)
|
||||
|
||||
if noisePayloadType == .authenticatedPeerState {
|
||||
env.handleAuthenticatedPeerState(
|
||||
peerID,
|
||||
Data(payloadData),
|
||||
decryption.sessionGeneration
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
let ts = Date(timeIntervalSince1970: Double(packet.timestamp) / 1000)
|
||||
env.deliverNoisePayload(peerID, noisePayloadType, Data(payloadData), ts)
|
||||
} catch NoiseEncryptionError.transportGenerationNotReady {
|
||||
if isDeferredRetry {
|
||||
SecureLogger.warning(
|
||||
"Dropping deferred Noise ciphertext from \(peerID.id.prefix(8))… because its authenticated transport generation changed again",
|
||||
category: .session
|
||||
)
|
||||
return
|
||||
}
|
||||
// The manager promoted or restored keys before BLE's serialized
|
||||
// callback installed generation-bound transport state. The
|
||||
// manager rejected this before decrypting, so replay is safe.
|
||||
deferCiphertext(packet, from: peerID)
|
||||
} catch NoiseEncryptionError.sessionNotEstablished {
|
||||
if isDeferredRetry {
|
||||
SecureLogger.warning(
|
||||
"Dropping deferred Noise ciphertext from \(peerID.id.prefix(8))… because the authenticated session is unavailable",
|
||||
category: .session
|
||||
)
|
||||
return
|
||||
}
|
||||
// We received an encrypted message before establishing a session with this peer.
|
||||
// Trigger a handshake so future messages can be decrypted.
|
||||
// An initiator may already have sent message 3 followed by this
|
||||
// ciphertext, with BLE delivering the ciphertext first.
|
||||
if env.isAwaitingResponderHandshakeCompletion(peerID) {
|
||||
deferCiphertext(packet, from: peerID)
|
||||
return
|
||||
}
|
||||
// Otherwise trigger a handshake so future messages can decrypt.
|
||||
SecureLogger.debug("🔑 Encrypted message from \(peerID.id.prefix(8))… without session; initiating handshake")
|
||||
if !env.hasNoiseSession(peerID) {
|
||||
env.initiateHandshake(peerID)
|
||||
}
|
||||
} catch {
|
||||
if isDeferredRetry {
|
||||
// An early packet cannot tear down the authenticated session
|
||||
// merely because its single bounded retry still fails.
|
||||
SecureLogger.warning(
|
||||
"Dropping deferred Noise ciphertext from \(peerID.id.prefix(8))… after retry failed: \(error)",
|
||||
category: .session
|
||||
)
|
||||
return
|
||||
}
|
||||
// A responder may retain an older transport as receive-only
|
||||
// rollback state while ordinary XX waits for message 3. New-key
|
||||
// ciphertext can fail against those retained receive keys first.
|
||||
if env.isAwaitingResponderHandshakeCompletion(peerID) {
|
||||
if isDeferrableEarlyHandshakeFailure(error) {
|
||||
deferCiphertext(packet, from: peerID)
|
||||
} else {
|
||||
SecureLogger.warning(
|
||||
"Dropping invalid Noise ciphertext from \(peerID.id.prefix(8))… while responder handshake is completing: \(error)",
|
||||
category: .session
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
if isDropOnlyCiphertextFailure(error) {
|
||||
// The packet is attacker-controlled and did not prove a
|
||||
// transport-state failure. Never let malformed, replayed,
|
||||
// forged, oversized, or rate-limited bytes evict working keys.
|
||||
SecureLogger.warning(
|
||||
"Dropping rejected Noise ciphertext from \(peerID.id.prefix(8))… without clearing its session: \(error)",
|
||||
category: .security
|
||||
)
|
||||
return
|
||||
}
|
||||
// Decryption failed - clear the corrupted session and re-initiate handshake
|
||||
// This handles cases where session state got out of sync (nonce mismatch, etc.)
|
||||
// Only local/session lifecycle failures reach this path.
|
||||
SecureLogger.error("❌ Failed to decrypt message from \(peerID.id.prefix(8))…: \(error) - clearing session and re-initiating handshake")
|
||||
env.clearSession(peerID)
|
||||
env.initiateHandshake(peerID)
|
||||
}
|
||||
}
|
||||
|
||||
private func isDeferrableEarlyHandshakeFailure(_ error: Error) -> Bool {
|
||||
if let noiseError = error as? NoiseError {
|
||||
switch noiseError {
|
||||
case .authenticationFailure, .replayDetected:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
if let cryptoError = error as? CryptoKitError,
|
||||
case .authenticationFailure = cryptoError {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private func isDropOnlyCiphertextFailure(_ error: Error) -> Bool {
|
||||
if let securityError = error as? NoiseSecurityError {
|
||||
switch securityError {
|
||||
case .messageTooLarge, .rateLimitExceeded, .invalidPeerID:
|
||||
return true
|
||||
case .sessionExpired, .sessionExhausted:
|
||||
return false
|
||||
}
|
||||
}
|
||||
if let noiseError = error as? NoiseError {
|
||||
switch noiseError {
|
||||
case .invalidCiphertext, .authenticationFailure, .replayDetected:
|
||||
return true
|
||||
case .uninitializedCipher, .handshakeComplete,
|
||||
.handshakeNotComplete, .missingLocalStaticKey,
|
||||
.missingKeys, .invalidMessage, .invalidPublicKey,
|
||||
.nonceExceeded:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return error is CryptoKitError
|
||||
}
|
||||
|
||||
private func deferCiphertext(_ packet: BitchatPacket, from peerID: PeerID) {
|
||||
guard NoiseSecurityValidator.validatePrivateFileCiphertextSize(
|
||||
packet.payload
|
||||
) else {
|
||||
SecureLogger.warning(
|
||||
"Dropping oversized early Noise ciphertext from \(peerID.id.prefix(8))…",
|
||||
category: .security
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
let now = environment.now()
|
||||
deferredLock.lock()
|
||||
defer { deferredLock.unlock() }
|
||||
purgeExpiredCiphertextsLocked(now: now)
|
||||
|
||||
let peerCount = deferredCiphertexts[peerID]?.count ?? 0
|
||||
let globalCount = deferredCiphertexts.values.reduce(0) {
|
||||
$0 + $1.count
|
||||
}
|
||||
guard peerCount < Self.maxDeferredPacketsPerPeer,
|
||||
globalCount < Self.maxDeferredPacketsGlobal,
|
||||
deferredCiphertextBytes + packet.payload.count
|
||||
<= Self.maxDeferredBytes else {
|
||||
SecureLogger.warning(
|
||||
"Dropping early Noise ciphertext from \(peerID.id.prefix(8))… because the handshake buffer is full",
|
||||
category: .security
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
deferredCiphertexts[peerID, default: []].append(
|
||||
DeferredCiphertext(packet: packet, receivedAt: now)
|
||||
)
|
||||
deferredCiphertextBytes += packet.payload.count
|
||||
SecureLogger.debug(
|
||||
"Deferring early Noise ciphertext from \(peerID.id.prefix(8))… until responder handshake completion",
|
||||
category: .session
|
||||
)
|
||||
}
|
||||
|
||||
private func drainDeferredCiphertextsIfReady(for peerID: PeerID) {
|
||||
let env = environment
|
||||
guard !env.isAwaitingResponderHandshakeCompletion(peerID),
|
||||
env.hasNoiseSession(peerID) else {
|
||||
return
|
||||
}
|
||||
|
||||
let now = env.now()
|
||||
deferredLock.lock()
|
||||
purgeExpiredCiphertextsLocked(now: now)
|
||||
let deferred = deferredCiphertexts.removeValue(forKey: peerID) ?? []
|
||||
deferredCiphertextBytes -= deferred.reduce(0) {
|
||||
$0 + $1.packet.payload.count
|
||||
}
|
||||
deferredLock.unlock()
|
||||
|
||||
guard !deferred.isEmpty else { return }
|
||||
SecureLogger.debug(
|
||||
"Retrying \(deferred.count) early Noise ciphertext packet(s) from \(peerID.id.prefix(8))… after handshake completion",
|
||||
category: .session
|
||||
)
|
||||
for item in deferred {
|
||||
handleEncrypted(item.packet, from: peerID, isDeferredRetry: true)
|
||||
}
|
||||
}
|
||||
|
||||
private func purgeExpiredCiphertextsLocked(now: Date) {
|
||||
for peerID in Array(deferredCiphertexts.keys) {
|
||||
guard let items = deferredCiphertexts[peerID] else { continue }
|
||||
let retained = items.filter {
|
||||
now.timeIntervalSince($0.receivedAt) <= Self.deferredLifetime
|
||||
}
|
||||
guard retained.count != items.count else { continue }
|
||||
|
||||
deferredCiphertextBytes -= items.reduce(0) {
|
||||
$0 + $1.packet.payload.count
|
||||
}
|
||||
deferredCiphertextBytes += retained.reduce(0) {
|
||||
$0 + $1.packet.payload.count
|
||||
}
|
||||
if retained.isEmpty {
|
||||
deferredCiphertexts.removeValue(forKey: peerID)
|
||||
} else {
|
||||
deferredCiphertexts[peerID] = retained
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,16 @@ enum BLENoisePayloadFactory {
|
||||
typedPayload(.delivered, payload: Data(messageID.utf8))
|
||||
}
|
||||
|
||||
static func privateFile(_ filePacket: BitchatFilePacket) -> Data? {
|
||||
guard let payload = filePacket.encode() else { return nil }
|
||||
return typedPayload(.privateFile, payload: payload)
|
||||
}
|
||||
|
||||
static func authenticatedPeerState(_ state: AuthenticatedPeerStatePacket) -> Data? {
|
||||
guard let payload = state.encode() else { return nil }
|
||||
return typedPayload(.authenticatedPeerState, payload: payload)
|
||||
}
|
||||
|
||||
static func typedPayload(_ type: NoisePayloadType, payload: Data) -> Data {
|
||||
var typed = Data([type.rawValue])
|
||||
typed.append(payload)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import Foundation
|
||||
|
||||
/// Bounds ordinary Noise revalidation to one attempt per physical-link epoch.
|
||||
/// A live epoch may retry after the cooldown so a lost handshake cannot leave
|
||||
/// the link permanently unauthenticated.
|
||||
struct BLENoiseReconnectPolicy {
|
||||
static let minimumRetryInterval: TimeInterval = 60
|
||||
|
||||
private var lastAttemptAt: [BLEIngressLinkID: Date] = [:]
|
||||
|
||||
mutating func shouldRevalidate(
|
||||
on link: BLEIngressLinkID,
|
||||
hasEstablishedSession: Bool,
|
||||
isNoiseAuthenticatedLink: Bool,
|
||||
hasAuthenticatedPeerLink: Bool,
|
||||
now: Date
|
||||
) -> Bool {
|
||||
guard hasEstablishedSession,
|
||||
!isNoiseAuthenticatedLink,
|
||||
!hasAuthenticatedPeerLink else {
|
||||
return false
|
||||
}
|
||||
if let previous = lastAttemptAt[link],
|
||||
now.timeIntervalSince(previous) < Self.minimumRetryInterval {
|
||||
return false
|
||||
}
|
||||
lastAttemptAt[link] = now
|
||||
return true
|
||||
}
|
||||
|
||||
/// Link identifiers can be stable across CoreBluetooth reconnects, so a
|
||||
/// disconnect explicitly starts a new epoch and permits one fresh attempt.
|
||||
mutating func endLinkEpoch(_ link: BLEIngressLinkID) {
|
||||
lastAttemptAt.removeValue(forKey: link)
|
||||
}
|
||||
|
||||
mutating func removeAll() {
|
||||
lastAttemptAt.removeAll()
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,16 @@ struct BLEPendingPrivateMessage: Equatable {
|
||||
let messageID: String
|
||||
}
|
||||
|
||||
struct BLEPendingTypedPayload: Equatable {
|
||||
let payload: Data
|
||||
/// Present for app-initiated media so handshake queuing preserves the
|
||||
/// fragment scheduler's progress/cancellation identity.
|
||||
let transferId: String?
|
||||
}
|
||||
|
||||
struct BLENoiseSessionQueues {
|
||||
private var privateMessagesByPeerID: [PeerID: [BLEPendingPrivateMessage]] = [:]
|
||||
private var typedPayloadsByPeerID: [PeerID: [Data]] = [:]
|
||||
private var typedPayloadsByPeerID: [PeerID: [BLEPendingTypedPayload]] = [:]
|
||||
|
||||
var isEmpty: Bool {
|
||||
privateMessagesByPeerID.isEmpty && typedPayloadsByPeerID.isEmpty
|
||||
@@ -34,13 +41,35 @@ struct BLENoiseSessionQueues {
|
||||
privateMessagesByPeerID[peerID, default: []].insert(contentsOf: messages, at: 0)
|
||||
}
|
||||
|
||||
mutating func appendTypedPayload(_ payload: Data, for peerID: PeerID) {
|
||||
typedPayloadsByPeerID[peerID, default: []].append(payload)
|
||||
mutating func appendTypedPayload(_ payload: Data, transferId: String? = nil, for peerID: PeerID) {
|
||||
typedPayloadsByPeerID[peerID, default: []].append(
|
||||
BLEPendingTypedPayload(payload: payload, transferId: transferId)
|
||||
)
|
||||
}
|
||||
|
||||
mutating func takeTypedPayloads(for peerID: PeerID) -> [Data] {
|
||||
mutating func takeTypedPayloads(for peerID: PeerID) -> [BLEPendingTypedPayload] {
|
||||
let payloads = typedPayloadsByPeerID[peerID] ?? []
|
||||
typedPayloadsByPeerID.removeValue(forKey: peerID)
|
||||
return payloads
|
||||
}
|
||||
|
||||
func containsTypedPayload(transferId: String) -> Bool {
|
||||
typedPayloadsByPeerID.values.contains { payloads in
|
||||
payloads.contains { $0.transferId == transferId }
|
||||
}
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
mutating func removeTypedPayload(transferId: String) -> Bool {
|
||||
for peerID in Array(typedPayloadsByPeerID.keys) {
|
||||
guard var payloads = typedPayloadsByPeerID[peerID],
|
||||
let index = payloads.firstIndex(where: { $0.transferId == transferId }) else {
|
||||
continue
|
||||
}
|
||||
payloads.remove(at: index)
|
||||
typedPayloadsByPeerID[peerID] = payloads.isEmpty ? nil : payloads
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ struct BLEOutboundFragmentPlan {
|
||||
}
|
||||
|
||||
enum BLEOutboundFragmentPlanner {
|
||||
/// Current Android receivers reject fragment sets above 256. Private
|
||||
/// media v1 treats that deployed ceiling as a cross-platform contract.
|
||||
static let privateMediaV1MaxFragments = 256
|
||||
private static let minimumChunkSize = 64
|
||||
private static let fragmentIDLength = 8
|
||||
|
||||
@@ -71,6 +74,10 @@ enum BLEOutboundFragmentPlanner {
|
||||
)
|
||||
}
|
||||
|
||||
static func isPrivateMediaV1Compatible(_ plan: BLEOutboundFragmentPlan) -> Bool {
|
||||
plan.totalFragments <= privateMediaV1MaxFragments
|
||||
}
|
||||
|
||||
private static func sizingPolicy(
|
||||
for packet: BitchatPacket,
|
||||
requestedMaxChunk: Int?,
|
||||
|
||||
@@ -29,8 +29,9 @@ struct BLEOutboundFragmentTransferRequest {
|
||||
}
|
||||
|
||||
var resolvedTransferId: String? {
|
||||
if let transferId { return transferId }
|
||||
guard packet.type == MessageType.fileTransfer.rawValue else { return nil }
|
||||
return transferId ?? packet.payload.sha256Hex()
|
||||
return packet.payload.sha256Hex()
|
||||
}
|
||||
|
||||
/// Content identity independent of the caller-chosen transfer ID: the
|
||||
|
||||
@@ -10,6 +10,9 @@ struct BLEPeerInfo: Equatable {
|
||||
var isVerifiedNickname: Bool
|
||||
var lastSeen: Date
|
||||
var capabilities: PeerCapabilities = []
|
||||
/// Distinguishes an old client that omitted the capabilities TLV from a
|
||||
/// modern client that explicitly advertised a set without a given bit.
|
||||
var capabilitiesWereExplicitlyAdvertised: Bool = false
|
||||
/// Rendezvous cell from the peer's announce when it advertises `.bridge`.
|
||||
var bridgeGeohash: String?
|
||||
}
|
||||
@@ -114,6 +117,10 @@ struct BLEPeerRegistry {
|
||||
peers[peerID.toShort()]?.capabilities ?? []
|
||||
}
|
||||
|
||||
func capabilitiesWereExplicitlyAdvertised(for peerID: PeerID) -> Bool {
|
||||
peers[peerID.toShort()]?.capabilitiesWereExplicitlyAdvertised == true
|
||||
}
|
||||
|
||||
/// Peers whose last verified announce advertised the given capability.
|
||||
func peers(advertising capability: PeerCapabilities) -> [PeerID] {
|
||||
peers.values.filter { $0.capabilities.contains(capability) }.map(\.peerID)
|
||||
@@ -174,6 +181,14 @@ struct BLEPeerRegistry {
|
||||
peers[peerID] = peer
|
||||
}
|
||||
|
||||
/// Replaces the announcement signing key only after the surrounding Noise
|
||||
/// session proved possession of this peer's static key.
|
||||
mutating func bindAuthenticatedSigningPublicKey(_ key: Data, for peerID: PeerID) {
|
||||
guard var peer = peers[peerID.toShort()] else { return }
|
||||
peer.signingPublicKey = key
|
||||
peers[peer.peerID] = peer
|
||||
}
|
||||
|
||||
mutating func upsertVerifiedAnnounce(
|
||||
peerID: PeerID,
|
||||
nickname: String,
|
||||
@@ -181,7 +196,7 @@ struct BLEPeerRegistry {
|
||||
signingPublicKey: Data?,
|
||||
isConnected: Bool,
|
||||
now: Date,
|
||||
capabilities: PeerCapabilities = [],
|
||||
capabilities: PeerCapabilities? = nil,
|
||||
bridgeGeohash: String? = nil
|
||||
) -> BLEPeerAnnounceUpdate {
|
||||
let existing = peers[peerID]
|
||||
@@ -199,7 +214,8 @@ struct BLEPeerRegistry {
|
||||
signingPublicKey: signingPublicKey,
|
||||
isVerifiedNickname: true,
|
||||
lastSeen: now,
|
||||
capabilities: capabilities,
|
||||
capabilities: capabilities ?? [],
|
||||
capabilitiesWereExplicitlyAdvertised: capabilities != nil,
|
||||
bridgeGeohash: bridgeGeohash
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
import BitLogger
|
||||
import Foundation
|
||||
|
||||
enum BLEPrivateMediaReceiptState: Equatable {
|
||||
/// No durable receiver decision exists for this stable message ID.
|
||||
case absent
|
||||
/// The payload is durably mapped to a file that still exists.
|
||||
case accepted(URL)
|
||||
/// The user explicitly deleted the payload; retries must not resurrect it.
|
||||
case tombstoned
|
||||
/// Durable state could not be read safely. Callers must fail closed and
|
||||
/// must not save, deliver, or acknowledge the payload.
|
||||
case unavailable
|
||||
}
|
||||
|
||||
/// Durable, per-message receiver decisions for stable private media.
|
||||
///
|
||||
/// Each ID has its own atomic record so one hot lookup never rewrites or
|
||||
/// decodes the entire ledger. The process-lifetime index is installed only
|
||||
/// after a complete, successful directory scan. An enumeration, read, decode,
|
||||
/// or structural-validation failure therefore remains retryable and cannot be
|
||||
/// mistaken for an empty ledger.
|
||||
final class BLEPrivateMediaReceiptStore: @unchecked Sendable {
|
||||
typealias DirectoryReader = (_ directory: URL) throws -> [URL]
|
||||
typealias DataReader = (_ url: URL) throws -> Data
|
||||
private static let receiptDirectoryName = ".private-media-receipts"
|
||||
|
||||
private struct ReceiptRecord: Codable, Equatable {
|
||||
enum Kind: String, Codable {
|
||||
case accepted
|
||||
case tombstone
|
||||
}
|
||||
|
||||
let kind: Kind
|
||||
/// Path below the app's `files/` root. Absolute application-container
|
||||
/// prefixes are not stable across updates, restores, or reinstalls.
|
||||
let relativePath: String?
|
||||
let recordedAt: Date
|
||||
}
|
||||
|
||||
private final class Runtime: @unchecked Sendable {
|
||||
let lock = NSLock()
|
||||
var records: [String: ReceiptRecord]?
|
||||
var volatileTombstones: [String: Date] = [:]
|
||||
}
|
||||
|
||||
private let fileManager: FileManager
|
||||
private let baseDirectory: URL?
|
||||
private let capacity: Int
|
||||
private let ttl: TimeInterval
|
||||
private let now: () -> Date
|
||||
private let directoryReader: DirectoryReader?
|
||||
private let dataReader: DataReader?
|
||||
private let runtime = Runtime()
|
||||
|
||||
init(
|
||||
fileManager: FileManager = .default,
|
||||
baseDirectory: URL? = nil,
|
||||
capacity: Int = TransportConfig.privateMediaReceivedLedgerCapacity,
|
||||
ttl: TimeInterval = TransportConfig.privateMediaReceivedLedgerTTLSeconds,
|
||||
now: @escaping () -> Date = Date.init,
|
||||
directoryReader: DirectoryReader? = nil,
|
||||
dataReader: DataReader? = nil
|
||||
) {
|
||||
self.fileManager = fileManager
|
||||
self.baseDirectory = baseDirectory
|
||||
self.capacity = max(1, capacity)
|
||||
self.ttl = max(0, ttl)
|
||||
self.now = now
|
||||
self.directoryReader = directoryReader
|
||||
self.dataReader = dataReader
|
||||
}
|
||||
|
||||
/// Drops process-lifetime decisions after the enclosing media directory
|
||||
/// has been panic-wiped. A later lookup must rebuild from the durable
|
||||
/// ledger instead of retaining an accepted receipt or tombstone whose
|
||||
/// backing files no longer exist.
|
||||
func resetForPanic() {
|
||||
runtime.lock.lock()
|
||||
runtime.records = nil
|
||||
runtime.volatileTombstones.removeAll(keepingCapacity: false)
|
||||
runtime.lock.unlock()
|
||||
}
|
||||
|
||||
func state(for messageID: String) -> BLEPrivateMediaReceiptState {
|
||||
guard PrivateMediaMessageIdentity.isStableID(messageID) else {
|
||||
return .absent
|
||||
}
|
||||
|
||||
runtime.lock.lock()
|
||||
defer { runtime.lock.unlock() }
|
||||
|
||||
let date = now()
|
||||
if let tombstonedAt = runtime.volatileTombstones[messageID] {
|
||||
if !isExpired(tombstonedAt, at: date) {
|
||||
return .tombstoned
|
||||
}
|
||||
runtime.volatileTombstones.removeValue(forKey: messageID)
|
||||
}
|
||||
|
||||
guard let directory = resolvedReceiptDirectory(),
|
||||
var records = loadIndexIfNeeded(from: directory, at: date) else {
|
||||
return .unavailable
|
||||
}
|
||||
guard let record = records[messageID] else { return .absent }
|
||||
|
||||
if isExpired(record.recordedAt, at: date) {
|
||||
records.removeValue(forKey: messageID)
|
||||
runtime.records = records
|
||||
removeRecord(messageID: messageID, from: directory)
|
||||
return .absent
|
||||
}
|
||||
|
||||
switch record.kind {
|
||||
case .tombstone:
|
||||
removePayloadRecordedByTombstone(record)
|
||||
return .tombstoned
|
||||
|
||||
case .accepted:
|
||||
guard let relativePath = record.relativePath,
|
||||
let existingURL = existingPayload(relativePath: relativePath) else {
|
||||
// Quota cleanup is not explicit deletion. Remove the stale
|
||||
// receipt so a sender retry can restore the payload and bubble.
|
||||
records.removeValue(forKey: messageID)
|
||||
runtime.records = records
|
||||
removeRecord(messageID: messageID, from: directory)
|
||||
return .absent
|
||||
}
|
||||
return .accepted(existingURL)
|
||||
}
|
||||
}
|
||||
|
||||
/// Records an accepted ID only after the payload is on disk. Callers must
|
||||
/// roll the payload back and withhold UI delivery/ACK when this returns
|
||||
/// false.
|
||||
func commitAccepted(messageID: String, storedURL: URL) -> Bool {
|
||||
guard PrivateMediaMessageIdentity.isStableID(messageID),
|
||||
validExistingPayload(storedURL) != nil,
|
||||
let relativePath = relativePath(for: storedURL) else {
|
||||
return false
|
||||
}
|
||||
|
||||
runtime.lock.lock()
|
||||
defer { runtime.lock.unlock() }
|
||||
|
||||
let date = now()
|
||||
if let tombstonedAt = runtime.volatileTombstones[messageID],
|
||||
!isExpired(tombstonedAt, at: date) {
|
||||
return false
|
||||
}
|
||||
|
||||
guard let directory = resolvedReceiptDirectory(),
|
||||
var records = loadIndexIfNeeded(from: directory, at: date) else {
|
||||
return false
|
||||
}
|
||||
if let existing = records[messageID],
|
||||
existing.kind == .tombstone,
|
||||
!isExpired(existing.recordedAt, at: date) {
|
||||
return false
|
||||
}
|
||||
|
||||
let victim = capacityVictim(
|
||||
for: .accepted,
|
||||
replacing: messageID,
|
||||
in: records
|
||||
)
|
||||
if records[messageID]?.kind != .accepted,
|
||||
records.values.lazy.filter({ $0.kind == .accepted }).count >= capacity,
|
||||
victim == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
let record = ReceiptRecord(
|
||||
kind: .accepted,
|
||||
relativePath: relativePath,
|
||||
recordedAt: date
|
||||
)
|
||||
guard persist(record, messageID: messageID, to: directory) else {
|
||||
return false
|
||||
}
|
||||
|
||||
records[messageID] = record
|
||||
if let victim, victim != messageID {
|
||||
records.removeValue(forKey: victim)
|
||||
removeRecord(messageID: victim, from: directory)
|
||||
}
|
||||
runtime.records = records
|
||||
return true
|
||||
}
|
||||
|
||||
/// Foundation for explicit media deletion. This branch does not wire the
|
||||
/// chat-clear UI; it only makes a tombstone durable and fail closed.
|
||||
func recordDeleted(messageID: String) -> Bool {
|
||||
guard PrivateMediaMessageIdentity.isStableID(messageID) else {
|
||||
return false
|
||||
}
|
||||
|
||||
runtime.lock.lock()
|
||||
defer { runtime.lock.unlock() }
|
||||
|
||||
let date = now()
|
||||
addVolatileTombstone(messageID, at: date)
|
||||
|
||||
guard let directory = resolvedReceiptDirectory(),
|
||||
var records = loadIndexIfNeeded(from: directory, at: date) else {
|
||||
runtime.volatileTombstones.removeValue(forKey: messageID)
|
||||
return false
|
||||
}
|
||||
if let existing = records[messageID],
|
||||
existing.kind == .tombstone,
|
||||
!isExpired(existing.recordedAt, at: date) {
|
||||
runtime.volatileTombstones.removeValue(forKey: messageID)
|
||||
removePayloadRecordedByTombstone(existing)
|
||||
return true
|
||||
}
|
||||
|
||||
let victim = capacityVictim(
|
||||
for: .tombstone,
|
||||
replacing: messageID,
|
||||
in: records
|
||||
)
|
||||
if records[messageID]?.kind != .tombstone,
|
||||
records.values.lazy.filter({ $0.kind == .tombstone }).count >= capacity,
|
||||
victim == nil {
|
||||
runtime.volatileTombstones.removeValue(forKey: messageID)
|
||||
return false
|
||||
}
|
||||
|
||||
let tombstone = ReceiptRecord(
|
||||
kind: .tombstone,
|
||||
// Retain the accepted path so a crash between the atomic record
|
||||
// write and payload unlink can finish cleanup after relaunch.
|
||||
relativePath: records[messageID]?.relativePath,
|
||||
recordedAt: date
|
||||
)
|
||||
guard persist(tombstone, messageID: messageID, to: directory) else {
|
||||
runtime.volatileTombstones.removeValue(forKey: messageID)
|
||||
return false
|
||||
}
|
||||
|
||||
records[messageID] = tombstone
|
||||
if let victim, victim != messageID {
|
||||
records.removeValue(forKey: victim)
|
||||
removeRecord(messageID: victim, from: directory)
|
||||
}
|
||||
runtime.records = records
|
||||
runtime.volatileTombstones.removeValue(forKey: messageID)
|
||||
removePayloadRecordedByTombstone(tombstone)
|
||||
return true
|
||||
}
|
||||
|
||||
private func loadIndexIfNeeded(
|
||||
from directory: URL,
|
||||
at date: Date
|
||||
) -> [String: ReceiptRecord]? {
|
||||
if let records = runtime.records {
|
||||
return records
|
||||
}
|
||||
|
||||
do {
|
||||
try fileManager.createDirectory(
|
||||
at: directory,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil
|
||||
)
|
||||
} catch {
|
||||
SecureLogger.error(
|
||||
"❌ Failed to create private-media receipt directory: \(error)",
|
||||
category: .session
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
let urls: [URL]
|
||||
do {
|
||||
if let directoryReader {
|
||||
urls = try directoryReader(directory)
|
||||
} else {
|
||||
urls = try fileManager.contentsOfDirectory(
|
||||
at: directory,
|
||||
includingPropertiesForKeys: nil,
|
||||
options: []
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
SecureLogger.error(
|
||||
"❌ Failed to enumerate private-media receipts: \(error)",
|
||||
category: .session
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
var records: [String: ReceiptRecord] = [:]
|
||||
var expired: [String] = []
|
||||
var tombstones: [ReceiptRecord] = []
|
||||
for url in urls {
|
||||
guard url.pathExtension == "json" else { continue }
|
||||
let messageID = url.deletingPathExtension().lastPathComponent
|
||||
guard PrivateMediaMessageIdentity.isStableID(messageID) else {
|
||||
continue
|
||||
}
|
||||
|
||||
let record: ReceiptRecord
|
||||
do {
|
||||
let data = try dataReader?(url) ?? Data(contentsOf: url)
|
||||
record = try JSONDecoder().decode(ReceiptRecord.self, from: data)
|
||||
} catch {
|
||||
// Never delete or skip an unreadable stable-ID record. Treating
|
||||
// it as absent could resurrect accepted or deleted media.
|
||||
SecureLogger.error(
|
||||
"❌ Failed to read private-media receipt \(messageID.prefix(12))…: \(error)",
|
||||
category: .session
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
guard isStructurallyValid(record) else {
|
||||
SecureLogger.error(
|
||||
"❌ Invalid private-media receipt \(messageID.prefix(12))…",
|
||||
category: .session
|
||||
)
|
||||
return nil
|
||||
}
|
||||
if isExpired(record.recordedAt, at: date) {
|
||||
expired.append(messageID)
|
||||
continue
|
||||
}
|
||||
records[messageID] = record
|
||||
if record.kind == .tombstone {
|
||||
tombstones.append(record)
|
||||
}
|
||||
}
|
||||
|
||||
let overflow = overflowVictims(in: records)
|
||||
for messageID in overflow {
|
||||
records.removeValue(forKey: messageID)
|
||||
}
|
||||
|
||||
// Install the index only after every stable-ID record was read and
|
||||
// validated successfully. Cleanup cannot influence a failed scan.
|
||||
runtime.records = records
|
||||
|
||||
for messageID in expired + overflow {
|
||||
removeRecord(messageID: messageID, from: directory)
|
||||
}
|
||||
for tombstone in tombstones {
|
||||
removePayloadRecordedByTombstone(tombstone)
|
||||
}
|
||||
return records
|
||||
}
|
||||
|
||||
private func isStructurallyValid(_ record: ReceiptRecord) -> Bool {
|
||||
switch record.kind {
|
||||
case .tombstone:
|
||||
guard let relativePath = record.relativePath else { return true }
|
||||
return candidatePayload(relativePath: relativePath) != nil
|
||||
case .accepted:
|
||||
guard let relativePath = record.relativePath else { return false }
|
||||
return candidatePayload(relativePath: relativePath) != nil
|
||||
}
|
||||
}
|
||||
|
||||
private func isExpired(_ recordedAt: Date, at date: Date) -> Bool {
|
||||
date.timeIntervalSince(recordedAt) > ttl
|
||||
}
|
||||
|
||||
private func overflowVictims(
|
||||
in records: [String: ReceiptRecord]
|
||||
) -> [String] {
|
||||
var victims: [String] = []
|
||||
for kind in [ReceiptRecord.Kind.accepted, .tombstone] {
|
||||
let matching = records.filter { $0.value.kind == kind }
|
||||
let overflow = matching.count - capacity
|
||||
guard overflow > 0 else { continue }
|
||||
victims.append(contentsOf: matching.sorted { lhs, rhs in
|
||||
if lhs.value.recordedAt == rhs.value.recordedAt {
|
||||
return lhs.key < rhs.key
|
||||
}
|
||||
return lhs.value.recordedAt < rhs.value.recordedAt
|
||||
}
|
||||
.prefix(overflow)
|
||||
.map(\.key))
|
||||
}
|
||||
return victims
|
||||
}
|
||||
|
||||
/// Accepted receipts and tombstones have independent capacity. High media
|
||||
/// volume cannot evict explicit deletion intent, and vice versa.
|
||||
private func capacityVictim(
|
||||
for incomingKind: ReceiptRecord.Kind,
|
||||
replacing messageID: String,
|
||||
in records: [String: ReceiptRecord]
|
||||
) -> String? {
|
||||
guard records[messageID]?.kind != incomingKind else { return nil }
|
||||
let matching = records.filter {
|
||||
$0.key != messageID && $0.value.kind == incomingKind
|
||||
}
|
||||
guard matching.count >= capacity else { return nil }
|
||||
return matching.min { lhs, rhs in
|
||||
if lhs.value.recordedAt == rhs.value.recordedAt {
|
||||
return lhs.key < rhs.key
|
||||
}
|
||||
return lhs.value.recordedAt < rhs.value.recordedAt
|
||||
}?.key
|
||||
}
|
||||
|
||||
private func persist(
|
||||
_ record: ReceiptRecord,
|
||||
messageID: String,
|
||||
to directory: URL
|
||||
) -> Bool {
|
||||
do {
|
||||
try fileManager.createDirectory(
|
||||
at: directory,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil
|
||||
)
|
||||
let data = try JSONEncoder().encode(record)
|
||||
var options: Data.WritingOptions = [.atomic]
|
||||
#if os(iOS)
|
||||
options.insert(.completeFileProtectionUntilFirstUserAuthentication)
|
||||
#endif
|
||||
let url = recordURL(messageID: messageID, in: directory)
|
||||
try data.write(to: url, options: options)
|
||||
return true
|
||||
} catch {
|
||||
SecureLogger.error(
|
||||
"❌ Failed to persist private-media receipt \(messageID.prefix(12))…: \(error)",
|
||||
category: .session
|
||||
)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private func removeRecord(messageID: String, from directory: URL) {
|
||||
let url = recordURL(messageID: messageID, in: directory)
|
||||
guard fileManager.fileExists(atPath: url.path) else { return }
|
||||
do {
|
||||
try fileManager.removeItem(at: url)
|
||||
} catch {
|
||||
SecureLogger.warning(
|
||||
"⚠️ Failed to prune private-media receipt \(messageID.prefix(12))…: \(error)",
|
||||
category: .session
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func recordURL(messageID: String, in directory: URL) -> URL {
|
||||
directory
|
||||
.appendingPathComponent(messageID, isDirectory: false)
|
||||
.appendingPathExtension("json")
|
||||
}
|
||||
|
||||
private func removePayloadRecordedByTombstone(_ record: ReceiptRecord) {
|
||||
guard record.kind == .tombstone,
|
||||
let relativePath = record.relativePath,
|
||||
let payload = candidatePayload(relativePath: relativePath),
|
||||
fileManager.fileExists(atPath: payload.path) else {
|
||||
return
|
||||
}
|
||||
do {
|
||||
try fileManager.removeItem(at: payload)
|
||||
} catch {
|
||||
SecureLogger.warning(
|
||||
"⚠️ Failed to remove explicitly deleted private media: \(error)",
|
||||
category: .session
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func addVolatileTombstone(_ messageID: String, at date: Date) {
|
||||
runtime.volatileTombstones[messageID] = date
|
||||
let overflow = runtime.volatileTombstones.count - capacity
|
||||
guard overflow > 0 else { return }
|
||||
let oldest = runtime.volatileTombstones.sorted {
|
||||
if $0.value == $1.value { return $0.key < $1.key }
|
||||
return $0.value < $1.value
|
||||
}
|
||||
for (oldMessageID, _) in oldest.prefix(overflow) {
|
||||
runtime.volatileTombstones.removeValue(forKey: oldMessageID)
|
||||
}
|
||||
}
|
||||
|
||||
private func validExistingPayload(_ url: URL) -> URL? {
|
||||
let standardized = url.standardizedFileURL
|
||||
guard isInsideFilesDirectory(standardized) else { return nil }
|
||||
var isDirectory: ObjCBool = false
|
||||
guard fileManager.fileExists(
|
||||
atPath: standardized.path,
|
||||
isDirectory: &isDirectory
|
||||
), !isDirectory.boolValue else {
|
||||
return nil
|
||||
}
|
||||
return standardized
|
||||
}
|
||||
|
||||
private func relativePath(for url: URL) -> String? {
|
||||
guard let filesRoot = try? filesDirectory().standardizedFileURL else {
|
||||
return nil
|
||||
}
|
||||
let prefix = filesRoot.path + "/"
|
||||
let standardized = url.standardizedFileURL
|
||||
guard standardized.path.hasPrefix(prefix) else { return nil }
|
||||
let relativePath = String(standardized.path.dropFirst(prefix.count))
|
||||
return relativePath.isEmpty ? nil : relativePath
|
||||
}
|
||||
|
||||
private func existingPayload(relativePath: String) -> URL? {
|
||||
guard let candidate = candidatePayload(relativePath: relativePath) else {
|
||||
return nil
|
||||
}
|
||||
return validExistingPayload(candidate)
|
||||
}
|
||||
|
||||
private func candidatePayload(relativePath: String) -> URL? {
|
||||
guard !relativePath.isEmpty,
|
||||
let filesRoot = try? filesDirectory().standardizedFileURL else {
|
||||
return nil
|
||||
}
|
||||
let candidate = filesRoot
|
||||
.appendingPathComponent(relativePath, isDirectory: false)
|
||||
.standardizedFileURL
|
||||
guard candidate.path.hasPrefix(filesRoot.path + "/") else { return nil }
|
||||
return candidate
|
||||
}
|
||||
|
||||
private func isInsideFilesDirectory(_ url: URL) -> Bool {
|
||||
guard let filesRoot = try? filesDirectory().standardizedFileURL else {
|
||||
return false
|
||||
}
|
||||
return url.standardizedFileURL.path.hasPrefix(filesRoot.path + "/")
|
||||
}
|
||||
|
||||
private func resolvedReceiptDirectory() -> URL? {
|
||||
return try? filesDirectory().appendingPathComponent(
|
||||
Self.receiptDirectoryName,
|
||||
isDirectory: true
|
||||
)
|
||||
}
|
||||
|
||||
private func filesDirectory() throws -> URL {
|
||||
let root = try baseDirectory ?? fileManager.url(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask,
|
||||
appropriateFor: nil,
|
||||
create: true
|
||||
)
|
||||
let files = root.appendingPathComponent("files", isDirectory: true)
|
||||
try fileManager.createDirectory(
|
||||
at: files,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil
|
||||
)
|
||||
return files
|
||||
}
|
||||
}
|
||||
+1836
-103
File diff suppressed because it is too large
Load Diff
@@ -165,7 +165,6 @@ final class NoiseEncryptionService {
|
||||
// Peer fingerprints (SHA256 hash of static public key)
|
||||
private var peerFingerprints: [PeerID: String] = [:]
|
||||
private var fingerprintToPeerID: [String: PeerID] = [:]
|
||||
|
||||
// Thread safety
|
||||
private let serviceQueue = DispatchQueue(label: "chat.bitchat.noise.service", attributes: .concurrent)
|
||||
|
||||
@@ -183,12 +182,24 @@ final class NoiseEncryptionService {
|
||||
|
||||
// Callbacks
|
||||
private var onPeerAuthenticatedHandlers: [((PeerID, String) -> Void)] = [] // Array of handlers for peer authentication
|
||||
private var onPeerAuthenticatedWithGenerationHandlers: [((PeerID, String, UUID) -> Void)] = []
|
||||
var onHandshakeRequired: ((PeerID) -> Void)? // peerID needs handshake
|
||||
/// Automatic rekey prepared XX message 1. The transport must claim the
|
||||
/// exact attempt at its actual BLE handoff; a crossed inbound initiation
|
||||
/// can invalidate the token before that point.
|
||||
var onRekeyHandshakeReady:
|
||||
((_ peerID: PeerID, _ initiation: NoiseHandshakeInitiation) -> Void)?
|
||||
var onHandshakeRecoveryRequired:
|
||||
((_ request: NoiseHandshakeRecoveryRequest) -> Void)?
|
||||
/// An unauthenticated reconnect attempt failed or timed out and the
|
||||
/// receive-only rollback session became the active transport again.
|
||||
/// Transport queues must be drained for this exact restored generation.
|
||||
var onSessionRestoredWithGeneration: ((_ peerID: PeerID, _ generation: UUID) -> Void)?
|
||||
|
||||
// Add a handler for peer authentication
|
||||
func addOnPeerAuthenticatedHandler(_ handler: @escaping (PeerID, String) -> Void) {
|
||||
serviceQueue.async(flags: .barrier) { [weak self] in
|
||||
self?.onPeerAuthenticatedHandlers.append(handler)
|
||||
serviceQueue.sync(flags: .barrier) {
|
||||
onPeerAuthenticatedHandlers.append(handler)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,8 +212,30 @@ final class NoiseEncryptionService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Generation-aware authentication notifications are used by protocols
|
||||
/// whose state must be bound to one exact Noise transport session.
|
||||
var onPeerAuthenticatedWithGeneration: ((PeerID, String, UUID) -> Void)? {
|
||||
get { nil }
|
||||
set {
|
||||
guard let handler = newValue else { return }
|
||||
serviceQueue.sync(flags: .barrier) {
|
||||
onPeerAuthenticatedWithGenerationHandlers.append(handler)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init(keychain: KeychainManagerProtocol) {
|
||||
init(
|
||||
keychain: KeychainManagerProtocol,
|
||||
ordinaryHandshakeTimeout: TimeInterval =
|
||||
NoiseSecurityConstants.ordinaryHandshakeTimeout,
|
||||
ordinaryResponderHandshakeTimeout: TimeInterval =
|
||||
NoiseSecurityConstants.ordinaryResponderHandshakeTimeout,
|
||||
recentInitiatorCompletionGracePeriod: TimeInterval =
|
||||
NoiseSecurityConstants.recentInitiatorCompletionGracePeriod,
|
||||
ordinaryReconnectRollbackCooldown: TimeInterval =
|
||||
NoiseSecurityConstants.ordinaryReconnectRollbackCooldown
|
||||
) {
|
||||
self.keychain = keychain
|
||||
self.localPrekeys = LocalPrekeyStore(keychain: keychain)
|
||||
|
||||
@@ -292,11 +325,31 @@ final class NoiseEncryptionService {
|
||||
self.signingPublicKey = signingKey.publicKey
|
||||
|
||||
// Initialize session manager
|
||||
self.sessionManager = NoiseSessionManager(localStaticKey: staticIdentityKey, keychain: keychain)
|
||||
self.sessionManager = NoiseSessionManager(
|
||||
localStaticKey: staticIdentityKey,
|
||||
keychain: keychain,
|
||||
ordinaryHandshakeTimeout: ordinaryHandshakeTimeout,
|
||||
ordinaryResponderHandshakeTimeout:
|
||||
ordinaryResponderHandshakeTimeout,
|
||||
recentInitiatorCompletionGracePeriod:
|
||||
recentInitiatorCompletionGracePeriod,
|
||||
ordinaryReconnectRollbackCooldown:
|
||||
ordinaryReconnectRollbackCooldown
|
||||
)
|
||||
|
||||
// Set up session callbacks
|
||||
sessionManager.onSessionEstablished = { [weak self] peerID, remoteStaticKey in
|
||||
self?.handleSessionEstablished(peerID: peerID, remoteStaticKey: remoteStaticKey)
|
||||
sessionManager.onSessionEstablished = { [weak self] peerID, remoteStaticKey, generation in
|
||||
self?.handleSessionEstablished(
|
||||
peerID: peerID,
|
||||
remoteStaticKey: remoteStaticKey,
|
||||
sessionGeneration: generation
|
||||
)
|
||||
}
|
||||
sessionManager.onSessionRestored = { [weak self] peerID, generation in
|
||||
self?.onSessionRestoredWithGeneration?(peerID, generation)
|
||||
}
|
||||
sessionManager.onHandshakeRecoveryRequired = { [weak self] request in
|
||||
self?.onHandshakeRecoveryRequired?(request)
|
||||
}
|
||||
|
||||
// Start session maintenance timer
|
||||
@@ -661,6 +714,90 @@ final class NoiseEncryptionService {
|
||||
let handshakeData = try sessionManager.initiateHandshake(with: peerID)
|
||||
return handshakeData
|
||||
}
|
||||
|
||||
/// Atomically admits and prepares one initial ordinary handshake. Returns
|
||||
/// nil when another discovery callback already created a session.
|
||||
func initiateHandshakeIfNeeded(
|
||||
with peerID: PeerID,
|
||||
retryOnTimeout: Bool = false
|
||||
) throws -> NoiseHandshakeInitiation? {
|
||||
guard peerID.isValid else {
|
||||
SecureLogger.warning(.authenticationFailed(peerID: peerID.id))
|
||||
throw NoiseSecurityError.invalidPeerID
|
||||
}
|
||||
|
||||
guard let initiation = try sessionManager.initiateHandshakeIfAbsent(
|
||||
with: peerID,
|
||||
notifyOnTimeout: retryOnTimeout,
|
||||
authorize: { [rateLimiter] in
|
||||
guard rateLimiter.allowHandshake(from: peerID) else {
|
||||
SecureLogger.warning(
|
||||
.authenticationFailed(peerID: "Rate limited: \(peerID)")
|
||||
)
|
||||
throw NoiseSecurityError.rateLimitExceeded
|
||||
}
|
||||
}
|
||||
) else {
|
||||
return nil
|
||||
}
|
||||
SecureLogger.info(.handshakeStarted(peerID: peerID.id))
|
||||
return initiation
|
||||
}
|
||||
|
||||
/// Atomically prepares an ordinary reconnect for a peer whose cached
|
||||
/// transport belongs to an earlier physical link. Failed authorization or
|
||||
/// handshake setup preserves the established session.
|
||||
func initiateReconnectHandshake(
|
||||
with peerID: PeerID,
|
||||
retryOnTimeout: Bool = false
|
||||
) throws -> NoiseHandshakeInitiation {
|
||||
guard peerID.isValid else {
|
||||
SecureLogger.warning(.authenticationFailed(peerID: peerID.id))
|
||||
throw NoiseSecurityError.invalidPeerID
|
||||
}
|
||||
|
||||
return try sessionManager.initiateReconnectHandshake(
|
||||
with: peerID,
|
||||
notifyOnTimeout: retryOnTimeout,
|
||||
authorize: { [rateLimiter] in
|
||||
guard rateLimiter.allowHandshake(from: peerID) else {
|
||||
SecureLogger.warning(
|
||||
.authenticationFailed(peerID: "Rate limited: \(peerID)")
|
||||
)
|
||||
throw NoiseSecurityError.rateLimitExceeded
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
func prepareHandshakeRecovery(
|
||||
_ request: NoiseHandshakeRecoveryRequest
|
||||
) throws -> NoiseHandshakeRecoveryPreparation? {
|
||||
try sessionManager.prepareHandshakeRecovery(
|
||||
request,
|
||||
authorizeAttempt: { [rateLimiter] in
|
||||
guard rateLimiter.allowHandshake(from: request.peerID) else {
|
||||
SecureLogger.warning(
|
||||
.authenticationFailed(
|
||||
peerID: "Rate limited: \(request.peerID)"
|
||||
)
|
||||
)
|
||||
throw NoiseSecurityError.rateLimitExceeded
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
func cancelHandshakeRecovery(_ request: NoiseHandshakeRecoveryRequest) {
|
||||
sessionManager.cancelHandshakeRecovery(request)
|
||||
}
|
||||
|
||||
func claimHandshakeInitiation(
|
||||
_ initiation: NoiseHandshakeInitiation,
|
||||
for peerID: PeerID
|
||||
) -> Data? {
|
||||
sessionManager.claimHandshakeInitiation(initiation, for: peerID)
|
||||
}
|
||||
|
||||
/// Process an incoming handshake message
|
||||
func processHandshakeMessage(from peerID: PeerID, message: Data) throws -> Data? {
|
||||
@@ -716,6 +853,13 @@ final class NoiseEncryptionService {
|
||||
func hasSession(with peerID: PeerID) -> Bool {
|
||||
return sessionManager.getSession(for: peerID) != nil
|
||||
}
|
||||
|
||||
/// True while an inbound ordinary XX responder is waiting for message 3.
|
||||
/// A small amount of immediately-following ciphertext may arrive first
|
||||
/// over BLE and must be retried only after responder promotion.
|
||||
func isAwaitingResponderHandshakeCompletion(with peerID: PeerID) -> Bool {
|
||||
sessionManager.isAwaitingResponderHandshakeCompletion(for: peerID)
|
||||
}
|
||||
|
||||
// MARK: - Encryption/Decryption
|
||||
|
||||
@@ -740,25 +884,87 @@ final class NoiseEncryptionService {
|
||||
|
||||
return try sessionManager.encrypt(data, for: peerID)
|
||||
}
|
||||
|
||||
/// Decrypt data from a specific peer
|
||||
func decrypt(_ data: Data, from peerID: PeerID) throws -> Data {
|
||||
// Validate message size
|
||||
guard NoiseSecurityValidator.validateMessageSize(data) else {
|
||||
|
||||
/// Encrypts a finalized private-media packet. Ordinary Noise application
|
||||
/// messages retain the 64 KiB ceiling; this purpose-specific path permits
|
||||
/// the bounded `BitchatFilePacket` envelope and refuses every other typed
|
||||
/// payload so the larger allocation budget cannot become a generic bypass.
|
||||
func encryptPrivateFilePayload(
|
||||
_ data: Data,
|
||||
for peerID: PeerID,
|
||||
sessionGeneration: UUID? = nil
|
||||
) throws -> Data {
|
||||
guard NoisePayloadType.isPrivateFile(rawValue: data.first),
|
||||
NoiseSecurityValidator.validatePrivateFileMessageSize(data) else {
|
||||
throw NoiseSecurityError.messageTooLarge
|
||||
}
|
||||
|
||||
// Check rate limit
|
||||
|
||||
guard rateLimiter.allowMessage(from: peerID) else {
|
||||
throw NoiseSecurityError.rateLimitExceeded
|
||||
}
|
||||
|
||||
// Check if we have an established session
|
||||
|
||||
guard hasEstablishedSession(with: peerID) else {
|
||||
onHandshakeRequired?(peerID)
|
||||
throw NoiseEncryptionError.handshakeRequired
|
||||
}
|
||||
|
||||
// `maxPrivateFilePlaintextSize` already subtracts the cipher's fixed
|
||||
// nonce/tag overhead, so the result is bounded without a second copy.
|
||||
if let sessionGeneration {
|
||||
return try sessionManager.encrypt(
|
||||
data,
|
||||
for: peerID,
|
||||
expectedSessionGeneration: sessionGeneration
|
||||
)
|
||||
}
|
||||
return try sessionManager.encrypt(data, for: peerID)
|
||||
}
|
||||
|
||||
/// Decrypt data from a specific peer
|
||||
func decrypt(_ data: Data, from peerID: PeerID) throws -> Data {
|
||||
try decryptWithSessionGeneration(data, from: peerID).plaintext
|
||||
}
|
||||
|
||||
func decryptWithSessionGeneration(
|
||||
_ data: Data,
|
||||
from peerID: PeerID,
|
||||
establishedGenerationIsReady: (UUID) -> Bool = { _ in true }
|
||||
) throws -> (plaintext: Data, sessionGeneration: UUID) {
|
||||
// Standard transport ciphertext has 20 bytes of nonce/tag overhead.
|
||||
// A larger ciphertext is admitted only up to the framed-file ceiling;
|
||||
// after authenticated decryption it must prove it is `.privateFile`.
|
||||
let isStandardCiphertext = NoiseSecurityValidator.validateCiphertextSize(data)
|
||||
let isAdmittedCiphertext = isStandardCiphertext
|
||||
|| NoiseSecurityValidator.validatePrivateFileCiphertextSize(data)
|
||||
|
||||
// A quarantined transport is deliberately unavailable for outbound
|
||||
// state, but remains receive-only until the responder proves identity
|
||||
// or the bounded rollback restores it.
|
||||
guard sessionManager.hasReceiveSession(for: peerID) else {
|
||||
throw NoiseEncryptionError.sessionNotEstablished
|
||||
}
|
||||
|
||||
return try sessionManager.decrypt(data, from: peerID)
|
||||
let result = try sessionManager.decryptWithSessionGeneration(
|
||||
data,
|
||||
from: peerID,
|
||||
establishedGenerationIsReady:
|
||||
establishedGenerationIsReady,
|
||||
authorizeDecrypt: { [rateLimiter] in
|
||||
guard isAdmittedCiphertext else {
|
||||
throw NoiseSecurityError.messageTooLarge
|
||||
}
|
||||
guard rateLimiter.allowMessage(from: peerID) else {
|
||||
throw NoiseSecurityError.rateLimitExceeded
|
||||
}
|
||||
}
|
||||
)
|
||||
if !isStandardCiphertext {
|
||||
guard NoisePayloadType.isPrivateFile(rawValue: result.plaintext.first),
|
||||
NoiseSecurityValidator.validatePrivateFileMessageSize(result.plaintext) else {
|
||||
throw NoiseSecurityError.messageTooLarge
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// MARK: - Peer Management
|
||||
@@ -770,6 +976,25 @@ final class NoiseEncryptionService {
|
||||
}
|
||||
}
|
||||
|
||||
func sessionGeneration(for peerID: PeerID) -> UUID? {
|
||||
sessionManager.sessionGeneration(for: peerID)
|
||||
}
|
||||
|
||||
/// Runs `body` while holding a read lease on the exact session generation.
|
||||
/// Session insertion, replacement, and removal use the same manager
|
||||
/// barrier, so they cannot interleave with an authenticated-state commit.
|
||||
func withCurrentSessionGeneration<Result>(
|
||||
for peerID: PeerID,
|
||||
expected: UUID,
|
||||
_ body: () -> Result
|
||||
) -> Result? {
|
||||
sessionManager.withCurrentSessionGeneration(
|
||||
for: peerID,
|
||||
expected: expected,
|
||||
body
|
||||
)
|
||||
}
|
||||
|
||||
func clearEphemeralStateForPanic() {
|
||||
sessionManager.removeAllSessions()
|
||||
serviceQueue.sync(flags: .barrier) {
|
||||
@@ -792,24 +1017,36 @@ final class NoiseEncryptionService {
|
||||
|
||||
// MARK: - Private Helpers
|
||||
|
||||
private func handleSessionEstablished(peerID: PeerID, remoteStaticKey: Curve25519.KeyAgreement.PublicKey) {
|
||||
private func handleSessionEstablished(
|
||||
peerID: PeerID,
|
||||
remoteStaticKey: Curve25519.KeyAgreement.PublicKey,
|
||||
sessionGeneration: UUID
|
||||
) {
|
||||
// Calculate fingerprint
|
||||
let fingerprint = remoteStaticKey.rawRepresentation.sha256Fingerprint()
|
||||
|
||||
// Store fingerprint mapping
|
||||
serviceQueue.sync(flags: .barrier) {
|
||||
// Registering handlers is synchronous, and this barrier snapshots them
|
||||
// with the fingerprint update. Invoke the snapshot outside the queue:
|
||||
// parallel Swift Testing workers must not block behind queued callback
|
||||
// registration or allow a handler to re-enter serviceQueue.
|
||||
let handlers: (
|
||||
generationAware: [(PeerID, String, UUID) -> Void],
|
||||
legacy: [(PeerID, String) -> Void]
|
||||
) = serviceQueue.sync(flags: .barrier) {
|
||||
peerFingerprints[peerID] = fingerprint
|
||||
fingerprintToPeerID[fingerprint] = peerID
|
||||
return (onPeerAuthenticatedWithGenerationHandlers, onPeerAuthenticatedHandlers)
|
||||
}
|
||||
|
||||
// Log security event
|
||||
SecureLogger.info(.handshakeCompleted(peerID: peerID.id))
|
||||
|
||||
// Notify all handlers about authentication
|
||||
serviceQueue.async { [weak self] in
|
||||
self?.onPeerAuthenticatedHandlers.forEach { handler in
|
||||
handler(peerID, fingerprint)
|
||||
}
|
||||
// Notify all handlers about authentication.
|
||||
handlers.generationAware.forEach { handler in
|
||||
handler(peerID, fingerprint, sessionGeneration)
|
||||
}
|
||||
handlers.legacy.forEach { handler in
|
||||
handler(peerID, fingerprint)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -830,19 +1067,26 @@ final class NoiseEncryptionService {
|
||||
let sessionsNeedingRekey = sessionManager.getSessionsNeedingRekey()
|
||||
|
||||
for (peerID, needsRekey) in sessionsNeedingRekey where needsRekey {
|
||||
|
||||
// Attempt to rekey the session
|
||||
do {
|
||||
try sessionManager.initiateRekey(for: peerID)
|
||||
SecureLogger.debug("Key rotation initiated for peer: \(peerID)", category: .security)
|
||||
|
||||
// Signal that handshake is needed
|
||||
onHandshakeRequired?(peerID)
|
||||
try initiateAutomaticRekey(for: peerID)
|
||||
} catch {
|
||||
SecureLogger.error(error, context: "Failed to initiate rekey for peer: \(peerID)", category: .session)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func initiateAutomaticRekey(for peerID: PeerID) throws {
|
||||
let initiation = try sessionManager.initiateRekey(for: peerID)
|
||||
SecureLogger.debug("Key rotation initiated for peer: \(peerID)", category: .security)
|
||||
onRekeyHandshakeReady?(peerID, initiation)
|
||||
onHandshakeRequired?(peerID)
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
func _test_initiateAutomaticRekey(for peerID: PeerID) throws {
|
||||
try initiateAutomaticRekey(for: peerID)
|
||||
}
|
||||
#endif
|
||||
|
||||
deinit {
|
||||
stopRekeyTimer()
|
||||
@@ -930,6 +1174,9 @@ struct NoiseMessage: Codable {
|
||||
enum NoiseEncryptionError: Error {
|
||||
case handshakeRequired
|
||||
case sessionNotEstablished
|
||||
/// Manager keys are established or restored, but BLE has not installed
|
||||
/// generation-bound transport state. No receive nonce was consumed.
|
||||
case transportGenerationNotReady
|
||||
/// Envelope references a prekey ID we don't hold (never ours, already
|
||||
/// deleted after its grace window, or wiped in a panic).
|
||||
case unknownPrekey
|
||||
|
||||
@@ -11,6 +11,7 @@ final class TransferProgressManager {
|
||||
case updated(id: String, sentFragments: Int, totalFragments: Int)
|
||||
case completed(id: String, totalFragments: Int)
|
||||
case cancelled(id: String, sentFragments: Int, totalFragments: Int)
|
||||
case rejected(id: String, reason: String)
|
||||
}
|
||||
|
||||
private let subject = PassthroughSubject<Event, Never>()
|
||||
@@ -49,6 +50,17 @@ final class TransferProgressManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fails a preflight check while keeping the outgoing placeholder visible
|
||||
/// with an actionable reason instead of treating policy/size rejection as
|
||||
/// a user cancellation.
|
||||
func rejectBeforeStart(id: String, reason: String) {
|
||||
queue.async(flags: .barrier) { [weak self] in
|
||||
guard let self = self else { return }
|
||||
self.states.removeValue(forKey: id)
|
||||
self.subject.send(.rejected(id: id, reason: reason))
|
||||
}
|
||||
}
|
||||
|
||||
func snapshot(id: String) -> (sent: Int, total: Int)? {
|
||||
var result: (sent: Int, total: Int)?
|
||||
queue.sync {
|
||||
|
||||
@@ -83,10 +83,31 @@ enum TransportEvent: @unchecked Sendable {
|
||||
case bluetoothStateUpdated(CBManagerState)
|
||||
}
|
||||
|
||||
/// Downgrade-safe decision for a private-media recipient. Callers ask before
|
||||
/// prompting, and BLEService checks again when it consumes any one-shot
|
||||
/// legacy consent.
|
||||
enum PrivateMediaSendPolicy: Equatable {
|
||||
case encrypted
|
||||
/// A public announce hinted at encrypted media (or a prior authenticated
|
||||
/// pin exists), but this exact Noise session has not yet supplied its
|
||||
/// authenticated peer-state proof. Callers wait boundedly; they must not
|
||||
/// pre-queue encrypted bytes or silently select the legacy path.
|
||||
case awaitingCapabilityProof
|
||||
case legacyRequiresConsent
|
||||
case blockedDowngrade
|
||||
}
|
||||
|
||||
protocol TransportEventDelegate: AnyObject {
|
||||
@MainActor func didReceiveTransportEvent(_ event: TransportEvent)
|
||||
}
|
||||
|
||||
/// Optional typed-event contract for sinks that can synchronously decide
|
||||
/// whether an inbound message was accepted.
|
||||
protocol SynchronousMessageTransportEventDelegate: TransportEventDelegate {
|
||||
@MainActor
|
||||
func didReceiveTransportMessageSynchronously(_ message: BitchatMessage) -> Bool
|
||||
}
|
||||
|
||||
protocol Transport: AnyObject {
|
||||
// Event sink
|
||||
var delegate: BitchatDelegate? { get set }
|
||||
@@ -163,6 +184,12 @@ protocol Transport: AnyObject {
|
||||
func sendDeliveryAck(for messageID: String, to peerID: PeerID)
|
||||
func sendFileBroadcast(_ packet: BitchatFilePacket, transferId: String)
|
||||
func sendFilePrivate(_ packet: BitchatFilePacket, to peerID: PeerID, transferId: String)
|
||||
func sendFilePrivate(
|
||||
_ packet: BitchatFilePacket,
|
||||
to peerID: PeerID,
|
||||
transferId: String,
|
||||
allowLegacyFallback: Bool
|
||||
)
|
||||
func cancelTransfer(_ transferId: String)
|
||||
|
||||
// Live voice / push-to-talk (mesh transports only): one encoded
|
||||
@@ -208,6 +235,11 @@ protocol Transport: AnyObject {
|
||||
/// Capabilities the peer advertised in its last verified announce;
|
||||
/// empty for peers that predate the capabilities TLV.
|
||||
func peerCapabilities(_ peerID: PeerID) -> PeerCapabilities
|
||||
func privateMediaSendPolicy(to peerID: PeerID) -> PrivateMediaSendPolicy
|
||||
func resolvePrivateMediaSendPolicy(
|
||||
to peerID: PeerID,
|
||||
completion: @escaping @MainActor (PrivateMediaSendPolicy) -> Void
|
||||
)
|
||||
/// Sends an encoded vouch-attestation batch inside the Noise session.
|
||||
func sendVouchAttestations(_ payload: Data, to peerID: PeerID)
|
||||
/// Appends a peer-authenticated observer. Unlike
|
||||
@@ -278,6 +310,16 @@ extension Transport {
|
||||
func sendGroupKeyUpdate(_ statePayload: Data, to peerID: PeerID) {}
|
||||
func broadcastGroupMessage(_ envelope: Data) {}
|
||||
func peerCapabilities(_ peerID: PeerID) -> PeerCapabilities { [] }
|
||||
func privateMediaSendPolicy(to peerID: PeerID) -> PrivateMediaSendPolicy { .blockedDowngrade }
|
||||
func resolvePrivateMediaSendPolicy(
|
||||
to peerID: PeerID,
|
||||
completion: @escaping @MainActor (PrivateMediaSendPolicy) -> Void
|
||||
) {
|
||||
let policy = privateMediaSendPolicy(to: peerID)
|
||||
Task { @MainActor in
|
||||
completion(policy == .awaitingCapabilityProof ? .blockedDowngrade : policy)
|
||||
}
|
||||
}
|
||||
func sendVouchAttestations(_ payload: Data, to peerID: PeerID) {}
|
||||
func addPeerAuthenticatedObserver(_ handler: @escaping (PeerID, String) -> Void) {}
|
||||
func sendCourierMessage(_ content: String, messageID: String, recipientNoiseKey: Data, via couriers: [PeerID]) -> Bool { false }
|
||||
@@ -294,6 +336,15 @@ extension Transport {
|
||||
func currentMeshTopology() -> MeshTopologySnapshot? { nil }
|
||||
func sendFileBroadcast(_ packet: BitchatFilePacket, transferId: String) {}
|
||||
func sendFilePrivate(_ packet: BitchatFilePacket, to peerID: PeerID, transferId: String) {}
|
||||
func sendFilePrivate(
|
||||
_ packet: BitchatFilePacket,
|
||||
to peerID: PeerID,
|
||||
transferId: String,
|
||||
allowLegacyFallback: Bool
|
||||
) {
|
||||
guard !allowLegacyFallback else { return }
|
||||
sendFilePrivate(packet, to: peerID, transferId: transferId)
|
||||
}
|
||||
func cancelTransfer(_ transferId: String) {}
|
||||
|
||||
func sendMessage(_ content: String, mentions: [String], messageID: String, timestamp: Date) {
|
||||
|
||||
@@ -9,6 +9,19 @@ enum TransportConfig {
|
||||
static let bleMaxInFlightAssemblies: Int = 128 // Cap concurrent fragment assemblies
|
||||
static let bleHighDegreeThreshold: Int = 6 // For adaptive TTL/probabilistic relays
|
||||
static let bleMaxConcurrentTransfers: Int = 2 // Limit simultaneous large media sends
|
||||
// Bounded wait for the session-authenticated capability proof used by
|
||||
// private-media migration. Expiry never auto-sends clear bytes; it only
|
||||
// resolves to the existing one-shot consent or downgrade-blocked path.
|
||||
static let privateMediaCapabilityProofTimeoutSeconds: TimeInterval = 5
|
||||
static let privateMediaCapabilityProofPendingPeerCap: Int = 64
|
||||
static let privateMediaCapabilityProofWaitersPerPeerCap: Int = 16
|
||||
/// Accepted private-media receipts and explicit-deletion tombstones each
|
||||
/// receive this independent capacity.
|
||||
static let privateMediaReceivedLedgerCapacity: Int = 4_096
|
||||
/// A bounded retry horizon prevents stable receipt state from growing into
|
||||
/// permanent application history.
|
||||
static let privateMediaReceivedLedgerTTLSeconds: TimeInterval =
|
||||
7 * 24 * 60 * 60
|
||||
static let bleFragmentRelayMinDelayMs: Int = 8 // Faster forwarding for media fragments
|
||||
static let bleFragmentRelayMaxDelayMs: Int = 25 // Upper jitter bound for fragment relays
|
||||
// Fragment relay TTL in sparse graphs; matches messageTTLDefault so media
|
||||
|
||||
@@ -10,6 +10,7 @@ import Foundation
|
||||
@MainActor
|
||||
protocol ChatLiveVoiceContext: AnyObject {
|
||||
var nickname: String { get }
|
||||
var myPeerID: PeerID { get }
|
||||
var selectedPrivateChatPeer: PeerID? { get }
|
||||
/// Whether the public mesh timeline is what's on screen (autoplay gate
|
||||
/// for public bursts).
|
||||
@@ -30,6 +31,12 @@ protocol ChatLiveVoiceContext: AnyObject {
|
||||
func upsertPublicMeshMessage(_ message: BitchatMessage)
|
||||
@discardableResult
|
||||
func removePrivateMessage(withID messageID: String) -> BitchatMessage?
|
||||
/// Records and sends the finalized note's read receipt after a live
|
||||
/// bubble adopts its wire-derivable message ID.
|
||||
func hasSentReadReceipt(_ messageID: String) -> Bool
|
||||
@discardableResult
|
||||
func markReadReceiptSent(_ messageID: String) -> Bool
|
||||
func sendMeshReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID)
|
||||
/// Removes a message from whichever conversation holds it.
|
||||
func removeMessage(withID messageID: String, cleanupFile: Bool)
|
||||
/// Publishes who is currently talking live in the public mesh channel
|
||||
@@ -272,8 +279,16 @@ final class ChatLiveVoiceCoordinator {
|
||||
guard let entry = finishedBursts.first(where: { matches($0.key) }) else { return false }
|
||||
let finished = entry.value
|
||||
|
||||
// A DM live bubble starts before the finalized file exists and
|
||||
// therefore has a receiver-local random ID. Adopt the finalized
|
||||
// message's deterministic ID so delivery/read ACKs address the same
|
||||
// row as the sender's media placeholder. Public notes retain their
|
||||
// live-bubble ID because public transfers have no private receipts.
|
||||
let replacementID = finished.scope == .directMessage
|
||||
? message.id
|
||||
: finished.messageID
|
||||
let replacement = BitchatMessage(
|
||||
id: finished.messageID,
|
||||
id: replacementID,
|
||||
sender: message.sender,
|
||||
content: message.content,
|
||||
timestamp: finished.messageTimestamp,
|
||||
@@ -287,7 +302,31 @@ final class ChatLiveVoiceCoordinator {
|
||||
)
|
||||
switch finished.scope {
|
||||
case .directMessage:
|
||||
// Capture read state before rekeying. The user may have read the
|
||||
// live bubble and navigated away before the finalized .m4a lands.
|
||||
let shouldSendAdoptedReadReceipt =
|
||||
context.hasSentReadReceipt(finished.messageID)
|
||||
|| context.selectedPrivateChatPeer == finished.peerID
|
||||
|
||||
// Insert first so replacing the only row in a DM never
|
||||
// transiently deletes its conversation, unread state, or current
|
||||
// selection. Then remove the receiver-local live-bubble alias.
|
||||
context.upsertPrivateMessage(replacement, in: finished.peerID)
|
||||
if replacementID != finished.messageID {
|
||||
context.removePrivateMessage(withID: finished.messageID)
|
||||
}
|
||||
// The live bubble may already have emitted a receiver-local READ
|
||||
// before the sender created its finalized media row. Re-emit once
|
||||
// for the adopted stable ID now that the file has arrived.
|
||||
if shouldSendAdoptedReadReceipt,
|
||||
context.markReadReceiptSent(replacementID) {
|
||||
let receipt = ReadReceipt(
|
||||
originalMessageID: replacementID,
|
||||
readerID: context.myPeerID,
|
||||
readerNickname: context.nickname
|
||||
)
|
||||
context.sendMeshReadReceipt(receipt, to: finished.peerID)
|
||||
}
|
||||
case .publicMesh:
|
||||
context.upsertPublicMeshMessage(replacement)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,19 @@ import Foundation
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
struct LegacyPrivateMediaConsentRequest: Identifiable, Equatable {
|
||||
let id: UUID
|
||||
let peerID: PeerID
|
||||
let peerName: String
|
||||
let transferId: String
|
||||
let messageID: String
|
||||
}
|
||||
|
||||
struct PendingLegacyPrivateMediaConsent {
|
||||
let request: LegacyPrivateMediaConsentRequest
|
||||
let completion: @MainActor (Bool) -> Void
|
||||
}
|
||||
|
||||
/// The narrow surface `ChatMediaTransferCoordinator` needs from its owner.
|
||||
///
|
||||
/// Follows the `ChatDeliveryContext` exemplar: the coordinator depends on the
|
||||
@@ -43,7 +56,24 @@ protocol ChatMediaTransferContext: AnyObject {
|
||||
func recordContentKey(_ key: String, timestamp: Date)
|
||||
|
||||
// MARK: Mesh file transfer
|
||||
func sendFilePrivate(_ packet: BitchatFilePacket, to peerID: PeerID, transferId: String)
|
||||
func privateMediaSendPolicy(to peerID: PeerID) -> PrivateMediaSendPolicy
|
||||
func resolvePrivateMediaSendPolicy(
|
||||
to peerID: PeerID,
|
||||
completion: @escaping @MainActor (PrivateMediaSendPolicy) -> Void
|
||||
)
|
||||
func requestLegacyPrivateMediaConsent(
|
||||
for peerID: PeerID,
|
||||
transferId: String,
|
||||
messageID: String,
|
||||
completion: @escaping @MainActor (Bool) -> Void
|
||||
)
|
||||
func cancelLegacyPrivateMediaConsent(transferId: String, messageID: String)
|
||||
func sendFilePrivate(
|
||||
_ packet: BitchatFilePacket,
|
||||
to peerID: PeerID,
|
||||
transferId: String,
|
||||
allowLegacyFallback: Bool
|
||||
)
|
||||
func sendFileBroadcast(_ packet: BitchatFilePacket, transferId: String)
|
||||
func cancelTransfer(_ transferId: String)
|
||||
}
|
||||
@@ -59,8 +89,50 @@ extension ChatViewModel: ChatMediaTransferContext {
|
||||
// other contexts or satisfied by existing `ChatViewModel` members. The
|
||||
// members below flatten mesh service accesses.
|
||||
|
||||
func sendFilePrivate(_ packet: BitchatFilePacket, to peerID: PeerID, transferId: String) {
|
||||
meshService.sendFilePrivate(packet, to: peerID, transferId: transferId)
|
||||
func privateMediaSendPolicy(to peerID: PeerID) -> PrivateMediaSendPolicy {
|
||||
meshService.privateMediaSendPolicy(to: peerID)
|
||||
}
|
||||
|
||||
func resolvePrivateMediaSendPolicy(
|
||||
to peerID: PeerID,
|
||||
completion: @escaping @MainActor (PrivateMediaSendPolicy) -> Void
|
||||
) {
|
||||
meshService.resolvePrivateMediaSendPolicy(to: peerID, completion: completion)
|
||||
}
|
||||
|
||||
func requestLegacyPrivateMediaConsent(
|
||||
for peerID: PeerID,
|
||||
transferId: String,
|
||||
messageID: String,
|
||||
completion: @escaping @MainActor (Bool) -> Void
|
||||
) {
|
||||
enqueueLegacyPrivateMediaConsent(
|
||||
for: peerID,
|
||||
transferId: transferId,
|
||||
messageID: messageID,
|
||||
completion: completion
|
||||
)
|
||||
}
|
||||
|
||||
func cancelLegacyPrivateMediaConsent(transferId: String, messageID: String) {
|
||||
invalidateLegacyPrivateMediaConsent(
|
||||
transferId: transferId,
|
||||
messageID: messageID
|
||||
)
|
||||
}
|
||||
|
||||
func sendFilePrivate(
|
||||
_ packet: BitchatFilePacket,
|
||||
to peerID: PeerID,
|
||||
transferId: String,
|
||||
allowLegacyFallback: Bool
|
||||
) {
|
||||
meshService.sendFilePrivate(
|
||||
packet,
|
||||
to: peerID,
|
||||
transferId: transferId,
|
||||
allowLegacyFallback: allowLegacyFallback
|
||||
)
|
||||
}
|
||||
|
||||
func sendFileBroadcast(_ packet: BitchatFilePacket, transferId: String) {
|
||||
@@ -152,6 +224,7 @@ final class ChatMediaTransferCoordinator {
|
||||
private unowned let context: any ChatMediaTransferContext
|
||||
private let prepareImagePacket: @Sendable (URL) throws -> ChatPreparedImage
|
||||
private let imagePreparationBarrier = ImagePreparationBarrier()
|
||||
private let prepareVoiceNotePacket: @Sendable (URL) throws -> BitchatFilePacket
|
||||
|
||||
private(set) var transferIdToMessageIDs: [String: [String]] = [:]
|
||||
private(set) var messageIDToTransferId: [String: String] = [:]
|
||||
@@ -160,10 +233,14 @@ final class ChatMediaTransferCoordinator {
|
||||
context: any ChatMediaTransferContext,
|
||||
prepareImagePacket: @escaping @Sendable (URL) throws -> ChatPreparedImage = {
|
||||
try ChatMediaPreparation.prepareImagePacket(from: $0)
|
||||
},
|
||||
prepareVoiceNotePacket: @escaping @Sendable (URL) throws -> BitchatFilePacket = {
|
||||
try ChatMediaPreparation.prepareVoiceNotePacket(at: $0)
|
||||
}
|
||||
) {
|
||||
self.context = context
|
||||
self.prepareImagePacket = prepareImagePacket
|
||||
self.prepareVoiceNotePacket = prepareVoiceNotePacket
|
||||
}
|
||||
|
||||
func sendVoiceNote(at url: URL) {
|
||||
@@ -175,28 +252,47 @@ final class ChatMediaTransferCoordinator {
|
||||
}
|
||||
|
||||
let targetPeer = context.selectedPrivateChatPeer
|
||||
let privateMessageID = targetPeer.flatMap { peerID in
|
||||
PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: context.myPeerID,
|
||||
recipientPeerID: peerID,
|
||||
fileName: url.lastPathComponent
|
||||
)
|
||||
}
|
||||
let message = enqueueMediaMessage(
|
||||
content: "\(MimeType.Category.audio.messagePrefix)\(url.lastPathComponent)",
|
||||
targetPeer: targetPeer
|
||||
targetPeer: targetPeer,
|
||||
messageID: privateMessageID
|
||||
)
|
||||
let messageID = message.id
|
||||
let transferId = makeTransferID(messageID: messageID)
|
||||
let generation = imagePreparationBarrier.currentGeneration
|
||||
// Own the transfer before detached preparation begins. Cancel/delete
|
||||
// must be able to invalidate this exact invocation even while file I/O
|
||||
// is still running off the main actor.
|
||||
registerTransfer(transferId: transferId, messageID: messageID)
|
||||
let prepareVoiceNotePacket = self.prepareVoiceNotePacket
|
||||
let barrier = imagePreparationBarrier
|
||||
let generation = barrier.currentGeneration
|
||||
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
Task.detached(priority: .userInitiated) { [weak self, barrier] in
|
||||
do {
|
||||
let packet = try await runBlockingMediaPreparation {
|
||||
try ChatMediaPreparation.prepareVoiceNotePacket(at: url)
|
||||
try prepareVoiceNotePacket(url)
|
||||
}
|
||||
|
||||
await MainActor.run { [weak self] in
|
||||
await MainActor.run { [weak self, barrier] in
|
||||
guard let self,
|
||||
self.imagePreparationBarrier.isCurrent(generation) else {
|
||||
barrier.isCurrent(generation),
|
||||
self.isRegisteredTransfer(transferId, messageID: messageID) else {
|
||||
return
|
||||
}
|
||||
self.registerTransfer(transferId: transferId, messageID: messageID)
|
||||
if let peerID = targetPeer {
|
||||
self.context.sendFilePrivate(packet, to: peerID, transferId: transferId)
|
||||
self.beginPrivateMediaSend(
|
||||
packet,
|
||||
to: peerID,
|
||||
transferId: transferId,
|
||||
messageID: messageID
|
||||
)
|
||||
} else {
|
||||
self.context.sendFileBroadcast(packet, transferId: transferId)
|
||||
}
|
||||
@@ -204,18 +300,20 @@ final class ChatMediaTransferCoordinator {
|
||||
} catch ChatMediaPreparationError.voiceNoteTooLarge(let size) {
|
||||
SecureLogger.warning("Voice note exceeds size limit (\(size) bytes)", category: .session)
|
||||
try? FileManager.default.removeItem(at: url)
|
||||
await MainActor.run { [weak self] in
|
||||
await MainActor.run { [weak self, barrier] in
|
||||
guard let self,
|
||||
self.imagePreparationBarrier.isCurrent(generation) else {
|
||||
barrier.isCurrent(generation),
|
||||
self.isRegisteredTransfer(transferId, messageID: messageID) else {
|
||||
return
|
||||
}
|
||||
self.handleMediaSendFailure(messageID: messageID, reason: String(localized: "content.delivery.reason.voice_too_large", comment: "Failure reason shown when a voice note exceeds the size limit"))
|
||||
}
|
||||
} catch {
|
||||
SecureLogger.error("Voice note send failed: \(error)", category: .session)
|
||||
await MainActor.run { [weak self] in
|
||||
await MainActor.run { [weak self, barrier] in
|
||||
guard let self,
|
||||
self.imagePreparationBarrier.isCurrent(generation) else {
|
||||
barrier.isCurrent(generation),
|
||||
self.isRegisteredTransfer(transferId, messageID: messageID) else {
|
||||
return
|
||||
}
|
||||
self.handleMediaSendFailure(messageID: messageID, reason: String(localized: "content.delivery.reason.voice_send_failed", comment: "Failure reason shown when a voice note could not be sent"))
|
||||
@@ -329,15 +427,28 @@ final class ChatMediaTransferCoordinator {
|
||||
try? FileManager.default.removeItem(at: prepared.outputURL)
|
||||
return
|
||||
}
|
||||
let privateMessageID = targetPeer.flatMap { peerID in
|
||||
PrivateMediaMessageIdentity.stableID(
|
||||
for: prepared.packet,
|
||||
senderPeerID: self.context.myPeerID,
|
||||
recipientPeerID: peerID
|
||||
)
|
||||
}
|
||||
let message = self.enqueueMediaMessage(
|
||||
content: "\(MimeType.Category.image.messagePrefix)\(prepared.outputURL.lastPathComponent)",
|
||||
targetPeer: targetPeer
|
||||
targetPeer: targetPeer,
|
||||
messageID: privateMessageID
|
||||
)
|
||||
let messageID = message.id
|
||||
let transferId = self.makeTransferID(messageID: messageID)
|
||||
self.registerTransfer(transferId: transferId, messageID: messageID)
|
||||
if let peerID = targetPeer {
|
||||
self.context.sendFilePrivate(prepared.packet, to: peerID, transferId: transferId)
|
||||
self.beginPrivateMediaSend(
|
||||
prepared.packet,
|
||||
to: peerID,
|
||||
transferId: transferId,
|
||||
messageID: messageID
|
||||
)
|
||||
} else {
|
||||
self.context.sendFileBroadcast(prepared.packet, transferId: transferId)
|
||||
}
|
||||
@@ -364,12 +475,17 @@ final class ChatMediaTransferCoordinator {
|
||||
}
|
||||
}
|
||||
|
||||
func enqueueMediaMessage(content: String, targetPeer: PeerID?) -> BitchatMessage {
|
||||
func enqueueMediaMessage(
|
||||
content: String,
|
||||
targetPeer: PeerID?,
|
||||
messageID: String? = nil
|
||||
) -> BitchatMessage {
|
||||
let timestamp = Date()
|
||||
let message: BitchatMessage
|
||||
|
||||
if let peerID = targetPeer {
|
||||
message = BitchatMessage(
|
||||
id: messageID,
|
||||
sender: context.nickname,
|
||||
content: content,
|
||||
timestamp: timestamp,
|
||||
@@ -403,17 +519,127 @@ final class ChatMediaTransferCoordinator {
|
||||
return message
|
||||
}
|
||||
|
||||
private func beginPrivateMediaSend(
|
||||
_ packet: BitchatFilePacket,
|
||||
to peerID: PeerID,
|
||||
transferId: String,
|
||||
messageID: String
|
||||
) {
|
||||
continuePrivateMediaSend(
|
||||
packet,
|
||||
to: peerID,
|
||||
transferId: transferId,
|
||||
messageID: messageID,
|
||||
policy: context.privateMediaSendPolicy(to: peerID)
|
||||
)
|
||||
}
|
||||
|
||||
private func continuePrivateMediaSend(
|
||||
_ packet: BitchatFilePacket,
|
||||
to peerID: PeerID,
|
||||
transferId: String,
|
||||
messageID: String,
|
||||
policy: PrivateMediaSendPolicy
|
||||
) {
|
||||
switch policy {
|
||||
case .encrypted:
|
||||
context.sendFilePrivate(
|
||||
packet,
|
||||
to: peerID,
|
||||
transferId: transferId,
|
||||
allowLegacyFallback: false
|
||||
)
|
||||
|
||||
case .awaitingCapabilityProof:
|
||||
context.resolvePrivateMediaSendPolicy(to: peerID) { [weak self] resolvedPolicy in
|
||||
guard let self,
|
||||
self.isRegisteredTransfer(transferId, messageID: messageID) else {
|
||||
return
|
||||
}
|
||||
guard resolvedPolicy != .awaitingCapabilityProof else {
|
||||
self.handleMediaSendFailure(
|
||||
messageID: messageID,
|
||||
reason: String(
|
||||
localized: "content.delivery.reason.private_media_capability_unresolved",
|
||||
defaultValue: "Could not confirm encrypted media support",
|
||||
comment: "Failure reason when private-media capability negotiation did not resolve"
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
self.continuePrivateMediaSend(
|
||||
packet,
|
||||
to: peerID,
|
||||
transferId: transferId,
|
||||
messageID: messageID,
|
||||
policy: resolvedPolicy
|
||||
)
|
||||
}
|
||||
|
||||
case .legacyRequiresConsent:
|
||||
context.requestLegacyPrivateMediaConsent(
|
||||
for: peerID,
|
||||
transferId: transferId,
|
||||
messageID: messageID
|
||||
) { [weak self] approved in
|
||||
guard let self else { return }
|
||||
// Consent belongs to this exact placeholder/transfer. A late
|
||||
// dialog callback after cancel/delete must never resurrect it.
|
||||
guard self.messageIDToTransferId[messageID] == transferId,
|
||||
self.transferIdToMessageIDs[transferId]?.contains(messageID) == true else {
|
||||
return
|
||||
}
|
||||
guard approved else {
|
||||
self.handleMediaSendFailure(
|
||||
messageID: messageID,
|
||||
reason: String(
|
||||
localized: "content.delivery.reason.legacy_media_declined",
|
||||
defaultValue: "Not sent without end-to-end encryption",
|
||||
comment: "Failure reason after declining the warning for a legacy clear private-media send"
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
self.context.sendFilePrivate(
|
||||
packet,
|
||||
to: peerID,
|
||||
transferId: transferId,
|
||||
allowLegacyFallback: true
|
||||
)
|
||||
}
|
||||
|
||||
case .blockedDowngrade:
|
||||
handleMediaSendFailure(
|
||||
messageID: messageID,
|
||||
reason: String(
|
||||
localized: "content.delivery.reason.private_media_downgrade_blocked",
|
||||
defaultValue: "Encrypted media required; ask this contact to upgrade",
|
||||
comment: "Failure reason when a peer that previously supported encrypted media appears to downgrade"
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func registerTransfer(transferId: String, messageID: String) {
|
||||
transferIdToMessageIDs[transferId, default: []].append(messageID)
|
||||
messageIDToTransferId[messageID] = transferId
|
||||
}
|
||||
|
||||
private func isRegisteredTransfer(_ transferId: String, messageID: String) -> Bool {
|
||||
messageIDToTransferId[messageID] == transferId
|
||||
&& transferIdToMessageIDs[transferId]?.contains(messageID) == true
|
||||
}
|
||||
|
||||
func makeTransferID(messageID: String) -> String {
|
||||
"\(messageID)-\(UUID().uuidString)"
|
||||
}
|
||||
|
||||
func clearTransferMapping(for messageID: String) {
|
||||
guard let transferId = messageIDToTransferId.removeValue(forKey: messageID) else { return }
|
||||
context.cancelLegacyPrivateMediaConsent(
|
||||
transferId: transferId,
|
||||
messageID: messageID
|
||||
)
|
||||
guard var queue = transferIdToMessageIDs[transferId] else { return }
|
||||
|
||||
if !queue.isEmpty {
|
||||
@@ -448,6 +674,9 @@ final class ChatMediaTransferCoordinator {
|
||||
guard let messageID = transferIdToMessageIDs[id]?.first else { return }
|
||||
clearTransferMapping(for: messageID)
|
||||
context.removeMessage(withID: messageID, cleanupFile: true)
|
||||
case .rejected(let id, let reason):
|
||||
guard let messageID = transferIdToMessageIDs[id]?.first else { return }
|
||||
handleMediaSendFailure(messageID: messageID, reason: reason)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -488,6 +717,13 @@ final class ChatMediaTransferCoordinator {
|
||||
}
|
||||
|
||||
func deleteMediaMessage(messageID: String) {
|
||||
// Delete is also a send cancellation. In particular, an approved
|
||||
// legacy-clear send may still be waiting on BLEService.messageQueue;
|
||||
// removing only the UI mapping would let that deferred work transmit.
|
||||
if let transferId = messageIDToTransferId[messageID],
|
||||
transferIdToMessageIDs[transferId]?.first == messageID {
|
||||
context.cancelTransfer(transferId)
|
||||
}
|
||||
clearTransferMapping(for: messageID)
|
||||
context.removeMessage(withID: messageID, cleanupFile: true)
|
||||
}
|
||||
|
||||
@@ -100,9 +100,14 @@ final class ChatPeerListCoordinator: @unchecked Sendable {
|
||||
|
||||
func didUpdatePeerList(_ peers: [PeerID]) {
|
||||
Task { @MainActor [weak self] in
|
||||
self?.handlePeerListUpdate(peers)
|
||||
self?.didUpdatePeerListSynchronously(peers)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func didUpdatePeerListSynchronously(_ peers: [PeerID]) {
|
||||
handlePeerListUpdate(peers)
|
||||
}
|
||||
}
|
||||
|
||||
private extension ChatPeerListCoordinator {
|
||||
|
||||
@@ -163,21 +163,20 @@ final class ChatTransportEventCoordinator {
|
||||
}
|
||||
|
||||
func didReceiveMessage(_ message: BitchatMessage) {
|
||||
runOnMain { context in
|
||||
guard !context.isMessageBlocked(message) else { return }
|
||||
guard !message.content.trimmed.isEmpty || message.isPrivate else { return }
|
||||
|
||||
if message.isPrivate {
|
||||
context.handlePrivateMessage(message)
|
||||
} else {
|
||||
context.handlePublicMessage(message)
|
||||
}
|
||||
|
||||
context.checkForMentions(message)
|
||||
context.sendHapticFeedback(for: message)
|
||||
runOnMain { [self] context in
|
||||
handleReceivedMessage(message, in: context)
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed transport events already arrive on the main actor. Handle them
|
||||
/// synchronously so observers see the ConversationStore mutation before
|
||||
/// the transport completes delivery.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
func didReceiveMessageSynchronously(_ message: BitchatMessage) -> Bool {
|
||||
handleReceivedMessage(message, in: context)
|
||||
}
|
||||
|
||||
func didReceivePublicMessage(
|
||||
from peerID: PeerID,
|
||||
nickname: String,
|
||||
@@ -185,28 +184,36 @@ final class ChatTransportEventCoordinator {
|
||||
timestamp: Date,
|
||||
messageID: String?
|
||||
) {
|
||||
runOnMain { context in
|
||||
let normalized = content.trimmed
|
||||
let mentions = context.parseMentions(from: normalized)
|
||||
let message = BitchatMessage(
|
||||
id: messageID,
|
||||
sender: nickname,
|
||||
content: normalized,
|
||||
runOnMain { [self] context in
|
||||
handlePublicMessage(
|
||||
from: peerID,
|
||||
nickname: nickname,
|
||||
content: content,
|
||||
timestamp: timestamp,
|
||||
isRelay: false,
|
||||
originalSender: nil,
|
||||
isPrivate: false,
|
||||
recipientNickname: nil,
|
||||
senderPeerID: peerID,
|
||||
mentions: mentions.isEmpty ? nil : mentions
|
||||
messageID: messageID,
|
||||
in: context
|
||||
)
|
||||
|
||||
context.handlePublicMessage(message)
|
||||
context.checkForMentions(message)
|
||||
context.sendHapticFeedback(for: message)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func didReceivePublicMessageSynchronously(
|
||||
from peerID: PeerID,
|
||||
nickname: String,
|
||||
content: String,
|
||||
timestamp: Date,
|
||||
messageID: String?
|
||||
) {
|
||||
handlePublicMessage(
|
||||
from: peerID,
|
||||
nickname: nickname,
|
||||
content: content,
|
||||
timestamp: timestamp,
|
||||
messageID: messageID,
|
||||
in: context
|
||||
)
|
||||
}
|
||||
|
||||
func didReceiveNoisePayload(
|
||||
from peerID: PeerID,
|
||||
type: NoisePayloadType,
|
||||
@@ -224,59 +231,134 @@ final class ChatTransportEventCoordinator {
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func didReceiveNoisePayloadSynchronously(
|
||||
from peerID: PeerID,
|
||||
type: NoisePayloadType,
|
||||
payload: Data,
|
||||
timestamp: Date
|
||||
) {
|
||||
handleNoisePayload(
|
||||
from: peerID,
|
||||
type: type,
|
||||
payload: payload,
|
||||
timestamp: timestamp,
|
||||
in: context
|
||||
)
|
||||
}
|
||||
|
||||
func didConnectToPeer(_ peerID: PeerID) {
|
||||
SecureLogger.debug("🤝 Peer connected: \(peerID)", category: .session)
|
||||
|
||||
runOnMain { context in
|
||||
context.isConnected = true
|
||||
context.registerEphemeralSession(peerID: peerID)
|
||||
context.notifyUIChanged()
|
||||
|
||||
if let peer = context.unifiedPeer(for: peerID) {
|
||||
let stablePeerID = PeerID(hexData: peer.noisePublicKey)
|
||||
context.cacheStablePeerID(stablePeerID, for: peerID)
|
||||
}
|
||||
|
||||
context.flushRouterOutbox(for: peerID)
|
||||
context.retryCourierDeposits(via: peerID)
|
||||
runOnMain { [weak self] _ in
|
||||
self?.didConnectToPeerSynchronously(peerID)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func didConnectToPeerSynchronously(_ peerID: PeerID) {
|
||||
SecureLogger.debug("🤝 Peer connected: \(peerID)", category: .session)
|
||||
|
||||
context.isConnected = true
|
||||
context.registerEphemeralSession(peerID: peerID)
|
||||
context.notifyUIChanged()
|
||||
|
||||
if let peer = context.unifiedPeer(for: peerID) {
|
||||
let stablePeerID = PeerID(hexData: peer.noisePublicKey)
|
||||
context.cacheStablePeerID(stablePeerID, for: peerID)
|
||||
}
|
||||
|
||||
context.flushRouterOutbox(for: peerID)
|
||||
context.retryCourierDeposits(via: peerID)
|
||||
}
|
||||
|
||||
func didDisconnectFromPeer(_ peerID: PeerID) {
|
||||
runOnMain { [weak self] _ in
|
||||
self?.didDisconnectFromPeerSynchronously(peerID)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func didDisconnectFromPeerSynchronously(_ peerID: PeerID) {
|
||||
SecureLogger.debug("👋 Peer disconnected: \(peerID)", category: .session)
|
||||
|
||||
runOnMain { context in
|
||||
context.removeEphemeralSession(peerID: peerID)
|
||||
context.removeEphemeralSession(peerID: peerID)
|
||||
|
||||
var stablePeerID = context.cachedStablePeerID(for: peerID)
|
||||
if stablePeerID == nil,
|
||||
let key = context.noiseSessionPublicKeyData(for: peerID) {
|
||||
let derivedPeerID = PeerID(hexData: key)
|
||||
context.cacheStablePeerID(derivedPeerID, for: peerID)
|
||||
stablePeerID = derivedPeerID
|
||||
}
|
||||
|
||||
if let currentPeerID = context.selectedPrivateChatPeer,
|
||||
currentPeerID == peerID,
|
||||
let stablePeerID {
|
||||
self.migrateSelectedConversationIfNeeded(
|
||||
from: peerID,
|
||||
to: stablePeerID,
|
||||
in: context
|
||||
)
|
||||
}
|
||||
|
||||
let receiptIDs = context.privateMessages(for: peerID)
|
||||
.filter { $0.senderPeerID == peerID }
|
||||
.map(\.id)
|
||||
context.unmarkReadReceiptsSent(receiptIDs)
|
||||
|
||||
context.notifyUIChanged()
|
||||
var stablePeerID = context.cachedStablePeerID(for: peerID)
|
||||
if stablePeerID == nil,
|
||||
let key = context.noiseSessionPublicKeyData(for: peerID) {
|
||||
let derivedPeerID = PeerID(hexData: key)
|
||||
context.cacheStablePeerID(derivedPeerID, for: peerID)
|
||||
stablePeerID = derivedPeerID
|
||||
}
|
||||
|
||||
if let currentPeerID = context.selectedPrivateChatPeer,
|
||||
currentPeerID == peerID,
|
||||
let stablePeerID {
|
||||
migrateSelectedConversationIfNeeded(
|
||||
from: peerID,
|
||||
to: stablePeerID,
|
||||
in: context
|
||||
)
|
||||
}
|
||||
|
||||
let receiptIDs = context.privateMessages(for: peerID)
|
||||
.filter { $0.senderPeerID == peerID }
|
||||
.map(\.id)
|
||||
context.unmarkReadReceiptsSent(receiptIDs)
|
||||
|
||||
context.notifyUIChanged()
|
||||
}
|
||||
}
|
||||
|
||||
private extension ChatTransportEventCoordinator {
|
||||
@MainActor
|
||||
func handlePublicMessage(
|
||||
from peerID: PeerID,
|
||||
nickname: String,
|
||||
content: String,
|
||||
timestamp: Date,
|
||||
messageID: String?,
|
||||
in context: any ChatTransportEventContext
|
||||
) {
|
||||
let normalized = content.trimmed
|
||||
let mentions = context.parseMentions(from: normalized)
|
||||
let message = BitchatMessage(
|
||||
id: messageID,
|
||||
sender: nickname,
|
||||
content: normalized,
|
||||
timestamp: timestamp,
|
||||
isRelay: false,
|
||||
originalSender: nil,
|
||||
isPrivate: false,
|
||||
recipientNickname: nil,
|
||||
senderPeerID: peerID,
|
||||
mentions: mentions.isEmpty ? nil : mentions
|
||||
)
|
||||
|
||||
context.handlePublicMessage(message)
|
||||
context.checkForMentions(message)
|
||||
context.sendHapticFeedback(for: message)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@discardableResult
|
||||
func handleReceivedMessage(
|
||||
_ message: BitchatMessage,
|
||||
in context: any ChatTransportEventContext
|
||||
) -> Bool {
|
||||
guard !context.isMessageBlocked(message) else { return false }
|
||||
guard !message.content.trimmed.isEmpty || message.isPrivate else { return false }
|
||||
|
||||
if message.isPrivate {
|
||||
context.handlePrivateMessage(message)
|
||||
} else {
|
||||
context.handlePublicMessage(message)
|
||||
}
|
||||
|
||||
context.checkForMentions(message)
|
||||
context.sendHapticFeedback(for: message)
|
||||
return true
|
||||
}
|
||||
|
||||
func runOnMain(_ action: @escaping @MainActor (any ChatTransportEventContext) -> Void) {
|
||||
Task { @MainActor [weak context = self.context] in
|
||||
guard let context else { return }
|
||||
@@ -407,6 +489,13 @@ private extension ChatTransportEventCoordinator {
|
||||
|
||||
case .voiceFrame:
|
||||
context.handleVoiceFramePayload(from: peerID, payload: payload, timestamp: timestamp)
|
||||
|
||||
case .privateFile, .authenticatedPeerState:
|
||||
// BLEService validates and persists decrypted private files before
|
||||
// emitting a normal `.messageReceived` event, and consumes peer
|
||||
// state inside the transport. Neither payload crosses this
|
||||
// UI-facing typed-payload fallback.
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ struct PanicNetworkLifecycle {
|
||||
/// Manages the application state and business logic for BitChat.
|
||||
/// Acts as the primary coordinator between UI components and backend services,
|
||||
/// implementing the BitchatDelegate protocol to handle network events.
|
||||
final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDelegate, CommandContextProvider, GeohashParticipantContext, MessageFormattingContext {
|
||||
final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessageTransportEventDelegate, CommandContextProvider, GeohashParticipantContext, MessageFormattingContext {
|
||||
// Use MessageFormattingEngine.Patterns for regex matching (shared, precompiled)
|
||||
typealias Patterns = MessageFormattingEngine.Patterns
|
||||
|
||||
@@ -375,6 +375,8 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
@Published var showBluetoothAlert = false
|
||||
@Published var bluetoothAlertMessage = ""
|
||||
@Published var bluetoothState: CBManagerState = .unknown
|
||||
@Published private(set) var legacyPrivateMediaConsentRequest: LegacyPrivateMediaConsentRequest?
|
||||
private var pendingLegacyPrivateMediaConsents: [PendingLegacyPrivateMediaConsent] = []
|
||||
|
||||
private func performDeliveryUpdate(_ update: @escaping @MainActor (ChatDeliveryCoordinator) -> Void) {
|
||||
if Thread.isMainThread {
|
||||
@@ -493,6 +495,12 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a read receipt has already been recorded for `messageID`.
|
||||
@MainActor
|
||||
func hasSentReadReceipt(_ messageID: String) -> Bool {
|
||||
sentReadReceipts.contains(messageID)
|
||||
}
|
||||
|
||||
/// Records that a read receipt is being sent for `messageID`.
|
||||
/// Returns `false` when one was already recorded — the caller must skip sending.
|
||||
@MainActor
|
||||
@@ -1268,6 +1276,10 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
mediaTransferCoordinator.resetForPanic()
|
||||
liveVoiceCoordinator.resetForPanic()
|
||||
|
||||
// Deny and release any clear-media confirmations before identities,
|
||||
// message state, and local files are wiped.
|
||||
cancelAllLegacyPrivateMediaConsents()
|
||||
|
||||
// Clear all messages (public timelines and private chats live in the
|
||||
// single-writer ConversationStore; the derived `messages` view and
|
||||
// the legacy mirror empty with it)
|
||||
@@ -1695,7 +1707,81 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
|
||||
@MainActor
|
||||
func didReceiveTransportEvent(_ event: TransportEvent) {
|
||||
receiveTransportEvent(event)
|
||||
switch event {
|
||||
case .messageReceived(let message):
|
||||
_ = didReceiveTransportMessageSynchronously(message)
|
||||
|
||||
case let .publicMessageReceived(
|
||||
peerID,
|
||||
nickname,
|
||||
content,
|
||||
timestamp,
|
||||
messageID
|
||||
):
|
||||
transportEventCoordinator.didReceivePublicMessageSynchronously(
|
||||
from: peerID,
|
||||
nickname: nickname,
|
||||
content: content,
|
||||
timestamp: timestamp,
|
||||
messageID: messageID
|
||||
)
|
||||
|
||||
case let .noisePayloadReceived(peerID, type, payload, timestamp):
|
||||
transportEventCoordinator.didReceiveNoisePayloadSynchronously(
|
||||
from: peerID,
|
||||
type: type,
|
||||
payload: payload,
|
||||
timestamp: timestamp
|
||||
)
|
||||
|
||||
case let .groupMessageReceived(payload, timestamp):
|
||||
groupCoordinator.handleGroupMessagePayload(
|
||||
payload,
|
||||
timestamp: timestamp
|
||||
)
|
||||
|
||||
case let .publicVoiceFrameReceived(
|
||||
peerID,
|
||||
nickname,
|
||||
payload,
|
||||
timestamp
|
||||
):
|
||||
liveVoiceCoordinator.handlePublicVoiceFramePayload(
|
||||
from: peerID,
|
||||
nickname: nickname,
|
||||
payload: payload,
|
||||
timestamp: timestamp
|
||||
)
|
||||
|
||||
case .peerConnected(let peerID):
|
||||
transportEventCoordinator.didConnectToPeerSynchronously(peerID)
|
||||
|
||||
case .peerDisconnected(let peerID):
|
||||
transportEventCoordinator.didDisconnectFromPeerSynchronously(peerID)
|
||||
|
||||
case .peerListUpdated(let peers):
|
||||
peerListCoordinator.didUpdatePeerListSynchronously(peers)
|
||||
// A peer-list update follows every verified announce, which is
|
||||
// where a peer's `.vouch` capability actually arrives.
|
||||
vouchCoordinator.peersUpdated(peers)
|
||||
|
||||
case .peerSnapshotsUpdated:
|
||||
break
|
||||
|
||||
case let .messageDeliveryStatusUpdated(messageID, status):
|
||||
deliveryCoordinator.didUpdateMessageDeliveryStatus(
|
||||
messageID,
|
||||
status: status
|
||||
)
|
||||
|
||||
case .bluetoothStateUpdated(let state):
|
||||
updateBluetoothState(state)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func didReceiveTransportMessageSynchronously(_ message: BitchatMessage) -> Bool {
|
||||
transportEventCoordinator.didReceiveMessageSynchronously(message)
|
||||
}
|
||||
|
||||
func didReceiveMessage(_ message: BitchatMessage) {
|
||||
@@ -1922,4 +2008,91 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
publicConversationCoordinator.sendHapticFeedback(for: message)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
extension ChatViewModel {
|
||||
func enqueueLegacyPrivateMediaConsent(
|
||||
for peerID: PeerID,
|
||||
transferId: String,
|
||||
messageID: String,
|
||||
completion: @escaping @MainActor (Bool) -> Void
|
||||
) {
|
||||
let request = LegacyPrivateMediaConsentRequest(
|
||||
id: UUID(),
|
||||
peerID: peerID,
|
||||
peerName: nicknameForPeer(peerID),
|
||||
transferId: transferId,
|
||||
messageID: messageID
|
||||
)
|
||||
pendingLegacyPrivateMediaConsents.append(PendingLegacyPrivateMediaConsent(
|
||||
request: request,
|
||||
completion: completion
|
||||
))
|
||||
if legacyPrivateMediaConsentRequest == nil {
|
||||
legacyPrivateMediaConsentRequest = request
|
||||
}
|
||||
}
|
||||
|
||||
func resolveLegacyPrivateMediaConsent(requestID: UUID, approved: Bool) {
|
||||
// SwiftUI may report both the selected button and the presentation
|
||||
// binding's dismissal. Resolve only the exact request that was shown;
|
||||
// a duplicate callback for it must not consume the next queued send.
|
||||
guard legacyPrivateMediaConsentRequest?.id == requestID,
|
||||
pendingLegacyPrivateMediaConsents.first?.request.id == requestID else {
|
||||
return
|
||||
}
|
||||
let resolved = pendingLegacyPrivateMediaConsents.removeFirst()
|
||||
// Drive the boolean presentation state through false before showing
|
||||
// the next queued per-send warning. Otherwise SwiftUI sees true→true,
|
||||
// closes the first dialog, and never presents the second.
|
||||
legacyPrivateMediaConsentRequest = nil
|
||||
resolved.completion(approved)
|
||||
presentNextLegacyPrivateMediaConsentDeferred()
|
||||
}
|
||||
|
||||
func invalidateLegacyPrivateMediaConsent(transferId: String, messageID: String) {
|
||||
let invalidatedIDs = Set(
|
||||
pendingLegacyPrivateMediaConsents.compactMap { pending -> UUID? in
|
||||
let request = pending.request
|
||||
return request.transferId == transferId && request.messageID == messageID
|
||||
? request.id
|
||||
: nil
|
||||
}
|
||||
)
|
||||
guard !invalidatedIDs.isEmpty else { return }
|
||||
|
||||
pendingLegacyPrivateMediaConsents.removeAll {
|
||||
invalidatedIDs.contains($0.request.id)
|
||||
}
|
||||
if let currentID = legacyPrivateMediaConsentRequest?.id,
|
||||
invalidatedIDs.contains(currentID) {
|
||||
legacyPrivateMediaConsentRequest = nil
|
||||
presentNextLegacyPrivateMediaConsentDeferred()
|
||||
}
|
||||
}
|
||||
|
||||
func cancelAllLegacyPrivateMediaConsents() {
|
||||
let pending = pendingLegacyPrivateMediaConsents
|
||||
pendingLegacyPrivateMediaConsents.removeAll()
|
||||
legacyPrivateMediaConsentRequest = nil
|
||||
for item in pending {
|
||||
item.completion(false)
|
||||
}
|
||||
}
|
||||
|
||||
private func presentNextLegacyPrivateMediaConsentDeferred() {
|
||||
guard legacyPrivateMediaConsentRequest == nil,
|
||||
let nextRequestID = pendingLegacyPrivateMediaConsents.first?.request.id else {
|
||||
return
|
||||
}
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self,
|
||||
self.legacyPrivateMediaConsentRequest == nil,
|
||||
self.pendingLegacyPrivateMediaConsents.first?.request.id == nextRequestID else {
|
||||
return
|
||||
}
|
||||
self.legacyPrivateMediaConsentRequest = self.pendingLegacyPrivateMediaConsents[0].request
|
||||
}
|
||||
}
|
||||
}
|
||||
// End of ChatViewModel class
|
||||
|
||||
@@ -310,7 +310,7 @@ final class NostrInboundPipeline {
|
||||
// claiming to be group traffic over Nostr is ignored.
|
||||
// Live voice is mesh-only: latency and relay cost make it
|
||||
// meaningless over Nostr.
|
||||
case .verifyChallenge, .verifyResponse, .groupInvite, .groupKeyUpdate, .vouch, .voiceFrame:
|
||||
case .verifyChallenge, .verifyResponse, .groupInvite, .groupKeyUpdate, .vouch, .voiceFrame, .privateFile, .authenticatedPeerState:
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -366,7 +366,7 @@ final class NostrInboundPipeline {
|
||||
// claiming to be group traffic over Nostr is ignored.
|
||||
// Live voice is mesh-only: latency and relay cost make it
|
||||
// meaningless over Nostr.
|
||||
case .verifyChallenge, .verifyResponse, .groupInvite, .groupKeyUpdate, .vouch, .voiceFrame:
|
||||
case .verifyChallenge, .verifyResponse, .groupInvite, .groupKeyUpdate, .vouch, .voiceFrame, .privateFile, .authenticatedPeerState:
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -449,7 +449,7 @@ final class NostrInboundPipeline {
|
||||
// in v1; group traffic over Nostr is ignored.
|
||||
// Live voice is mesh-only: latency and relay cost make it
|
||||
// meaningless over Nostr.
|
||||
case .verifyChallenge, .verifyResponse, .groupInvite, .groupKeyUpdate, .vouch, .voiceFrame:
|
||||
case .verifyChallenge, .verifyResponse, .groupInvite, .groupKeyUpdate, .vouch, .voiceFrame, .privateFile, .authenticatedPeerState:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ struct ContentPeopleSheetView: View {
|
||||
#endif
|
||||
|
||||
var body: some View {
|
||||
let legacyConsentRequest = conversationUIModel.legacyPrivateMediaConsentRequest
|
||||
NavigationStack {
|
||||
Group {
|
||||
if privateConversationModel.selectedPeerID != nil {
|
||||
@@ -97,6 +98,63 @@ struct ContentPeopleSheetView: View {
|
||||
}
|
||||
.themedSheetBackground()
|
||||
.foregroundColor(palette.primary)
|
||||
.confirmationDialog(
|
||||
String(
|
||||
localized: "content.private_media.legacy_warning.title",
|
||||
defaultValue: "Send without end-to-end encryption?",
|
||||
comment: "Title warning before sending private media to an older client in a clear signed envelope"
|
||||
),
|
||||
isPresented: Binding(
|
||||
get: { legacyConsentRequest != nil },
|
||||
set: { isPresented in
|
||||
if !isPresented, let requestID = legacyConsentRequest?.id {
|
||||
conversationUIModel.resolveLegacyPrivateMediaConsent(
|
||||
requestID: requestID,
|
||||
approved: false
|
||||
)
|
||||
}
|
||||
}
|
||||
),
|
||||
titleVisibility: .visible
|
||||
) {
|
||||
Button(
|
||||
String(
|
||||
localized: "content.private_media.legacy_warning.send",
|
||||
defaultValue: "send visible file",
|
||||
comment: "Destructive confirmation action for one legacy clear private-media send"
|
||||
),
|
||||
role: .destructive
|
||||
) {
|
||||
if let requestID = legacyConsentRequest?.id {
|
||||
conversationUIModel.resolveLegacyPrivateMediaConsent(
|
||||
requestID: requestID,
|
||||
approved: true
|
||||
)
|
||||
}
|
||||
}
|
||||
Button("common.cancel", role: .cancel) {
|
||||
if let requestID = legacyConsentRequest?.id {
|
||||
conversationUIModel.resolveLegacyPrivateMediaConsent(
|
||||
requestID: requestID,
|
||||
approved: false
|
||||
)
|
||||
}
|
||||
}
|
||||
} message: {
|
||||
if let request = legacyConsentRequest {
|
||||
Text(
|
||||
String(
|
||||
format: String(
|
||||
localized: "content.private_media.legacy_warning.message",
|
||||
defaultValue: "%@'s client does not advertise encrypted private media. This file will be signed but not end-to-end encrypted, so mesh relays can see it. Send this file anyway?",
|
||||
comment: "Warning explaining the confidentiality loss for one legacy private-media send; parameter is the peer name"
|
||||
),
|
||||
locale: .current,
|
||||
request.peerName
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
#if os(macOS)
|
||||
.frame(minWidth: 420, minHeight: 520)
|
||||
#endif
|
||||
|
||||
@@ -502,14 +502,26 @@ struct BLEServiceCoreTests {
|
||||
)
|
||||
let replay = try #require(victim.signPacket(unsigned), "Failed to sign replayed announce")
|
||||
#expect(ble._test_recordIngressIfNew(packet: replay, linkID: attackerLink))
|
||||
let rebindGate = VerifiedDirectRebindGate()
|
||||
ble._test_afterVerifiedDirectRebindEnqueued = rebindGate.pause
|
||||
defer {
|
||||
rebindGate.release()
|
||||
ble._test_afterVerifiedDirectRebindEnqueued = nil
|
||||
}
|
||||
ble._test_handlePacket(replay, fromPeerID: victimPeerID, preseedPeer: false)
|
||||
|
||||
let rebound = await TestHelpers.waitUntil(
|
||||
{ ble._test_centralBinding(attackerLink) == victimPeerID },
|
||||
let announcePaused = await TestHelpers.waitUntil(
|
||||
{ rebindGate.hasPaused },
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(rebound)
|
||||
#expect(ble.canDeliverSecurely(to: victimPeerID))
|
||||
try #require(announcePaused)
|
||||
|
||||
// Rebind and ordinary reconnect preparation are one bleQueue
|
||||
// critical section. Once the binding is visible, stale sending keys
|
||||
// must already be unavailable.
|
||||
#expect(ble._test_centralBinding(attackerLink) == victimPeerID)
|
||||
#expect(!ble.canDeliverSecurely(to: victimPeerID))
|
||||
rebindGate.release()
|
||||
|
||||
let outbound = OutboundPacketTap()
|
||||
ble._test_onOutboundPacket = { outbound.record($0) }
|
||||
@@ -537,20 +549,26 @@ struct BLEServiceCoreTests {
|
||||
|
||||
// Preserve a working victim session while an unauthenticated
|
||||
// replacement candidate arrives on a newly bound physical link.
|
||||
let message1 = try ble._test_noiseInitiateHandshake(with: victimPeerID)
|
||||
// Establish BLE as responder so the replacement candidate below is
|
||||
// not coalesced by the initiator-completion grace path.
|
||||
let message1 = try victim.initiateHandshake(with: ble.myPeerID)
|
||||
let message2 = try #require(
|
||||
try victim.processHandshakeMessage(from: ble.myPeerID, message: message1)
|
||||
)
|
||||
let message3 = try #require(
|
||||
try ble._test_noiseProcessHandshakeMessage(
|
||||
from: victimPeerID,
|
||||
message: message1
|
||||
)
|
||||
)
|
||||
let message3 = try #require(
|
||||
try victim.processHandshakeMessage(
|
||||
from: ble.myPeerID,
|
||||
message: message2
|
||||
)
|
||||
)
|
||||
_ = try victim.processHandshakeMessage(
|
||||
from: ble.myPeerID,
|
||||
_ = try ble._test_noiseProcessHandshakeMessage(
|
||||
from: victimPeerID,
|
||||
message: message3
|
||||
)
|
||||
await ble._test_drainNoiseMessagePipeline()
|
||||
#expect(ble.canDeliverSecurely(to: victimPeerID))
|
||||
|
||||
let centralUUID = "central-replacement-xx-message-one"
|
||||
@@ -614,7 +632,168 @@ struct BLEServiceCoreTests {
|
||||
for: victimPeerID
|
||||
)
|
||||
)
|
||||
#expect(ble.canDeliverSecurely(to: victimPeerID))
|
||||
// Ordinary reconnect hardening quarantines the cached transport while
|
||||
// this candidate proves the claimed identity. It must be unavailable
|
||||
// for sending as well as unable to authenticate this ingress link.
|
||||
#expect(!ble.canDeliverSecurely(to: victimPeerID))
|
||||
}
|
||||
|
||||
@Test
|
||||
func failedInboundReconnectRestoresAndDrainsWaitingWorkOnce() async throws {
|
||||
let ble = makeService()
|
||||
let alice = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let mallory = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let alicePeerID = PeerID(publicKey: alice.getStaticPublicKeyData())
|
||||
|
||||
// Establish BLE as responder so the following inbound reconnect is
|
||||
// not intentionally coalesced by the initiator-completion grace path.
|
||||
let message1 = try alice.initiateHandshake(with: ble.myPeerID)
|
||||
let message2 = try #require(
|
||||
try ble._test_noiseProcessHandshakeMessage(
|
||||
from: alicePeerID,
|
||||
message: message1
|
||||
)
|
||||
)
|
||||
let message3 = try #require(
|
||||
try alice.processHandshakeMessage(
|
||||
from: ble.myPeerID,
|
||||
message: message2
|
||||
)
|
||||
)
|
||||
_ = try ble._test_noiseProcessHandshakeMessage(
|
||||
from: alicePeerID,
|
||||
message: message3
|
||||
)
|
||||
await ble._test_drainNoiseMessagePipeline()
|
||||
#expect(ble.canDeliverSecurely(to: alicePeerID))
|
||||
|
||||
let outbound = OutboundPacketTap()
|
||||
ble._test_onOutboundPacket = outbound.record
|
||||
let forgedMessage1 = try mallory.initiateHandshake(with: ble.myPeerID)
|
||||
let firstPacket = BitchatPacket(
|
||||
type: MessageType.noiseHandshake.rawValue,
|
||||
senderID: Data(hexString: alicePeerID.id) ?? Data(),
|
||||
recipientID: Data(hexString: ble.myPeerID.id),
|
||||
timestamp: UInt64(Date().timeIntervalSince1970 * 1_000),
|
||||
payload: forgedMessage1,
|
||||
signature: nil,
|
||||
ttl: 7
|
||||
)
|
||||
ble._test_handlePacket(firstPacket, fromPeerID: alicePeerID)
|
||||
|
||||
let responseReady = await TestHelpers.waitUntil(
|
||||
{
|
||||
outbound.snapshot().contains {
|
||||
$0.type == MessageType.noiseHandshake.rawValue
|
||||
&& PeerID(hexData: $0.senderID) == ble.myPeerID
|
||||
&& $0.payload.count
|
||||
!= NoiseSecurityConstants.xxInitialMessageSize
|
||||
}
|
||||
},
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
try #require(responseReady)
|
||||
let forgedMessage2 = try #require(
|
||||
outbound.snapshot().first {
|
||||
$0.type == MessageType.noiseHandshake.rawValue
|
||||
&& PeerID(hexData: $0.senderID) == ble.myPeerID
|
||||
&& $0.payload.count
|
||||
!= NoiseSecurityConstants.xxInitialMessageSize
|
||||
}?.payload
|
||||
)
|
||||
#expect(!ble.canDeliverSecurely(to: alicePeerID))
|
||||
|
||||
// Typed control traffic must queue behind the ordinary responder,
|
||||
// rather than attempting encryption and disappearing.
|
||||
let privateMessageID = "quarantine-pm-\(UUID().uuidString)"
|
||||
ble.sendPrivateMessage(
|
||||
"queued private message",
|
||||
to: alicePeerID,
|
||||
recipientNickname: "Alice",
|
||||
messageID: privateMessageID
|
||||
)
|
||||
ble.sendGroupInvite(Data("queued-during-quarantine".utf8), to: alicePeerID)
|
||||
await ble._test_drainNoiseMessagePipeline()
|
||||
#expect(outbound.count(ofType: .noiseEncrypted) == 0)
|
||||
|
||||
let forgedMessage3 = try #require(
|
||||
try mallory.processHandshakeMessage(
|
||||
from: ble.myPeerID,
|
||||
message: forgedMessage2
|
||||
)
|
||||
)
|
||||
let forgedEarlyPayload = try #require(
|
||||
BLENoisePayloadFactory.privateMessage(
|
||||
content: "forged early message",
|
||||
messageID: "forged-early"
|
||||
)
|
||||
)
|
||||
try #require(
|
||||
mallory.hasEstablishedSession(with: ble.myPeerID),
|
||||
"forged initiator did not establish after producing message three"
|
||||
)
|
||||
let forgedEarlyCiphertext = try mallory.encrypt(
|
||||
forgedEarlyPayload,
|
||||
for: ble.myPeerID
|
||||
)
|
||||
let earlyPacket = BitchatPacket(
|
||||
type: MessageType.noiseEncrypted.rawValue,
|
||||
senderID: Data(hexString: alicePeerID.id) ?? Data(),
|
||||
recipientID: Data(hexString: ble.myPeerID.id),
|
||||
timestamp: UInt64(Date().timeIntervalSince1970 * 1_000) + 1,
|
||||
payload: forgedEarlyCiphertext,
|
||||
signature: nil,
|
||||
ttl: 7
|
||||
)
|
||||
ble._test_handlePacket(earlyPacket, fromPeerID: alicePeerID)
|
||||
await ble._test_drainNoiseMessagePipeline()
|
||||
|
||||
let thirdPacket = BitchatPacket(
|
||||
type: MessageType.noiseHandshake.rawValue,
|
||||
senderID: Data(hexString: alicePeerID.id) ?? Data(),
|
||||
recipientID: Data(hexString: ble.myPeerID.id),
|
||||
timestamp: UInt64(Date().timeIntervalSince1970 * 1_000) + 2,
|
||||
payload: forgedMessage3,
|
||||
signature: nil,
|
||||
ttl: 7
|
||||
)
|
||||
ble._test_handlePacket(thirdPacket, fromPeerID: alicePeerID)
|
||||
|
||||
// Rollback restores the same generation. It retries the bounded early
|
||||
// ciphertext and drains both outbound queues, but must not repeat a
|
||||
// new-generation capability proof or forced announce.
|
||||
let drained = await TestHelpers.waitUntil(
|
||||
{ outbound.count(ofType: .noiseEncrypted) >= 2 },
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
try #require(drained)
|
||||
await ble._test_drainNoiseMessagePipeline()
|
||||
let plaintexts = try outbound.snapshot()
|
||||
.filter { $0.type == MessageType.noiseEncrypted.rawValue }
|
||||
.map { try alice.decrypt($0.payload, from: ble.myPeerID) }
|
||||
#expect(plaintexts.count == 2)
|
||||
#expect(
|
||||
plaintexts.filter {
|
||||
$0.first == NoisePayloadType.authenticatedPeerState.rawValue
|
||||
}.isEmpty
|
||||
)
|
||||
#expect(
|
||||
plaintexts.filter {
|
||||
$0.first == NoisePayloadType.privateMessage.rawValue
|
||||
}.count == 1
|
||||
)
|
||||
#expect(
|
||||
plaintexts.filter {
|
||||
$0.first == NoisePayloadType.groupInvite.rawValue
|
||||
}.count == 1
|
||||
)
|
||||
#expect(outbound.count(ofType: .announce) == 0)
|
||||
|
||||
// A duplicate ready callback cannot replay either buffer.
|
||||
ble._test_reconcileCurrentNoiseSession(for: alicePeerID)
|
||||
await ble._test_drainNoiseMessagePipeline()
|
||||
#expect(outbound.count(ofType: .noiseEncrypted) == 2)
|
||||
#expect(outbound.count(ofType: .announce) == 0)
|
||||
}
|
||||
|
||||
/// A legitimate rotation announce necessarily arrives on a link still
|
||||
@@ -943,6 +1122,40 @@ private final class OutboundPacketTap {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
return packets.filter { $0.type == type.rawValue }.count
|
||||
}
|
||||
|
||||
func snapshot() -> [BitchatPacket] {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
return packets
|
||||
}
|
||||
}
|
||||
|
||||
private final class VerifiedDirectRebindGate: @unchecked Sendable {
|
||||
private let condition = NSCondition()
|
||||
private var paused = false
|
||||
private var released = false
|
||||
|
||||
var hasPaused: Bool {
|
||||
condition.lock()
|
||||
defer { condition.unlock() }
|
||||
return paused
|
||||
}
|
||||
|
||||
func pause() {
|
||||
condition.lock()
|
||||
paused = true
|
||||
condition.broadcast()
|
||||
while !released {
|
||||
condition.wait()
|
||||
}
|
||||
condition.unlock()
|
||||
}
|
||||
|
||||
func release() {
|
||||
condition.lock()
|
||||
released = true
|
||||
condition.broadcast()
|
||||
condition.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
private final class ReceivePacketHandoffGate: @unchecked Sendable {
|
||||
@@ -1076,6 +1289,7 @@ private final class PublicCaptureDelegate: BitchatDelegate {
|
||||
defer { lock.unlock() }
|
||||
return publicMessages
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@MainActor
|
||||
|
||||
@@ -14,6 +14,7 @@ import BitFoundation
|
||||
@MainActor
|
||||
private final class MockChatLiveVoiceContext: ChatLiveVoiceContext {
|
||||
var nickname = "me"
|
||||
var myPeerID = PeerID(str: "0102030405060708")
|
||||
var selectedPrivateChatPeer: PeerID?
|
||||
var isViewingPublicMeshTimeline = false
|
||||
var blockedPeers: Set<PeerID> = []
|
||||
@@ -23,7 +24,10 @@ private final class MockChatLiveVoiceContext: ChatLiveVoiceContext {
|
||||
private(set) var upsertedMessages: [(message: BitchatMessage, peerID: PeerID)] = []
|
||||
private(set) var upsertedPublicMessages: [BitchatMessage] = []
|
||||
private(set) var removedMessageIDs: [String] = []
|
||||
private(set) var sentReadReceipts: [(receipt: ReadReceipt, peerID: PeerID)] = []
|
||||
private(set) var talkerUpdates: [String?] = []
|
||||
private(set) var privateMutationLog: [String] = []
|
||||
private var readReceiptMessageIDs: Set<String> = []
|
||||
|
||||
func isPeerBlocked(_ peerID: PeerID) -> Bool { blockedPeers.contains(peerID) }
|
||||
func resolveNickname(for peerID: PeerID) -> String { "alice" }
|
||||
@@ -31,6 +35,7 @@ private final class MockChatLiveVoiceContext: ChatLiveVoiceContext {
|
||||
func appendPublicMeshMessage(_ message: BitchatMessage) { appendedPublicMessages.append(message) }
|
||||
func upsertPrivateMessage(_ message: BitchatMessage, in peerID: PeerID) {
|
||||
upsertedMessages.append((message, peerID))
|
||||
privateMutationLog.append("upsert:\(message.id)")
|
||||
}
|
||||
func upsertPublicMeshMessage(_ message: BitchatMessage) {
|
||||
upsertedPublicMessages.append(message)
|
||||
@@ -38,8 +43,18 @@ private final class MockChatLiveVoiceContext: ChatLiveVoiceContext {
|
||||
@discardableResult
|
||||
func removePrivateMessage(withID messageID: String) -> BitchatMessage? {
|
||||
removedMessageIDs.append(messageID)
|
||||
privateMutationLog.append("remove:\(messageID)")
|
||||
return nil
|
||||
}
|
||||
func hasSentReadReceipt(_ messageID: String) -> Bool {
|
||||
readReceiptMessageIDs.contains(messageID)
|
||||
}
|
||||
func markReadReceiptSent(_ messageID: String) -> Bool {
|
||||
readReceiptMessageIDs.insert(messageID).inserted
|
||||
}
|
||||
func sendMeshReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) {
|
||||
sentReadReceipts.append((receipt, peerID))
|
||||
}
|
||||
func removeMessage(withID messageID: String, cleanupFile: Bool) {
|
||||
removedMessageIDs.append(messageID)
|
||||
}
|
||||
@@ -151,17 +166,29 @@ struct ChatLiveVoiceCoordinatorTests {
|
||||
|
||||
@Test func absorbsFinalizedNoteIntoLiveBubble() throws {
|
||||
let context = MockChatLiveVoiceContext()
|
||||
context.selectedPrivateChatPeer = peer
|
||||
let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false)
|
||||
let burstID = makeBurstID(0xB2)
|
||||
let hex = burstID.hexEncodedString()
|
||||
let fileName = "voice_\(hex).m4a"
|
||||
let stableMessageID = try #require(PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: peer,
|
||||
recipientPeerID: context.myPeerID,
|
||||
fileName: fileName
|
||||
))
|
||||
|
||||
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([Data(repeating: 7, count: 50)]))), to: coordinator, from: peer)
|
||||
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 2, kind: .end(totalDataPackets: 1, durationMs: 64))), to: coordinator, from: peer)
|
||||
let bubble = try #require(context.handledPrivateMessages.first)
|
||||
// The user read the live bubble, then left before the finalized file
|
||||
// arrived. Stable-ID adoption must preserve that read state.
|
||||
#expect(context.markReadReceiptSent(bubble.id))
|
||||
context.selectedPrivateChatPeer = nil
|
||||
|
||||
let note = BitchatMessage(
|
||||
id: stableMessageID,
|
||||
sender: "alice",
|
||||
content: "[voice] voice_\(hex).m4a",
|
||||
content: "[voice] \(fileName)",
|
||||
timestamp: Date(),
|
||||
isRelay: false,
|
||||
isPrivate: true,
|
||||
@@ -170,12 +197,21 @@ struct ChatLiveVoiceCoordinatorTests {
|
||||
)
|
||||
#expect(coordinator.absorbFinalizedVoiceNote(note))
|
||||
|
||||
// The note replaced the live bubble in place: same message ID, new
|
||||
// content, partial capture deleted.
|
||||
// The finalized note adopts the sender-correlatable ID, removes the
|
||||
// receiver-local live ID, and emits a fresh READ now that the sender
|
||||
// has created its finalized media row.
|
||||
let replacement = try #require(context.upsertedMessages.last)
|
||||
#expect(replacement.message.id == bubble.id)
|
||||
#expect(replacement.message.id == stableMessageID)
|
||||
#expect(replacement.message.content == note.content)
|
||||
#expect(replacement.peerID == peer)
|
||||
#expect(context.removedMessageIDs.contains(bubble.id))
|
||||
#expect(Array(context.privateMutationLog.suffix(2)) == [
|
||||
"upsert:\(stableMessageID)",
|
||||
"remove:\(bubble.id)"
|
||||
])
|
||||
#expect(context.sentReadReceipts.count == 1)
|
||||
#expect(context.sentReadReceipts.first?.receipt.originalMessageID == stableMessageID)
|
||||
#expect(context.sentReadReceipts.first?.peerID == peer)
|
||||
// The promoted partial capture is deleted in favor of the note.
|
||||
let url = try #require(fallbackFileURL(burstID: burstID, peerID: peer))
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
@@ -449,7 +485,8 @@ struct ChatLiveVoiceCoordinatorTests {
|
||||
isRelay: false, isPrivate: true, recipientNickname: "me", senderPeerID: peer
|
||||
)
|
||||
#expect(coordinator.absorbFinalizedVoiceNote(dmNote))
|
||||
#expect(try #require(context.upsertedMessages.last).message.id == dmBubble.id)
|
||||
#expect(try #require(context.upsertedMessages.last).message.id == dmNote.id)
|
||||
#expect(context.removedMessageIDs.contains(dmBubble.id))
|
||||
}
|
||||
|
||||
@Test func finalizedNoteBindsToItsAuthenticatedSender() throws {
|
||||
@@ -479,8 +516,9 @@ struct ChatLiveVoiceCoordinatorTests {
|
||||
)
|
||||
#expect(coordinator.absorbFinalizedVoiceNote(note))
|
||||
let replacement = try #require(context.upsertedMessages.last)
|
||||
#expect(replacement.message.id == victimBubble.id)
|
||||
#expect(replacement.message.id == note.id)
|
||||
#expect(replacement.peerID == peer)
|
||||
#expect(context.removedMessageIDs.contains(victimBubble.id))
|
||||
|
||||
// The attacker's note can only ever claim the attacker's own bubble.
|
||||
let attackerNote = BitchatMessage(
|
||||
@@ -489,8 +527,9 @@ struct ChatLiveVoiceCoordinatorTests {
|
||||
)
|
||||
#expect(coordinator.absorbFinalizedVoiceNote(attackerNote))
|
||||
let attackerReplacement = try #require(context.upsertedMessages.last)
|
||||
#expect(attackerReplacement.message.id == attackerBubble.id)
|
||||
#expect(attackerReplacement.message.id == attackerNote.id)
|
||||
#expect(attackerReplacement.peerID == attacker)
|
||||
#expect(context.removedMessageIDs.contains(attackerBubble.id))
|
||||
|
||||
// Both registry entries are consumed — nothing left to hijack.
|
||||
#expect(!coordinator.absorbFinalizedVoiceNote(note))
|
||||
|
||||
@@ -7,10 +7,9 @@
|
||||
// `ChatViewModel`, following the `ChatDeliveryCoordinatorContextTests` /
|
||||
// `ChatPrivateConversationCoordinatorContextTests` exemplars.
|
||||
//
|
||||
// Scope note: the async media-preparation pipelines (`ImageUtils`,
|
||||
// `ChatMediaPreparation`) run real file/codec work and remain covered by
|
||||
// `ChatMediaPreparationTests`; here we cover message enqueueing, transfer
|
||||
// bookkeeping, and the blocked-context guards.
|
||||
// Real file/codec work remains covered by `ChatMediaPreparationTests`. These
|
||||
// tests inject paused media preparers to exercise cancellation ownership
|
||||
// across the detached-preparation/MainActor boundary deterministically.
|
||||
//
|
||||
|
||||
import Testing
|
||||
@@ -90,12 +89,77 @@ private final class MockChatMediaTransferContext: ChatMediaTransferContext {
|
||||
}
|
||||
|
||||
// Mesh file transfer
|
||||
private(set) var privateFileSends: [(peerID: PeerID, transferId: String)] = []
|
||||
private(set) var privateFileSends: [(
|
||||
packet: BitchatFilePacket,
|
||||
peerID: PeerID,
|
||||
transferId: String
|
||||
)] = []
|
||||
private(set) var privateFileLegacyAllowances: [Bool] = []
|
||||
private(set) var broadcastFileSends: [String] = []
|
||||
private(set) var cancelledTransfers: [String] = []
|
||||
var privateMediaPolicy: PrivateMediaSendPolicy = .encrypted
|
||||
var resolvedPrivateMediaPolicy: PrivateMediaSendPolicy?
|
||||
private(set) var legacyConsentRequests: [(
|
||||
id: UUID,
|
||||
peerID: PeerID,
|
||||
transferId: String,
|
||||
messageID: String
|
||||
)] = []
|
||||
private(set) var invalidatedLegacyConsents: [(transferId: String, messageID: String)] = []
|
||||
private var pendingLegacyConsentIDs: [UUID] = []
|
||||
private var legacyConsentCompletions: [UUID: @MainActor (Bool) -> Void] = [:]
|
||||
|
||||
func sendFilePrivate(_ packet: BitchatFilePacket, to peerID: PeerID, transferId: String) {
|
||||
privateFileSends.append((peerID, transferId))
|
||||
func privateMediaSendPolicy(to peerID: PeerID) -> PrivateMediaSendPolicy {
|
||||
privateMediaPolicy
|
||||
}
|
||||
|
||||
func resolvePrivateMediaSendPolicy(
|
||||
to peerID: PeerID,
|
||||
completion: @escaping @MainActor (PrivateMediaSendPolicy) -> Void
|
||||
) {
|
||||
completion(resolvedPrivateMediaPolicy ?? privateMediaPolicy)
|
||||
}
|
||||
|
||||
func requestLegacyPrivateMediaConsent(
|
||||
for peerID: PeerID,
|
||||
transferId: String,
|
||||
messageID: String,
|
||||
completion: @escaping @MainActor (Bool) -> Void
|
||||
) {
|
||||
let id = UUID()
|
||||
legacyConsentRequests.append((id, peerID, transferId, messageID))
|
||||
pendingLegacyConsentIDs.append(id)
|
||||
legacyConsentCompletions[id] = completion
|
||||
}
|
||||
|
||||
func cancelLegacyPrivateMediaConsent(transferId: String, messageID: String) {
|
||||
invalidatedLegacyConsents.append((transferId, messageID))
|
||||
let matchingIDs = Set(legacyConsentRequests.compactMap { request in
|
||||
request.transferId == transferId && request.messageID == messageID
|
||||
? request.id
|
||||
: nil
|
||||
})
|
||||
pendingLegacyConsentIDs.removeAll { matchingIDs.contains($0) }
|
||||
}
|
||||
|
||||
func resolveNextLegacyConsent(_ approved: Bool) {
|
||||
guard !pendingLegacyConsentIDs.isEmpty else { return }
|
||||
let id = pendingLegacyConsentIDs.removeFirst()
|
||||
legacyConsentCompletions[id]?(approved)
|
||||
}
|
||||
|
||||
func invokeLegacyConsentEvenIfInvalidated(id: UUID, approved: Bool) {
|
||||
legacyConsentCompletions[id]?(approved)
|
||||
}
|
||||
|
||||
func sendFilePrivate(
|
||||
_ packet: BitchatFilePacket,
|
||||
to peerID: PeerID,
|
||||
transferId: String,
|
||||
allowLegacyFallback: Bool
|
||||
) {
|
||||
privateFileSends.append((packet, peerID, transferId))
|
||||
privateFileLegacyAllowances.append(allowLegacyFallback)
|
||||
}
|
||||
|
||||
func sendFileBroadcast(_ packet: BitchatFilePacket, transferId: String) {
|
||||
@@ -107,6 +171,51 @@ private final class MockChatMediaTransferContext: ChatMediaTransferContext {
|
||||
}
|
||||
}
|
||||
|
||||
private final class PausedVoiceNotePreparer: @unchecked Sendable {
|
||||
private let condition = NSCondition()
|
||||
private var started = false
|
||||
private var released = false
|
||||
private var finished = false
|
||||
|
||||
func prepare(_ url: URL) throws -> BitchatFilePacket {
|
||||
condition.lock()
|
||||
started = true
|
||||
condition.broadcast()
|
||||
while !released {
|
||||
condition.wait()
|
||||
}
|
||||
finished = true
|
||||
condition.broadcast()
|
||||
condition.unlock()
|
||||
let content = Data("voice".utf8)
|
||||
return BitchatFilePacket(
|
||||
fileName: url.lastPathComponent,
|
||||
fileSize: UInt64(content.count),
|
||||
mimeType: "audio/mp4",
|
||||
content: content
|
||||
)
|
||||
}
|
||||
|
||||
var hasStarted: Bool {
|
||||
condition.lock()
|
||||
defer { condition.unlock() }
|
||||
return started
|
||||
}
|
||||
|
||||
var hasFinished: Bool {
|
||||
condition.lock()
|
||||
defer { condition.unlock() }
|
||||
return finished
|
||||
}
|
||||
|
||||
func release() {
|
||||
condition.lock()
|
||||
released = true
|
||||
condition.broadcast()
|
||||
condition.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Coordinator Tests Against Mock Context
|
||||
|
||||
/// Exercises `ChatMediaTransferCoordinator` against
|
||||
@@ -171,6 +280,14 @@ struct ChatMediaTransferCoordinatorContextTests {
|
||||
#expect(context.removedMessages.count == 1)
|
||||
#expect(context.removedMessages.first?.messageID == "m2")
|
||||
#expect(context.removedMessages.first?.cleanupFile == true)
|
||||
|
||||
// A pre-start rejection keeps the placeholder visible and failed,
|
||||
// including queued post-handshake encryption failures.
|
||||
coordinator.registerTransfer(transferId: "t3", messageID: "m3")
|
||||
coordinator.handleTransferEvent(.rejected(id: "t3", reason: "encryption failed"))
|
||||
#expect(context.deliveryStatusUpdates.last?.messageID == "m3")
|
||||
#expect(context.deliveryStatusUpdates.last?.status == .failed(reason: "encryption failed"))
|
||||
#expect(coordinator.messageIDToTransferId["m3"] == nil)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
@@ -301,6 +418,20 @@ struct ChatMediaTransferCoordinatorContextTests {
|
||||
))
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func deleteMediaMessage_cancelsApprovedTransferBeforeRemovingMapping() {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let coordinator = ChatMediaTransferCoordinator(context: context)
|
||||
coordinator.registerTransfer(transferId: "approved-delete", messageID: "message-delete")
|
||||
|
||||
coordinator.deleteMediaMessage(messageID: "message-delete")
|
||||
|
||||
#expect(context.cancelledTransfers == ["approved-delete"])
|
||||
#expect(coordinator.messageIDToTransferId["message-delete"] == nil)
|
||||
#expect(context.removedMessages.map(\.messageID) == ["message-delete"])
|
||||
#expect(context.removedMessages.first?.cleanupFile == true)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func sendVoiceNote_blockedContextRemovesFileAndExplains() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
@@ -319,6 +450,354 @@ struct ChatMediaTransferCoordinatorContextTests {
|
||||
#expect(context.appendedPublicMessages.isEmpty)
|
||||
#expect(coordinator.transferIdToMessageIDs.isEmpty)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func privateVoiceNoteUsesWireDerivableMessageID() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let coordinator = ChatMediaTransferCoordinator(context: context)
|
||||
let peerID = PeerID(str: "1122334455667788")
|
||||
context.selectedPrivateChatPeer = peerID
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("voice_receipt_\(UUID().uuidString).m4a")
|
||||
try Data("voice".utf8).write(to: url)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
coordinator.sendVoiceNote(at: url)
|
||||
|
||||
#expect(await TestHelpers.waitUntil(
|
||||
{ context.privateFileSends.count == 1 },
|
||||
timeout: TestConstants.longTimeout
|
||||
))
|
||||
let message = try #require(context.privateChats[peerID]?.first)
|
||||
let sentPacket = try #require(context.privateFileSends.first?.packet)
|
||||
#expect(message.id == PrivateMediaMessageIdentity.stableID(
|
||||
for: sentPacket,
|
||||
senderPeerID: context.myPeerID,
|
||||
recipientPeerID: peerID
|
||||
))
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func privateImageUsesWireDerivableMessageID() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let coordinator = ChatMediaTransferCoordinator(context: context)
|
||||
let peerID = PeerID(str: "99aabbccddeeff00")
|
||||
context.selectedPrivateChatPeer = peerID
|
||||
let sourceURL = try makeCoordinatorTestImageURL()
|
||||
defer { try? FileManager.default.removeItem(at: sourceURL) }
|
||||
|
||||
coordinator.sendImage(from: sourceURL)
|
||||
|
||||
#expect(await TestHelpers.waitUntil(
|
||||
{ context.privateFileSends.count == 1 },
|
||||
timeout: TestConstants.longTimeout
|
||||
))
|
||||
let message = try #require(context.privateChats[peerID]?.first)
|
||||
let sentPacket = try #require(context.privateFileSends.first?.packet)
|
||||
#expect(message.id == PrivateMediaMessageIdentity.stableID(
|
||||
for: sentPacket,
|
||||
senderPeerID: context.myPeerID,
|
||||
recipientPeerID: peerID
|
||||
))
|
||||
coordinator.cleanupLocalFile(forMessage: message)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func panicDuringImagePreparationDeletesStaleOutputWithoutSideEffects() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let peerID = PeerID(str: "99aabbccddeeff00")
|
||||
context.selectedPrivateChatPeer = peerID
|
||||
let sourceURL = try makeCoordinatorTestImageURL()
|
||||
let outputURL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(
|
||||
"panic-stale-image-\(UUID().uuidString).jpg"
|
||||
)
|
||||
let preparer = PausedImagePreparer(outputURL: outputURL)
|
||||
let coordinator = ChatMediaTransferCoordinator(
|
||||
context: context,
|
||||
prepareImagePacket: { url in try preparer.prepare(url) }
|
||||
)
|
||||
defer {
|
||||
preparer.release()
|
||||
try? FileManager.default.removeItem(at: sourceURL)
|
||||
try? FileManager.default.removeItem(at: outputURL)
|
||||
}
|
||||
|
||||
coordinator.sendImage(from: sourceURL)
|
||||
#expect(await TestHelpers.waitUntil(
|
||||
{ preparer.hasStarted },
|
||||
timeout: TestConstants.longTimeout
|
||||
))
|
||||
|
||||
DispatchQueue.global(qos: .userInitiated).asyncAfter(
|
||||
deadline: .now() + .milliseconds(100)
|
||||
) {
|
||||
preparer.release()
|
||||
}
|
||||
coordinator.resetForPanic()
|
||||
|
||||
#expect(await TestHelpers.waitUntil(
|
||||
{ preparer.hasFinished },
|
||||
timeout: TestConstants.longTimeout
|
||||
))
|
||||
#expect(await TestHelpers.waitUntil(
|
||||
{ !FileManager.default.fileExists(atPath: outputURL.path) },
|
||||
timeout: TestConstants.longTimeout
|
||||
))
|
||||
#expect(context.privateChats[peerID]?.isEmpty != false)
|
||||
#expect(context.appendedPublicMessages.isEmpty)
|
||||
#expect(context.privateFileSends.isEmpty)
|
||||
#expect(context.broadcastFileSends.isEmpty)
|
||||
#expect(context.systemMessages.isEmpty)
|
||||
#expect(context.deliveryStatusUpdates.isEmpty)
|
||||
#expect(coordinator.transferIdToMessageIDs.isEmpty)
|
||||
#expect(coordinator.messageIDToTransferId.isEmpty)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func cancelVoiceNoteDuringDetachedPreparationCannotSendOrRestoreMapping() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let peerID = PeerID(str: "5566778899aabbcc")
|
||||
context.selectedPrivateChatPeer = peerID
|
||||
let preparer = PausedVoiceNotePreparer()
|
||||
let coordinator = ChatMediaTransferCoordinator(
|
||||
context: context,
|
||||
prepareVoiceNotePacket: { url in try preparer.prepare(url) }
|
||||
)
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("paused-private-\(UUID().uuidString).m4a")
|
||||
try Data("voice".utf8).write(to: url)
|
||||
defer {
|
||||
preparer.release()
|
||||
try? FileManager.default.removeItem(at: url)
|
||||
}
|
||||
|
||||
coordinator.sendVoiceNote(at: url)
|
||||
#expect(await TestHelpers.waitUntil({ preparer.hasStarted }, timeout: TestConstants.longTimeout))
|
||||
let messageID = try #require(context.privateChats[peerID]?.first?.id)
|
||||
let transferId = try #require(coordinator.messageIDToTransferId[messageID])
|
||||
|
||||
coordinator.cancelMediaSend(messageID: messageID)
|
||||
preparer.release()
|
||||
#expect(await TestHelpers.waitUntil({ preparer.hasFinished }, timeout: TestConstants.longTimeout))
|
||||
for _ in 0..<10 { await Task.yield() }
|
||||
|
||||
#expect(context.cancelledTransfers == [transferId])
|
||||
#expect(context.privateFileSends.isEmpty)
|
||||
#expect(context.broadcastFileSends.isEmpty)
|
||||
#expect(coordinator.messageIDToTransferId[messageID] == nil)
|
||||
#expect(coordinator.transferIdToMessageIDs[transferId] == nil)
|
||||
#expect(context.removedMessages.map(\.messageID) == [messageID])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func deletePublicVoiceNoteDuringDetachedPreparationCannotBroadcastOrRestoreMapping() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let preparer = PausedVoiceNotePreparer()
|
||||
let coordinator = ChatMediaTransferCoordinator(
|
||||
context: context,
|
||||
prepareVoiceNotePacket: { url in try preparer.prepare(url) }
|
||||
)
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("paused-public-\(UUID().uuidString).m4a")
|
||||
try Data("voice".utf8).write(to: url)
|
||||
defer {
|
||||
preparer.release()
|
||||
try? FileManager.default.removeItem(at: url)
|
||||
}
|
||||
|
||||
coordinator.sendVoiceNote(at: url)
|
||||
#expect(await TestHelpers.waitUntil({ preparer.hasStarted }, timeout: TestConstants.longTimeout))
|
||||
let messageID = try #require(context.appendedPublicMessages.first?.message.id)
|
||||
let transferId = try #require(coordinator.messageIDToTransferId[messageID])
|
||||
|
||||
coordinator.deleteMediaMessage(messageID: messageID)
|
||||
preparer.release()
|
||||
#expect(await TestHelpers.waitUntil({ preparer.hasFinished }, timeout: TestConstants.longTimeout))
|
||||
for _ in 0..<10 { await Task.yield() }
|
||||
|
||||
#expect(context.cancelledTransfers == [transferId])
|
||||
#expect(context.broadcastFileSends.isEmpty)
|
||||
#expect(context.privateFileSends.isEmpty)
|
||||
#expect(coordinator.messageIDToTransferId[messageID] == nil)
|
||||
#expect(coordinator.transferIdToMessageIDs[transferId] == nil)
|
||||
#expect(context.removedMessages.map(\.messageID) == [messageID])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func voicePreparationFailureMarksPlaceholderFailedAndClearsEarlyMapping() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let peerID = PeerID(str: "66778899aabbccdd")
|
||||
context.selectedPrivateChatPeer = peerID
|
||||
let coordinator = ChatMediaTransferCoordinator(
|
||||
context: context,
|
||||
prepareVoiceNotePacket: { _ in
|
||||
throw ChatMediaPreparationError.voiceNoteTooLarge(bytes: 999_999)
|
||||
}
|
||||
)
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("failing-private-\(UUID().uuidString).m4a")
|
||||
try Data("voice".utf8).write(to: url)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
coordinator.sendVoiceNote(at: url)
|
||||
#expect(await TestHelpers.waitUntil(
|
||||
{
|
||||
context.deliveryStatusUpdates.contains { update in
|
||||
if case .failed = update.status { return true }
|
||||
return false
|
||||
}
|
||||
},
|
||||
timeout: TestConstants.longTimeout
|
||||
))
|
||||
let messageID = try #require(context.privateChats[peerID]?.first?.id)
|
||||
|
||||
#expect(coordinator.messageIDToTransferId[messageID] == nil)
|
||||
#expect(coordinator.transferIdToMessageIDs.isEmpty)
|
||||
#expect(context.privateFileSends.isEmpty)
|
||||
#expect(context.broadcastFileSends.isEmpty)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func legacyPrivateVoiceNoteWaitsForPerSendConsent() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let coordinator = ChatMediaTransferCoordinator(context: context)
|
||||
let peerID = PeerID(str: "1122334455667788")
|
||||
context.selectedPrivateChatPeer = peerID
|
||||
context.privateMediaPolicy = .legacyRequiresConsent
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("legacy-consent-\(UUID().uuidString).m4a")
|
||||
try (Data([0x00, 0x00, 0x00, 0x18]) + Data("ftypM4A voice".utf8)).write(to: url)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
coordinator.sendVoiceNote(at: url)
|
||||
|
||||
let prompted = await TestHelpers.waitUntil(
|
||||
{ context.legacyConsentRequests.count == 1 },
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(prompted)
|
||||
#expect(context.legacyConsentRequests.map { $0.peerID } == [peerID])
|
||||
#expect(context.privateFileSends.isEmpty)
|
||||
|
||||
context.resolveNextLegacyConsent(true)
|
||||
|
||||
#expect(context.privateFileSends.count == 1)
|
||||
#expect(context.privateFileLegacyAllowances == [true])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func capabilityProofTimeoutTransitionsToConsentWithoutAutomaticRawSend() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let coordinator = ChatMediaTransferCoordinator(context: context)
|
||||
let peerID = PeerID(str: "1020304050607080")
|
||||
context.selectedPrivateChatPeer = peerID
|
||||
context.privateMediaPolicy = .awaitingCapabilityProof
|
||||
context.resolvedPrivateMediaPolicy = .legacyRequiresConsent
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("proof-timeout-consent-\(UUID().uuidString).m4a")
|
||||
try Data("voice".utf8).write(to: url)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
coordinator.sendVoiceNote(at: url)
|
||||
|
||||
let prompted = await TestHelpers.waitUntil(
|
||||
{ context.legacyConsentRequests.count == 1 },
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(prompted)
|
||||
#expect(context.privateFileSends.isEmpty)
|
||||
context.resolveNextLegacyConsent(false)
|
||||
#expect(context.privateFileSends.isEmpty)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func legacyConsentApprovalAfterCancelCannotSend() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let coordinator = ChatMediaTransferCoordinator(context: context)
|
||||
let peerID = PeerID(str: "2233445566778899")
|
||||
context.selectedPrivateChatPeer = peerID
|
||||
context.privateMediaPolicy = .legacyRequiresConsent
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("legacy-cancel-\(UUID().uuidString).m4a")
|
||||
try Data("voice".utf8).write(to: url)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
coordinator.sendVoiceNote(at: url)
|
||||
let prompted = await TestHelpers.waitUntil(
|
||||
{ context.legacyConsentRequests.count == 1 },
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(prompted)
|
||||
let request = try #require(context.legacyConsentRequests.first)
|
||||
|
||||
coordinator.cancelMediaSend(messageID: request.messageID)
|
||||
#expect(context.invalidatedLegacyConsents.contains {
|
||||
$0.transferId == request.transferId && $0.messageID == request.messageID
|
||||
})
|
||||
|
||||
// Model a stale framework callback that escaped active invalidation.
|
||||
// The coordinator's transfer/message binding check is the final gate.
|
||||
context.invokeLegacyConsentEvenIfInvalidated(id: request.id, approved: true)
|
||||
#expect(context.privateFileSends.isEmpty)
|
||||
#expect(coordinator.messageIDToTransferId[request.messageID] == nil)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func legacyConsentApprovalAfterDeleteCannotSend() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let coordinator = ChatMediaTransferCoordinator(context: context)
|
||||
let peerID = PeerID(str: "33445566778899aa")
|
||||
context.selectedPrivateChatPeer = peerID
|
||||
context.privateMediaPolicy = .legacyRequiresConsent
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("legacy-delete-\(UUID().uuidString).m4a")
|
||||
try Data("voice".utf8).write(to: url)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
coordinator.sendVoiceNote(at: url)
|
||||
let prompted = await TestHelpers.waitUntil(
|
||||
{ context.legacyConsentRequests.count == 1 },
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(prompted)
|
||||
let request = try #require(context.legacyConsentRequests.first)
|
||||
|
||||
coordinator.deleteMediaMessage(messageID: request.messageID)
|
||||
context.invokeLegacyConsentEvenIfInvalidated(id: request.id, approved: true)
|
||||
|
||||
#expect(context.invalidatedLegacyConsents.contains {
|
||||
$0.transferId == request.transferId && $0.messageID == request.messageID
|
||||
})
|
||||
#expect(context.privateFileSends.isEmpty)
|
||||
#expect(coordinator.messageIDToTransferId[request.messageID] == nil)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func pinnedPrivateMediaDowngradeNeverPromptsOrSends() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let coordinator = ChatMediaTransferCoordinator(context: context)
|
||||
let peerID = PeerID(str: "1122334455667788")
|
||||
context.selectedPrivateChatPeer = peerID
|
||||
context.privateMediaPolicy = .blockedDowngrade
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("blocked-downgrade-\(UUID().uuidString).m4a")
|
||||
try Data("voice".utf8).write(to: url)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
coordinator.sendVoiceNote(at: url)
|
||||
|
||||
let failed = await TestHelpers.waitUntil(
|
||||
{ context.deliveryStatusUpdates.contains { update in
|
||||
if case .failed = update.status { return true }
|
||||
return false
|
||||
} },
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(failed)
|
||||
#expect(context.legacyConsentRequests.isEmpty)
|
||||
#expect(context.privateFileSends.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
private final class PausedImagePreparer: @unchecked Sendable {
|
||||
|
||||
@@ -104,6 +104,20 @@ private func makeMessage(id: String, senderPeerID: PeerID? = nil) -> BitchatMess
|
||||
/// no `ChatViewModel`.
|
||||
struct ChatPeerListCoordinatorContextTests {
|
||||
|
||||
@Test @MainActor
|
||||
func synchronousPeerListUpdate_appliesBeforeReturning() {
|
||||
let context = MockChatPeerListContext()
|
||||
let coordinator = ChatPeerListCoordinator(context: context)
|
||||
let peerID = PeerID(str: "0011223344556677")
|
||||
|
||||
coordinator.didUpdatePeerListSynchronously([peerID])
|
||||
|
||||
#expect(context.isConnected)
|
||||
#expect(context.registeredEphemeralSessions == [peerID])
|
||||
#expect(context.updateEncryptionStatusForPeersCount == 1)
|
||||
#expect(context.cleanupOldReadReceiptsCount == 1)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func didUpdatePeerList_updatesConnectionSessionsAndEncryptionStatus() async {
|
||||
let context = MockChatPeerListContext()
|
||||
|
||||
@@ -220,26 +220,85 @@ struct ChatTransportEventCoordinatorContextTests {
|
||||
func didReceiveMessage_routesPrivateAndPublic_skipsBlockedAndEmpty() async {
|
||||
let context = MockChatTransportEventContext()
|
||||
let coordinator = ChatTransportEventCoordinator(context: context)
|
||||
let peerID = PeerID(str: "1122334455667788")
|
||||
|
||||
// Blocked messages are dropped before any handling.
|
||||
context.blockedMessageIDs = ["blocked"]
|
||||
context.blockedMessageIDs = ["blocked", "blocked-private"]
|
||||
coordinator.didReceiveMessage(makeMessage(id: "blocked"))
|
||||
coordinator.didReceiveMessage(makeMessage(
|
||||
id: "blocked-private",
|
||||
isPrivate: true,
|
||||
senderPeerID: peerID
|
||||
))
|
||||
// Empty public content is dropped too.
|
||||
coordinator.didReceiveMessage(makeMessage(id: "empty", content: " "))
|
||||
await drainMainActorTasks()
|
||||
#expect(context.handledPublicMessages.isEmpty)
|
||||
#expect(context.handledPrivateMessages.isEmpty)
|
||||
#expect(context.mentionCheckedMessageIDs.isEmpty)
|
||||
#expect(context.meshDeliveryAcks.isEmpty)
|
||||
|
||||
// Private goes to the private handler, public to the public handler;
|
||||
// both get mention checks and haptics.
|
||||
coordinator.didReceiveMessage(makeMessage(id: "pm", isPrivate: true))
|
||||
// both get mention checks and haptics. Stable-media ACK authorization
|
||||
// belongs to BLEFileTransferHandler after its durable commit and this
|
||||
// synchronous acceptance result, not to the generic UI coordinator.
|
||||
let stableMediaID = "media-\(String(repeating: "a", count: 32))"
|
||||
coordinator.didReceiveMessage(makeMessage(
|
||||
id: stableMediaID,
|
||||
isPrivate: true,
|
||||
senderPeerID: peerID
|
||||
))
|
||||
coordinator.didReceiveMessage(makeMessage(
|
||||
id: "legacy-media",
|
||||
isPrivate: true,
|
||||
senderPeerID: peerID
|
||||
))
|
||||
coordinator.didReceiveMessage(makeMessage(id: "pm-missing-sender", isPrivate: true))
|
||||
coordinator.didReceiveMessage(makeMessage(id: "pub"))
|
||||
await drainMainActorTasks()
|
||||
#expect(context.handledPrivateMessages.map(\.id) == ["pm"])
|
||||
#expect(context.handledPrivateMessages.map(\.id) == [
|
||||
stableMediaID,
|
||||
"legacy-media",
|
||||
"pm-missing-sender"
|
||||
])
|
||||
#expect(context.handledPublicMessages.map(\.id) == ["pub"])
|
||||
#expect(context.mentionCheckedMessageIDs == ["pm", "pub"])
|
||||
#expect(context.hapticMessageIDs == ["pm", "pub"])
|
||||
#expect(context.mentionCheckedMessageIDs == [
|
||||
stableMediaID,
|
||||
"legacy-media",
|
||||
"pm-missing-sender",
|
||||
"pub"
|
||||
])
|
||||
#expect(context.hapticMessageIDs == [
|
||||
stableMediaID,
|
||||
"legacy-media",
|
||||
"pm-missing-sender",
|
||||
"pub"
|
||||
])
|
||||
#expect(context.meshDeliveryAcks.isEmpty)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func synchronousMessageDeliveryReportsAcceptanceForAckGating() {
|
||||
let context = MockChatTransportEventContext()
|
||||
let coordinator = ChatTransportEventCoordinator(context: context)
|
||||
let peerID = PeerID(str: "1122334455667788")
|
||||
let blocked = makeMessage(
|
||||
id: "blocked-private-media",
|
||||
isPrivate: true,
|
||||
senderPeerID: peerID
|
||||
)
|
||||
context.blockedMessageIDs = [blocked.id]
|
||||
|
||||
#expect(coordinator.didReceiveMessageSynchronously(blocked) == false)
|
||||
#expect(context.handledPrivateMessages.isEmpty)
|
||||
|
||||
let accepted = makeMessage(
|
||||
id: "accepted-private-media",
|
||||
isPrivate: true,
|
||||
senderPeerID: peerID
|
||||
)
|
||||
#expect(coordinator.didReceiveMessageSynchronously(accepted) == true)
|
||||
#expect(context.handledPrivateMessages.map(\.id) == [accepted.id])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
@@ -295,6 +354,32 @@ struct ChatTransportEventCoordinatorContextTests {
|
||||
#expect(context.notifyUIChangedCount == 2)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func synchronousConnectAndDisconnect_applyBeforeReturning() {
|
||||
let context = MockChatTransportEventContext()
|
||||
let coordinator = ChatTransportEventCoordinator(context: context)
|
||||
let peerID = PeerID(str: "2233445566778899")
|
||||
let incoming = makeMessage(
|
||||
id: "incoming-receipt",
|
||||
isPrivate: true,
|
||||
senderPeerID: peerID
|
||||
)
|
||||
context.privateChats[peerID] = [incoming]
|
||||
|
||||
coordinator.didConnectToPeerSynchronously(peerID)
|
||||
|
||||
#expect(context.isConnected)
|
||||
#expect(context.registeredEphemeralSessions == [peerID])
|
||||
#expect(context.flushedOutboxPeerIDs == [peerID])
|
||||
#expect(context.courierRetryPeerIDs == [peerID])
|
||||
|
||||
coordinator.didDisconnectFromPeerSynchronously(peerID)
|
||||
|
||||
#expect(context.removedEphemeralSessions == [peerID])
|
||||
#expect(context.unmarkedReadReceiptBatches == [[incoming.id]])
|
||||
#expect(context.notifyUIChangedCount == 2)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func didDisconnect_whileViewingChat_migratesConversationToStablePeerID() async {
|
||||
let context = MockChatTransportEventContext()
|
||||
|
||||
@@ -1048,6 +1048,89 @@ struct ChatViewModelMediaTransferTests {
|
||||
#expect(viewModel.transferIdToMessageIDs.count == 1)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func legacyPrivateMediaConsentRequestsArePerSendAndQueued() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let firstPeer = PeerID(str: "1111111111111111")
|
||||
let secondPeer = PeerID(str: "2222222222222222")
|
||||
var decisions: [Bool] = []
|
||||
|
||||
viewModel.enqueueLegacyPrivateMediaConsent(
|
||||
for: firstPeer,
|
||||
transferId: "transfer-1",
|
||||
messageID: "message-1"
|
||||
) { decisions.append($0) }
|
||||
viewModel.enqueueLegacyPrivateMediaConsent(
|
||||
for: secondPeer,
|
||||
transferId: "transfer-2",
|
||||
messageID: "message-2"
|
||||
) { decisions.append($0) }
|
||||
|
||||
#expect(viewModel.legacyPrivateMediaConsentRequest?.peerID == firstPeer)
|
||||
let firstRequestID = try #require(viewModel.legacyPrivateMediaConsentRequest?.id)
|
||||
viewModel.resolveLegacyPrivateMediaConsent(requestID: firstRequestID, approved: true)
|
||||
let showedSecond = await TestHelpers.waitUntil(
|
||||
{ viewModel.legacyPrivateMediaConsentRequest?.peerID == secondPeer },
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(showedSecond)
|
||||
let secondRequestID = try #require(viewModel.legacyPrivateMediaConsentRequest?.id)
|
||||
|
||||
// A button action and the dialog binding may both resolve the first
|
||||
// ID. The stale second callback must not consume the queued request.
|
||||
viewModel.resolveLegacyPrivateMediaConsent(requestID: firstRequestID, approved: false)
|
||||
#expect(decisions == [true])
|
||||
#expect(viewModel.legacyPrivateMediaConsentRequest?.id == secondRequestID)
|
||||
|
||||
viewModel.resolveLegacyPrivateMediaConsent(requestID: secondRequestID, approved: false)
|
||||
|
||||
#expect(decisions == [true, false])
|
||||
#expect(viewModel.legacyPrivateMediaConsentRequest == nil)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func invalidatingPresentedLegacyConsentAdvancesQueueAndStaleResolutionNoops() async throws {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let firstPeer = PeerID(str: "3333333333333333")
|
||||
let secondPeer = PeerID(str: "4444444444444444")
|
||||
var decisions: [String] = []
|
||||
|
||||
viewModel.enqueueLegacyPrivateMediaConsent(
|
||||
for: firstPeer,
|
||||
transferId: "transfer-cancelled",
|
||||
messageID: "message-cancelled"
|
||||
) { decisions.append("first:\($0)") }
|
||||
viewModel.enqueueLegacyPrivateMediaConsent(
|
||||
for: secondPeer,
|
||||
transferId: "transfer-kept",
|
||||
messageID: "message-kept"
|
||||
) { decisions.append("second:\($0)") }
|
||||
|
||||
let cancelledRequestID = try #require(viewModel.legacyPrivateMediaConsentRequest?.id)
|
||||
viewModel.invalidateLegacyPrivateMediaConsent(
|
||||
transferId: "transfer-cancelled",
|
||||
messageID: "message-cancelled"
|
||||
)
|
||||
let advanced = await TestHelpers.waitUntil(
|
||||
{ viewModel.legacyPrivateMediaConsentRequest?.peerID == secondPeer },
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(advanced)
|
||||
#expect(decisions.isEmpty, "Invalidation drops the request rather than resolving its send")
|
||||
|
||||
viewModel.resolveLegacyPrivateMediaConsent(
|
||||
requestID: cancelledRequestID,
|
||||
approved: true
|
||||
)
|
||||
#expect(viewModel.legacyPrivateMediaConsentRequest?.peerID == secondPeer)
|
||||
#expect(decisions.isEmpty)
|
||||
|
||||
let keptRequestID = try #require(viewModel.legacyPrivateMediaConsentRequest?.id)
|
||||
viewModel.resolveLegacyPrivateMediaConsent(requestID: keptRequestID, approved: true)
|
||||
#expect(decisions == ["second:true"])
|
||||
#expect(viewModel.legacyPrivateMediaConsentRequest == nil)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func sendVoiceNote_oversizedFileFailsAndDeletesTempFile() async throws {
|
||||
let (viewModel, transport) = makeTestableViewModel()
|
||||
|
||||
@@ -864,6 +864,80 @@ struct ChatViewModelPublicConversationTests {
|
||||
|
||||
struct ChatViewModelPeerTests {
|
||||
|
||||
@Test @MainActor
|
||||
func typedPeerLifecycleEvents_applyBeforeReturning() {
|
||||
let (viewModel, _) = makeTestableViewModel()
|
||||
let peerID = PeerID(str: "1122334455667788")
|
||||
let incoming = BitchatMessage(
|
||||
id: "typed-peer-incoming",
|
||||
sender: "Alice",
|
||||
content: "Hello",
|
||||
timestamp: Date(),
|
||||
isRelay: false,
|
||||
isPrivate: true,
|
||||
recipientNickname: viewModel.nickname,
|
||||
senderPeerID: peerID
|
||||
)
|
||||
viewModel.seedPrivateChat([incoming], for: peerID)
|
||||
viewModel.sentReadReceipts.insert(incoming.id)
|
||||
|
||||
viewModel.didReceiveTransportEvent(.peerConnected(peerID))
|
||||
|
||||
#expect(viewModel.isConnected)
|
||||
|
||||
viewModel.didReceiveTransportEvent(.peerDisconnected(peerID))
|
||||
|
||||
#expect(!viewModel.sentReadReceipts.contains(incoming.id))
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func typedPeerListDeliveryAndBluetoothEvents_applyBeforeReturning() {
|
||||
let (viewModel, transport) = makeTestableViewModel()
|
||||
let stalePeer = PeerID(str: "00000000000000a2")
|
||||
let deliveryPeer = PeerID(str: "0102030405060708")
|
||||
let messageID = "typed-delivery-status"
|
||||
let delivered = DeliveryStatus.delivered(
|
||||
to: "Alice",
|
||||
at: Date(timeIntervalSince1970: 1_234)
|
||||
)
|
||||
let outgoing = BitchatMessage(
|
||||
id: messageID,
|
||||
sender: viewModel.nickname,
|
||||
content: "On the way",
|
||||
timestamp: Date(),
|
||||
isRelay: false,
|
||||
isPrivate: true,
|
||||
recipientNickname: "Alice",
|
||||
senderPeerID: transport.myPeerID,
|
||||
deliveryStatus: .sent
|
||||
)
|
||||
viewModel.markPrivateChatUnread(stalePeer)
|
||||
viewModel.seedPrivateChat([outgoing], for: deliveryPeer)
|
||||
|
||||
viewModel.didReceiveTransportEvent(.peerListUpdated([]))
|
||||
#expect(!viewModel.unreadPrivateMessages.contains(stalePeer))
|
||||
|
||||
viewModel.didReceiveTransportEvent(
|
||||
.messageDeliveryStatusUpdated(
|
||||
messageID: messageID,
|
||||
status: delivered
|
||||
)
|
||||
)
|
||||
#expect(
|
||||
viewModel.privateMessages(for: deliveryPeer).first?.deliveryStatus
|
||||
== delivered
|
||||
)
|
||||
|
||||
viewModel.didReceiveTransportEvent(.bluetoothStateUpdated(.poweredOff))
|
||||
#expect(viewModel.bluetoothState == .poweredOff)
|
||||
#expect(viewModel.showBluetoothAlert)
|
||||
|
||||
// Snapshot events belong to TransportPeerEventsDelegate and are
|
||||
// intentionally ignored at this typed sink.
|
||||
viewModel.didReceiveTransportEvent(.peerSnapshotsUpdated([]))
|
||||
#expect(viewModel.bluetoothState == .poweredOff)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func didConnectToPeer_notifiesDelegate() async {
|
||||
let (_, transport) = makeTestableViewModel()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -12,6 +12,7 @@ import Testing
|
||||
@testable import BitFoundation // to avoid unnecessary public's
|
||||
@testable import bitchat
|
||||
|
||||
@Suite("Integration Tests", .serialized)
|
||||
struct IntegrationTests {
|
||||
|
||||
private var helper = TestNetworkHelper()
|
||||
@@ -272,8 +273,18 @@ struct IntegrationTests {
|
||||
// Re-establish Noise handshake explicitly via managers
|
||||
do {
|
||||
let m1 = try helper.noiseManagers["Bob"]!.initiateHandshake(with: helper.nodes["Alice"]!.peerID)
|
||||
let m2 = try helper.noiseManagers["Alice"]!.handleIncomingHandshake(from: helper.nodes["Bob"]!.peerID, message: m1)!
|
||||
let m3 = try helper.noiseManagers["Bob"]!.handleIncomingHandshake(from: helper.nodes["Alice"]!.peerID, message: m2)!
|
||||
let m2 = try #require(
|
||||
try helper.noiseManagers["Alice"]!.handleIncomingHandshake(
|
||||
from: helper.nodes["Bob"]!.peerID,
|
||||
message: m1
|
||||
)
|
||||
)
|
||||
let m3 = try #require(
|
||||
try helper.noiseManagers["Bob"]!.handleIncomingHandshake(
|
||||
from: helper.nodes["Alice"]!.peerID,
|
||||
message: m2
|
||||
)
|
||||
)
|
||||
_ = try helper.noiseManagers["Alice"]!.handleIncomingHandshake(from: helper.nodes["Bob"]!.peerID, message: m3)
|
||||
} catch {
|
||||
Issue.record("Failed to re-establish Noise session after restart: \(error)")
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import Testing
|
||||
@testable import BitFoundation // to avoid unnecessary public's
|
||||
@testable import bitchat
|
||||
|
||||
@@ -27,9 +28,14 @@ final class TestNetworkHelper {
|
||||
node.mockNickname = name
|
||||
nodes[name] = node
|
||||
|
||||
// Create/replace Noise manager for this node
|
||||
// This synchronous helper directly drives all three XX messages and
|
||||
// has no transport callback loop for delayed collision recovery.
|
||||
let key = Curve25519.KeyAgreement.PrivateKey()
|
||||
noiseManagers[name] = NoiseSessionManager(localStaticKey: key, keychain: mockKeychain)
|
||||
noiseManagers[name] = NoiseSessionManager(
|
||||
localStaticKey: key,
|
||||
keychain: mockKeychain,
|
||||
recentInitiatorCompletionGracePeriod: 0
|
||||
)
|
||||
return node
|
||||
}
|
||||
|
||||
@@ -108,8 +114,18 @@ final class TestNetworkHelper {
|
||||
let peer2ID = nodes[node2]?.peerID else { return }
|
||||
|
||||
let msg1 = try manager1.initiateHandshake(with: peer2ID)
|
||||
let msg2 = try manager2.handleIncomingHandshake(from: peer1ID, message: msg1)!
|
||||
let msg3 = try manager1.handleIncomingHandshake(from: peer2ID, message: msg2)!
|
||||
let msg2 = try #require(
|
||||
try manager2.handleIncomingHandshake(
|
||||
from: peer1ID,
|
||||
message: msg1
|
||||
)
|
||||
)
|
||||
let msg3 = try #require(
|
||||
try manager1.handleIncomingHandshake(
|
||||
from: peer2ID,
|
||||
message: msg2
|
||||
)
|
||||
)
|
||||
_ = try manager2.handleIncomingHandshake(from: peer1ID, message: msg3)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ final class MockIdentityManager: SecureIdentityStateManagerProtocol {
|
||||
private var blockedFingerprints: Set<String> = []
|
||||
private var blockedNostrPubkeys: Set<String> = []
|
||||
private var socialIdentities: [String: SocialIdentity] = [:]
|
||||
private var privateMediaCapableFingerprints: Set<String> = []
|
||||
private var authenticatedSigningKeys: [String: Data] = [:]
|
||||
|
||||
init(_: KeychainManagerProtocol) {}
|
||||
|
||||
@@ -87,7 +89,10 @@ final class MockIdentityManager: SecureIdentityStateManagerProtocol {
|
||||
|
||||
func registerEphemeralSession(peerID: PeerID, handshakeState: HandshakeState) {}
|
||||
|
||||
func clearAllIdentityData() {}
|
||||
func clearAllIdentityData() {
|
||||
privateMediaCapableFingerprints.removeAll()
|
||||
authenticatedSigningKeys.removeAll()
|
||||
}
|
||||
|
||||
func removeEphemeralSession(peerID: PeerID) {}
|
||||
|
||||
@@ -101,6 +106,22 @@ final class MockIdentityManager: SecureIdentityStateManagerProtocol {
|
||||
Set()
|
||||
}
|
||||
|
||||
func markPrivateMediaCapable(fingerprint: String) {
|
||||
privateMediaCapableFingerprints.insert(fingerprint)
|
||||
}
|
||||
|
||||
func hasObservedPrivateMediaCapability(fingerprint: String) -> Bool {
|
||||
privateMediaCapableFingerprints.contains(fingerprint)
|
||||
}
|
||||
|
||||
func bindAuthenticatedSigningPublicKey(_ signingPublicKey: Data, fingerprint: String) {
|
||||
authenticatedSigningKeys[fingerprint] = signingPublicKey
|
||||
}
|
||||
|
||||
func authenticatedSigningPublicKey(forFingerprint fingerprint: String) -> Data? {
|
||||
authenticatedSigningKeys[fingerprint]
|
||||
}
|
||||
|
||||
// MARK: Vouching (transitive verification)
|
||||
|
||||
private var vouchesByVouchee: [String: [VouchRecord]] = [:]
|
||||
|
||||
@@ -36,6 +36,7 @@ final class MockTransport: Transport {
|
||||
private(set) var sentFavoriteNotifications: [(peerID: PeerID, isFavorite: Bool)] = []
|
||||
private(set) var sentBroadcastFiles: [(packet: BitchatFilePacket, transferID: String)] = []
|
||||
private(set) var sentPrivateFiles: [(packet: BitchatFilePacket, peerID: PeerID, transferID: String)] = []
|
||||
private(set) var sentPrivateFileLegacyAllowances: [Bool] = []
|
||||
private(set) var cancelledTransfers: [String] = []
|
||||
private(set) var sentVerifyChallenges: [(peerID: PeerID, noiseKeyHex: String, nonceA: Data)] = []
|
||||
private(set) var sentVerifyResponses: [(peerID: PeerID, noiseKeyHex: String, nonceA: Data)] = []
|
||||
@@ -58,6 +59,7 @@ final class MockTransport: Transport {
|
||||
var peerNicknames: [PeerID: String] = [:]
|
||||
var peerFingerprints: [PeerID: String] = [:]
|
||||
var peerNoiseStates: [PeerID: LazyHandshakeState] = [:]
|
||||
var privateMediaPolicies: [PeerID: PrivateMediaSendPolicy] = [:]
|
||||
private let mockKeychain = MockKeychain()
|
||||
|
||||
// MARK: - Transport Protocol Implementation
|
||||
@@ -186,6 +188,29 @@ final class MockTransport: Transport {
|
||||
|
||||
func sendFilePrivate(_ packet: BitchatFilePacket, to peerID: PeerID, transferId: String) {
|
||||
sentPrivateFiles.append((packet, peerID, transferId))
|
||||
sentPrivateFileLegacyAllowances.append(false)
|
||||
}
|
||||
|
||||
func sendFilePrivate(
|
||||
_ packet: BitchatFilePacket,
|
||||
to peerID: PeerID,
|
||||
transferId: String,
|
||||
allowLegacyFallback: Bool
|
||||
) {
|
||||
sentPrivateFiles.append((packet, peerID, transferId))
|
||||
sentPrivateFileLegacyAllowances.append(allowLegacyFallback)
|
||||
}
|
||||
|
||||
func privateMediaSendPolicy(to peerID: PeerID) -> PrivateMediaSendPolicy {
|
||||
privateMediaPolicies[peerID] ?? .encrypted
|
||||
}
|
||||
|
||||
func resolvePrivateMediaSendPolicy(
|
||||
to peerID: PeerID,
|
||||
completion: @escaping @MainActor (PrivateMediaSendPolicy) -> Void
|
||||
) {
|
||||
let policy = privateMediaPolicies[peerID] ?? .encrypted
|
||||
Task { @MainActor in completion(policy) }
|
||||
}
|
||||
|
||||
func cancelTransfer(_ transferId: String) {
|
||||
|
||||
@@ -5,7 +5,7 @@ import BitFoundation
|
||||
|
||||
@testable import bitchat
|
||||
|
||||
@Suite("Noise Coverage Tests")
|
||||
@Suite("Noise Coverage Tests", .serialized)
|
||||
struct NoiseCoverageTests {
|
||||
private let keychain = MockKeychain()
|
||||
private let aliceStaticKey = Curve25519.KeyAgreement.PrivateKey()
|
||||
@@ -542,8 +542,12 @@ struct NoiseCoverageTests {
|
||||
let aliceManager = NoiseSessionManager(localStaticKey: aliceStaticKey, keychain: keychain)
|
||||
let bobManager = NoiseSessionManager(localStaticKey: bobStaticKey, keychain: keychain)
|
||||
|
||||
aliceManager.onSessionEstablished = establishedRecorder.recordEstablished(peerID:remoteKey:)
|
||||
bobManager.onSessionEstablished = establishedRecorder.recordEstablished(peerID:remoteKey:)
|
||||
aliceManager.onSessionEstablished = establishedRecorder.recordEstablished(
|
||||
peerID:remoteKey:sessionGeneration:
|
||||
)
|
||||
bobManager.onSessionEstablished = establishedRecorder.recordEstablished(
|
||||
peerID:remoteKey:sessionGeneration:
|
||||
)
|
||||
|
||||
try establishManagerSessions(aliceManager: aliceManager, bobManager: bobManager)
|
||||
|
||||
@@ -629,8 +633,16 @@ struct NoiseCoverageTests {
|
||||
)
|
||||
let replacementSession = try #require(manager.getSession(for: alicePeerID))
|
||||
|
||||
#expect(replacementResponse != nil)
|
||||
#expect(replacementSession !== restartedSession)
|
||||
let localPeerID = PeerID(
|
||||
publicKey: aliceStaticKey.publicKey.rawRepresentation
|
||||
)
|
||||
if localPeerID < alicePeerID {
|
||||
#expect(replacementResponse == nil)
|
||||
#expect(replacementSession === restartedSession)
|
||||
} else {
|
||||
#expect(replacementResponse != nil)
|
||||
#expect(replacementSession !== restartedSession)
|
||||
}
|
||||
|
||||
let aliceManager = NoiseSessionManager(localStaticKey: aliceStaticKey, keychain: keychain)
|
||||
let bobManager = NoiseSessionManager(localStaticKey: bobStaticKey, keychain: keychain)
|
||||
@@ -650,13 +662,128 @@ struct NoiseCoverageTests {
|
||||
try aliceManager.initiateHandshake(with: alicePeerID)
|
||||
}
|
||||
|
||||
try aliceManager.initiateRekey(for: alicePeerID)
|
||||
let rekeyInitiation = try aliceManager.initiateRekey(for: alicePeerID)
|
||||
let rekeyHandshake = try #require(
|
||||
aliceManager.claimHandshakeInitiation(
|
||||
rekeyInitiation,
|
||||
for: alicePeerID
|
||||
)
|
||||
)
|
||||
#expect(!rekeyHandshake.isEmpty)
|
||||
let rekeyedSession = try #require(aliceManager.getSession(for: alicePeerID))
|
||||
|
||||
#expect(rekeyedSession !== establishedSession)
|
||||
#expect(rekeyedSession.getState() == .handshaking)
|
||||
}
|
||||
|
||||
@Test("A stale decrypt generation cannot commit across session promotion")
|
||||
func staleDecryptGenerationCannotCommitAcrossPromotion() throws {
|
||||
let aliceManager = NoiseSessionManager(
|
||||
localStaticKey: aliceStaticKey,
|
||||
keychain: keychain,
|
||||
recentInitiatorCompletionGracePeriod: 0,
|
||||
sessionFactory: { peerID, role in
|
||||
BlockingDecryptNoiseSession(
|
||||
peerID: peerID,
|
||||
role: role,
|
||||
keychain: self.keychain,
|
||||
localStaticKey: self.aliceStaticKey
|
||||
)
|
||||
}
|
||||
)
|
||||
let bobManager = NoiseSessionManager(localStaticKey: bobStaticKey, keychain: keychain)
|
||||
try establishManagerSessions(aliceManager: aliceManager, bobManager: bobManager)
|
||||
|
||||
let oldSession = try #require(
|
||||
aliceManager.getSession(for: alicePeerID) as? BlockingDecryptNoiseSession
|
||||
)
|
||||
let oldGeneration = try #require(aliceManager.sessionGeneration(for: alicePeerID))
|
||||
|
||||
// Prepare a fully authenticated responder candidate without promoting
|
||||
// it yet. Its final XX message is the exact operation that replaces
|
||||
// the old `sessions[peerID]` entry.
|
||||
let replacementInitiator = NoiseSession(
|
||||
peerID: bobPeerID,
|
||||
role: .initiator,
|
||||
keychain: keychain,
|
||||
localStaticKey: bobStaticKey
|
||||
)
|
||||
let message1 = try replacementInitiator.startHandshake()
|
||||
let message2 = try #require(
|
||||
try aliceManager.handleIncomingHandshake(from: alicePeerID, message: message1)
|
||||
)
|
||||
let message3 = try #require(try replacementInitiator.processHandshakeMessage(message2))
|
||||
|
||||
let ciphertext = try bobManager.encrypt(Data("old session".utf8), for: bobPeerID)
|
||||
oldSession.pauseNextDecrypt()
|
||||
|
||||
let decryptResult = ConcurrentTestResult<(plaintext: Data, sessionGeneration: UUID)>()
|
||||
var promotionResultForCleanup: ConcurrentTestResult<Data?>?
|
||||
defer {
|
||||
// A failed startup requirement must not strand a late thread in
|
||||
// the blocking test double after the test has returned.
|
||||
oldSession.resumeDecrypt()
|
||||
_ = decryptResult.wait(timeout: 5)
|
||||
if let promotionResultForCleanup {
|
||||
_ = promotionResultForCleanup.wait(timeout: 5)
|
||||
}
|
||||
}
|
||||
|
||||
let decryptThread = Thread {
|
||||
decryptResult.capture {
|
||||
try aliceManager.decryptWithSessionGeneration(ciphertext, from: self.alicePeerID)
|
||||
}
|
||||
}
|
||||
decryptThread.name = "NoiseCoverageTests.staleDecrypt.decrypt"
|
||||
decryptThread.qualityOfService = .userInitiated
|
||||
decryptThread.start()
|
||||
try #require(oldSession.waitForDecryptStart(timeout: 5))
|
||||
|
||||
let promotionStarted = DispatchSemaphore(value: 0)
|
||||
let promotionResult = ConcurrentTestResult<Data?>()
|
||||
promotionResultForCleanup = promotionResult
|
||||
let promotionThread = Thread {
|
||||
promotionStarted.signal()
|
||||
promotionResult.capture {
|
||||
try aliceManager.handleIncomingHandshake(from: self.alicePeerID, message: message3)
|
||||
}
|
||||
}
|
||||
promotionThread.name = "NoiseCoverageTests.staleDecrypt.promote"
|
||||
promotionThread.qualityOfService = .userInitiated
|
||||
promotionThread.start()
|
||||
try #require(promotionStarted.wait(timeout: .now() + 5) == .success)
|
||||
#expect(
|
||||
promotionResult.wait(timeout: 0.05) == nil,
|
||||
"Promotion must wait for the exact decrypting-session lease"
|
||||
)
|
||||
|
||||
oldSession.resumeDecrypt()
|
||||
let decrypted = try #require(decryptResult.wait(timeout: 5)).get()
|
||||
_ = try #require(promotionResult.wait(timeout: 5)).get()
|
||||
|
||||
#expect(decrypted.plaintext == Data("old session".utf8))
|
||||
#expect(decrypted.sessionGeneration == oldGeneration)
|
||||
#expect(aliceManager.sessionGeneration(for: alicePeerID) != oldGeneration)
|
||||
#expect(throws: NoiseEncryptionError.sessionNotEstablished) {
|
||||
try aliceManager.encrypt(
|
||||
Data("stale send".utf8),
|
||||
for: alicePeerID,
|
||||
expectedSessionGeneration: oldGeneration
|
||||
)
|
||||
}
|
||||
|
||||
var staleCommitRan = false
|
||||
let staleCommit = aliceManager.withCurrentSessionGeneration(
|
||||
for: alicePeerID,
|
||||
expected: decrypted.sessionGeneration
|
||||
) {
|
||||
staleCommitRan = true
|
||||
return true
|
||||
}
|
||||
#expect(staleCommit == nil)
|
||||
#expect(!staleCommitRan)
|
||||
}
|
||||
|
||||
@Test("Secure noise sessions enforce limits and renegotiation thresholds")
|
||||
func secureNoiseSessionsEnforceLimitsAndThresholds() throws {
|
||||
let initiator = SecureNoiseSession(
|
||||
@@ -851,7 +978,11 @@ private final class SessionCallbackRecorder: @unchecked Sendable {
|
||||
return establishedEntries.map(\.0)
|
||||
}
|
||||
|
||||
func recordEstablished(peerID: PeerID, remoteKey: Curve25519.KeyAgreement.PublicKey) {
|
||||
func recordEstablished(
|
||||
peerID: PeerID,
|
||||
remoteKey: Curve25519.KeyAgreement.PublicKey,
|
||||
sessionGeneration _: UUID
|
||||
) {
|
||||
lock.lock()
|
||||
establishedEntries.append((peerID, remoteKey.rawRepresentation))
|
||||
lock.unlock()
|
||||
@@ -873,3 +1004,62 @@ private final class FailingNoiseSession: NoiseSession {
|
||||
throw Error.synthetic
|
||||
}
|
||||
}
|
||||
|
||||
private final class BlockingDecryptNoiseSession: NoiseSession, @unchecked Sendable {
|
||||
private let controlLock = NSLock()
|
||||
private var shouldPauseNextDecrypt = false
|
||||
private let decryptStarted = DispatchSemaphore(value: 0)
|
||||
private let resumeDecryptSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
func pauseNextDecrypt() {
|
||||
controlLock.lock()
|
||||
shouldPauseNextDecrypt = true
|
||||
controlLock.unlock()
|
||||
}
|
||||
|
||||
func waitForDecryptStart(timeout: TimeInterval) -> Bool {
|
||||
decryptStarted.wait(timeout: .now() + timeout) == .success
|
||||
}
|
||||
|
||||
func resumeDecrypt() {
|
||||
resumeDecryptSemaphore.signal()
|
||||
}
|
||||
|
||||
override func decrypt(_ ciphertext: Data) throws -> Data {
|
||||
controlLock.lock()
|
||||
let shouldPause = shouldPauseNextDecrypt
|
||||
shouldPauseNextDecrypt = false
|
||||
controlLock.unlock()
|
||||
|
||||
if shouldPause {
|
||||
decryptStarted.signal()
|
||||
resumeDecryptSemaphore.wait()
|
||||
}
|
||||
return try super.decrypt(ciphertext)
|
||||
}
|
||||
}
|
||||
|
||||
private final class ConcurrentTestResult<Value>: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private let completed = DispatchGroup()
|
||||
private var storedResult: Result<Value, Error>?
|
||||
|
||||
init() {
|
||||
completed.enter()
|
||||
}
|
||||
|
||||
func capture(_ operation: () throws -> Value) {
|
||||
let result = Result(catching: operation)
|
||||
lock.lock()
|
||||
storedResult = result
|
||||
lock.unlock()
|
||||
completed.leave()
|
||||
}
|
||||
|
||||
func wait(timeout: TimeInterval) -> Result<Value, Error>? {
|
||||
guard completed.wait(timeout: .now() + timeout) == .success else { return nil }
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return storedResult
|
||||
}
|
||||
}
|
||||
|
||||
@@ -357,8 +357,18 @@ struct NoiseProtocolTests {
|
||||
|
||||
@Test func peerRestartDetection() throws {
|
||||
// Establish initial sessions
|
||||
let aliceManager = NoiseSessionManager(localStaticKey: aliceKey, keychain: mockKeychain)
|
||||
let bobManager = NoiseSessionManager(localStaticKey: bobKey, keychain: mockKeychain)
|
||||
// This test explicitly drives the three synchronous XX messages and
|
||||
// does not exercise the transport's delayed collision recovery.
|
||||
let aliceManager = NoiseSessionManager(
|
||||
localStaticKey: aliceKey,
|
||||
keychain: mockKeychain,
|
||||
recentInitiatorCompletionGracePeriod: 0
|
||||
)
|
||||
let bobManager = NoiseSessionManager(
|
||||
localStaticKey: bobKey,
|
||||
keychain: mockKeychain,
|
||||
recentInitiatorCompletionGracePeriod: 0
|
||||
)
|
||||
|
||||
try establishManagerSessions(aliceManager: aliceManager, bobManager: bobManager)
|
||||
|
||||
@@ -377,15 +387,24 @@ struct NoiseProtocolTests {
|
||||
let newHandshake1 = try bobManagerRestarted.initiateHandshake(with: bobPeerID)
|
||||
|
||||
// Alice should accept the new handshake (clearing old session)
|
||||
let newHandshake2 = try aliceManager.handleIncomingHandshake(
|
||||
from: alicePeerID, message: newHandshake1)
|
||||
#expect(newHandshake2 != nil)
|
||||
let newHandshake2 = try #require(
|
||||
try aliceManager.handleIncomingHandshake(
|
||||
from: alicePeerID,
|
||||
message: newHandshake1
|
||||
)
|
||||
)
|
||||
|
||||
// Complete the new handshake
|
||||
let newHandshake3 = try bobManagerRestarted.handleIncomingHandshake(
|
||||
from: bobPeerID, message: newHandshake2!)
|
||||
#expect(newHandshake3 != nil)
|
||||
_ = try aliceManager.handleIncomingHandshake(from: alicePeerID, message: newHandshake3!)
|
||||
let newHandshake3 = try #require(
|
||||
try bobManagerRestarted.handleIncomingHandshake(
|
||||
from: bobPeerID,
|
||||
message: newHandshake2
|
||||
)
|
||||
)
|
||||
_ = try aliceManager.handleIncomingHandshake(
|
||||
from: alicePeerID,
|
||||
message: newHandshake3
|
||||
)
|
||||
|
||||
// Should be able to exchange messages with new sessions
|
||||
let testMessage = Data("After restart".utf8)
|
||||
@@ -543,8 +562,18 @@ struct NoiseProtocolTests {
|
||||
|
||||
@Test func nonceDesynchronizationCausesRehandshake() throws {
|
||||
// Test that nonce desynchronization leads to proper re-handshake
|
||||
let aliceManager = NoiseSessionManager(localStaticKey: aliceKey, keychain: mockKeychain)
|
||||
let bobManager = NoiseSessionManager(localStaticKey: bobKey, keychain: mockKeychain)
|
||||
// This test explicitly drives the three synchronous XX messages and
|
||||
// does not exercise the transport's delayed collision recovery.
|
||||
let aliceManager = NoiseSessionManager(
|
||||
localStaticKey: aliceKey,
|
||||
keychain: mockKeychain,
|
||||
recentInitiatorCompletionGracePeriod: 0
|
||||
)
|
||||
let bobManager = NoiseSessionManager(
|
||||
localStaticKey: bobKey,
|
||||
keychain: mockKeychain,
|
||||
recentInitiatorCompletionGracePeriod: 0
|
||||
)
|
||||
|
||||
// Establish sessions
|
||||
try establishManagerSessions(aliceManager: aliceManager, bobManager: bobManager)
|
||||
@@ -572,15 +601,25 @@ struct NoiseProtocolTests {
|
||||
let rehandshake1 = try bobManager.initiateHandshake(with: bobPeerID)
|
||||
|
||||
// Alice should accept despite having a "valid" (but desynced) session
|
||||
let rehandshake2 = try aliceManager.handleIncomingHandshake(
|
||||
from: alicePeerID, message: rehandshake1)
|
||||
#expect(rehandshake2 != nil, "Alice should accept handshake to fix desync")
|
||||
let rehandshake2 = try #require(
|
||||
try aliceManager.handleIncomingHandshake(
|
||||
from: alicePeerID,
|
||||
message: rehandshake1
|
||||
),
|
||||
"Alice should accept handshake to fix desync"
|
||||
)
|
||||
|
||||
// Complete handshake
|
||||
let rehandshake3 = try bobManager.handleIncomingHandshake(
|
||||
from: bobPeerID, message: rehandshake2!)
|
||||
#expect(rehandshake3 != nil)
|
||||
_ = try aliceManager.handleIncomingHandshake(from: alicePeerID, message: rehandshake3!)
|
||||
let rehandshake3 = try #require(
|
||||
try bobManager.handleIncomingHandshake(
|
||||
from: bobPeerID,
|
||||
message: rehandshake2
|
||||
)
|
||||
)
|
||||
_ = try aliceManager.handleIncomingHandshake(
|
||||
from: alicePeerID,
|
||||
message: rehandshake3
|
||||
)
|
||||
|
||||
// Verify communication works again
|
||||
let testResynced = Data("Resynced".utf8)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import BitFoundation
|
||||
import XCTest
|
||||
@testable import bitchat
|
||||
|
||||
@@ -73,4 +74,85 @@ final class BitchatFilePacketTests: XCTestCase {
|
||||
XCTAssertEqual(decoded.fileSize, UInt64(content.count))
|
||||
XCTAssertEqual(decoded.content, content)
|
||||
}
|
||||
|
||||
func testPrivateMediaMessageIdentityConvergesAcrossPeerIDAliases() throws {
|
||||
let senderKey = Data(repeating: 0x11, count: 32)
|
||||
let recipientKey = Data(repeating: 0x22, count: 32)
|
||||
let senderStable = PeerID(hexData: senderKey)
|
||||
let recipientStable = PeerID(hexData: recipientKey)
|
||||
let fileName = "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg"
|
||||
|
||||
let senderID = try XCTUnwrap(PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: senderStable.toShort(),
|
||||
recipientPeerID: PeerID(str: "mesh:\(recipientStable.toShort().bare)"),
|
||||
fileName: fileName
|
||||
))
|
||||
let receiverID = try XCTUnwrap(PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: senderStable,
|
||||
recipientPeerID: recipientStable.toShort(),
|
||||
fileName: fileName
|
||||
))
|
||||
|
||||
XCTAssertEqual(senderID, receiverID)
|
||||
XCTAssertTrue(senderID.hasPrefix("media-"))
|
||||
XCTAssertEqual(senderID.count, 38)
|
||||
XCTAssertTrue(PrivateMediaMessageIdentity.isStableID(senderID))
|
||||
XCTAssertFalse(PrivateMediaMessageIdentity.isStableID("media-\(String(repeating: "A", count: 32))"))
|
||||
XCTAssertFalse(PrivateMediaMessageIdentity.isStableID("media-\(String(repeating: "a", count: 31))"))
|
||||
XCTAssertFalse(PrivateMediaMessageIdentity.isStableID(UUID().uuidString))
|
||||
}
|
||||
|
||||
func testPrivateMediaMessageIdentitySeparatesDirectionAndFilename() throws {
|
||||
let alice = PeerID(str: "0011223344556677")
|
||||
let bob = PeerID(str: "8899aabbccddeeff")
|
||||
let firstName = "voice_20260725_105708_11111111-1111-1111-1111-111111111111.m4a"
|
||||
let secondName = "voice_20260725_105709_22222222-2222-2222-2222-222222222222.m4a"
|
||||
let first = try XCTUnwrap(PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: alice,
|
||||
recipientPeerID: bob,
|
||||
fileName: firstName
|
||||
))
|
||||
|
||||
XCTAssertNotEqual(first, PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: bob,
|
||||
recipientPeerID: alice,
|
||||
fileName: firstName
|
||||
))
|
||||
XCTAssertNotEqual(first, PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: alice,
|
||||
recipientPeerID: bob,
|
||||
fileName: secondName
|
||||
))
|
||||
XCTAssertNil(PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: alice,
|
||||
recipientPeerID: bob,
|
||||
fileName: nil
|
||||
))
|
||||
XCTAssertNil(PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: alice,
|
||||
recipientPeerID: bob,
|
||||
fileName: "photo.jpg"
|
||||
))
|
||||
XCTAssertNil(PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: alice,
|
||||
recipientPeerID: bob,
|
||||
fileName: "img_11111111-1111-1111-1111-111111111111.pdf"
|
||||
))
|
||||
XCTAssertNotNil(PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: alice,
|
||||
recipientPeerID: bob,
|
||||
fileName: "voice_0011223344556677.m4a"
|
||||
))
|
||||
}
|
||||
|
||||
func testPrivateMediaMessageIdentityMatchesVersionOneGoldenVector() {
|
||||
XCTAssertEqual(
|
||||
PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: PeerID(str: "0011223344556677"),
|
||||
recipientPeerID: PeerID(str: "8899aabbccddeeff"),
|
||||
fileName: "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg"
|
||||
),
|
||||
"media-910bd42c65060ab76bb6406f220c4516"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,6 +145,39 @@ struct PacketsTests {
|
||||
#expect(decoded.capabilities?.rawValue == 0x0180)
|
||||
}
|
||||
|
||||
@Test
|
||||
func authenticatedPeerStateUsesVersionedCanonicalTLVs() throws {
|
||||
let signingKey = Data(repeating: 0xA5, count: 32)
|
||||
let packet = AuthenticatedPeerStatePacket(
|
||||
capabilities: [.privateMedia, .vouch],
|
||||
signingPublicKey: signingKey
|
||||
)
|
||||
|
||||
var encoded = try #require(packet.encode())
|
||||
#expect(encoded.prefix(5) == Data([0x01, 0x01, 0x02, 0x20, 0x01]))
|
||||
// Unknown TLVs are forward-compatible and do not alter v1 state.
|
||||
encoded.append(makeTLV(type: 0x7F, value: Data([0xCA, 0xFE])))
|
||||
|
||||
#expect(AuthenticatedPeerStatePacket.decode(from: encoded) == packet)
|
||||
}
|
||||
|
||||
@Test
|
||||
func authenticatedPeerStateRejectsMalformedAmbiguousOrUnknownVersion() {
|
||||
let key = Data(repeating: 0x44, count: 32)
|
||||
let capabilities = makeTLV(type: 0x01, value: Data([0x00, 0x01]))
|
||||
let signing = makeTLV(type: 0x02, value: key)
|
||||
|
||||
#expect(AuthenticatedPeerStatePacket.decode(from: Data([0x02]) + capabilities + signing) == nil)
|
||||
#expect(AuthenticatedPeerStatePacket.decode(from: Data([0x01]) + signing) == nil)
|
||||
#expect(AuthenticatedPeerStatePacket.decode(from: Data([0x01]) + capabilities + capabilities + signing) == nil)
|
||||
#expect(AuthenticatedPeerStatePacket.decode(from: Data([0x01, 0x01, 0x00]) + signing) == nil)
|
||||
// 0x0001 is non-minimal little endian; the canonical form is [0x01].
|
||||
#expect(AuthenticatedPeerStatePacket.decode(from: Data([0x01]) + makeTLV(type: 0x01, value: Data([0x01, 0x00])) + signing) == nil)
|
||||
#expect(AuthenticatedPeerStatePacket.decode(from: Data([0x01]) + capabilities + makeTLV(type: 0x02, value: Data(key.dropLast()))) == nil)
|
||||
#expect(AuthenticatedPeerStatePacket.decode(from: Data([0x01]) + capabilities + Data(signing.dropLast())) == nil)
|
||||
#expect(AuthenticatedPeerStatePacket.decode(from: Data([0x01]) + makeTLV(type: 0x01, value: Data(repeating: 0x01, count: 9)) + signing) == nil)
|
||||
}
|
||||
|
||||
@Test
|
||||
func privateMessagePacketRejectsUnknownTypeAndTruncation() {
|
||||
let unknownTLV = Data([0x7F, 0x01, 0x41])
|
||||
|
||||
@@ -6,6 +6,7 @@ import Testing
|
||||
struct BLEAnnounceHandlerTests {
|
||||
private final class Recorder {
|
||||
var existingNoisePublicKey: Data?
|
||||
var authenticatedSigningPublicKey: Data?
|
||||
var signatureValid = true
|
||||
var linkState: (hasPeripheral: Bool, hasCentral: Bool) = (false, false)
|
||||
var linkBoundToOtherPeer = false
|
||||
@@ -37,6 +38,7 @@ struct BLEAnnounceHandlerTests {
|
||||
messageTTL: TransportConfig.messageTTLDefault,
|
||||
now: { now },
|
||||
existingNoisePublicKey: { _ in recorder.existingNoisePublicKey },
|
||||
authenticatedSigningPublicKey: { _ in recorder.authenticatedSigningPublicKey },
|
||||
verifySignature: { packet, signingPublicKey in
|
||||
recorder.verifySignatureCalls.append((packet, signingPublicKey))
|
||||
return recorder.signatureValid
|
||||
|
||||
@@ -169,6 +169,23 @@ struct BLEAnnounceHandlingPolicyTests {
|
||||
#expect(decision.isVerified)
|
||||
}
|
||||
|
||||
@Test
|
||||
func trustPolicyRejectsSigningKeyReplacementAfterNoiseBinding() {
|
||||
let noiseKey = Data(repeating: 0xCC, count: 32)
|
||||
let boundSigningKey = Data(repeating: 0x11, count: 32)
|
||||
|
||||
let decision = BLEAnnounceTrustPolicy.evaluate(
|
||||
hasSignature: true,
|
||||
signatureValid: true,
|
||||
existingNoisePublicKey: noiseKey,
|
||||
announcedNoisePublicKey: noiseKey,
|
||||
authenticatedSigningPublicKey: boundSigningKey,
|
||||
announcedSigningPublicKey: Data(repeating: 0x22, count: 32)
|
||||
)
|
||||
|
||||
#expect(decision == .reject(.authenticatedSigningKeyMismatch))
|
||||
}
|
||||
|
||||
@Test
|
||||
func responsePolicyConnectsOnlyForDirectNewOrReconnectedPeers() {
|
||||
let directNew = BLEAnnounceResponsePolicy.plan(
|
||||
|
||||
@@ -13,11 +13,27 @@ struct BLEFileTransferHandlerTests {
|
||||
|
||||
var signatureVerifyCount = 0
|
||||
var signedNameQueries: [PeerID] = []
|
||||
var blockedPeers: Set<PeerID> = []
|
||||
var trackedPackets: [BitchatPacket] = []
|
||||
var quotaReservations: [Int] = []
|
||||
var saveCalls: [(data: Data, preferredName: String?, subdirectory: String, fallbackExtension: String?, defaultPrefix: String)] = []
|
||||
var receiptStates: [String: BLEPrivateMediaReceiptState] = [:]
|
||||
var receiptCommits: [(messageID: String, storedURL: URL)] = []
|
||||
var receiptCommitSucceeds = true
|
||||
var removedIncomingFiles: [URL] = []
|
||||
var lastSeenUpdates: [PeerID] = []
|
||||
var deliveryAcks: [(messageID: String, peerID: PeerID)] = []
|
||||
var deliveredMessages: [BitchatMessage] = []
|
||||
var saveOverride: ((
|
||||
_ data: Data,
|
||||
_ preferredName: String?,
|
||||
_ subdirectory: String,
|
||||
_ fallbackExtension: String?,
|
||||
_ defaultPrefix: String
|
||||
) -> URL?)?
|
||||
var receiptStateOverride: ((String) -> BLEPrivateMediaReceiptState)?
|
||||
var receiptCommitOverride: ((String, URL) -> Bool)?
|
||||
var removeIncomingFileOverride: ((URL) -> Void)?
|
||||
}
|
||||
|
||||
private let localPeerID = PeerID(str: "0102030405060708")
|
||||
@@ -33,6 +49,7 @@ struct BLEFileTransferHandlerTests {
|
||||
recorder.signatureVerifyCount += 1
|
||||
return recorder.signatureVerifies
|
||||
},
|
||||
localSigningPublicKey: { [sampleSigningKey] in sampleSigningKey },
|
||||
signedSenderDisplayName: { _, peerID in
|
||||
recorder.signedNameQueries.append(peerID)
|
||||
return recorder.signedName
|
||||
@@ -45,13 +62,44 @@ struct BLEFileTransferHandlerTests {
|
||||
},
|
||||
saveIncomingFile: { data, preferredName, subdirectory, fallbackExtension, defaultPrefix in
|
||||
recorder.saveCalls.append((data, preferredName, subdirectory, fallbackExtension, defaultPrefix))
|
||||
if let saveOverride = recorder.saveOverride {
|
||||
return saveOverride(data, preferredName, subdirectory, fallbackExtension, defaultPrefix)
|
||||
}
|
||||
return recorder.saveResult
|
||||
},
|
||||
privateMediaReceiptState: { messageID in
|
||||
if let receiptStateOverride = recorder.receiptStateOverride {
|
||||
return receiptStateOverride(messageID)
|
||||
}
|
||||
return recorder.receiptStates[messageID] ?? .absent
|
||||
},
|
||||
commitPrivateMediaFile: { messageID, storedURL in
|
||||
recorder.receiptCommits.append((messageID, storedURL))
|
||||
if let receiptCommitOverride = recorder.receiptCommitOverride {
|
||||
return receiptCommitOverride(messageID, storedURL)
|
||||
}
|
||||
guard recorder.receiptCommitSucceeds else { return false }
|
||||
recorder.receiptStates[messageID] = .accepted(storedURL)
|
||||
return true
|
||||
},
|
||||
removeIncomingFile: { storedURL in
|
||||
recorder.removedIncomingFiles.append(storedURL)
|
||||
recorder.removeIncomingFileOverride?(storedURL)
|
||||
},
|
||||
isPrivateMediaSenderBlocked: { peerID in
|
||||
recorder.blockedPeers.contains(peerID)
|
||||
},
|
||||
updatePeerLastSeen: { peerID in
|
||||
recorder.lastSeenUpdates.append(peerID)
|
||||
},
|
||||
deliverMessage: { message in
|
||||
acknowledgePrivateMedia: { messageID, peerID in
|
||||
recorder.deliveryAcks.append((messageID, peerID))
|
||||
},
|
||||
deliverMessage: { message, shouldDeliver, completion in
|
||||
guard shouldDeliver() else { return }
|
||||
recorder.deliveredMessages.append(message)
|
||||
guard shouldDeliver() else { return }
|
||||
completion()
|
||||
}
|
||||
)
|
||||
return BLEFileTransferHandler(environment: environment)
|
||||
@@ -92,12 +140,11 @@ struct BLEFileTransferHandlerTests {
|
||||
@Test
|
||||
func selfEchoIsDropped() throws {
|
||||
let recorder = Recorder()
|
||||
recorder.signatureVerifies = true
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let packet = try makeFileTransferPacket(sender: localPeerID, mimeType: "application/pdf", content: Data("%PDF-1.7".utf8), ttl: 3)
|
||||
|
||||
// The relay pipeline already suppresses self-originated packets, so the
|
||||
// handler reports "relayable" rather than treating the echo as forged.
|
||||
#expect(handler.handle(packet, from: localPeerID))
|
||||
#expect(!handler.handle(packet, from: localPeerID))
|
||||
|
||||
expectNoSideEffects(recorder)
|
||||
}
|
||||
@@ -120,7 +167,12 @@ struct BLEFileTransferHandlerTests {
|
||||
let recorder = Recorder()
|
||||
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Bob", isVerified: false, isConnected: true)]
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let packet = try makeFileTransferPacket(sender: remotePeerID, mimeType: "application/pdf", content: Data("%PDF-1.7".utf8))
|
||||
let packet = try makeFileTransferPacket(
|
||||
sender: remotePeerID,
|
||||
mimeType: "application/pdf",
|
||||
content: Data("%PDF-1.7".utf8),
|
||||
hasSignature: false
|
||||
)
|
||||
|
||||
// Failed sender authentication must also stop the packet from being
|
||||
// relayed to downstream nodes.
|
||||
@@ -129,7 +181,7 @@ struct BLEFileTransferHandlerTests {
|
||||
// Broadcast files carry an attacker-controllable senderID, so — like
|
||||
// public messages — a connected-but-unverified peer must present a valid
|
||||
// packet signature. No signing key + no signed identity means dropped.
|
||||
#expect(recorder.signedNameQueries == [remotePeerID])
|
||||
#expect(recorder.signedNameQueries.isEmpty)
|
||||
#expect(recorder.trackedPackets.isEmpty)
|
||||
#expect(recorder.deliveredMessages.isEmpty)
|
||||
}
|
||||
@@ -153,12 +205,11 @@ struct BLEFileTransferHandlerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
func selfBroadcastReplayIsDeliveredWithoutSignatureCheck() throws {
|
||||
// Our own broadcast file replayed via gossip sync arrives with ttl==0
|
||||
// (so it is not treated as a self-echo) and cannot be verified against
|
||||
// the peer registry — it must still be accepted, matching
|
||||
// BLEPublicMessageHandler's self exemption.
|
||||
func signedSelfBroadcastReplayIsDelivered() throws {
|
||||
// Our own broadcast file replayed via gossip sync arrives with ttl==0;
|
||||
// it is verified against our local signing key before delivery.
|
||||
let recorder = Recorder()
|
||||
recorder.signatureVerifies = true
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let packet = try makeFileTransferPacket(
|
||||
sender: localPeerID,
|
||||
@@ -169,7 +220,7 @@ struct BLEFileTransferHandlerTests {
|
||||
|
||||
#expect(handler.handle(packet, from: localPeerID))
|
||||
|
||||
#expect(recorder.signatureVerifyCount == 0)
|
||||
#expect(recorder.signatureVerifyCount == 1)
|
||||
#expect(recorder.signedNameQueries.isEmpty)
|
||||
#expect(recorder.deliveredMessages.count == 1)
|
||||
#expect(recorder.deliveredMessages.first?.sender == "Me")
|
||||
@@ -205,7 +256,8 @@ struct BLEFileTransferHandlerTests {
|
||||
sender: remotePeerID,
|
||||
mimeType: "audio/mp4",
|
||||
content: m4a,
|
||||
fileName: "voice_1122334455667788"
|
||||
fileName: "voice_1122334455667788",
|
||||
hasSignature: false
|
||||
)
|
||||
|
||||
// The spoofed note must be dropped locally AND not relayed onward.
|
||||
@@ -215,7 +267,7 @@ struct BLEFileTransferHandlerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
func privateFileFromConnectedUnverifiedPeerIsAccepted() throws {
|
||||
func rawDirectedFileWithoutVerifiableSignatureIsDroppedWithoutWriteOrRelay() throws {
|
||||
let recorder = Recorder()
|
||||
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Bob", isVerified: false, isConnected: true)]
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
@@ -223,23 +275,25 @@ struct BLEFileTransferHandlerTests {
|
||||
sender: remotePeerID,
|
||||
mimeType: "application/pdf",
|
||||
content: Data("%PDF-1.7".utf8),
|
||||
recipientID: Data(hexString: localPeerID.id)
|
||||
recipientID: Data(hexString: localPeerID.id),
|
||||
hasSignature: false
|
||||
)
|
||||
|
||||
#expect(handler.handle(packet, from: remotePeerID))
|
||||
#expect(!handler.handle(packet, from: remotePeerID))
|
||||
|
||||
// Directed transfers keep the lenient connected-peer path (no broadcast
|
||||
// exposure); no signature check is required.
|
||||
#expect(recorder.signatureVerifyCount == 0)
|
||||
#expect(recorder.signedNameQueries.isEmpty)
|
||||
#expect(recorder.deliveredMessages.count == 1)
|
||||
#expect(recorder.deliveredMessages.first?.isPrivate == true)
|
||||
#expect(recorder.trackedPackets.isEmpty)
|
||||
#expect(recorder.quotaReservations.isEmpty)
|
||||
#expect(recorder.saveCalls.isEmpty)
|
||||
#expect(recorder.deliveredMessages.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func fileDirectedToAnotherPeerIsIgnored() throws {
|
||||
let recorder = Recorder()
|
||||
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
|
||||
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true, signingPublicKey: sampleSigningKey)]
|
||||
recorder.signatureVerifies = true
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let packet = try makeFileTransferPacket(
|
||||
sender: remotePeerID,
|
||||
@@ -260,7 +314,8 @@ struct BLEFileTransferHandlerTests {
|
||||
@Test
|
||||
func privateFileUpdatesLastSeenAndDeliversPrivateMessage() throws {
|
||||
let recorder = Recorder()
|
||||
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
|
||||
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true, signingPublicKey: sampleSigningKey)]
|
||||
recorder.signatureVerifies = true
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let packet = try makeFileTransferPacket(
|
||||
sender: remotePeerID,
|
||||
@@ -276,12 +331,416 @@ struct BLEFileTransferHandlerTests {
|
||||
#expect(recorder.lastSeenUpdates == [remotePeerID])
|
||||
#expect(recorder.deliveredMessages.count == 1)
|
||||
#expect(recorder.deliveredMessages.first?.isPrivate == true)
|
||||
#expect(recorder.deliveredMessages.first?.id.hasPrefix("media-") == false)
|
||||
// Must be explicit: BitchatMessage defaults private messages to
|
||||
// .sending, which the media views render as an in-flight send
|
||||
// (empty reveal mask, disabled reveal tap).
|
||||
#expect(recorder.deliveredMessages.first?.deliveryStatus == .delivered(to: "Me", at: Date(timeIntervalSince1970: 900)))
|
||||
}
|
||||
|
||||
@Test
|
||||
func bit8EncryptedPrivateFileKeepsStableIDAndAckWithoutBit9Proof() throws {
|
||||
let recorder = Recorder()
|
||||
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let content = Data([0xFF, 0xD8, 0xFF]) + Data(repeating: 0x41, count: 128)
|
||||
let fileName = "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg"
|
||||
let file = BitchatFilePacket(
|
||||
fileName: fileName,
|
||||
fileSize: UInt64(content.count),
|
||||
mimeType: "image/jpeg",
|
||||
content: content
|
||||
)
|
||||
let payload = try #require(file.encode())
|
||||
let timestamp = Date(timeIntervalSince1970: 1_234)
|
||||
|
||||
#expect(handler.handlePrivatePayload(payload, from: remotePeerID, timestamp: timestamp))
|
||||
|
||||
#expect(recorder.signatureVerifyCount == 0)
|
||||
#expect(recorder.signedNameQueries.isEmpty)
|
||||
#expect(recorder.trackedPackets.isEmpty)
|
||||
#expect(recorder.quotaReservations == [content.count])
|
||||
#expect(recorder.saveCalls.first?.data == content)
|
||||
#expect(recorder.lastSeenUpdates == [remotePeerID])
|
||||
#expect(recorder.deliveredMessages.count == 1)
|
||||
#expect(recorder.deliveredMessages.first?.isPrivate == true)
|
||||
#expect(recorder.deliveredMessages.first?.timestamp == timestamp)
|
||||
#expect(recorder.deliveredMessages.first?.id == PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: remotePeerID,
|
||||
recipientPeerID: localPeerID,
|
||||
fileName: fileName
|
||||
))
|
||||
#expect(recorder.receiptCommits.count == 1)
|
||||
#expect(recorder.deliveryAcks.count == 1)
|
||||
#expect(recorder.deliveryAcks.first?.messageID == recorder.deliveredMessages.first?.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
func rawLegacyPrivateFileWithRetryShapedNameNeverUsesReceiptLedger() throws {
|
||||
let recorder = Recorder()
|
||||
recorder.peers = [remotePeerID: makePeerInfo(
|
||||
remotePeerID,
|
||||
nickname: "Alice",
|
||||
isVerified: true,
|
||||
signingPublicKey: sampleSigningKey
|
||||
)]
|
||||
recorder.signatureVerifies = true
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let content = Data([0xFF, 0xD8, 0xFF, 0xD9])
|
||||
let packet = try makeFileTransferPacket(
|
||||
sender: remotePeerID,
|
||||
mimeType: "image/jpeg",
|
||||
content: content,
|
||||
recipientID: Data(hexString: localPeerID.id),
|
||||
fileName: "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg"
|
||||
)
|
||||
|
||||
#expect(handler.handle(packet, from: remotePeerID))
|
||||
#expect(recorder.receiptCommits.isEmpty)
|
||||
#expect(recorder.deliveryAcks.isEmpty)
|
||||
#expect(recorder.deliveredMessages.count == 1)
|
||||
#expect(recorder.deliveredMessages.first?.id.hasPrefix("media-") == false)
|
||||
}
|
||||
|
||||
@Test
|
||||
func repeatedLegacyPrivateImageNamesKeepDistinctRandomMessageIDs() throws {
|
||||
let recorder = Recorder()
|
||||
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let content = Data([0xFF, 0xD8, 0xFF]) + Data(repeating: 0x41, count: 128)
|
||||
let file = BitchatFilePacket(
|
||||
fileName: "photo.jpg",
|
||||
fileSize: UInt64(content.count),
|
||||
mimeType: "image/jpeg",
|
||||
content: content
|
||||
)
|
||||
let payload = try #require(file.encode())
|
||||
|
||||
#expect(handler.handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_234)
|
||||
))
|
||||
#expect(handler.handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_235)
|
||||
))
|
||||
|
||||
#expect(recorder.deliveredMessages.count == 2)
|
||||
#expect(recorder.deliveredMessages[0].id != recorder.deliveredMessages[1].id)
|
||||
#expect(recorder.deliveredMessages.allSatisfy { !$0.id.hasPrefix("media-") })
|
||||
}
|
||||
|
||||
@Test
|
||||
func lostCapabilityProofThenStableRetryReusesDurableIDWithoutSecondDiskWrite() throws {
|
||||
let recorder = Recorder()
|
||||
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let content = Data([0xFF, 0xD8, 0xFF]) + Data(repeating: 0x41, count: 128)
|
||||
let fileName = "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg"
|
||||
let file = BitchatFilePacket(
|
||||
fileName: fileName,
|
||||
fileSize: UInt64(content.count),
|
||||
mimeType: "image/jpeg",
|
||||
content: content
|
||||
)
|
||||
let payload = try #require(file.encode())
|
||||
let expectedID = try #require(PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: remotePeerID,
|
||||
recipientPeerID: localPeerID,
|
||||
fileName: fileName
|
||||
))
|
||||
|
||||
// First encrypted arrival may precede the sender's authenticated bit-9
|
||||
// proof. It still uses the bit-8 stable ID/ACK contract.
|
||||
#expect(handler.handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_234)
|
||||
))
|
||||
// A later automatic retry after proof must resolve the same durable ID
|
||||
// rather than create a legacy random-ID bubble.
|
||||
#expect(handler.handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_235)
|
||||
))
|
||||
|
||||
#expect(recorder.quotaReservations == [content.count])
|
||||
#expect(recorder.saveCalls.count == 1)
|
||||
// The handler re-offers a durable duplicate so a relaunched UI can
|
||||
// restore its bubble; the synchronous conversation sink deduplicates.
|
||||
#expect(recorder.deliveredMessages.count == 2)
|
||||
#expect(recorder.lastSeenUpdates == [remotePeerID, remotePeerID])
|
||||
#expect(recorder.deliveryAcks.count == 2)
|
||||
#expect(recorder.deliveryAcks.allSatisfy {
|
||||
$0.messageID == expectedID && $0.peerID == remotePeerID
|
||||
})
|
||||
}
|
||||
|
||||
@Test
|
||||
func acceptedPrivateMediaAfterRelaunchRedeliversDurableURLBeforeAck() throws {
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent(
|
||||
"private-media-handler-relaunch-\(UUID().uuidString)",
|
||||
isDirectory: true
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let store = BLEIncomingFileStore(baseDirectory: root)
|
||||
let content = Data([0xFF, 0xD8, 0xFF, 0xD9])
|
||||
let file = BitchatFilePacket(
|
||||
fileName: "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg",
|
||||
fileSize: UInt64(content.count),
|
||||
mimeType: "image/jpeg",
|
||||
content: content
|
||||
)
|
||||
let payload = try #require(file.encode())
|
||||
|
||||
func configure(_ recorder: Recorder) {
|
||||
recorder.peers = [remotePeerID: makePeerInfo(
|
||||
remotePeerID,
|
||||
nickname: "Alice",
|
||||
isVerified: true
|
||||
)]
|
||||
recorder.saveOverride = {
|
||||
data,
|
||||
preferredName,
|
||||
subdirectory,
|
||||
fallbackExtension,
|
||||
defaultPrefix in
|
||||
store.save(
|
||||
data: data,
|
||||
preferredName: preferredName,
|
||||
subdirectory: subdirectory,
|
||||
fallbackExtension: fallbackExtension,
|
||||
defaultPrefix: defaultPrefix
|
||||
)
|
||||
}
|
||||
recorder.receiptStateOverride = {
|
||||
store.privateMediaReceiptState(messageID: $0)
|
||||
}
|
||||
recorder.receiptCommitOverride = {
|
||||
store.commitPrivateMediaFile(messageID: $0, storedURL: $1)
|
||||
}
|
||||
recorder.removeIncomingFileOverride = {
|
||||
store.removeIncomingFile(at: $0)
|
||||
}
|
||||
}
|
||||
|
||||
let first = Recorder()
|
||||
configure(first)
|
||||
#expect(makeHandler(recorder: first).handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_234)
|
||||
))
|
||||
let originalMessage = try #require(first.deliveredMessages.first)
|
||||
#expect(first.deliveryAcks.count == 1)
|
||||
|
||||
// A fresh handler models process relaunch: its in-memory reservation
|
||||
// cache is empty, so only the durable receipt can suppress disk work.
|
||||
let relaunched = Recorder()
|
||||
configure(relaunched)
|
||||
#expect(makeHandler(recorder: relaunched).handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_235)
|
||||
))
|
||||
|
||||
#expect(relaunched.quotaReservations.isEmpty)
|
||||
#expect(relaunched.saveCalls.isEmpty)
|
||||
#expect(relaunched.receiptCommits.isEmpty)
|
||||
#expect(relaunched.deliveredMessages.count == 1)
|
||||
#expect(relaunched.deliveredMessages.first?.id == originalMessage.id)
|
||||
#expect(relaunched.deliveredMessages.first?.content == originalMessage.content)
|
||||
#expect(relaunched.deliveryAcks.count == 1)
|
||||
#expect(relaunched.deliveryAcks.first?.messageID == originalMessage.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
func inFlightStableDuplicateIsNotAcknowledgedAndFailedSaveRemainsRetryable() throws {
|
||||
let recorder = Recorder()
|
||||
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
|
||||
let content = Data([0xFF, 0xD8, 0xFF]) + Data(repeating: 0x41, count: 128)
|
||||
let file = BitchatFilePacket(
|
||||
fileName: "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg",
|
||||
fileSize: UInt64(content.count),
|
||||
mimeType: "image/jpeg",
|
||||
content: content
|
||||
)
|
||||
let payload = try #require(file.encode())
|
||||
var handler: BLEFileTransferHandler!
|
||||
var nestedResult: Bool?
|
||||
var failFirstSave = true
|
||||
recorder.saveOverride = { _, _, _, _, _ in
|
||||
if failFirstSave {
|
||||
failFirstSave = false
|
||||
nestedResult = handler.handlePrivatePayload(
|
||||
payload,
|
||||
from: self.remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_235)
|
||||
)
|
||||
return nil
|
||||
}
|
||||
return recorder.saveResult
|
||||
}
|
||||
handler = makeHandler(recorder: recorder)
|
||||
|
||||
// The nested arrival sees the first reservation as pending. It is
|
||||
// coalesced without an ACK; then the first durable save fails.
|
||||
#expect(!handler.handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_234)
|
||||
))
|
||||
#expect(nestedResult == true)
|
||||
#expect(recorder.saveCalls.count == 1)
|
||||
#expect(recorder.deliveryAcks.isEmpty)
|
||||
#expect(recorder.deliveredMessages.isEmpty)
|
||||
|
||||
// Failure released the reservation, so the sender's later retry can
|
||||
// persist and deliver normally.
|
||||
#expect(handler.handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_236)
|
||||
))
|
||||
#expect(recorder.saveCalls.count == 2)
|
||||
#expect(recorder.deliveryAcks.count == 1)
|
||||
#expect(recorder.deliveredMessages.count == 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
func unavailableDurableReceiptStateWithholdsDiskDeliveryAndAck() throws {
|
||||
let recorder = Recorder()
|
||||
recorder.peers = [remotePeerID: makePeerInfo(
|
||||
remotePeerID,
|
||||
nickname: "Alice",
|
||||
isVerified: true
|
||||
)]
|
||||
let fileName =
|
||||
"img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg"
|
||||
let messageID = try #require(PrivateMediaMessageIdentity.stableID(
|
||||
senderPeerID: remotePeerID,
|
||||
recipientPeerID: localPeerID,
|
||||
fileName: fileName
|
||||
))
|
||||
recorder.receiptStates[messageID] = .unavailable
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let content = Data([0xFF, 0xD8, 0xFF, 0xD9])
|
||||
let payload = try #require(BitchatFilePacket(
|
||||
fileName: fileName,
|
||||
fileSize: UInt64(content.count),
|
||||
mimeType: "image/jpeg",
|
||||
content: content
|
||||
).encode())
|
||||
|
||||
#expect(handler.handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_234)
|
||||
))
|
||||
#expect(recorder.quotaReservations.isEmpty)
|
||||
#expect(recorder.saveCalls.isEmpty)
|
||||
#expect(recorder.receiptCommits.isEmpty)
|
||||
#expect(recorder.deliveredMessages.isEmpty)
|
||||
#expect(recorder.deliveryAcks.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func durableReceiptCommitFailureRollsBackAndWithholdsDeliveryAck() throws {
|
||||
let recorder = Recorder()
|
||||
recorder.peers = [remotePeerID: makePeerInfo(
|
||||
remotePeerID,
|
||||
nickname: "Alice",
|
||||
isVerified: true
|
||||
)]
|
||||
recorder.receiptCommitSucceeds = false
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let content = Data([0xFF, 0xD8, 0xFF, 0xD9])
|
||||
let payload = try #require(BitchatFilePacket(
|
||||
fileName: "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg",
|
||||
fileSize: UInt64(content.count),
|
||||
mimeType: "image/jpeg",
|
||||
content: content
|
||||
).encode())
|
||||
|
||||
#expect(!handler.handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_234)
|
||||
))
|
||||
#expect(recorder.saveCalls.count == 1)
|
||||
#expect(recorder.receiptCommits.count == 1)
|
||||
#expect(recorder.removedIncomingFiles.count == 1)
|
||||
#expect(recorder.removedIncomingFiles.first == recorder.saveResult)
|
||||
#expect(recorder.deliveredMessages.isEmpty)
|
||||
#expect(recorder.deliveryAcks.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func blockedPrivateMediaIsDroppedBeforeQuotaDiskAndDedupState() throws {
|
||||
let recorder = Recorder()
|
||||
recorder.blockedPeers = [remotePeerID]
|
||||
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let content = Data([0xFF, 0xD8, 0xFF]) + Data(repeating: 0x41, count: 128)
|
||||
let file = BitchatFilePacket(
|
||||
fileName: "img_20260725_105708_1CC2760D-76AA-40C3-8013-C7FAA6C2EF99.jpg",
|
||||
fileSize: UInt64(content.count),
|
||||
mimeType: "image/jpeg",
|
||||
content: content
|
||||
)
|
||||
let payload = try #require(file.encode())
|
||||
|
||||
#expect(handler.handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_234)
|
||||
))
|
||||
|
||||
#expect(recorder.quotaReservations.isEmpty)
|
||||
#expect(recorder.saveCalls.isEmpty)
|
||||
#expect(recorder.lastSeenUpdates.isEmpty)
|
||||
#expect(recorder.deliveryAcks.isEmpty)
|
||||
#expect(recorder.deliveredMessages.isEmpty)
|
||||
|
||||
// Unblocking must allow a retry through; the blocked attempt cannot
|
||||
// poison the stable-ID dedup reservation.
|
||||
recorder.blockedPeers = []
|
||||
#expect(handler.handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_235)
|
||||
))
|
||||
#expect(recorder.saveCalls.count == 1)
|
||||
#expect(recorder.deliveredMessages.count == 1)
|
||||
#expect(recorder.deliveryAcks.count == 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
func decryptedPrivateFileOverPayloadCapIsRejectedBeforeQuotaOrDiskWrite() {
|
||||
let recorder = Recorder()
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let oversizedCount = FileTransferLimits.maxPayloadBytes + 1
|
||||
var length = UInt32(oversizedCount).bigEndian
|
||||
var payload = Data([0x04]) // BitchatFilePacket CONTENT TLV
|
||||
withUnsafeBytes(of: &length) { payload.append(contentsOf: $0) }
|
||||
payload.append(Data(repeating: 0x41, count: oversizedCount))
|
||||
|
||||
#expect(!handler.handlePrivatePayload(
|
||||
payload,
|
||||
from: remotePeerID,
|
||||
timestamp: Date(timeIntervalSince1970: 1_234)
|
||||
))
|
||||
|
||||
#expect(recorder.quotaReservations.isEmpty)
|
||||
#expect(recorder.saveCalls.isEmpty)
|
||||
#expect(recorder.lastSeenUpdates.isEmpty)
|
||||
#expect(recorder.deliveryAcks.isEmpty)
|
||||
#expect(recorder.deliveredMessages.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func malformedPayloadIsTrackedForSyncButDropped() {
|
||||
let recorder = Recorder()
|
||||
@@ -294,7 +753,7 @@ struct BLEFileTransferHandlerTests {
|
||||
recipientID: nil,
|
||||
timestamp: 900_000,
|
||||
payload: Data([0x01, 0x02, 0x03]),
|
||||
signature: nil,
|
||||
signature: Data(repeating: 0x5A, count: 64),
|
||||
ttl: TransportConfig.messageTTLDefault
|
||||
)
|
||||
|
||||
@@ -410,6 +869,33 @@ struct BLEFileTransferHandlerTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func panicWipeClearsCachedPrivateMediaReceiptDecisions() throws {
|
||||
let base = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(
|
||||
"panic-receipt-cache-\(UUID().uuidString)",
|
||||
isDirectory: true
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: base) }
|
||||
let messageID = "media-00112233445566778899aabbccddeeff"
|
||||
|
||||
let seed = BLEPrivateMediaReceiptStore(baseDirectory: base)
|
||||
#expect(seed.recordDeleted(messageID: messageID))
|
||||
|
||||
let store = BLEIncomingFileStore(baseDirectory: base)
|
||||
#expect(
|
||||
store.privateMediaReceiptState(messageID: messageID)
|
||||
== .tombstoned
|
||||
)
|
||||
|
||||
try store.panicWipe()
|
||||
|
||||
#expect(
|
||||
store.privateMediaReceiptState(messageID: messageID)
|
||||
== .absent
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func panicWipeAttemptsDeletionWhenMarkerPersistenceFails() throws {
|
||||
enum MarkerFailure: Error { case unavailable }
|
||||
@@ -529,7 +1015,8 @@ struct BLEFileTransferHandlerTests {
|
||||
content: Data,
|
||||
ttl: UInt8 = TransportConfig.messageTTLDefault,
|
||||
recipientID: Data? = nil,
|
||||
fileName: String = "sample"
|
||||
fileName: String = "sample",
|
||||
hasSignature: Bool = true
|
||||
) throws -> BitchatPacket {
|
||||
let filePacket = BitchatFilePacket(
|
||||
fileName: fileName,
|
||||
@@ -544,7 +1031,7 @@ struct BLEFileTransferHandlerTests {
|
||||
recipientID: recipientID,
|
||||
timestamp: 900_000,
|
||||
payload: payload,
|
||||
signature: nil,
|
||||
signature: hasSignature ? Data(repeating: 0x5A, count: 64) : nil,
|
||||
ttl: ttl
|
||||
)
|
||||
}
|
||||
|
||||
@@ -117,6 +117,35 @@ struct BLEFragmentAssemblyBufferTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func encryptedPrivateFileAssemblyGetsFramedFileHeadroom() throws {
|
||||
var buffer = BLEFragmentAssemblyBuffer()
|
||||
let fragmentID = Data(repeating: 0x15, count: 8)
|
||||
let first = try #require(BLEFragmentHeader(packet: makeFragmentPacket(
|
||||
fragmentID: fragmentID,
|
||||
index: 0,
|
||||
total: 2,
|
||||
originalType: MessageType.noiseEncrypted.rawValue,
|
||||
fragmentData: Data(repeating: 0x01, count: FileTransferLimits.maxPayloadBytes)
|
||||
)))
|
||||
let second = try #require(BLEFragmentHeader(packet: makeFragmentPacket(
|
||||
fragmentID: fragmentID,
|
||||
index: 1,
|
||||
total: 2,
|
||||
originalType: MessageType.noiseEncrypted.rawValue,
|
||||
fragmentData: Data([0x02])
|
||||
)))
|
||||
|
||||
_ = buffer.append(first, maxInFlightAssemblies: 8)
|
||||
let result = buffer.append(second, maxInFlightAssemblies: 8)
|
||||
|
||||
if case let .complete(_, data, _) = result {
|
||||
#expect(data.count == FileTransferLimits.maxPayloadBytes + 1)
|
||||
} else {
|
||||
Issue.record("Expected encrypted private-file assembly to use framed-file limit")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func removeExpiredDropsOldAssemblies() throws {
|
||||
var buffer = BLEFragmentAssemblyBuffer()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,6 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import BitFoundation
|
||||
@testable import bitchat
|
||||
|
||||
struct BLENoisePayloadFactoryTests {
|
||||
@@ -31,4 +32,63 @@ struct BLENoisePayloadFactoryTests {
|
||||
|
||||
#expect(payload == Data([NoisePayloadType.verifyChallenge.rawValue, 0xCA, 0xFE]))
|
||||
}
|
||||
|
||||
@Test
|
||||
func privateFilePayloadPrefixesCanonicalFilePacket() throws {
|
||||
let content = Data("%PDF-secret".utf8)
|
||||
let file = BitchatFilePacket(
|
||||
fileName: "secret.pdf",
|
||||
fileSize: UInt64(content.count),
|
||||
mimeType: "application/pdf",
|
||||
content: content
|
||||
)
|
||||
|
||||
let payload = try #require(BLENoisePayloadFactory.privateFile(file))
|
||||
|
||||
#expect(payload.first == 0x20, "Encrypted files must use Android's deployed wire value")
|
||||
let decoded = try #require(BitchatFilePacket.decode(Data(payload.dropFirst())))
|
||||
#expect(decoded.fileName == "secret.pdf")
|
||||
#expect(decoded.mimeType == "application/pdf")
|
||||
#expect(decoded.content == content)
|
||||
}
|
||||
|
||||
@Test
|
||||
func androidB7f0b33PrivateFilePlaintextFixtureIsByteCompatible() throws {
|
||||
// Runtime-emitted by Android commit b7f0b33d from
|
||||
// BitchatFilePacket("a.txt", 3, "text/plain", [01, 02, 03]) and
|
||||
// NoisePayload(type = FILE_TRANSFER, data = file.encode()).encode().
|
||||
let fixtureHex = "20010005612e7478740200040000000303000a746578742f706c61696e0400000003010203"
|
||||
let fixture = try #require(Data(hexString: fixtureHex))
|
||||
|
||||
let typed = try #require(NoisePayload.decode(fixture))
|
||||
#expect(typed.type == .privateFile)
|
||||
let file = try #require(BitchatFilePacket.decode(typed.data))
|
||||
#expect(file.fileName == "a.txt")
|
||||
#expect(file.fileSize == 3)
|
||||
#expect(file.mimeType == "text/plain")
|
||||
#expect(file.content == Data([0x01, 0x02, 0x03]))
|
||||
#expect(BLENoisePayloadFactory.privateFile(file) == fixture)
|
||||
}
|
||||
|
||||
@Test
|
||||
func prereleasePrivateFileTypeCanonicalizesOnDecode() throws {
|
||||
let encoded = Data([NoisePayloadType.prereleasePrivateFileRawValue, 0xCA, 0xFE])
|
||||
let decoded = try #require(NoisePayload.decode(encoded))
|
||||
|
||||
#expect(decoded.type == .privateFile)
|
||||
#expect(decoded.data == Data([0xCA, 0xFE]))
|
||||
#expect(decoded.encode().first == 0x20)
|
||||
}
|
||||
|
||||
@Test
|
||||
func authenticatedPeerStateUsesPermanent0x21Type() throws {
|
||||
let state = AuthenticatedPeerStatePacket(
|
||||
capabilities: .privateMedia,
|
||||
signingPublicKey: Data(repeating: 0x77, count: 32)
|
||||
)
|
||||
let encoded = try #require(BLENoisePayloadFactory.authenticatedPeerState(state))
|
||||
|
||||
#expect(encoded.first == 0x21)
|
||||
#expect(AuthenticatedPeerStatePacket.decode(from: Data(encoded.dropFirst())) == state)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import BitFoundation
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import bitchat
|
||||
|
||||
@Suite("BLE Noise reconnect policy")
|
||||
struct BLENoiseReconnectPolicyTests {
|
||||
@Test("Revalidation requires a cached session and no authenticated link")
|
||||
func revalidationPreconditions() {
|
||||
var policy = BLENoiseReconnectPolicy()
|
||||
let link = BLEIngressLinkID.peripheral("peripheral-a")
|
||||
let now = Date(timeIntervalSince1970: 1_000)
|
||||
|
||||
let withoutSession = policy.shouldRevalidate(
|
||||
on: link,
|
||||
hasEstablishedSession: false,
|
||||
isNoiseAuthenticatedLink: false,
|
||||
hasAuthenticatedPeerLink: false,
|
||||
now: now
|
||||
)
|
||||
#expect(!withoutSession)
|
||||
let authenticated = policy.shouldRevalidate(
|
||||
on: link,
|
||||
hasEstablishedSession: true,
|
||||
isNoiseAuthenticatedLink: true,
|
||||
hasAuthenticatedPeerLink: true,
|
||||
now: now
|
||||
)
|
||||
#expect(!authenticated)
|
||||
let eligible = policy.shouldRevalidate(
|
||||
on: link,
|
||||
hasEstablishedSession: true,
|
||||
isNoiseAuthenticatedLink: false,
|
||||
hasAuthenticatedPeerLink: false,
|
||||
now: now
|
||||
)
|
||||
#expect(eligible)
|
||||
}
|
||||
|
||||
@Test("Revalidation is once per link epoch or after sixty seconds")
|
||||
func revalidationIsBoundPerLinkEpoch() {
|
||||
var policy = BLENoiseReconnectPolicy()
|
||||
let link = BLEIngressLinkID.central("central-a")
|
||||
let start = Date(timeIntervalSince1970: 2_000)
|
||||
|
||||
let initial = policy.shouldRevalidate(
|
||||
on: link,
|
||||
hasEstablishedSession: true,
|
||||
isNoiseAuthenticatedLink: false,
|
||||
hasAuthenticatedPeerLink: false,
|
||||
now: start
|
||||
)
|
||||
#expect(initial)
|
||||
let duringCooldown = policy.shouldRevalidate(
|
||||
on: link,
|
||||
hasEstablishedSession: true,
|
||||
isNoiseAuthenticatedLink: false,
|
||||
hasAuthenticatedPeerLink: false,
|
||||
now: start.addingTimeInterval(59.999)
|
||||
)
|
||||
#expect(!duringCooldown)
|
||||
let afterCooldown = policy.shouldRevalidate(
|
||||
on: link,
|
||||
hasEstablishedSession: true,
|
||||
isNoiseAuthenticatedLink: false,
|
||||
hasAuthenticatedPeerLink: false,
|
||||
now: start.addingTimeInterval(60)
|
||||
)
|
||||
#expect(afterCooldown)
|
||||
|
||||
policy.endLinkEpoch(link)
|
||||
let nextEpoch = policy.shouldRevalidate(
|
||||
on: link,
|
||||
hasEstablishedSession: true,
|
||||
isNoiseAuthenticatedLink: false,
|
||||
hasAuthenticatedPeerLink: false,
|
||||
now: start.addingTimeInterval(60.001)
|
||||
)
|
||||
#expect(nextEpoch)
|
||||
}
|
||||
|
||||
@Test("An authenticated sibling suppresses redundant reconnect")
|
||||
func authenticatedSiblingSuppressesReconnect() {
|
||||
var policy = BLENoiseReconnectPolicy()
|
||||
let link = BLEIngressLinkID.peripheral("unproven-sibling")
|
||||
let start = Date(timeIntervalSince1970: 3_000)
|
||||
|
||||
let suppressed = policy.shouldRevalidate(
|
||||
on: link,
|
||||
hasEstablishedSession: true,
|
||||
isNoiseAuthenticatedLink: false,
|
||||
hasAuthenticatedPeerLink: true,
|
||||
now: start
|
||||
)
|
||||
#expect(!suppressed)
|
||||
let eligible = policy.shouldRevalidate(
|
||||
on: link,
|
||||
hasEstablishedSession: true,
|
||||
isNoiseAuthenticatedLink: false,
|
||||
hasAuthenticatedPeerLink: false,
|
||||
now: start
|
||||
)
|
||||
#expect(eligible)
|
||||
}
|
||||
|
||||
@Test("Reserved replacement bit is not advertised")
|
||||
func reservedReplacementBitIsNotAdvertised() {
|
||||
#expect(
|
||||
!PeerCapabilities.localSupported.contains(
|
||||
.nonDestructiveNoiseReplacement
|
||||
)
|
||||
)
|
||||
#expect(PeerCapabilities.localSupported.contains(.privateMedia))
|
||||
#expect(
|
||||
PeerCapabilities.localSupported.contains(.privateMediaReceipts)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,10 @@ struct BLENoiseSessionQueuesTests {
|
||||
queues.appendTypedPayload(Data([0x01]), for: peerID)
|
||||
queues.appendTypedPayload(Data([0x02]), for: peerID)
|
||||
|
||||
#expect(queues.takeTypedPayloads(for: peerID) == [Data([0x01]), Data([0x02])])
|
||||
#expect(queues.takeTypedPayloads(for: peerID) == [
|
||||
BLEPendingTypedPayload(payload: Data([0x01]), transferId: nil),
|
||||
BLEPendingTypedPayload(payload: Data([0x02]), transferId: nil)
|
||||
])
|
||||
#expect(queues.takeTypedPayloads(for: peerID).isEmpty)
|
||||
#expect(queues.takePrivateMessages(for: peerID).map(\.messageID) == ["m1"])
|
||||
}
|
||||
@@ -64,4 +67,21 @@ struct BLENoiseSessionQueuesTests {
|
||||
|
||||
#expect(queues.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func transferIDSurvivesHandshakeQueueAndCanBeCancelledBeforeDrain() {
|
||||
let peerID = PeerID(str: "aaaaaaaaaaaaaaaa")
|
||||
var queues = BLENoiseSessionQueues()
|
||||
|
||||
queues.appendTypedPayload(Data([0x20, 0xAA]), transferId: "media-1", for: peerID)
|
||||
queues.appendTypedPayload(Data([0x01, 0xBB]), for: peerID)
|
||||
|
||||
let removed = queues.removeTypedPayload(transferId: "media-1")
|
||||
let removedAgain = queues.removeTypedPayload(transferId: "media-1")
|
||||
#expect(removed)
|
||||
#expect(!removedAgain)
|
||||
#expect(queues.takeTypedPayloads(for: peerID) == [
|
||||
BLEPendingTypedPayload(payload: Data([0x01, 0xBB]), transferId: nil)
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,6 +108,58 @@ struct BLEOutboundFragmentPlannerTests {
|
||||
) == nil)
|
||||
}
|
||||
|
||||
@Test("private media v1 accepts exactly 256 fragments and rejects 257")
|
||||
func privateMediaCrossPlatformFragmentBoundary() throws {
|
||||
let maxPayload = makePayload(count: 160 * 1024, seed: 0xFACE_CAFE)
|
||||
|
||||
func plan(payloadCount: Int) throws -> BLEOutboundFragmentPlan {
|
||||
let packet = BitchatPacket(
|
||||
type: MessageType.noiseEncrypted.rawValue,
|
||||
senderID: Data(hexString: "0011223344556677") ?? Data(),
|
||||
recipientID: Data(hexString: "8877665544332211"),
|
||||
timestamp: 0x0102030405,
|
||||
payload: Data(maxPayload.prefix(payloadCount)),
|
||||
signature: nil,
|
||||
ttl: 3,
|
||||
version: 2
|
||||
)
|
||||
return try #require(BLEOutboundFragmentPlanner.makePlan(
|
||||
for: BLEOutboundFragmentTransferRequest(
|
||||
packet: packet,
|
||||
pad: false,
|
||||
maxChunk: nil,
|
||||
directedPeer: PeerID(str: "8877665544332211"),
|
||||
transferId: "boundary"
|
||||
),
|
||||
defaultChunkSize: TransportConfig.bleDefaultFragmentSize,
|
||||
bleMaxMTU: 512,
|
||||
fragmentID: Data(repeating: 0xD4, count: 8)
|
||||
))
|
||||
}
|
||||
|
||||
func firstPlan(withAtLeast target: Int) throws -> BLEOutboundFragmentPlan {
|
||||
var low = 1
|
||||
var high = maxPayload.count
|
||||
while low < high {
|
||||
let mid = low + (high - low) / 2
|
||||
if try plan(payloadCount: mid).totalFragments >= target {
|
||||
high = mid
|
||||
} else {
|
||||
low = mid + 1
|
||||
}
|
||||
}
|
||||
return try plan(payloadCount: low)
|
||||
}
|
||||
|
||||
let at256 = try firstPlan(withAtLeast: 256)
|
||||
let at257 = try firstPlan(withAtLeast: 257)
|
||||
|
||||
#expect(at256.totalFragments == 256)
|
||||
#expect(BLEOutboundFragmentPlanner.isPrivateMediaV1Compatible(at256))
|
||||
#expect(at257.totalFragments == 257)
|
||||
#expect(!BLEOutboundFragmentPlanner.isPrivateMediaV1Compatible(at257))
|
||||
}
|
||||
|
||||
private func makePacket(
|
||||
payload: Data,
|
||||
route: [Data]? = nil,
|
||||
|
||||
@@ -20,6 +20,24 @@ struct BLEOutboundFragmentTransferSchedulerTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func explicitTransferIDReservesEncryptedPrivateFileFragments() {
|
||||
var scheduler = BLEOutboundFragmentTransferScheduler()
|
||||
let request = makeRequest(
|
||||
type: MessageType.noiseEncrypted.rawValue,
|
||||
transferId: "private-media"
|
||||
)
|
||||
|
||||
let result = scheduler.submit(request, maxConcurrentTransfers: 1)
|
||||
|
||||
if case let .start(_, reservedTransferId) = result {
|
||||
#expect(reservedTransferId == "private-media")
|
||||
#expect(scheduler.activeCount == 1)
|
||||
} else {
|
||||
Issue.record("Expected encrypted private media to reserve its progress slot")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func submitQueuesFileTransferWhenSlotsAreFull() {
|
||||
var scheduler = BLEOutboundFragmentTransferScheduler()
|
||||
|
||||
@@ -42,6 +42,37 @@ struct BLEPeerRegistryTests {
|
||||
#expect(registry.info(for: peerID)?.nickname == "alice-renamed")
|
||||
}
|
||||
|
||||
@Test("registry preserves absent versus explicit empty capabilities")
|
||||
func capabilitiesPresenceIsPreserved() {
|
||||
var registry = BLEPeerRegistry()
|
||||
let oldPeer = PeerID(str: "1122334455667788")
|
||||
let modernPeer = PeerID(str: "8877665544332211")
|
||||
|
||||
_ = registry.upsertVerifiedAnnounce(
|
||||
peerID: oldPeer,
|
||||
nickname: "old",
|
||||
noisePublicKey: Data(repeating: 0x11, count: 32),
|
||||
signingPublicKey: Data(repeating: 0x12, count: 32),
|
||||
isConnected: true,
|
||||
now: Date(),
|
||||
capabilities: nil
|
||||
)
|
||||
_ = registry.upsertVerifiedAnnounce(
|
||||
peerID: modernPeer,
|
||||
nickname: "modern",
|
||||
noisePublicKey: Data(repeating: 0x21, count: 32),
|
||||
signingPublicKey: Data(repeating: 0x22, count: 32),
|
||||
isConnected: true,
|
||||
now: Date(),
|
||||
capabilities: []
|
||||
)
|
||||
|
||||
#expect(registry.capabilities(for: oldPeer).isEmpty)
|
||||
#expect(!registry.capabilitiesWereExplicitlyAdvertised(for: oldPeer))
|
||||
#expect(registry.capabilities(for: modernPeer).isEmpty)
|
||||
#expect(registry.capabilitiesWereExplicitlyAdvertised(for: modernPeer))
|
||||
}
|
||||
|
||||
@Test("reachability keeps recent verified offline peers only when mesh is attached")
|
||||
func reachabilityRequiresMeshAttachmentForOfflinePeers() {
|
||||
let offlinePeer = PeerID(str: "1122334455667788")
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import bitchat
|
||||
|
||||
struct BLEPrivateMediaReceiptStoreTests {
|
||||
private struct TestError: Error {}
|
||||
|
||||
private let messageID = "media-00112233445566778899aabbccddeeff"
|
||||
|
||||
@Test
|
||||
func acceptedReceiptPersistsAcrossStoreInstances() throws {
|
||||
let root = makeRoot("persist")
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let payload = try makePayload(in: root)
|
||||
|
||||
let first = BLEPrivateMediaReceiptStore(baseDirectory: root)
|
||||
#expect(first.commitAccepted(messageID: messageID, storedURL: payload))
|
||||
#expect(first.state(for: messageID) == .accepted(payload))
|
||||
|
||||
let relaunched = BLEPrivateMediaReceiptStore(baseDirectory: root)
|
||||
#expect(relaunched.state(for: messageID) == .accepted(payload))
|
||||
}
|
||||
|
||||
@Test
|
||||
func directoryEnumerationFailureIsUnavailableAndRetriesWithoutCachingEmpty() throws {
|
||||
let root = makeRoot("list-failure")
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let payload = try makePayload(in: root)
|
||||
#expect(BLEPrivateMediaReceiptStore(baseDirectory: root).commitAccepted(
|
||||
messageID: messageID,
|
||||
storedURL: payload
|
||||
))
|
||||
let record = receiptRecord(in: root)
|
||||
#expect(FileManager.default.fileExists(atPath: record.path))
|
||||
|
||||
var shouldFail = true
|
||||
let store = BLEPrivateMediaReceiptStore(
|
||||
baseDirectory: root,
|
||||
directoryReader: { directory in
|
||||
if shouldFail {
|
||||
shouldFail = false
|
||||
throw TestError()
|
||||
}
|
||||
return try FileManager.default.contentsOfDirectory(
|
||||
at: directory,
|
||||
includingPropertiesForKeys: nil
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
#expect(store.state(for: messageID) == .unavailable)
|
||||
#expect(FileManager.default.fileExists(atPath: record.path))
|
||||
#expect(store.state(for: messageID) == .accepted(payload))
|
||||
}
|
||||
|
||||
@Test
|
||||
func recordReadFailureIsUnavailableAndPreservesReceiptForRetry() throws {
|
||||
let root = makeRoot("read-failure")
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let payload = try makePayload(in: root)
|
||||
#expect(BLEPrivateMediaReceiptStore(baseDirectory: root).commitAccepted(
|
||||
messageID: messageID,
|
||||
storedURL: payload
|
||||
))
|
||||
let record = receiptRecord(in: root)
|
||||
|
||||
var shouldFail = true
|
||||
let store = BLEPrivateMediaReceiptStore(
|
||||
baseDirectory: root,
|
||||
dataReader: { url in
|
||||
if shouldFail {
|
||||
shouldFail = false
|
||||
throw TestError()
|
||||
}
|
||||
return try Data(contentsOf: url)
|
||||
}
|
||||
)
|
||||
|
||||
#expect(store.state(for: messageID) == .unavailable)
|
||||
#expect(FileManager.default.fileExists(atPath: record.path))
|
||||
#expect(store.state(for: messageID) == .accepted(payload))
|
||||
}
|
||||
|
||||
@Test
|
||||
func decodeFailureIsUnavailableAndDoesNotDeleteOrCachePastRepair() throws {
|
||||
let root = makeRoot("decode-failure")
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let payload = try makePayload(in: root)
|
||||
#expect(BLEPrivateMediaReceiptStore(baseDirectory: root).commitAccepted(
|
||||
messageID: messageID,
|
||||
storedURL: payload
|
||||
))
|
||||
let record = receiptRecord(in: root)
|
||||
let durableBytes = try Data(contentsOf: record)
|
||||
let corruptBytes = Data("{not-json".utf8)
|
||||
try corruptBytes.write(to: record, options: .atomic)
|
||||
|
||||
let store = BLEPrivateMediaReceiptStore(baseDirectory: root)
|
||||
#expect(store.state(for: messageID) == .unavailable)
|
||||
#expect(!store.commitAccepted(messageID: messageID, storedURL: payload))
|
||||
#expect(FileManager.default.fileExists(atPath: record.path))
|
||||
#expect(try Data(contentsOf: record) == corruptBytes)
|
||||
|
||||
try durableBytes.write(to: record, options: .atomic)
|
||||
#expect(store.state(for: messageID) == .accepted(payload))
|
||||
}
|
||||
|
||||
@Test
|
||||
func unreadableTombstoneNeverBecomesAbsentOrGetsDeleted() throws {
|
||||
let root = makeRoot("tombstone-decode")
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let payload = try makePayload(in: root)
|
||||
let seed = BLEPrivateMediaReceiptStore(baseDirectory: root)
|
||||
#expect(seed.commitAccepted(messageID: messageID, storedURL: payload))
|
||||
#expect(seed.recordDeleted(messageID: messageID))
|
||||
#expect(!FileManager.default.fileExists(atPath: payload.path))
|
||||
|
||||
let record = receiptRecord(in: root)
|
||||
let durableBytes = try Data(contentsOf: record)
|
||||
try Data([0xFF, 0x00, 0x7B]).write(to: record, options: .atomic)
|
||||
|
||||
let relaunched = BLEPrivateMediaReceiptStore(baseDirectory: root)
|
||||
#expect(relaunched.state(for: messageID) == .unavailable)
|
||||
#expect(FileManager.default.fileExists(atPath: record.path))
|
||||
|
||||
try durableBytes.write(to: record, options: .atomic)
|
||||
#expect(relaunched.state(for: messageID) == .tombstoned)
|
||||
}
|
||||
|
||||
@Test
|
||||
func failedTombstonePersistenceDoesNotPoisonVolatileState() throws {
|
||||
let root = makeRoot("failed-tombstone-write")
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let store = BLEPrivateMediaReceiptStore(baseDirectory: root)
|
||||
#expect(store.state(for: messageID) == .absent)
|
||||
|
||||
// Force the atomic record write itself to fail after the store has
|
||||
// successfully loaded its empty index.
|
||||
let record = receiptRecord(in: root)
|
||||
try FileManager.default.createDirectory(
|
||||
at: record,
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
#expect(!store.recordDeleted(messageID: messageID))
|
||||
try FileManager.default.removeItem(at: record)
|
||||
|
||||
// The UI must be able to report the deletion failure without a
|
||||
// process-lifetime tombstone silently hiding a later retry.
|
||||
#expect(store.state(for: messageID) == .absent)
|
||||
}
|
||||
|
||||
@Test
|
||||
func unreleasedAggregateLedgerIsIgnoredAndLeftUntouched() throws {
|
||||
let root = makeRoot("no-legacy-migration")
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let files = root.appendingPathComponent("files", isDirectory: true)
|
||||
try FileManager.default.createDirectory(
|
||||
at: files,
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
let legacy = files.appendingPathComponent(
|
||||
".private-media-receipts.json",
|
||||
isDirectory: false
|
||||
)
|
||||
let bytes = Data(
|
||||
#"{"entries":{"media-00112233445566778899aabbccddeeff":{"relativePath":"images/incoming/old.jpg","acceptedAt":0}}}"#
|
||||
.utf8
|
||||
)
|
||||
try bytes.write(to: legacy, options: .atomic)
|
||||
|
||||
let store = BLEPrivateMediaReceiptStore(baseDirectory: root)
|
||||
#expect(store.state(for: messageID) == .absent)
|
||||
#expect(try Data(contentsOf: legacy) == bytes)
|
||||
}
|
||||
|
||||
private func makeRoot(_ label: String) -> URL {
|
||||
FileManager.default.temporaryDirectory.appendingPathComponent(
|
||||
"private-media-receipt-\(label)-\(UUID().uuidString)",
|
||||
isDirectory: true
|
||||
)
|
||||
}
|
||||
|
||||
private func makePayload(in root: URL) throws -> URL {
|
||||
let directory = root.appendingPathComponent(
|
||||
"files/images/incoming",
|
||||
isDirectory: true
|
||||
)
|
||||
try FileManager.default.createDirectory(
|
||||
at: directory,
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
let payload = directory.appendingPathComponent("image.jpg")
|
||||
try Data([0xFF, 0xD8, 0xFF, 0xD9]).write(to: payload)
|
||||
return payload
|
||||
}
|
||||
|
||||
private func receiptRecord(in root: URL) -> URL {
|
||||
root
|
||||
.appendingPathComponent(
|
||||
"files/.private-media-receipts",
|
||||
isDirectory: true
|
||||
)
|
||||
.appendingPathComponent(messageID)
|
||||
.appendingPathExtension("json")
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -399,6 +399,59 @@ final class SecureIdentityStateManagerTests: XCTestCase {
|
||||
XCTAssertTrue(cleared)
|
||||
}
|
||||
|
||||
func test_privateMediaCapabilityPinPersistsMonotonicallyAndPanicClearRemovesIt() async {
|
||||
let keychain = MockKeychain()
|
||||
let fingerprint = Data(repeating: 0x42, count: 32).sha256Fingerprint()
|
||||
let manager = SecureIdentityStateManager(keychain)
|
||||
|
||||
XCTAssertFalse(manager.hasObservedPrivateMediaCapability(fingerprint: fingerprint))
|
||||
manager.markPrivateMediaCapable(fingerprint: fingerprint)
|
||||
XCTAssertTrue(
|
||||
manager.hasObservedPrivateMediaCapability(fingerprint: fingerprint),
|
||||
"pin insertion must be synchronously visible to the next downgrade decision"
|
||||
)
|
||||
|
||||
// Re-marking is idempotent, and the encrypted cache carries the pin
|
||||
// across launches.
|
||||
manager.markPrivateMediaCapable(fingerprint: fingerprint)
|
||||
manager.forceSave()
|
||||
let reloaded = SecureIdentityStateManager(keychain)
|
||||
XCTAssertTrue(reloaded.hasObservedPrivateMediaCapability(fingerprint: fingerprint))
|
||||
|
||||
// ChatViewModel's panic path calls this same wipe after deleting
|
||||
// keychain data; the in-memory pin must disappear immediately too.
|
||||
reloaded.clearAllIdentityData()
|
||||
let cleared = await waitUntil {
|
||||
!reloaded.hasObservedPrivateMediaCapability(fingerprint: fingerprint)
|
||||
}
|
||||
XCTAssertTrue(cleared)
|
||||
}
|
||||
|
||||
func test_noiseAuthenticatedSigningKeyBindingPersistsAndPanicClearRemovesIt() async {
|
||||
let keychain = MockKeychain()
|
||||
let fingerprint = Data(repeating: 0x31, count: 32).sha256Fingerprint()
|
||||
let firstKey = Data(repeating: 0x41, count: 32)
|
||||
let rotatedKey = Data(repeating: 0x42, count: 32)
|
||||
let manager = SecureIdentityStateManager(keychain)
|
||||
|
||||
manager.bindAuthenticatedSigningPublicKey(firstKey, fingerprint: fingerprint)
|
||||
XCTAssertEqual(manager.authenticatedSigningPublicKey(forFingerprint: fingerprint), firstKey)
|
||||
// A later authenticated Noise session may legitimately rotate the
|
||||
// announcement signing key.
|
||||
manager.bindAuthenticatedSigningPublicKey(rotatedKey, fingerprint: fingerprint)
|
||||
XCTAssertEqual(manager.authenticatedSigningPublicKey(forFingerprint: fingerprint), rotatedKey)
|
||||
|
||||
manager.forceSave()
|
||||
let reloaded = SecureIdentityStateManager(keychain)
|
||||
XCTAssertEqual(reloaded.authenticatedSigningPublicKey(forFingerprint: fingerprint), rotatedKey)
|
||||
|
||||
reloaded.clearAllIdentityData()
|
||||
let cleared = await waitUntil {
|
||||
reloaded.authenticatedSigningPublicKey(forFingerprint: fingerprint) == nil
|
||||
}
|
||||
XCTAssertTrue(cleared)
|
||||
}
|
||||
|
||||
func test_forceSave_withFailingCacheWriteDoesNotPersistCache() async {
|
||||
let keychain = FailingCacheSaveKeychain()
|
||||
let manager = SecureIdentityStateManager(keychain)
|
||||
|
||||
@@ -49,7 +49,7 @@ struct TransferProgressManagerTests {
|
||||
recorder.append("updated:\(id):\(sent):\(total)")
|
||||
case .completed(let id, let total):
|
||||
recorder.append("completed:\(id):\(total)")
|
||||
case .cancelled:
|
||||
case .cancelled, .rejected:
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ struct TransferProgressManagerTests {
|
||||
recorder.append("started:\(id):\(total)")
|
||||
case .cancelled(let id, let sent, let total):
|
||||
recorder.append("cancelled:\(id):\(sent):\(total)")
|
||||
case .updated, .completed:
|
||||
case .updated, .completed, .rejected:
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -105,6 +105,28 @@ struct TransferProgressManagerTests {
|
||||
#expect(manager.snapshot(id: transferID) == nil)
|
||||
_ = cancellable
|
||||
}
|
||||
|
||||
@Test("Preflight policy rejection publishes a visible failure reason")
|
||||
@MainActor
|
||||
func rejectBeforeStartPublishesReason() async {
|
||||
let manager = TransferProgressManager()
|
||||
let transferID = "transfer-visible-reject"
|
||||
let recorder = EventRecorder()
|
||||
let cancellable = manager.publisher.sink { event in
|
||||
if case .rejected(let id, let reason) = event {
|
||||
recorder.append("rejected:\(id):\(reason)")
|
||||
}
|
||||
}
|
||||
|
||||
manager.rejectBeforeStart(id: transferID, reason: "upgrade required")
|
||||
|
||||
let didReceive = await TestHelpers.waitUntil({
|
||||
recorder.values == ["rejected:\(transferID):upgrade required"]
|
||||
}, timeout: 5.0)
|
||||
#expect(didReceive)
|
||||
#expect(manager.snapshot(id: transferID) == nil)
|
||||
_ = cancellable
|
||||
}
|
||||
}
|
||||
|
||||
private final class EventRecorder: @unchecked Sendable {
|
||||
|
||||
@@ -266,6 +266,11 @@ private final class TestIdentityManager: SecureIdentityStateManagerProtocol {
|
||||
verified.removeAll()
|
||||
}
|
||||
|
||||
func markPrivateMediaCapable(fingerprint: String) {}
|
||||
func hasObservedPrivateMediaCapability(fingerprint: String) -> Bool { false }
|
||||
func bindAuthenticatedSigningPublicKey(_ signingPublicKey: Data, fingerprint: String) {}
|
||||
func authenticatedSigningPublicKey(forFingerprint fingerprint: String) -> Data? { nil }
|
||||
|
||||
func removeEphemeralSession(peerID: PeerID) {}
|
||||
|
||||
func setVerified(fingerprint: String, verified: Bool) {
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
# Private-media wire migration
|
||||
|
||||
Private files use the `BitchatFilePacket` TLV shared by iOS and Android. The
|
||||
preferred direct-message wire form encrypts that complete TLV inside the
|
||||
peer's Noise session before BLE fragmentation.
|
||||
|
||||
## Wire values and capability
|
||||
|
||||
- `NoisePayloadType.privateFile` is `0x20`, the value already deployed by the
|
||||
Android client. New sends must use this value.
|
||||
- iOS temporarily accepts `0x09`, which appeared in prerelease builds of the
|
||||
private-media change. Decoders canonicalize it to `privateFile`; they never
|
||||
emit it.
|
||||
- `NoisePayloadType.authenticatedPeerState` is permanently assigned `0x21`.
|
||||
It is emitted after every completed/rekeyed Noise XX session and echoed at
|
||||
most once when the remote state arrives, so message-3/proof reordering over
|
||||
different mesh links converges. This type is part of the protocol security
|
||||
boundary and is not removed when the media migration ends.
|
||||
- The `0x21` payload starts with version `0x01`, followed by one-byte
|
||||
type/length/value fields. Version 1 requires canonical TLV `0x01` (the
|
||||
minimal little-endian `PeerCapabilities` bitfield, 1-8 bytes) and TLV `0x02`
|
||||
(the 32-byte Ed25519 announcement signing key). Duplicate required fields,
|
||||
non-minimal capabilities, malformed lengths, missing fields, and unknown
|
||||
versions are ignored without changing state. Unknown TLVs are skipped.
|
||||
- The public `PeerCapabilities.privateMedia` announce bit is a discovery hint:
|
||||
it starts a Noise handshake, but never selects encrypted sending or creates
|
||||
a pin. A private transfer waits boundedly for the exact session's encrypted
|
||||
`0x21`. A valid bit-8 proof selects Noise `0x20`; a valid no-bit proof or a
|
||||
no-proof timeout reaches the explicit legacy-consent path for an unpinned
|
||||
peer. No timeout automatically sends raw bytes.
|
||||
- `PeerCapabilities.privateMediaReceipts` is bit 9. Its exact-session
|
||||
authenticated proof enables bounded sender-side automatic retry; a public
|
||||
announce never does. It does not replace bit 8: encrypted `0x20` media from
|
||||
bit-8-only prior iOS clients keeps the same deterministic stable ID and
|
||||
delivery ACK. Receivers durably commit that ID before UI delivery or ACK, so
|
||||
a lost proof followed by a later bit-9 retry cannot create a second,
|
||||
random-ID bubble.
|
||||
- An unpinned peer with a stable Noise key but without that capability is
|
||||
eligible for one signed, directed
|
||||
`fileTransfer`, matching the pre-migration wire form used by older iOS and
|
||||
accepted by current Android clients, only after the sender confirms a
|
||||
per-send warning that the file is not end-to-end encrypted and mesh relays
|
||||
can see it. The
|
||||
consent is consumed by that invocation and is never remembered.
|
||||
- A signed announce never creates a pin by itself: an attacker can copy a
|
||||
victim's public Noise key, supply its own Ed25519 key and capability bits,
|
||||
and self-sign an internally consistent announce. Only successfully
|
||||
decrypted `0x21` state pins the authenticated Noise fingerprint and binds
|
||||
the Ed25519 key used by later announces/public messages. A later valid
|
||||
no-bit `0x21` is treated as a downgrade, and raw fallback is blocked even if
|
||||
a caller presents legacy consent. Public no-bit announces cannot overwrite
|
||||
current session-authenticated state.
|
||||
- During migration, both an absent capabilities TLV and an explicit TLV
|
||||
without `privateMedia` are legacy-eligible when that stable fingerprint is
|
||||
not pinned. This supports clients that added capability advertisement before
|
||||
encrypted media. Neither shape bypasses a previously authenticated pin.
|
||||
|
||||
Older clients decrypt and ignore unknown inner type `0x21`; they do not need to
|
||||
understand it to continue using text or the warned legacy media path. They are
|
||||
never inferred capable merely because the handshake succeeded.
|
||||
|
||||
Removal gates are independent and must not share an arbitrary calendar date:
|
||||
|
||||
- Remove the `0x09` receive alias only after every TestFlight/internal build
|
||||
that emitted it has expired and minimum-supported-client policy excludes it.
|
||||
- Remove the signed directed raw `0x22` fallback only after minimum-supported
|
||||
iOS and Android clients emit authenticated bit-8 `0x21` state and the legacy
|
||||
population has aged out.
|
||||
- Nostr kind `1059` compatibility is a separate envelope migration. Its dual
|
||||
publish/removal gate is not evidence that either BLE compatibility shape can
|
||||
be removed.
|
||||
|
||||
## Security boundary
|
||||
|
||||
The encrypted form provides Noise confidentiality and peer authentication.
|
||||
The fallback is signed and its signature is required on receive, so relays
|
||||
cannot forge its sender or contents. It is not confidential: relays can see
|
||||
the raw file TLV. The UI says this explicitly and asks on every send. A peer
|
||||
without a stable Noise key from a verified registry entry cannot use the
|
||||
fallback. Keep it only for the mixed-version migration, and remove it only
|
||||
after minimum-supported Android and iOS releases emit authenticated bit-8
|
||||
`0x21` state and the legacy population has aged out. Never replace it with an
|
||||
unsigned fallback, persist blanket consent, or send both forms.
|
||||
|
||||
Incoming clients accept all three migration-era shapes:
|
||||
|
||||
| Sender | Inbound form | Result |
|
||||
| --- | --- | --- |
|
||||
| Current Android | Noise `0x20` | Decrypt and deliver |
|
||||
| Prerelease iOS | Noise `0x09` | Decrypt, canonicalize, and deliver |
|
||||
| Older client | Signed directed `fileTransfer` | Verify signature and deliver |
|
||||
| Forged/unsigned raw sender | Directed `fileTransfer` | Reject |
|
||||
|
||||
Panic wipe clears the persistent capability pins together with the rest of
|
||||
the encrypted identity cache.
|
||||
|
||||
This migration path is mesh-Noise-only (BLE and compatible direct mesh links).
|
||||
Nostr private-media transport is unchanged and remains a follow-up. Nostr
|
||||
inbound paths explicitly ignore `0x21`; do not infer the mesh consent fallback
|
||||
or capability-pin semantics for Nostr delivery.
|
||||
|
||||
## Size interoperability
|
||||
|
||||
iOS bounds inbound file content at 1 MiB and applies the expanded allocation
|
||||
budget only after a large Noise ciphertext authenticates to `0x20` or the
|
||||
temporary `0x09` alias. Ordinary Noise messages retain their 64 KiB limit.
|
||||
|
||||
Current Android builds cap each reassembly at 256 fragments. Depending on the
|
||||
negotiated BLE packet size and routing overhead, that is roughly 110-120 KiB,
|
||||
well below iOS's absolute inbound ceiling. Private-media v1 therefore runs the
|
||||
actual route-aware BLE fragment planner before both encrypted and consented
|
||||
legacy sends and rejects any plan above 256 fragments with a visible failure.
|
||||
This fragment-count contract, rather than a guessed byte threshold, stays
|
||||
correct as route overhead changes.
|
||||
@@ -24,6 +24,22 @@ public struct PeerCapabilities: OptionSet, Equatable, Hashable, Sendable {
|
||||
/// (uplink/downlink carriers for mesh-only peers). Advertised alongside
|
||||
/// a `bridgeGeohash` TLV carrying the rendezvous cell.
|
||||
public static let bridge = PeerCapabilities(rawValue: 1 << 7)
|
||||
/// Finalized direct-message media encrypted as Noise payload `0x20`
|
||||
/// before outer BLE fragmentation. Peers that omit this bit require the
|
||||
/// signed directed raw-file migration fallback.
|
||||
public static let privateMedia = PeerCapabilities(rawValue: 1 << 8)
|
||||
/// Stable private-media IDs are durably deduplicated by the receiver and
|
||||
/// correlated delivery/read receipts permit bounded automatic resend.
|
||||
///
|
||||
/// Bit 8 remains the encrypted-media compatibility contract. Bit 9 only
|
||||
/// enables sender-side automatic retry after exact-session proof.
|
||||
public static let privateMediaReceipts =
|
||||
PeerCapabilities(rawValue: 1 << 9)
|
||||
/// Reserved for test builds that briefly advertised non-destructive Noise
|
||||
/// replacement. Current clients intentionally do not advertise or act on
|
||||
/// this bit; keep it decodable so the wire assignment is never reused.
|
||||
public static let nonDestructiveNoiseReplacement =
|
||||
PeerCapabilities(rawValue: 1 << 10)
|
||||
|
||||
/// Minimal little-endian byte encoding; always at least one byte so an
|
||||
/// empty set is distinguishable from an absent TLV.
|
||||
|
||||
@@ -16,11 +16,32 @@ struct PeerCapabilitiesTests {
|
||||
#expect(PeerCapabilities([]).encoded() == Data([0x00]))
|
||||
#expect(PeerCapabilities.prekeys.encoded() == Data([0x01]))
|
||||
#expect(PeerCapabilities.meshDiagnostics.encoded() == Data([0x40]))
|
||||
#expect(PeerCapabilities.privateMedia.encoded() == Data([0x00, 0x01]))
|
||||
|
||||
let high = PeerCapabilities(rawValue: 1 << 9)
|
||||
#expect(high.encoded() == Data([0x00, 0x02]))
|
||||
#expect(
|
||||
PeerCapabilities.privateMediaReceipts.encoded()
|
||||
== Data([0x00, 0x02])
|
||||
)
|
||||
#expect(
|
||||
PeerCapabilities.nonDestructiveNoiseReplacement.encoded()
|
||||
== Data([0x00, 0x04])
|
||||
)
|
||||
|
||||
let all: PeerCapabilities = [.prekeys, .wifiBulk, .gateway, .groups, .board, .vouch, .meshDiagnostics]
|
||||
let high = PeerCapabilities(rawValue: 1 << 11)
|
||||
#expect(high.encoded() == Data([0x00, 0x08]))
|
||||
|
||||
let all: PeerCapabilities = [
|
||||
.prekeys,
|
||||
.wifiBulk,
|
||||
.gateway,
|
||||
.groups,
|
||||
.board,
|
||||
.vouch,
|
||||
.meshDiagnostics,
|
||||
.privateMedia,
|
||||
.privateMediaReceipts,
|
||||
.nonDestructiveNoiseReplacement
|
||||
]
|
||||
#expect(PeerCapabilities(encoded: all.encoded()) == all)
|
||||
#expect(PeerCapabilities(encoded: high.encoded()) == high)
|
||||
#expect(PeerCapabilities(encoded: PeerCapabilities([]).encoded()) == [])
|
||||
|
||||
Reference in New Issue
Block a user