Fix location notes and mesh notice correctness bugs (#1963)

* Fix location notes and mesh notice correctness bugs

- Scope BoardStore orphan tombstone eviction by (postID, authorSigningKey) and isOrphan so an attacker cannot evict a genuine author's matched tombstone and resurrect deleted mesh notices; use saturating arithmetic on deletedAt retention.
- Suppress postArrivals when a newly ingested board post is immediately evicted by per-author or global quota.
- Filter expired board posts in BoardManager, UnifiedNotices, and ContentHeaderView, and add BoardStore.pruneExpired() on notice/feed appear.
- Fix merged delete of bridged geo notices: tag NIP-09 deletions with geohash, retract the bridged event locally via LocationNotesPool.retractEvent, and fall back to deleting matching own bridged notes after relaunch.
- Normalize/validate geohash in BoardManager.createPost, gate live Nostr bridging on LocationNotesSettings.enabled and activationAllowed, and clear bridgedEventIDs on panic wipe.
- Track bounded author-scoped pending NIP-09 deletions in LocationNotesManager so kind-5 deletions arriving before kind-1/kind-7 backfill suppress matching-author events; persist local deletes in deletedEventIDs across refresh and tag with note.geohash.
- Guard LocationNotesManager subscribe callbacks by subscriptionID, clear reactionMetaByEventID on refresh, and gate send/sendFeedPost/toggleReaction/delete/postDrop on network activationAllowed when not uplinked via BLE gateway.
- Hold NearbyNotesCounter active in PlacesTabView so the Location Notes card and building header indicator show live counts, and mark geohash board alerts seen when opening Location Notes or Place Feed.

* Fix Periphery assign-only warning and make async board tests deterministic

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
This commit is contained in:
jackandjack authored and GitHub committed 2026-11-28 15:15:39 -10:00
1 parent aae990f7ee
commit d783e8cc24
12 files changed
+743 -62

No files matched your search

+45 -9
View File
@@ -19,6 +19,8 @@ final class BoardManager: ObservableObject {
@Published private(set) var posts: [BoardPostPacket] = []
private let transport: Transport
private let store: BoardStore
private let now: () -> Date
/// Board broadcast rides the mesh only; absent on other transports.
private var boardTransport: MeshBoardBroadcasting? { transport as? MeshBoardBroadcasting }
/// Publishes a bridged kind-1 note (expiring with the board post via
@@ -32,14 +34,18 @@ final class BoardManager: ObservableObject {
/// Nostr copy is left to expire with relay retention.
private var bridgedEventIDs: [Data: String] = [:]
private var cancellable: AnyCancellable?
private var wipeCancellable: AnyCancellable?
init(
transport: Transport,
store: BoardStore = .shared,
now: @escaping () -> Date = Date.init,
publishToNostr: ((String, String, String, UInt64, Bool) -> String?)? = nil,
deleteFromNostr: ((String, String) -> Void)? = nil
) {
self.transport = transport
self.store = store
self.now = now
self.publishToNostr = publishToNostr ?? Self.livePublishToNostr
self.deleteFromNostr = deleteFromNostr ?? Self.liveDeleteFromNostr
cancellable = store.$postsSnapshot
@@ -47,12 +53,25 @@ final class BoardManager: ObservableObject {
.sink { [weak self] snapshot in
self?.posts = snapshot
}
wipeCancellable = store.didWipe
.receive(on: DispatchQueue.main)
.sink { [weak self] in
self?.bridgedEventIDs.removeAll(keepingCapacity: false)
}
}
/// Posts for one board context, urgent first, then newest first.
/// Triggers an expiry sweep in the underlying store so `posts` stays fresh
/// even when no new wire packets or gossip sync rounds have arrived.
func pruneExpired() {
store.pruneExpired()
}
/// Posts for one board context, unexpired only, urgent first, then newest first.
func posts(forGeohash geohash: String) -> [BoardPostPacket] {
posts
.filter { $0.geohash == geohash }
let normalizedGeohash = geohash.lowercased()
let nowMs = UInt64(max(0, now().timeIntervalSince1970) * 1000)
return posts
.filter { $0.geohash == normalizedGeohash && $0.expiresAt > nowMs }
.sorted {
if $0.isUrgent != $1.isUrgent { return $0.isUrgent }
return $0.createdAt > $1.createdAt
@@ -78,6 +97,13 @@ final class BoardManager: ObservableObject {
trimmed.utf8.count <= BoardWireConstants.contentMaxBytes else {
return false
}
let normalizedGeohash = geohash.lowercased()
guard normalizedGeohash.isEmpty || (
normalizedGeohash.count <= BoardWireConstants.geohashMaxLength
&& Geohash.isValidGeohash(normalizedGeohash)
) else {
return false
}
let signingKey = transport.noiseSigningPublicKeyData()
guard signingKey.count == BoardWireConstants.signingKeyLength else { return false }
@@ -85,7 +111,7 @@ final class BoardManager: ObservableObject {
while cleanNickname.utf8.count > BoardWireConstants.nicknameMaxBytes {
cleanNickname.removeLast()
}
let createdAt = UInt64(Date().timeIntervalSince1970 * 1000)
let createdAt = UInt64(max(0, now().timeIntervalSince1970) * 1000)
let lifetimeMs = min(
UInt64(max(1, expiryDays)) * 24 * 60 * 60 * 1000,
BoardWireConstants.maxLifetimeMs
@@ -101,7 +127,7 @@ final class BoardManager: ObservableObject {
let signingBytes = BoardPostPacket.signingBytes(
postID: postID,
geohash: geohash,
geohash: normalizedGeohash,
content: trimmed,
authorSigningKey: signingKey,
authorNickname: cleanNickname,
@@ -115,7 +141,7 @@ final class BoardManager: ObservableObject {
}
let post = BoardPostPacket(
postID: postID,
geohash: geohash,
geohash: normalizedGeohash,
content: trimmed,
authorSigningKey: signingKey,
authorNickname: cleanNickname,
@@ -128,7 +154,7 @@ final class BoardManager: ObservableObject {
// Nostr bridge: geohash posts also go out as kind-1 location notes so
// online users see them. Remember the event id for merged deletes.
if !geohash.isEmpty, let eventID = publishToNostr(trimmed, geohash, cleanNickname, expiresAt, urgent) {
if !normalizedGeohash.isEmpty, let eventID = publishToNostr(trimmed, normalizedGeohash, cleanNickname, expiresAt, urgent) {
bridgedEventIDs[postID] = eventID
}
return true
@@ -138,7 +164,7 @@ final class BoardManager: ObservableObject {
@discardableResult
func deletePost(_ post: BoardPostPacket) -> Bool {
guard isOwnPost(post) else { return false }
let deletedAt = UInt64(Date().timeIntervalSince1970 * 1000)
let deletedAt = UInt64(max(0, now().timeIntervalSince1970) * 1000)
let signingBytes = BoardTombstonePacket.signingBytes(postID: post.postID, deletedAt: deletedAt)
guard let signature = transport.noiseSignData(signingBytes) else {
SecureLogger.error("Board: failed to sign tombstone", category: .session)
@@ -161,6 +187,9 @@ final class BoardManager: ObservableObject {
}
private static func livePublishToNostr(content: String, geohash: String, nickname: String, expiresAtMs: UInt64, urgent: Bool) -> String? {
guard LocationNotesSettings.enabled, NetworkActivationService.shared.activationAllowed else {
return nil
}
let relays = GeoRelayDirectory.shared.closestRelays(toGeohash: geohash, count: TransportConfig.nostrGeoRelayCount)
guard !relays.isEmpty else {
SecureLogger.debug("Board: no geo relays for \(geohash); skipping Nostr bridge", category: .session)
@@ -185,11 +214,18 @@ final class BoardManager: ObservableObject {
}
private static func liveDeleteFromNostr(eventID: String, geohash: String) {
// Retract locally right away so removing the board post doesn't
// uncover the echoed kind-1 Nostr copy in UnifiedNotices.merge.
LocationNotesPool.shared.retractEvent(id: eventID, geohash: geohash)
let relays = GeoRelayDirectory.shared.closestRelays(toGeohash: geohash, count: TransportConfig.nostrGeoRelayCount)
guard !relays.isEmpty else { return }
do {
let identity = try NostrIdentityBridge.shared.deriveIdentity(forGeohash: geohash)
let deletion = try NostrProtocol.createDeleteEvent(ofEventID: eventID, senderIdentity: identity)
let deletion = try NostrProtocol.createDeleteEvent(
ofEventID: eventID,
senderIdentity: identity,
geohash: geohash
)
NostrRelayManager.shared.sendEvent(deletion, to: relays)
} catch {
SecureLogger.error("Board: failed to delete bridged Nostr note: \(error)", category: .session)
+24 -4
View File
@@ -128,7 +128,8 @@ final class BoardStore {
let result = ingestLocked(wire, packet: packet, rawPacket: rawPacket, nowMs: nowMs)
if result == .accepted {
persistLocked()
if case .post(let post) = wire {
if case .post(let post) = wire,
posts.contains(where: { $0.post.postID == post.postID }) {
DispatchQueue.main.async { [weak self] in
self?.postArrivals.send(post)
}
@@ -160,6 +161,20 @@ final class BoardStore {
// MARK: - Maintenance
/// Drops expired posts and tombstones, updating `postsSnapshot` and disk
/// storage if anything changed.
func pruneExpired() {
let nowMs = currentMs()
queue.sync {
let postsBefore = posts.count
let tombstonesBefore = tombstones.count
pruneExpiredLocked(nowMs: nowMs)
if posts.count != postsBefore || tombstones.count != tombstonesBefore {
persistLocked()
}
}
}
/// Panic wipe: drop all board data from memory and disk.
func wipe() {
queue.sync {
@@ -264,8 +279,11 @@ final class BoardStore {
// cannot pin a tombstone past any legal expiry) and the receive time:
// deletedAt is sender-chosen, so a far-future value must not retain
// the tombstone longer than any post still able to arrive could live.
let (deletedPlusLifetime, deletedOverflow) = tombstone.deletedAt
.addingReportingOverflow(Limits.orphanTombstoneLifetimeMs)
let claimedRetain = deletedOverflow ? UInt64.max : deletedPlusLifetime
let maxRetain = min(
tombstone.deletedAt &+ Limits.orphanTombstoneLifetimeMs,
claimedRetain,
nowMs &+ Limits.orphanTombstoneLifetimeMs &+ Limits.clockSkewMs
)
let retainUntil: UInt64
@@ -323,8 +341,10 @@ final class BoardStore {
private func removeTombstonesLocked(_ victims: ArraySlice<StoredTombstone>) {
guard !victims.isEmpty else { return }
let victimIDs = Set(victims.map { $0.tombstone.postID })
tombstones.removeAll { victimIDs.contains($0.tombstone.postID) }
let victimKeys = Set(victims.map { $0.tombstone.postID + $0.tombstone.authorSigningKey })
tombstones.removeAll {
$0.isOrphan && victimKeys.contains($0.tombstone.postID + $0.tombstone.authorSigningKey)
}
}
private func evictOldestLocked(from candidates: [StoredPost], keep: Int) {
+32 -12
View File
@@ -102,23 +102,43 @@ enum UnifiedNotices {
/// heuristically by content + author within a time window.
static let bridgeDedupeWindow: TimeInterval = 15 * 60
/// Whether `note` looks like the Nostr-bridged copy of `post`: exact
/// geohash match, identical content and normalized nickname, within
/// `bridgeDedupeWindow`.
static func isBridgedCopy(post: BoardPostPacket, note: LocationNotesManager.Note) -> Bool {
let noteNickname = note.nickname?.trimmedOrNilIfEmpty ?? "anon"
let postNickname = post.authorNickname.trimmedOrNilIfEmpty ?? "anon"
return post.geohash == note.geohash
&& post.content == note.content
&& postNickname == noteNickname
&& abs(Date(timeIntervalSince1970: TimeInterval(post.createdAt) / 1000).timeIntervalSince(note.createdAt)) <= bridgeDedupeWindow
}
/// Returns board posts and notes as one list, urgent posts first, then
/// newest first. Notes that look like bridged copies of a board post are
/// dropped — the board copy wins because it carries urgency and supports
/// merged deletion. The geohash must match exactly: the notes
/// subscription also surfaces neighboring cells, and a same-text note
/// from a neighbor is not the bridged copy.
static func merge(posts: [BoardPostPacket], notes: [LocationNotesManager.Note]) -> [NoticeItem] {
var items = posts.map(NoticeItem.init(post:))
for note in notes {
let noteNickname = note.nickname?.trimmedOrNilIfEmpty ?? "anon"
let isBridgedCopy = posts.contains { post in
post.geohash == note.geohash
&& post.content == note.content
&& (post.authorNickname.trimmedOrNilIfEmpty ?? "anon") == noteNickname
&& abs(Date(timeIntervalSince1970: TimeInterval(post.createdAt) / 1000).timeIntervalSince(note.createdAt)) <= bridgeDedupeWindow
}
if !isBridgedCopy {
/// from a neighbor is not the bridged copy. When `now` is supplied,
/// expired board posts and NIP-40 notes are excluded.
static func merge(
posts: [BoardPostPacket],
notes: [LocationNotesManager.Note],
now: Date? = nil
) -> [NoticeItem] {
let livePosts: [BoardPostPacket]
let liveNotes: [LocationNotesManager.Note]
if let now {
let nowMs = UInt64(max(0, now.timeIntervalSince1970) * 1000)
livePosts = posts.filter { $0.expiresAt == 0 || $0.expiresAt > nowMs }
liveNotes = notes.filter { $0.expiresAt.map { $0 > now } ?? true }
} else {
livePosts = posts
liveNotes = notes
}
var items = livePosts.map(NoticeItem.init(post:))
for note in liveNotes {
if !livePosts.contains(where: { isBridgedCopy(post: $0, note: note) }) {
items.append(NoticeItem(note: note))
}
}
+139 -34
View File
@@ -27,6 +27,9 @@ struct LocationNotesDependencies {
/// "loaded, empty" from "still connecting (Tor warming up)" when EOSE
/// fires without data. Defaults to true so tests keep legacy behavior.
var anyRelayConnected: @MainActor (_ relayUrls: [String]) -> Bool = { _ in true }
/// Whether outbound Nostr network activation is currently permitted.
/// Defaults to true so existing unit tests keep legacy behavior.
var activationAllowed: @MainActor () -> Bool = { true }
/// Persistent primary Nostr identity used only when the user opts into
/// posting with their public handle (`.publicHandle`).
var publicIdentity: () throws -> NostrIdentity? = { nil }
@@ -91,6 +94,9 @@ struct LocationNotesDependencies {
anyRelayConnected: { relayUrls in
NostrRelayManager.shared.isAnyRelayConnected(among: relayUrls)
},
activationAllowed: {
NetworkActivationService.shared.activationAllowed
},
publicIdentity: {
try idBridge.getCurrentNostrIdentity()
},
@@ -226,8 +232,14 @@ final class LocationNotesManager: ObservableObject {
private var ownReactionEventIDs: [String: String] = [:]
/// Maps kind-7 reaction event ID -> (targetID, emoji, actorPubkey) so inbound NIP-09 deletions can retract reactions.
private var reactionMetaByEventID: [String: (targetID: String, emoji: String, actorPubkey: String)] = [:]
/// Event IDs retracted by verified NIP-09 kind-5 deletions (prevents out-of-order replay resurrection).
/// Event IDs retracted by verified NIP-09 kind-5 deletions or local deletes
/// (prevents out-of-order replay or refresh resurrection).
private var deletedEventIDs = Set<String>()
private var deletedEventOrder: [String] = []
/// NIP-09 kind-5 deletions that arrived before their target kind-1/kind-7
/// event (normal for descending `created_at` relay backfill): targetID -> deleter pubkeys.
private var pendingDeletionsByTargetID: [String: Set<String>] = [:]
private var pendingDeletionOrder: [String] = []
private var directoryUpdateCancellable: AnyCancellable?
private var networkAvailableCancellable: AnyCancellable?
@@ -238,6 +250,7 @@ final class LocationNotesManager: ObservableObject {
private let maxNotesInMemory = 500 // Defensive cap (relay limit is 200)
private let maxRepliesPerThread = 200
private let maxTrackedReactionEvents = 2_000
private let maxTrackedDeletions = 2_000
/// Short 4-char hex suffix of our unlinkable per-place pubkey, for composer attribution.
var ownIdentitySuffix: String? {
@@ -375,6 +388,7 @@ final class LocationNotesManager: ObservableObject {
reactionActorsByTarget.removeAll()
reactionEmojiOrderByTarget.removeAll()
ownReactionEventIDs.removeAll()
reactionMetaByEventID.removeAll()
subscribe()
}
@@ -415,10 +429,10 @@ final class LocationNotesManager: ObservableObject {
let validGeohashes = Set(allGeohashes.map { $0.lowercased() })
dependencies.subscribe(filter, subID, relays, { [weak self] event in
guard let self = self else { return }
guard let self, self.subscriptionID == subID else { return }
self.ingestInboundEvent(event, validGeohashes: validGeohashes, fromGateway: false)
}, { [weak self] in
guard let self = self else { return }
guard let self, self.subscriptionID == subID else { return }
self.initialLoadComplete = true
guard self.state != .noRelays else { return }
// EOSE with no data and zero connected target relays means the
@@ -460,7 +474,13 @@ final class LocationNotesManager: ObservableObject {
@discardableResult
private func ingestTextNote(_ event: NostrEvent, validGeohashes: Set<String>) -> String? {
let normalizedID = event.id.lowercased()
let authorPubkey = event.pubkey.lowercased()
guard !noteIDs.contains(normalizedID), !deletedEventIDs.contains(normalizedID) else { return nil }
if pendingDeletionsByTargetID[normalizedID]?.contains(authorPubkey) == true {
pendingDeletionsByTargetID.removeValue(forKey: normalizedID)
recordDeletedEventID(normalizedID)
return nil
}
// Single pass over tags: match any of our 9 cells + extract nick/expiration/urgent/teleport.
var matchedGeohash: String?
@@ -548,10 +568,16 @@ final class LocationNotesManager: ObservableObject {
@discardableResult
private func ingestReaction(_ event: NostrEvent, validGeohashes: Set<String>) -> String? {
let normalizedEventID = event.id.lowercased()
let authorPubkey = event.pubkey.lowercased()
guard !reactionEventIDs.contains(normalizedEventID),
!deletedEventIDs.contains(normalizedEventID) else {
return nil
}
if pendingDeletionsByTargetID[normalizedEventID]?.contains(authorPubkey) == true {
pendingDeletionsByTargetID.removeValue(forKey: normalizedEventID)
recordDeletedEventID(normalizedEventID)
return nil
}
// Require the reaction to belong to one of our 9 subscribed cells.
guard let matchedGeohash = event.tags.first(where: { tag in
@@ -563,7 +589,6 @@ final class LocationNotesManager: ObservableObject {
guard let parsed = NostrProtocol.parseReactionTarget(from: event) else { return nil }
recordReactionEventID(normalizedEventID)
let authorPubkey = event.pubkey.lowercased()
applyReaction(
targetID: parsed.targetEventID,
emoji: parsed.emoji,
@@ -575,7 +600,9 @@ final class LocationNotesManager: ObservableObject {
/// Processes an inbound NIP-09 kind-5 deletion event. Verifies that the
/// deletion author matches the original reaction or note author before
/// retracting the reaction or removing the note.
/// retracting the reaction or removing the note. When the target event has
/// not yet arrived (common during newest-first relay backfill), records a
/// pending author-scoped deletion so the target is suppressed on arrival.
private func ingestDeletion(_ event: NostrEvent) {
let deleterPubkey = event.pubkey.lowercased()
for tag in event.tags where tag.count >= 2 && tag[0].lowercased() == "e" {
@@ -585,7 +612,7 @@ final class LocationNotesManager: ObservableObject {
// 1. Retract a tracked kind-7 reaction if signed by the same author.
if let meta = reactionMetaByEventID[targetID] {
guard meta.actorPubkey == deleterPubkey else { continue }
deletedEventIDs.insert(targetID)
recordDeletedEventID(targetID)
reactionMetaByEventID.removeValue(forKey: targetID)
removeReaction(targetID: meta.targetID, emoji: meta.emoji, actorPubkey: meta.actorPubkey)
let ownKey = Self.reactionTargetKey(targetID: meta.targetID, emoji: meta.emoji)
@@ -598,14 +625,16 @@ final class LocationNotesManager: ObservableObject {
// 2. Remove a top-level note or reply if signed by the same author.
if let noteIndex = notes.firstIndex(where: { $0.id == targetID }) {
guard notes[noteIndex].pubkey.lowercased() == deleterPubkey else { continue }
deletedEventIDs.insert(targetID)
recordDeletedEventID(targetID)
notes.remove(at: noteIndex)
continue
}
var matchedReply = false
for (rootID, replies) in repliesByRootID {
if let replyIndex = replies.firstIndex(where: { $0.id == targetID }) {
matchedReply = true
guard replies[replyIndex].pubkey.lowercased() == deleterPubkey else { break }
deletedEventIDs.insert(targetID)
recordDeletedEventID(targetID)
var updated = replies
updated.remove(at: replyIndex)
if updated.isEmpty {
@@ -616,6 +645,44 @@ final class LocationNotesManager: ObservableObject {
break
}
}
if matchedReply {
continue
}
// 3. Target has not arrived yet (e.g. descending relay backfill):
// remember the deleter pubkey so a matching event is dropped on ingest.
recordPendingDeletion(targetID: targetID, deleterPubkey: deleterPubkey)
}
}
/// Immediately removes a locally known note/reply/reaction by event ID and
/// suppresses future replay (used when deleting a bridged board post so its
/// echoed kind-1 copy disappears in lockstep).
func retractLocalEvent(id eventID: String) {
let targetID = eventID.lowercased()
recordDeletedEventID(targetID)
if let meta = reactionMetaByEventID.removeValue(forKey: targetID) {
removeReaction(targetID: meta.targetID, emoji: meta.emoji, actorPubkey: meta.actorPubkey)
let ownKey = Self.reactionTargetKey(targetID: meta.targetID, emoji: meta.emoji)
if ownReactionEventIDs[ownKey] == targetID {
ownReactionEventIDs.removeValue(forKey: ownKey)
}
return
}
if notes.contains(where: { $0.id == targetID }) {
notes.removeAll { $0.id == targetID }
return
}
for (rootID, replies) in repliesByRootID {
if replies.contains(where: { $0.id == targetID }) {
let remaining = replies.filter { $0.id != targetID }
if remaining.isEmpty {
repliesByRootID.removeValue(forKey: rootID)
} else {
repliesByRootID[rootID] = remaining
}
return
}
}
}
@@ -744,8 +811,36 @@ final class LocationNotesManager: ObservableObject {
reactionEventIDs = ownIDs.union([id])
reactionMetaByEventID = reactionMetaByEventID.filter { reactionEventIDs.contains($0.key) }
}
if deletedEventIDs.count > maxTrackedReactionEvents {
deletedEventIDs.removeAll(keepingCapacity: false)
}
private func recordDeletedEventID(_ id: String) {
if deletedEventIDs.insert(id).inserted {
deletedEventOrder.append(id)
if deletedEventOrder.count > maxTrackedDeletions {
let overflow = deletedEventOrder.count - maxTrackedDeletions
for evicted in deletedEventOrder.prefix(overflow) {
deletedEventIDs.remove(evicted)
}
deletedEventOrder.removeFirst(overflow)
}
}
}
private func recordPendingDeletion(targetID: String, deleterPubkey: String) {
let isNewTarget = pendingDeletionsByTargetID[targetID] == nil
var deleters = pendingDeletionsByTargetID[targetID] ?? []
guard deleters.count < 8 || deleters.contains(deleterPubkey) else { return }
deleters.insert(deleterPubkey)
pendingDeletionsByTargetID[targetID] = deleters
if isNewTarget {
pendingDeletionOrder.append(targetID)
if pendingDeletionOrder.count > maxTrackedDeletions {
let overflow = pendingDeletionOrder.count - maxTrackedDeletions
for evicted in pendingDeletionOrder.prefix(overflow) {
pendingDeletionsByTargetID.removeValue(forKey: evicted)
}
pendingDeletionOrder.removeFirst(overflow)
}
}
}
@@ -793,10 +888,10 @@ final class LocationNotesManager: ObservableObject {
) {
guard let trimmed = content.trimmedOrNilIfEmpty else { return }
let relays = dependencies.relayLookup(geohash, TransportConfig.nostrGeoRelayCount)
guard !relays.isEmpty else {
state = .noRelays
guard dependencies.activationAllowed(), !relays.isEmpty else {
state = relays.isEmpty ? .noRelays : .connecting
errorMessage = Strings.noRelays
SecureLogger.warning("LocationNotesManager: send blocked, no geo relays for geohash=\(geohash)", category: .session)
SecureLogger.warning("LocationNotesManager: send blocked, relays unavailable for geohash=\(geohash)", category: .session)
return
}
do {
@@ -884,19 +979,21 @@ final class LocationNotesManager: ObservableObject {
attachments: attachments,
createdAt: dependencies.now()
)
let uplinked = !dependencies.anyRelayConnected(relays)
let canSendToRelays = dependencies.activationAllowed() && !relays.isEmpty
let hasConnectedRelays = canSendToRelays && dependencies.anyRelayConnected(relays)
let uplinked = !hasConnectedRelays
&& dependencies.uplinkViaMesh(event, geohash)
guard !relays.isEmpty || uplinked else {
state = .noRelays
guard canSendToRelays || uplinked else {
state = relays.isEmpty ? .noRelays : .connecting
errorMessage = Strings.noRelays
return false
}
if mirrorToDefaultRelays {
if canSendToRelays && mirrorToDefaultRelays {
dependencies.sendToDefaultRelays(event)
}
publishAndEcho(
event: event,
relays: relays,
relays: canSendToRelays ? relays : [],
content: trimmed,
nickname: nickname,
expiresAt: expiresAt,
@@ -975,8 +1072,8 @@ final class LocationNotesManager: ObservableObject {
let actors = byEmoji[normalizedEmoji, default: []]
if actors.contains(ownHex) {
guard !relays.isEmpty else {
state = .noRelays
guard dependencies.activationAllowed(), !relays.isEmpty else {
state = relays.isEmpty ? .noRelays : .connecting
errorMessage = Strings.noRelays
return false
}
@@ -985,7 +1082,7 @@ final class LocationNotesManager: ObservableObject {
if let reactionEventID = ownReactionEventIDs.removeValue(forKey: key) {
reactionMetaByEventID.removeValue(forKey: reactionEventID)
deletedEventIDs.insert(reactionEventID)
recordDeletedEventID(reactionEventID)
let deletion = try NostrProtocol.createDeleteEvent(
ofEventID: reactionEventID,
senderIdentity: identity,
@@ -1003,14 +1100,15 @@ final class LocationNotesManager: ObservableObject {
senderIdentity: identity,
createdAt: dependencies.now()
)
let hasConnectedRelays = !relays.isEmpty && dependencies.anyRelayConnected(relays)
let canSendToRelays = dependencies.activationAllowed() && !relays.isEmpty
let hasConnectedRelays = canSendToRelays && dependencies.anyRelayConnected(relays)
let uplinked = !hasConnectedRelays && dependencies.uplinkViaMesh(reactionEvent, geohash)
guard hasConnectedRelays || uplinked || !relays.isEmpty else {
state = .noRelays
guard canSendToRelays || uplinked else {
state = relays.isEmpty ? .noRelays : .connecting
errorMessage = Strings.noRelays
return false
}
if !relays.isEmpty {
if canSendToRelays {
dependencies.sendEvent(reactionEvent, relays)
}
let reactionID = reactionEvent.id.lowercased()
@@ -1041,8 +1139,8 @@ final class LocationNotesManager: ObservableObject {
func delete(note: Note) -> Bool {
guard isOwnNote(note) else { return false }
let relays = dependencies.relayLookup(geohash, TransportConfig.nostrGeoRelayCount)
guard !relays.isEmpty else {
state = .noRelays
guard dependencies.activationAllowed(), !relays.isEmpty else {
state = relays.isEmpty ? .noRelays : .connecting
errorMessage = Strings.noRelays
return false
}
@@ -1054,16 +1152,19 @@ final class LocationNotesManager: ObservableObject {
} else {
identity = try dependencies.deriveIdentity(geohash)
}
let targetGeohash = note.geohash.isEmpty ? geohash : note.geohash
let deletion = try NostrProtocol.createDeleteEvent(
ofEventID: note.id,
senderIdentity: identity,
geohash: geohash
geohash: targetGeohash
)
dependencies.sendEvent(deletion, relays)
if usedPublicHandle {
dependencies.sendToDefaultRelays(deletion)
}
// Keep the id in noteIDs so a relay replay can't resurrect it.
// Record in deletedEventIDs so neither relay replays nor pull-to-refresh
// can resurrect the note before relays finish honoring NIP-09.
recordDeletedEventID(note.id.lowercased())
if let rootID = note.rootEventID {
var thread = repliesByRootID[rootID] ?? []
thread.removeAll { $0.id == note.id }
@@ -1103,16 +1204,17 @@ final class LocationNotesManager: ObservableObject {
dependencies: LocationNotesDependencies = .live
) -> Bool {
guard let trimmed = content.trimmedOrNilIfEmpty else { return false }
let relays = dependencies.relayLookup(geohash, TransportConfig.nostrGeoRelayCount)
guard !relays.isEmpty else {
SecureLogger.warning("LocationNotesManager: drop blocked, no geo relays for geohash=\(geohash)", category: .session)
let normalizedGeohash = geohash.lowercased()
let relays = dependencies.relayLookup(normalizedGeohash, TransportConfig.nostrGeoRelayCount)
guard dependencies.activationAllowed(), !relays.isEmpty else {
SecureLogger.warning("LocationNotesManager: drop blocked, relays unavailable for geohash=\(normalizedGeohash)", category: .session)
return false
}
do {
let identity = try dependencies.deriveIdentity(geohash)
let identity = try dependencies.deriveIdentity(normalizedGeohash)
let event = try NostrProtocol.createGeohashTextNote(
content: trimmed,
geohash: geohash,
geohash: normalizedGeohash,
senderIdentity: identity,
nickname: nickname,
expiresAt: dependencies.now().addingTimeInterval(expiry)
@@ -1158,6 +1260,9 @@ final class LocationNotesManager: ObservableObject {
ownReactionEventIDs.removeAll(keepingCapacity: false)
reactionMetaByEventID.removeAll(keepingCapacity: false)
deletedEventIDs.removeAll(keepingCapacity: false)
deletedEventOrder.removeAll(keepingCapacity: false)
pendingDeletionsByTargetID.removeAll(keepingCapacity: false)
pendingDeletionOrder.removeAll(keepingCapacity: false)
ownPubkey = nil
ownPublicPubkey = nil
initialLoadComplete = false
+12
View File
@@ -71,6 +71,18 @@ final class LocationNotesPool {
}
}
/// Retracts a locally deleted event ID (e.g. a bridged board post's Nostr
/// copy) from any active pooled manager whose 9-cell grid covers `geohash`.
func retractEvent(id eventID: String, geohash: String) {
let target = geohash.lowercased()
for entry in entries.values {
let manager = entry.manager
if manager.geohash == target || Geohash.neighbors(of: manager.geohash).contains(target) {
manager.retractLocalEvent(id: eventID)
}
}
}
/// Snapshot of currently loaded note counts per pooled geohash (used by
/// the 3D globe activity layer).
func activeNoteCounts() -> [String: Int] {
+3 -2
View File
@@ -375,12 +375,13 @@ private extension ContentHeaderView {
}
var scopeHasNotices: Bool {
let nowMs = UInt64(max(0, Date().timeIntervalSince1970) * 1000)
if case .location(let channel) = locationChannelsModel.selectedChannel {
let isCurrentBuilding = channel.geohash == locationChannelsModel.currentBuildingGeohash
return boardPosts.contains { $0.geohash == channel.geohash }
return boardPosts.contains { $0.geohash == channel.geohash && $0.expiresAt > nowMs }
|| (isCurrentBuilding && nearbyNotes.noteCount > 0)
}
return boardPosts.contains { $0.geohash.isEmpty }
return boardPosts.contains { $0.geohash.isEmpty && $0.expiresAt > nowMs }
}
var unseenNoticesCount: Int {
+10
View File
@@ -324,6 +324,7 @@ struct NoticesView: View {
#endif
.themedSheetBackground()
.onAppear {
board.pruneExpired()
if tab == .geo && geoTabNeedsDeviceLocation,
Self.revealsNearbyNotes(onSwitchingTo: .geo, geoGeohash: geoGeohash) {
NearbyNotesCounter.shared.reveal()
@@ -789,6 +790,15 @@ private struct NoticesList: View {
case .board(let post):
// Tombstones the board post and retracts the bridged Nostr copy.
board.deletePost(post)
// Post-relaunch fallback: if the in-memory bridgedEventIDs map was
// lost across restart and our own bridged kind-1 copy is loaded,
// delete it too so it does not reappear once the board copy vanishes.
if let notesManager,
let bridgedNote = notesManager.notes.first(where: {
notesManager.isOwnNote($0) && UnifiedNotices.isBridgedCopy(post: post, note: $0)
}) {
notesManager.delete(note: bridgedNote)
}
case .nostr(let note):
notesManager?.delete(note: note)
}
+10 -1
View File
@@ -25,6 +25,7 @@ struct PlaceFeedView: View {
let injectedNotesManager: LocationNotesManager?
@EnvironmentObject private var locationChannelsModel: LocationChannelsModel
@Environment(\.appEnvironmentModels) private var appEnvironmentModels
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
@ThemedPalette private var palette
@@ -112,9 +113,12 @@ struct PlaceFeedView: View {
}
}
.onAppear {
board.pruneExpired()
appEnvironmentModels?.boardAlertsModel.markSeen(forScopes: [geohash])
reconcileManager()
}
.onChange(of: geohash) { _ in
.onChange(of: geohash) { newGeohash in
appEnvironmentModels?.boardAlertsModel.markSeen(forScopes: [newGeohash])
reconcileManager()
}
.onReceive(NotificationCenter.default.publisher(for: LocationNotesSettings.didChangeNotification)) { _ in
@@ -850,6 +854,11 @@ private struct PlaceFeedContent: View {
switch item.source {
case .board(let post):
board.deletePost(post)
if let bridgedNote = manager.notes.first(where: {
manager.isOwnNote($0) && UnifiedNotices.isBridgedCopy(post: post, note: $0)
}) {
manager.delete(note: bridgedNote)
}
case .nostr(let note):
manager.delete(note: note)
}
+13
View File
@@ -17,6 +17,7 @@ struct PlacesTabView<RoomContent: View>: View {
@EnvironmentObject private var appChromeModel: AppChromeModel
@EnvironmentObject private var locationChannelsModel: LocationChannelsModel
@EnvironmentObject private var peerListModel: PeerListModel
@Environment(\.appEnvironmentModels) private var appEnvironmentModels
@Environment(\.scenePhase) private var scenePhase
@Environment(\.appTheme) private var theme
@ThemedPalette private var palette
@@ -37,6 +38,7 @@ struct PlacesTabView<RoomContent: View>: View {
@State private var showLocalPlaceNotes = false
@State private var tabMode: PlacesTabMode = .explore
@State private var showPublicProfileSheet = false
@State private var holdsNotesCounter = false
@ObservedObject private var nearbyNotes = NearbyNotesCounter.shared
@ObservedObject private var profileStore = NostrProfileStore.shared
@@ -50,9 +52,17 @@ struct PlacesTabView<RoomContent: View>: View {
}
.onAppear {
locationChannelsModel.beginLiveRefresh()
if !holdsNotesCounter {
holdsNotesCounter = true
NearbyNotesCounter.shared.activate()
}
}
.onDisappear {
locationChannelsModel.endLiveRefresh()
if holdsNotesCounter {
holdsNotesCounter = false
NearbyNotesCounter.shared.deactivate()
}
}
.onChange(of: scenePhase) { newPhase in
if newPhase == .active {
@@ -351,6 +361,9 @@ struct PlacesTabView<RoomContent: View>: View {
}()
Button {
if let building = locationChannelsModel.currentBuildingGeohash {
appEnvironmentModels?.boardAlertsModel.markSeen(forScopes: [building])
}
showLocalPlaceNotes = true
} label: {
ThemedCard {
@@ -480,6 +480,248 @@ struct LocationNotesManagerTests {
#expect(manager.state == .loading)
}
@Test
func inboundDeletionArrivingBeforeNote_suppressesMatchingAuthorOnly() throws {
var storedHandler: ((NostrEvent) -> Void)?
let now = Date(timeIntervalSince1970: 1_700_000_000)
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, _ in storedHandler = handler },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { now }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
let author = try NostrIdentity.generate()
let attacker = try NostrIdentity.generate()
let deletedNote = try NostrProtocol.createGeohashTextNote(
content: "retracted",
geohash: "u4pruydq",
senderIdentity: author,
createdAt: now.addingTimeInterval(-60)
)
let keptNote = try NostrProtocol.createGeohashTextNote(
content: "forged delete target",
geohash: "u4pruydq",
senderIdentity: author,
createdAt: now.addingTimeInterval(-30)
)
// Relay delivers newer kind-5 deletions BEFORE older kind-1 notes.
let genuineDelete = try NostrProtocol.createDeleteEvent(
ofEventID: deletedNote.id,
senderIdentity: author,
geohash: "u4pruydq"
)
let forgedDelete = try NostrProtocol.createDeleteEvent(
ofEventID: keptNote.id,
senderIdentity: attacker,
geohash: "u4pruydq"
)
storedHandler?(genuineDelete)
storedHandler?(forgedDelete)
// Now older kind-1 notes arrive in backfill.
storedHandler?(deletedNote)
storedHandler?(keptNote)
#expect(manager.notes.map(\.id) == [keptNote.id.lowercased()])
}
@Test
func inboundDeletionArrivingBeforeReaction_suppressesMatchingAuthorOnly() throws {
var storedHandler: ((NostrEvent) -> Void)?
let now = Date(timeIntervalSince1970: 1_700_000_000)
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, _ in storedHandler = handler },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { now }
)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
let author = try NostrIdentity.generate()
let reactor = try NostrIdentity.generate()
let attacker = try NostrIdentity.generate()
let note = try NostrProtocol.createGeohashTextNote(
content: "hello",
geohash: "u4pruydq",
senderIdentity: author,
createdAt: now.addingTimeInterval(-120)
)
let removedReaction = try NostrProtocol.createGeohashReactionEvent(
emoji: "🔥",
targetEventID: note.id,
targetAuthorPubkey: author.publicKeyHex,
geohash: "u4pruydq",
senderIdentity: reactor,
createdAt: now.addingTimeInterval(-60)
)
let keptReaction = try NostrProtocol.createGeohashReactionEvent(
emoji: "👍",
targetEventID: note.id,
targetAuthorPubkey: author.publicKeyHex,
geohash: "u4pruydq",
senderIdentity: reactor,
createdAt: now.addingTimeInterval(-50)
)
// Deliver kind-5 deletions before the kind-7 reactions arrive.
storedHandler?(try NostrProtocol.createDeleteEvent(ofEventID: removedReaction.id, senderIdentity: reactor, geohash: "u4pruydq"))
storedHandler?(try NostrProtocol.createDeleteEvent(ofEventID: keptReaction.id, senderIdentity: attacker, geohash: "u4pruydq"))
storedHandler?(note)
storedHandler?(removedReaction)
storedHandler?(keptReaction)
let reactions = manager.reactions(forNoteID: note.id)
#expect(reactions.map(\.emoji) == ["👍"])
}
@Test
func localDelete_survivesRefreshAndTagsNoteGeohash() throws {
var storedHandler: ((NostrEvent) -> Void)?
var sentEvents: [NostrEvent] = []
let identity = try NostrIdentity.generate()
let neighbor = try #require(Geohash.neighbors(of: "u4pruydq").first)
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, _ in storedHandler = handler },
unsubscribe: { _ in },
sendEvent: { event, _ in sentEvents.append(event) },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { Date(timeIntervalSince1970: 1_700_000_000) }
)
deps.publicIdentity = { identity }
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
let noteEvent = try NostrProtocol.createGeohashTextNote(
content: "neighbor note",
geohash: neighbor,
senderIdentity: identity,
createdAt: Date(timeIntervalSince1970: 1_700_000_000)
)
storedHandler?(noteEvent)
let note = try #require(manager.notes.first)
#expect(manager.delete(note: note))
#expect(manager.notes.isEmpty)
// Deletion event must tag the note's own geohash (neighbor).
let deletion = try #require(sentEvents.first { $0.kind == NostrProtocol.EventKind.deletion.rawValue })
#expect(deletion.tags.contains(["g", neighbor]))
// Refreshing and replaying the deleted event must not resurrect it.
manager.refresh()
storedHandler?(noteEvent)
#expect(manager.notes.isEmpty)
}
@Test
func staleSubscriptionCallbacks_areIgnoredAfterRefreshAndCancel() throws {
var handlers: [(NostrEvent) -> Void] = []
var eoses: [() -> Void] = []
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, eose in
handlers.append(handler)
if let eose { eoses.append(eose) }
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date(timeIntervalSince1970: 1_700_000_000) }
)
deps.anyRelayConnected = { _ in false }
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
manager.refresh()
#expect(handlers.count == 2)
#expect(eoses.count == 2)
// Firing the first subscription's stale EOSE must not mark the second subscription loaded/connecting.
eoses[0]()
#expect(!manager.initialLoadComplete)
#expect(manager.state == .loading)
// Cancelling must ignore late events from the cancelled subscription.
manager.cancel()
let identity = try NostrIdentity.generate()
let lateEvent = try NostrProtocol.createGeohashTextNote(
content: "late",
geohash: "u4pruydq",
senderIdentity: identity
)
handlers[1](lateEvent)
#expect(manager.notes.isEmpty)
#expect(manager.state == .idle)
}
@Test
func sendAndPostDrop_failWhenActivationDisallowed() throws {
var sendCalled = false
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, _, _ in },
unsubscribe: { _ in },
sendEvent: { _, _ in sendCalled = true },
deriveIdentity: { _ in try NostrIdentity.generate() },
now: { Date(timeIntervalSince1970: 1_700_000_000) }
)
deps.activationAllowed = { false }
#expect(!LocationNotesManager.postDrop(content: "offline drop", nickname: "alice", geohash: "u4pruydq", dependencies: deps))
#expect(!sendCalled)
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
manager.send(content: "offline note", nickname: "alice")
#expect(!sendCalled)
#expect(manager.notes.isEmpty)
#expect(manager.errorMessage != nil)
#expect(!manager.sendFeedPost(content: "offline feed post", nickname: "alice"))
#expect(!sendCalled)
#expect(manager.notes.isEmpty)
}
@Test
func poolRetractEvent_removesBridgedNoteFromCoveringManagers() throws {
var storedHandler: ((NostrEvent) -> Void)?
let deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, handler, _ in storedHandler = handler },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date(timeIntervalSince1970: 1_700_000_000) }
)
let pool = LocationNotesPool(makeManager: { LocationNotesManager(geohash: $0, dependencies: deps) })
let manager = pool.acquire("u4pruydq")
let identity = try NostrIdentity.generate()
let bridged = try NostrProtocol.createGeohashTextNote(
content: "bridged notice",
geohash: "u4pruydq",
senderIdentity: identity,
createdAt: Date(timeIntervalSince1970: 1_700_000_000)
)
storedHandler?(bridged)
#expect(manager.notes.count == 1)
pool.retractEvent(id: bridged.id, geohash: "u4pruydq")
#expect(manager.notes.isEmpty)
// Replaying the retracted event must not resurrect it.
storedHandler?(bridged)
#expect(manager.notes.isEmpty)
pool.release(manager)
}
private enum TestError: Error {
case shouldNotDerive
}
@@ -7,6 +7,7 @@
//
import BitFoundation
import Combine
import CryptoKit
import Foundation
import Testing
@@ -404,4 +405,100 @@ struct BoardStoreTests {
#expect(store.ingest(genuineTombstone.wire, packet: genuineTombstone.packet) == .accepted)
#expect(store.posts(forGeohash: "9q8yy").isEmpty)
}
@Test func attackerOrphanEvictionDoesNotDeleteGenuineAuthorTombstone() throws {
let clock = MutableClock(now: baseDate)
let store = makeStore(clock: clock)
let author = Curve25519.Signing.PrivateKey()
let attacker = Curve25519.Signing.PrivateKey()
// Alice posts and deletes her post, leaving a matched (non-orphan) tombstone.
let entry = try makePost(author: author, createdAt: baseMs)
#expect(store.ingest(entry.wire, packet: entry.packet) == .accepted)
let genuineTombstone = try makeTombstone(for: entry.post, author: author, deletedAt: baseMs + 1000)
#expect(store.ingest(genuineTombstone.wire, packet: genuineTombstone.packet) == .accepted)
#expect(store.posts(forGeohash: "9q8yy").isEmpty)
// Attacker plants an orphan tombstone for Alice's postID under attacker's key,
// then fills their own orphan quota to force eviction of that orphan.
let attackerOrphan = try makeTombstone(for: entry.post, author: attacker, deletedAt: baseMs + 2000)
#expect(store.ingest(attackerOrphan.wire, packet: attackerOrphan.packet) == .accepted)
for index in 0..<BoardStore.Limits.maxOrphanTombstonesPerAuthor {
let dummy = try makePost(author: attacker, createdAt: baseMs + 3000 + UInt64(index))
let dummyTombstone = try makeTombstone(for: dummy.post, author: attacker, deletedAt: baseMs + 4000 + UInt64(index))
#expect(store.ingest(dummyTombstone.wire, packet: dummyTombstone.packet) == .accepted)
}
// Alice's genuine tombstone MUST still be intact so replaying her post is rejected.
#expect(store.ingest(entry.wire, packet: entry.packet) == .rejected)
#expect(store.posts(forGeohash: "9q8yy").isEmpty)
}
@Test @MainActor func immediatelyEvictedPostDoesNotFirePostArrivals() async throws {
let clock = MutableClock(now: baseDate)
let store = makeStore(clock: clock)
let author = Curve25519.Signing.PrivateKey()
var arrivedIDs: [Data] = []
let cancellable = store.postArrivals.sink { post in
arrivedIDs.append(post.postID)
}
defer { cancellable.cancel() }
// Fill author's cap with newer posts.
for index in 0..<BoardStore.Limits.maxPostsPerAuthor {
let entry = try makePost(author: author, createdAt: baseMs + 10_000 + UInt64(index) * 1000)
#expect(store.ingest(entry.wire, packet: entry.packet) == .accepted)
}
// Ingest an older post from the same author: accepted for relay, but immediately evicted locally.
let older = try makePost(author: author, createdAt: baseMs)
#expect(store.ingest(older.wire, packet: older.packet) == .accepted)
#expect(!store.posts(forGeohash: "9q8yy").contains { $0.postID == older.post.postID })
await drainMainQueueTwice()
#expect(!arrivedIDs.contains(older.post.postID))
#expect(arrivedIDs.count == BoardStore.Limits.maxPostsPerAuthor)
}
@Test @MainActor func pruneExpiredUpdatesSnapshotForIdleStore() async throws {
let clock = MutableClock(now: baseDate)
let store = makeStore(clock: clock)
let author = Curve25519.Signing.PrivateKey()
let entry = try makePost(author: author, createdAt: baseMs, lifetimeMs: 60 * 60 * 1000)
#expect(store.ingest(entry.wire, packet: entry.packet) == .accepted)
await drainMainQueueTwice()
#expect(store.postsSnapshot.count == 1)
clock.now = baseDate.addingTimeInterval(2 * 60 * 60)
store.pruneExpired()
await drainMainQueueTwice()
#expect(store.postsSnapshot.isEmpty)
}
@MainActor
private func drainMainQueueTwice() async {
for _ in 0..<2 {
await withCheckedContinuation { continuation in
DispatchQueue.main.async {
continuation.resume()
}
}
}
}
@Test func orphanTombstoneWithMaxDeletedAtDoesNotOverflow() throws {
let clock = MutableClock(now: baseDate)
let store = makeStore(clock: clock)
let author = Curve25519.Signing.PrivateKey()
let entry = try makePost(author: author, createdAt: baseMs)
let tombstone = try makeTombstone(for: entry.post, author: author, deletedAt: UInt64.max)
#expect(store.ingest(tombstone.wire, packet: tombstone.packet) == .accepted)
#expect(store.syncCandidates().count == 1)
clock.now = baseDate.addingTimeInterval(8 * 24 * 60 * 60)
#expect(store.syncCandidates().isEmpty)
}
}
@@ -6,6 +6,7 @@
// For more information, see <https://unlicense.org>
//
import BitFoundation
import Foundation
import Testing
@testable import bitchat
@@ -139,4 +140,119 @@ struct UnifiedNoticesTests {
#expect(!item.isBoardPost)
#expect(!item.isUrgent)
}
@Test
func merge_withNowFiltersExpiredPostsAndNotes() {
let expiredPost = makePost(content: "stale mesh notice", createdAt: baseMs - 48 * 60 * 60 * 1000)
let livePost = makePost(content: "fresh mesh notice", createdAt: baseMs)
let expiredNote = LocationNotesManager.Note(
id: "e-exp",
pubkey: "deadbeef",
content: "expired drop",
createdAt: baseDate.addingTimeInterval(-3600),
nickname: "alice",
geohash: "9q8yy",
expiresAt: baseDate.addingTimeInterval(-60)
)
let liveNote = LocationNotesManager.Note(
id: "e-live",
pubkey: "deadbeef",
content: "active drop",
createdAt: baseDate,
nickname: "bob",
geohash: "9q8yy",
expiresAt: baseDate.addingTimeInterval(3600)
)
let merged = UnifiedNotices.merge(
posts: [expiredPost, livePost],
notes: [expiredNote, liveNote],
now: baseDate
)
#expect(merged.map(\.content) == ["fresh mesh notice", "active drop"])
}
@Test @MainActor
func boardManager_normalizesGeohash_filtersExpired_andClearsBridgedIDsOnWipe() async throws {
var currentNow = baseDate
let store = BoardStore(persistsToDisk: false, now: { currentNow })
let transport = MockTransport()
var bridgedGeohashes: [String] = []
var deletedEventIDs: [(String, String)] = []
let manager = BoardManager(
transport: transport,
store: store,
now: { currentNow },
publishToNostr: { _, gh, _, _, _ in
bridgedGeohashes.append(gh)
return String(repeating: "a", count: 64)
},
deleteFromNostr: { eventID, gh in
deletedEventIDs.append((eventID, gh))
}
)
// Invalid geohash must be rejected before signing or bridging.
#expect(!manager.createPost(content: "bad", geohash: "INVALID!", urgent: false, expiryDays: 1, nickname: "alice"))
#expect(bridgedGeohashes.isEmpty)
// Uppercase valid geohash is normalized to lowercase in both wire packet and Nostr bridge.
#expect(manager.createPost(content: "ok", geohash: "9Q8YY", urgent: false, expiryDays: 1, nickname: "alice"))
#expect(bridgedGeohashes == ["9q8yy"])
let encoded = try #require(transport.sentBoardPayloads.last)
guard case .post(let createdPost) = BoardWire.decode(from: encoded) else {
Issue.record("Expected decodable BoardPostPacket")
return
}
#expect(createdPost.geohash == "9q8yy")
// Wipe clears bridgedEventIDs so a subsequent delete cannot leak pre-wipe Nostr event IDs.
store.wipe()
await drainMainQueueTwice()
#expect(manager.deletePost(createdPost))
#expect(deletedEventIDs.isEmpty)
// posts(forGeohash:) filters expired posts even before a store prune runs.
let expiring = BoardPostPacket(
postID: Data((0..<16).map { _ in UInt8.random(in: 0...255) }),
geohash: "9q8yy",
content: "short",
authorSigningKey: transport.noiseSigningPublicKeyData(),
authorNickname: "alice",
createdAt: baseMs,
expiresAt: baseMs + 60 * 60 * 1000,
flags: 0,
signature: Data(repeating: 2, count: 64)
)
let wire = BoardWire.post(expiring)
let packet = BitchatPacket(
type: MessageType.boardPost.rawValue,
senderID: Data(repeating: 1, count: 8),
recipientID: nil,
timestamp: baseMs,
payload: wire.encode(),
signature: nil,
ttl: 7
)
#expect(store.ingest(wire, packet: packet) == .accepted)
await drainMainQueueTwice()
#expect(manager.posts(forGeohash: "9Q8YY").count == 1)
currentNow = baseDate.addingTimeInterval(2 * 60 * 60)
#expect(manager.posts(forGeohash: "9q8yy").isEmpty)
}
@MainActor
private func drainMainQueueTwice() async {
for _ in 0..<2 {
await withCheckedContinuation { continuation in
DispatchQueue.main.async {
continuation.resume()
}
}
}
}
}