Merge main into fix/gift-wrap-outer-timestamp-window

This commit is contained in:
Taksh 2026-09-25 15:45:01 +05:30
commit 108a9eb00f
66 changed files with 3758 additions and 261 deletions

View File

@ -98,7 +98,7 @@ jobs:
path: SOURCE-MANIFEST.txt
- name: Attach to release
if: startsWith(github.ref, 'refs/tags/')
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
env:
GH_TOKEN: ${{ github.token }}
run: |

114
.github/workflows/validate_georelays.yml vendored Normal file
View File

@ -0,0 +1,114 @@
name: Validate GeoRelay Data
# The weekly automation validates a relay snapshot before pushing its branch,
# but that check lives inside the scheduled job: a relay-directory change that
# arrives as a pull request is otherwise reviewed on faith. This runs the same
# validator against the reviewed baseline and publishes the resulting hash, so
# a proposed snapshot can be matched against the one the automation published.
on:
pull_request:
paths:
- "relays/online_relays_gps.csv"
- "scripts/validate_georelays.py"
- "scripts/tests/**"
- ".github/workflows/validate_georelays.yml"
# Both jobs run against pull-request content. Read-only, no secrets, and never
# pull_request_target.
permissions:
contents: read
# A superseded run has nothing left to report; the sibling PR workflows do not
# set this, so drop it if the repo prefers them uniform.
concurrency:
group: validate-georelays-${{ github.ref }}
cancel-in-progress: true
jobs:
# The trust boundary. Nothing authored by the pull request executes in this
# job, and the bytes it validates come from a git object rather than a
# worktree that PR-authored code could have rewritten.
gate:
name: Validate relay directory
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Check out the reviewed base
# base.sha, not the merge ref: the pull request's validator and its
# tests are never present in this workspace, so the gate cannot be
# influenced by code under review.
uses: actions/checkout@v5
with:
ref: ${{ github.event.pull_request.base.sha }}
persist-credentials: false
- name: Validate the proposed relay directory
env:
PR_NUMBER: ${{ github.event.pull_request.number }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
set -euo pipefail
# Read the candidate as a git object pinned to the event's head commit.
# Reading it from a checked-out worktree would let PR-authored code
# swap the file first, so the hash below would describe a snapshot
# that never merges.
git fetch --no-tags --depth=1 origin "refs/pull/${PR_NUMBER}/head"
fetched_sha="$(git rev-parse FETCH_HEAD)"
if [[ "$fetched_sha" != "$HEAD_SHA" ]]; then
echo "::error::pull request head moved to $fetched_sha since this event ($HEAD_SHA); a newer run validates it"
exit 1
fi
git show "${HEAD_SHA}:relays/online_relays_gps.csv" > "$RUNNER_TEMP/candidate.csv"
# Validator and baseline are the checked-out base commit's, so a change
# cannot relax the rule that judges it. --output is required and gets a
# verbatim copy of --input; it stays in RUNNER_TEMP.
python3 scripts/validate_georelays.py \
--input "$RUNNER_TEMP/candidate.csv" \
--baseline relays/online_relays_gps.csv \
--output "$RUNNER_TEMP/validated-copy.csv" \
--github-output "$RUNNER_TEMP/summary.txt"
# Publish the hash so a reviewer can match a proposed snapshot against
# the one the automation published, instead of taking it on faith.
{
echo "### GeoRelay validation"
echo
sed 's/^/- /' "$RUNNER_TEMP/summary.txt"
} >> "$GITHUB_STEP_SUMMARY"
# Runs code authored by the pull request, so it is an honest-mistake check and
# not a trust boundary: it catches a validator change that would invalidate the
# committed directory and break the weekly automation after merge.
proposed-validator:
name: Test the proposed validator
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Check out the pull request
uses: actions/checkout@v5
with:
persist-credentials: false
- name: Test GeoRelay validator
run: python3 -m unittest discover -s scripts/tests -p "test_*.py" -v
- name: Run the proposed validator against the real directory
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
set -euo pipefail
# Without this the proposed validator only ever sees unit-test
# fixtures, and a new constraint can make the committed directory
# invalid while this workflow stays green.
git fetch --no-tags --depth=1 origin "$BASE_SHA"
git show "${BASE_SHA}:relays/online_relays_gps.csv" > "$RUNNER_TEMP/baseline.csv"
python3 scripts/validate_georelays.py \
--input relays/online_relays_gps.csv \
--baseline "$RUNNER_TEMP/baseline.csv" \
--output "$RUNNER_TEMP/proposed-copy.csv"

View File

@ -98,6 +98,10 @@ final class ConversationUIModel: ObservableObject {
chatViewModel.unblockMeshPeer(peerID: peerID, displayName: displayName)
}
func getFingerprint(for peerID: PeerID) -> String? {
chatViewModel.getFingerprint(for: peerID)
}
func updateAutocomplete(for text: String, cursorPosition: Int) {
chatViewModel.updateAutocomplete(for: text, cursorPosition: cursorPosition)
}

View File

@ -66,12 +66,24 @@ final class SecureNoiseSession: NoiseSession {
if messageCount >= messageThreshold {
return true
}
// Check if last activity was more than 30 minutes ago
// Check if last activity exceeded sessionTimeout
if Date().timeIntervalSince(lastActivityTime) > NoiseSecurityConstants.sessionTimeout {
return true
}
// A session that never goes idle (a long-lived conversation with
// steady traffic) keeps refreshing lastActivityTime forever, so the
// check above never fires -- only sessionStartTime tracks how close
// encrypt/decrypt are to the hard sessionExpired cutoff above. Firing
// at 90% of sessionTimeout leaves the rekey timer's polling interval
// (checked every 60s, see NoiseEncryptionService.rekeyCheckInterval)
// room to complete a full handshake well before the old session
// starts throwing sessionExpired on every call.
if Date().timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout * 0.9 {
return true
}
return false
}

View File

@ -55,7 +55,8 @@ struct NostrEmbeddedBitChat {
}
/// Build a `bitchat1:` ACK (delivered/read) without an embedded recipient peer ID (geohash DMs).
static func encodeAckForNostrNoRecipient(type: NoisePayloadType, messageID: String, senderPeerID: PeerID) -> String? {
/// The sender ID is random per envelope; see `unlinkableSenderID()`.
static func encodeAckForNostrNoRecipient(type: NoisePayloadType, messageID: String) -> String? {
guard type == .delivered || type == .readReceipt else { return nil }
var payload = Data([type.rawValue])
@ -63,7 +64,7 @@ struct NostrEmbeddedBitChat {
let packet = BitchatPacket(
type: MessageType.noiseEncrypted.rawValue,
senderID: Data(hexString: senderPeerID.id) ?? Data(),
senderID: unlinkableSenderID(),
recipientID: nil,
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
payload: payload,
@ -76,7 +77,8 @@ struct NostrEmbeddedBitChat {
}
/// Build a `bitchat1:` payload without an embedded recipient peer ID (used for geohash DMs).
static func encodePMForNostrNoRecipient(content: String, messageID: String, senderPeerID: PeerID) -> String? {
/// The sender ID is random per envelope; see `unlinkableSenderID()`.
static func encodePMForNostrNoRecipient(content: String, messageID: String) -> String? {
let pm = PrivateMessagePacket(messageID: messageID, content: content)
guard let tlv = pm.encode() else { return nil }
@ -85,7 +87,7 @@ struct NostrEmbeddedBitChat {
let packet = BitchatPacket(
type: MessageType.noiseEncrypted.rawValue,
senderID: Data(hexString: senderPeerID.id) ?? Data(),
senderID: unlinkableSenderID(),
recipientID: nil,
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
payload: payload,
@ -97,6 +99,18 @@ struct NostrEmbeddedBitChat {
return "bitchat1:" + base64URLEncode(data)
}
/// Sender ID for the recipient-less envelopes above. They go out under a
/// per-geohash identity (and as the acks for inbound account DMs), where
/// no receiver reads this field: iOS and Android both key these
/// conversations on the Nostr sender pubkey. The mesh peer ID must never
/// go here: it is the stable Noise fingerprint prefix, so anyone who DMs
/// a geohash identity (and gets the automatic DELIVERED ack back) could
/// link that persona to the device and to its other geohash personas.
/// Fresh random bytes per envelope keep even our own envelopes unlinkable.
private static func unlinkableSenderID() -> Data {
Data((0..<BinaryProtocol.senderIDSize).map { _ in UInt8.random(in: .min ... .max) })
}
private static func normalizeRecipientPeerID(_ recipientPeerID: PeerID) -> PeerID {
if let maybeData = Data(hexString: recipientPeerID.id) {
if maybeData.count == 32 {

View File

@ -2,7 +2,7 @@
// AutocompleteService.swift
// bitchat
//
// Handles autocomplete suggestions for mentions and commands
// Handles autocomplete suggestions for mentions
// This is free and unencumbered software released into the public domain.
//
@ -10,49 +10,47 @@ import Foundation
/// Manages autocomplete functionality for chat
final class AutocompleteService {
private let mentionRegex = try? NSRegularExpression(pattern: "@([\\p{L}0-9_]*)$", options: [])
private typealias Patterns = MessageFormattingEngine.Patterns
/// Get autocomplete suggestions for current text
func getSuggestions(for text: String, peers: [String], cursorPosition: Int) -> (suggestions: [String], range: NSRange?) {
let textToPosition = String(text.prefix(cursorPosition))
// Check for mention autocomplete
// Mentions only — slash-command suggestions are owned by
// `CommandSuggestionsView` / the composer, not this service.
if let (mentionSuggestions, mentionRange) = getMentionSuggestions(textToPosition, peers: peers) {
return (mentionSuggestions, mentionRange)
}
// Don't handle command autocomplete here - ContentView handles it with better UI
// if let (commandSuggestions, commandRange) = getCommandSuggestions(textToPosition) {
// return (commandSuggestions, commandRange)
// }
return ([], nil)
}
/// Apply selected suggestion to text
func applySuggestion(_ suggestion: String, to text: String, range: NSRange) -> String {
guard let textRange = Range(range, in: text) else { return text }
var replacement = suggestion
// Add space after command if it takes arguments
if suggestion.hasPrefix("/") && needsArgument(command: suggestion) {
replacement += " "
}
return text.replacingCharacters(in: textRange, with: replacement)
}
// MARK: - Private Methods
private func getMentionSuggestions(_ text: String, peers: [String]) -> ([String], NSRange)? {
guard let regex = mentionRegex else { return nil }
let nsText = text as NSString
let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
let matches = Patterns.mentionAutocomplete.matches(
in: text,
options: [],
range: NSRange(location: 0, length: nsText.length)
)
guard let match = matches.last else { return nil }
let fullRange = match.range(at: 0)
let captureRange = match.range(at: 1)
let prefix = nsText.substring(with: captureRange).normalizedNickname.lowercased()
@ -62,10 +60,10 @@ final class AutocompleteService {
.sorted()
.prefix(5)
.map { "@\($0)" }
return suggestions.isEmpty ? nil : (Array(suggestions), fullRange)
}
private func needsArgument(command: String) -> Bool {
switch command {
case "/who", "/clear":

View File

@ -273,8 +273,14 @@ final class BLEAnnounceHandler {
responsePlan.shouldNotifyPeerConnected && responsePlan.shouldScheduleInitialSync
)
// Track for sync (include our own and others' announces)
env.trackPacketSeen(packet)
// Track for sync — verified announces only (our own are tracked at
// send time). An unverified announce costs nothing to mint (any 32
// random bytes satisfy the sender binding), so tracking it would let
// a nearby device fill the announce store and the sync filter with
// junk identities that every peer then re-serves.
if verifiedAnnounce {
env.trackPacketSeen(packet)
}
if responsePlan.shouldSendAnnounceBack {
// Reciprocate announce for bidirectional discovery

View File

@ -6,22 +6,53 @@ struct BLEDirectedRelaySpoolEntry {
let packet: BitchatPacket
}
/// Directed packets held at a relay while no onward link exists.
///
/// Bounded by count and by total payload bytes, evicting oldest-first: a
/// spooled noiseEncrypted packet keeps the framed-file decompression cap, so
/// a ~1 KB compressed frame can decode to ~1 MB, and a window-only bound let
/// a stream of such frames pin gigabytes before the first entry expired.
struct BLEDirectedRelaySpool {
private struct Key: Hashable {
let recipient: PeerID
// periphery:ignore - read only via the synthesized Hashable
// conformance (dictionary-key identity), which the indexer
// cannot attribute.
let messageID: String
}
private struct StoredPacket {
let packet: BitchatPacket
let enqueuedAt: Date
}
private var packetsByRecipient: [PeerID: [String: StoredPacket]] = [:]
private let capacity: Int
private let byteBudget: Int
private var packets: [Key: StoredPacket] = [:]
/// Enqueue order, oldest first: the eviction order, and the drain order.
private var order: [Key] = []
/// Sum of spooled payload sizes, maintained on every insert/remove.
private var payloadBytes = 0
init(
capacity: Int = TransportConfig.bleDirectedSpoolCapacity,
byteBudget: Int = TransportConfig.bleDirectedSpoolByteBudget
) {
self.capacity = capacity
self.byteBudget = byteBudget
}
var isEmpty: Bool {
packetsByRecipient.isEmpty
packets.isEmpty
}
var count: Int {
packetsByRecipient.values.reduce(0) { $0 + $1.count }
packets.count
}
/// Spools `packet` unless it is already spooled for `recipient` or is
/// larger than the whole byte budget, then evicts oldest-first until
/// both the count and the byte budget hold.
@discardableResult
mutating func enqueue(
packet: BitchatPacket,
@ -29,43 +60,55 @@ struct BLEDirectedRelaySpool {
messageID: String,
enqueuedAt: Date
) -> Bool {
var packets = packetsByRecipient[recipient] ?? [:]
guard packets[messageID] == nil else {
let key = Key(recipient: recipient, messageID: messageID)
guard packets[key] == nil, packet.payload.count <= byteBudget else {
return false
}
packets[messageID] = StoredPacket(packet: packet, enqueuedAt: enqueuedAt)
packetsByRecipient[recipient] = packets
packets[key] = StoredPacket(packet: packet, enqueuedAt: enqueuedAt)
order.append(key)
payloadBytes += packet.payload.count
while order.count > capacity || payloadBytes > byteBudget {
let victim = order.removeFirst()
if let evicted = packets.removeValue(forKey: victim) {
payloadBytes -= evicted.packet.payload.count
}
}
return true
}
mutating func drainUnexpired(now: Date, window: TimeInterval) -> [BLEDirectedRelaySpoolEntry] {
var entries: [BLEDirectedRelaySpoolEntry] = []
for (recipient, packets) in packetsByRecipient {
for stored in packets.values where now.timeIntervalSince(stored.enqueuedAt) <= window {
entries.append(BLEDirectedRelaySpoolEntry(recipient: recipient, packet: stored.packet))
}
for key in order {
guard let stored = packets[key],
now.timeIntervalSince(stored.enqueuedAt) <= window else { continue }
entries.append(BLEDirectedRelaySpoolEntry(recipient: key.recipient, packet: stored.packet))
}
packetsByRecipient.removeAll()
removeAll()
return entries
}
mutating func pruneExpired(now: Date, window: TimeInterval) {
guard !packetsByRecipient.isEmpty else { return }
guard !packets.isEmpty else { return }
var pruned: [PeerID: [String: StoredPacket]] = [:]
for (recipient, packets) in packetsByRecipient {
let freshPackets = packets.filter { now.timeIntervalSince($0.value.enqueuedAt) <= window }
if !freshPackets.isEmpty {
pruned[recipient] = freshPackets
var freshOrder: [Key] = []
for key in order {
guard let stored = packets[key] else { continue }
if now.timeIntervalSince(stored.enqueuedAt) <= window {
freshOrder.append(key)
} else {
packets.removeValue(forKey: key)
payloadBytes -= stored.packet.payload.count
}
}
packetsByRecipient = pruned
order = freshOrder
}
mutating func removeAll() {
packetsByRecipient.removeAll()
packets.removeAll()
order.removeAll()
payloadBytes = 0
}
}

View File

@ -152,12 +152,21 @@ final class BLEFileTransferHandler {
return true
}
// Once authenticated, a local decode/quota/save failure is not proof
// that downstream nodes should be denied the valid signed packet, so
// every exit below still relays.
guard let acceptance = validatedFile(packet.payload, from: peerID) else {
return true
}
// Track only validated payloads: the gossip store holds and re-serves
// what it is given, so a malformed or oversized file must not enter it.
if deliveryPlan.shouldTrackForSync {
env.trackPacketSeen(packet)
}
_ = storeIncomingPayload(
packet.payload,
_ = storeIncomingFile(
acceptance,
from: peerID,
senderNickname: senderNickname,
timestamp: Date(timeIntervalSince1970: Double(packet.timestamp) / 1000),
@ -165,8 +174,6 @@ final class BLEFileTransferHandler {
usesDurableReceipts: false,
env: env
)
// Once authenticated, a local decode/quota/save failure is not proof
// that downstream nodes should be denied the valid signed packet.
return true
}
@ -178,6 +185,9 @@ final class BLEFileTransferHandler {
@discardableResult
func handlePrivatePayload(_ payload: Data, from peerID: PeerID, timestamp: Date) -> Bool {
let env = environment
guard let acceptance = validatedFile(payload, from: peerID) else {
return false
}
let peers = env.peersSnapshot()
let senderNickname = BLEPeerSenderDisplayName.resolveKnownPeer(
peerID: peerID,
@ -187,8 +197,8 @@ final class BLEFileTransferHandler {
allowConnectedUnverified: true
) ?? BLEPeerSenderDisplayName.anonymousNickname(for: peerID)
return storeIncomingPayload(
payload,
return storeIncomingFile(
acceptance,
from: peerID,
senderNickname: senderNickname,
timestamp: timestamp,
@ -202,8 +212,26 @@ final class BLEFileTransferHandler {
)
}
private func storeIncomingPayload(
_ payload: Data,
/// Decodes and validates a file payload (size, MIME allow-list, magic
/// bytes), logging the reason for any rejection.
private func validatedFile(_ payload: Data, from peerID: PeerID) -> BLEIncomingFileAcceptance? {
switch BLEIncomingFileValidator.validate(payload: payload) {
case .success(let acceptance):
return acceptance
case .failure(.malformedPayload):
SecureLogger.error("❌ Failed to decode file transfer payload", category: .session)
case .failure(.payloadTooLarge(let bytes)):
SecureLogger.warning("🚫 Dropping file transfer exceeding size cap (\(bytes) bytes)", category: .security)
case .failure(.unsupportedMime(let mimeType, let bytes)):
SecureLogger.warning("🚫 MIME REJECT: '\(mimeType ?? "<empty>")' not supported. Size=\(bytes)b from \(peerID.id.prefix(8))...", category: .security)
case .failure(.magicMismatch(let mime, let bytes, let prefixHex)):
SecureLogger.warning("🚫 MAGIC REJECT: MIME='\(mime)' size=\(bytes)b prefix=[\(prefixHex)] from \(peerID.id.prefix(8))...", category: .security)
}
return nil
}
private func storeIncomingFile(
_ acceptance: BLEIncomingFileAcceptance,
from peerID: PeerID,
senderNickname: String,
timestamp: Date,
@ -213,25 +241,8 @@ final class BLEFileTransferHandler {
) -> Bool {
let localPeerID = env.localPeerID()
let filePacket: BitchatFilePacket
let mime: MimeType
switch BLEIncomingFileValidator.validate(payload: payload) {
case .success(let acceptance):
filePacket = acceptance.filePacket
mime = acceptance.mime
case .failure(.malformedPayload):
SecureLogger.error("❌ Failed to decode file transfer payload", category: .session)
return false
case .failure(.payloadTooLarge(let bytes)):
SecureLogger.warning("🚫 Dropping file transfer exceeding size cap (\(bytes) bytes)", category: .security)
return false
case .failure(.unsupportedMime(let mimeType, let bytes)):
SecureLogger.warning("🚫 MIME REJECT: '\(mimeType ?? "<empty>")' not supported. Size=\(bytes)b from \(peerID.id.prefix(8))...", category: .security)
return false
case .failure(.magicMismatch(let mime, let bytes, let prefixHex)):
SecureLogger.warning("🚫 MAGIC REJECT: MIME='\(mime)' size=\(bytes)b prefix=[\(prefixHex)] from \(peerID.id.prefix(8))...", category: .security)
return false
}
let filePacket = acceptance.filePacket
let mime = acceptance.mime
if isPrivate, env.isPrivateMediaSenderBlocked(peerID) {
SecureLogger.debug(

View File

@ -97,9 +97,14 @@ struct BLEFragmentAssemblyBuffer {
) -> AppendResult {
let started = startAssemblyIfNeeded(for: header, maxInFlightAssemblies: maxInFlightAssemblies, now: now)
let currentSize = fragmentsByKey[header.key]?.values.reduce(0) { $0 + $1.count } ?? 0
let held = fragmentsByKey[header.key]
let currentSize = held?.values.reduce(0) { $0 + $1.count } ?? 0
let limit = Self.assemblyLimit(for: header.originalType)
let projectedSize = currentSize + header.fragmentData.count
// A re-delivered index replaces what it held rather than adding to
// it: fragments bypass dedup and sync re-serves held indexes, so a
// duplicate near the cap must not tip a valid assembly over it.
let replacedSize = held?[header.index]?.count ?? 0
let projectedSize = currentSize - replacedSize + header.fragmentData.count
guard projectedSize <= limit else {
fragmentsByKey.removeValue(forKey: header.key)
@ -200,15 +205,12 @@ struct BLEFragmentAssemblyBuffer {
}
}
/// The largest frame a packet of the claimed type could decode from:
/// framed-file scale only for media (a large noiseEncrypted packet can be
/// an E2E-encrypted private file, validated after decrypt), link or
/// message scale for everything else. The handler drops a reassembled
/// packet whose type differs from the claim.
private static func assemblyLimit(for originalType: UInt8) -> Int {
if originalType == MessageType.fileTransfer.rawValue
|| originalType == MessageType.noiseEncrypted.rawValue {
// Allow headroom for TLV metadata and binary framing overhead.
// A large noiseEncrypted packet can be an E2E-encrypted private
// file; its authenticated plaintext is validated after decrypt.
return FileTransferLimits.maxFramedFileBytes
}
return FileTransferLimits.maxPayloadBytes
PacketPayloadLimits.maxFrameBytes(forType: originalType)
}
}

View File

@ -61,9 +61,16 @@ final class BLEFragmentHandler {
// Decode the original packet bytes we reassembled, so flags/compression are preserved
if var originalPacket = BinaryProtocol.decode(reassembled) {
// Reassembled packet validation
// Reassembled packet validation. Both platforms' fragmenters copy
// the inner type into every fragment, and the assembly was sized
// for that claim, so a packet of any other type is forged.
let innerSender = PeerID(hexData: originalPacket.senderID)
if !env.isAcceptedIngressPayload(originalPacket, innerSender) {
if originalPacket.type != completedHeader.originalType {
SecureLogger.warning(
"🚫 Reassembled packet id=\(completedHeader.idLogString) is type \(originalPacket.type), fragments claimed \(completedHeader.originalType)",
category: .security
)
} else if !env.isAcceptedIngressPayload(originalPacket, innerSender) {
// Cleanup below
} else {
SecureLogger.debug("✅ Reassembled packet id=\(completedHeader.idLogString) type=\(originalPacket.type) bytes=\(reassembled.count)", category: .session)

View File

@ -16,7 +16,7 @@ enum BLEIngressPacketGuard {
localPeerID: PeerID,
directAnnounceTTL: UInt8,
nowMs: UInt64 = UInt64(Date().timeIntervalSince1970 * 1000),
maxTimestampSkewMs: UInt64 = 120_000,
maxTimestampSkewMs: UInt64 = TransportConfig.bleMaxTimestampSkewMs,
isValidSyncResponse: (PeerID) -> Bool
) -> Result<BLEIngressPacketContext, Rejection> {
let contextResult = BLEIngressLinkRegistry.packetContext(
@ -55,17 +55,25 @@ enum BLEIngressPacketGuard {
_ packet: BitchatPacket,
from peerID: PeerID,
nowMs: UInt64 = UInt64(Date().timeIntervalSince1970 * 1000),
maxTimestampSkewMs: UInt64 = 120_000,
maxTimestampSkewMs: UInt64 = TransportConfig.bleMaxTimestampSkewMs,
isValidSyncResponse: (PeerID) -> Bool
) -> Result<Void, Rejection> {
let packetTime = packet.timestamp
if packet.isRSR {
guard isValidSyncResponse(peerID) else {
return .failure(.invalidRSR(peerID: peerID))
}
// Sync replies legitimately replay old packets, so only the past
// bound is waived. A far-future packet is never legitimate: it
// would outlive every gossip freshness window, drag requesters'
// since-cursors past all real history, and pin itself below live
// chat.
guard packetTime <= nowMs || packetTime - nowMs <= maxTimestampSkewMs else {
return .failure(.timestampSkew(peerID: peerID, skewMs: packetTime - nowMs, maxSkewMs: maxTimestampSkewMs))
}
return .success(())
}
let packetTime = packet.timestamp
let skew = packetTime > nowMs ? packetTime - nowMs : nowMs - packetTime
guard skew <= maxTimestampSkewMs else {
return .failure(.timestampSkew(peerID: peerID, skewMs: skew, maxSkewMs: maxTimestampSkewMs))

View File

@ -40,6 +40,8 @@ struct BLEPublicMessageHandlerEnvironment {
/// policy, sender display-name resolution, gossip tracking, payload decoding,
/// and UI delivery.
final class BLEPublicMessageHandler {
private static let maxDeliveredPayloadBytes = Int(UInt16.max)
private let environment: BLEPublicMessageHandlerEnvironment
init(environment: BLEPublicMessageHandlerEnvironment) {
@ -110,6 +112,16 @@ final class BLEPublicMessageHandler {
env.trackPacketSeen(packet)
}
// Both platforms send public messages as v1 frames, whose payload
// tops out at 65,535 bytes. The decode cap leaves headroom above
// that for relaying, but the timeline keeps messages by count and
// its length check counts characters (a combining-mark run is one),
// so nothing larger than a v1 frame is delivered.
guard packet.payload.count <= Self.maxDeliveredPayloadBytes else {
SecureLogger.warning("🚫 Dropping \(packet.payload.count)-byte public message from \(peerID.id.prefix(8))…: larger than a v1 frame", category: .security)
return
}
guard let content = String(data: packet.payload, encoding: .utf8) else {
SecureLogger.error("❌ Failed to decode message payload as UTF-8", category: .session)
return

View File

@ -1943,7 +1943,7 @@ final class BLEService: NSObject {
private func logValidRSR(from peerID: PeerID) {
guard logRateLimiter.shouldLog(key: "valid-rsr:\(peerID.id)") else { return }
SecureLogger.debug("Valid RSR packet from \(peerID.id.prefix(8))… - skipping timestamp check", category: .security)
SecureLogger.debug("Valid RSR packet from \(peerID.id.prefix(8))… - skipping past-timestamp check", category: .security)
}
private func logSelfLoopback(packetType: UInt8, linkDescription: String) {

View File

@ -0,0 +1,127 @@
//
// ComposerDraftStore.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
import BitFoundation
/// Holds unfinished composer text per conversation so switching mesh /
/// geohash / DM channels does not silently discard what someone was typing.
///
/// Drafts stay **in memory only** — message content must not land in
/// UserDefaults (see MessageOutboxStore: only the sealed outbox persists
/// plaintext). Losing a draft on process death is acceptable; surviving a
/// channel/DM switch is the value.
///
/// Panic wipe clears the whole map so a seized phone does not keep
/// half-written messages in RAM either.
enum ComposerDraftStore {
/// Cap each draft so a pasted novel cannot bloat the map forever.
static let maxDraftLength = 8_000
/// Cap how many conversations keep a draft; oldest entries fall off first.
static let maxDraftCount = 64
private struct Entry {
var text: String
var updatedAt: Date
}
private static var entries: [String: Entry] = [:]
private static let lock = NSLock()
enum Key: Hashable, Equatable {
case mesh
case location(geohash: String)
/// Mesh DM keyed by Noise fingerprint when known; falls back to the
/// current peerID only before handshake so drafts do not orphan on
/// peerID rotation mid-session.
case privateChat(stableID: String)
var storageString: String {
switch self {
case .mesh:
return "mesh"
case .location(let geohash):
return "geo:\(geohash.lowercased())"
case .privateChat(let stableID):
return "dm:\(stableID.lowercased())"
}
}
static func from(
peerID: PeerID?,
fingerprint: String?,
channel: ChannelID
) -> Key {
if let peerID {
if let fingerprint, !fingerprint.isEmpty {
return .privateChat(stableID: fingerprint)
}
return .privateChat(stableID: peerID.id)
}
switch channel {
case .mesh:
return .mesh
case .location(let ch):
return .location(geohash: ch.geohash)
}
}
}
static func load(_ key: Key) -> String {
lock.lock()
defer { lock.unlock() }
return entries[key.storageString]?.text ?? ""
}
static func save(_ text: String, for key: Key) {
lock.lock()
defer { lock.unlock() }
let trimmed = String(text.prefix(maxDraftLength))
if trimmed.isEmpty {
entries.removeValue(forKey: key.storageString)
} else {
entries[key.storageString] = Entry(text: trimmed, updatedAt: Date())
evictOldestIfNeededLocked()
}
}
static func reset() {
lock.lock()
defer { lock.unlock() }
entries.removeAll(keepingCapacity: false)
}
/// Test helper: replace the in-memory map (and return the previous one).
@discardableResult
static func replaceAllForTesting(_ newEntries: [String: String] = [:]) -> [String: String] {
lock.lock()
defer { lock.unlock() }
let previous = entries.mapValues(\.text)
let now = Date()
entries = Dictionary(uniqueKeysWithValues: newEntries.map { ($0.key, Entry(text: $0.value, updatedAt: now)) })
return previous
}
static func countForTesting() -> Int {
lock.lock()
defer { lock.unlock() }
return entries.count
}
private static func evictOldestIfNeededLocked() {
guard entries.count > maxDraftCount else { return }
let surplus = entries.count - maxDraftCount
let doomed = entries
.sorted { $0.value.updatedAt < $1.value.updatedAt }
.prefix(surplus)
.map(\.key)
for key in doomed {
entries.removeValue(forKey: key)
}
}
}

View File

@ -41,6 +41,12 @@ final class GeohashChatActivityTracker: ObservableObject {
private var lastMessages: [String: GeohashChatPreview] = [:]
private let now: () -> Date
#if DEBUG
/// Number of distinct geohashes currently held in memory; exposed only
/// for regression tests verifying stale entries get evicted.
var _trackedGeohashCountForTesting: Int { messageTimes.count }
#endif
init(
window: TimeInterval = TransportConfig.uiGeohashChatActivityWindowSeconds,
now: @escaping () -> Date = { Date() }
@ -68,6 +74,15 @@ final class GeohashChatActivityTracker: ObservableObject {
} else {
lastMessages[gh] = GeohashChatPreview(senderName: senderName, content: content, timestamp: clamped)
}
// A geohash's timestamp array only ever gets pruned down to empty —
// its dictionary entry (and the paired lastMessages entry) is never
// dropped, so roaming across many regions over a long session leaks
// one entry per distinct geohash ever observed. Sweep other geohashes
// here so activity that has fully aged out gets evicted instead of
// sitting in memory for the rest of the process's lifetime.
pruneStaleGeohashes(except: gh)
objectWillChange.send()
}
@ -113,4 +128,15 @@ final class GeohashChatActivityTracker: ObservableObject {
let cutoff = now().addingTimeInterval(-window)
return times.filter { $0 >= cutoff }
}
/// Drops any tracked geohash (other than `keep`) whose messages have all
/// aged out of the window, so the maps stay bounded to recently-active
/// geohashes instead of growing for the life of the process.
private func pruneStaleGeohashes(except keep: String) {
for gh in Array(messageTimes.keys) where gh != keep {
guard prune(messageTimes[gh] ?? []).isEmpty else { continue }
messageTimes.removeValue(forKey: gh)
lastMessages.removeValue(forKey: gh)
}
}
}

View File

@ -59,6 +59,16 @@ struct BitchatGroup: Codable, Equatable {
func member(withSigningKey signingKey: Data) -> GroupMember? {
members.first { $0.signingKey == signingKey }
}
/// Whether `other` names the same creator — fingerprint AND signing key —
/// as this group. A group keeps the creator it was created with: state
/// for a known groupID naming anyone else is a takeover attempt, however
/// validly it is self-signed.
func hasSameCreator(as other: BitchatGroup) -> Bool {
guard let creator, let otherCreator = other.creator else { return false }
return creator.fingerprint == otherCreator.fingerprint
&& creator.signingKey == otherCreator.signingKey
}
}
// MARK: - TLV helpers
@ -192,7 +202,9 @@ enum GroupRosterCoding {
/// key updates (0x07); receivers verify the creator signature — computed over
/// "bitchat-group-v1" | groupID | epoch | SHA256(key) | SHA256(roster) —
/// against the creator's signing key pinned in the roster, and require the
/// Noise session peer to BE the creator before accepting any state.
/// Noise session peer to BE the creator before accepting any state. Both
/// checks are self-referential (the state names its own creator), so for a
/// group already held the creator must also match the stored one.
struct GroupStatePayload: Equatable {
let groupID: Data
let name: String

View File

@ -68,14 +68,20 @@ final class GroupStore: ObservableObject {
}
/// Inserts or replaces a group and its current key. Rejects rosters over
/// the hard cap or groups whose creator is missing from the roster.
/// the hard cap, groups whose creator is missing from the roster, and any
/// change to the creator (fingerprint or signing key) of a group already
/// held, so no caller can hand a known groupID to a different creator.
@discardableResult
func upsert(_ group: BitchatGroup, key: Data) -> Bool {
guard group.groupID.count == BitchatGroup.groupIDLength,
key.count == BitchatGroup.keyLength,
!group.members.isEmpty,
group.members.count <= BitchatGroup.maxMembers,
group.creator != nil else { return false }
guard key.count == BitchatGroup.keyLength,
Self.isWellFormed(group) else { return false }
if let existing = self.group(withID: group.groupID), !existing.hasSameCreator(as: group) {
SecureLogger.warning(
"Refusing group state: creator \(group.creatorFingerprint.prefix(8))… does not match stored creator \(existing.creatorFingerprint.prefix(8))…",
category: .security
)
return false
}
guard keychain.saveIdentityKey(key, forKey: Self.keychainKey(for: group.groupID)) else {
SecureLogger.error("Failed to store group key in keychain", category: .security)
return false
@ -90,16 +96,17 @@ final class GroupStore: ObservableObject {
}
/// Updates the roster of an existing group without changing key or epoch
/// (creator-side invite). Enforces the member cap.
/// (creator-side invite). Enforces the member cap and keeps the creator's
/// roster entry (fingerprint and signing key) pinned.
@discardableResult
func updateRoster(groupID: Data, members: [GroupMember]) -> BitchatGroup? {
guard let index = groups.firstIndex(where: { $0.groupID == groupID }),
!members.isEmpty,
members.count <= BitchatGroup.maxMembers,
members.contains(where: { $0.fingerprint == groups[index].creatorFingerprint }) else { return nil }
groups[index].members = members
guard let index = groups.firstIndex(where: { $0.groupID == groupID }) else { return nil }
var updated = groups[index]
updated.members = members
guard Self.isWellFormed(updated), groups[index].hasSameCreator(as: updated) else { return nil }
groups[index] = updated
persist()
return groups[index]
return updated
}
/// Rotates the group key (creator-side removal/rotation): new random key,
@ -139,6 +146,15 @@ final class GroupStore: ObservableObject {
"groupKey-\(groupID.hexEncodedString())"
}
/// Structural invariants every stored group satisfies: a well-sized ID,
/// a non-empty roster within the cap, and the creator in that roster.
private static func isWellFormed(_ group: BitchatGroup) -> Bool {
group.groupID.count == BitchatGroup.groupIDLength
&& !group.members.isEmpty
&& group.members.count <= BitchatGroup.maxMembers
&& group.creator != nil
}
private static func randomBytes(_ count: Int) -> Data? {
var bytes = Data(count: count)
let status = bytes.withUnsafeMutableBytes { buffer -> OSStatus in
@ -176,8 +192,15 @@ final class GroupStore: ObservableObject {
let stored = try? JSONDecoder().decode([BitchatGroup].self, from: data) else {
return
}
// Only groups whose key survived in the keychain are usable.
groups = stored.filter { key(forGroupID: $0.groupID) != nil }
// Only groups whose key survived in the keychain are usable. Loading
// bypasses `upsert`, so re-check its invariants here too, and keep one
// entry per groupID so a group can never carry two creators.
var seenGroupIDs = Set<Data>()
groups = stored.filter { group in
Self.isWellFormed(group)
&& seenGroupIDs.insert(group.groupID).inserted
&& key(forGroupID: group.groupID) != nil
}
}
private static func defaultFileURL() -> URL? {

View File

@ -267,7 +267,14 @@ final class LocationNotesManager: ObservableObject {
if let expiresAt, expiresAt <= self.dependencies.now() { return }
self.noteIDs.insert(event.id)
let nick = event.tags.first(where: { $0.first?.lowercased() == "n" && $0.count >= 2 })?.dropFirst().first
let ts = Date(timeIntervalSince1970: TimeInterval(event.created_at))
// created_at is author-chosen; clamp so a future-dated note can't
// hold the top of the newest-first list past the memory cap. The
// bound is the board's clock-skew allowance: a bridged copy of an
// accepted board post must keep its timestamp, or
// UnifiedNotices.merge no longer recognizes it as the same notice.
let latestAccepted = self.dependencies.now()
.addingTimeInterval(TimeInterval(BoardStore.Limits.clockSkewMs) / 1000)
let ts = min(Date(timeIntervalSince1970: TimeInterval(event.created_at)), latestAccepted)
let urgent = event.tags.contains { $0.count >= 2 && $0[0].lowercased() == "t" && $0[1].lowercased() == "urgent" }
let note = Note(id: event.id, pubkey: event.pubkey, content: event.content, createdAt: ts, nickname: nick, geohash: matchedGeohash, expiresAt: expiresAt, isUrgent: urgent)
self.notes.append(note)

View File

@ -43,6 +43,9 @@ final class MessageFormattingEngine {
static let mention = SafeRegex.compile("@([\\p{L}0-9_]+(?:#[a-fA-F0-9]{4})?)")
/// Trailing partial `@nickname` at the composer cursor — autocomplete only.
static let mentionAutocomplete = SafeRegex.compile("@([\\p{L}0-9_]*)$")
static let cashu = SafeRegex.compile("\\bcashu[AB][A-Za-z0-9._-]{40,}\\b")
static let bolt11 = SafeRegex.compile("(?i)\\bln(bc|tb|bcrt)[0-9][a-z0-9]{50,}\\b")

View File

@ -67,7 +67,8 @@ final class NostrTransport: Transport, @unchecked Sendable {
}
}
// Provide BLE short peer ID for BitChat embedding
// BLE short peer ID embedded in favorites (recipient-addressed) envelopes.
// Geohash envelopes never carry it (see NostrEmbeddedBitChat).
var senderPeerID = PeerID(str: "")
// Throttle outbound acks — READ receipts and DELIVERED acks, direct and
@ -315,7 +316,7 @@ extension NostrTransport {
Task { @MainActor in
guard !recipientHex.isEmpty else { return }
SecureLogger.debug("GeoDM: send PM mid=\(messageID.prefix(8))…", category: .session)
guard let embedded = NostrEmbeddedBitChat.encodePMForNostrNoRecipient(content: content, messageID: messageID, senderPeerID: senderPeerID) else {
guard let embedded = NostrEmbeddedBitChat.encodePMForNostrNoRecipient(content: content, messageID: messageID) else {
SecureLogger.error("NostrTransport: failed to embed geohash PM packet", category: .session)
return
}
@ -382,12 +383,12 @@ extension NostrTransport {
case .deliveredGeohash(let messageID, let recipientHex, let identity):
SecureLogger.debug("GeoDM: send DELIVERED mid=\(messageID.prefix(8))…", category: .session)
guard let embedded = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .delivered, messageID: messageID, senderPeerID: senderPeerID) else { return }
guard let embedded = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .delivered, messageID: messageID) else { return }
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
case .readGeohash(let messageID, let recipientHex, let identity):
SecureLogger.debug("GeoDM: send READ mid=\(messageID.prefix(8))…", category: .session)
guard let embedded = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .readReceipt, messageID: messageID, senderPeerID: senderPeerID) else { return }
guard let embedded = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .readReceipt, messageID: messageID) else { return }
sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true)
}
}

View File

@ -9,6 +9,11 @@ enum TransportConfig {
static let bleMaxInFlightAssemblies: Int = 128 // Cap concurrent fragment assemblies
static let bleHighDegreeThreshold: Int = 6 // For adaptive TTL/probabilistic relays
static let bleMaxConcurrentTransfers: Int = 2 // Limit simultaneous large media sends
// Clock skew tolerated on received packet timestamps. Live packets must
// sit within ± this of local time; sync replies may be arbitrarily old
// but never further ahead than this, and the gossip store applies the
// same future bound so nothing future-dated is stored, served or restored.
static let bleMaxTimestampSkewMs: UInt64 = 120_000
// Bounded wait for the session-authenticated capability proof used by
// private-media migration. Expiry never auto-sends clear bytes; it only
// resolves to the existing one-shot consent or downgrade-blocked path.
@ -319,6 +324,14 @@ enum TransportConfig {
// on each maintenance flush until the window lapses; a longer window lets
// brief link gaps (walking between rooms, reconnect churn) heal themselves.
static let bleDirectedSpoolWindowSeconds: TimeInterval = 60.0
// The spool evicts oldest-first past either bound. Only noiseEncrypted
// and noiseHandshake packets are spooled, and relayed ones arrive as
// single frames (larger sends travel as fragments, which are never
// spooled), so ordinary entries are a few hundred bytes. The byte budget
// still fits one packet at the framed-file decompression cap (~1.13 MiB)
// plus hundreds of ordinary DMs.
static let bleDirectedSpoolCapacity: Int = 512
static let bleDirectedSpoolByteBudget: Int = 2 * 1024 * 1024
// Log/UI debounce windows
// Shorter debounce so UI reacts faster while still suppressing duplicate callbacks

View File

@ -251,17 +251,21 @@ final class UnifiedPeerService: ObservableObject, TransportPeerEventsDelegate {
return peerIndex[peerID]
}
/// Get peer ID for nickname
/// Get peer ID for nickname.
///
/// An unsuffixed name is accepted only when it identifies exactly one peer.
/// Colliding nicknames must be disambiguated with the people-list `#xxxx`
/// suffix (first four hex characters of the peer ID).
func getPeerID(for nickname: String) -> PeerID? {
// Normalize both sides: the query may come from typed content and
// stored names may predate NFC-at-ingest (e.g. persisted favorites).
let target = nickname.normalizedNickname
for peer in peers {
if peer.displayName.normalizedNickname == target || peer.nickname.normalizedNickname == target {
return peer.peerID
guard let id = NicknameLookup.uniquePeerIDString(
for: nickname,
peers: peers.map { peer in
(id: peer.peerID.id, nickname: peer.nickname, displayName: peer.displayName)
}
) else {
return nil
}
return nil
return peers.first(where: { $0.peerID.id == id })?.peerID
}
/// Check if peer is blocked

View File

@ -14,18 +14,27 @@ final class GossipSyncManager {
private struct PacketStore {
private(set) var packets: [String: BitchatPacket] = [:]
private(set) var order: [String] = []
/// Sum of retained payload sizes, maintained on every insert/remove.
private var payloadBytes = 0
mutating func insert(idHex: String, packet: BitchatPacket, capacity: Int) {
guard capacity > 0 else { return }
if packets[idHex] != nil {
/// Evicts oldest-first until both the count and the byte budget hold.
/// The count cap alone let a few max-size packets per slot pin
/// hundreds of MB; the budget bounds memory whatever the sizes.
mutating func insert(idHex: String, packet: BitchatPacket, capacity: Int, byteBudget: Int) {
guard capacity > 0, packet.payload.count <= byteBudget else { return }
if let existing = packets[idHex] {
payloadBytes += packet.payload.count - existing.payload.count
packets[idHex] = packet
return
} else {
packets[idHex] = packet
order.append(idHex)
payloadBytes += packet.payload.count
}
packets[idHex] = packet
order.append(idHex)
while order.count > capacity {
while order.count > capacity || payloadBytes > byteBudget {
let victim = order.removeFirst()
packets.removeValue(forKey: victim)
if let evicted = packets.removeValue(forKey: victim) {
payloadBytes -= evicted.payload.count
}
}
}
@ -42,6 +51,7 @@ final class GossipSyncManager {
guard let packet = packets[key] else { continue }
if shouldRemove(packet) {
packets.removeValue(forKey: key)
payloadBytes -= packet.payload.count
} else {
nextOrder.append(key)
}
@ -74,6 +84,14 @@ final class GossipSyncManager {
var fragmentCapacity: Int = 600
var fileTransferCapacity: Int = 200
var groupMessageCapacity: Int = 200
// Payload byte budgets on top of the count caps. Each sits well above
// what the count cap holds in ordinary traffic (1000 chat messages,
// 600 fragments of ~500 B), so it only binds when packets are
// oversized — e.g. 200 file transfers at the 1.1 MB frame cap.
var messageByteBudget: Int = 8 * 1024 * 1024
var fragmentByteBudget: Int = 1024 * 1024
var fileTransferByteBudget: Int = 32 * 1024 * 1024
var groupMessageByteBudget: Int = 4 * 1024 * 1024
var fragmentSyncIntervalSeconds: TimeInterval = 30.0
var fileTransferSyncIntervalSeconds: TimeInterval = 60.0
var messageSyncIntervalSeconds: TimeInterval = 15.0
@ -89,6 +107,9 @@ final class GossipSyncManager {
var prekeyBundleCapacity: Int = 200
var prekeyBundleSyncIntervalSeconds: TimeInterval = 60.0
var prekeyBundleMaxAgeSeconds: TimeInterval = 24 * 60 * 60
// Future bound for every store: matches the ingress skew so nothing
// the radio accepts is refused here.
var maxFutureSkewMs: UInt64 = TransportConfig.bleMaxTimestampSkewMs
}
private let myPeerID: PeerID
@ -224,6 +245,13 @@ final class GossipSyncManager {
maxAgeSeconds = config.maxMessageAgeSeconds
}
let nowMs = UInt64(Date().timeIntervalSince1970 * 1000)
// Age windows only bound the past. A future-dated packet would never
// expire, sort ahead of everything in each GCS filter, and push the
// requester's since-cursor past all real history, so anything dated
// beyond the ingress skew is never stored, served or restored.
if packet.timestamp > nowMs, packet.timestamp - nowMs > config.maxFutureSkewMs {
return false
}
let ageThresholdMs = UInt64(maxAgeSeconds * 1000)
// If current time is less than threshold, accept all (handle clock issues gracefully)
@ -263,25 +291,25 @@ final class GossipSyncManager {
guard isBroadcastRecipient else { return }
guard isPacketFresh(packet) else { return }
let idHex = PacketIdUtil.computeId(packet).hexEncodedString()
messages.insert(idHex: idHex, packet: packet, capacity: max(1, config.seenCapacity))
messages.insert(idHex: idHex, packet: packet, capacity: max(1, config.seenCapacity), byteBudget: config.messageByteBudget)
archiveDirty = true
case .fragment:
guard isBroadcastRecipient else { return }
guard isPacketFresh(packet) else { return }
let idHex = PacketIdUtil.computeId(packet).hexEncodedString()
fragments.insert(idHex: idHex, packet: packet, capacity: max(1, config.fragmentCapacity))
fragments.insert(idHex: idHex, packet: packet, capacity: max(1, config.fragmentCapacity), byteBudget: config.fragmentByteBudget)
case .fileTransfer:
guard isBroadcastRecipient else { return }
guard isPacketFresh(packet) else { return }
let idHex = PacketIdUtil.computeId(packet).hexEncodedString()
fileTransfers.insert(idHex: idHex, packet: packet, capacity: max(1, config.fileTransferCapacity))
fileTransfers.insert(idHex: idHex, packet: packet, capacity: max(1, config.fileTransferCapacity), byteBudget: config.fileTransferByteBudget)
case .groupMessage:
// Opaque ciphertext to non-members; carried and served like any
// other broadcast so members get backfill from any relay.
guard isBroadcastRecipient else { return }
guard isPacketFresh(packet) else { return }
let idHex = PacketIdUtil.computeId(packet).hexEncodedString()
groupMessages.insert(idHex: idHex, packet: packet, capacity: max(1, config.groupMessageCapacity))
groupMessages.insert(idHex: idHex, packet: packet, capacity: max(1, config.groupMessageCapacity), byteBudget: config.groupMessageByteBudget)
case .prekeyBundle:
// Callers only feed verified bundles here (own bundles at send
// time, peers' after signature verification), so gossip never
@ -619,20 +647,39 @@ final class GossipSyncManager {
// MARK: - Archive (public message persistence)
/// Rebuild the public message store from disk on launch, dropping
/// anything that aged out while the app was dead.
/// anything that aged out while the app was dead — or that is dated in
/// the future, which an older build could have archived from a sync
/// reply. Any drop rewrites the file so it is purged from disk too.
///
/// Bounded like live intake: entries are stored oldest-first, so walk
/// them newest-first and stop once the count or byte budget is spent. An
/// oversized archive then costs at most one budget of decode work at
/// launch instead of re-inflating everything it holds.
private func restoreArchivedMessages() {
guard let archive else { return }
var restored = 0
for data in archive.load() {
let capacity = max(1, config.seenCapacity)
var kept: [(idHex: String, packet: BitchatPacket)] = []
var keptBytes = 0
var droppedAny = false
for data in archive.load().reversed() {
guard kept.count < capacity else { break }
guard let packet = BitchatPacket.from(data),
packet.type == MessageType.message.rawValue,
isPacketFresh(packet) else { continue }
let idHex = PacketIdUtil.computeId(packet).hexEncodedString()
messages.insert(idHex: idHex, packet: packet, capacity: max(1, config.seenCapacity))
restored += 1
isPacketFresh(packet) else {
droppedAny = true
continue
}
guard keptBytes + packet.payload.count <= config.messageByteBudget else { break }
keptBytes += packet.payload.count
kept.append((PacketIdUtil.computeId(packet).hexEncodedString(), packet))
}
if restored > 0 {
SecureLogger.debug("Restored \(restored) archived public message(s) for gossip sync", category: .sync)
for entry in kept.reversed() {
messages.insert(idHex: entry.idHex, packet: entry.packet, capacity: capacity, byteBudget: config.messageByteBudget)
}
if !kept.isEmpty {
SecureLogger.debug("Restored \(kept.count) archived public message(s) for gossip sync", category: .sync)
}
if !kept.isEmpty || droppedAny {
archiveDirty = true
}
}

View File

@ -0,0 +1,29 @@
import Foundation
/// Resolve a typed nickname to a peer ID string.
///
/// An unsuffixed name is accepted only when it identifies exactly one peer.
/// Colliding nicknames must be disambiguated with the people-list `#xxxx`
/// suffix (first four hex characters of the peer ID).
enum NicknameLookup {
static func uniquePeerIDString(
for query: String,
peers: [(id: String, nickname: String, displayName: String)]
) -> String? {
let target = query.normalizedNickname
var matches: [String] = []
for peer in peers {
let nick = peer.nickname.normalizedNickname
let display = peer.displayName.normalizedNickname
let prefix = String(peer.id.prefix(4))
let suffixedNick = (nick + "#" + prefix).normalizedNickname
let suffixedDisplay = (display + "#" + prefix).normalizedNickname
if display == target || nick == target || suffixedNick == target || suffixedDisplay == target {
if !matches.contains(peer.id) {
matches.append(peer.id)
}
}
}
return matches.count == 1 ? matches.first : nil
}
}

View File

@ -466,12 +466,14 @@ final class ChatGroupCoordinator {
/// Accepts creator-signed group state arriving as an invite. The Noise
/// session peer must BE the creator, the signature must verify against
/// the creator key pinned in the roster, and we must be in the roster.
/// For a group we already hold, the creator must be the stored one.
func handleGroupInvitePayload(from peerID: PeerID, payload: Data) {
applyGroupState(from: peerID, payload: payload, isInvite: true)
}
/// Accepts creator-signed state updates (rotation/roster). A state whose
/// roster no longer includes us means we were removed: drop the group.
/// Accepts creator-signed state updates (rotation/roster). A state from
/// the stored creator whose roster no longer includes us means we were
/// removed: drop the group.
func handleGroupKeyUpdatePayload(from peerID: PeerID, payload: Data) {
applyGroupState(from: peerID, payload: payload, isInvite: false)
}
@ -558,6 +560,30 @@ private extension ChatGroupCoordinator {
let myFingerprint = context.myNoiseFingerprint()
let existing = context.groupStore.group(withID: state.groupID)
if let existing {
// A group keeps the creator it was created with. The checks above
// only prove the sender is the creator the state names — anyone
// passes them by naming themselves and self-signing — so pin the
// creator's fingerprint AND signing key to the stored group.
// Both existing-group checks run before the removal branch, which
// drops the group without ever reaching `upsert`'s own pin.
guard existing.hasSameCreator(as: state.asGroup) else {
SecureLogger.warning(
"Dropping group state claiming creator \(state.creatorFingerprint.prefix(8))… for a group created by \(existing.creatorFingerprint.prefix(8))…",
category: .security
)
return
}
// Never regress the epoch: state travels over live Noise sessions,
// so an older epoch here is a stale (or misbehaving) creator
// device. That includes a stale removal, which must not undo a
// later re-invite.
guard state.epoch >= existing.epoch else {
SecureLogger.warning("Dropping stale group state (epoch \(state.epoch) < \(existing.epoch))", category: .security)
return
}
}
// A creator-signed roster that no longer includes us is a removal.
guard state.members.contains(where: { $0.fingerprint == myFingerprint }) else {
if let existing {
@ -576,13 +602,6 @@ private extension ChatGroupCoordinator {
return
}
// Never regress the epoch: state travels over live Noise sessions,
// so an older epoch here is a stale (or misbehaving) creator device.
if let existing, state.epoch < existing.epoch {
SecureLogger.warning("Dropping stale group state (epoch \(state.epoch) < \(existing.epoch))", category: .security)
return
}
let isNewMembership = existing == nil
guard context.groupStore.upsert(state.asGroup, key: state.key) else {
SecureLogger.error("Failed to store group state for \(state.name)", category: .session)

View File

@ -518,12 +518,15 @@ final class ChatPeerIdentityCoordinator {
let nickname = nickname.normalizedNickname
switch context.activeChannel {
case .location:
if nickname.contains("#"),
let person = context.visibleGeohashPeople()
.first(where: { $0.displayName == nickname }) {
let conversationKey = PeerID(nostr_: person.id)
context.registerNostrKeyMapping(person.id, for: conversationKey)
return conversationKey
if nickname.contains("#") {
let people = context.visibleGeohashPeople().filter {
$0.displayName.normalizedNickname == nickname
}
if people.count == 1, let person = people.first {
let conversationKey = PeerID(nostr_: person.id)
context.registerNostrKeyMapping(person.id, for: conversationKey)
return conversationKey
}
}
let base = nickname
@ -531,11 +534,15 @@ final class ChatPeerIdentityCoordinator {
.first
.map(String.init)?
.lowercased() ?? nickname.lowercased()
if let pubkey = context.geoNicknames.first(where: { $0.value.lowercased() == base })?.key {
let geoMatches = context.geoNicknames.filter { $0.value.lowercased() == base }
if geoMatches.count == 1, let pubkey = geoMatches.keys.first {
let conversationKey = PeerID(nostr_: pubkey)
context.registerNostrKeyMapping(pubkey, for: conversationKey)
return conversationKey
}
if geoMatches.count > 1 {
return nil
}
case .mesh:
break

View File

@ -226,10 +226,11 @@ extension ChatViewModel: ChatPrivateConversationContext {
NotificationService.shared.sendPrivateMessageNotification(from: senderName, message: message, peerID: peerID)
}
/// Deliberately no `senderPeerID`: geohash envelopes (and the acks for
/// inbound account DMs sent through here) must never carry the mesh
/// peer ID. The recipient-less encoders fill that field with random bytes.
private func makeGeohashNostrTransport() -> NostrTransport {
let transport = NostrTransport(keychain: keychain, idBridge: idBridge)
transport.senderPeerID = meshService.myPeerID
return transport
NostrTransport(keychain: keychain, idBridge: idBridge)
}
}
@ -491,18 +492,21 @@ final class ChatPrivateConversationCoordinator {
guard let pm = PrivateMessagePacket.decode(from: payload.data) else { return }
let messageId = pm.messageID
// Ack before the dedup guard: a re-sent copy means the sender may not
// have our DELIVERED yet, and markGeoDeliveryAckSent dedups the
// actual sends.
sendDeliveryAckIfNeeded(to: messageId, senderPubKey: senderPubkey, from: id)
// Block check before anything that answers the sender: a blocked
// sender gets no DELIVERED or READ ack back (not even a liveness
// signal) and doesn't consume a dedup slot.
if context.isNostrBlocked(pubkeyHexLowercased: senderPubkey) {
return
}
guard markInboundGeoDMSeen(messageId) else { return }
SecureLogger.info("GeoDM: recv PM <- sender=\(senderPubkey.prefix(8))… mid=\(messageId.prefix(8))…", category: .session)
if context.isNostrBlocked(pubkeyHexLowercased: senderPubkey) {
return
}
// Ack only once the block and dedup checks pass. Outbox retries of a
// message we've already acked are dropped by the dedup guard, and
// markGeoDeliveryAckSent dedups the actual sends by message ID.
sendDeliveryAckIfNeeded(to: messageId, senderPubKey: senderPubkey, from: id)
// Prefer the favorite's stored nickname when the sender resolved to a
// known noise key; the Nostr display name is a geohash-scoped

View File

@ -435,8 +435,14 @@ final class ChatPublicConversationCoordinator: PublicMessagePipelineDelegate {
}
static func archivedEchoKey(senderPeerID: PeerID?, timestamp: Date, content: String) -> String {
let ms = UInt64((timestamp.timeIntervalSince1970 * 1000).rounded())
return "\(senderPeerID?.id ?? "")|\(ms)|\(content)"
// The timestamp is peer-chosen: a wire value near UInt64.max comes
// back from Date as 2^64, so a trapping UInt64(_:) here would be a
// remote crash. Anything that isn't an exact UInt64 keys on its
// Double form instead — still deterministic, which is all the dedup
// needs.
let ms = (timestamp.timeIntervalSince1970 * 1000).rounded()
let msKey = UInt64(exactly: ms).map { String($0) } ?? "\(ms)"
return "\(senderPeerID?.id ?? "")|\(msKey)|\(content)"
}
func handlePublicMessage(_ message: BitchatMessage, powBits: Int = 0) {

View File

@ -1641,6 +1641,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
MeshSightingsTracker.shared.clear()
MeshEchoSettings.reset()
NotificationPrivacySettings.reset()
ComposerDraftStore.reset()
// A hand-added relay names an operator someone chose to route through,
// which is the kind of trace a wipe should not leave behind.
NostrRelaySettings.reset()

View File

@ -98,6 +98,9 @@ struct ContentView: View {
@StateObject private var voiceRecordingVM = VoiceRecordingViewModel()
@State private var messageText = ""
/// Conversation the current `messageText` belongs to, so a channel switch
/// can save under the previous key before loading the next draft.
@State private var activeDraftKey: ComposerDraftStore.Key = .mesh
@FocusState private var isTextFieldFocused: Bool
@Environment(\.colorScheme) var colorScheme
@Environment(\.appTheme) private var appTheme
@ -233,6 +236,11 @@ struct ContentView: View {
}
appChromeModel.setPanicPreparation { [weak voiceRecordingVM] in
voiceRecordingVM?.panicWipe()
// Drop in-memory composer text before ChatViewModel resets
// persisted drafts — otherwise the next inactive/background
// transition would write the pre-wipe draft back.
messageText = ""
activeDraftKey = .mesh
}
#if os(macOS)
DispatchQueue.main.async {
@ -241,6 +249,12 @@ struct ContentView: View {
}
#endif
sharedContentImportModel.updateDestination(sharedContentDestination)
activeDraftKey = ComposerDraftStore.Key.from(
peerID: selectedPrivatePeerID,
fingerprint: selectedPrivatePeerID.flatMap { conversationUIModel.getFingerprint(for: $0) },
channel: locationChannelsModel.selectedChannel
)
messageText = ComposerDraftStore.load(activeDraftKey)
}
.onChange(of: colorScheme) { newValue in
conversationUIModel.setCurrentColorScheme(newValue)
@ -258,9 +272,31 @@ struct ContentView: View {
showSidebar = true
}
sharedContentImportModel.updateDestination(sharedContentDestination)
switchComposerDraft(to: ComposerDraftStore.Key.from(
peerID: newValue,
fingerprint: newValue.flatMap { conversationUIModel.getFingerprint(for: $0) },
channel: locationChannelsModel.selectedChannel
))
}
.onChange(of: locationChannelsModel.selectedChannel) { _ in
.onChange(of: locationChannelsModel.selectedChannel) { newChannel in
sharedContentImportModel.updateDestination(sharedContentDestination)
// Private drafts are keyed by peer; only public channel switches
// need a draft swap while no DM is open.
if selectedPrivatePeerID == nil {
switchComposerDraft(to: ComposerDraftStore.Key.from(
peerID: nil,
fingerprint: nil,
channel: newChannel
))
}
}
.onChange(of: scenePhase) { phase in
if phase == .background || phase == .inactive {
// Always save, including empty — clearing the composer must
// remove the in-memory draft so it does not resurrect on the
// next switch back into this conversation.
ComposerDraftStore.save(messageText, for: activeDraftKey)
}
}
.sheet(
isPresented: Binding(
@ -577,9 +613,17 @@ struct ContentView: View {
guard let trimmed = messageText.trimmedOrNilIfEmpty else { return }
messageText = ""
ComposerDraftStore.save("", for: activeDraftKey)
DispatchQueue.main.async {
self.conversationUIModel.sendMessage(trimmed)
}
}
private func switchComposerDraft(to newKey: ComposerDraftStore.Key) {
guard newKey != activeDraftKey else { return }
ComposerDraftStore.save(messageText, for: activeDraftKey)
activeDraftKey = newKey
messageText = ComposerDraftStore.load(newKey)
}
}

View File

@ -0,0 +1,302 @@
//
// ChatGroupCoordinatorContextTests.swift
// bitchatTests
//
// Exercises `ChatGroupCoordinator`'s group-state authorization against a
// mock `ChatGroupContext` and a real in-memory `GroupStore`, with real
// Ed25519 creator signatures. The Noise session binding is modelled by
// `MockChatGroupContext.fingerprintsByPeerID` (what `meshFingerprint(for:)`
// reports for the authenticated session peer). Store-level pinning is
// covered by `GroupStoreTests`; wire/crypto by `GroupProtocolTests`.
//
import CryptoKit
import Foundation
import Testing
import BitFoundation
@testable import bitchat
// MARK: - Mock Context
@MainActor
private final class MockChatGroupContext: ChatGroupContext {
// Identity & state
let nickname = "me"
let myPeerID: PeerID
var selectedPrivateChatPeer: PeerID?
let groupStore = GroupStore(keychain: MockKeychain(), persistsToDisk: false)
private let identity: TestIdentity
init(identity: TestIdentity) {
self.identity = identity
self.myPeerID = identity.peerID
}
func myNoiseFingerprint() -> String { identity.fingerprint }
func mySigningPublicKey() -> Data { identity.member.signingKey }
func signWithNoiseKey(_ data: Data) -> Data? { identity.sign(data) }
// Peers: the fingerprint each Noise session authenticated.
var fingerprintsByPeerID: [PeerID: String] = [:]
func getPeerIDForNickname(_ nickname: String) -> PeerID? { nil }
func isPeerConnected(_ peerID: PeerID) -> Bool { false }
func peerNickname(for peerID: PeerID) -> String? { nil }
func meshFingerprint(for peerID: PeerID) -> String? { fingerprintsByPeerID[peerID] }
func cryptoIdentity(for peerID: PeerID) -> (fingerprint: String, signingKey: Data)? { nil }
func connectedPeerID(forFingerprint fingerprint: String) -> PeerID? { nil }
func isFingerprintBlocked(_ fingerprint: String) -> Bool { false }
// Transport (outbound state is not exercised by these tests)
func sendGroupInvitePayload(_ payload: Data, to peerID: PeerID) {}
func sendGroupKeyUpdatePayload(_ payload: Data, to peerID: PeerID) {}
func broadcastGroupMessagePayload(_ payload: Data) {}
// Conversation intents
private(set) var removedPrivateChats: [PeerID] = []
private(set) var endPrivateChatCount = 0
private(set) var systemMessages: [String] = []
@discardableResult
func appendPrivateMessage(_ message: BitchatMessage, to peerID: PeerID) -> Bool { true }
func markPrivateChatUnread(_ peerID: PeerID) {}
func removePrivateChat(_ peerID: PeerID) { removedPrivateChats.append(peerID) }
func startPrivateChat(with peerID: PeerID) {}
func endPrivateChat() { endPrivateChatCount += 1 }
func addSystemMessage(_ content: String) { systemMessages.append(content) }
func addLocalPrivateSystemMessage(_ content: String, to peerID: PeerID) {}
func notifyUIChanged() {}
func notifyPrivateMessage(from senderName: String, message: String, peerID: PeerID) {}
func clearRecordedEffects() {
removedPrivateChats.removeAll()
endPrivateChatCount = 0
systemMessages.removeAll()
}
}
// MARK: - Fixtures
/// A Noise identity (fingerprint → short peer ID) plus a real Ed25519
/// signing key, so creator signatures verify for real.
private struct TestIdentity {
let fingerprint: String
let nickname: String
private let signingKey = Curve25519.Signing.PrivateKey()
init(seed: UInt8, nickname: String) {
fingerprint = Data(repeating: seed, count: 32).hexEncodedString()
self.nickname = nickname
}
var peerID: PeerID { PeerID(str: String(fingerprint.prefix(16))) }
var member: GroupMember {
GroupMember(fingerprint: fingerprint, signingKey: signingKey.publicKey.rawRepresentation, nickname: nickname)
}
/// A roster entry claiming this identity's fingerprint and nickname but
/// pinning `forger`'s signing key — how a forged roster impersonates
/// real members.
func impersonated(by forger: TestIdentity) -> GroupMember {
GroupMember(fingerprint: fingerprint, signingKey: forger.member.signingKey, nickname: nickname)
}
func sign(_ data: Data) -> Data? { try? signingKey.signature(for: data) }
}
// MARK: - Tests
@MainActor
struct ChatGroupCoordinatorContextTests {
private let me = TestIdentity(seed: 0x0E, nickname: "me")
private let creator = TestIdentity(seed: 0xC1, nickname: "creator")
private let member = TestIdentity(seed: 0xA2, nickname: "member")
private let attacker = TestIdentity(seed: 0xEE, nickname: "creator")
private let groupID = Data((0..<16).map { UInt8($0) })
private let groupKey = Data(repeating: 0x42, count: 32)
private let joinedEpoch: UInt32 = 3
/// A creator-signed state payload, encoded for the wire.
private func statePayload(
epoch: UInt32,
members: [GroupMember],
creatorFingerprint: String,
key: Data,
signedBy signer: TestIdentity
) throws -> Data {
let group = BitchatGroup(
groupID: groupID,
name: "trail crew",
epoch: epoch,
members: members,
creatorFingerprint: creatorFingerprint
)
let payload = try #require(GroupStatePayload.makeSigned(group: group, key: key, sign: signer.sign))
return try #require(payload.encode())
}
/// State from the real creator over their authenticated session.
private func creatorState(epoch: UInt32, members: [GroupMember], key: Data) throws -> Data {
try statePayload(epoch: epoch, members: members, creatorFingerprint: creator.fingerprint, key: key, signedBy: creator)
}
/// Joins the group through the coordinator (the creator's invite), opens
/// its chat, and clears the join side effects. Both the creator and the
/// attacker hold Noise sessions with us.
private func makeJoinedGroup() throws -> (MockChatGroupContext, ChatGroupCoordinator, BitchatGroup) {
let context = MockChatGroupContext(identity: me)
let coordinator = ChatGroupCoordinator(context: context)
context.fingerprintsByPeerID[creator.peerID] = creator.fingerprint
context.fingerprintsByPeerID[attacker.peerID] = attacker.fingerprint
let invite = try creatorState(epoch: joinedEpoch, members: [creator.member, member.member, me.member], key: groupKey)
coordinator.handleGroupInvitePayload(from: creator.peerID, payload: invite)
let joined = try #require(context.groupStore.group(withID: groupID))
#expect(joined.creatorFingerprint == creator.fingerprint)
#expect(context.systemMessages.count == 1) // the join notice
context.selectedPrivateChatPeer = joined.peerID
context.clearRecordedEffects()
return (context, coordinator, joined)
}
private func expectUnchanged(_ context: MockChatGroupContext, joined: BitchatGroup) {
#expect(context.groupStore.group(withID: groupID) == joined)
#expect(context.groupStore.key(forGroupID: groupID) == groupKey)
#expect(context.removedPrivateChats.isEmpty)
#expect(context.endPrivateChatCount == 0)
#expect(context.systemMessages.isEmpty)
}
// MARK: Takeover
@Test
func nonCreatorNamingItselfCreatorAtHigherEpochIsRejected() throws {
let (context, coordinator, joined) = try makeJoinedGroup()
// Self-named creator, self-signed, at the highest epoch, with every
// real member re-pinned to the attacker's key. Passes the sender and
// signature checks; only the stored-creator pin stops it.
let hijack = try statePayload(
epoch: .max,
members: [attacker.member, me.member, creator.impersonated(by: attacker), member.impersonated(by: attacker)],
creatorFingerprint: attacker.fingerprint,
key: Data(repeating: 0xAB, count: 32),
signedBy: attacker
)
coordinator.handleGroupKeyUpdatePayload(from: attacker.peerID, payload: hijack)
expectUnchanged(context, joined: joined)
coordinator.handleGroupInvitePayload(from: attacker.peerID, payload: hijack)
expectUnchanged(context, joined: joined)
// The attacker's epoch did not lock the real creator out.
let rotatedKey = Data(repeating: 0x5A, count: 32)
let rotation = try creatorState(epoch: joinedEpoch + 1, members: [creator.member, member.member, me.member], key: rotatedKey)
coordinator.handleGroupKeyUpdatePayload(from: creator.peerID, payload: rotation)
#expect(context.groupStore.group(withID: groupID)?.epoch == joinedEpoch + 1)
#expect(context.groupStore.key(forGroupID: groupID) == rotatedKey)
}
@Test
func stateNamingTheStoredCreatorWithAnotherSigningKeyIsRejected() throws {
let (context, coordinator, joined) = try makeJoinedGroup()
// Even a session that resolves to the stored creator's fingerprint
// cannot re-pin the creator's signing key.
let impostorPeerID = PeerID(str: "00112233aabbccdd")
context.fingerprintsByPeerID[impostorPeerID] = creator.fingerprint
let repin = try statePayload(
epoch: joinedEpoch + 1,
members: [creator.impersonated(by: attacker), member.member, me.member],
creatorFingerprint: creator.fingerprint,
key: Data(repeating: 0xAB, count: 32),
signedBy: attacker
)
coordinator.handleGroupKeyUpdatePayload(from: impostorPeerID, payload: repin)
expectUnchanged(context, joined: joined)
}
// MARK: Deletion
@Test
func nonCreatorRosterOmittingUsDoesNotDeleteTheGroup() throws {
let (context, coordinator, joined) = try makeJoinedGroup()
let eviction = try statePayload(
epoch: joinedEpoch + 1,
members: [attacker.member, creator.impersonated(by: attacker)],
creatorFingerprint: attacker.fingerprint,
key: Data(repeating: 0xAB, count: 32),
signedBy: attacker
)
coordinator.handleGroupKeyUpdatePayload(from: attacker.peerID, payload: eviction)
expectUnchanged(context, joined: joined)
}
// MARK: Legitimate creator
@Test
func creatorRotationIsAccepted() throws {
let (context, coordinator, joined) = try makeJoinedGroup()
let rotatedKey = Data(repeating: 0x5A, count: 32)
let rotation = try creatorState(epoch: joinedEpoch + 1, members: [creator.member, me.member], key: rotatedKey)
coordinator.handleGroupKeyUpdatePayload(from: creator.peerID, payload: rotation)
let stored = try #require(context.groupStore.group(withID: groupID))
#expect(stored.epoch == joinedEpoch + 1)
#expect(stored.members == [creator.member, me.member])
#expect(stored.creator == joined.creator)
#expect(context.groupStore.key(forGroupID: groupID) == rotatedKey)
#expect(context.removedPrivateChats.isEmpty)
#expect(context.systemMessages.isEmpty) // not a new membership
}
@Test
func creatorRemovalStillRemovesTheGroup() throws {
let (context, coordinator, joined) = try makeJoinedGroup()
// What `notifyRemovedMember` sends: the rotated roster without us,
// under a throwaway all-zero key.
let removal = try creatorState(
epoch: joinedEpoch + 1,
members: [creator.member, member.member],
key: Data(count: BitchatGroup.keyLength)
)
coordinator.handleGroupKeyUpdatePayload(from: creator.peerID, payload: removal)
#expect(context.groupStore.group(withID: groupID) == nil)
#expect(context.groupStore.key(forGroupID: groupID) == nil)
#expect(context.removedPrivateChats == [joined.peerID])
#expect(context.endPrivateChatCount == 1)
#expect(context.systemMessages.count == 1) // "removed from group"
}
@Test
func staleCreatorStateIsRejectedIncludingStaleRemoval() throws {
let (context, coordinator, joined) = try makeJoinedGroup()
let staleRotation = try creatorState(
epoch: joinedEpoch - 1,
members: [creator.member, me.member],
key: Data(repeating: 0x5A, count: 32)
)
coordinator.handleGroupKeyUpdatePayload(from: creator.peerID, payload: staleRotation)
expectUnchanged(context, joined: joined)
// An older removal (e.g. delivered after a re-invite) must not undo
// the newer membership.
let staleRemoval = try creatorState(
epoch: joinedEpoch - 1,
members: [creator.member, member.member],
key: Data(count: BitchatGroup.keyLength)
)
coordinator.handleGroupKeyUpdatePayload(from: creator.peerID, payload: staleRemoval)
expectUnchanged(context, joined: joined)
}
}

View File

@ -343,8 +343,7 @@ struct ChatNostrCoordinatorContextTests {
let sender = try NostrIdentity.generate()
let embedded = try #require(NostrEmbeddedBitChat.encodePMForNostrNoRecipient(
content: "psst",
messageID: "gm-1",
senderPeerID: PeerID(str: "aabbccddeeff0011")
messageID: "gm-1"
))
let giftWrap = try NostrProtocol.createPrivateMessage(
content: embedded,
@ -386,8 +385,7 @@ struct ChatNostrCoordinatorContextTests {
let sender = try NostrIdentity.generate()
let embedded = try #require(NostrEmbeddedBitChat.encodePMForNostrNoRecipient(
content: "pre-wipe secret",
messageID: "gm-wipe-1",
senderPeerID: PeerID(str: "aabbccddeeff0011")
messageID: "gm-wipe-1"
))
let giftWrap = try NostrProtocol.createPrivateMessage(
content: embedded,

View File

@ -446,6 +446,27 @@ struct ChatPeerIdentityCoordinatorContextTests {
context.peerIDsByNickname["carol"] = meshPeer
#expect(coordinator.getPeerIDForNickname("carol") == meshPeer)
}
@Test @MainActor
func getPeerIDForNickname_inGeohashChannel_refusesAmbiguousBaseName() async {
let context = MockChatPeerIdentityContext()
let coordinator = ChatPeerIdentityCoordinator(context: context)
let aliceA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
let aliceB = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
context.activeChannel = .location(GeohashChannel(level: .city, geohash: "u4pruy"))
context.geohashPeople = [
GeoPerson(id: aliceA, displayName: "alice#aaaa", lastSeen: Date()),
GeoPerson(id: aliceB, displayName: "alice#bbbb", lastSeen: Date())
]
context.geoNicknames[aliceA] = "alice"
context.geoNicknames[aliceB] = "alice"
context.peerIDsByNickname["alice"] = PeerID(str: "1122334455667788")
#expect(coordinator.getPeerIDForNickname("alice") == nil)
#expect(coordinator.getPeerIDForNickname("alice#aaaa") == PeerID(nostr_: aliceA))
#expect(coordinator.getPeerIDForNickname("alice#bbbb") == PeerID(nostr_: aliceB))
}
@Test @MainActor
func toggleFavorite_forNoiseKeyPeer_usesInjectedFavoritesStore() async {
let context = MockChatPeerIdentityContext()

View File

@ -491,6 +491,49 @@ struct ChatPrivateConversationCoordinatorContextTests {
#expect(context.privateChats[convKey]?.count == 1)
}
@Test @MainActor
func geoPrivateMessage_blockedSenderGetsNoAckOrReadReceipt() async {
let context = MockChatPrivateConversationContext()
let coordinator = ChatPrivateConversationCoordinator(context: context)
let convKey = PeerID(str: "nostr_abcdef12")
let senderPubkey = "feedface00112233"
context.blockedNostrPubkeys = [senderPubkey]
// Viewing the chat: an admitted message would also get a READ ack.
context.selectedPrivateChatPeer = convKey
let payloadData = PrivateMessagePacket(messageID: "geo-blocked", content: "you there?").encode()!
let payload = NoisePayload(type: .privateMessage, data: payloadData)
coordinator.handlePrivateMessage(
payload,
senderPubkey: senderPubkey,
convKey: convKey,
id: MockChatPrivateConversationContext.dummyIdentity,
messageTimestamp: Date()
)
// Nothing goes back to a blocked sender, not even a DELIVERED ack
// that would confirm this identity is online.
#expect(context.geoDeliveryAcks.isEmpty)
#expect(context.geoReadReceipts.isEmpty)
#expect(context.sentGeoDeliveryAcks.isEmpty)
#expect(context.privateChats[convKey] == nil)
#expect(context.privateMessageNotifications.isEmpty)
// The dropped copy didn't consume the dedup slot: after unblocking, a
// retry of the same message is admitted and acked exactly once.
context.blockedNostrPubkeys = []
coordinator.handlePrivateMessage(
payload,
senderPubkey: senderPubkey,
convKey: convKey,
id: MockChatPrivateConversationContext.dummyIdentity,
messageTimestamp: Date()
)
#expect(context.geoDeliveryAcks.map(\.messageID) == ["geo-blocked"])
#expect(context.geoReadReceipts.map(\.messageID) == ["geo-blocked"])
#expect(context.privateChats[convKey]?.map(\.id) == ["geo-blocked"])
}
@Test @MainActor
func accountDM_handsOpenShortIDConversationToStableWhenOffline() async {
let context = MockChatPrivateConversationContext()

View File

@ -350,6 +350,68 @@ struct ChatPublicConversationCoordinatorContextTests {
#expect(context.enqueuedMessages.first?.conversationID == .geohash(geohash))
}
/// A peer-chosen wire timestamp near UInt64.max comes back from Date as
/// 2^64 ms; keying an archived echo on it used to trap the main actor —
/// a remote crash on receipt, and on every launch once archived.
@Test @MainActor
func handlePublicMessage_uint64MaxTimestamp_neitherTrapsNorBreaksEchoDedup() async {
let context = MockChatPublicConversationContext()
let coordinator = ChatPublicConversationCoordinator(context: context)
let senderPeerID = PeerID(str: "aabbccddeeff0011")
// Same conversion as BLEPublicMessageHandler / the archive decoder.
let wireMax = Date(timeIntervalSince1970: Double(UInt64.max) / 1000)
// Launch-time echo seeding path.
coordinator.registerArchivedEcho(senderPeerID: senderPeerID, timestamp: wireMax, content: "echoed")
// Live path: a copy of the seeded echo is still recognized...
coordinator.handlePublicMessage(BitchatMessage(
id: "live-copy",
sender: "alice",
content: "echoed",
timestamp: wireMax,
isRelay: false,
senderPeerID: senderPeerID
))
#expect(context.enqueuedMessageIDs.isEmpty)
// ...and a fresh message with the same timestamp is delivered.
coordinator.handlePublicMessage(BitchatMessage(
id: "live-new",
sender: "alice",
content: "new",
timestamp: wireMax,
isRelay: false,
senderPeerID: senderPeerID
))
#expect(context.enqueuedMessageIDs == ["live-new"])
}
@Test @MainActor
func archivedEchoKey_isTotalForAnyDate() async {
let sender = PeerID(str: "aabbccddeeff0011")
func key(_ date: Date) -> String {
ChatPublicConversationCoordinator.archivedEchoKey(senderPeerID: sender, timestamp: date, content: "x")
}
// Ordinary timestamps keep the integer-millisecond key.
#expect(key(Date(timeIntervalSince1970: 1_700_000_000.123)) == "aabbccddeeff0011|1700000000123|x")
// Out-of-range dates key deterministically instead of trapping.
let extremes = [
Date(timeIntervalSince1970: Double(UInt64.max) / 1000),
Date(timeIntervalSince1970: -1),
Date(timeIntervalSince1970: .infinity),
Date(timeIntervalSince1970: -.infinity),
Date(timeIntervalSince1970: .nan),
.distantFuture,
.distantPast
]
for date in extremes {
#expect(key(date).hasPrefix("aabbccddeeff0011|"))
}
#expect(key(extremes[0]) != key(Date(timeIntervalSince1970: 1_700_000_000)))
}
/// `/clear` on the mesh timeline used to only record a watermark, leaving
/// the archive on disk for up to its freshness window — so someone who
/// cleared before a police stop had deleted nothing. It must now erase the

View File

@ -452,7 +452,7 @@ struct ChatViewModelNostrExtensionTests {
)
], for: convKey)
let content = try ackContent(type: .delivered, messageID: messageID, senderPeerID: PeerID(str: "0123456789abcdef"))
let content = try ackContent(type: .delivered, messageID: messageID)
let giftWrap = try NostrProtocol.createPrivateMessage(
content: content,
recipientPubkey: recipient.publicKeyHex,
@ -490,7 +490,7 @@ struct ChatViewModelNostrExtensionTests {
)
], for: convKey)
let content = try ackContent(type: .readReceipt, messageID: messageID, senderPeerID: PeerID(str: "0123456789abcdef"))
let content = try ackContent(type: .readReceipt, messageID: messageID)
let giftWrap = try NostrProtocol.createPrivateMessage(
content: content,
recipientPubkey: recipient.publicKeyHex,
@ -516,8 +516,7 @@ struct ChatViewModelNostrExtensionTests {
let content = try privateMessageContent(
text: "Hello from gift wrap",
messageID: messageID,
senderPeerID: PeerID(str: "0123456789abcdef")
messageID: messageID
)
let giftWrap = try NostrProtocol.createPrivateMessage(
content: content,
@ -548,8 +547,7 @@ struct ChatViewModelNostrExtensionTests {
let content = try privateMessageContent(
text: "Blocked",
messageID: messageID,
senderPeerID: PeerID(str: "0123456789abcdef")
messageID: messageID
)
let giftWrap = try NostrProtocol.createPrivateMessage(
content: content,
@ -559,14 +557,17 @@ struct ChatViewModelNostrExtensionTests {
viewModel.handleGiftWrap(giftWrap, id: recipient)
// Gift-wrap decryption runs off the main actor; wait for the ack
// (sent even for blocked senders) to know processing finished.
let didAck = await TestHelpers.waitUntil(
{ viewModel.sentGeoDeliveryAcks.contains(messageID) },
// Gift-wrap decryption runs off the main actor. The key mapping is
// registered in the same main-actor hop that runs the PM handler, so
// once it shows up the handler has already returned.
let didProcess = await TestHelpers.waitUntil(
{ viewModel.nostrKeyMapping[convKey] == sender.publicKeyHex },
timeout: TestConstants.settleTimeout
)
#expect(didAck)
#expect(didProcess)
#expect(viewModel.privateChats[convKey] == nil)
// A blocked sender gets nothing back, not even a DELIVERED ack.
#expect(!viewModel.sentGeoDeliveryAcks.contains(messageID))
}
@Test @MainActor
@ -591,7 +592,7 @@ struct ChatViewModelNostrExtensionTests {
)
], for: convKey)
let content = try ackContent(type: .delivered, messageID: messageID, senderPeerID: PeerID(str: "0123456789abcdef"))
let content = try ackContent(type: .delivered, messageID: messageID)
let giftWrap = try NostrProtocol.createPrivateMessage(
content: content,
recipientPubkey: recipient.publicKeyHex,
@ -1262,22 +1263,20 @@ private func base64URLEncode(_ data: Data) -> String {
.replacingOccurrences(of: "=", with: "")
}
private func ackContent(type: NoisePayloadType, messageID: String, senderPeerID: PeerID) throws -> String {
private func ackContent(type: NoisePayloadType, messageID: String) throws -> String {
if let content = NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(
type: type,
messageID: messageID,
senderPeerID: senderPeerID
messageID: messageID
) {
return content
}
throw ChatViewModelExtensionsTestError.invalidAckContent
}
private func privateMessageContent(text: String, messageID: String, senderPeerID: PeerID) throws -> String {
private func privateMessageContent(text: String, messageID: String) throws -> String {
if let content = NostrEmbeddedBitChat.encodePMForNostrNoRecipient(
content: text,
messageID: messageID,
senderPeerID: senderPeerID
messageID: messageID
) {
return content
}

View File

@ -738,6 +738,121 @@ struct GossipSyncManagerTests {
#expect(manager._hasPrekeyBundle(for: ownerPeer))
}
// MARK: - Future-dated packets
/// Age windows used to bound only the past, so a sync reply dated 2099
/// never expired and was re-served to every requester.
@Test func futureDatedPacketsAreNeitherStoredNorServed() async throws {
var config = GossipSyncManager.Config()
config.messageSyncIntervalSeconds = 0
config.fragmentSyncIntervalSeconds = 0
config.fileTransferSyncIntervalSeconds = 0
config.prekeyBundleSyncIntervalSeconds = 0
let manager = GossipSyncManager(myPeerID: myPeerID, config: config, requestSyncManager: RequestSyncManager())
let delegate = RecordingDelegate()
manager.delegate = delegate
let futureSender = try #require(Data(hexString: "f0f1f2f3f4f5f6f7"))
let honestSender = try #require(Data(hexString: "a0a1a2a3a4a5a6a7"))
let nowMs = UInt64(Date().timeIntervalSince1970 * 1000)
let beyondSkewMs = nowMs + config.maxFutureSkewMs + 60_000
let futureTypes: [MessageType] = [.announce, .message, .fragment, .fileTransfer, .groupMessage]
for (index, type) in futureTypes.enumerated() {
for timestamp in [beyondSkewMs, UInt64.max] {
manager.onPublicPacketSeen(BitchatPacket(
type: type.rawValue,
senderID: futureSender,
recipientID: nil,
timestamp: timestamp,
payload: Data([UInt8(index), 0xEE]),
signature: nil,
ttl: 1
))
}
}
let honest = BitchatPacket(
type: MessageType.message.rawValue,
senderID: honestSender,
recipientID: nil,
timestamp: nowMs,
payload: Data([0x01]),
signature: nil,
ttl: 1
)
manager.onPublicPacketSeen(honest)
#expect(manager._hasAnnouncement(for: PeerID(hexData: futureSender)) == false)
#expect(manager._messageCount(for: PeerID(hexData: futureSender)) == 0)
// An empty filter asks for everything the stores hold.
let request = RequestSyncPacket(
p: 7,
m: 1,
data: Data(),
types: SyncTypeFlags.publicMessages.union([.fragment, .fileTransfer, .groupMessage])
)
manager.handleRequestSync(from: PeerID(str: "FFFFFFFFFFFFFFFF"), request: request)
try await TestHelpers.waitFor({ !delegate.packets.isEmpty }, timeout: TestConstants.settleTimeout)
// Barrier: flush the sync queue so any late future-dated reply is visible.
manager._performMaintenanceSynchronously(now: Date())
#expect(delegate.packets.map(\.senderID) == [honestSender])
}
/// The sync cursor is the oldest timestamp the filter covers. Enough
/// future-dated junk used to fill the filter's newest slots and push the
/// cursor past every real message, so responders skipped all backfill.
@Test func futureDatedJunkCannotDragTheSinceCursor() throws {
var config = GossipSyncManager.Config()
config.seenCapacity = 100
config.gcsMaxBytes = 32 // caps the filter at 28 IDs (256 bits / 9 bits per element)
config.messageSyncIntervalSeconds = 1
config.fragmentSyncIntervalSeconds = 0
config.fileTransferSyncIntervalSeconds = 0
config.prekeyBundleSyncIntervalSeconds = 0
config.maintenanceIntervalSeconds = 0
let manager = GossipSyncManager(myPeerID: myPeerID, config: config, requestSyncManager: RequestSyncManager())
let delegate = RecordingDelegate()
manager.delegate = delegate
let junkSender = try #require(Data(hexString: "f0f1f2f3f4f5f6f7"))
let honestSender = try #require(Data(hexString: "a0a1a2a3a4a5a6a7"))
let nowMs = UInt64(Date().timeIntervalSince1970 * 1000)
// Unsigned group ciphertext needs no key to mint.
for i in 0..<40 {
manager.onPublicPacketSeen(BitchatPacket(
type: MessageType.groupMessage.rawValue,
senderID: junkSender,
recipientID: nil,
timestamp: nowMs + 3_600_000 + UInt64(i),
payload: Data([UInt8(i)]),
signature: nil,
ttl: 1
))
}
for i in 0..<5 {
manager.onPublicPacketSeen(BitchatPacket(
type: MessageType.message.rawValue,
senderID: honestSender,
recipientID: nil,
timestamp: nowMs - 60_000 + UInt64(i),
payload: Data([UInt8(i)]),
signature: nil,
ttl: 1
))
}
manager._performMaintenanceSynchronously(now: Date())
let requests = delegate.packets.compactMap { RequestSyncPacket.decode(from: $0.payload) }
let messageRequest = try #require(requests.first { $0.types?.contains(.message) == true })
// Only the five honest messages are candidates, so the filter covers
// them all and no cursor is needed.
#expect(messageRequest.sinceTimestamp == nil)
}
// MARK: - Archive persistence
@Test func publicMessagesRestoreFromArchiveAcrossRestart() async throws {
@ -810,6 +925,143 @@ struct GossipSyncManagerTests {
#expect(manager._messageCount(for: PeerID(hexData: senderID)) == 0)
}
/// An older build could archive a future-dated sync reply; restoring it
/// seeded a launch-time echo that crashed the app on every launch. The
/// restore must drop it and rewrite the file without it.
@Test func archiveRestoreDropsAndPurgesFutureDatedMessages() async throws {
let mixedURL = FileManager.default.temporaryDirectory
.appendingPathComponent("gossip-archive-\(UUID().uuidString).json")
let poisonOnlyURL = FileManager.default.temporaryDirectory
.appendingPathComponent("gossip-archive-\(UUID().uuidString).json")
defer {
try? FileManager.default.removeItem(at: mixedURL)
try? FileManager.default.removeItem(at: poisonOnlyURL)
}
let poisonSender = try #require(Data(hexString: "f0f1f2f3f4f5f6f7"))
let honestSender = try #require(Data(hexString: "a0a1a2a3a4a5a6a7"))
let nowMs = UInt64(Date().timeIntervalSince1970 * 1000)
func archived(from sender: Data, at timestamp: UInt64) throws -> Data {
try #require(BitchatPacket(
type: MessageType.message.rawValue,
senderID: sender,
recipientID: nil,
timestamp: timestamp,
payload: Data([0x01]),
signature: nil,
ttl: 1
).toBinaryData(padding: false))
}
let poison = [try archived(from: poisonSender, at: .max), try archived(from: poisonSender, at: nowMs + 3_600_000)]
// Mixed archive: only the honest entry is restored, offered as an
// echo, and written back.
let mixedArchive = GossipMessageArchive(fileURL: mixedURL)
mixedArchive.save(poison + [try archived(from: honestSender, at: nowMs)])
let manager = GossipSyncManager(myPeerID: myPeerID, requestSyncManager: RequestSyncManager(), archive: mixedArchive)
// The restore is queued at init; this synchronous pass runs after it
// and persists the dirty store.
manager._performMaintenanceSynchronously(now: Date())
#expect(manager._messageCount(for: PeerID(hexData: honestSender)) == 1)
#expect(manager._messageCount(for: PeerID(hexData: poisonSender)) == 0)
let echoes = await withCheckedContinuation { continuation in
manager.collectPublicMessagePackets { continuation.resume(returning: $0) }
}
#expect(echoes.map(\.senderID) == [honestSender])
#expect(mixedArchive.load().compactMap { BitchatPacket.from($0)?.senderID } == [honestSender])
// Poison-only archive: nothing restores, and the file is purged.
let poisonOnlyArchive = GossipMessageArchive(fileURL: poisonOnlyURL)
poisonOnlyArchive.save(poison)
let purging = GossipSyncManager(myPeerID: myPeerID, requestSyncManager: RequestSyncManager(), archive: poisonOnlyArchive)
purging._performMaintenanceSynchronously(now: Date())
#expect(purging._messageCount(for: PeerID(hexData: poisonSender)) == 0)
#expect(!FileManager.default.fileExists(atPath: poisonOnlyURL.path))
}
// MARK: - Byte budgets
/// Three 100-byte packets from distinct senders, oldest first.
private func makeBudgetPackets(type: MessageType) throws -> [BitchatPacket] {
let nowMs = UInt64(Date().timeIntervalSince1970 * 1000)
return try ["00000000000000a1", "00000000000000a2", "00000000000000a3"].enumerated().map { index, hex in
BitchatPacket(
type: type.rawValue,
senderID: try #require(Data(hexString: hex)),
recipientID: nil,
timestamp: nowMs + UInt64(index),
payload: Data(repeating: UInt8(index), count: 100),
signature: nil,
ttl: 1
)
}
}
@Test func messageStoreEvictsOldestPastItsByteBudget() throws {
var config = GossipSyncManager.Config()
config.messageByteBudget = 250
let manager = GossipSyncManager(myPeerID: myPeerID, config: config, requestSyncManager: RequestSyncManager())
let packets = try makeBudgetPackets(type: .message)
packets.forEach(manager.onPublicPacketSeen)
// 300 bytes against a 250-byte budget: only the oldest goes, even
// though the 1000-packet count cap is nowhere near.
#expect(manager._messageCount(for: PeerID(hexData: packets[0].senderID)) == 0)
#expect(manager._messageCount(for: PeerID(hexData: packets[1].senderID)) == 1)
#expect(manager._messageCount(for: PeerID(hexData: packets[2].senderID)) == 1)
}
@Test func fragmentFileAndGroupStoresEvictOldestPastTheirByteBudgets() async throws {
var config = GossipSyncManager.Config()
config.fragmentByteBudget = 250
config.fileTransferByteBudget = 250
config.groupMessageByteBudget = 250
config.messageSyncIntervalSeconds = 0
config.fragmentSyncIntervalSeconds = 0
config.fileTransferSyncIntervalSeconds = 0
config.prekeyBundleSyncIntervalSeconds = 0
let manager = GossipSyncManager(myPeerID: myPeerID, config: config, requestSyncManager: RequestSyncManager())
let delegate = RecordingDelegate()
manager.delegate = delegate
var expectedIDs: Set<Data> = []
for type in [MessageType.fragment, .fileTransfer, .groupMessage] {
let packets = try makeBudgetPackets(type: type)
packets.forEach(manager.onPublicPacketSeen)
expectedIDs.formUnion(packets.dropFirst().map { PacketIdUtil.computeId($0) })
}
let request = RequestSyncPacket(p: 4, m: 1, data: Data(), types: [.fragment, .fileTransfer, .groupMessage])
manager.handleRequestSync(from: PeerID(str: "FFFFFFFFFFFFFFFF"), request: request)
try await TestHelpers.waitFor({ delegate.packets.count >= expectedIDs.count }, timeout: TestConstants.settleTimeout)
// Barrier: flush the sync queue so an evicted packet served late would be visible.
manager._performMaintenanceSynchronously(now: Date())
#expect(Set(delegate.packets.map { PacketIdUtil.computeId($0) }) == expectedIDs)
#expect(delegate.packets.count == expectedIDs.count)
}
@Test func archiveRestoreStopsAtTheByteBudgetKeepingTheNewest() throws {
let fileURL = FileManager.default.temporaryDirectory
.appendingPathComponent("gossip-archive-\(UUID().uuidString).json")
defer { try? FileManager.default.removeItem(at: fileURL) }
let packets = try makeBudgetPackets(type: .message)
let archive = GossipMessageArchive(fileURL: fileURL)
archive.save(try packets.map { try #require($0.toBinaryData(padding: false)) })
var config = GossipSyncManager.Config()
config.messageByteBudget = 250
let manager = GossipSyncManager(myPeerID: myPeerID, config: config, requestSyncManager: RequestSyncManager(), archive: archive)
// Barrier: the restore is queued on the sync queue at init.
manager._performMaintenanceSynchronously(now: Date())
#expect(manager._messageCount(for: PeerID(hexData: packets[0].senderID)) == 0)
#expect(manager._messageCount(for: PeerID(hexData: packets[1].senderID)) == 1)
#expect(manager._messageCount(for: PeerID(hexData: packets[2].senderID)) == 1)
}
/// Clearing the mesh timeline must leave nothing behind on disk: a
/// relaunch that restored the archive would undo the clear.
@Test func removeAllPublicMessagesErasesTheArchiveOnDisk() async throws {
@ -859,11 +1111,15 @@ private final class RecordingDelegate: GossipSyncManager.Delegate {
private let lock = NSLock()
func sendPacket(_ packet: BitchatPacket) {
// Run the hook before recording: a waiter that sees `lastPacket`
// then knows the hook already ran. Recording first let
// concurrentPacketIntakeAndSyncRequest's waitFor win the race and
// close its confirmation before the hook confirmed it.
onSend?()
lock.lock()
lastPacket = packet
packets.append(packet)
lock.unlock()
onSend?()
}
func sendPacket(to peerID: PeerID, packet: BitchatPacket) {

View File

@ -71,43 +71,139 @@ struct LocalizationCoverageTests {
}
/// The catalog tests above validate the CATALOG; this one validates the
/// CODE. A `String(localized:)` whose key is absent from every catalog
/// compiles and runs fine — it just silently ships its English
/// `defaultValue` to all 29 non-source locales. That blind spot let the
/// entire notices/board composer (10 keys), two delivery states, and two
/// media-failure reasons go untranslated while the coverage tests stayed
/// green. Interpolated keys can't be checked statically and are skipped;
/// every literal key must resolve.
@Test func everyCodeReferencedKeyExistsInACatalog() throws {
let main = try Self.loadCatalog("bitchat/Localizable.xcstrings")
let shareExt = try Self.loadCatalog("bitchatShareExtension/Localization/Localizable.xcstrings")
let knownKeys = Set(main.coverage.keys).union(shareExt.coverage.keys)
/// CODE. A `String(localized:)` whose key is absent from the catalog its
/// target actually ships compiles and runs fine — it just silently ships
/// its English `defaultValue` to all 29 non-source locales. That blind
/// spot let the entire notices/board composer (10 keys), two delivery
/// states, and two media-failure reasons go untranslated while the
/// coverage tests stayed green. Interpolated keys can't be checked
/// statically and are skipped; every literal key must resolve.
///
/// The catalogs are checked per target, not as a union: the share
/// extension bundles only its own catalog, so a key it references that
/// lives solely in the app catalog is just as untranslated there as one
/// that exists nowhere.
@Test func everyCodeReferencedKeyExistsInItsOwnCatalog() throws {
let main = try Self.loadCatalog(Self.mainCatalogPath)
let shareExt = try Self.loadCatalog(Self.shareExtensionCatalogPath)
let mainKeys = Set(main.coverage.keys)
let shareKeys = Set(shareExt.coverage.keys)
let pattern = try NSRegularExpression(pattern: #"String\(\s*localized:\s*"([^"\\]+)""#)
var missing: [String] = []
// Files under `bitchat/` that the share extension also compiles have to
// resolve in both catalogs, since each target bundles only its own.
let sharedSources = try Self.shareExtensionMembershipExceptions()
for sourceRoot in ["bitchat", "bitchatShareExtension"] {
let rootURL = Self.repoRoot.appendingPathComponent(sourceRoot)
let enumerator = try #require(FileManager.default.enumerator(
at: rootURL,
includingPropertiesForKeys: nil
))
for case let fileURL as URL in enumerator where fileURL.pathExtension == "swift" {
let source = try String(contentsOf: fileURL, encoding: .utf8)
let range = NSRange(source.startIndex..., in: source)
pattern.enumerateMatches(in: source, range: range) { match, _, _ in
guard let match, let keyRange = Range(match.range(at: 1), in: source) else { return }
let key = String(source[keyRange])
if !knownKeys.contains(key) {
missing.append("\(key) (\(fileURL.lastPathComponent))")
}
for (sourceRoot, ownKeys, otherKeys, ownCatalog, otherCatalog) in [
("bitchat", mainKeys, shareKeys, Self.mainCatalogPath, Self.shareExtensionCatalogPath),
("bitchatShareExtension", shareKeys, mainKeys,
Self.shareExtensionCatalogPath, Self.mainCatalogPath)
] {
let references = try Self.localizedKeyReferences(in: sourceRoot)
let missing = references
.filter { !ownKeys.contains($0.key) }
.map { reference -> String in
let note = otherKeys.contains(reference.key)
? " (present in \(otherCatalog), which this target does not bundle)"
: " (present in no catalog)"
return "\(reference.location) \(reference.key)\(note)"
}
}
}
#expect(
missing.isEmpty,
"keys referenced in code but absent from every catalog — these ship English to all non-source locales: \(missing.sorted().joined(separator: ", "))"
#expect(
missing.isEmpty,
"""
keys referenced under \(sourceRoot)/ but absent from \(ownCatalog) — \
these ship English to all non-source locales:
\(missing.sorted().joined(separator: "\n"))
"""
)
guard sourceRoot == "bitchat" else { continue }
let missingInBoth = references
.filter { sharedSources.contains($0.location.prefix(while: { $0 != ":" }).description) }
.filter { !shareKeys.contains($0.key) }
.map { "\($0.location) \($0.key)" }
#expect(
missingInBoth.isEmpty,
"""
keys referenced from files the share extension also compiles, but absent \
from \(Self.shareExtensionCatalogPath) — these ship English inside the \
extension:
\(missingInBoth.sorted().joined(separator: "\n"))
"""
)
}
}
/// The files under `bitchat/` that the share-extension target compiles, read
/// from the project's membership exceptions so this cannot drift when the
/// set changes.
private static func shareExtensionMembershipExceptions() throws -> Set<String> {
let project = try String(
contentsOf: repoRoot.appendingPathComponent("bitchat.xcodeproj/project.pbxproj"),
encoding: .utf8
)
let marker = #"Exceptions for "bitchat" folder in "bitchatShareExtension" target"#
guard let markerRange = project.range(of: marker),
let listStart = project.range(
of: "membershipExceptions = (", range: markerRange.upperBound..<project.endIndex
),
let listEnd = project.range(
of: ");", range: listStart.upperBound..<project.endIndex
)
else { return [] }
return Set(
project[listStart.upperBound..<listEnd.lowerBound]
.split(separator: ",")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { $0.hasSuffix(".swift") }
.map { "bitchat/\($0)" }
)
}
private static let mainCatalogPath = "bitchat/Localizable.xcstrings"
private static let shareExtensionCatalogPath =
"bitchatShareExtension/Localization/Localizable.xcstrings"
/// A literal `String(localized:)` key, with where it was written.
private struct KeyReference {
let key: String
/// `path/to/File.swift:line`, relative to the repository root.
let location: String
}
/// Every literal `String(localized:)` key under `sourceRoot`, with its
/// repo-relative file and line so a failure points at the call site
/// instead of just naming a file.
private static func localizedKeyReferences(in sourceRoot: String) throws -> [KeyReference] {
let pattern = try NSRegularExpression(pattern: #"String\(\s*localized:\s*"([^"\\]+)""#)
let rootURL = repoRoot.appendingPathComponent(sourceRoot)
let enumerator = try #require(FileManager.default.enumerator(
at: rootURL,
includingPropertiesForKeys: nil
))
var references: [KeyReference] = []
for case let fileURL as URL in enumerator where fileURL.pathExtension == "swift" {
let source = try String(contentsOf: fileURL, encoding: .utf8)
let relativePath = fileURL.path.replacingOccurrences(
of: repoRoot.path + "/", with: ""
)
let range = NSRange(source.startIndex..., in: source)
pattern.enumerateMatches(in: source, range: range) { match, _, _ in
guard let match,
let keyRange = Range(match.range(at: 1), in: source),
let matchStart = Range(match.range, in: source)?.lowerBound
else { return }
let line = source[source.startIndex..<matchStart].count(where: { $0 == "\n" }) + 1
references.append(KeyReference(
key: String(source[keyRange]),
location: "\(relativePath):\(line)"
))
}
}
return references
}
}

View File

@ -236,6 +236,65 @@ struct LocationNotesManagerTests {
#expect(manager.notes.first?.expiresAt == Date(timeIntervalSince1970: TimeInterval(Int(now.timeIntervalSince1970) + 3600)))
}
/// created_at is author-chosen: a note dated 2100 used to sort above
/// every real note forever and survive the newest-first memory cap.
@Test
func ingestClampsFutureDatedNotesToTheBoardSkew() throws {
var storedHandler: ((NostrEvent) -> Void)?
let start = Date(timeIntervalSince1970: 1_700_000_000)
var currentNow = start
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, _ in
storedHandler = handler
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { currentNow }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
let identity = try NostrIdentity.generate()
let skew = TimeInterval(BoardStore.Limits.clockSkewMs) / 1000
// Within the board's skew allowance the author's timestamp is kept,
// so a bridged copy of a board post still dedupes against the post.
let slightlyAhead = start.addingTimeInterval(30 * 60)
let bridged = NostrEvent(
pubkey: identity.publicKeyHex,
createdAt: slightlyAhead,
kind: .textNote,
tags: [["g", "u4pruydq"]],
content: "bridged"
)
storedHandler?(try bridged.sign(with: identity.schnorrSigningKey()))
#expect(manager.notes.first(where: { $0.content == "bridged" })?.createdAt == slightlyAhead)
// Far-future timestamps are clamped to the edge of that allowance.
let futureDated = NostrEvent(
pubkey: identity.publicKeyHex,
createdAt: Date(timeIntervalSince1970: 4_102_444_800), // 2100-01-01
kind: .textNote,
tags: [["g", "u4pruydq"]],
content: "pinned"
)
storedHandler?(try futureDated.sign(with: identity.schnorrSigningKey()))
#expect(manager.notes.first(where: { $0.content == "pinned" })?.createdAt == start.addingTimeInterval(skew))
// Once local time passes that edge, newer notes sort above it.
currentNow = start.addingTimeInterval(skew + 120)
let later = NostrEvent(
pubkey: identity.publicKeyHex,
createdAt: start.addingTimeInterval(skew + 60),
kind: .textNote,
tags: [["g", "u4pruydq"]],
content: "later"
)
storedHandler?(try later.sign(with: identity.schnorrSigningKey()))
#expect(manager.notes.map(\.content) == ["later", "pinned", "bridged"])
}
@Test
func postDrop_sendsExpiringNoteToGeoRelays() throws {
var sentEvents: [NostrEvent] = []

View File

@ -893,6 +893,44 @@ struct NoiseCoverageTests {
}
}
@Test("A continuously active session still schedules a rekey before it hard-expires")
func continuouslyActiveSessionStillNeedsRenegotiationBeforeExpiry() throws {
// A session with steady traffic never goes idle, so lastActivityTime
// stays fresh right up to the moment sessionStartTime crosses the
// hard sessionTimeout cutoff above and encrypt/decrypt start throwing
// sessionExpired on every call. needsRenegotiation() has to notice
// the session is old on its own -- it can't rely on the idle check,
// because there is no idle time to find.
let session = SecureNoiseSession(
peerID: alicePeerID,
role: .initiator,
keychain: keychain,
localStaticKey: aliceStaticKey
)
let responder = SecureNoiseSession(
peerID: bobPeerID,
role: .responder,
keychain: keychain,
localStaticKey: bobStaticKey
)
try establishSessions(initiator: session, responder: responder)
// Just under the hard cutoff, but past the 90% rekey threshold.
session.setSessionStartTimeForTesting(
Date().addingTimeInterval(-(NoiseSecurityConstants.sessionTimeout * 0.95))
)
session.setLastActivityTimeForTesting(Date())
session.setMessageCountForTesting(0)
#expect(session.needsRenegotiation())
// The session is still within its hard cutoff, so it must keep
// working right up until a rekey actually replaces it -- the fix is
// to schedule the rekey earlier, not to expire the session sooner.
let ciphertext = try session.encrypt(Data("still working".utf8))
#expect(try responder.decrypt(ciphertext) == Data("still working".utf8))
}
@Test("Rate limiter handles global message caps and per-peer resets")
func rateLimiterGlobalMessageCapAndReset() async throws {
let globalLimiter = NoiseRateLimiter()

View File

@ -341,10 +341,9 @@ struct NostrProtocolTests {
// Build a DELIVERED ack embedded payload (geohash-style, no recipient peer ID)
let messageID = "TEST-MSG-DELIVERED-1"
let senderPeerID = PeerID(str: "0123456789abcdef") // 8-byte hex peer ID
let embedded = try #require(
NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .delivered, messageID: messageID, senderPeerID: senderPeerID),
NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .delivered, messageID: messageID),
"Failed to embed delivered ack"
)
@ -391,9 +390,8 @@ struct NostrProtocolTests {
let recipient = try NostrIdentity.generate()
let messageID = "TEST-MSG-READ-1"
let senderPeerID = PeerID(str: "fedcba9876543210") // 8-byte hex peer ID
let embedded = try #require(
NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .readReceipt, messageID: messageID, senderPeerID: senderPeerID),
NostrEmbeddedBitChat.encodeAckForNostrNoRecipient(type: .readReceipt, messageID: messageID),
"Failed to embed read ack"
)

View File

@ -0,0 +1,257 @@
//
// PacketPayloadCapInteropTests.swift
// bitchatTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import BitFoundation
import Foundation
import Testing
@testable import bitchat
/// Receive-side interop for the per-type payload caps in `BinaryProtocol`:
/// the largest payload each shipping encoder produces (iOS, and Android for
/// the types it sends) still decodes, while the same type inflated from ~1 KB
/// on air to ~1 MB, or reassembled uncompressed from a fragment stream, does
/// not.
struct PacketPayloadCapInteropTests {
private let senderID = Data(repeating: 0x5A, count: 8)
private let signature = Data(repeating: 0xAB, count: 64)
@Test func longestPublicMessagesStillDecode() throws {
// Both platforms send public messages as v1 frames (iOS
// BLEService.sendMessage, Android MeshCore.sendMessage), so these
// composer-sized messages are as large as the type legitimately gets.
let cjk = String(repeating: "漢字仮名交じり文", count: 2_000)
let ascii = String(repeating: "x", count: InputValidator.Limits.maxMessageLength)
#expect(cjk.count == 16_000)
for content in [cjk, ascii] {
let packet = makePacket(type: .message, payload: Data(content.utf8))
#expect(try roundTripIsCompressed(packet))
}
#expect(BinaryProtocol.decode(try inflatedFrame(type: .message)) == nil)
}
@Test func androidAndIOSSizedFragmentsStillDecode() throws {
// Every byte value once, then zeros: the inner packet stays
// uncompressed (its bytes are 100% unique) while the zero-filled
// chunks compress, so the fragment frames take the inflate path.
var inner = Data((0...255).map { UInt8($0) })
inner.append(Data(count: 4_000))
let packet = makePacket(type: .fileTransfer, payload: inner, version: 2)
// 469 B: Android's MAX_FRAGMENT_SIZE and the iOS default chunk.
// 482 B: the largest iOS chunk, from a 524-byte BLE link limit.
// 500 B: the chunk both platforms used before mid-2025.
let chunkSizes = [
TransportConfig.bleDefaultFragmentSize,
BLEOutboundPacketPolicy.fragmentChunkSize(forLinkLimit: 524),
500
]
for chunkSize in chunkSizes {
let request = BLEOutboundFragmentTransferRequest(
packet: packet,
pad: false,
maxChunk: chunkSize,
directedPeer: nil,
transferId: nil
)
let plan = try #require(BLEOutboundFragmentPlanner.makePlan(
for: request,
defaultChunkSize: TransportConfig.bleDefaultFragmentSize,
bleMaxMTU: 512
))
#expect(plan.fragmentPackets.map(\.payload.count).max() == 13 + chunkSize)
var compressedFragments = 0
for fragment in plan.fragmentPackets {
if try roundTripIsCompressed(fragment) {
compressedFragments += 1
}
}
#expect(compressedFragments > 0)
}
// Fragments are link-scale: 2 KiB is four times the largest any
// sender produces, so a few dozen bytes on air cannot stand for it.
let oversized = makePacket(type: .fragment, payload: Data(repeating: 0x41, count: 2 * 1_024))
let oversizedFrame = try #require(oversized.toBinaryData(padding: false))
#expect(oversizedFrame[BinaryProtocol.Offsets.flags] & BinaryProtocol.Flags.isCompressed != 0)
#expect(BinaryProtocol.decode(oversizedFrame) == nil)
#expect(BinaryProtocol.decode(try inflatedFrame(type: .fragment)) == nil)
}
@Test func largestControlAndEnvelopePayloadsStillDecode() throws {
let cases: [(type: MessageType, payload: Data, compresses: Bool)] = [
(.announce, try maxAnnounce(), true),
(.boardPost, maxBoardPost(), true),
(.nostrCarrier, try maxNostrCarrier(), true),
(.requestSync, maxRequestSync(), false),
(.courierEnvelope, try maxCourierEnvelope(), false),
(.groupMessage, try maxGroupMessage(), false),
(.prekeyBundle, try maxPrekeyBundle(), false),
(.voiceFrame, try maxVoiceFrame(), false)
// announceV2's largest payload is checked in BitFoundation's
// PacketPayloadLimitsTests: nothing in the app emits it yet, and a
// reference here would make it look used to the dead-code scan.
]
for testCase in cases {
let packet = makePacket(type: testCase.type, payload: testCase.payload)
let compressed = try roundTripIsCompressed(packet)
#expect(compressed || !testCase.compresses, "\(testCase.type.description) should take the inflate path")
#expect(
BinaryProtocol.decode(try inflatedFrame(type: testCase.type)) == nil,
"\(testCase.type.description) inflated to ~1 MB must be rejected"
)
}
}
@Test func largeFileTransfersStillDecode() throws {
// A 1 MiB image whose bytes compress well: the largest legitimate
// inflation a broadcast file can ask for.
var content = Data([0xFF, 0xD8, 0xFF, 0xE0])
content.append(Data(count: FileTransferLimits.maxPayloadBytes - content.count))
let file = BitchatFilePacket(fileName: "photo.jpg", fileSize: nil, mimeType: "image/jpeg", content: content)
let payload = try #require(file.encode())
let packet = makePacket(type: .fileTransfer, payload: payload, version: 2)
#expect(try roundTripIsCompressed(packet))
// The same bytes under a non-media type are what the caps stop.
let asGroupMessage = makePacket(type: .groupMessage, payload: payload, version: 2)
#expect(BinaryProtocol.decode(try #require(asGroupMessage.toBinaryData())) == nil)
}
// MARK: - Legitimate maxima, built with the real encoders
private func maxAnnounce() throws -> Data {
try #require(AnnouncementPacket(
nickname: String(repeating: "n", count: 255),
noisePublicKey: Data(repeating: 0x21, count: 32),
signingPublicKey: Data(repeating: 0x22, count: 32),
directNeighbors: (0..<10).map { Data(repeating: UInt8($0), count: 8) },
capabilities: PeerCapabilities(rawValue: .max),
bridgeGeohash: "9q8yyk8yuv12"
).encode())
}
private func maxBoardPost() -> Data {
BoardWire.post(BoardPostPacket(
postID: Data(repeating: 0x31, count: BoardWireConstants.postIDLength),
geohash: "9q8yyk8yuv12",
content: String(repeating: "x", count: BoardWireConstants.contentMaxBytes),
authorSigningKey: Data(repeating: 0x32, count: BoardWireConstants.signingKeyLength),
authorNickname: String(repeating: "n", count: BoardWireConstants.nicknameMaxBytes),
createdAt: 1_740_000_000_000,
expiresAt: 1_740_000_000_000 + BoardWireConstants.maxLifetimeMs,
flags: BoardPostPacket.urgentFlag,
signature: signature
)).encode()
}
private func maxNostrCarrier() throws -> Data {
let prefix = Data(#"{"content":""#.utf8)
let suffix = Data(#""}"#.utf8)
var json = prefix
json.append(Data(repeating: 0x61, count: NostrCarrierPacket.maxEventJSONBytes - prefix.count - suffix.count))
json.append(suffix)
let carrier = try #require(NostrCarrierPacket(direction: .fromGateway, geohash: "9q8yyk8yuv12", eventJSON: json))
return try #require(carrier.encode())
}
private func maxRequestSync() -> Data {
let fragmentIDs = (0..<RequestSyncPacket.maxFragmentIdFilterCount).map {
Data(repeating: UInt8($0), count: 8)
}
return RequestSyncPacket(
p: 7,
m: 1 << 20,
data: Data((0..<1_024).map { UInt8(truncatingIfNeeded: $0 &* 37) }),
types: [.publicMessages, .fragment, .fileTransfer, .groupMessage, .prekeyBundle, .board],
sinceTimestamp: 1_740_000_000_000,
fragmentIdFilter: RequestSyncPacket.encodeFragmentIdFilter(fragmentIDs)
).encode()
}
private func maxCourierEnvelope() throws -> Data {
try #require(CourierEnvelope(
recipientTag: Data(repeating: 0x41, count: CourierEnvelope.tagLength),
expiry: 1_740_000_000_000,
ciphertext: randomBytes(CourierEnvelope.maxCiphertextBytes),
copies: CourierEnvelope.maxCopies,
prekeyID: 7
).encode())
}
private func maxGroupMessage() throws -> Data {
try GroupCrypto.sealMessage(
content: String(repeating: "g", count: InputValidator.Limits.maxMessageLength),
messageID: UUID().uuidString,
senderNickname: String(repeating: "n", count: 50),
senderSigningKey: Data(repeating: 0x51, count: 32),
timestampMs: 1_740_000_000_000,
groupID: Data(repeating: 0x52, count: BitchatGroup.groupIDLength),
epoch: 1,
key: Data(repeating: 0x53, count: BitchatGroup.keyLength),
sign: { [signature] _ in signature }
)
}
private func maxPrekeyBundle() throws -> Data {
try #require(PrekeyBundle(
noiseStaticPublicKey: Data(repeating: 0x61, count: PrekeyBundle.keyLength),
prekeys: (0..<PrekeyBundle.maxPrekeys).map {
PrekeyBundle.Prekey(id: UInt32($0), publicKey: randomBytes(PrekeyBundle.keyLength))
},
generatedAt: 1_740_000_000_000,
signature: signature
).encode())
}
private func maxVoiceFrame() throws -> Data {
// 11-byte header + 2-byte length + frame = the 210-byte burst budget.
let frame = randomBytes(TransportConfig.pttMaxBurstContentBytes - 13)
let burst = try #require(VoiceBurstPacket(burstID: Data(repeating: 0x71, count: 8), seq: 1, kind: .frames([frame])))
return burst.encode()
}
// MARK: - Helpers
private func makePacket(type: MessageType, payload: Data, version: UInt8 = 1) -> BitchatPacket {
BitchatPacket(
type: type.rawValue,
senderID: senderID,
recipientID: nil,
timestamp: 1_740_000_000_000,
payload: payload,
signature: signature,
ttl: TransportConfig.messageTTLDefault,
version: version
)
}
/// Encodes as on the wire (padded), decodes, and checks the payload
/// survives; returns whether the frame went out compressed.
private func roundTripIsCompressed(_ packet: BitchatPacket) throws -> Bool {
let frame = try #require(packet.toBinaryData())
let decoded = try #require(BinaryProtocol.decode(frame), "type \(packet.type) failed to decode")
#expect(decoded.payload == packet.payload)
return frame[BinaryProtocol.Offsets.flags] & BinaryProtocol.Flags.isCompressed != 0
}
/// ~1 MB of one byte in a v2 frame: about 1 KB on air, and accepted by
/// the old frame-wide cap for every type.
private func inflatedFrame(type: MessageType) throws -> Data {
let packet = makePacket(type: type, payload: Data(repeating: 0x41, count: 1_024 * 1_024), version: 2)
let frame = try #require(packet.toBinaryData(padding: false))
#expect(frame.count < 4_096)
return frame
}
private func randomBytes(_ count: Int) -> Data {
Data((0..<count).map { _ in UInt8.random(in: 0...255) })
}
}

View File

@ -186,8 +186,8 @@ struct BLEAnnounceHandlerTests {
#expect(recorder.upsertCalls.isEmpty)
#expect(recorder.topologyUpdates.isEmpty)
#expect(recorder.afterglowDelays.isEmpty)
// Original behavior: list refresh, identity persistence, sync tracking
// and announce-back still occur for unverified announces.
// Original behavior: list refresh and announce-back still occur for
// unverified announces.
#expect(recorder.uiEventDeliveries.count == 1)
#expect(recorder.uiEventDeliveries.first?.notifyPeerConnected == false)
#expect(recorder.uiEventDeliveries.first?.scheduleInitialSync == false)
@ -195,7 +195,9 @@ struct BLEAnnounceHandlerTests {
// persisting would let an attacker who replays a victim's noisePublicKey
// overwrite the victim's stored signing key/nickname (identity poisoning).
#expect(recorder.persistedIdentities.isEmpty)
#expect(recorder.trackedPackets.count == 1)
// Nor gossip tracking: an unsigned announce is free to mint, so
// tracking it let junk identities fill the sync store and filter.
#expect(recorder.trackedPackets.isEmpty)
#expect(recorder.announceBacks == 1)
}
@ -222,6 +224,7 @@ struct BLEAnnounceHandlerTests {
#expect(recorder.upsertCalls.isEmpty)
#expect(recorder.uiEventDeliveries.count == 1)
#expect(recorder.uiEventDeliveries.first?.notifyPeerConnected == false)
#expect(recorder.trackedPackets.isEmpty)
}
@Test
@ -542,6 +545,8 @@ struct BLEAnnounceHandlerTests {
#expect(recorder.topologyUpdates.isEmpty)
#expect(recorder.uiEventDeliveries.count == 1)
#expect(recorder.uiEventDeliveries.first?.notifyPeerConnected == false)
// The impersonation announce is not carried for sync either.
#expect(recorder.trackedPackets.isEmpty)
}
@Test

View File

@ -80,13 +80,102 @@ struct BLEDirectedRelaySpoolTests {
#expect(spool.isEmpty)
}
// MARK: - Bounds
@Test
func enqueueEvictsOldestPastTheByteBudget() {
let recipient = PeerID(str: "1122334455667788")
let now = Date()
var spool = BLEDirectedRelaySpool(capacity: 10, byteBudget: 250)
for index in 0..<3 {
spool.enqueue(
packet: makePacket(payload: [UInt8](repeating: UInt8(index), count: 100)),
recipient: recipient,
messageID: "message-\(index)",
enqueuedAt: now.addingTimeInterval(Double(index))
)
}
// 300 bytes against a 250-byte budget: only the oldest goes, though
// the count cap is nowhere near. Survivors drain oldest-first.
#expect(spool.count == 2)
let drained = spool.drainUnexpired(now: now, window: 60)
#expect(drained.map { $0.packet.payload.first } == [1, 2])
}
@Test
func enqueueEvictsOldestPastTheCountCap() {
let now = Date()
var spool = BLEDirectedRelaySpool(capacity: 2, byteBudget: 1024)
for index in 0..<3 {
spool.enqueue(
packet: makePacket(payload: [UInt8(index)]),
recipient: PeerID(str: "112233445566778\(index)"),
messageID: "message-\(index)",
enqueuedAt: now
)
}
#expect(spool.count == 2)
let drained = spool.drainUnexpired(now: now, window: 60)
#expect(drained.map { $0.packet.payload.first } == [1, 2])
}
@Test
func packetLargerThanTheWholeBudgetIsRefusedWithoutEvicting() {
let recipient = PeerID(str: "1122334455667788")
let now = Date()
var spool = BLEDirectedRelaySpool(capacity: 10, byteBudget: 250)
spool.enqueue(packet: makePacket(payload: [0x01]), recipient: recipient, messageID: "small", enqueuedAt: now)
let oversized = spool.enqueue(
packet: makePacket(payload: [UInt8](repeating: 0x02, count: 251)),
recipient: recipient,
messageID: "oversized",
enqueuedAt: now
)
#expect(!oversized)
#expect(spool.drainUnexpired(now: now, window: 60).map { $0.packet.payload } == [Data([0x01])])
}
/// A relay with no onward link used to hold every spooled packet for the
/// whole window with no count or byte limit, and a noiseEncrypted frame
/// may decode to the framed-file cap: each ~1 KB on air pinned ~1.1 MB.
@Test
func defaultBoundsHoldAFramedFilePacketButNotAFloodOfThem() {
let recipient = PeerID(str: "1122334455667788")
let now = Date()
var spool = BLEDirectedRelaySpool()
let inflated = Data(repeating: 0x41, count: FileTransferLimits.maxFramedFileBytes)
for index in 0..<20 {
let accepted = spool.enqueue(
packet: makePacket(payload: inflated),
recipient: recipient,
messageID: "inflated-\(index)",
enqueuedAt: now
)
#expect(accepted)
}
#expect(spool.count == TransportConfig.bleDirectedSpoolByteBudget / FileTransferLimits.maxFramedFileBytes)
#expect(spool.count >= 1)
}
private func makePacket(payload: [UInt8]) -> BitchatPacket {
makePacket(payload: Data(payload))
}
private func makePacket(payload: Data) -> BitchatPacket {
BitchatPacket(
type: MessageType.noiseEncrypted.rawValue,
senderID: Data(hexString: "8877665544332211") ?? Data(),
recipientID: Data(hexString: "1122334455667788"),
timestamp: 1234,
payload: Data(payload),
payload: payload,
signature: nil,
ttl: TransportConfig.messageTTLDefault
)

View File

@ -953,7 +953,7 @@ struct BLEFileTransferHandlerTests {
}
@Test
func malformedPayloadIsTrackedForSyncButDropped() {
func malformedPayloadIsRelayedButNeverTrackedForSync() {
let recorder = Recorder()
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true, signingPublicKey: sampleSigningKey)]
recorder.signatureVerifies = true
@ -971,8 +971,9 @@ struct BLEFileTransferHandlerTests {
// Local decode failures are not proof of forgery; the packet stays relayable.
#expect(handler.handle(packet, from: remotePeerID))
// Sync tracking happens before payload validation, matching the original order.
#expect(recorder.trackedPackets.count == 1)
// But the gossip store re-serves whatever it tracks, so validation
// runs first and an undecodable payload never enters it.
#expect(recorder.trackedPackets.isEmpty)
#expect(recorder.quotaReservations.isEmpty)
#expect(recorder.saveCalls.isEmpty)
#expect(recorder.deliveredMessages.isEmpty)
@ -988,7 +989,39 @@ struct BLEFileTransferHandlerTests {
#expect(handler.handle(packet, from: remotePeerID))
#expect(recorder.trackedPackets.count == 1)
#expect(recorder.trackedPackets.isEmpty)
#expect(recorder.quotaReservations.isEmpty)
#expect(recorder.saveCalls.isEmpty)
#expect(recorder.deliveredMessages.isEmpty)
}
@Test
func oversizedBroadcastFileIsRelayedButNeverTrackedForSync() {
let recorder = Recorder()
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true, signingPublicKey: sampleSigningKey)]
recorder.signatureVerifies = true
let handler = makeHandler(recorder: recorder)
// A CONTENT TLV one byte over the file cap: it fits the framed-file
// ceiling at decode, so only payload validation can stop it.
let oversizedCount = FileTransferLimits.maxPayloadBytes + 1
var length = UInt32(oversizedCount).bigEndian
var payload = Data([0x04])
withUnsafeBytes(of: &length) { payload.append(contentsOf: $0) }
payload.append(Data(repeating: 0x41, count: oversizedCount))
let packet = BitchatPacket(
type: MessageType.fileTransfer.rawValue,
senderID: Data(hexString: remotePeerID.id) ?? Data(),
recipientID: nil,
timestamp: 900_000,
payload: payload,
signature: Data(repeating: 0x5A, count: 64),
ttl: TransportConfig.messageTTLDefault,
version: 2
)
#expect(handler.handle(packet, from: remotePeerID))
#expect(recorder.trackedPackets.isEmpty)
#expect(recorder.quotaReservations.isEmpty)
#expect(recorder.saveCalls.isEmpty)
#expect(recorder.deliveredMessages.isEmpty)

View File

@ -84,12 +84,13 @@ struct BLEFragmentAssemblyBufferTests {
func appendOversizedAssemblyDropsPartialState() throws {
var buffer = BLEFragmentAssemblyBuffer()
let fragmentID = Data(repeating: 0x05, count: 8)
let limit = PacketPayloadLimits.maxFrameBytes(forType: MessageType.message.rawValue)
let first = try #require(BLEFragmentHeader(packet: makeFragmentPacket(
fragmentID: fragmentID,
index: 0,
total: 2,
originalType: MessageType.message.rawValue,
fragmentData: Data(repeating: 0x01, count: FileTransferLimits.maxPayloadBytes)
fragmentData: Data(repeating: 0x01, count: limit)
)))
let oversized = try #require(BLEFragmentHeader(packet: makeFragmentPacket(
fragmentID: fragmentID,
@ -102,9 +103,9 @@ struct BLEFragmentAssemblyBufferTests {
_ = buffer.append(first, maxInFlightAssemblies: 8)
let result = buffer.append(oversized, maxInFlightAssemblies: 8)
if case let .oversized(_, projectedSize, limit, started) = result {
#expect(projectedSize == FileTransferLimits.maxPayloadBytes + 1)
#expect(limit == FileTransferLimits.maxPayloadBytes)
if case let .oversized(_, projectedSize, reportedLimit, started) = result {
#expect(projectedSize == limit + 1)
#expect(reportedLimit == limit)
#expect(!started)
} else {
Issue.record("Expected oversized fragment assembly to be evicted")
@ -117,6 +118,77 @@ struct BLEFragmentAssemblyBufferTests {
}
}
@Test
func redeliveredIndexNearTheLimitDoesNotEvictTheAssembly() throws {
// Fragments bypass dedup and sync re-serves held indexes, so a
// duplicate must replace its index's bytes, not count them twice.
var buffer = BLEFragmentAssemblyBuffer()
let fragmentID = Data(repeating: 0x06, count: 8)
let limit = PacketPayloadLimits.maxFrameBytes(forType: MessageType.message.rawValue)
func fragment(_ index: Int, bytes: Int) throws -> BLEFragmentHeader {
try #require(BLEFragmentHeader(packet: makeFragmentPacket(
fragmentID: fragmentID,
index: index,
total: 3,
originalType: MessageType.message.rawValue,
fragmentData: Data(repeating: UInt8(index + 1), count: bytes)
)))
}
let large = try fragment(0, bytes: limit - 2)
_ = buffer.append(large, maxInFlightAssemblies: 8)
_ = buffer.append(try fragment(1, bytes: 1), maxInFlightAssemblies: 8)
guard case .stored = buffer.append(large, maxInFlightAssemblies: 8) else {
Issue.record("Expected a re-delivered index to keep the assembly")
return
}
if case let .complete(_, data, _) = buffer.append(try fragment(2, bytes: 1), maxInFlightAssemblies: 8) {
#expect(data.count == limit)
} else {
Issue.record("Expected the assembly to complete at its limit")
}
}
@Test
func assemblyIsHeldToTheFrameItsClaimedTypeCanFill() throws {
// Not a flat 1 MiB for every type: an assembly claiming a
// link-scale or message-scale type is cut off just past the largest
// frame that type could still decode from.
let claims: [(type: MessageType, id: UInt8)] = [(.fragment, 0x30), (.announce, 0x40), (.message, 0x50)]
for claim in claims {
var buffer = BLEFragmentAssemblyBuffer()
let limit = PacketPayloadLimits.maxFrameBytes(forType: claim.type.rawValue)
#expect(limit < FileTransferLimits.maxPayloadBytes / 4)
let atLimit = try #require(BLEFragmentHeader(packet: makeFragmentPacket(
fragmentID: Data(repeating: claim.id, count: 8),
index: 0,
total: 1,
originalType: claim.type.rawValue,
fragmentData: Data(repeating: 0x01, count: limit)
)))
if case let .complete(_, data, _) = buffer.append(atLimit, maxInFlightAssemblies: 8) {
#expect(data.count == limit)
} else {
Issue.record("Expected a \(claim.type.description) assembly at its frame ceiling to complete")
}
let pastLimit = try #require(BLEFragmentHeader(packet: makeFragmentPacket(
fragmentID: Data(repeating: claim.id + 1, count: 8),
index: 0,
total: 1,
originalType: claim.type.rawValue,
fragmentData: Data(repeating: 0x01, count: limit + 1)
)))
if case let .oversized(_, _, reportedLimit, _) = buffer.append(pastLimit, maxInFlightAssemblies: 8) {
#expect(reportedLimit == limit)
} else {
Issue.record("Expected a \(claim.type.description) assembly past its frame ceiling to be evicted")
}
}
}
@Test
func encryptedPrivateFileAssemblyGetsFramedFileHeadroom() throws {
var buffer = BLEFragmentAssemblyBuffer()

View File

@ -1,4 +1,4 @@
import BitFoundation
@testable import BitFoundation
import Foundation
import Testing
@testable import bitchat
@ -172,6 +172,77 @@ struct BLEFragmentHandlerTests {
#expect(recorder.reinjectedPackets.isEmpty)
}
@Test
func reassembledPacketPastItsTypeCapNeverReachesThePipeline() throws {
// A large uncompressed inner frame streamed as compressed fragments
// (each zero-filled chunk is a few dozen bytes on air) through the
// real fragmenter and assembly buffer. One byte past the type's cap still fits the
// assembly, whose ceiling adds framing, so decode must stop it.
for type in [MessageType.message, .announce] {
let cap = PacketPayloadLimits.maxPayloadBytes(forType: type.rawValue)
var buffer = BLEFragmentAssemblyBuffer()
let recorder = Recorder()
recorder.appendResult = { header in
buffer.append(header, maxInFlightAssemblies: 8)
}
let handler = makeHandler(recorder: recorder)
for payloadSize in [cap, cap + 1] {
let inner = BitchatPacket(
type: type.rawValue,
senderID: Data(hexString: "99AABBCCDDEEFF00") ?? Data(),
recipientID: nil,
timestamp: 900_000,
payload: uncompressiblePrefixThenZeros(count: payloadSize),
signature: nil,
ttl: 5,
version: payloadSize > Int(UInt16.max) ? 2 : 1
)
for fragment in try fragmentsAsReceived(inner) {
handler.handle(fragment, from: remotePeerID)
}
}
#expect(
recorder.reinjectedPackets.map(\.packet.payload.count) == [cap],
"\(type.description) past its cap must not be reassembled into the pipeline"
)
}
}
@Test
func reassembledPacketOfAnotherTypeThanItsFragmentsClaimIsDropped() throws {
let innerPacket = BitchatPacket(
type: MessageType.message.rawValue,
senderID: Data(hexString: "99AABBCCDDEEFF00") ?? Data(),
recipientID: nil,
timestamp: 900_000,
payload: Data("hello".utf8),
signature: nil,
ttl: 5
)
let reassembled = try #require(innerPacket.toBinaryData())
let recorder = Recorder()
recorder.appendResult = { header in
.complete(header: header, reassembledData: reassembled, started: false)
}
let handler = makeHandler(recorder: recorder)
// A file-transfer claim buys a framed-file-sized assembly; the
// packet it produced must be a file transfer.
let packet = makeFragmentPacket(
sender: remotePeerID,
index: 1,
total: 2,
originalType: MessageType.fileTransfer.rawValue
)
handler.handle(packet, from: remotePeerID)
#expect(recorder.ingressChecks.isEmpty)
#expect(recorder.reinjectedPackets.isEmpty)
}
@Test
func undecodableReassembledDataIsDropped() {
let recorder = Recorder()
@ -200,6 +271,43 @@ struct BLEFragmentHandlerTests {
#expect(recorder.reinjectedPackets.isEmpty)
}
/// Every byte value once, then zeros: the encoder leaves the inner
/// payload uncompressed (100% byte diversity), while the zero chunks
/// compress inside their fragments.
private func uncompressiblePrefixThenZeros(count: Int) -> Data {
var payload = Data((0...255).map { UInt8($0) })
payload.append(Data(count: count - payload.count))
return payload
}
/// Fragments `packet` with the real planner, then puts each fragment
/// through the wire codec as a receiver would.
private func fragmentsAsReceived(_ packet: BitchatPacket) throws -> [BitchatPacket] {
let request = BLEOutboundFragmentTransferRequest(
packet: packet,
pad: false,
maxChunk: nil,
directedPeer: nil,
transferId: nil
)
let plan = try #require(BLEOutboundFragmentPlanner.makePlan(
for: request,
defaultChunkSize: TransportConfig.bleDefaultFragmentSize,
bleMaxMTU: 512
))
var compressedFragments = 0
let received = try plan.fragmentPackets.map { fragment in
let frame = try #require(fragment.toBinaryData())
if frame[BinaryProtocol.Offsets.flags] & BinaryProtocol.Flags.isCompressed != 0 {
compressedFragments += 1
}
return try #require(BinaryProtocol.decode(frame))
}
// All but the first (the diverse bytes) and a short tail.
#expect(compressedFragments >= received.count - 2)
return received
}
private func makeFragmentPacket(
sender: PeerID,
index: UInt16,

View File

@ -119,7 +119,7 @@ struct BLEIngressPacketGuardTests {
)))
}
@Test("valid RSR packets use bound peer validation and bypass timestamp skew")
@Test("valid RSR packets use bound peer validation and bypass the past timestamp bound")
func validRSRUsesBoundPeerAndBypassesTimestamp() throws {
let local = PeerID(str: "0011223344556677")
let bound = PeerID(str: "1122334455667788")
@ -141,6 +141,61 @@ struct BLEIngressPacketGuardTests {
#expect(context.validationPeerID == bound)
}
@Test("valid RSR packets dated beyond the skew window are rejected")
func futureDatedRSRIsRejected() throws {
// Sync replies may replay old packets but never future-dated ones:
// UInt64.max used to reach the UI (and trap) or pin the gossip store.
let local = PeerID(str: "0011223344556677")
let bound = PeerID(str: "1122334455667788")
let sender = PeerID(str: "8899aabbccddeeff")
let nowMs: UInt64 = 1_000_000
let skewMs: UInt64 = 120_000
func evaluateRSR(timestamp: UInt64) -> Result<BLEIngressPacketContext, BLEIngressPacketGuard.Rejection> {
var packet = makePacket(sender: sender, timestamp: timestamp)
packet.isRSR = true
return BLEIngressPacketGuard.evaluate(
packet: packet,
claimedSenderID: sender,
boundPeerID: bound,
localPeerID: local,
directAnnounceTTL: 7,
nowMs: nowMs,
maxTimestampSkewMs: skewMs,
isValidSyncResponse: { $0 == bound }
)
}
#expect(evaluateRSR(timestamp: .max) == .failure(.timestampSkew(
peerID: bound,
skewMs: .max - nowMs,
maxSkewMs: skewMs
)))
#expect(evaluateRSR(timestamp: nowMs + skewMs + 1) == .failure(.timestampSkew(
peerID: bound,
skewMs: skewMs + 1,
maxSkewMs: skewMs
)))
// The edge of the window is still tolerated clock skew.
let edgeContext = try #require(success(evaluateRSR(timestamp: nowMs + skewMs)))
#expect(edgeContext.validationPeerID == bound)
// Reassembled inner packets are checked through validatePayload alone.
var innerPacket = makePacket(sender: sender, timestamp: .max)
innerPacket.isRSR = true
let innerResult = BLEIngressPacketGuard.validatePayload(
innerPacket,
from: sender,
nowMs: nowMs,
maxTimestampSkewMs: skewMs,
isValidSyncResponse: { _ in true }
)
guard case .failure(.timestampSkew) = innerResult else {
Issue.record("Expected a future-dated reassembled RSR packet to be rejected, got \(innerResult)")
return
}
}
@Test("invalid RSR packets are rejected")
func invalidRSRIsRejected() {
let local = PeerID(str: "0011223344556677")

View File

@ -238,6 +238,28 @@ struct BLEPublicMessageHandlerTests {
#expect(recorder.deliveries.isEmpty)
}
@Test
func payloadLargerThanAV1FrameIsTrackedForSyncButNotDelivered() {
let now = Date(timeIntervalSince1970: 1_000)
let recorder = Recorder()
recorder.peers = [remotePeerID: makePeerInfo(remotePeerID, nickname: "Alice", isVerified: true)]
recorder.signedName = "SignedAlice"
let handler = makeHandler(recorder: recorder, now: now)
// One character on screen, 65,537 bytes: combining marks pass any
// character-count check, so only a byte bound keeps them out of the
// count-capped timeline.
let combining = "a" + String(repeating: "\u{0301}", count: 32_768)
#expect(combining.count == 1)
let largest = String(repeating: "x", count: Int(UInt16.max))
handler.handle(makeMessagePacket(sender: remotePeerID, content: combining, timestamp: timestamp(now)), from: remotePeerID)
handler.handle(makeMessagePacket(sender: remotePeerID, content: largest, timestamp: timestamp(now)), from: remotePeerID)
// Sync tracking still follows the decode cap; only delivery is bounded.
#expect(recorder.trackedPackets.count == 2)
#expect(recorder.deliveries.map(\.content) == [largest])
}
@Test
func selfSyncReplayResolvesOriginalMessageID() {
let now = Date(timeIntervalSince1970: 1_000)

View File

@ -0,0 +1,102 @@
import Foundation
import Testing
@testable import bitchat
import BitFoundation
@Suite(.serialized)
struct ComposerDraftStoreTests {
/// Isolate each test from leftover in-memory drafts.
private func withCleanStore(_ body: () throws -> Void) rethrows {
ComposerDraftStore.replaceAllForTesting([:])
defer { ComposerDraftStore.replaceAllForTesting([:]) }
try body()
}
@Test func emptyDraftIsNotStored() throws {
try withCleanStore {
ComposerDraftStore.save("hello", for: .mesh)
ComposerDraftStore.save(" ", for: .mesh)
// Whitespace-only is still a draft the user typed; empty string clears.
ComposerDraftStore.save("", for: .mesh)
#expect(ComposerDraftStore.load(.mesh).isEmpty)
#expect(ComposerDraftStore.countForTesting() == 0)
}
}
@Test func draftsAreIsolatedPerConversation() throws {
try withCleanStore {
let peer = PeerID(str: "aabbccddeeff0011")
ComposerDraftStore.save("mesh draft", for: .mesh)
ComposerDraftStore.save("geo draft", for: .location(geohash: "u4pruy"))
ComposerDraftStore.save("dm draft", for: .privateChat(stableID: peer.id))
#expect(ComposerDraftStore.load(.mesh) == "mesh draft")
#expect(ComposerDraftStore.load(.location(geohash: "u4pruy")) == "geo draft")
#expect(ComposerDraftStore.load(.privateChat(stableID: peer.id)) == "dm draft")
#expect(ComposerDraftStore.load(.location(geohash: "other")).isEmpty)
}
}
@Test func geohashKeysAreCaseInsensitive() throws {
try withCleanStore {
ComposerDraftStore.save("city chat", for: .location(geohash: "U4PRUY"))
#expect(ComposerDraftStore.load(.location(geohash: "u4pruy")) == "city chat")
}
}
@Test func keyFromPeerPrefersFingerprintWhenPresent() {
let peer = PeerID(str: "aabbccddeeff0011")
let withFP = ComposerDraftStore.Key.from(
peerID: peer,
fingerprint: "deadbeefcafebabe",
channel: .location(GeohashChannel(level: .city, geohash: "u4pruy"))
)
#expect(withFP == .privateChat(stableID: "deadbeefcafebabe"))
let withoutFP = ComposerDraftStore.Key.from(
peerID: peer,
fingerprint: nil,
channel: .mesh
)
#expect(withoutFP == .privateChat(stableID: peer.id))
}
@Test func longDraftsAreTruncated() throws {
try withCleanStore {
let long = String(repeating: "a", count: ComposerDraftStore.maxDraftLength + 50)
ComposerDraftStore.save(long, for: .mesh)
#expect(ComposerDraftStore.load(.mesh).count == ComposerDraftStore.maxDraftLength)
}
}
@Test func resetClearsAllDrafts() throws {
try withCleanStore {
ComposerDraftStore.save("keep quiet", for: .mesh)
ComposerDraftStore.reset()
#expect(ComposerDraftStore.load(.mesh).isEmpty)
#expect(ComposerDraftStore.countForTesting() == 0)
}
}
@Test func maxDraftCountEvictsOldestKeys() throws {
try withCleanStore {
for index in 0..<ComposerDraftStore.maxDraftCount {
ComposerDraftStore.save(
"d\(index)",
for: .location(geohash: String(format: "gh%04d", index))
)
}
ComposerDraftStore.save("newest", for: .mesh)
#expect(ComposerDraftStore.countForTesting() == ComposerDraftStore.maxDraftCount)
#expect(ComposerDraftStore.load(.mesh) == "newest")
}
}
@Test func clearingDraftRemovesKeySoItDoesNotResurrect() throws {
try withCleanStore {
ComposerDraftStore.save("old text", for: .mesh)
ComposerDraftStore.save("", for: .mesh)
#expect(ComposerDraftStore.load(.mesh).isEmpty)
}
}
}

View File

@ -110,4 +110,32 @@ struct GeohashChatActivityTrackerTests {
#expect(tracker.messageCount(for: "9q8yy") == 0)
#expect(tracker.mostActiveConversation(among: [channel("9q8yy", .city)]) == nil)
}
@Test
func staleGeohashesAreEvictedNotJustEmptied() {
let (tracker, advance) = makeTracker(window: 900)
tracker.recordChatMessage(geohash: "9q8yy", senderName: "a#1111", content: "old region", timestamp: baseDate)
#expect(tracker._trackedGeohashCountForTesting == 1)
// Move well past the window, then record activity in a different
// geohash — this should sweep the now-stale "9q8yy" entry out of
// memory instead of leaving an empty-but-present dictionary entry.
advance(baseDate.addingTimeInterval(901))
tracker.recordChatMessage(geohash: "9r1zz", senderName: "b#2222", content: "new region", timestamp: baseDate.addingTimeInterval(901))
#expect(tracker._trackedGeohashCountForTesting == 1)
#expect(tracker.messageCount(for: "9q8yy") == 0)
#expect(tracker.messageCount(for: "9r1zz") == 1)
}
@Test
func activeGeohashSurvivesSweepEvenWhenMomentarilyEmpty() {
// The geohash currently being recorded to is exempt from the sweep,
// so recording its own first message never evicts itself.
let (tracker, _) = makeTracker(window: 900)
tracker.recordChatMessage(geohash: "9q8yy", senderName: "a#1111", content: "hi", timestamp: baseDate)
#expect(tracker._trackedGeohashCountForTesting == 1)
#expect(tracker.messageCount(for: "9q8yy") == 1)
}
}

View File

@ -81,6 +81,58 @@ struct GroupStoreTests {
#expect(store.group(withID: group.groupID)?.members == [creator])
}
// MARK: - Creator pinning
@Test func upsertRefusesToChangeTheCreatorOfAnExistingGroup() throws {
let store = GroupStore(keychain: MockKeychain(), persistsToDisk: false)
let creator = makeMember(seed: 0xC1, nickname: "creator")
let me = makeMember(seed: 0x0E, nickname: "me")
let attacker = makeMember(seed: 0xEE, nickname: "creator")
let group = try #require(store.createGroup(named: "trip", creator: creator))
#expect(store.updateRoster(groupID: group.groupID, members: [creator, me]) != nil)
let stored = try #require(store.group(withID: group.groupID))
let realKey = try #require(store.key(forGroupID: group.groupID))
// Same groupID at a higher epoch with the attacker as creator…
let hijack = BitchatGroup(
groupID: group.groupID,
name: group.name,
epoch: .max,
members: [attacker, me],
creatorFingerprint: attacker.fingerprint
)
#expect(!store.upsert(hijack, key: Data(repeating: 0xAB, count: 32)))
// …or the creator's fingerprint re-pinned to the attacker's signing key.
let repinned = GroupMember(fingerprint: creator.fingerprint, signingKey: attacker.signingKey, nickname: creator.nickname)
var repin = stored
repin.epoch = .max
repin.members = [repinned, me]
#expect(!store.upsert(repin, key: Data(repeating: 0xAB, count: 32)))
#expect(store.group(withID: group.groupID) == stored)
#expect(store.key(forGroupID: group.groupID) == realKey)
// The boundary: the same creator still moves the group forward.
var rotated = stored
rotated.epoch = stored.epoch + 1
let newKey = Data(repeating: 0x5A, count: 32)
#expect(store.upsert(rotated, key: newKey))
#expect(store.group(withID: group.groupID)?.epoch == stored.epoch + 1)
#expect(store.key(forGroupID: group.groupID) == newKey)
}
@Test func updateRosterRefusesToRepinTheCreatorSigningKey() throws {
let store = GroupStore(keychain: MockKeychain(), persistsToDisk: false)
let creator = makeMember(seed: 0xC1, nickname: "creator")
let me = makeMember(seed: 0x0E, nickname: "me")
let group = try #require(store.createGroup(named: "trip", creator: creator))
let repinned = GroupMember(fingerprint: creator.fingerprint, signingKey: Data(repeating: 0xEF, count: 32), nickname: creator.nickname)
#expect(store.updateRoster(groupID: group.groupID, members: [repinned, me]) == nil)
#expect(store.group(withID: group.groupID) == group)
}
// MARK: - Rotation
@Test func rotateKeyBumpsEpochAndReplacesKey() throws {
@ -136,6 +188,42 @@ struct GroupStoreTests {
#expect(reloaded.group(withID: group.groupID) == nil)
}
@Test func loadEnforcesTheUpsertInvariants() throws {
let keychain = MockKeychain()
let fileURL = tempFileURL()
defer { try? FileManager.default.removeItem(at: fileURL.deletingLastPathComponent()) }
let creator = makeMember(seed: 0xC1, nickname: "creator")
let other = makeMember(seed: 0xEE, nickname: "other")
let kept: BitchatGroup
let orphaned: BitchatGroup
do {
let store = GroupStore(keychain: keychain, fileURL: fileURL)
kept = try #require(store.createGroup(named: "kept", creator: creator))
orphaned = try #require(store.createGroup(named: "orphaned", creator: creator))
}
// Loading bypasses `upsert`: a second entry handing `kept` to another
// creator, and an entry whose creator is missing from its roster.
let rehomed = BitchatGroup(
groupID: kept.groupID,
name: kept.name,
epoch: kept.epoch + 1,
members: [other],
creatorFingerprint: other.fingerprint
)
let creatorless = BitchatGroup(
groupID: orphaned.groupID,
name: orphaned.name,
epoch: orphaned.epoch,
members: orphaned.members,
creatorFingerprint: other.fingerprint
)
try JSONEncoder().encode([kept, rehomed, creatorless]).write(to: fileURL)
let reloaded = GroupStore(keychain: keychain, fileURL: fileURL)
#expect(reloaded.groups == [kept])
}
// MARK: - Panic wipe
@Test func wipeRemovesMetadataAndKeys() throws {

View File

@ -173,6 +173,9 @@ struct NostrTransportTests {
#expect(privateMessage.messageID == "pm-1")
#expect(privateMessage.content == "hello over nostr")
#expect(result.packet.recipientID == shortPeerID.routingData)
// Favorites DMs keep the mesh sender ID: the recipient already binds
// this npub to our Noise key.
#expect(result.packet.senderID == transport.senderPeerID.routingData)
#expect(probe.pendingGiftWrapIDs.isEmpty)
}
@ -257,6 +260,7 @@ struct NostrTransportTests {
#expect(result.payload.type == .delivered)
#expect(String(data: result.payload.data, encoding: .utf8) == "ack-1")
#expect(result.packet.recipientID == fullPeerID.toShort().routingData)
#expect(result.packet.senderID == transport.senderPeerID.routingData)
}
@Test("Geohash private message registers pending gift wrap")
@ -300,6 +304,66 @@ struct NostrTransportTests {
#expect(probe.pendingGiftWrapIDs == [event.id])
}
@Test("Geohash envelopes never carry the mesh peer ID")
@MainActor
func geohashEnvelopesNeverCarryMeshPeerID() async throws {
let keychain = MockKeychain()
let idBridge = NostrIdentityBridge(keychain: keychain)
let sender = try NostrIdentity.generate()
let recipient = try NostrIdentity.generate()
let probe = NostrTransportProbe()
let transport = NostrTransport(
keychain: keychain,
idBridge: idBridge,
dependencies: makeDependencies(
currentIdentity: { sender },
registerPendingGiftWrap: probe.recordPendingGiftWrap(id:),
sendEvent: probe.record(event:),
scheduleAfter: { delay, action in
probe.enqueueScheduledAction(delay: delay, action: action)
}
)
)
// Even a transport that knows the mesh peer ID must not embed it
// under a geohash identity: whoever receives the envelope (including
// the automatic DELIVERED ack) could link that persona to the device.
let meshPeerID = PeerID(str: "0123456789abcdef")
let meshIDBytes = try #require(meshPeerID.routingData)
transport.senderPeerID = meshPeerID
transport.sendPrivateMessageGeohash(
content: "geo hello",
toRecipientHex: recipient.publicKeyHex,
from: sender,
messageID: "geo-pm"
)
transport.sendDeliveryAckGeohash(for: "geo-delivered", toRecipientHex: recipient.publicKeyHex, from: sender)
transport.sendReadReceiptGeohash("geo-read", toRecipientHex: recipient.publicKeyHex, from: sender)
// The PM goes out directly; the two acks share the pacer, so the
// second leaves only once the queued throttle action runs.
let sentFirst = await TestHelpers.waitUntil(
{ probe.sentEvents.count == 2 && probe.scheduledActionCount == 1 },
timeout: TestConstants.settleTimeout
)
try #require(sentFirst, "Expected the PM and the first paced ack")
try #require(probe.runNextScheduledAction(), "Expected queued throttle action after first ack")
let sentAll = await TestHelpers.waitUntil({ probe.sentEvents.count == 3 }, timeout: TestConstants.settleTimeout)
try #require(sentAll, "Expected the second paced ack")
let envelopes = try probe.sentEvents.map { try decodeEmbeddedPayload(from: $0, recipient: recipient) }
#expect(Set(envelopes.map(\.payload.type)) == [.privateMessage, .delivered, .readReceipt])
for envelope in envelopes {
#expect(envelope.packet.recipientID == nil)
#expect(envelope.packet.senderID.count == BinaryProtocol.senderIDSize)
#expect(envelope.packet.senderID != meshIDBytes)
#expect(envelope.packetData.range(of: meshIDBytes) == nil)
}
// Fresh random bytes per envelope, so the field can't tie two
// envelopes (or two geohash identities) to one sender either.
#expect(Set(envelopes.map(\.packet.senderID)).count == envelopes.count)
}
@Test("Read receipt queue sends in order and waits for scheduler")
@MainActor
func readReceiptQueueThrottlesSequentially() async throws {
@ -456,7 +520,7 @@ struct NostrTransportTests {
private func decodeEmbeddedPayload(
from event: NostrEvent,
recipient: NostrIdentity
) throws -> (packet: BitchatPacket, payload: NoisePayload, senderPubkey: String) {
) throws -> (packet: BitchatPacket, payload: NoisePayload, senderPubkey: String, packetData: Data) {
let (content, senderPubkey, _) = try NostrProtocol.decryptPrivateMessage(
giftWrap: event,
recipientIdentity: recipient
@ -470,7 +534,7 @@ struct NostrTransportTests {
let payload = NoisePayload.decode(packet.payload) else {
throw NostrTransportTestError.invalidPacket
}
return (packet, payload, senderPubkey)
return (packet, payload, senderPubkey, packetData)
}
private func decodePrivateMessage(from payload: NoisePayload) throws -> PrivateMessagePacket {

View File

@ -27,6 +27,38 @@ struct UnifiedPeerServiceTests {
#expect(fingerprint == "fp-1")
}
@Test @MainActor
func getPeerID_acceptsAUniqueNickname() async {
let transport = MockTransport()
let identity = TestIdentityManager()
let idBridge = NostrIdentityBridge(keychain: MockKeychainHelper())
let service = UnifiedPeerService(meshService: transport, idBridge: idBridge, identityManager: identity)
let alice = PeerID(str: "1111111111111111")
transport.simulateConnect(alice, nickname: "alice")
service.didUpdatePeerSnapshots(transport.currentPeerSnapshots())
#expect(service.getPeerID(for: "alice") == alice)
}
@Test @MainActor
func getPeerID_refusesAmbiguousNicknameUnlessSuffixed() async {
let transport = MockTransport()
let identity = TestIdentityManager()
let idBridge = NostrIdentityBridge(keychain: MockKeychainHelper())
let service = UnifiedPeerService(meshService: transport, idBridge: idBridge, identityManager: identity)
let aliceA = PeerID(str: "1111111111111111")
let aliceB = PeerID(str: "2222222222222222")
transport.simulateConnect(aliceA, nickname: "alice")
transport.simulateConnect(aliceB, nickname: "alice")
service.didUpdatePeerSnapshots(transport.currentPeerSnapshots())
#expect(service.getPeerID(for: "alice") == nil)
#expect(service.getPeerID(for: "alice#1111") == aliceA)
#expect(service.getPeerID(for: "alice#2222") == aliceB)
}
@Test @MainActor
func isBlocked_usesSocialIdentity() async {
let transport = MockTransport()

View File

@ -0,0 +1,141 @@
# Service UUID Detectability
**Status:** Analysis for cross-platform review. **No implementation is proposed.** This documents why the obvious fix — rotating or deriving the service UUID — does not work, so the idea stops being re-raised without its constraints, and records what is achievable instead.
**Audience:** bitchat iOS and Android maintainers.
`docs/PEER-ID-ROTATION.md` §2 lists this as an explicit non-goal: *"Hiding **that** bitchat is in use. The service UUID is a separate problem; BLE requires something discoverable. Tracked separately."* This is that tracking document.
**The conclusion, up front:** hiding that bitchat is running is **not achievable** for an open-source app that supports discovery between strangers. That is a consequence of the threat model, not a gap in the implementation. `docs/privacy-assessment.md:34` already says so; this document explains why, so the honesty there is preserved rather than softened by a scheme that looks like a fix.
---
## 1. What is exposed today
`BLEService.swift:187-191` defines three compile-time constants:
| Constant | Value | Exposure |
|---|---|---|
| `serviceUUID` (mainnet) | `F47B5E2D-…-4B5C` | Advertised; a globally unique constant in the clear |
| `serviceUUID` (testnet, `#if DEBUG`) | `F47B5E2D-…-4B5A` | as above |
| `characteristicUUID` | `A1B2C3D4-…-4C5D` | Reachable by anything that connects and walks the GATT table |
`BLERadioController.advertisementData()` advertises the service UUID and deliberately no local name. In the **foreground** that 128-bit constant goes out in the clear, occupying 18 of the 31 advertising bytes — the strongest possible app fingerprint. Scanning filters on the same constant (`BLERadioController.swift:83`, `BLEService.swift:960`).
Note there are **two** fixed identifiers, not one. Even if the advertised UUID changed, `BLEService+LinkLayerPeripheralRole.swift:38-46` builds one primary service containing one characteristic, both constants, so an active prober that connects still identifies bitchat.
---
## 2. Why rotating the service UUID does not work
Two reasons. The first is sufficient on its own; the second constrains whatever survives it.
### 2.1 The threat model forecloses it
Rotation only helps if an adversary cannot compute the current value. But:
- iOS **requires** background scanners to name the exact service UUIDs they want (§3.1). A UUID that a stranger's phone cannot pre-compute is a UUID it cannot scan for.
- So any value a **stranger** can derive in order to find us, an adversary running the same open-source binary derives identically.
Stranger discovery (`PEER-ID-ROTATION.md` goal **G4**) and invisibility-to-a-code-reading-adversary are therefore mutually exclusive in the same advertisement. Rotation from a *public* input defeats a scanner using a stale hardcoded list; it does not defeat a censor who runs our algorithm.
Covert rendezvous with an adversary who knows the algorithm requires a **pre-shared secret**. That is the consistent finding of the literature — secret handshakes (Balfanz et al.), matchmaking encryption (PriSrv), Bluetooth 5.4 Encrypted Advertising Data, and the covert-communication square-root law all assume one. Public-key steganography is the near-miss that lets parties who never met communicate covertly, but the sender must know the *recipient's* key; for an open-source app that reduces to a key in the binary, which the adversary extracts.
The closest real-world analogue is Tor's twenty-year bridge-distribution problem — let unknown strangers find a resource without letting the censor find it. Every mitigation that works (Salmon, Lox, rBridge) gates on social trust and thereby gives up open stranger access. There is no known escape from that trade.
### 2.2 iOS constrains it mechanically
- **Third-party iOS apps cannot control advertisement contents.** Only `CBAdvertisementDataLocalNameKey` and `CBAdvertisementDataServiceUUIDsKey` are supported; other keys error. Manufacturer data and service data — where every comparable system puts its rotating payload — are unavailable to us. MASHaBLE, the one BLE secret-handshake prototype, could not be built on iOS for exactly this reason and fell back to Windows Phone.
- **Advertised services cannot be changed while backgrounded (iOS 14+).** A wall-clock rotation cannot advance while the app is in the background — which is the state during the scenario this feature exists for. *Undocumented by Apple; needs device verification (§6).*
- **Backgrounded, the UUID is not transmitted at all.** iOS re-encodes it as Apple manufacturer data (`0x004C`) plus a 128-bit bitmask, one bit per advertised UUID. This is worth understanding precisely, because it cuts both ways: background exposure is already only ~7 bits with genuine collisions against every other backgrounded Apple advertiser — but the mapping is stable and empirically discoverable with a free Android app, so an adversary installs bitchat once, notes the bit, and matches passively forever.
The practical consequence: **the real identification exposure is foreground advertising**, where the raw constant is on the air. iOS does permit rotation there — a foreground app can stop advertising, swap the service, and start again under a new UUID, the same stop / remove / add / start cycle `BLEService+LinkLayerPeripheralRole.swift` already runs at runtime — so the mechanics alone do not foreclose it. What they foreclose is rotation in the **background**, where the app spends most of its life in the scenario this feature exists for, and any scheme that puts the rotating value in manufacturer or service data. Foreground rotation would defeat a scanner holding a stale UUID list; it would not defeat an adversary running the public derivation (§2.1), and GATT connect-and-probe (§4) identifies us regardless of what is advertised.
---
## 3. What comparable deployments chose
Every large deployment faced this and made the same call: **fix the identifier, rotate the payload.**
| System | Identifier | Rotates? |
|---|---|---|
| Exposure Notification | service UUID **`0xFD6F`** | Fixed; 16-byte Rolling Proximity Identifier rotates ~15 min |
| Apple Find My / Offline Finding | mfr data, OF type **`0x12`** | Type byte fixed; only the key rotates |
| Google Fast Pair | service UUID **`0xFE2C`** | Fixed; salted account-key filter rotates |
| Eddystone-EID | service UUID **`0xFEAA`** | Fixed; EID in service data rotates |
Exposure Notification is the most instructive. Its byte budget left no room for a 128-bit UUID alongside a 16-byte identifier — flags (3) + 16-bit UUID section (4) + service data (24) is exactly the 31-byte legacy maximum — and iOS↔Android background interop requires a registered service UUID regardless. Hiding participation was never a goal, and detecting EN users promptly became a shipped consumer app. France's use of a *different* UUID (`0xFD64`) meant the identifier revealed which country's app you ran.
The transferable lesson is **not** "rotate the UUID." It is that the EN spec mandates the payload *"shall not include other data types"*, so every EN advertiser is byte-identical in structure. They gave up hiding participation and hardened against distinguishing *which app, version, or user*. That is the achievable goal.
Fast Pair's salted account-key filter is the best deployed example of private group rendezvous — only holders of the account key recognise it — and it lives **inside** a fixed, public service UUID. Same shape: hide *who*, not *what*.
### 3.1 The mesh apps, from their shipped source
Not one of the comparable mesh messengers rotates or derives its identifier from a shared secret:
| | Identifier | Also broadcast |
|---|---|---|
| Bridgefy | service UUID = `SHA-256(app API key)[0:16]` — derived, but from a per-app licensing constant | full user ID in service data |
| Berty | `0x4240` alias, hardcoded | last 4 chars of the libp2p PeerID in service data |
| qaul | hardcoded (currently *different* UUIDs on Android vs iOS/Rust) | mfr data, company `0xFFFF`, 5 bytes of node ID |
| Meshtastic | `6ba1b218-…` hardcoded | device name pattern `Meshtastic_ab3c` (MAC-derived) |
| Briar | **no BLE at all** — Bluetooth Classic RFCOMM/SDP | — |
Bridgefy is the instructive near-miss: its UUID *is* cryptographically derived, but from a value that never changes, so every user of a given app advertises the identical UUID forever — derivation without rotation buys nothing.
Two observations that matter for us:
- **bitchat's advertisement is already cleaner than all of them.** Every app above leaks a stable **per-user** identifier alongside the app identifier — so BLE MAC randomization buys them nothing at all. bitchat advertises the service UUID and deliberately nothing else: no local name, no service data, no manufacturer data. Our advertisement says "a bitchat device is here", not "this person is here". The per-user leak in bitchat lives one layer up, in the announce payload (stable peer ID, cleartext static keys, nickname, neighbour list) — which is precisely what `PEER-ID-ROTATION.md` addresses, and another reason §7.1 is where the effort belongs.
- **Briar is the only structurally different answer**, and it is not a UUID trick: it does not broadcast. It uses Bluetooth Classic and dials a contact's known MAC directly, requesting discoverability only during in-person QR pairing — where it *does* derive a per-session rendezvous UUID from the key commitment. That is contact-scoped rendezvous with an in-person secret (our §7.4), achieved by giving up broadcast discovery entirely.
---
## 4. What still identifies bitchat after any UUID change
Rotation would leave all of these intact:
Ordered by how cheaply an adversary can actually use them — which is not the order they are usually discussed in.
- **GATT connect-and-probe — the one to worry about, and the reason rotation cannot succeed.** Cheap, active, decisive, and completely unaffected by anything done to the advertisement. Any central connects and enumerates our one primary service containing one read/write/notify characteristic (§1).
The distinction that matters, because the literature is easy to misread here: the well-known GATT-fingerprinting results are about telling *devices apart* — and by that measure the attack is weak against phones (only 4.28% of randomizing addresses uniquely identified; 85.49% of iPhones sit in anonymity sets of ≥100). But **"does this phone run bitchat" is a lookup, not a discrimination problem.** A custom 128-bit service UUID paired with a custom characteristic UUID is a categorical exact match. The measured cost of collecting a profile was ~**3.7 seconds** per device on a **Raspberry Pi 3 with four USB dongles** — squarely a cheap dragnet.
This is what forecloses rotation as a fix rather than merely complicating it. A prober reads whatever the values *currently* are, so rotating them changes nothing for an attacker who connects; and the **structure** — exactly one custom primary service, exactly one custom read/write/notify characteristic — is invariant under any rotation scheme. Worse, `characteristicUUID` is a *separate* constant today, so rotating only the service UUID would leave it as a static relink handle: the textbook out-of-sync-identifier failure that has repeatedly re-linked devices across MAC rotations in deployed Apple protocols. Gating characteristic *values* behind authentication (the mitigation that paper recommends) reduces what is served but does **not** hide the UUIDs or the shape from an enumerator.
- **Automated, at-scale UUID mining.** The precedent that matters: a 2019 field study fingerprinted **5,509 of 5,822 real BLE devices (94.6%)** across ~1.3 square miles, using a UUID→app mapping built *automatically* by mining app stores. For a closed-source app that mapping takes reverse engineering; for us it is a grep of the repository. This is the detector that rotation would actually defeat — and the one that got Bridgefy's users tracked.
- **Traffic metadata.** Packet sizes and inter-packet timing alone identify devices from *encrypted* BLE traffic at ~0.97 F1. The same work tested padding, delaying, and dummy traffic as defences and found they "do not provide sufficient protection … and introduce significant costs" — worth knowing before cover traffic is proposed elsewhere as a fix.
- **Behavioural timing.** Our scan duty cycle is a published constant (`TransportConfig.swift`: 5 s on / 10 s off, tightening when dense). Scanning is not transmitted, but the connect cadence it produces is observable, and that rhythm is distinctive. On iOS the *advertising* interval is not ours to choose, which is good camouflage — it makes us look like every other iOS app. On Android `AdvertiseSettings` mode **is** app-chosen, so a non-default choice is a cross-platform tell worth a few bits.
- **Mesh structure itself.** Multiple nearby devices exchanging correlated bursts with propagation delays is a signature no single-device fingerprint has, and no identifier change touches it. It is exactly what the Bridgefy social-graph and topology attacks exploited, and exactly what a published ML pipeline — built on Bridgefy traffic and framed as assisting law enforcement — set out to classify.
- **Physical-layer RF fingerprinting — real, but a targeted tool, not a dragnet.** I stated this too strongly in an earlier draft and am correcting it. The IEEE S&P 2022 field study found only **~40–47% of devices uniquely identifiable**, needed ~50 clean packets to enrol, used a USRP N210 rather than a cheap dongle, and degraded badly with temperature (at ΔT ≈ 25 °C carrier-frequency offset "becomes useless for identification"); same-vendor confusion was ~3× the median false-positive rate, which matters in an Apple-heavy crowd. Later work (INFOCOM 2024's transient fingerprints, and 2026 work aimed explicitly at aggressively-rotating trackers) attacks the temperature caveat and reports much stronger results, so the trend is unfavourable — but it still requires per-device SDR capture. Treat it as "can this adversary target a person they have already gotten close to", not "can they enumerate everyone in the square".
---
## 5. Two ways a rotation scheme would make things worse
This is the part that matters most, because each is counter-intuitive.
1. **A derived UUID shrinks the anonymity set.** A global constant hides an individual inside the entire bitchat population. A per-group or per-user derived UUID is a *stronger* selector for a targeted adversary — it identifies not "a bitchat user" but "a member of this cell." Against blanket blocking that is a gain; against targeted work it is a gift.
2. **State restoration becomes a stale-identifier trap.** If iOS terminates the app while scanning, the system continues scanning for the **old** UUID indefinitely and relaunches the app *into the background*, where §2.2 says the advertisement cannot be updated. A restored device could sit advertising a dead epoch's UUID — undiscoverable by current peers *and* wearing a distinctive stale identifier. Strictly worse than the fixed UUID for that device.
---
## 6. What needs device verification before anyone relies on this
Two load-bearing claims are undocumented by Apple and were established from reverse-engineering and engineer forum statements:
- **Can a backgrounded app change its advertised services?** (§2.2). Everything in §5.2 follows from "no". Test: advertise UUID A, background, attempt a switch to B, observe from a second device.
- **Is there a hard cap on the scan-filter array?** Undocumented. Note the structural ceiling regardless: background advertising collapses to 128 bit positions, so at most 128 mutually distinguishable UUIDs exist, and each extra UUID scanned costs roughly 1/128 of *all* backgrounded Apple advertisers as false wakeups. A ±1 epoch skew window is defensible; a wide window degenerates into a near-wildcard scan.
Unresolved and not guessed at here: whether the overflow payload rides in the primary ADV PDU or the scan response, and the exact GATT cache lifetime for unbonded peers.
---
## 7. What is actually available
Ranked by value per unit of risk, given everything above.
1. **Fix linkability, not detectability.** The far larger exposure is that today a stable 8-byte peer ID, cleartext static keys, a nickname, and a neighbour list identify a **specific person**, not merely "a bitchat user." `docs/PEER-ID-ROTATION.md` targets exactly that and is achievable. Invisibility is not. If effort is going anywhere, it should go there.
2. **If anything is done to the advertisement, it must be *blending in*, not *removing*.** Adopting a widely-shared service UUID in place of a globally unique constant trades a perfect app fingerprint for genuine cover from unrelated devices. But note the trap in the obvious version of this idea: **an advertisement with no local name, no manufacturer data, and no service UUID is itself a distinctive negative signature.** Ordinary crowd BLE is dominated by Apple Continuity (`0x004C`) and Microsoft (`0x0006`) manufacturer data; stripping our identifier does not put us in the crowd, it puts us in a small, odd bucket. Any such change must also carry the §4 GATT problem, which it cannot solve, and it invites the well-supported "unobservability by imitation is fundamentally flawed" critique. A maintainer decision with real downside, not an obvious win.
3. **Uniformity, per the Exposure Notification lesson.** Make every bitchat advertisement byte-identical in structure and timing so implementations, versions, and users do not distinguish themselves from each other. This is achievable unilaterally and has no discovery cost.
4. **Contact-scoped covert rendezvous is genuinely possible** — a UUID derived from a shared secret, for peers who have already exchanged one. Group keys with epochs already exist (`Services/Groups/GroupStore.swift`). But it cannot coexist with stranger discovery in the same advertisement, it inherits the §5.1 anonymity-set problem, and §2.2 constrains when it can rotate at all. If it is ever built it should be an explicit, opt-in mode whose costs are stated plainly, not the default.
**What to tell users:** bitchat does not hide that it is running, and no known technique would let it while strangers can still find each other. `docs/privacy-assessment.md` already states this correctly. That honesty is the right posture and should be preserved.

View File

@ -0,0 +1,137 @@
{
"_comment": [
"Golden vectors for the bitchat courier wire format. Generated from the iOS",
"implementation and asserted by CourierVectorTests in the BitFoundation test",
"target, so these cannot drift from the code without a test failing.",
"All hex is lowercase. All multi-byte integers are big-endian.",
"",
"These exist because three courier encoding mistakes fail SILENTLY — the",
"client builds, connects, and delivers nothing, with no error at either end:",
" 1. treating `expiry` as seconds when it is milliseconds",
" 2. signing the wire bytes instead of the padded, ttl-zeroed pre-image",
" 3. reaching for X25519 key agreement because CryptoKit spells Ed25519",
" as `Curve25519.Signing`"
],
"inputs": {
"_comment": "Synthetic. Not derived from any real key.",
"recipientTag": "000102030405060708090a0b0c0d0e0f",
"noiseStaticKey": "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf",
"ciphertextUTF8": "courier-vector-ciphertext-0001",
"ciphertext": "636f75726965722d766563746f722d636970686572746578742d30303031",
"expiryMillis": 1800000000000,
"epochDay": 20833,
"senderID": "1122334455667788",
"recipientID": "99aabbccddeeff00",
"timestampMillis": 1750000000000,
"signingSeed": "4242424242424242424242424242424242424242424242424242424242424242"
},
"envelopeTLV": {
"_comment": [
"TLV records are type(1) length(2, big-endian) value(length).",
"0x01 recipientTag(16) 0x02 expiry(8) 0x03 ciphertext 0x04 copies(1) 0x05 prekeyID(4).",
"Lengths are checked exactly, not as minimums. Unknown types are skipped",
"using the length field.",
"NOTE the 0x02 value below is 000001a3185c5000 = 1800000000000 MILLISECONDS.",
"Emitting seconds yields a value ~1000x too small, so every envelope reads",
"as long expired and is dropped at deposit with nothing logged."
],
"copies": 4,
"prekeyID": 287454020,
"encoded": "010010000102030405060708090a0b0c0d0e0f020008000001a3185c500003001e636f75726965722d766563746f722d636970686572746578742d303030310400010405000411223344",
"encodedLength": 74
},
"copiesClamping": {
"_comment": [
"`copies` is clamped into 1...maxCopies by the initializer, never rejected.",
"An implementation that rejects out-of-range values will drop envelopes",
"this one accepts."
],
"maxCopies": 8,
"cases": [
{ "requested": 0, "stored": 1 },
{ "requested": 4, "stored": 4 },
{ "requested": 200, "stored": 8 }
]
},
"recipientTagDerivation": {
"_comment": [
"HMAC-SHA256(key = recipient noise static key,",
" message = \"bitchat-courier-tag-v1\" || BE32(epochDay))",
"truncated to the first 16 bytes. The label is ASCII with no terminator.",
"epochDay = floor(unixSeconds / 86400).",
"A matcher computes tags for the previous, current and next epoch day and",
"accepts any of the three, so mail crossing UTC midnight still resolves."
],
"label": "bitchat-courier-tag-v1",
"epochDay": 20833,
"expected": "ad8514c90ca1fa6bf44e38c8a6252482"
},
"packetSigning": {
"_comment": [
"THE trap. The signature does NOT cover the bytes as they appear on the",
"wire. It covers a re-encoding in which ttl is set to 0, the isRSR flag is",
"cleared, the signature is omitted (so the hasSignature flag bit 0x02 is",
"CLEAR in the signed bytes although SET on the wire) — and the result is",
"then PKCS#7-padded.",
"",
"Padding target is the smallest of [256, 512, 1024, 2048] that fits",
"size + 16, applied only when the shortfall is 1...255, every pad byte",
"equal to the shortfall. Here: 104 + 16 = 120 <= 256, so target 256,",
"shortfall 152 = 0x98.",
"",
"Signing the 104 unpadded bytes produces a signature that never verifies,",
"and nothing in any log points at the cause."
],
"packet": {
"_comment": "A real courierEnvelope deposit frame: type 0x04 carrying the encoded envelope from envelopeTLV.encoded above as its payload.",
"version": 1,
"type": "0x04",
"ttlOnWire": 7,
"payloadIs": "envelopeTLV.encoded (74 bytes)"
},
"unsignedUnpaddedLength": 104,
"unsignedUnpadded": "010407000001977420dc0001004a112233445566778899aabbccddeeff00010010000102030405060708090a0b0c0d0e0f020008000001a3185c500003001e636f75726965722d766563746f722d636970686572746578742d303030310400010405000411223344",
"signingPreimageLength": 256,
"signingPreimagePadByte": "0x98",
"signingPreimagePadCount": 152,
"signingPreimage": "010400000001977420dc0001004a112233445566778899aabbccddeeff00010010000102030405060708090a0b0c0d0e0f020008000001a3185c500003001e636f75726965722d766563746f722d636970686572746578742d3030303104000104050004112233449898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898989898",
"signedWireLength": 168,
"flags": {
"_comment": [
"Flag bits: hasRecipient 0x01, hasSignature 0x02, isCompressed 0x04,",
"hasRoute 0x08, isRSR 0x10. Byte lives at offset 11.",
"The unsignedUnpadded and signingPreimage vectors above both carry 0x01",
"because the signature is absent from each. Only the finished 168-byte",
"wire packet sets 0x02 as well — which is exactly why re-signing a",
"received packet requires clearing that bit before re-encoding."
],
"unsignedUnpadded": "0x01",
"signingPreimage": "0x01",
"signedWirePacket": "0x03"
}
},
"signature": {
"_comment": [
"Ed25519. CryptoKit spells the type `Curve25519.Signing.PrivateKey`, which",
"IS Ed25519 — reaching for a primitive named 'Curve25519' in another",
"language gets you X25519 key agreement, the wrong algorithm.",
"",
"Signature BYTES are deliberately not pinned here. CryptoKit's Ed25519",
"signing is RANDOMIZED rather than the deterministic RFC 8032",
"construction, so two signatures over identical input differ and both",
"verify. A second implementation using a deterministic Ed25519 library",
"will not reproduce iOS's bytes and does not need to. Pin the pre-image;",
"verification is the contract."
],
"publicKey": "2152f8d19b791d24453242e15f2eab6cb7cffa7b6a5ed30097960e069881db12",
"signatureLength": 64,
"deterministic": false,
"verify": "Ed25519 verify(publicKey, signature, packetSigning.signingPreimage) must succeed"
}
}

View File

@ -46,7 +46,8 @@
/// ## Compression Strategy
/// - Automatic compression for payloads > 256 bytes
/// - zlib compression for broad compatibility on Apple platforms
/// - Original size stored for decompression
/// - Original size stored for decompression; decoded payloads, compressed or
/// not, are capped per message type (see `PacketPayloadLimits`)
/// - Flag bit indicates compressed payload
///
/// ## Flag Bits
@ -355,6 +356,10 @@ public struct BinaryProtocol {
}
// Payload: payloadLength is exactly the payload size (+ compression preamble if compressed)
// Per-type ceiling on the decoded payload, compressed or not,
// checked before any allocation: see PacketPayloadLimits for why
// one frame-wide cap is not enough.
let maxPayloadSize = PacketPayloadLimits.maxPayloadBytes(forType: type)
let payload: Data
if isCompressed {
guard payloadLength >= lengthFieldBytes else { return nil }
@ -366,13 +371,15 @@ public struct BinaryProtocol {
guard let rawSize = read16() else { return nil }
originalSize = Int(rawSize)
}
guard originalSize >= 0 && originalSize <= FileTransferLimits.maxFramedFileBytes else { return nil }
guard originalSize >= 0 && originalSize <= maxPayloadSize else {
SecureLogger.debug("🚫 Compressed payload for type \(type) declares \(originalSize) bytes (cap \(maxPayloadSize))", category: .security)
return nil
}
let compressedSize = payloadLength - lengthFieldBytes
guard compressedSize > 0, let compressed = readData(compressedSize) else { return nil }
let compressionRatio = Double(originalSize) / Double(compressedSize)
guard compressionRatio <= 50_000.0 else {
SecureLogger.warning("🚫 Suspicious compression ratio: \(String(format: "%.0f", compressionRatio)):1", category: .security)
guard originalSize <= compressedSize * PacketPayloadLimits.maxDeflateRatio else {
SecureLogger.debug("🚫 Impossible compression ratio: \(originalSize) bytes from \(compressedSize)", category: .security)
return nil
}
@ -380,6 +387,12 @@ public struct BinaryProtocol {
decompressed.count == originalSize else { return nil }
payload = decompressed
} else {
// Uncompressed payloads get the same ceiling, or a large frame
// could arrive as small compressed fragments and be reassembled.
guard payloadLength <= maxPayloadSize else {
SecureLogger.debug("🚫 Payload for type \(type) is \(payloadLength) bytes (cap \(maxPayloadSize))", category: .security)
return nil
}
guard let rawPayload = readData(payloadLength) else { return nil }
payload = rawPayload
}

View File

@ -45,7 +45,12 @@ public extension Data {
for _ in 0..<len {
let nextIndex = hex.index(index, offsetBy: 2)
guard let byte = UInt8(String(hex[index..<nextIndex]), radix: 16) else {
let pair = hex[index..<nextIndex]
// UInt8(_:radix:) accepts a leading sign, so "+f" parses as 0x0f.
// That gives an identity-bearing hex string a second spelling which
// decodes to the same bytes, so require two hex digits first.
guard pair.allSatisfy(\.isHexDigit),
let byte = UInt8(pair, radix: 16) else {
return nil
}
data.append(byte)

View File

@ -0,0 +1,106 @@
//
// PacketPayloadLimits.swift
// BitFoundation
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
/// Receive-side ceilings on how large a packet's payload may be, per type.
///
/// A compressed frame declares its original size, and raw DEFLATE lets ~1 KB
/// on air stand for ~1 MB decoded; fragment reassembly lets a large
/// uncompressed frame arrive as a stream of small, compressed fragments.
/// Every accepted packet is then held at its decoded size by stores that
/// evict by count (gossip sync, the public-message archive, the mesh
/// timeline), relayed, and re-served by sync, so a single frame-wide ceiling
/// turns airtime into memory on every node. `BinaryProtocol` enforces these
/// caps on every decoded payload, compressed or not, and fragment reassembly
/// bounds an assembly by the frame its claimed type can fill. Only the types
/// that carry media keep the framed-file ceiling; every other type is capped
/// at no less than twice the largest payload any shipping iOS or Android
/// encoder produces for it. Receive-side only: senders are unchanged.
///
/// | Type | Largest legitimate payload | Cap |
/// |------------------------------|--------------------------------------------------------------|--------------------|
/// | fileTransfer, noiseEncrypted | 1 MiB file + name/MIME TLVs (+ Noise framing for private) | maxFramedFileBytes |
/// | message | 65,535 B: iOS and Android both send public messages as v1 | 128 KiB |
/// | | frames (16-bit length); 60,000-char composer limit | |
/// | groupMessage | 65,535 B: v1 frame (iOS only) | 128 KiB |
/// | courierEnvelope | 16 KiB ciphertext + 44 B of TLVs (iOS only) | 64 KiB |
/// | nostrCarrier | 16 KiB event JSON + 22 B of TLVs (iOS only) | 64 KiB |
/// | requestSync | ~2.1 KB: 1,024 B GCS filter (both platforms) + 1,019 B | 8 KiB |
/// | | fragment-ID filter (iOS) | |
/// | announce | ~680 B: nickname, keys, 10 neighbours, capabilities, cell | 4 KiB |
/// | fragment | ≤ 513 B: 13 B header + chunk (Android 469 B, 500 B before | 1,280 B |
/// | | Aug 2025; iOS 469 B default, ≤ 482 B from the link limit; | |
/// | | iOS 500 B before Jul 2025). Kept tight: every fragment also | |
/// | | lands in the reassembly buffer and the gossip fragment store | |
/// | boardPost | ~750 B: 512 B content cap + IDs, key, signature (iOS only) | 4 KiB |
/// | prekeyBundle | ~400 B: 8 prekeys + key + signature (iOS only) | 4 KiB |
/// | announceV2 | ~340 B: 64 B tag block + capabilities + cell (iOS only) | 4 KiB |
/// | voiceFrame | ~210 B burst budget (both platforms) | 4 KiB |
/// | noiseHandshake | 96 B (XX with empty payloads, both platforms) | 4 KiB |
/// | leave | ≤ 255 B: empty on iOS, nickname from Android Wi-Fi Aware | 4 KiB |
/// | ping, pong | 9 B (iOS only) | 4 KiB |
/// | unknown / future types | a v1 frame (65,535 B) stays relayable | 128 KiB |
///
/// A future type that needs more than a v1 frame must be added here before it
/// ships, or current receivers will drop it at decode.
public enum PacketPayloadLimits {
/// Raw DEFLATE's hard expansion ceiling: every 258-byte match costs at
/// least a 1-bit length code plus a 1-bit distance code. A declared
/// original size beyond this multiple of the compressed bytes cannot be
/// produced by any stream, so it is rejected before the output buffer is
/// allocated.
static let maxDeflateRatio = 1032
private static let fragmentBytes = 1_280
private static let controlBytes = 4 * 1024
private static let requestSyncBytes = 8 * 1024
private static let envelopeBytes = 64 * 1024
private static let twiceV1FrameBytes = 128 * 1024
/// Everything a frame can carry besides its payload: the v2 header, the
/// sender and recipient, the widest route the decoder accepts (255 hops),
/// the compressed-size field, the signature, and the most padding
/// `MessagePadding` adds (iOS fragments the padded frame).
private static let maxFrameOverheadBytes = BinaryProtocol.v2HeaderSize
+ BinaryProtocol.senderIDSize
+ BinaryProtocol.recipientIDSize
+ 1 + Int(UInt8.max) * BinaryProtocol.senderIDSize
+ 4
+ BinaryProtocol.signatureSize
+ Int(UInt8.max)
/// Largest decoded payload accepted for a packet of `type`, whether it
/// arrived compressed or not.
static func maxPayloadBytes(forType type: UInt8) -> Int {
guard let messageType = MessageType(rawValue: type) else {
return twiceV1FrameBytes
}
switch messageType {
case .fileTransfer, .noiseEncrypted:
return FileTransferLimits.maxFramedFileBytes
case .message, .groupMessage:
return twiceV1FrameBytes
case .courierEnvelope, .nostrCarrier:
return envelopeBytes
case .requestSync:
return requestSyncBytes
case .fragment:
return fragmentBytes
case .announce, .announceV2, .leave, .boardPost, .prekeyBundle,
.voiceFrame, .noiseHandshake, .ping, .pong:
return controlBytes
}
}
/// Largest encoded frame, padding included, that can still decode as a
/// packet of `type`. Fragment reassembly holds an assembly to this for
/// the type its fragments claim, so it never buffers more than the
/// reassembled packet would be allowed to decode to.
public static func maxFrameBytes(forType type: UInt8) -> Int {
maxPayloadBytes(forType: type) + maxFrameOverheadBytes
}
}

View File

@ -296,9 +296,11 @@ struct BinaryProtocolTests {
func payloadCompression() throws {
let repeatedString = String(repeating: "This is a test message. ", count: 200)
let largePayload = Data(repeatedString.utf8)
let packet = TestHelpers.createTestPacket(payload: largePayload)
// A public message: the helper's default type (announce) is capped at
// 4 KiB decompressed, below this 4.8 KB payload.
let packet = TestHelpers.createTestPacket(type: MessageType.message.rawValue, payload: largePayload)
// Encode (should compress)
let encodedData = try #require(BinaryProtocol.encode(packet), "Failed to encode packet with large payload")

View File

@ -0,0 +1,336 @@
//
// CourierVectorTests.swift
// bitchatTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Testing
import Foundation
import CryptoKit
@testable import BitFoundation
/// Golden vectors for the courier wire format, published as
/// `docs/courier-test-vectors.json` so a second implementation can check itself
/// without running this app.
///
/// Every value asserted below is **read from that file**, not duplicated here.
/// A format change that updates only the Swift side leaves the published JSON
/// stale, and a stale JSON fails these tests — which is the only thing that
/// makes the document trustworthy to someone who cannot run it.
///
/// These cover the three ways a courier client fails *silently* — it builds,
/// connects, and delivers nothing, with no error at either end:
///
/// 1. `expiry` is milliseconds. Seconds makes every envelope read as long
/// expired, so it is dropped at deposit with nothing logged.
/// 2. The signature does not cover the wire bytes. It covers a re-encoding with
/// `ttl = 0`, `isRSR` cleared and the signature omitted, which is then
/// PKCS#7-padded. Signing the unpadded bytes produces a signature that never
/// verifies.
/// 3. The signing key is Ed25519. CryptoKit spells it `Curve25519.Signing`;
/// reaching for a "Curve25519" primitive elsewhere yields X25519 key
/// agreement instead.
struct CourierVectorTests {
// MARK: Loading the published vectors
/// The published file, located relative to this source file. It lives at
/// repo-root `docs/`, outside this package, so it cannot be a SwiftPM
/// resource the way `NoiseTestVectors.json` is — the repo already resolves
/// a repo-root path this way in `bitchatTests/LocalizationCoverageTests`.
static let vectorFileURL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // → BitFoundationTests
.deletingLastPathComponent() // → Tests
.deletingLastPathComponent() // → BitFoundation
.deletingLastPathComponent() // → localPackages
.deletingLastPathComponent() // → repo root
.appendingPathComponent("docs/courier-test-vectors.json")
struct MissingVectorFile: Error, CustomStringConvertible {
let path: String
var description: String {
"docs/courier-test-vectors.json not found at \(path). These tests assert "
+ "the published vectors; they must not silently pass without them."
}
}
static func loadVectors() throws -> Vectors {
guard FileManager.default.fileExists(atPath: vectorFileURL.path) else {
throw MissingVectorFile(path: vectorFileURL.path)
}
return try JSONDecoder().decode(Vectors.self,
from: try Data(contentsOf: vectorFileURL))
}
/// Decoded shape of the published file. `_comment` keys are prose for human
/// readers and are deliberately not decoded; every other key is, so a field
/// cannot be renamed or dropped without failing here.
struct Vectors: Decodable {
struct Inputs: Decodable {
let recipientTag: String
let noiseStaticKey: String
let ciphertextUTF8: String
let ciphertext: String
let expiryMillis: UInt64
let epochDay: UInt32
let senderID: String
let recipientID: String
let timestampMillis: UInt64
let signingSeed: String
}
struct EnvelopeTLV: Decodable {
let copies: UInt8
let prekeyID: UInt32
let encoded: String
let encodedLength: Int
}
struct CopiesClamping: Decodable {
struct Case: Decodable {
let requested: UInt8
let stored: UInt8
}
let maxCopies: UInt8
let cases: [Case]
}
struct RecipientTagDerivation: Decodable {
let label: String
let epochDay: UInt32
let expected: String
}
struct PacketSigning: Decodable {
struct Packet: Decodable {
let version: UInt8
let type: String
let ttlOnWire: UInt8
/// Declared so it cannot be renamed or dropped unnoticed; the
/// byte count it names is asserted against the real payload.
let payloadIs: String
}
struct Flags: Decodable {
let unsignedUnpadded: String
let signingPreimage: String
let signedWirePacket: String
}
let packet: Packet
let unsignedUnpaddedLength: Int
let unsignedUnpadded: String
let signingPreimageLength: Int
let signingPreimagePadByte: String
let signingPreimagePadCount: Int
let signingPreimage: String
let signedWireLength: Int
let flags: Flags
}
struct Signature: Decodable {
let publicKey: String
let signatureLength: Int
let deterministic: Bool
/// Declared for the same reason as `payloadIs`: an undeclared key
/// can vanish from the published file and every test stays green.
let verify: String
}
let inputs: Inputs
let envelopeTLV: EnvelopeTLV
let copiesClamping: CopiesClamping
let recipientTagDerivation: RecipientTagDerivation
let packetSigning: PacketSigning
let signature: Signature
}
/// Fails loudly if the published file is missing, renamed, or has lost a
/// key — otherwise a rename would skip every assertion below while the
/// suite still reported green.
@Test func publishedVectorFileLoads() throws {
let v = try Self.loadVectors()
#expect(v.inputs.ciphertextUTF8 == "courier-vector-ciphertext-0001")
#expect(v.copiesClamping.cases.isEmpty == false)
}
// MARK: Decoded inputs
private static func hex(_ string: String) throws -> Data {
try #require(Data(hexString: string), "not valid hex: \(string)")
}
/// `"0x03"` → `3`.
private static func flagByte(_ string: String) throws -> UInt8 {
let digits = string.hasPrefix("0x") ? String(string.dropFirst(2)) : string
return try #require(UInt8(digits, radix: 16), "not a hex byte: \(string)")
}
private static func envelope(from v: Vectors) throws -> CourierEnvelope {
CourierEnvelope(recipientTag: try hex(v.inputs.recipientTag),
expiry: v.inputs.expiryMillis,
ciphertext: try hex(v.inputs.ciphertext),
copies: v.envelopeTLV.copies,
prekeyID: v.envelopeTLV.prekeyID)
}
// MARK: Envelope
/// `expiry` is milliseconds since epoch, big-endian, in an 8-byte TLV.
@Test func envelopeTLVEncoding() throws {
let v = try Self.loadVectors()
// The published ciphertext hex and its UTF-8 source must agree, or the
// document contradicts itself.
#expect(try Self.hex(v.inputs.ciphertext) == Data(v.inputs.ciphertextUTF8.utf8))
let encoded = try #require(try Self.envelope(from: v).encode())
#expect(encoded.hexEncodedString() == v.envelopeTLV.encoded)
#expect(encoded.count == v.envelopeTLV.encodedLength)
// The prose in `packet.payloadIs` states this byte count. Prose that
// states a number is a claim like any other, and this is the one place
// it can be checked rather than trusted.
#expect(v.packetSigning.packet.payloadIs.contains("\(encoded.count) bytes"),
"packet.payloadIs disagrees with the real payload length")
// 0x02 carries 000001a3185c5000 == 1_800_000_000_000 ms, not seconds.
let decoded = try #require(CourierEnvelope.decode(encoded))
#expect(decoded.expiry == v.inputs.expiryMillis)
#expect(decoded.copies == v.envelopeTLV.copies)
#expect(decoded.prekeyID == v.envelopeTLV.prekeyID)
}
/// `copies` is clamped into 1...maxCopies, never rejected. An implementation
/// that rejects out-of-range values drops envelopes this one accepts.
@Test func copiesAreClampedNotRejected() throws {
let v = try Self.loadVectors()
#expect(CourierEnvelope.maxCopies == v.copiesClamping.maxCopies)
for testCase in v.copiesClamping.cases {
let stored = CourierEnvelope(recipientTag: try Self.hex(v.inputs.recipientTag),
expiry: v.inputs.expiryMillis,
ciphertext: try Self.hex(v.inputs.ciphertext),
copies: testCase.requested).copies
#expect(stored == testCase.stored,
"copies(\(testCase.requested)) expected \(testCase.stored), got \(stored)")
}
}
/// HMAC-SHA256(noiseStaticKey, "bitchat-courier-tag-v1" || BE32(epochDay)),
/// truncated to 16 bytes.
@Test func recipientTagDerivation() throws {
let v = try Self.loadVectors()
let noiseStaticKey = try Self.hex(v.inputs.noiseStaticKey)
#expect(v.recipientTagDerivation.epochDay == v.inputs.epochDay)
let tag = CourierEnvelope.recipientTag(noiseStaticKey: noiseStaticKey,
epochDay: v.recipientTagDerivation.epochDay)
#expect(tag.hexEncodedString() == v.recipientTagDerivation.expected)
#expect(tag.count == CourierEnvelope.tagLength)
// Recompute from the published `label` so that field is load-bearing
// too: the implementation's context string is private, so without this
// the document could name the wrong label and nothing would notice.
var message = Data(v.recipientTagDerivation.label.utf8)
withUnsafeBytes(of: v.recipientTagDerivation.epochDay.bigEndian) { message.append(contentsOf: $0) }
let recomputed = Data(HMAC<SHA256>.authenticationCode(
for: message, using: SymmetricKey(data: noiseStaticKey)
).prefix(CourierEnvelope.tagLength))
#expect(recomputed == tag)
}
// MARK: Packet canonicalization — the trap worth a vector
/// A real `courierEnvelope` frame: type 0x04 carrying an encoded envelope,
/// which is what a deposit actually puts on the wire.
static func envelopePacket(from v: Vectors) throws -> BitchatPacket {
BitchatPacket(type: try flagByte(v.packetSigning.packet.type),
senderID: try hex(v.inputs.senderID),
recipientID: try hex(v.inputs.recipientID),
timestamp: v.inputs.timestampMillis,
payload: try #require(try envelope(from: v).encode()),
signature: nil,
ttl: v.packetSigning.packet.ttlOnWire)
}
/// The signed pre-image is **not** the wire bytes. It zeroes `ttl`, clears
/// the `hasSignature` flag, and is PKCS#7-padded to a block boundary.
/// Both sequences are compared in full — a change to timestamp encoding,
/// payload length, or field layout has to fail here, otherwise the JSON
/// fixture could go stale while this stayed green.
@Test func signingPreimageIsTTLZeroedAndPadded() throws {
let v = try Self.loadVectors()
let signing = v.packetSigning
let packet = try Self.envelopePacket(from: v)
let unpadded = try #require(BinaryProtocol.encode(packet, padding: false))
// #require, not #expect: every assertion below subscripts these bytes,
// and `Data` subscripting past the end traps. A short frame has to fail
// the test, not crash the process and take the rest of the run with it.
try #require(unpadded.count == signing.unsignedUnpaddedLength)
#expect(unpadded.hexEncodedString() == signing.unsignedUnpadded)
let preimage = try #require(packet.toBinaryDataForSigning())
try #require(preimage.count == signing.signingPreimageLength)
#expect(preimage.hexEncodedString() == signing.signingPreimage)
// The pad byte equals the shortfall to the block boundary, and every
// pad byte equals it.
let padByte = try Self.flagByte(signing.signingPreimagePadByte)
#expect(Int(padByte) == signing.signingPreimagePadCount)
#expect(signing.unsignedUnpaddedLength + signing.signingPreimagePadCount
== signing.signingPreimageLength)
#expect(preimage.dropFirst(signing.unsignedUnpaddedLength).count
== signing.signingPreimagePadCount)
#expect(preimage.dropFirst(signing.unsignedUnpaddedLength).allSatisfy { $0 == padByte })
#expect(preimage[BinaryProtocol.Offsets.flags]
== (try Self.flagByte(signing.flags.signingPreimage)))
#expect(unpadded[BinaryProtocol.Offsets.flags]
== (try Self.flagByte(signing.flags.unsignedUnpadded)))
#expect(unpadded[2] == signing.packet.ttlOnWire && preimage[2] == 0)
#expect(unpadded[0] == signing.packet.version)
}
/// Ed25519 — CryptoKit's `Curve25519.Signing`, not X25519 key agreement.
@Test func signatureOverPreimageVerifies() throws {
let v = try Self.loadVectors()
let packet = try Self.envelopePacket(from: v)
let preimage = try #require(packet.toBinaryDataForSigning())
// Pin what is being signed. Without this the test is self-consistent by
// construction — it would sign whatever it was handed, verify it, and
// pass over a wrong canonicalization. Proven by mutating an input and
// watching this line, not the verification below, be the one that fails.
#expect(preimage.hexEncodedString() == v.packetSigning.signingPreimage)
let key = try Curve25519.Signing.PrivateKey(
rawRepresentation: try Self.hex(v.inputs.signingSeed)
)
#expect(key.publicKey.rawRepresentation.hexEncodedString() == v.signature.publicKey)
// Signature BYTES are deliberately not pinned. CryptoKit's Ed25519
// signing is randomized rather than the deterministic RFC 8032
// construction, so two signatures over identical input differ and both
// verify. A second implementation using a deterministic Ed25519 library
// will therefore not reproduce iOS's bytes — and does not need to.
// What must match is the pre-image above; verification is the contract.
let a = try key.signature(for: preimage)
let b = try key.signature(for: preimage)
#expect(v.signature.deterministic == false)
// The published instruction must keep naming the field it points at,
// so renaming `signingPreimage` cannot leave it dangling.
#expect(v.signature.verify.contains("signingPreimage"))
#expect(Data(a) != Data(b), "CryptoKit Ed25519 signing is randomized")
#expect(key.publicKey.isValidSignature(a, for: preimage))
#expect(key.publicKey.isValidSignature(b, for: preimage))
#expect(Data(a).count == BinaryProtocol.signatureSize)
#expect(Data(a).count == v.signature.signatureLength)
// On the wire the packet carries the 64-byte signature on top of the
// unsigned frame, and the flags byte now also carries hasSignature.
var signed = packet
signed.signature = Data(a)
let wire = try #require(BinaryProtocol.encode(signed, padding: false))
try #require(wire.count == v.packetSigning.signedWireLength)
#expect(wire.count == v.packetSigning.unsignedUnpaddedLength + v.signature.signatureLength)
#expect(wire[BinaryProtocol.Offsets.flags]
== (try Self.flagByte(v.packetSigning.flags.signedWirePacket)))
}
}

View File

@ -0,0 +1,62 @@
//
// DataHexTests.swift
// bitchatTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Testing
import Foundation
import BitFoundation
struct DataHexTests {
// MARK: - Accepted forms
@Test func decodes_plain_hex() {
#expect(Data(hexString: "0a1b2c")?.hexEncodedString() == "0a1b2c")
}
@Test func decodes_uppercase_hex() {
#expect(Data(hexString: "0A1B2C")?.hexEncodedString() == "0a1b2c")
}
@Test func decodes_prefixed_and_padded_hex() {
#expect(Data(hexString: "0x0a1b")?.hexEncodedString() == "0a1b")
#expect(Data(hexString: "0X0a1b")?.hexEncodedString() == "0a1b")
#expect(Data(hexString: " 0a1b ")?.hexEncodedString() == "0a1b")
}
@Test func round_trips_encoded_bytes() {
let bytes = Data((0...255).map { UInt8($0) })
#expect(Data(hexString: bytes.hexEncodedString()) == bytes)
}
// MARK: - Rejected forms
@Test func rejects_odd_length() {
#expect(Data(hexString: "0a1") == nil)
}
@Test func rejects_non_hex_characters() {
#expect(Data(hexString: "zz") == nil)
#expect(Data(hexString: "0a zz") == nil)
}
/// UInt8(_:radix:) accepts a leading sign, so "+f" parses as 0x0f unless the
/// digits are checked first. Two spellings of one identity-bearing hex
/// string decoding to the same bytes is the whole problem.
@Test func rejects_signed_byte_pairs() {
#expect(Data(hexString: "+a") == nil)
#expect(Data(hexString: "-a") == nil)
#expect(Data(hexString: "0a+b") == nil)
#expect(Data(hexString: "+a+b") == nil)
}
@Test func a_signed_pair_does_not_alias_a_genuine_key() {
let genuine = String(repeating: "0b", count: 32)
let signed = String(repeating: "+b", count: 32)
#expect(Data(hexString: genuine) != nil)
#expect(Data(hexString: signed) == nil)
}
}

View File

@ -0,0 +1,164 @@
//
// PacketPayloadLimitsTests.swift
// BitFoundationTests
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
import Testing
@testable import BitFoundation
/// Per-type payload caps at decode: a payload may reach its type's cap and no
/// further, whether it inflates from a few bytes on the wire or arrives
/// uncompressed (as a reassembled fragment stream does).
struct PacketPayloadLimitsTests {
private static let cappedTypes: [UInt8] = [
MessageType.message.rawValue,
MessageType.groupMessage.rawValue,
MessageType.fragment.rawValue,
MessageType.announce.rawValue,
MessageType.requestSync.rawValue,
MessageType.courierEnvelope.rawValue,
MessageType.nostrCarrier.rawValue,
MessageType.boardPost.rawValue,
MessageType.noiseHandshake.rawValue,
0x7F // unassigned: future types keep a v1 frame's worth
]
@Test(arguments: cappedTypes)
func compressedPayloadInflatesToItsTypeCapAndNoFurther(type: UInt8) throws {
let cap = PacketPayloadLimits.maxPayloadBytes(forType: type)
#expect(cap < FileTransferLimits.maxFramedFileBytes)
// v1 frames carry a 16-bit original size, so caps below that are
// exercised on v1 (the default for everything but media) too.
let version: UInt8 = cap + 1 <= Int(UInt16.max) ? 1 : 2
let atCap = try encodeCompressed(type: type, payloadSize: cap, version: version)
#expect(BinaryProtocol.decode(atCap)?.payload.count == cap)
let pastCap = try encodeCompressed(type: type, payloadSize: cap + 1, version: version)
#expect(BinaryProtocol.decode(pastCap) == nil)
}
@Test(arguments: cappedTypes)
func uncompressedPayloadIsCappedLikeACompressedOne(type: UInt8) throws {
let cap = PacketPayloadLimits.maxPayloadBytes(forType: type)
let version: UInt8 = cap + 1 <= Int(UInt16.max) ? 1 : 2
let atCap = try encodeUncompressed(type: type, payloadSize: cap, version: version)
#expect(BinaryProtocol.decode(atCap)?.payload.count == cap)
let pastCap = try encodeUncompressed(type: type, payloadSize: cap + 1, version: version)
#expect(BinaryProtocol.decode(pastCap) == nil)
}
@Test func onlyMediaTypesReachTheFramedFileCeiling() throws {
let size = FileTransferLimits.maxFramedFileBytes
for mediaType in [MessageType.fileTransfer, .noiseEncrypted] {
let frame = try encodeCompressed(type: mediaType.rawValue, payloadSize: size, version: 2)
#expect(BinaryProtocol.decode(frame)?.payload.count == size)
let raw = try encodeUncompressed(type: mediaType.rawValue, payloadSize: size, version: 2)
#expect(BinaryProtocol.decode(raw)?.payload.count == size)
}
// The same ~1 KB on air as a public message would have pinned ~1.1 MB.
let message = try encodeCompressed(type: MessageType.message.rawValue, payloadSize: size, version: 2)
#expect(BinaryProtocol.decode(message) == nil)
}
@Test func frameCeilingCoversTheLargestFrameThatStillDecodes() throws {
// An uncompressed payload at its cap with everything optional at its
// widest (recipient, a 255-hop route, signature), padded as iOS pads
// before fragmenting. Reassembly must never cut off such a frame.
for type in Self.cappedTypes + [MessageType.fileTransfer.rawValue] {
let cap = PacketPayloadLimits.maxPayloadBytes(forType: type)
let packet = BitchatPacket(
type: type,
senderID: Data(repeating: 0x11, count: BinaryProtocol.senderIDSize),
recipientID: Data(repeating: 0x22, count: BinaryProtocol.recipientIDSize),
timestamp: 1_740_000_000_000,
payload: diversePayload(count: cap),
signature: Data(repeating: 0x33, count: BinaryProtocol.signatureSize),
ttl: 7,
version: 2,
route: (0..<255).map { Data(repeating: UInt8($0), count: BinaryProtocol.senderIDSize) }
)
let raw = try #require(BinaryProtocol.encode(packet, padding: true))
#expect(raw[BinaryProtocol.Offsets.flags] & BinaryProtocol.Flags.isCompressed == 0)
#expect(BinaryProtocol.decode(raw)?.payload.count == cap)
#expect(raw.count <= PacketPayloadLimits.maxFrameBytes(forType: type))
}
}
/// AnnounceV2 isn't emitted by the app yet, so its largest payload is
/// checked here rather than in the app's interop tests.
@Test func largestAnnounceV2PayloadDecodesWithHeadroom() throws {
let payload = try #require(AnnounceV2Packet(
epoch: 1,
tagBlock: Data(repeating: 0x5A, count: AnnounceV2Packet.tagBlockLength),
capabilities: PeerCapabilities(rawValue: .max),
bridgeGeohash: "9q8yyk8yuv12"
).encode())
#expect(payload.count * 2 <= PacketPayloadLimits.maxPayloadBytes(forType: MessageType.announceV2.rawValue))
let packet = BitchatPacket(
type: MessageType.announceV2.rawValue,
senderID: Data(repeating: 0x11, count: BinaryProtocol.senderIDSize),
recipientID: nil,
timestamp: 1_740_000_000_000,
payload: payload,
signature: Data(repeating: 0x33, count: BinaryProtocol.signatureSize),
ttl: 7,
version: 1
)
let frame = try #require(BinaryProtocol.encode(packet, padding: true))
#expect(BinaryProtocol.decode(frame)?.payload == payload)
}
/// Every byte value once, then zeros: 100% byte diversity, so the encoder
/// leaves it uncompressed, while the zero run would still compress well
/// inside fragments (the reassembly bypass shape).
private func diversePayload(count: Int) -> Data {
var payload = Data((0...255).map { UInt8($0) }.prefix(count))
payload.append(Data(count: count - payload.count))
return payload
}
private func encodeUncompressed(type: UInt8, payloadSize: Int, version: UInt8) throws -> Data {
let packet = BitchatPacket(
type: type,
senderID: Data(repeating: 0x11, count: BinaryProtocol.senderIDSize),
recipientID: nil,
timestamp: 1_740_000_000_000,
payload: diversePayload(count: payloadSize),
signature: nil,
ttl: 7,
version: version
)
let frame = try #require(BinaryProtocol.encode(packet, padding: false))
#expect(frame[BinaryProtocol.Offsets.flags] & BinaryProtocol.Flags.isCompressed == 0)
return frame
}
/// Encodes a maximally compressible payload and checks that the frame
/// really went out compressed, so decode exercises the inflate path.
private func encodeCompressed(type: UInt8, payloadSize: Int, version: UInt8) throws -> Data {
let packet = BitchatPacket(
type: type,
senderID: Data(repeating: 0x11, count: BinaryProtocol.senderIDSize),
recipientID: nil,
timestamp: 1_740_000_000_000,
payload: Data(repeating: 0x41, count: payloadSize),
signature: nil,
ttl: 7,
version: version
)
let frame = try #require(BinaryProtocol.encode(packet, padding: false))
#expect(frame.count < payloadSize / 10)
#expect(frame[BinaryProtocol.Offsets.flags] & BinaryProtocol.Flags.isCompressed != 0)
return frame
}
}

View File

@ -362,6 +362,10 @@ struct PeerIDTests {
@Test func rejects_invalid_characters() {
#expect(!PeerID(str: "peer!@#").isValid)
#expect(!PeerID(str: "gggggggggggggggg").isValid) // not hex for short form
// A 64-character id is only valid because it decodes to a Noise key, so
// it has to be rejected on the same grounds a short one is.
#expect(!PeerID(str: String(repeating: "+b", count: 32)).isValid)
#expect(!PeerID(str: String(repeating: "gg", count: 32)).isValid)
}
@Test func rejects_too_long() {
@ -388,6 +392,13 @@ struct PeerIDTests {
let badPeerID = PeerID(str: bad)
#expect(!badPeerID.isNoiseKeyHex)
#expect(badPeerID.noiseKey == nil)
// isHex and isNoiseKeyHex have to agree: a signed pair is not hex, so it
// must not decode to a Noise key either.
let signedPeerID = PeerID(str: String(repeating: "+b", count: 32))
#expect(!signedPeerID.isHex)
#expect(!signedPeerID.isNoiseKeyHex)
#expect(signedPeerID.noiseKey == nil)
}
@Test func prefixes() {

View File

@ -0,0 +1,89 @@
import re
from pathlib import Path
import unittest
REPOSITORY_ROOT = Path(__file__).resolve().parents[2]
WORKFLOW_PATH = REPOSITORY_ROOT / ".github/workflows/validate_georelays.yml"
RELAY_DATA_PATH = "relays/online_relays_gps.csv"
VALIDATOR_PATH = "scripts/validate_georelays.py"
class ValidateGeoRelaysWorkflowTests(unittest.TestCase):
"""The relay directory is reviewed data. A pull request that changes it must
be judged by the base branch's validator, on the bytes that would actually
merge, and the job that does so must not run anything the pull request
wrote -- the `gate` job is the trust boundary, `proposed-validator` is not.
"""
@classmethod
def setUpClass(cls) -> None:
cls.workflow = WORKFLOW_PATH.read_text(encoding="utf-8")
# Comments explain why a construct is absent and would otherwise trip
# the assertions looking for it, so directives are checked without them.
cls.directives = "\n".join(
line for line in cls.workflow.splitlines() if not line.lstrip().startswith("#")
)
def job(self, name: str) -> str:
block = re.search(rf"^ {name}:\n(.*?)(?=^ \S|\Z)", self.directives, re.MULTILINE | re.DOTALL)
self.assertIsNotNone(block, f"no {name} job in the workflow")
return block.group(1)
def test_runs_on_untrusted_pull_request_trigger(self) -> None:
self.assertIn("pull_request:", self.directives)
# pull_request_target would run PR-authored code with repository secrets.
self.assertNotIn("pull_request_target", self.directives)
def test_no_job_holds_a_write_scope(self) -> None:
self.assertIn("permissions:\n contents: read", self.directives)
write_scope = re.search(r"^\s*[\w-]+:\s*write\s*$", self.directives, re.MULTILINE)
self.assertIsNone(write_scope, "a job running PR-authored code must not hold a write scope")
def test_checkout_does_not_persist_credentials(self) -> None:
self.assertEqual(2, self.directives.count("persist-credentials: false"))
def test_relay_data_changes_trigger_the_workflow(self) -> None:
paths_block = re.search(r"paths:\n((?:\s+- .+\n)+)", self.directives)
self.assertIsNotNone(paths_block)
self.assertIn(RELAY_DATA_PATH, paths_block.group(1))
self.assertIn(VALIDATOR_PATH, paths_block.group(1))
def test_gate_checks_out_the_reviewed_base(self) -> None:
# Checking out the merge ref would put the pull request's validator and
# tests in the gate's workspace.
self.assertIn("ref: ${{ github.event.pull_request.base.sha }}", self.job("gate"))
def test_gate_runs_nothing_the_pull_request_wrote(self) -> None:
gate = self.job("gate")
self.assertNotIn("unittest discover", gate)
# The candidate is read as a git object, never from the worktree, so
# code running earlier in the job cannot substitute the bytes validated.
self.assertIn('git show "${HEAD_SHA}:' + RELAY_DATA_PATH + '"', gate)
self.assertIn('--input "$RUNNER_TEMP/candidate.csv"', gate)
self.assertNotIn(f"--input {RELAY_DATA_PATH}", gate)
def test_gate_pins_both_inputs_to_the_event(self) -> None:
gate = self.job("gate")
self.assertIn("HEAD_SHA: ${{ github.event.pull_request.head.sha }}", gate)
# A head that moved after the event means these bytes are not the ones
# this run was asked about.
self.assertIn('if [[ "$fetched_sha" != "$HEAD_SHA" ]]; then', gate)
self.assertIn("exit 1", gate)
def test_gate_validation_cannot_write_to_the_reviewed_file(self) -> None:
gate = self.job("gate")
self.assertIn('--output "$RUNNER_TEMP/', gate)
self.assertNotIn(f"--output {RELAY_DATA_PATH}", gate)
def test_proposed_validator_is_exercised_against_the_real_directory(self) -> None:
# Unit-test fixtures are small and synthetic; a new constraint can pass
# them while invalidating the committed directory.
job = self.job("proposed-validator")
self.assertIn("unittest discover", job)
self.assertIn(f"--input {RELAY_DATA_PATH}", job)
self.assertIn('git show "${BASE_SHA}:' + RELAY_DATA_PATH + '"', job)
if __name__ == "__main__":
unittest.main()