mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-11-22 08:17:28 +00:00
Merge cf93872d2140c113d0bf85658f30493a2804a533 into 04995f68e470a18d1fc99f86fa326c2a87bab4f2
This commit is contained in:
commit
b3ebc7f92c
@ -171,10 +171,11 @@ final class MessageDeduplicationService {
|
||||
private let nostrAckCache: LRUDeduplicationCache<Bool>
|
||||
|
||||
/// Optional cross-launch persistence for the Nostr event cache. BitChat
|
||||
/// randomizes private-envelope timestamps, so DM subscriptions look back 24h and
|
||||
/// relays redeliver the same events on every launch; without this record
|
||||
/// each relaunch reprocesses old PMs and acks. Nil (tests, macOS callers
|
||||
/// that don't opt in) keeps the cache purely in-memory.
|
||||
/// and peer clients randomize private-envelope timestamps (up to ~48h
|
||||
/// into the past on Android), so DM subscriptions look back across that
|
||||
/// window and relays redeliver the same events on every launch; without
|
||||
/// this record each relaunch reprocesses old PMs and acks. Nil (tests,
|
||||
/// macOS callers that don't opt in) keeps the cache purely in-memory.
|
||||
private let nostrEventStore: NostrProcessedEventStore?
|
||||
private let nostrEventCapacity: Int
|
||||
private var persistScheduled = false
|
||||
|
||||
@ -10,8 +10,9 @@ import BitLogger
|
||||
import Foundation
|
||||
|
||||
/// Disk persistence for processed private-envelope event IDs. BitChat
|
||||
/// randomizes envelope timestamps, so DM subscriptions must look back
|
||||
/// generously (24h)
|
||||
/// and peer clients randomize envelope timestamps (up to ~48h into the
|
||||
/// past on Android), so DM subscriptions must look back across that
|
||||
/// window
|
||||
/// and relays redeliver the same events on every launch — without a
|
||||
/// cross-launch record, each relaunch reprocesses old PMs and acks
|
||||
/// (re-sent DELIVERED bursts, "delivered ack for unknown mid" noise).
|
||||
|
||||
@ -220,11 +220,18 @@ enum TransportConfig {
|
||||
static let nostrGeoRelayCount: Int = 5
|
||||
static let nostrGeohashSampleLookbackSeconds: TimeInterval = 300
|
||||
static let nostrGeohashSampleLimit: Int = 100
|
||||
// Inner-rumor lookback: senders stamp the rumor with real send time.
|
||||
static let nostrDMSubscribeLookbackSeconds: TimeInterval = 86400
|
||||
// Tolerated clock skew for the client-side rumor-timestamp window on
|
||||
// inbound Nostr DMs (senders stamp the inner rumor with real time; only
|
||||
// the outer gift wrap is randomized per NIP-17).
|
||||
// Tolerated clock skew for client-side Nostr DM timestamp windows.
|
||||
static let nostrDMMaxClockSkewSeconds: TimeInterval = 900
|
||||
// Outer gift-wrap age ceiling. Android (and NIP-17-style clients) may
|
||||
// randomize the wrap's created_at up to 48h into the past; relays that
|
||||
// honor `since` will not deliver those wraps under a 24h filter. The
|
||||
// envelope may then wait offline for the full inner-rumor delivery window.
|
||||
// Keep that grace in the outer gate and relay filter; the inner timestamp
|
||||
// still independently enforces message freshness after decryption.
|
||||
static let nostrGiftWrapMaxAgeSeconds: TimeInterval = 172_800
|
||||
+ nostrDMSubscribeLookbackSeconds + nostrDMMaxClockSkewSeconds
|
||||
// A sampled chat message this recent means "a conversation is happening
|
||||
// there" for the empty-timeline nearby-activity hint.
|
||||
static let uiGeohashChatActivityWindowSeconds: TimeInterval = 900
|
||||
|
||||
@ -177,7 +177,7 @@ final class GeohashSubscriptionManager {
|
||||
context.setGeoDmSubscriptionID(dmSub)
|
||||
let dmFilter = NostrFilter.giftWrapsFor(
|
||||
pubkey: identity.publicKeyHex,
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrGiftWrapMaxAgeSeconds)
|
||||
)
|
||||
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in
|
||||
Task { @MainActor [weak self] in
|
||||
@ -281,7 +281,7 @@ final class GeohashSubscriptionManager {
|
||||
}
|
||||
let dmFilter = NostrFilter.giftWrapsFor(
|
||||
pubkey: identity.publicKeyHex,
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrGiftWrapMaxAgeSeconds)
|
||||
)
|
||||
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in
|
||||
Task { @MainActor [weak self] in
|
||||
@ -415,7 +415,7 @@ final class GeohashSubscriptionManager {
|
||||
|
||||
let filter = NostrFilter.giftWrapsFor(
|
||||
pubkey: currentIdentity.publicKeyHex,
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
since: Date().addingTimeInterval(-TransportConfig.nostrGiftWrapMaxAgeSeconds)
|
||||
)
|
||||
|
||||
context.nostrRelayManager?.subscribe(filter: filter, id: "chat-messages") { [weak self] event in
|
||||
|
||||
@ -368,6 +368,16 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
if alreadyProcessed { return }
|
||||
|
||||
// Cheap outer-wrap gate before the NIP-17 unwrap (two ECDH+ChaCha
|
||||
// rounds). Android may stamp wraps up to 48h into the past; a
|
||||
// future-dated wrap beyond skew is never legitimate for our clients.
|
||||
guard Self.isAcceptableGiftWrapTimestamp(giftWrap.created_at) else {
|
||||
if verbose {
|
||||
SecureLogger.warning("GeoDM: dropping gift-wrap with implausible outer timestamp id=\(giftWrap.id.prefix(8))…", category: .session)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
guard let (content, senderPubkey, rumorTs) = try? NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
recipientIdentity: id
|
||||
@ -467,6 +477,11 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
guard let currentIdentity else { return }
|
||||
|
||||
guard Self.isAcceptableGiftWrapTimestamp(giftWrap.created_at) else {
|
||||
SecureLogger.warning("Dropping Nostr DM with implausible outer gift-wrap timestamp id=\(giftWrap.id.prefix(8))…", category: .session)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let (content, senderPubkey, rumorTimestamp) = try NostrProtocol.decryptPrivateMessage(
|
||||
giftWrap: giftWrap,
|
||||
@ -576,12 +591,9 @@ final class NostrInboundPipeline {
|
||||
}
|
||||
|
||||
extension NostrInboundPipeline {
|
||||
/// Client-side mirror of the relay-side `since` filter on DM
|
||||
/// subscriptions: a relay that ignores `since` — or replays archived
|
||||
/// events — must not inject stale or future-dated DMs. The inner rumor
|
||||
/// timestamp is the sender's true send time (only the outer gift wrap
|
||||
/// is randomized per NIP-17), so the plausible window is the
|
||||
/// subscription lookback plus tolerated clock skew on both ends.
|
||||
/// Inner-message freshness, independent of the wider outer-wrap relay
|
||||
/// filter. The rumor carries the sender's true send time, so accepting an
|
||||
/// older randomized envelope must not admit stale or future-dated DMs.
|
||||
/// Internal (not private) so tests can pin the window directly.
|
||||
static func isPlausibleRumorTimestamp(_ ts: Int, now: Date = Date()) -> Bool {
|
||||
let age = now.timeIntervalSince1970 - TimeInterval(ts)
|
||||
@ -589,6 +601,17 @@ extension NostrInboundPipeline {
|
||||
&& age <= TransportConfig.nostrDMSubscribeLookbackSeconds
|
||||
+ TransportConfig.nostrDMMaxClockSkewSeconds
|
||||
}
|
||||
|
||||
/// Accept an outer gift-wrap `created_at` that is not in the far future
|
||||
/// and not older than the randomization ceiling plus the inner delivery
|
||||
/// window and clock skew. Checked before decrypt so a hostile relay
|
||||
/// cannot force ECDH work with
|
||||
/// ancient or far-future wraps.
|
||||
static func isAcceptableGiftWrapTimestamp(_ createdAt: Int, now: Date = Date()) -> Bool {
|
||||
let age = now.timeIntervalSince1970 - TimeInterval(createdAt)
|
||||
return age >= -TransportConfig.nostrDMMaxClockSkewSeconds
|
||||
&& age <= TransportConfig.nostrGiftWrapMaxAgeSeconds
|
||||
}
|
||||
}
|
||||
|
||||
private extension NostrInboundPipeline {
|
||||
|
||||
@ -15,6 +15,7 @@ struct NostrInboundPipelineTimestampTests {
|
||||
private let nowSeconds = 1_700_000_000
|
||||
private let skew = Int(TransportConfig.nostrDMMaxClockSkewSeconds)
|
||||
private let lookback = Int(TransportConfig.nostrDMSubscribeLookbackSeconds)
|
||||
private let giftWrapMaxAge = Int(TransportConfig.nostrGiftWrapMaxAgeSeconds)
|
||||
|
||||
@Test("Rumor timestamps inside the lookback-plus-skew window are accepted")
|
||||
func acceptsPlausibleTimestamps() {
|
||||
@ -29,4 +30,48 @@ struct NostrInboundPipelineTimestampTests {
|
||||
#expect(!NostrInboundPipeline.isPlausibleRumorTimestamp(nowSeconds + skew + 60, now: now))
|
||||
#expect(!NostrInboundPipeline.isPlausibleRumorTimestamp(nowSeconds - lookback - skew - 60, now: now))
|
||||
}
|
||||
|
||||
@Test("Outer gift wraps inside the randomization and delivery window are accepted")
|
||||
func acceptsPlausibleGiftWrapTimestamps() {
|
||||
#expect(NostrInboundPipeline.isAcceptableGiftWrapTimestamp(nowSeconds, now: now))
|
||||
// Android randomizes wraps up to 48h into the past.
|
||||
#expect(NostrInboundPipeline.isAcceptableGiftWrapTimestamp(nowSeconds - 172_800 + 60, now: now))
|
||||
#expect(NostrInboundPipeline.isAcceptableGiftWrapTimestamp(nowSeconds + skew - 60, now: now))
|
||||
}
|
||||
|
||||
@Test("Far-future and over-age outer gift wraps are rejected")
|
||||
func rejectsImplausibleGiftWrapTimestamps() {
|
||||
#expect(!NostrInboundPipeline.isAcceptableGiftWrapTimestamp(nowSeconds + skew + 60, now: now))
|
||||
#expect(!NostrInboundPipeline.isAcceptableGiftWrapTimestamp(nowSeconds - giftWrapMaxAge - 60, now: now))
|
||||
// A wrap older than 24h but inside 48h+skew must still pass — that is
|
||||
// the Android→iOS delivery gap this gate exists to keep open.
|
||||
#expect(NostrInboundPipeline.isAcceptableGiftWrapTimestamp(nowSeconds - lookback - 3_600, now: now))
|
||||
}
|
||||
|
||||
@Test("A wrap randomized 48h back remains deliverable after 23h offline")
|
||||
func acceptsQueuedGiftWrapWithFreshRumor() {
|
||||
// Fixed wire timestamps: created together 23h before receipt, with the
|
||||
// outer timestamp moved another 48h back. Do not derive the vector
|
||||
// from the policy constants: that would hide an undersized window.
|
||||
let rumorCreatedAt = 1_699_917_200
|
||||
let wrapCreatedAt = 1_699_744_400
|
||||
#expect(NostrInboundPipeline.isPlausibleRumorTimestamp(rumorCreatedAt, now: now))
|
||||
#expect(NostrInboundPipeline.isAcceptableGiftWrapTimestamp(wrapCreatedAt, now: now))
|
||||
let subscriptionSince = now.addingTimeInterval(-TransportConfig.nostrGiftWrapMaxAgeSeconds)
|
||||
#expect(Date(timeIntervalSince1970: TimeInterval(wrapCreatedAt)) >= subscriptionSince)
|
||||
}
|
||||
|
||||
@Test("Delivery grace covers the inner boundary without extending rumor freshness")
|
||||
func preservesIndependentTimestampBoundaries() {
|
||||
// At this receive time, 24h plus 15min is the last valid inner rumor;
|
||||
// its maximally randomized wrap is exactly 72h plus 15min old.
|
||||
#expect(NostrInboundPipeline.isPlausibleRumorTimestamp(1_699_912_700, now: now))
|
||||
#expect(NostrInboundPipeline.isAcceptableGiftWrapTimestamp(1_699_739_900, now: now))
|
||||
#expect(!NostrInboundPipeline.isAcceptableGiftWrapTimestamp(1_699_739_899, now: now))
|
||||
// A freshly rewrapped envelope cannot revive an expired inner rumor.
|
||||
#expect(NostrInboundPipeline.isAcceptableGiftWrapTimestamp(nowSeconds, now: now))
|
||||
#expect(!NostrInboundPipeline.isPlausibleRumorTimestamp(1_699_912_699, now: now))
|
||||
#expect(!NostrInboundPipeline.isAcceptableGiftWrapTimestamp(1_700_000_901, now: now))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user