From 72c1b6a7199ebb304e1a20dfddd2d6cfd4ec388c Mon Sep 17 00:00:00 2001 From: jack <212554440+jackjackbits@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:03:12 -1000 Subject: [PATCH] Prep 2.0.0 App Store submission (#1962) * Integrate Tier 1 2.0.0 security and reliability fixes (#1941, #1935, #1662) * Add author block controls to Place Feed, Home Feed, and threads * Prep 2.0.0 App Store submission: update Privacy Policy and bump build to 3 * Remove unrelated board calls from PlaceFeedView * Address unaddressed Codex review findings (#1931, #1946, #1961, #1924) * Fix autocorrection callsite in ContentComposerView after #1913/#1870 * Keep channel invite links intact in every language (#1818) * Fence in-flight notifications on panic wipe and drop DM senderName userInfo (#1783) --------- Co-authored-by: jack --- Configs/Release.xcconfig | 2 +- PRIVACY_POLICY.md | 13 +- .../Identity/SecureIdentityStateManager.swift | 19 + bitchat/Localizable.xcstrings | 2 +- bitchat/Nostr/GeoRelayDirectory.swift | 22 +- bitchat/Nostr/NostrRelayInboundRouter.swift | 84 +++- .../Protocols/MessageInteractionCodec.swift | 15 + bitchat/Services/BLE/BLEService+Courier.swift | 19 +- bitchat/Services/BLE/BLEService.swift | 4 +- bitchat/Services/ChannelShare.swift | 19 +- bitchat/Services/Groups/GroupStore.swift | 20 + bitchat/Services/LocalWebOfTrustService.swift | 8 + bitchat/Services/NotificationService.swift | 78 +++- bitchat/Services/PlaceFeedModel.swift | 7 + .../ChatPrivateConversationCoordinator.swift | 93 ++++- .../ChatViewModelBootstrapper.swift | 2 +- bitchat/Views/ContentComposerView.swift | 4 +- bitchat/Views/HomeFeedView.swift | 14 +- bitchat/Views/MessageListView.swift | 4 +- bitchat/Views/PlaceFeedView.swift | 35 ++ bitchat/Views/PlaceThreadSheet.swift | 41 +- bitchatTests/ChannelShareTests.swift | 37 ++ ...eConversationCoordinatorContextTests.swift | 258 ++++++++++++ .../EndToEnd/PrekeyEndToEndTests.swift | 32 ++ bitchatTests/Mocks/MockKeychain.swift | 12 +- .../Nostr/GeoRelayDirectoryTests.swift | 378 ++++++++++++++++++ bitchatTests/PlaceFeedTests.swift | 10 + bitchatTests/Services/GroupStoreTests.swift | 25 ++ .../KeychainTransientReadSafetyTests.swift | 2 - .../Services/NostrRelayManagerTests.swift | 191 +++++++++ .../Services/NotificationServiceTests.swift | 126 +++++- .../Services/Phase1FeaturesTests.swift | 28 ++ docs/privacy-assessment.md | 4 +- localPackages/Arti/Sources/TorManager.swift | 27 +- 34 files changed, 1553 insertions(+), 82 deletions(-) diff --git a/Configs/Release.xcconfig b/Configs/Release.xcconfig index fdb25b51..4ccb75e2 100644 --- a/Configs/Release.xcconfig +++ b/Configs/Release.xcconfig @@ -1,5 +1,5 @@ MARKETING_VERSION = 2.0.0 -CURRENT_PROJECT_VERSION = 2 +CURRENT_PROJECT_VERSION = 3 IPHONEOS_DEPLOYMENT_TARGET = 16.0 MACOSX_DEPLOYMENT_TARGET = 13.0 diff --git a/PRIVACY_POLICY.md b/PRIVACY_POLICY.md index 6b0f5e3e..7f19facf 100644 --- a/PRIVACY_POLICY.md +++ b/PRIVACY_POLICY.md @@ -22,6 +22,8 @@ bitchat is designed for private, account-free communication. This policy describ 2. **Nickname, preferences, and relationships** - Your nickname, settings, favorites, petnames, read-receipt identifiers, and bounded operational metadata are stored locally. + - Your **private following list** for Home Feed (followed Nostr public keys and optional local aliases) is stored locally in the system keychain; bitchat does not publish a public Nostr `kind 3` contact list. + - If you opt in to a **Public Handle**, your chosen display name and bio are stored locally and published as a public Nostr `kind 0` profile event on relays. Public Handle is off by default. - The share extension can retain one item you choose to share in the app-group preferences for up to 24 hours. The app shows the destination and a preview for review; it does not send the item automatically. The item is cleared when you add it to the composer, cancel, panic-wipe, or it expires. 3. **Private group state** @@ -80,10 +82,13 @@ Private group members receive the group's name, roster, key epoch, and encrypted Internet-backed features are optional. When enabled or used: - Private fallback messages use BitChat's app-specific encrypted envelopes. This format is not NIP-17, NIP-44, or NIP-59 compatible. Relays can observe the recipient public-key tag, event timing and size, and network metadata, but not the message plaintext or stable sender identity. -- Public location-channel messages, notes, notices, and presence include a geohash tag, event kind, timestamp, and a public key. A geohash reveals an approximate area; finer precision reveals a smaller area. +- Public location-channel messages, notes, Place Feed posts, threaded replies, emoji reactions (`kind 1`, `kind 7`), notices, and presence include a geohash tag, event kind, timestamp, and a public key. A geohash reveals an approximate area; finer precision reveals a smaller area. +- If you enable **Public Handle** (off by default), your `kind 0` profile metadata and any global Home Feed posts are published publicly to your configured Nostr relays under your primary Nostr public key. +- Optional **Blossom image attachments** on Place Feed posts strip EXIF/GPS metadata locally before uploading to a third-party Blossom media server (default `blossom.primal.net`, configurable in settings) and include the public URL and SHA-256 hash in the post's `imeta` tag. When Tor routing is enabled, uploads and downloads route fail-closed through Tor, and remote images require an explicit tap to load. +- **Read receipts** for private messages are on by default in Everyday Mode (and can be turned off in Settings) and are always off in Stealth Mode. - The optional mesh bridge publishes bridge-enabled public mesh messages and presence to a neighborhood rendezvous cell. Those messages are public to participants and relays for that cell. A per-message “nearby only” choice prevents that message from crossing the bridge. - Bridge courier drops contain opaque end-to-end encrypted envelopes and a rotating recipient tag. Relays still observe timing and network metadata. -- A device with gateway features enabled may relay signed bridge/location traffic or opaque courier envelopes for nearby mesh devices. +- A device with gateway features enabled may relay signed bridge/location traffic (including Place Feed posts and reactions) or opaque courier envelopes for nearby mesh devices. Nostr relays are operated by third parties. Their retention, logging, availability, and privacy practices are outside the project's control. Public events and encrypted events may remain on relays according to each relay's policy. @@ -91,8 +96,8 @@ You can add custom `wss://` relays yourself in settings. Added relays are stored bitchat offers two privacy postures that you can choose during setup or switch anytime in Settings: -- **Everyday Mode** (default on fresh 2.0 installs): Connects directly to Nostr relays when internet features are used for fast startup, and stores encrypted private chat history on your device. While Tor routing is off, every relay you connect to can see your IP address, including relays carrying your private messages. -- **Stealth Mode**: Routes all internet traffic through Tor (fail-closed), keeps chat timelines in RAM only, enforces hidden lock-screen previews, and arms the triple-tap panic wipe gesture on the header bar. +- **Everyday Mode** (default on fresh 2.0 installs): Connects directly to Nostr relays when internet features are used for fast startup, stores encrypted private chat history on your device, and sends private-message read receipts unless turned off in Settings. While Tor routing is off, every relay or Blossom server you connect to can see your IP address, including relays carrying your private messages. +- **Stealth Mode**: Routes all internet traffic (relays and Blossom media) through Tor (fail-closed), keeps chat timelines in RAM only, enforces hidden lock-screen previews, disables outbound read receipts, requires tap-to-load for remote feed images, and arms the triple-tap panic wipe gesture on the header bar. - **Upgrades from 1.x**: Existing installs preserve their prior Tor setting (keeping Tor on for users who relied on the 1.x Tor-on default) and RAM-only history until you explicitly choose a mode. Tor routing can also be toggled independently in Settings at any time. diff --git a/bitchat/Identity/SecureIdentityStateManager.swift b/bitchat/Identity/SecureIdentityStateManager.swift index 8ac0a19b..4edb21d7 100644 --- a/bitchat/Identity/SecureIdentityStateManager.swift +++ b/bitchat/Identity/SecureIdentityStateManager.swift @@ -507,6 +507,8 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol { } // MARK: - Geohash (Nostr) Blocking + + static let blockedUsersDidChangeNotification = Notification.Name("bitchat.blockedUsersDidChange") func isNostrBlocked(pubkeyHexLowercased: String) -> Bool { queue.sync { @@ -516,6 +518,7 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol { func setNostrBlocked(_ pubkeyHexLowercased: String, isBlocked: Bool) { let key = pubkeyHexLowercased.lowercased() + var didChange = false queue.sync(flags: .barrier) { var changed: Bool if isBlocked { @@ -531,13 +534,20 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol { } } } + didChange = changed guard changed || self.pendingSave else { return } self.saveIdentityCache() } + if didChange { + DispatchQueue.main.async { + NotificationCenter.default.post(name: Self.blockedUsersDidChangeNotification, object: nil) + } + } } func setAssociatedNostrBlock(forFingerprint fingerprint: String, nostrPubkeyHex: String) { let key = nostrPubkeyHex.lowercased() + var didChange = false queue.sync(flags: .barrier) { var changed = self.cache.blockedNostrPubkeys.insert(key).inserted var mapping = self.cache.blockedNostrPubkeysByFingerprint ?? [:] @@ -546,9 +556,15 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol { self.cache.blockedNostrPubkeysByFingerprint = mapping changed = true } + didChange = changed guard changed || self.pendingSave else { return } self.saveIdentityCache() } + if didChange { + DispatchQueue.main.async { + NotificationCenter.default.post(name: Self.blockedUsersDidChangeNotification, object: nil) + } + } } func getBlockedNostrPubkeys() -> Set { @@ -580,6 +596,9 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol { self.encryptionKeyIsEphemeral = !saved SecureLogger.logKeyOperation(.generate, keyType: "identity cache encryption key", success: saved) } + DispatchQueue.main.async { + NotificationCenter.default.post(name: Self.blockedUsersDidChangeNotification, object: nil) + } } // MARK: - Verification diff --git a/bitchat/Localizable.xcstrings b/bitchat/Localizable.xcstrings index 01eec935..477cd347 100644 --- a/bitchat/Localizable.xcstrings +++ b/bitchat/Localizable.xcstrings @@ -22849,7 +22849,7 @@ "ko" : { "stringUnit" : { "state" : "translated", - "value" : "bitchat의 #%1$@ 채널에 참여하세요: bitchat://geohash/%1$@ — bitchat이 처음이신가요? %2$@에서 받은 뒤 위치 채널에서 #%1$@을(를) 입력하세요." + "value" : "bitchat의 #%1$@ 채널에 참여하세요: bitchat://geohash/%1$@ — bitchat이 처음이신가요? %2$@ 에서 받은 뒤 위치 채널에서 #%1$@을(를) 입력하세요." } }, "ms" : { diff --git a/bitchat/Nostr/GeoRelayDirectory.swift b/bitchat/Nostr/GeoRelayDirectory.swift index e424f0b7..a0f26a73 100644 --- a/bitchat/Nostr/GeoRelayDirectory.swift +++ b/bitchat/Nostr/GeoRelayDirectory.swift @@ -815,10 +815,10 @@ final class GeoRelayDirectory { } /// Chunked, strictly byte-bounded HTTP body reader for `GeoRelayDirectory`. -/// Replaces byte-by-byte `AsyncBytes` iteration (~50k async suspensions for -/// the relay CSV) while still enforcing `maximumBytes` before unbounded memory -/// allocation and rejecting HTTP errors or unexpected redirect URLs. -private final class BoundedHTTPDataReader: NSObject, URLSessionDataDelegate, @unchecked Sendable { +/// Avoids byte-by-byte `AsyncBytes` suspensions while enforcing `maximumBytes` +/// before unbounded memory allocation, rejecting HTTP errors, and refusing +/// HTTP redirects before following them. +final class BoundedHTTPDataReader: NSObject, URLSessionDataDelegate, @unchecked Sendable { private let expectedURL: URL? private let maximumBytes: Int private let lock = NSLock() @@ -897,6 +897,20 @@ private final class BoundedHTTPDataReader: NSObject, URLSessionDataDelegate, @un pendingContinuation?.resume(with: result) } + func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void + ) { + _ = session + _ = task + _ = response + _ = request + completionHandler(nil) + } + func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, diff --git a/bitchat/Nostr/NostrRelayInboundRouter.swift b/bitchat/Nostr/NostrRelayInboundRouter.swift index 7511cedb..57ec7598 100644 --- a/bitchat/Nostr/NostrRelayInboundRouter.swift +++ b/bitchat/Nostr/NostrRelayInboundRouter.swift @@ -15,9 +15,11 @@ struct InboundFrame: Sendable { /// because the guarded critical section is only a dictionary lookup + yield. final class InboundFrameRouter: @unchecked Sendable { /// Full cryptographic identity of a Nostr event being verified. - /// Including every field covered by the NIP-01 event ID + signature ensures - /// a forged/tampered copy can never coalesce onto — or poison — a genuine copy. - private struct VerificationFingerprint: Hashable { + /// Including every field covered by the NIP-01 event ID + signature with + /// byte-exact UTF-8 equality ensures canonically equivalent Unicode variants + /// (such as NFC vs. NFD) or tampered copies can never coalesce onto — or + /// poison — a genuine copy. + struct VerificationFingerprint: Hashable { let id: String let pubkey: String let createdAt: Int @@ -37,23 +39,70 @@ final class InboundFrameRouter: @unchecked Sendable { } static func == (lhs: VerificationFingerprint, rhs: VerificationFingerprint) -> Bool { - lhs.id == rhs.id && - lhs.pubkey == rhs.pubkey && lhs.createdAt == rhs.createdAt && lhs.kind == rhs.kind && - lhs.sig == rhs.sig && - lhs.content == rhs.content && - lhs.tags == rhs.tags + utf8Equal(lhs.id, rhs.id) && + utf8Equal(lhs.pubkey, rhs.pubkey) && + optionalUTF8Equal(lhs.sig, rhs.sig) && + utf8Equal(lhs.content, rhs.content) && + tagsUTF8Equal(lhs.tags, rhs.tags) } func hash(into hasher: inout Hasher) { - hasher.combine(id) - hasher.combine(pubkey) + Self.combineUTF8(id, into: &hasher) + Self.combineUTF8(pubkey, into: &hasher) hasher.combine(createdAt) hasher.combine(kind) - hasher.combine(sig) - hasher.combine(content) - hasher.combine(tags) + if let sig { + hasher.combine(true) + Self.combineUTF8(sig, into: &hasher) + } else { + hasher.combine(false) + } + Self.combineUTF8(content, into: &hasher) + hasher.combine(tags.count) + for tag in tags { + hasher.combine(tag.count) + for element in tag { + Self.combineUTF8(element, into: &hasher) + } + } + } + + private static func utf8Equal(_ lhs: String, _ rhs: String) -> Bool { + lhs.utf8.elementsEqual(rhs.utf8) + } + + private static func optionalUTF8Equal(_ lhs: String?, _ rhs: String?) -> Bool { + switch (lhs, rhs) { + case (nil, nil): + return true + case let (l?, r?): + return utf8Equal(l, r) + default: + return false + } + } + + private static func tagsUTF8Equal(_ lhs: [[String]], _ rhs: [[String]]) -> Bool { + guard lhs.count == rhs.count else { return false } + for (lhsTag, rhsTag) in zip(lhs, rhs) { + guard lhsTag.count == rhsTag.count else { return false } + for (lhsElement, rhsElement) in zip(lhsTag, rhsTag) where !utf8Equal(lhsElement, rhsElement) { + return false + } + } + return true + } + + private static func combineUTF8(_ value: String, into hasher: inout Hasher) { + // Normalize to contiguous UTF-8 so native Swift Strings and + // JSONSerialization-bridged NSStrings hash identically. + var copy = value + copy.withUTF8 { buffer in + hasher.combine(buffer.count) + hasher.combine(bytes: UnsafeRawBufferPointer(buffer)) + } } } @@ -103,7 +152,10 @@ final class InboundFrameRouter: @unchecked Sendable { /// Verifies `event.isValidSignature()` while coalescing simultaneous fan-in /// deliveries of byte-identical events across multiple relay pipelines. - func verifySignatureCoalesced(_ event: NostrEvent) async -> Bool { + func verifySignatureCoalesced( + _ event: NostrEvent, + verify: @Sendable (NostrEvent) -> Bool = { $0.isValidSignature() } + ) async -> Bool { let fingerprint = VerificationFingerprint(event: event) let isOwner: Bool = { lock.lock() @@ -116,7 +168,7 @@ final class InboundFrameRouter: @unchecked Sendable { }() if isOwner { - let valid = event.isValidSignature() + let valid = verify(event) let waiters: [CheckedContinuation] = { lock.lock() defer { lock.unlock() } @@ -136,7 +188,7 @@ final class InboundFrameRouter: @unchecked Sendable { lock.unlock() } else { lock.unlock() - continuation.resume(returning: event.isValidSignature()) + continuation.resume(returning: verify(event)) } } } diff --git a/bitchat/Protocols/MessageInteractionCodec.swift b/bitchat/Protocols/MessageInteractionCodec.swift index 7001e8ff..eb71cf5b 100644 --- a/bitchat/Protocols/MessageInteractionCodec.swift +++ b/bitchat/Protocols/MessageInteractionCodec.swift @@ -179,6 +179,21 @@ enum MessageInteractionCodec { return nil } + /// Matches a quoted reply snippet against a candidate message's content. + /// Checks the formatted preview first (so localized media labels like + /// `"Voice message"`, `"Photo"`, and `"File"` match their source media + /// messages) and falls back to the raw unwrapped body for compatibility + /// with older quotes captured before media previews were formatted. + static func matchesQuotedSnippet(_ snippet: String, in content: String) -> Bool { + let needle = snippet.hasSuffix("…") ? String(snippet.dropLast()) : snippet + guard !needle.isEmpty else { return false } + if formattedPreview(for: content).localizedCaseInsensitiveContains(needle) { + return true + } + let rawBody = parseReply(from: content)?.body ?? content + return rawBody.localizedCaseInsensitiveContains(needle) + } + // MARK: - Quoted Replies /// Condenses a message into a single-line bounded preview suitable for reply quotes. diff --git a/bitchat/Services/BLE/BLEService+Courier.swift b/bitchat/Services/BLE/BLEService+Courier.swift index f4a11dca..a96b9a8e 100644 --- a/bitchat/Services/BLE/BLEService+Courier.swift +++ b/bitchat/Services/BLE/BLEService+Courier.swift @@ -390,12 +390,14 @@ extension BLEService { /// Forced sends (bundle changed after consumption) go immediately. func sendPrekeyBundle(force: Bool = false) { let now = Date() + var previousSentAt: Date? let shouldSend: Bool = onEngine { if !force, let last = lastPrekeyBundleSentAt, now.timeIntervalSince(last) < TransportConfig.prekeyBundleRebroadcastSeconds { return false } + previousSentAt = lastPrekeyBundleSentAt lastPrekeyBundleSentAt = now return true } @@ -403,6 +405,7 @@ extension BLEService { guard let bundle = noiseService.currentPrekeyBundle(), let payload = bundle.encode() else { SecureLogger.error("❌ Failed to build prekey bundle", category: .security) + restorePrekeyBundleSentAt(claimedAt: now, previous: previousSentAt) return } guard let signedPacket = buildSignedBroadcastPacket( @@ -410,7 +413,10 @@ extension BLEService { payload: payload, timestamp: now, logLabel: "prekey bundle packet" - ) else { return } + ) else { + restorePrekeyBundleSentAt(claimedAt: now, previous: previousSentAt) + return + } if DispatchQueue.getSpecific(key: messageQueueKey) != nil { broadcastPacket(signedPacket) } else { @@ -421,6 +427,17 @@ extension BLEService { gossipSyncManager?.onPublicPacketSeen(signedPacket) } + /// No bundle went out, so the rebroadcast window must not start. For + /// example, a failed prekey read gives an empty bundle until the next read. + private func restorePrekeyBundleSentAt(claimedAt: Date, previous: Date?) { + onEngine { + // A later send or a panic reset may have set a newer value. + if lastPrekeyBundleSentAt == claimedAt { + lastPrekeyBundleSentAt = previous + } + } + } + /// Ingests a gossiped prekey bundle. Attribution is layered: the outer /// packet must originate from the bundle owner (fabricated sender IDs, used /// to multiply cache/gossip entries, are rejected), and BOTH the inner diff --git a/bitchat/Services/BLE/BLEService.swift b/bitchat/Services/BLE/BLEService.swift index caff3529..da6ca090 100644 --- a/bitchat/Services/BLE/BLEService.swift +++ b/bitchat/Services/BLE/BLEService.swift @@ -4421,8 +4421,10 @@ extension BLEService { // Broadcast duplicate suppression: if a distinct neighbor already // relayed this broadcast while our own relay is waiting in its // jitter window, cancel our scheduled relay in dense graphs. - // Fragments and directed packets are excluded. + // Fragments, live voice frames (not gossip-synced), and directed + // packets are excluded. if packet.type != MessageType.fragment.rawValue, + packet.type != MessageType.voiceFrame.rawValue, BLEPacketFreshnessPolicy.isBroadcastRecipient(packet.recipientID), !priorIngressPeers.contains(context.receivedFromPeerID), BLEReceivePipeline.shouldCancelScheduledRelayForDuplicate(connectedPeerCount: peerRegistry.connectedCount) { diff --git a/bitchat/Services/ChannelShare.swift b/bitchat/Services/ChannelShare.swift index eec82fe8..a69895cf 100644 --- a/bitchat/Services/ChannelShare.swift +++ b/bitchat/Services/ChannelShare.swift @@ -28,18 +28,25 @@ enum ChannelShare { /// Channel-not-presence framing: "join #x", never "I'm in #x". static func payload(forGeohash geohash: String) -> String { - let gh = geohash.lowercased() - return String( + payload( + forGeohash: geohash, format: String( localized: "channel.share.payload", defaultValue: "join the #%1$@ channel on bitchat: bitchat://geohash/%1$@ — new to bitchat? get it at %2$@ then type #%1$@ under location channels.", comment: "Plain-text share payload for a location channel; %1$@ is the geohash, %2$@ is the App Store URL" - ), - locale: .current, - gh, - appStoreURL + ) ) } + + /// Formats without a locale on purpose. With one, Foundation wraps each + /// argument of a right-to-left format (ar, fa, he, ur) in bidi isolates + /// (U+2068…U+2069), and NSDataDetector then stops at the first one, + /// cutting the deep link off at `bitchat://geohash`. Both arguments are + /// plain strings, so a locale has nothing else to contribute. Takes the + /// format so tests can run every locale's string through it. + static func payload(forGeohash geohash: String, format: String) -> String { + String(format: format, locale: nil, geohash.lowercased(), appStoreURL) + } } /// Identifiable wrapper so `.sheet(item:)` can present the system share UI. diff --git a/bitchat/Services/Groups/GroupStore.swift b/bitchat/Services/Groups/GroupStore.swift index ffe21cd5..72a505d7 100644 --- a/bitchat/Services/Groups/GroupStore.swift +++ b/bitchat/Services/Groups/GroupStore.swift @@ -29,6 +29,9 @@ final class GroupStore: ObservableObject { /// (such as locked background boot). Prevents `persist()` from overwriting /// durable group metadata on disk with a truncated in-memory roster. private var loadUnavailable = false + /// Group IDs explicitly removed while `loadUnavailable` was true so a + /// subsequent retry load does not resurrect them. + private var removedGroupIDsWhileUnavailable: Set = [] /// - Parameters: /// - fileURL: Overrides the on-disk location (tests). Ignored when `persistsToDisk` is false. @@ -105,6 +108,10 @@ final class GroupStore: ObservableObject { func upsert(_ group: BitchatGroup, key: Data) -> Bool { guard key.count == BitchatGroup.keyLength, Self.isWellFormed(group) else { return false } + if loadUnavailable { + removedGroupIDsWhileUnavailable.remove(group.groupID) + loadFromDisk() + } let existingIndex = groups.firstIndex(where: { $0.groupID == group.groupID }) if let existingIndex { let existing = groups[existingIndex] @@ -163,6 +170,12 @@ final class GroupStore: ObservableObject { } func removeGroup(withID groupID: Data) { + if loadUnavailable { + loadFromDisk() + } + if loadUnavailable { + removedGroupIDsWhileUnavailable.insert(groupID) + } groups.removeAll { $0.groupID == groupID } keyCache.removeValue(forKey: groupID) _ = keychain.deleteIdentityKey(forKey: Self.keychainKey(for: groupID)) @@ -175,6 +188,7 @@ final class GroupStore: ObservableObject { func wipe() { lifecycleGeneration &+= 1 loadUnavailable = false + removedGroupIDsWhileUnavailable.removeAll() for group in groups { _ = keychain.deleteIdentityKey(forKey: Self.keychainKey(for: group.groupID)) } @@ -213,6 +227,9 @@ final class GroupStore: ObservableObject { } private func persist() { + if loadUnavailable { + loadFromDisk() + } guard !loadUnavailable else { SecureLogger.warning("⚠️ Skipping group store save while prior disk/keychain load was unavailable", category: .security) return @@ -235,6 +252,7 @@ final class GroupStore: ObservableObject { } guard let stored else { loadUnavailable = false + removedGroupIDsWhileUnavailable.removeAll() return } applyLoadedGroups(stored) @@ -272,6 +290,7 @@ final class GroupStore: ObservableObject { var loaded: [BitchatGroup] = [] for group in stored { guard Self.isWellFormed(group), + !removedGroupIDsWhileUnavailable.contains(group.groupID), seenGroupIDs.insert(group.groupID).inserted else { continue } switch keychain.getIdentityKeyWithResult(forKey: Self.keychainKey(for: group.groupID)) { case .success(let keyData): @@ -286,6 +305,7 @@ final class GroupStore: ObservableObject { } } loadUnavailable = false + removedGroupIDsWhileUnavailable.removeAll() guard !loaded.isEmpty else { return } groups = loaded + groups } diff --git a/bitchat/Services/LocalWebOfTrustService.swift b/bitchat/Services/LocalWebOfTrustService.swift index 0b100872..da3816e9 100644 --- a/bitchat/Services/LocalWebOfTrustService.swift +++ b/bitchat/Services/LocalWebOfTrustService.swift @@ -83,4 +83,12 @@ final class LocalWebOfTrustService { func isTrustedAuthor(_ nostrPubkeyHex: String) -> Bool { trust(forNostrPubkey: nostrPubkeyHex).isTrusted } + + func blockedNostrPubkeys() -> Set { + identityManager?.getBlockedNostrPubkeys() ?? [] + } + + func blockNostrAuthor(_ nostrPubkeyHex: String) { + identityManager?.setNostrBlocked(nostrPubkeyHex, isBlocked: true) + } } diff --git a/bitchat/Services/NotificationService.swift b/bitchat/Services/NotificationService.swift index 83e53bd8..a7ab724f 100644 --- a/bitchat/Services/NotificationService.swift +++ b/bitchat/Services/NotificationService.swift @@ -15,6 +15,35 @@ import UIKit import AppKit #endif +/// The part of `UNUserNotificationCenter` that posting uses, so ordering +/// against a panic wipe can be tested without the live system center. +protocol NotificationCenterPosting: Sendable { + func add(_ request: UNNotificationRequest) async throws + func removeDeliveredNotifications(withIdentifiers identifiers: [String]) + func removePendingNotificationRequests(withIdentifiers identifiers: [String]) +} + +extension UNUserNotificationCenter: NotificationCenterPosting {} + +/// Counts panic wipes so a notification post still on its way to the center +/// can detect when a wipe overtook it. +final class NotificationPostGeneration: @unchecked Sendable { + private let lock = NSLock() + private var value: UInt = 0 + + var current: UInt { + lock.withLock { value } + } + + func invalidate() { + lock.withLock { value &+= 1 } + } + + func isCurrent(_ generation: UInt) -> Bool { + lock.withLock { value == generation } + } +} + final class NotificationService { struct Dependencies { var requestAuthorization: (UNAuthorizationOptions, @escaping (Bool, Error?) -> Void) -> Void @@ -31,14 +60,23 @@ final class NotificationService { removeAllPending: {} ) - static func system(center: UNUserNotificationCenter = .current()) -> Dependencies { + static func system( + center: UNUserNotificationCenter = .current(), + generation: NotificationPostGeneration = NotificationPostGeneration() + ) -> Dependencies { Dependencies( requestAuthorization: { options, completion in center.requestAuthorization(options: options, completionHandler: completion) }, deliver: { request in + let postedIn = generation.current Task { - try? await center.add(request) + await NotificationService.deliver( + request, + postedIn: postedIn, + to: center, + generation: generation + ) } }, setCategories: { categories in @@ -54,6 +92,22 @@ final class NotificationService { } } + /// Delivers a notification request while fencing against concurrent panic wipes: + /// drops the post if a wipe occurred before `add`, and immediately removes it + /// from delivered/pending queues if a wipe occurred while `add` was in flight. + static func deliver( + _ request: UNNotificationRequest, + postedIn: UInt, + to center: NotificationCenterPosting, + generation: NotificationPostGeneration + ) async { + guard generation.isCurrent(postedIn) else { return } + try? await center.add(request) + guard !generation.isCurrent(postedIn) else { return } + center.removeDeliveredNotifications(withIdentifiers: [request.identifier]) + center.removePendingNotificationRequests(withIdentifiers: [request.identifier]) + } + static let shared = NotificationService() /// Category for the "bitchatters nearby" notification, carrying the wave quick action. @@ -94,6 +148,7 @@ final class NotificationService { private let isRunningTestsProvider: () -> Bool private let dependencies: Dependencies + private let postGeneration: NotificationPostGeneration /// Returns true if running in test environment (XCTest, Swift Testing, or CI) private var isRunningTests: Bool { @@ -101,26 +156,35 @@ final class NotificationService { } private init() { + let postGeneration = NotificationPostGeneration() + self.postGeneration = postGeneration self.hidePreviewsProvider = { NotificationPrivacySettings.hideMessagePreviews } self.isRunningTestsProvider = { TestEnvironment.isRunningTests } - self.dependencies = TestEnvironment.isRunningTests ? .noop : .system() + self.dependencies = TestEnvironment.isRunningTests + ? .noop + : .system(generation: postGeneration) } internal init( isRunningTestsProvider: @escaping () -> Bool = { TestEnvironment.isRunningTests }, dependencies: Dependencies = .noop, + postGeneration: NotificationPostGeneration = NotificationPostGeneration(), hidePreviewsProvider: @escaping () -> Bool = { NotificationPrivacySettings.hideMessagePreviews } ) { self.isRunningTestsProvider = isRunningTestsProvider self.dependencies = dependencies + self.postGeneration = postGeneration self.hidePreviewsProvider = hidePreviewsProvider } - /// Panic-wipe hook: removes all delivered and pending local notifications - /// from Notification Center so sender names, previews, and routing metadata - /// cannot linger on a seized device after a wipe. + /// Panic-wipe hook: invalidates any in-flight posts and removes all delivered + /// and pending local notifications from Notification Center so sender names, + /// previews, and routing metadata cannot linger after a wipe. Removal, not + /// erasure — the system's own record of shown alerts is outside the app's reach. func clearAllNotificationsForPanic() { guard !isRunningTests else { return } + // Invalidate first so a post finishing concurrently takes itself back out. + postGeneration.invalidate() dependencies.removeAllPending() dependencies.removeAllDelivered() } @@ -191,7 +255,7 @@ final class NotificationService { let identifier = "private-\(UUID().uuidString)" // Routing payload, not display copy: `userInfo` never reaches the lock // screen, and the conversation to open still has to be identifiable. - let userInfo = ["peerID": peerID.id, "senderName": sender] + let userInfo = ["peerID": peerID.id] sendLocalNotification(title: title, body: body, identifier: identifier, userInfo: userInfo) } diff --git a/bitchat/Services/PlaceFeedModel.swift b/bitchat/Services/PlaceFeedModel.swift index 1ee52cb5..f10dc8da 100644 --- a/bitchat/Services/PlaceFeedModel.swift +++ b/bitchat/Services/PlaceFeedModel.swift @@ -82,6 +82,7 @@ enum PlaceFeedOrganizer { sort: PlaceFeedSort, filter: PlaceFeedFilter, query: String = "", + blockedPubkeys: Set = [], replyCount: (String) -> Int = { _ in 0 }, reactionCount: (String) -> Int = { _ in 0 }, isVouched: (NoticeItem) -> Bool = { _ in false } @@ -89,6 +90,12 @@ enum PlaceFeedOrganizer { let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines) let filtered = items.filter { item in + if !blockedPubkeys.isEmpty, + let pubkey = item.nostrNote?.pubkey.lowercased(), + blockedPubkeys.contains(pubkey) { + return false + } + switch filter { case .all: break diff --git a/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift b/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift index 922ccabd..ec342bd9 100644 --- a/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift +++ b/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift @@ -948,18 +948,35 @@ final class ChatPrivateConversationCoordinator { } func processActionMessage(_ message: BitchatMessage) -> BitchatMessage { - let isActionMessage = message.content.hasPrefix("* ") - && message.content.hasSuffix(" *") - && (message.content.contains("🫂") - || message.content.contains("🐟") - || message.content.contains("took a screenshot")) + // This rewrite hands the message to the formatter as sender "system", + // which styles it as trusted, non-peer content. Substring sniffing + // ("contains 🫂") let ANY sender put arbitrary text in that styling: + // `* SECURITY: session expired — bob took a screenshot *` rendered as + // a system-authored line. Only the exact, locally-generatable action + // shapes qualify, and the actor slot must be the actual wire sender — + // a peer can only "hug"/"slap"/"screenshot" as themselves. + guard message.content.hasPrefix("* "), message.content.hasSuffix(" *") else { return message } + let inner = String(message.content.dropFirst(2).dropLast(2)) + // Match the ACTOR by base name: location-channel senders arrive + // suffixed (`bob#ab12`) while handleEmote embeds the unsuffixed + // nickname, so a raw-string compare would regress every received + // geohash action to plain text. + let senderBase = message.sender.splitSuffix().0 + guard Self.isNameToken(senderBase, maxLength: Self.maxActionActorLength) else { + return message + } + + let isActionMessage = + Self.matchesActionTemplate(inner, prefix: "🫂 \(senderBase) hugs ", suffix: "") + || Self.matchesActionTemplate(inner, prefix: "🐟 \(senderBase) slaps ", suffix: " around a bit with a large trout") + || inner == "\(senderBase) took a screenshot" guard isActionMessage else { return message } return BitchatMessage( id: message.id, sender: "system", - content: String(message.content.dropFirst(2).dropLast(2)), + content: inner, timestamp: message.timestamp, isRelay: message.isRelay, originalSender: message.originalSender, @@ -971,6 +988,70 @@ final class ChatPrivateConversationCoordinator { ) } + static let maxActionActorLength = 50 + + static func matchesActionTemplate(_ inner: String, prefix: String, suffix: String) -> Bool { + guard inner.hasPrefix(prefix), inner.hasSuffix(suffix), + inner.count >= prefix.count + suffix.count + 1 else { return false } + let target = String(inner.dropFirst(prefix.count).dropLast(suffix.count)) + return isNameToken(target) + } + + static func isNameToken(_ token: String, maxLength: Int = 32) -> Bool { + if token == "you" { return true } + guard !token.isEmpty, token.count <= maxLength else { return false } + guard hasOrthographicJoinerUseOnly(token) else { return false } + guard token.unicodeScalars.allSatisfy({ $0 == Self.zeroWidthNonJoiner || !rendersAsBlank($0) }) + else { return false } + let lower = token.lowercased() + return !lower.contains("://") && !lower.contains("www.") && !lower.contains("http") + } + + private static let zeroWidthNonJoiner: Unicode.Scalar = "\u{200C}" + private static let maxJoinersInName = 2 + + private static func hasOrthographicJoinerUseOnly(_ token: String) -> Bool { + let scalars = Array(token.unicodeScalars) + var joiners = 0 + for (index, scalar) in scalars.enumerated() where scalar == zeroWidthNonJoiner { + joiners += 1 + guard joiners <= maxJoinersInName, + index > 0, index + 1 < scalars.count, + isLetterLike(scalars[index - 1]), isLetterLike(scalars[index + 1]) + else { return false } + } + return true + } + + private static func isLetterLike(_ scalar: Unicode.Scalar) -> Bool { + switch scalar.properties.generalCategory { + case .lowercaseLetter, .uppercaseLetter, .titlecaseLetter, + .modifierLetter, .otherLetter, .nonspacingMark, .spacingMark: + return true + default: + return false + } + } + + private static let blankRenderingScalars: Set = [ + "\u{2800}", // braille pattern blank + "\u{FFFC}", // object replacement character + "\u{FFFD}", // replacement character + "\u{1D159}" // musical symbol null notehead + ] + + private static func rendersAsBlank(_ scalar: Unicode.Scalar) -> Bool { + switch scalar.properties.generalCategory { + case .spaceSeparator, .lineSeparator, .paragraphSeparator, + .control, .format, .surrogate, .privateUse, .unassigned: + return true + default: + break + } + if scalar.properties.isDefaultIgnorableCodePoint { return true } + return blankRenderingScalars.contains(scalar) + } + // Nicknames are self-chosen and not unique, so only a fingerprint match // migrates here. handlePrivateMessage joins key-derived aliases around // this call: a Noise-key ID's short ID before, a stable-key chat after. diff --git a/bitchat/ViewModels/ChatViewModelBootstrapper.swift b/bitchat/ViewModels/ChatViewModelBootstrapper.swift index 98821501..3545a811 100644 --- a/bitchat/ViewModels/ChatViewModelBootstrapper.swift +++ b/bitchat/ViewModels/ChatViewModelBootstrapper.swift @@ -159,7 +159,7 @@ private extension ChatViewModelBootstrapper { guard let viewModel, connected else { return } viewModel.messageRouter.flushAllOutbox() viewModel.messageRouter.retryBridgeCourierDeposits() - if let selectedPeer = viewModel.selectedPrivateChatPeer { + if viewModel.isAppActive, let selectedPeer = viewModel.selectedPrivateChatPeer { viewModel.markPrivateMessagesAsRead(from: selectedPeer) } } diff --git a/bitchat/Views/ContentComposerView.swift b/bitchat/Views/ContentComposerView.swift index 537117c3..883cdd2d 100644 --- a/bitchat/Views/ContentComposerView.swift +++ b/bitchat/Views/ContentComposerView.swift @@ -93,8 +93,8 @@ struct ContentComposerView: View { .focused(isTextFieldFocused) .autocorrectionDisabled( Self.shouldDisableAutocorrection( - for: messageText, - isAutocompleting: conversationUIModel.showAutocomplete + for: draftModel.messageText, + isAutocompleting: autocompleteModel.isShowingAutocomplete(for: draftModel.id) ) ) #if os(iOS) diff --git a/bitchat/Views/HomeFeedView.swift b/bitchat/Views/HomeFeedView.swift index df57b278..7ede9aee 100644 --- a/bitchat/Views/HomeFeedView.swift +++ b/bitchat/Views/HomeFeedView.swift @@ -34,6 +34,7 @@ struct HomeFeedView: View { @State private var draft = "" @State private var selectedThread: ThreadSelection? @State private var bottomComposerHeight: CGFloat = 0 + @State private var blockedPubkeys: Set = LocalWebOfTrustService.shared.blockedNostrPubkeys() private struct ThreadSelection: Identifiable { let note: LocationNotesManager.Note @@ -62,7 +63,9 @@ struct HomeFeedView: View { } private var visibleItems: [HomeFeedItem] { - feedManager.filteredItems(scope: scope, sort: sort, filter: filter) + let items = feedManager.filteredItems(scope: scope, sort: sort, filter: filter) + guard !blockedPubkeys.isEmpty else { return items } + return items.filter { !blockedPubkeys.contains($0.note.pubkey.lowercased()) } } private var hasAnySources: Bool { @@ -86,11 +89,15 @@ struct HomeFeedView: View { var body: some View { contentLayout .onAppear { + blockedPubkeys = LocalWebOfTrustService.shared.blockedNostrPubkeys() feedManager.activate( bookmarks: locationChannelsModel.bookmarks, followedPubkeys: followsStore.allFollowedPubkeys ) } + .onReceive(NotificationCenter.default.publisher(for: SecureIdentityStateManager.blockedUsersDidChangeNotification)) { _ in + blockedPubkeys = LocalWebOfTrustService.shared.blockedNostrPubkeys() + } .onChange(of: locationChannelsModel.bookmarks) { bookmarks in feedManager.updateSources( bookmarks: bookmarks, @@ -221,6 +228,11 @@ struct HomeFeedView: View { ) followsStore.toggleFollow(authorHex, alias: alias) }, + onBlockAuthor: isOwn ? nil : { + LocalWebOfTrustService.shared.blockNostrAuthor(authorHex) + followsStore.unfollow(authorHex) + blockedPubkeys.insert(authorHex.lowercased()) + }, onOpenThread: { if let gh = item.savedPlaceGeohash, let manager = feedManager.manager(forGeohash: gh) { diff --git a/bitchat/Views/MessageListView.swift b/bitchat/Views/MessageListView.swift index 09d44c34..a721f825 100644 --- a/bitchat/Views/MessageListView.swift +++ b/bitchat/Views/MessageListView.swift @@ -906,15 +906,13 @@ private extension MessageListContentView { let all = liveMessages(privatePeer) let searchLimit = all.firstIndex(where: { $0.id == beforeMessageID }) ?? all.count let prefix = all.prefix(searchLimit) - let needle = snippet.hasSuffix("…") ? String(snippet.dropLast()) : snippet guard let match = prefix.last(where: { candidate in guard candidate.sender != "system", MessageInteractionCodec.parseReaction(from: candidate.content) == nil else { return false } - let candidateBody = MessageInteractionCodec.parseReply(from: candidate.content)?.body ?? candidate.content return candidate.sender.caseInsensitiveCompare(sender) == .orderedSame - && candidateBody.localizedCaseInsensitiveContains(needle) + && MessageInteractionCodec.matchesQuotedSnippet(snippet, in: candidate.content) }) else { return } quoteHighlightTask?.cancel() diff --git a/bitchat/Views/PlaceFeedView.swift b/bitchat/Views/PlaceFeedView.swift index b96faf89..69f6c443 100644 --- a/bitchat/Views/PlaceFeedView.swift +++ b/bitchat/Views/PlaceFeedView.swift @@ -281,6 +281,7 @@ private struct PlaceFeedContent: View { @ObservedObject private var followsStore = NostrFollowsStore.shared @Environment(\.colorScheme) private var colorScheme @ThemedPalette private var palette + @State private var blockedPubkeys: Set = LocalWebOfTrustService.shared.blockedNostrPubkeys() private var geohash: String { channel.geohash.lowercased() } @@ -297,6 +298,7 @@ private struct PlaceFeedContent: View { sort: sort, filter: filter, query: searchQuery, + blockedPubkeys: blockedPubkeys, replyCount: { manager.replyCount(forRootID: $0) }, reactionCount: { manager.totalReactionCount(forNoteID: $0) }, isVouched: { item in @@ -393,6 +395,12 @@ private struct PlaceFeedContent: View { let alias = profileStore.displayName(for: hex, fallbackNickname: item.nostrNote?.nickname) followsStore.toggleFollow(hex, alias: alias) } : nil, + onBlockAuthor: (!own && authorHex != nil) ? { + guard let hex = authorHex else { return } + LocalWebOfTrustService.shared.blockNostrAuthor(hex) + followsStore.unfollow(hex) + blockedPubkeys.insert(hex.lowercased()) + } : nil, onOpenThread: { if let note = item.nostrNote { selectedThreadRoot = note @@ -417,6 +425,12 @@ private struct PlaceFeedContent: View { .refreshable { manager.refresh() } + .onAppear { + blockedPubkeys = LocalWebOfTrustService.shared.blockedNostrPubkeys() + } + .onReceive(NotificationCenter.default.publisher(for: SecureIdentityStateManager.blockedUsersDidChangeNotification)) { _ in + blockedPubkeys = LocalWebOfTrustService.shared.blockedNostrPubkeys() + } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(ThemedRootBackground()) } @@ -875,6 +889,7 @@ struct PlaceFeedPostCard: View { var isFollowingAuthor: Bool = false var onTapPlace: (() -> Void)? = nil var onToggleFollow: (() -> Void)? = nil + var onBlockAuthor: (() -> Void)? = nil let onOpenThread: () -> Void let onToggleReaction: (String) -> Void let onDelete: () -> Void @@ -969,6 +984,26 @@ struct PlaceFeedPostCard: View { .buttonStyle(.plain) } + if let onBlockAuthor, !isOwn { + Menu { + Button(role: .destructive, action: onBlockAuthor) { + Label( + String(localized: "content.actions.block"), + systemImage: "hand.raised.slash" + ) + } + } label: { + Image(systemName: "ellipsis") + .font(.system(size: 12, weight: .semibold)) + .foregroundColor(palette.secondary) + .frame(width: 28, height: 28) + .contentShape(Rectangle()) + } + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) + .accessibilityLabel(String(localized: "content.actions.title")) + } + if isOwn { Button(action: onDelete) { Image(systemName: "trash") diff --git a/bitchat/Views/PlaceThreadSheet.swift b/bitchat/Views/PlaceThreadSheet.swift index 5b3b7048..cfc27954 100644 --- a/bitchat/Views/PlaceThreadSheet.swift +++ b/bitchat/Views/PlaceThreadSheet.swift @@ -26,9 +26,12 @@ struct PlaceThreadSheet: View { @State private var replyDraft = "" /// Optional nested reply target inside the thread (nil replies directly to rootNote). @State private var replyTarget: LocationNotesManager.Note? + @State private var blockedPubkeys: Set = LocalWebOfTrustService.shared.blockedNostrPubkeys() private var replies: [LocationNotesManager.Note] { - manager.replies(forRootID: rootNote.id) + let all = manager.replies(forRootID: rootNote.id) + guard !blockedPubkeys.isEmpty else { return all } + return all.filter { !blockedPubkeys.contains($0.pubkey.lowercased()) } } private var maxDraftLines: Int { @@ -67,6 +70,13 @@ struct PlaceThreadSheet: View { isOwn: manager.isOwnNote(rootNote), replyCount: replies.count, reactions: manager.reactions(forNoteID: rootNote.id), + onBlockAuthor: manager.isOwnNote(rootNote) ? nil : { + let hex = rootNote.pubkey + LocalWebOfTrustService.shared.blockNostrAuthor(hex) + NostrFollowsStore.shared.unfollow(hex) + blockedPubkeys.insert(hex.lowercased()) + dismiss() + }, onOpenThread: { replyTarget = nil }, onToggleReaction: { emoji in manager.toggleReaction(emoji: emoji, on: rootNote) @@ -104,6 +114,12 @@ struct PlaceThreadSheet: View { composer } .themedSurface() + .onAppear { + blockedPubkeys = LocalWebOfTrustService.shared.blockedNostrPubkeys() + } + .onReceive(NotificationCenter.default.publisher(for: SecureIdentityStateManager.blockedUsersDidChangeNotification)) { _ in + blockedPubkeys = LocalWebOfTrustService.shared.blockedNostrPubkeys() + } #if os(macOS) .frame(minWidth: 420, idealWidth: 460, minHeight: 560, idealHeight: 660) #endif @@ -166,6 +182,29 @@ struct PlaceThreadSheet: View { } .buttonStyle(.plain) .accessibilityLabel(String(localized: "board.action.delete", defaultValue: "delete", comment: "Delete own reply")) + } else { + Menu { + Button(role: .destructive) { + let hex = reply.pubkey + LocalWebOfTrustService.shared.blockNostrAuthor(hex) + NostrFollowsStore.shared.unfollow(hex) + blockedPubkeys.insert(hex.lowercased()) + } label: { + Label( + String(localized: "content.actions.block"), + systemImage: "hand.raised.slash" + ) + } + } label: { + Image(systemName: "ellipsis") + .font(.system(size: 12, weight: .semibold)) + .foregroundColor(palette.secondary) + .frame(width: 26, height: 26) + .contentShape(Rectangle()) + } + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) + .accessibilityLabel(String(localized: "content.actions.title")) } } diff --git a/bitchatTests/ChannelShareTests.swift b/bitchatTests/ChannelShareTests.swift index ee5d13ad..399b663d 100644 --- a/bitchatTests/ChannelShareTests.swift +++ b/bitchatTests/ChannelShareTests.swift @@ -6,6 +6,7 @@ // For more information, see // +import Foundation import Testing @testable import bitchat @@ -18,9 +19,45 @@ struct ChannelShareTests { #expect(!text.lowercased().contains("i'm in")) } + /// Both links in an invite should come through link detection intact, + /// so this runs every locale's format through the shipped formatting and + /// checks what NSDataDetector finds. Two ways it has broken: a locale + /// makes Foundation wrap the arguments of a right-to-left format in bidi + /// isolates, which cut the deep link off at `bitchat://geohash`; and text + /// attached to a URL with no space (Korean `에서`) is read as part of it. + @Test func everyLocaleKeepsBothInviteLinksIntact() throws { + let formats = try Self.payloadFormats() + #expect(formats.count > 1, "catalog should carry more locales than the source language") + let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) + for (locale, format) in formats.sorted(by: { $0.key < $1.key }) { + let text = ChannelShare.payload(forGeohash: "u4pru", format: format) + let links = detector.matches(in: text, range: NSRange(text.startIndex..., in: text)) + .compactMap { $0.url?.absoluteString } + #expect(links.contains("bitchat://geohash/u4pru"), "\(locale): deep link not intact in \(links)") + #expect(links.contains(ChannelShare.appStoreURL), "\(locale): store link not intact in \(links)") + } + } + @Test func precisionWarningStartsAtNeighborhood() { #expect(!ChannelShare.shouldWarn(forGeohash: "u4pru")) // city = 5 #expect(ChannelShare.shouldWarn(forGeohash: "u4pruy")) // neighborhood = 6 #expect(ChannelShare.shouldWarn(forGeohash: "u4pruyzd")) } + + /// Every locale's `channel.share.payload` format, read from the catalog + /// source the way `LocalizationCoverageTests` reads it. + private static func payloadFormats() throws -> [String: String] { + let catalogURL = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // bitchatTests + .deletingLastPathComponent() // repo root + .appendingPathComponent("bitchat/Localizable.xcstrings") + let root = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: catalogURL)) as? [String: Any]) + let strings = try #require(root["strings"] as? [String: Any]) + let entry = try #require(strings["channel.share.payload"] as? [String: Any]) + let localizations = try #require(entry["localizations"] as? [String: [String: Any]]) + return try localizations.mapValues { localization in + let unit = try #require(localization["stringUnit"] as? [String: Any]) + return try #require(unit["value"] as? String) + } + } } diff --git a/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift b/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift index 25178001..d60d5f5d 100644 --- a/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift +++ b/bitchatTests/ChatPrivateConversationCoordinatorContextTests.swift @@ -335,6 +335,264 @@ private func makeFavoriteRelationship( /// live singletons. struct ChatPrivateConversationCoordinatorContextTests { + @Test @MainActor + func processActionMessage_rendersOnlyExactSenderAnchoredTemplates() async { + let context = MockChatPrivateConversationContext() + let coordinator = ChatPrivateConversationCoordinator(context: context) + + func processed(_ content: String, sender: String = "bob") -> BitchatMessage { + coordinator.processActionMessage( + BitchatMessage( + id: UUID().uuidString, + sender: sender, + content: content, + timestamp: Date(), + isRelay: false + ) + ) + } + + // Exact locally-generatable shapes, actor == wire sender: system. + #expect(processed("* 🫂 bob hugs alice *").sender == "system") + #expect(processed("* 🫂 bob hugs you *").sender == "system") + #expect(processed("* 🐟 bob slaps alice around a bit with a large trout *").sender == "system") + #expect(processed("* bob took a screenshot *").sender == "system") + + // Location-channel senders arrive suffixed while content stays + // unsuffixed — must still render as a system action. + #expect(processed("* 🫂 bob hugs alice *", sender: "bob#ab12").sender == "system") + #expect(processed("* 🫂 bob hugs alice#1a2b *").sender == "system") + + // The spoof this parser used to allow: arbitrary text between the + // markers with a magic substring rendered as system-authored. + #expect(processed("* SECURITY: your session key expired, re-verify at evil.example — bob took a screenshot *").sender == "bob") + #expect(processed("* 🫂 admin hugs alice — send your keys to @admin *").sender == "bob") + // Self-attributed preamble smuggled into the target slot: the target + // must be a single name token, so free text with spaces is rejected. + #expect(processed("* 🫂 bob hugs SECURITY: reset your keys at evil.example *").sender == "bob") + // Actor slot must be the actual sender, not someone else's name. + #expect(processed("* alice took a screenshot *", sender: "bob").sender == "bob") + #expect(processed("* 🫂 alice hugs you *", sender: "bob").sender == "bob") + // Target slot: single whitespace-free token, bounded length only. + #expect(processed("* 🫂 bob hugs " + String(repeating: "x", count: 200) + " *").sender == "bob") + #expect(processed("* 🫂 bob hugs a\nb *").sender == "bob") + #expect(processed("* 🫂 bob hugs a b *").sender == "bob") + // Not an action shape at all. + #expect(processed("hello there").sender == "bob") + } + + /// A name token is whitespace-free and bounded, but it still renders inside + /// the trusted `system` line, so a unicode separator or bidi mark reorders + /// the visible text there (@Chessing234 on #1662/#1699). The URL half of + /// the check is defense in depth, not a live tappable link: the formatter's + /// link-detection loop sits inside its `sender != "system"` branch and the + /// else branch that draws system lines attaches no link attributes — the + /// check exists so a later formatter change can't quietly make one + /// tappable. Both classes degrade to a plain message under the sender's own + /// name. + @Test @MainActor + func processActionMessage_rejectsLinkAndSeparatorPayloadsInSlots() async { + let context = MockChatPrivateConversationContext() + let coordinator = ChatPrivateConversationCoordinator(context: context) + + func processed(_ content: String, sender: String = "bob") -> BitchatMessage { + coordinator.processActionMessage( + BitchatMessage(id: UUID().uuidString, sender: sender, content: content, + timestamp: Date(), isRelay: false) + ) + } + + // URL in the target slot — the whole point of the actor-anchoring + // example, but as a tappable link rather than a preamble. + #expect(processed("* 🫂 bob hugs https://evil.tld *").sender == "bob") + // The www. variant has no ":" or "/", so a naive charset check misses + // it; the formatter linkifies it via the "www." hint just the same. + #expect(processed("* 🫂 bob hugs www.evil.tld *").sender == "bob") + #expect(processed("* bob took a screenshot http://evil.tld *", sender: "bob").sender == "bob") + // URL smuggled through the ACTOR nickname too. + #expect(processed("* https://evil.tld took a screenshot *", sender: "https://evil.tld").sender == "https://evil.tld") + // Unicode bidi mark (U+202E right-to-left override) in the slot — this + // is the case a plain `Character.isWhitespace` scan actually missed. + #expect(processed("* 🫂 bob hugs a\u{202E}b *").sender == "bob") + // Non-breaking space (U+00A0). Swift's `isWhitespace` already matched + // this one on the base; it's kept as a regression guard. + #expect(processed("* 🫂 bob hugs a\u{00A0}b *").sender == "bob") + + // Legitimate shapes still render as system actions. + #expect(processed("* 🫂 bob hugs alice *").sender == "system") + #expect(processed("* 🫂 bob hugs alice#1a2b *").sender == "system") + #expect(processed("* bob took a screenshot *").sender == "system") + } + + /// The target slot rejects free text, but the ACTOR slot is the peer's own + /// self-chosen nickname, and nothing upstream bounds what arrives on the + /// wire: `InputValidator.validateNickname` is only reached from ReadReceipt + /// decoding, announce nicknames are merely NFC-normalized, and content is + /// merely trimmed. So the preamble the target slot now refuses can simply + /// be moved into the nickname, and the line still lands in the formatter's + /// trusted "system" styling — unless the token check catches it here. + @Test @MainActor + func processActionMessage_rejectsPreambleSmuggledIntoTheActorNickname() async { + let context = MockChatPrivateConversationContext() + let coordinator = ChatPrivateConversationCoordinator(context: context) + + func processed(_ content: String, sender: String) -> BitchatMessage { + coordinator.processActionMessage( + BitchatMessage( + id: UUID().uuidString, + sender: sender, + content: content, + timestamp: Date(), + isRelay: false + ) + ) + } + + // 44 characters — comfortably inside the 50-char nickname limit. + let hostileNick = "SECURITY: session expired, re-verify at evil" + #expect(hostileNick.count <= 50) + + // Every one of these is a peer speaking as itself, so the actor check + // passes; the payload rides in the name. + #expect(processed("* \(hostileNick) took a screenshot *", sender: hostileNick).sender == hostileNick) + #expect(processed("* 🫂 \(hostileNick) hugs you *", sender: hostileNick).sender == hostileNick) + #expect( + processed( + "* 🐟 \(hostileNick) slaps you around a bit with a large trout *", + sender: hostileNick + ).sender == hostileNick + ) + + // Ordinary nicknames keep rendering as system actions. + #expect(processed("* bob took a screenshot *", sender: "bob").sender == "system") + #expect(processed("* 🫂 bob hugs you *", sender: "bob").sender == "system") + + // The reason the actor bound is the nickname limit and not the target + // slot's 32: a legitimate, space-free nickname longer than 32 must + // STILL render as a system action. If this bound is ever "simplified" + // back to 32, these regress to plain text under the peer's own name and + // their hugs/slaps/screenshots silently stop rendering as actions. + let longLegitNick = String(repeating: "a", count: 40) // > 32, ≤ 50, no spaces + #expect(longLegitNick.count > 32 && longLegitNick.count <= ChatPrivateConversationCoordinator.maxActionActorLength) + #expect(processed("* \(longLegitNick) took a screenshot *", sender: longLegitNick).sender == "system") + #expect(processed("* 🫂 \(longLegitNick) hugs you *", sender: longLegitNick).sender == "system") + #expect(processed("* 🐟 \(longLegitNick) slaps you around a bit with a large trout *", sender: longLegitNick).sender == "system") + } + + /// A blank-rendering scalar is neither whitespace nor a control character, + /// so the old set-membership check waved it through (Codex on #1699): every + /// gap in `SECURITY:⠀session⠀expired,⠀re-verify⠀at⠀evil` is U+2800 braille + /// pattern blank, which reads as a sentence but passes as a single token + /// and lands in the trusted "system" styling. The scalar rule is by category now, so + /// hangul fillers and private-use scalars fall the same way — while names + /// carrying combining marks keep rendering. + @Test @MainActor + func processActionMessage_rejectsBlankRenderingScalarsInSlots() async { + let context = MockChatPrivateConversationContext() + let coordinator = ChatPrivateConversationCoordinator(context: context) + + func processed(_ content: String, sender: String = "bob") -> BitchatMessage { + coordinator.processActionMessage( + BitchatMessage(id: UUID().uuidString, sender: sender, content: content, + timestamp: Date(), isRelay: false) + ) + } + + // The reported payload, verbatim: U+2800 in every gap. + let brailleBlank = "\u{2800}" + let hostileNick = [ + "SECURITY:", "session", "expired,", "re-verify", "at", "evil" + ].joined(separator: brailleBlank) + // Inside the 50-char actor bound, so the rejection has to come from the + // scalar rule rather than the length check. + #expect(hostileNick.count <= ChatPrivateConversationCoordinator.maxActionActorLength) + + // All three action templates, each a peer speaking as itself. + #expect(processed("* \(hostileNick) took a screenshot *", sender: hostileNick).sender == hostileNick) + #expect(processed("* 🫂 \(hostileNick) hugs you *", sender: hostileNick).sender == hostileNick) + #expect( + processed( + "* 🐟 \(hostileNick) slaps you around a bit with a large trout *", + sender: hostileNick + ).sender == hostileNick + ) + // Same scalar in the target slot. + #expect(processed("* 🫂 bob hugs SECURITY:\(brailleBlank)verify\(brailleBlank)at\(brailleBlank)evil *").sender == "bob") + + // U+3164 hangul filler is category Lo, not a separator — only its + // default-ignorable property gives it away. Well inside the 32-char + // target bound, so again the scalar rule is what rejects it. + let hangulFiller = "\u{3164}" + let fillerTarget = "SECURITY:\(hangulFiller)reset\(hangulFiller)keys" + #expect(fillerTarget.count <= 32) + #expect(processed("* 🫂 bob hugs \(fillerTarget) *").sender == "bob") + + // Private-use scalars render as whatever the font decides, including + // nothing at all. + #expect(processed("* 🫂 bob hugs a\u{E000}b *").sender == "bob") + + // Nonspacing combining marks are NOT blanks: Persian and Arabic names + // carry harakat and must keep rendering as system actions. + let harakatName = "\u{0645}\u{062D}\u{0645}\u{0651}\u{062F}" // محمّد, with a U+0651 shadda + #expect(processed("* \(harakatName) took a screenshot *", sender: harakatName).sender == "system") + #expect(processed("* 🫂 bob hugs \(harakatName) *").sender == "system") + + // A plain emoji nickname (no variation selector) is a symbol, not a + // blank. + let emojiNick = "\u{1F389}" // 🎉 + #expect(processed("* \(emojiNick) took a screenshot *", sender: emojiNick).sender == "system") + #expect(processed("* 🫂 bob hugs \(emojiNick) *").sender == "system") + } + + /// Persian writes compounds with the half-space, U+200C ZERO WIDTH + /// NON-JOINER: `علی\u{200C}رضا`, `می\u{200C}رود`. It is category Cf, so the + /// blank-scalar rule rejected it and those names stopped rendering as + /// actions — a cost carried only by Persian and Arabic speakers. Unlike the + /// invisible scalars that rule exists to stop, the joiner renders: a + /// visible half-space in Arabic script, nothing at all in Latin, where it + /// cannot fake a word boundary. That makes it no stronger than the hyphen + /// and colon this check has always allowed, so it is admitted in its + /// orthographic position — between two letters, at most twice — and + /// nowhere else. + @Test @MainActor + func processActionMessage_allowsPersianHalfSpaceButNotSentencesBuiltFromIt() async { + let context = MockChatPrivateConversationContext() + let coordinator = ChatPrivateConversationCoordinator(context: context) + + func processed(_ content: String, sender: String = "bob") -> BitchatMessage { + coordinator.processActionMessage( + BitchatMessage(id: UUID().uuidString, sender: sender, content: content, + timestamp: Date(), isRelay: false) + ) + } + + let zwnj = "\u{200C}" + + // Real names must render as system actions, in both slots. + for name in ["علی\(zwnj)رضا", "می\(zwnj)رود", "امیر\(zwnj)حسین", "علی\(zwnj)رضا\(zwnj)پور"] { + #expect(processed("* \(name) took a screenshot *", sender: name).sender == "system") + #expect(processed("* 🫂 bob hugs \(name) *").sender == "system") + } + // A joiner after a harakat is still between two letters to a reader. + let harakat = "\u{0645}\u{062D}\u{0645}\u{0651}\u{062F}\(zwnj)\u{0631}\u{0636}\u{0627}" + #expect(processed("* \(harakat) took a screenshot *", sender: harakat).sender == "system") + + // A sentence built out of joiners is not a name: three or more gaps. + let sentence = "امنیت\(zwnj)جلسه\(zwnj)منقضی\(zwnj)شد" + #expect(processed("* \(sentence) took a screenshot *", sender: sentence).sender == sentence) + #expect(processed("* 🫂 bob hugs \(sentence) *").sender == "bob") + + // Nor is a gap opened next to anything that is not a letter. + for shape in ["امنیت:\(zwnj)جلسه", "\(zwnj)امنیت", "امنیت\(zwnj)", "ab1\(zwnj)2cd"] { + #expect(processed("* 🫂 bob hugs \(shape) *").sender == "bob") + } + + // The exception is U+200C alone — every other invisible scalar stays out. + #expect(processed("* 🫂 bob hugs a\u{200B}b *").sender == "bob") + #expect(processed("* 🫂 bob hugs a\u{200D}b *").sender == "bob") + #expect(processed("* 🫂 bob hugs a\u{2800}b *").sender == "bob") + } + @Test @MainActor func addMessageToPrivateChats_upsertsByIdAndSanitizes() async { let context = MockChatPrivateConversationContext() diff --git a/bitchatTests/EndToEnd/PrekeyEndToEndTests.swift b/bitchatTests/EndToEnd/PrekeyEndToEndTests.swift index bcccb448..40bc7e69 100644 --- a/bitchatTests/EndToEnd/PrekeyEndToEndTests.swift +++ b/bitchatTests/EndToEnd/PrekeyEndToEndTests.swift @@ -503,4 +503,36 @@ struct PrekeyEndToEndTests { await alice._test_drainAllPipelines() #expect(!alice.prekeyBundleStore.hasUsableBundle(for: bob.noiseStaticPublicKeyData())) } + + @Test func unsentBundleDoesNotStartTheRebroadcastWindow() async throws { + // The prekey store cannot be read, so the bundle is empty and nothing goes out. + let keychain = MockKeychain() + keychain.simulatedReadError = .deviceLocked + keychain.simulatedReadErrorKeys = ["prekeysV1"] + let service = BLEService( + keychain: keychain, + idBridge: NostrIdentityBridge(keychain: MockKeychainHelper()), + identityManager: MockIdentityManager(keychain), + initializeBluetoothManagers: false + ) + service.courierStore = CourierStore(persistsToDisk: false) + service.prekeyBundleStore = PrekeyBundleStore(persistsToDisk: false) + let tap = PacketTap() + service._test_onOutboundPacket = tap.record + + service.sendPrekeyBundle() + await service._test_drainAllPipelines() + #expect(tap.first(ofType: .prekeyBundle) == nil) + + // Once the store reads again, the next unforced send goes out at once, + // not after the rebroadcast window. + keychain.simulatedReadError = nil + keychain.simulatedReadErrorKeys = nil + service.sendPrekeyBundle() + let sent = await TestHelpers.waitUntil( + { tap.first(ofType: .prekeyBundle) != nil }, + timeout: TestConstants.settleTimeout + ) + #expect(sent) + } } diff --git a/bitchatTests/Mocks/MockKeychain.swift b/bitchatTests/Mocks/MockKeychain.swift index f6f3bf38..c360b316 100644 --- a/bitchatTests/Mocks/MockKeychain.swift +++ b/bitchatTests/Mocks/MockKeychain.swift @@ -33,13 +33,18 @@ final class MockKeychain: KeychainManagerProtocol { func getIdentityKey(forKey key: String) -> Data? { getIdentityKeyCallCount += 1 - if simulatedReadError != nil, - simulatedReadErrorKeys == nil || simulatedReadErrorKeys?.contains(key) == true { + if simulatedReadFault(forKey: key) != nil { return nil } return storage[key] } + /// The simulated read error for `key`. With no key filter, it applies to every key. + private func simulatedReadFault(forKey key: String) -> KeychainReadResult? { + guard simulatedReadErrorKeys?.contains(key) ?? true else { return nil } + return simulatedReadError + } + func deleteIdentityKey(forKey key: String) -> Bool { storage.removeValue(forKey: key) return true @@ -64,8 +69,7 @@ final class MockKeychain: KeychainManagerProtocol { // BCH-01-009: New methods with proper error classification func getIdentityKeyWithResult(forKey key: String) -> KeychainReadResult { getIdentityKeyCallCount += 1 - if let simulated = simulatedReadError, - simulatedReadErrorKeys == nil || simulatedReadErrorKeys?.contains(key) == true { + if let simulated = simulatedReadFault(forKey: key) { return simulated } if let data = storage[key] { diff --git a/bitchatTests/Nostr/GeoRelayDirectoryTests.swift b/bitchatTests/Nostr/GeoRelayDirectoryTests.swift index 2fcf5f37..122a83b0 100644 --- a/bitchatTests/Nostr/GeoRelayDirectoryTests.swift +++ b/bitchatTests/Nostr/GeoRelayDirectoryTests.swift @@ -680,6 +680,199 @@ final class GeoRelayDirectoryTests: XCTestCase { XCTAssertNil(harness.dependencies.userDefaults.object(forKey: "georelay.lastFetchAt")) } + func test_boundedHTTPDataReader_readsChunkedResponseWithinLimit() async throws { + let url = makeStubURL() + let session = makeStubSession() + defer { + session.invalidateAndCancel() + BoundedReaderStubURLProtocol.unregister(url: url) + } + + let part1 = Data("relay url,lat,lon\n".utf8) + let part2 = Data("relay.example,10,20\n".utf8) + let expected = part1 + part2 + BoundedReaderStubURLProtocol.register( + url: url, + behavior: .chunks(statusCode: 200, expectedContentLength: Int64(expected.count), chunks: [part1, part2]) + ) + + let data = try await BoundedHTTPDataReader.fetch( + request: URLRequest(url: url), + using: session, + maximumBytes: expected.count + ) + XCTAssertEqual(data, expected) + } + + func test_boundedHTTPDataReader_rejectsExpectedContentLengthOverLimit() async { + let url = makeStubURL() + let session = makeStubSession() + defer { + session.invalidateAndCancel() + BoundedReaderStubURLProtocol.unregister(url: url) + } + + BoundedReaderStubURLProtocol.register( + url: url, + behavior: .chunks(statusCode: 200, expectedContentLength: 100, chunks: [Data("small".utf8)]) + ) + + do { + _ = try await BoundedHTTPDataReader.fetch( + request: URLRequest(url: url), + using: session, + maximumBytes: 50 + ) + XCTFail("Expected URLError(.dataLengthExceedsMaximum)") + } catch let error as URLError { + XCTAssertEqual(error.code, .dataLengthExceedsMaximum) + } catch { + XCTFail("Unexpected error: \(error)") + } + } + + func test_boundedHTTPDataReader_rejectsStreamingChunksOverLimitWithoutContentLength() async { + let url = makeStubURL() + let session = makeStubSession() + defer { + session.invalidateAndCancel() + BoundedReaderStubURLProtocol.unregister(url: url) + } + + BoundedReaderStubURLProtocol.register( + url: url, + behavior: .chunks( + statusCode: 200, + expectedContentLength: nil, + chunks: [Data(repeating: 0x41, count: 6), Data(repeating: 0x42, count: 6)] + ) + ) + + do { + _ = try await BoundedHTTPDataReader.fetch( + request: URLRequest(url: url), + using: session, + maximumBytes: 10 + ) + XCTFail("Expected URLError(.dataLengthExceedsMaximum)") + } catch let error as URLError { + XCTAssertEqual(error.code, .dataLengthExceedsMaximum) + } catch { + XCTFail("Unexpected error: \(error)") + } + } + + func test_boundedHTTPDataReader_rejectsNon2xxStatus() async { + let url = makeStubURL() + let session = makeStubSession() + defer { + session.invalidateAndCancel() + BoundedReaderStubURLProtocol.unregister(url: url) + } + + BoundedReaderStubURLProtocol.register( + url: url, + behavior: .chunks(statusCode: 500, expectedContentLength: 0, chunks: []) + ) + + do { + _ = try await BoundedHTTPDataReader.fetch( + request: URLRequest(url: url), + using: session, + maximumBytes: 1024 + ) + XCTFail("Expected URLError(.badServerResponse)") + } catch let error as URLError { + XCTAssertEqual(error.code, .badServerResponse) + } catch { + XCTFail("Unexpected error: \(error)") + } + } + + func test_boundedHTTPDataReader_refusesRedirectWithoutFollowingTarget() async { + let url = makeStubURL() + let redirectTarget = makeStubURL() + let session = makeStubSession() + defer { + session.invalidateAndCancel() + BoundedReaderStubURLProtocol.unregister(url: url) + BoundedReaderStubURLProtocol.unregister(url: redirectTarget) + } + + BoundedReaderStubURLProtocol.register(url: url, behavior: .redirect(statusCode: 302, targetURL: redirectTarget)) + BoundedReaderStubURLProtocol.register( + url: redirectTarget, + behavior: .chunks(statusCode: 200, expectedContentLength: 2, chunks: [Data("ok".utf8)]) + ) + + do { + _ = try await BoundedHTTPDataReader.fetch( + request: URLRequest(url: url), + using: session, + maximumBytes: 1024 + ) + XCTFail("Expected URLError(.badServerResponse)") + } catch let error as URLError { + XCTAssertEqual(error.code, .badServerResponse) + } catch { + XCTFail("Unexpected error: \(error)") + } + + XCTAssertEqual(BoundedReaderStubURLProtocol.requestCount(for: url), 1) + XCTAssertEqual(BoundedReaderStubURLProtocol.requestCount(for: redirectTarget), 0) + } + + func test_boundedHTTPDataReader_propagatesTaskCancellation() async { + let url = makeStubURL() + let session = makeStubSession() + defer { + session.invalidateAndCancel() + BoundedReaderStubURLProtocol.unregister(url: url) + } + + let started = StubSignal() + let stopped = StubSignal() + BoundedReaderStubURLProtocol.register( + url: url, + behavior: .hangUntilCancelled(started: started, stopped: stopped) + ) + + let fetchTask = Task.detached { + try await BoundedHTTPDataReader.fetch( + request: URLRequest(url: url), + using: session, + maximumBytes: 1024 + ) + } + + let didStart = await started.wait() + XCTAssertTrue(didStart) + fetchTask.cancel() + + do { + _ = try await fetchTask.value + XCTFail("Expected CancellationError") + } catch is CancellationError { + let didStop = await stopped.wait() + XCTAssertTrue(didStop) + XCTAssertGreaterThanOrEqual(BoundedReaderStubURLProtocol.stopCount(for: url), 1) + } catch let error as URLError where error.code == .cancelled { + XCTFail("Expected CancellationError rather than URLError.cancelled") + } catch { + XCTFail("Unexpected error: \(error)") + } + } + + private func makeStubURL() -> URL { + URL(string: "https://geo-reader-test.example/\(UUID().uuidString)/relays.csv")! + } + + private func makeStubSession() -> URLSession { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [BoundedReaderStubURLProtocol.self] + return URLSession(configuration: configuration) + } + private func makeHarness( cacheCSV: String? = nil, bundleCSV: String? = nil, @@ -895,3 +1088,188 @@ private enum GeoRelayTestError: Error { private func isExecutingOnMainThread() -> Bool { Thread.isMainThread } + +private final class StubSignal: @unchecked Sendable { + private let lock = NSLock() + private var signaled = false + private var continuation: CheckedContinuation? + + func signal() { + let pending: CheckedContinuation? = lock.withLock { + signaled = true + let cont = continuation + continuation = nil + return cont + } + pending?.resume(returning: true) + } + + func wait(timeoutNanoseconds: UInt64 = 2_000_000_000) async -> Bool { + await withCheckedContinuation { cont in + let resumeImmediately: Bool = lock.withLock { + if signaled { + return true + } + continuation = cont + return false + } + if resumeImmediately { + cont.resume(returning: true) + return + } + Task.detached { [weak self] in + try? await Task.sleep(nanoseconds: timeoutNanoseconds) + guard let self else { return } + let timedOut: CheckedContinuation? = self.lock.withLock { + guard !self.signaled, let pending = self.continuation else { return nil } + self.continuation = nil + return pending + } + timedOut?.resume(returning: false) + } + } + } +} + +private final class BoundedReaderStubURLProtocol: URLProtocol, @unchecked Sendable { + enum StubBehavior: @unchecked Sendable { + case chunks(statusCode: Int, expectedContentLength: Int64?, chunks: [Data]) + case redirect(statusCode: Int, targetURL: URL) + case hangUntilCancelled(started: StubSignal, stopped: StubSignal) + } + + private static let lock = NSLock() + private static var behaviorsByURL: [URL: StubBehavior] = [:] + private static var requestsByURL: [URL: Int] = [:] + private static var stopCountsByURL: [URL: Int] = [:] + + private let stateLock = NSLock() + private var stopped = false + private var stopSignal: StubSignal? + + static func register(url: URL, behavior: StubBehavior) { + lock.lock() + behaviorsByURL[url] = behavior + requestsByURL[url] = 0 + stopCountsByURL[url] = 0 + lock.unlock() + } + + static func unregister(url: URL) { + lock.lock() + behaviorsByURL.removeValue(forKey: url) + requestsByURL.removeValue(forKey: url) + stopCountsByURL.removeValue(forKey: url) + lock.unlock() + } + + static func requestCount(for url: URL) -> Int { + lock.lock() + defer { lock.unlock() } + return requestsByURL[url] ?? 0 + } + + static func stopCount(for url: URL) -> Int { + lock.lock() + defer { lock.unlock() } + return stopCountsByURL[url] ?? 0 + } + + override static func canInit(with request: URLRequest) -> Bool { + guard let url = request.url else { return false } + lock.lock() + let registered = behaviorsByURL[url] != nil + lock.unlock() + return registered + } + + override static func canonicalRequest(for request: URLRequest) -> URLRequest { + request + } + + override func startLoading() { + guard let url = request.url else { + client?.urlProtocol(self, didFailWithError: URLError(.badURL)) + return + } + + let behavior: StubBehavior? = Self.lock.withLock { + Self.requestsByURL[url, default: 0] += 1 + return Self.behaviorsByURL[url] + } + + guard let behavior else { + client?.urlProtocol(self, didFailWithError: URLError(.unsupportedURL)) + return + } + + switch behavior { + case .chunks(let statusCode, let expectedContentLength, let chunks): + var headers: [String: String] = [:] + if let expectedContentLength { + headers["Content-Length"] = "\(expectedContentLength)" + } + let response = HTTPURLResponse( + url: url, + statusCode: statusCode, + httpVersion: "HTTP/1.1", + headerFields: headers.isEmpty ? nil : headers + )! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + for chunk in chunks { + if isStopped { return } + client?.urlProtocol(self, didLoad: chunk) + } + if !isStopped { + client?.urlProtocolDidFinishLoading(self) + } + + case .redirect(let statusCode, let targetURL): + let response = HTTPURLResponse( + url: url, + statusCode: statusCode, + httpVersion: "HTTP/1.1", + headerFields: ["Location": targetURL.absoluteString] + )! + client?.urlProtocol(self, wasRedirectedTo: URLRequest(url: targetURL), redirectResponse: response) + if !isStopped { + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + } + if !isStopped { + client?.urlProtocolDidFinishLoading(self) + } + + case .hangUntilCancelled(let started, let stopped): + stateLock.withLock { + stopSignal = stopped + } + let response = HTTPURLResponse( + url: url, + statusCode: 200, + httpVersion: "HTTP/1.1", + headerFields: nil + )! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + started.signal() + } + } + + override func stopLoading() { + let signalToFire: StubSignal? = stateLock.withLock { + stopped = true + let signal = stopSignal + stopSignal = nil + return signal + } + if let url = request.url { + Self.lock.withLock { + Self.stopCountsByURL[url, default: 0] += 1 + } + } + signalToFire?.signal() + } + + private var isStopped: Bool { + stateLock.withLock { stopped } + } +} diff --git a/bitchatTests/PlaceFeedTests.swift b/bitchatTests/PlaceFeedTests.swift index f06be737..cbe07e67 100644 --- a/bitchatTests/PlaceFeedTests.swift +++ b/bitchatTests/PlaceFeedTests.swift @@ -441,6 +441,16 @@ struct PlaceFeedManagerTests { // Search query matches content or author case-insensitively let search = PlaceFeedOrganizer.organize(items: items, sort: .latest, filter: .all, query: "CAROL") #expect(search.map(\.id) == ["c3"]) + + // Blocked Nostr pubkeys are excluded case-insensitively + let unblocked = PlaceFeedOrganizer.organize( + items: items, + sort: .latest, + filter: .all, + blockedPubkeys: [items[1].nostrNote!.pubkey.lowercased()] + ) + #expect(unblocked.count == items.count - 1) + #expect(!unblocked.contains(where: { $0.id == items[1].id })) } @Test diff --git a/bitchatTests/Services/GroupStoreTests.swift b/bitchatTests/Services/GroupStoreTests.swift index 5858fd47..be20a29b 100644 --- a/bitchatTests/Services/GroupStoreTests.swift +++ b/bitchatTests/Services/GroupStoreTests.swift @@ -349,4 +349,29 @@ struct GroupStoreTests { #expect(store.groups.count == BitchatGroup.maxGroups) #expect(store.key(forGroupID: overflowID) == nil) } + + @Test func retriesUnavailableLoadOnMutationAfterKeychainUnlocks() throws { + let keychain = MockKeychain() + let fileURL = tempFileURL() + defer { try? FileManager.default.removeItem(at: fileURL.deletingLastPathComponent()) } + + // Persist an existing group while unlocked. + let initial = GroupStore(keychain: keychain, fileURL: fileURL) + let existing = try #require(initial.createGroup(named: "original", creator: makeMember(seed: 0xE1))) + AppSupportFileStore.drainPendingWrites() + + // Relaunch while Keychain is locked: startup read becomes unavailable. + keychain.simulatedReadError = .deviceLocked + let relaunched = GroupStore(keychain: keychain, fileURL: fileURL) + #expect(relaunched.groups.isEmpty) + + // Once unlocked, creating a new group retries loading the original group + // and durably persists both instead of silently discarding writes forever. + keychain.simulatedReadError = nil + let added = try #require(relaunched.createGroup(named: "after-unlock", creator: makeMember(seed: 0xE2))) + AppSupportFileStore.drainPendingWrites() + + let verified = GroupStore(keychain: keychain, fileURL: fileURL) + #expect(Set(verified.groups.map(\.groupID)) == Set([existing.groupID, added.groupID])) + } } diff --git a/bitchatTests/Services/KeychainTransientReadSafetyTests.swift b/bitchatTests/Services/KeychainTransientReadSafetyTests.swift index ce26fc2b..89246742 100644 --- a/bitchatTests/Services/KeychainTransientReadSafetyTests.swift +++ b/bitchatTests/Services/KeychainTransientReadSafetyTests.swift @@ -64,7 +64,6 @@ final class KeychainTransientReadSafetyTests: XCTestCase { // Simulate locked keychain on next launch: store must fail closed and // must NOT latch `loaded = true` or overwrite Keychain with fresh IDs. keychain.simulatedReadError = .deviceLocked - keychain.simulatedReadErrorKeys = ["prekeysV1"] let store2 = LocalPrekeyStore(keychain: keychain) XCTAssertTrue(store2.currentBundlePrekeys().prekeys.isEmpty) XCTAssertNil(store2.privateKey(for: firstPrekeyID)) @@ -74,7 +73,6 @@ final class KeychainTransientReadSafetyTests: XCTestCase { // Once unlocked, the SAME store2 instance retries loadLocked() and // recovers the exact persisted prekey privates intact. keychain.simulatedReadError = nil - keychain.simulatedReadErrorKeys = nil let recoveredPrivate = try XCTUnwrap(store2.privateKey(for: firstPrekeyID)) XCTAssertEqual(recoveredPrivate.rawRepresentation, firstPrivateBefore.rawRepresentation) XCTAssertEqual(store2.currentBundlePrekeys().prekeys, initialBundle.prekeys) diff --git a/bitchatTests/Services/NostrRelayManagerTests.swift b/bitchatTests/Services/NostrRelayManagerTests.swift index f2e4ff54..be905e37 100644 --- a/bitchatTests/Services/NostrRelayManagerTests.swift +++ b/bitchatTests/Services/NostrRelayManagerTests.swift @@ -1901,6 +1901,180 @@ final class NostrRelayManagerTests: XCTestCase { XCTAssertTrue(context.manager.relays.contains { $0.url == "wss://nos.lol" }) } + func test_verificationFingerprint_distinguishesUnicodeNormalizedContentAndTagsAndMatchesBridgedNSString() throws { + let identity = try NostrIdentity.generate() + let genuine = try NostrEvent( + pubkey: identity.publicKeyHex, + createdAt: Date(), + kind: .textNote, + tags: [["t", "\u{00E9}"]], + content: "caf\u{00E9}" + ).sign(with: identity.schnorrSigningKey()) + + let nfdContent = try makeEventCopy(from: genuine, content: "cafe\u{0301}") + let nfdTag = try makeEventCopy(from: genuine, tags: [["t", "e\u{0301}"]]) + let bridged = try makeEventCopy( + from: genuine, + content: ("caf\u{00E9}" as NSString) as String, + tags: [[("t" as NSString) as String, ("\u{00E9}" as NSString) as String]] + ) + let nilSig = try makeEventCopy(from: genuine, sig: .some(nil)) + let emptySig = try makeEventCopy(from: genuine, sig: .some("")) + + // Swift String equality considers NFC and NFD equal, whereas Nostr event IDs hash UTF-8 bytes. + XCTAssertEqual(genuine.content, nfdContent.content) + XCTAssertNotEqual( + InboundFrameRouter.VerificationFingerprint(event: genuine), + InboundFrameRouter.VerificationFingerprint(event: nfdContent) + ) + XCTAssertNotEqual( + InboundFrameRouter.VerificationFingerprint(event: genuine), + InboundFrameRouter.VerificationFingerprint(event: nfdTag) + ) + XCTAssertNotEqual( + InboundFrameRouter.VerificationFingerprint(event: nilSig), + InboundFrameRouter.VerificationFingerprint(event: emptySig) + ) + + let fpGenuine = InboundFrameRouter.VerificationFingerprint(event: genuine) + let fpBridged = InboundFrameRouter.VerificationFingerprint(event: bridged) + XCTAssertEqual(fpGenuine, fpBridged) + XCTAssertEqual(fpGenuine.hashValue, fpBridged.hashValue) + } + + func test_verifySignatureCoalesced_doesNotCoalesceUnicodeNormalizedForgedCopyWithGenuineEvent() async throws { + let identity = try NostrIdentity.generate() + let genuine = try NostrEvent( + pubkey: identity.publicKeyHex, + createdAt: Date(), + kind: .textNote, + tags: [["t", "\u{00E9}"]], + content: "caf\u{00E9}" + ).sign(with: identity.schnorrSigningKey()) + let forgedNFD = try makeEventCopy(from: genuine, content: "cafe\u{0301}") + + // Case A: genuine NFC enters first and holds in-flight while forged NFD arrives. + do { + let router = InboundFrameRouter() + let counter = VerificationCallCounter() + let firstEntered = DispatchSemaphore(value: 0) + let releaseFirst = DispatchSemaphore(value: 0) + + let firstTask = Task.detached(priority: .userInitiated) { + await router.verifySignatureCoalesced(genuine) { event in + counter.increment() + firstEntered.signal() + _ = releaseFirst.wait(timeout: .now() + 2) + return event.isValidSignature() + } + } + XCTAssertEqual(firstEntered.wait(timeout: .now() + 2), .success) + + let secondTask = Task.detached(priority: .userInitiated) { + await router.verifySignatureCoalesced(forgedNFD) { event in + counter.increment() + return event.isValidSignature() + } + } + + let secondResult = await secondTask.value + releaseFirst.signal() + let firstResult = await firstTask.value + + XCTAssertTrue(firstResult) + XCTAssertFalse(secondResult) + XCTAssertEqual(counter.count, 2) + } + + // Case B: forged NFD enters first and holds in-flight while genuine NFC arrives. + do { + let router = InboundFrameRouter() + let counter = VerificationCallCounter() + let firstEntered = DispatchSemaphore(value: 0) + let releaseFirst = DispatchSemaphore(value: 0) + + let firstTask = Task.detached(priority: .userInitiated) { + await router.verifySignatureCoalesced(forgedNFD) { event in + counter.increment() + firstEntered.signal() + _ = releaseFirst.wait(timeout: .now() + 2) + return event.isValidSignature() + } + } + XCTAssertEqual(firstEntered.wait(timeout: .now() + 2), .success) + + let secondTask = Task.detached(priority: .userInitiated) { + await router.verifySignatureCoalesced(genuine) { event in + counter.increment() + return event.isValidSignature() + } + } + + let secondResult = await secondTask.value + releaseFirst.signal() + let firstResult = await firstTask.value + + XCTAssertFalse(firstResult) + XCTAssertTrue(secondResult) + XCTAssertEqual(counter.count, 2) + } + } + + func test_verifySignatureCoalesced_coalescesByteIdenticalConcurrentDeliveries() async throws { + let genuine = try makeSignedEvent(content: "coalesce-me") + let duplicate = try makeEventCopy(from: genuine) + let router = InboundFrameRouter() + let counter = VerificationCallCounter() + let firstEntered = DispatchSemaphore(value: 0) + let releaseFirst = DispatchSemaphore(value: 0) + + let firstTask = Task.detached(priority: .userInitiated) { + await router.verifySignatureCoalesced(genuine) { event in + counter.increment() + firstEntered.signal() + _ = releaseFirst.wait(timeout: .now() + 2) + return event.isValidSignature() + } + } + XCTAssertEqual(firstEntered.wait(timeout: .now() + 2), .success) + + let secondTask = Task.detached(priority: .userInitiated) { + await router.verifySignatureCoalesced(duplicate) { event in + counter.increment() + return event.isValidSignature() + } + } + try? await Task.sleep(nanoseconds: 50_000_000) + releaseFirst.signal() + + let firstResult = await firstTask.value + let secondResult = await secondTask.value + XCTAssertTrue(firstResult) + XCTAssertTrue(secondResult) + XCTAssertEqual(counter.count, 1) + } + + private func makeEventCopy( + from base: NostrEvent, + content: String? = nil, + tags: [[String]]? = nil, + sig: String?? = nil + ) throws -> NostrEvent { + var dict: [String: Any] = [ + "id": base.id, + "pubkey": base.pubkey, + "created_at": base.created_at, + "kind": base.kind, + "tags": tags ?? base.tags, + "content": content ?? base.content + ] + let resolvedSig = sig ?? base.sig + if let resolvedSig { + dict["sig"] = resolvedSig + } + return try NostrEvent(from: dict) + } + // MARK: - Offline ↔ Online & Path Recovery @MainActor @@ -2311,3 +2485,20 @@ private final class MockRelayConnection: NostrRelayConnectionProtocol { } } } + +private final class VerificationCallCounter: @unchecked Sendable { + private let lock = NSLock() + private var value = 0 + + var count: Int { + lock.lock() + defer { lock.unlock() } + return value + } + + func increment() { + lock.lock() + value += 1 + lock.unlock() + } +} diff --git a/bitchatTests/Services/NotificationServiceTests.swift b/bitchatTests/Services/NotificationServiceTests.swift index 8caedc46..c42e26be 100644 --- a/bitchatTests/Services/NotificationServiceTests.swift +++ b/bitchatTests/Services/NotificationServiceTests.swift @@ -86,7 +86,7 @@ final class NotificationServiceTests: XCTestCase { XCTAssertEqual(request?.content.title, "🔒 DM from Alice") XCTAssertEqual(request?.content.body, "hi") XCTAssertEqual(request?.content.userInfo["peerID"] as? String, peerID.id) - XCTAssertEqual(request?.content.userInfo["senderName"] as? String, "Alice") + XCTAssertEqual(request?.content.userInfo.count, 1) } func test_sendPrivateMessageNotification_formatsMediaAndReactions() { @@ -136,6 +136,7 @@ final class NotificationServiceTests: XCTestCase { XCTAssertFalse(request?.content.body.contains("hi") ?? true) XCTAssertFalse(request?.content.title.isEmpty ?? true) XCTAssertEqual(request?.content.userInfo["peerID"] as? String, peerID.id) + XCTAssertEqual(request?.content.userInfo.count, 1) } func test_wrapperNotifications_setExpectedIdentifiersAndDeepLinks() { @@ -191,6 +192,129 @@ final class NotificationServiceTests: XCTestCase { XCTAssertEqual(removePendingCalls, 0) XCTAssertEqual(removeDeliveredCalls, 0) } + + func test_clearAllNotificationsForPanic_invalidatesPostsBeforeRemoving() { + let generation = NotificationPostGeneration() + let postedBefore = generation.current + var stillCurrentAtRemoval: Bool? + var deps = NotificationService.Dependencies.noop + deps.removeAllPending = { + stillCurrentAtRemoval = generation.isCurrent(postedBefore) + } + let service = NotificationService( + isRunningTestsProvider: { false }, + dependencies: deps, + postGeneration: generation + ) + + service.clearAllNotificationsForPanic() + + XCTAssertEqual(stillCurrentAtRemoval, false) + } + + func test_deliver_handsTheCenterARequestNoWipeOvertook() async { + let center = FakeNotificationCenter() + let generation = NotificationPostGeneration() + + await NotificationService.deliver( + Self.request("dm-1"), + postedIn: generation.current, + to: center, + generation: generation + ) + + XCTAssertEqual(center.added, ["dm-1"]) + XCTAssertEqual(center.removedDelivered, []) + XCTAssertEqual(center.removedPending, []) + } + + func test_deliver_dropsARequestPostedBeforeAWipe() async { + let center = FakeNotificationCenter() + let generation = NotificationPostGeneration() + let postedIn = generation.current + generation.invalidate() + + await NotificationService.deliver( + Self.request("dm-1"), + postedIn: postedIn, + to: center, + generation: generation + ) + + XCTAssertEqual(center.added, []) + } + + func test_deliver_takesBackARequestAWipeOvertakesInFlight() async { + let center = FakeNotificationCenter() + let addStarted = expectation(description: "the center started taking the request") + center.holdAdds { addStarted.fulfill() } + let generation = NotificationPostGeneration() + let postedIn = generation.current + + let delivery = Task { + await NotificationService.deliver( + Self.request("dm-1"), + postedIn: postedIn, + to: center, + generation: generation + ) + } + await fulfillment(of: [addStarted], timeout: TestConstants.settleTimeout) + generation.invalidate() + center.releaseHeldAdd() + await delivery.value + + XCTAssertEqual(center.added, ["dm-1"]) + XCTAssertEqual(center.removedDelivered, ["dm-1"]) + XCTAssertEqual(center.removedPending, ["dm-1"]) + } + + private static func request(_ identifier: String) -> UNNotificationRequest { + UNNotificationRequest(identifier: identifier, content: UNMutableNotificationContent(), trigger: nil) + } +} + +private final class FakeNotificationCenter: NotificationCenterPosting, @unchecked Sendable { + private let lock = NSLock() + private var addedIDs: [String] = [] + private var removedDeliveredIDs: [String] = [] + private var removedPendingIDs: [String] = [] + private var onAddHeld: (() -> Void)? + private var heldAdd: CheckedContinuation? + + var added: [String] { lock.withLock { addedIDs } } + var removedDelivered: [String] { lock.withLock { removedDeliveredIDs } } + var removedPending: [String] { lock.withLock { removedPendingIDs } } + + func holdAdds(onHeld: @escaping () -> Void) { + lock.withLock { onAddHeld = onHeld } + } + + func releaseHeldAdd() { + let continuation = lock.withLock { () -> CheckedContinuation? in + defer { heldAdd = nil } + return heldAdd + } + continuation?.resume() + } + + func add(_ request: UNNotificationRequest) async throws { + if let onHeld = lock.withLock({ onAddHeld }) { + await withCheckedContinuation { continuation in + lock.withLock { heldAdd = continuation } + onHeld() + } + } + lock.withLock { addedIDs.append(request.identifier) } + } + + func removeDeliveredNotifications(withIdentifiers identifiers: [String]) { + lock.withLock { removedDeliveredIDs += identifiers } + } + + func removePendingNotificationRequests(withIdentifiers identifiers: [String]) { + lock.withLock { removedPendingIDs += identifiers } + } } private extension Array { diff --git a/bitchatTests/Services/Phase1FeaturesTests.swift b/bitchatTests/Services/Phase1FeaturesTests.swift index 05686386..dbbc92c8 100644 --- a/bitchatTests/Services/Phase1FeaturesTests.swift +++ b/bitchatTests/Services/Phase1FeaturesTests.swift @@ -1030,4 +1030,32 @@ final class InboxPinnedChatsTests: XCTestCase { XCTAssertEqual(MessageInteractionCodec.matchingMessageIDs(in: [voice], query: "0D84B302"), []) XCTAssertEqual(MessageInteractionCodec.matchingMessageIDs(in: [voice], query: "voice"), ["v1"]) } + + func test_matchesQuotedSnippetHandlesFormattedMediaAndLegacyRawSnippets() { + let voiceRaw = "[voice] 0D84B302-F93A-45D5-986A-CE9196C.m4a" + let photoRaw = "[image] 9F11B2C3-1111-2222-3333-444455556666.jpg" + let fileRaw = "[file] itinerary.pdf" + + // Formatted media snippets produced by makeSnippet + XCTAssertTrue(MessageInteractionCodec.matchesQuotedSnippet( + MessageInteractionCodec.makeSnippet(from: voiceRaw), + in: voiceRaw + )) + XCTAssertTrue(MessageInteractionCodec.matchesQuotedSnippet( + MessageInteractionCodec.makeSnippet(from: photoRaw), + in: photoRaw + )) + XCTAssertTrue(MessageInteractionCodec.matchesQuotedSnippet( + MessageInteractionCodec.makeSnippet(from: fileRaw), + in: fileRaw + )) + + // Legacy raw media snippets remain navigable + XCTAssertTrue(MessageInteractionCodec.matchesQuotedSnippet("[voice] 0D84B302…", in: voiceRaw)) + + // Normal text & nested quoted replies + let quotedText = "> @alice: earlier\nSee you at noon" + XCTAssertTrue(MessageInteractionCodec.matchesQuotedSnippet("See you at noon", in: quotedText)) + XCTAssertFalse(MessageInteractionCodec.matchesQuotedSnippet("unrelated", in: voiceRaw)) + } } diff --git a/docs/privacy-assessment.md b/docs/privacy-assessment.md index b25caf26..21f739c7 100644 --- a/docs/privacy-assessment.md +++ b/docs/privacy-assessment.md @@ -97,7 +97,7 @@ Residual risk: Nostr relay retention and logging are outside project control. Pu The realistic compromise for many of the people this app is built for is not interception but a phone taken and, often, unlocked under coercion. -- Notification content is rendered by the system on the lock screen, so it is readable without unlocking. Message previews are therefore hidden by default: alerts state that a direct message, mention, or location-channel activity arrived, and withhold the message body, the sender's nickname, and the geohash until the app is opened. `userInfo` still carries the routing peer ID and deep link, neither of which the system displays. The preference is `notifications.hideMessagePreviews`; turning it off restores full previews. +- Notification content is rendered by the system on the lock screen, so it is readable without unlocking. Message previews are therefore hidden by default: alerts state that a direct message, mention, or location-channel activity arrived, and withhold the message body, the sender's nickname, and the geohash until the app is opened. `userInfo` still carries the routing peer ID and deep link, neither of which the system displays. The preference is `notifications.hideMessagePreviews`; turning it off restores full previews. Panic wipe removes bitchat's notifications from Notification Center and fences in-flight posts. That is removal, not erasure: the system can keep its own record of notifications it has shown, out of the app's reach, so with previews on their text can outlive the wipe. - The window is covered on `willResignActive`, so the snapshot iOS stores for the app switcher shows a placeholder rather than an open conversation. The cover is opaque rather than blurred, and is added synchronously because the capture follows shortly after that notification. Panic wipe separately deletes snapshots already on disk. - Clearing a mesh timeline erases the on-disk gossip archive behind it, so cleared public history is deleted rather than hidden. The echo watermark still suppresses pre-clear messages this device hears again from peers. - Managed media is bounded by age as well as size, so a received photo does not outlive its conversation indefinitely. @@ -110,7 +110,7 @@ Not addressed, and deliberately out of scope here: ## Panic Wipe Coverage -The panic action clears identity/session state, encrypted private chat history (`EncryptedHistoryStore`), preferences, location state, groups, prekeys, outbox mail, courier mail, bridge dedup state, gossip archive, board data, managed media, hand-added relays, and active subscriptions/transports. Managed media deletion completes synchronously, after active media work has been invalidated. In Stealth Mode (and on 1.x upgrades until changed), triple-tapping the top header bar triggers the panic confirmation dialog and panic reset preserves the Stealth/Tor posture rather than reverting to disk-persisted Everyday Mode. Keychain secrets use device-only accessibility, and an install marker detects and clears app keys that survive uninstall before a later reinstall can use them. New persistent stores must add an explicit wipe hook and a regression test. +The panic action clears identity/session state, encrypted private chat history (`EncryptedHistoryStore`), preferences, location state, groups, prekeys, outbox mail, courier mail, bridge dedup state, gossip archive, board data, managed media, hand-added relays, bitchat's notifications in Notification Center (removal only; see Locked and Seized Devices), and active subscriptions/transports. Managed media deletion completes synchronously, after active media work has been invalidated. In Stealth Mode (and on 1.x upgrades until changed), triple-tapping the top header bar triggers the panic confirmation dialog and panic reset preserves the Stealth/Tor posture rather than reverting to disk-persisted Everyday Mode. Keychain secrets use device-only accessibility, and an install marker detects and clears app keys that survive uninstall before a later reinstall can use them. New persistent stores must add an explicit wipe hook and a regression test. ## Release Review Checklist diff --git a/localPackages/Arti/Sources/TorManager.swift b/localPackages/Arti/Sources/TorManager.swift index 1382b21b..f6933d5e 100644 --- a/localPackages/Arti/Sources/TorManager.swift +++ b/localPackages/Arti/Sources/TorManager.swift @@ -358,31 +358,22 @@ public final class TorManager: ObservableObject { nonisolated private func bootstrapPollLoop(generation: Int) async { let deadline = Date().addingTimeInterval(75) var didComplete = false - var lastPublishedProgress: Int? while Date() < deadline { let progress = Int(arti_bootstrap_progress()) - if progress != lastPublishedProgress || progress >= 100 { - lastPublishedProgress = progress - let stillCurrent: Bool = await MainActor.run { - guard generation == self.bootstrapGeneration else { return false } - if self.bootstrapProgress != progress { - self.bootstrapProgress = progress - } - if progress >= 100, self.isStarting { - self.isStarting = false - } - self.recomputeReady() - return true + let stillCurrent: Bool = await MainActor.run { + guard generation == self.bootstrapGeneration else { return false } + if self.bootstrapProgress != progress { + self.bootstrapProgress = progress } - guard stillCurrent else { return } - } else { - let stillCurrent: Bool = await MainActor.run { - generation == self.bootstrapGeneration + if progress >= 100, self.isStarting { + self.isStarting = false } - guard stillCurrent else { return } + self.recomputeReady() + return true } + guard stillCurrent else { return } if progress >= 100 { didComplete = true