From 4a555b9d83ccfad0a8cc84a59497e8055bd845bf Mon Sep 17 00:00:00 2001 From: Taksh Date: Fri, 4 Sep 2026 22:50:25 +0530 Subject: [PATCH 1/6] Accept Android-aged gift wraps and gate outer timestamps Android randomizes outer gift-wrap created_at up to 48h into the past. iOS subscribed with a 24h since filter and decrypted before any outer age check, so relays that honor since silently dropped those DMs and a hostile relay could still force ECDH work with ancient or far-future wraps. Look back 48h+skew for gift-wrap subscriptions, reject implausible outer timestamps before decrypt, and keep the inner rumor window at 24h. --- .../MessageDeduplicationService.swift | 9 ++++--- .../Services/NostrProcessedEventStore.swift | 5 ++-- bitchat/Services/TransportConfig.swift | 11 +++++--- .../GeohashSubscriptionManager.swift | 6 ++--- bitchat/ViewModels/NostrInboundPipeline.swift | 25 +++++++++++++++++++ .../NostrInboundPipelineTimestampTests.swift | 18 +++++++++++++ 6 files changed, 62 insertions(+), 12 deletions(-) diff --git a/bitchat/Services/MessageDeduplicationService.swift b/bitchat/Services/MessageDeduplicationService.swift index 693365ca..8232dcbf 100644 --- a/bitchat/Services/MessageDeduplicationService.swift +++ b/bitchat/Services/MessageDeduplicationService.swift @@ -171,10 +171,11 @@ final class MessageDeduplicationService { private let nostrAckCache: LRUDeduplicationCache /// 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 diff --git a/bitchat/Services/NostrProcessedEventStore.swift b/bitchat/Services/NostrProcessedEventStore.swift index ee70f0e7..08a0e2d8 100644 --- a/bitchat/Services/NostrProcessedEventStore.swift +++ b/bitchat/Services/NostrProcessedEventStore.swift @@ -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). diff --git a/bitchat/Services/TransportConfig.swift b/bitchat/Services/TransportConfig.swift index b1e19701..8d17f9ea 100644 --- a/bitchat/Services/TransportConfig.swift +++ b/bitchat/Services/TransportConfig.swift @@ -215,11 +215,16 @@ 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 + // accept window is 48h plus skew so a wrap at the randomization floor + // still clears a mildly slow clock. + static let nostrGiftWrapMaxAgeSeconds: TimeInterval = 172_800 + 900 // A sampled chat message this recent means "a conversation is happening // there" for the empty-timeline nearby-activity hint. static let uiGeohashChatActivityWindowSeconds: TimeInterval = 900 diff --git a/bitchat/ViewModels/GeohashSubscriptionManager.swift b/bitchat/ViewModels/GeohashSubscriptionManager.swift index ce4c9448..0f2cf094 100644 --- a/bitchat/ViewModels/GeohashSubscriptionManager.swift +++ b/bitchat/ViewModels/GeohashSubscriptionManager.swift @@ -164,7 +164,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 @@ -262,7 +262,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 @@ -390,7 +390,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 diff --git a/bitchat/ViewModels/NostrInboundPipeline.swift b/bitchat/ViewModels/NostrInboundPipeline.swift index a6592802..d936f3f7 100644 --- a/bitchat/ViewModels/NostrInboundPipeline.swift +++ b/bitchat/ViewModels/NostrInboundPipeline.swift @@ -347,6 +347,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 @@ -446,6 +456,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, @@ -568,6 +583,16 @@ 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 48h randomization ceiling plus 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 { diff --git a/bitchatTests/NostrInboundPipelineTimestampTests.swift b/bitchatTests/NostrInboundPipelineTimestampTests.swift index 187133be..7267a8cd 100644 --- a/bitchatTests/NostrInboundPipelineTimestampTests.swift +++ b/bitchatTests/NostrInboundPipelineTimestampTests.swift @@ -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,21 @@ 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 48h-plus-skew 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)) + } } From ba3f7d6e7d92ef2f640eaa6d288c3d1f143904e8 Mon Sep 17 00:00:00 2001 From: Taksh Date: Fri, 4 Sep 2026 22:51:55 +0530 Subject: [PATCH 2/6] Randomize seal and gift-wrap timestamps up to 48h into the past iOS used a +/-15min jitter around now for seal and gift-wrap created_at. Android samples uniformly from the past 48h, which is what forces the wider gift-wrap subscription window. Match that past-only distribution so iOS envelopes get the same timing-correlation resistance and stay compatible with receivers that already look back 48h. --- bitchat/Nostr/NostrProtocol.swift | 34 +++++++++---------- bitchat/Services/TransportConfig.swift | 8 ++++- .../NostrInboundPipelineTimestampTests.swift | 17 ++++++++++ 3 files changed, 40 insertions(+), 19 deletions(-) diff --git a/bitchat/Nostr/NostrProtocol.swift b/bitchat/Nostr/NostrProtocol.swift index 2e3e35d8..7e3864e3 100644 --- a/bitchat/Nostr/NostrProtocol.swift +++ b/bitchat/Nostr/NostrProtocol.swift @@ -745,25 +745,23 @@ struct NostrProtocol { return sharedSecretData } + /// Randomized `created_at` for seals and gift wraps. Samples uniformly + /// from `[now − maxPast, now]` (never future) so relays cannot correlate + /// envelope timing with the true send time carried on the inner rumor. + /// Matches Android `NostrCrypto.randomizeTimestampUpToPast`. Internal so + /// tests can pin `now` / `maxPast`. + static func randomizedEnvelopeTimestamp( + now: Date = Date(), + maxPast: TimeInterval = TransportConfig.nostrGiftWrapTimestampRandomizationSeconds + ) -> Date { + let clampedPast = max(0, maxPast) + // Inclusive of both endpoints, matching Android's nextInt(maxPast+1). + let offsetSeconds = Int.random(in: 0...Int(clampedPast)) + return now.addingTimeInterval(-TimeInterval(offsetSeconds)) + } + private static func randomizedTimestamp() -> Date { - // Add random offset to current time for privacy - // This prevents timing correlation attacks while the actual message timestamp - // is preserved in the encrypted rumor - let offset = TimeInterval.random(in: -900...900) // +/- 15 minutes - let now = Date() - let randomized = now.addingTimeInterval(offset) - - // Log with explicit UTC and local time for debugging - let formatter = DateFormatter() - // - formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" - formatter.timeZone = TimeZone(abbreviation: "UTC") - - formatter.timeZone = TimeZone.current - - // Timestamp randomized for privacy - - return randomized + randomizedEnvelopeTimestamp() } } diff --git a/bitchat/Services/TransportConfig.swift b/bitchat/Services/TransportConfig.swift index 8d17f9ea..bddd94ef 100644 --- a/bitchat/Services/TransportConfig.swift +++ b/bitchat/Services/TransportConfig.swift @@ -219,12 +219,18 @@ enum TransportConfig { static let nostrDMSubscribeLookbackSeconds: TimeInterval = 86400 // Tolerated clock skew for client-side Nostr DM timestamp windows. static let nostrDMMaxClockSkewSeconds: TimeInterval = 900 + /// Outer gift-wrap / seal `created_at` randomization floor. Matches + /// Android `NostrCrypto.randomizeTimestampUpToPast` (up to 48h into the + /// past). The actual message time lives on the inner rumor. + static let nostrGiftWrapTimestampRandomizationSeconds: TimeInterval = 172_800 + // 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 // accept window is 48h plus skew so a wrap at the randomization floor // still clears a mildly slow clock. - static let nostrGiftWrapMaxAgeSeconds: TimeInterval = 172_800 + 900 + static let nostrGiftWrapMaxAgeSeconds: TimeInterval = + nostrGiftWrapTimestampRandomizationSeconds + 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 diff --git a/bitchatTests/NostrInboundPipelineTimestampTests.swift b/bitchatTests/NostrInboundPipelineTimestampTests.swift index 7267a8cd..74bbd9bc 100644 --- a/bitchatTests/NostrInboundPipelineTimestampTests.swift +++ b/bitchatTests/NostrInboundPipelineTimestampTests.swift @@ -48,3 +48,20 @@ struct NostrInboundPipelineTimestampTests { #expect(NostrInboundPipeline.isAcceptableGiftWrapTimestamp(nowSeconds - lookback - 3_600, now: now)) } } + +struct NostrEnvelopeTimestampRandomizationTests { + @Test("Envelope timestamps stay in [now-maxPast, now] and never go future") + func samplesPastOnlyWindow() { + let now = Date(timeIntervalSince1970: 1_700_000_000) + let maxPast: TimeInterval = 172_800 + for _ in 0..<200 { + let ts = NostrProtocol.randomizedEnvelopeTimestamp(now: now, maxPast: maxPast) + #expect(ts <= now) + #expect(ts >= now.addingTimeInterval(-maxPast)) + } + // Zero past collapses to exactly now. + #expect(NostrProtocol.randomizedEnvelopeTimestamp(now: now, maxPast: 0) == now) + // Negative past is treated as zero. + #expect(NostrProtocol.randomizedEnvelopeTimestamp(now: now, maxPast: -10) == now) + } +} From 7b9d319e4fa8c6e482e0e674484ceef317ba5b64 Mon Sep 17 00:00:00 2001 From: Taksh Date: Fri, 25 Sep 2026 15:43:31 +0530 Subject: [PATCH 3/6] Cap gift-wrap timestamp draw at lookback minus skew 48h randomization put half of wraps older than the 24h relay subscribe window every installed build still uses, so DMs and acks to not-yet-updated peers never arrived. Keep the 48h+skew accept gate for peers that still stamp that deep. --- bitchat/Nostr/NostrProtocol.swift | 12 +++++---- bitchat/Services/TransportConfig.swift | 25 +++++++++++-------- .../NostrInboundPipelineTimestampTests.swift | 15 +++++++++++ 3 files changed, 37 insertions(+), 15 deletions(-) diff --git a/bitchat/Nostr/NostrProtocol.swift b/bitchat/Nostr/NostrProtocol.swift index 7e3864e3..c323af36 100644 --- a/bitchat/Nostr/NostrProtocol.swift +++ b/bitchat/Nostr/NostrProtocol.swift @@ -745,11 +745,13 @@ struct NostrProtocol { return sharedSecretData } - /// Randomized `created_at` for seals and gift wraps. Samples uniformly - /// from `[now − maxPast, now]` (never future) so relays cannot correlate - /// envelope timing with the true send time carried on the inner rumor. - /// Matches Android `NostrCrypto.randomizeTimestampUpToPast`. Internal so - /// tests can pin `now` / `maxPast`. + /// Randomized `created_at` for the outer gift wrap (and the seal that + /// sits inside it). Samples uniformly from `[now − maxPast, now]` + /// (never future). Relays only see the wrap timestamp; the seal is + /// encrypted inside the wrap, so randomizing it is not observable to + /// anyone — callers still stamp both layers for parity with Android + /// `NostrCrypto.randomizeTimestampUpToPast`. The true send time lives + /// on the inner rumor. Internal so tests can pin `now` / `maxPast`. static func randomizedEnvelopeTimestamp( now: Date = Date(), maxPast: TimeInterval = TransportConfig.nostrGiftWrapTimestampRandomizationSeconds diff --git a/bitchat/Services/TransportConfig.swift b/bitchat/Services/TransportConfig.swift index 16731cce..1fa441be 100644 --- a/bitchat/Services/TransportConfig.swift +++ b/bitchat/Services/TransportConfig.swift @@ -224,18 +224,23 @@ enum TransportConfig { static let nostrDMSubscribeLookbackSeconds: TimeInterval = 86400 // Tolerated clock skew for client-side Nostr DM timestamp windows. static let nostrDMMaxClockSkewSeconds: TimeInterval = 900 - /// Outer gift-wrap / seal `created_at` randomization floor. Matches - /// Android `NostrCrypto.randomizeTimestampUpToPast` (up to 48h into the - /// past). The actual message time lives on the inner rumor. - static let nostrGiftWrapTimestampRandomizationSeconds: TimeInterval = 172_800 + /// Outer gift-wrap `created_at` randomization floor when *sending*. + /// Cap at lookback − skew so a wrap never lands older than + /// `nostrDMSubscribeLookbackSeconds` (every installed build still + /// subscribes `since: now − 86400`). A deeper draw would silently miss + /// half of DMs/acks to peers that have not yet widened their filter. + /// Android today draws up to 79_200s (`NIP17_DEFAULT_MAX_PAST_SECONDS`); + /// the true send time lives on the inner rumor either way. + static let nostrGiftWrapTimestampRandomizationSeconds: TimeInterval = + nostrDMSubscribeLookbackSeconds - nostrDMMaxClockSkewSeconds - // 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 - // accept window is 48h plus skew so a wrap at the randomization floor - // still clears a mildly slow clock. + // Outer gift-wrap age ceiling when *receiving*. Kept at the historical + // NIP-17 48h floor (+ skew) so wraps from peers that still randomize + // that deep (or that Android's 48h subscribe will deliver) are not + // dropped client-side after the relay hands them over. Independent of + // the send-side randomization above — do not derive one from the other. static let nostrGiftWrapMaxAgeSeconds: TimeInterval = - nostrGiftWrapTimestampRandomizationSeconds + nostrDMMaxClockSkewSeconds + 172_800 + 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 diff --git a/bitchatTests/NostrInboundPipelineTimestampTests.swift b/bitchatTests/NostrInboundPipelineTimestampTests.swift index 74bbd9bc..577f454c 100644 --- a/bitchatTests/NostrInboundPipelineTimestampTests.swift +++ b/bitchatTests/NostrInboundPipelineTimestampTests.swift @@ -64,4 +64,19 @@ struct NostrEnvelopeTimestampRandomizationTests { // Negative past is treated as zero. #expect(NostrProtocol.randomizedEnvelopeTimestamp(now: now, maxPast: -10) == now) } + + @Test("Default send randomization stays inside the 24h subscribe lookback") + func defaultDrawStaysInsideLookback() { + let now = Date(timeIntervalSince1970: 1_700_000_000) + let lookback = TransportConfig.nostrDMSubscribeLookbackSeconds + let maxPast = TransportConfig.nostrGiftWrapTimestampRandomizationSeconds + #expect(maxPast == lookback - TransportConfig.nostrDMMaxClockSkewSeconds) + for _ in 0..<200 { + let ts = NostrProtocol.randomizedEnvelopeTimestamp(now: now) + #expect(ts <= now) + #expect(ts >= now.addingTimeInterval(-maxPast)) + // Relays that honor `since: now − lookback` must still return it. + #expect(ts >= now.addingTimeInterval(-lookback)) + } + } } From cdb1faaabab5d5606c68ed6708133e63982a6de0 Mon Sep 17 00:00:00 2001 From: Taksh Date: Wed, 30 Sep 2026 10:36:23 +0530 Subject: [PATCH 4/6] fix: draw gift-wrap timestamps over 22h to match Android MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 85,500 still loses DMs as the 24h since-window recedes; use 79,200 and update the whitepaper line that still claimed ±15 minutes. Co-authored-by: Cursor --- WHITEPAPER.md | 2 +- bitchat/Services/TransportConfig.swift | 16 ++++++++-------- .../NostrInboundPipelineTimestampTests.swift | 4 +++- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/WHITEPAPER.md b/WHITEPAPER.md index 75e346fb..c855a7a7 100644 --- a/WHITEPAPER.md +++ b/WHITEPAPER.md @@ -84,7 +84,7 @@ Courier envelopes are sealed to the recipient's *static* key with the one-way No Private messages to mutual favorites use BitChat's proprietary private-envelope protocol. An unsigned inner message (kind 14) is encrypted and placed in a sender-signed seal (kind 13); that seal is encrypted again inside a public envelope (kind 1059) signed by a one-time key, so relays learn neither the stable sender identity nor the content. Each encrypted content field is `v2:` followed by base64url of a 24-byte nonce, XChaCha20-Poly1305 ciphertext, and its 16-byte tag. Keys come from secp256k1 ECDH and HKDF-SHA256 (the derivation reuses a "nip44-v2" info label but is not the NIP-44 key schedule). -This format reuses NIP-17/NIP-59 kind numbers but is **not NIP-17, NIP-44, or NIP-59 compatible** and interoperates only with BitChat clients. The outer `p` tag exposes the recipient's Nostr public key to relays; the plaintext and stable sender identity remain inside authenticated ciphertext. Public seal and envelope timestamps are randomized by up to ±15 minutes, while the actual message timestamp is encrypted. The protocol does not provide forward secrecy: compromise of the recipient's static Nostr private key can expose stored envelopes addressed to that key. +This format reuses NIP-17/NIP-59 kind numbers but is **not NIP-17, NIP-44, or NIP-59 compatible** and interoperates only with BitChat clients. The outer `p` tag exposes the recipient's Nostr public key to relays; the plaintext and stable sender identity remain inside authenticated ciphertext. Public seal and envelope timestamps are randomized uniformly into the past up to 22 hours (matching Android; never future-dated), while the actual message timestamp is encrypted. The protocol does not provide forward secrecy: compromise of the recipient's static Nostr private key can expose stored envelopes addressed to that key. ## 6. Store and Forward diff --git a/bitchat/Services/TransportConfig.swift b/bitchat/Services/TransportConfig.swift index 1fa441be..1aeb5cc6 100644 --- a/bitchat/Services/TransportConfig.swift +++ b/bitchat/Services/TransportConfig.swift @@ -225,14 +225,14 @@ enum TransportConfig { // Tolerated clock skew for client-side Nostr DM timestamp windows. static let nostrDMMaxClockSkewSeconds: TimeInterval = 900 /// Outer gift-wrap `created_at` randomization floor when *sending*. - /// Cap at lookback − skew so a wrap never lands older than - /// `nostrDMSubscribeLookbackSeconds` (every installed build still - /// subscribes `since: now − 86400`). A deeper draw would silently miss - /// half of DMs/acks to peers that have not yet widened their filter. - /// Android today draws up to 79_200s (`NIP17_DEFAULT_MAX_PAST_SECONDS`); - /// the true send time lives on the inner rumor either way. - static let nostrGiftWrapTimestampRandomizationSeconds: TimeInterval = - nostrDMSubscribeLookbackSeconds - nostrDMMaxClockSkewSeconds + /// Match Android's `NIP17_DEFAULT_MAX_PAST_SECONDS` (79_200 = 22h): every + /// installed build still subscribes `since: now − 86400`, and that window + /// keeps receding after send, so lookback − skew (85_500) still loses DMs + /// to a peer who comes online hours later. The two-hour margin reserves + /// room for that recession until #1706's wider subscribe is everywhere. + /// Accept stays at 48h+skew below so older Android wraps still clear. + /// The true send time lives on the inner rumor either way. + static let nostrGiftWrapTimestampRandomizationSeconds: TimeInterval = 79_200 // Outer gift-wrap age ceiling when *receiving*. Kept at the historical // NIP-17 48h floor (+ skew) so wraps from peers that still randomize diff --git a/bitchatTests/NostrInboundPipelineTimestampTests.swift b/bitchatTests/NostrInboundPipelineTimestampTests.swift index 577f454c..f48b44f4 100644 --- a/bitchatTests/NostrInboundPipelineTimestampTests.swift +++ b/bitchatTests/NostrInboundPipelineTimestampTests.swift @@ -70,7 +70,9 @@ struct NostrEnvelopeTimestampRandomizationTests { let now = Date(timeIntervalSince1970: 1_700_000_000) let lookback = TransportConfig.nostrDMSubscribeLookbackSeconds let maxPast = TransportConfig.nostrGiftWrapTimestampRandomizationSeconds - #expect(maxPast == lookback - TransportConfig.nostrDMMaxClockSkewSeconds) + // Match Android's 22h draw (two-hour margin under the 24h subscribe). + #expect(maxPast == 79_200) + #expect(maxPast < lookback - TransportConfig.nostrDMMaxClockSkewSeconds) for _ in 0..<200 { let ts = NostrProtocol.randomizedEnvelopeTimestamp(now: now) #expect(ts <= now) From 45b5eed2fe985118668017e68ec4ee88aa0e127b Mon Sep 17 00:00:00 2001 From: Taksh Date: Wed, 30 Sep 2026 22:21:22 +0530 Subject: [PATCH 5/6] fix: preserve the delivery window for queued gift wraps --- bitchat/Services/TransportConfig.swift | 17 ++++++----- bitchat/ViewModels/NostrInboundPipeline.swift | 14 ++++----- .../NostrInboundPipelineTimestampTests.swift | 29 ++++++++++++++++++- 3 files changed, 43 insertions(+), 17 deletions(-) diff --git a/bitchat/Services/TransportConfig.swift b/bitchat/Services/TransportConfig.swift index 1aeb5cc6..785f7bdc 100644 --- a/bitchat/Services/TransportConfig.swift +++ b/bitchat/Services/TransportConfig.swift @@ -230,17 +230,18 @@ enum TransportConfig { /// keeps receding after send, so lookback − skew (85_500) still loses DMs /// to a peer who comes online hours later. The two-hour margin reserves /// room for that recession until #1706's wider subscribe is everywhere. - /// Accept stays at 48h+skew below so older Android wraps still clear. + /// Receive-side age limits independently allow queued older wraps. /// The true send time lives on the inner rumor either way. static let nostrGiftWrapTimestampRandomizationSeconds: TimeInterval = 79_200 - // Outer gift-wrap age ceiling when *receiving*. Kept at the historical - // NIP-17 48h floor (+ skew) so wraps from peers that still randomize - // that deep (or that Android's 48h subscribe will deliver) are not - // dropped client-side after the relay hands them over. Independent of - // the send-side randomization above — do not derive one from the other. - static let nostrGiftWrapMaxAgeSeconds: TimeInterval = - 172_800 + nostrDMMaxClockSkewSeconds + // 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 diff --git a/bitchat/ViewModels/NostrInboundPipeline.swift b/bitchat/ViewModels/NostrInboundPipeline.swift index d936f3f7..0d54d599 100644 --- a/bitchat/ViewModels/NostrInboundPipeline.swift +++ b/bitchat/ViewModels/NostrInboundPipeline.swift @@ -570,12 +570,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) @@ -585,8 +582,9 @@ extension NostrInboundPipeline { } /// Accept an outer gift-wrap `created_at` that is not in the far future - /// and not older than the 48h randomization ceiling plus skew. Checked - /// before decrypt so a hostile relay cannot force ECDH work with + /// 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) diff --git a/bitchatTests/NostrInboundPipelineTimestampTests.swift b/bitchatTests/NostrInboundPipelineTimestampTests.swift index f48b44f4..fcc65d44 100644 --- a/bitchatTests/NostrInboundPipelineTimestampTests.swift +++ b/bitchatTests/NostrInboundPipelineTimestampTests.swift @@ -31,7 +31,7 @@ struct NostrInboundPipelineTimestampTests { #expect(!NostrInboundPipeline.isPlausibleRumorTimestamp(nowSeconds - lookback - skew - 60, now: now)) } - @Test("Outer gift wraps inside the 48h-plus-skew window are accepted") + @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. @@ -47,6 +47,33 @@ struct NostrInboundPipelineTimestampTests { // 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)) + } + } struct NostrEnvelopeTimestampRandomizationTests { From fdf74ea830272e435ebe2cbe5bb7ef00dc42f61f Mon Sep 17 00:00:00 2001 From: Taksh Date: Wed, 30 Sep 2026 22:36:00 +0530 Subject: [PATCH 6/6] fix: expand bounded gift-wrap backfill requests --- bitchat/Nostr/NostrRelayManager.swift | 2 +- bitchat/Services/TransportConfig.swift | 5 ++++- bitchatTests/NostrProtocolTests.swift | 21 +++++++++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/bitchat/Nostr/NostrRelayManager.swift b/bitchat/Nostr/NostrRelayManager.swift index 6601b863..19302781 100644 --- a/bitchat/Nostr/NostrRelayManager.swift +++ b/bitchat/Nostr/NostrRelayManager.swift @@ -1867,7 +1867,7 @@ struct NostrFilter: Encodable { filter.kinds = [1059] // Gift wrap kind filter.since = since?.timeIntervalSince1970.toInt() filter.tagFilters = ["p": [pubkey]] - filter.limit = TransportConfig.nostrRelayDefaultFetchLimit // reasonable limit + filter.limit = TransportConfig.nostrGiftWrapFetchLimit return filter } diff --git a/bitchat/Services/TransportConfig.swift b/bitchat/Services/TransportConfig.swift index 785f7bdc..c8cf68fb 100644 --- a/bitchat/Services/TransportConfig.swift +++ b/bitchat/Services/TransportConfig.swift @@ -269,7 +269,10 @@ enum TransportConfig { // Reconnect delays get ±20% random jitter so relays that dropped together // (e.g. a network blip) don't thundering-herd the same reconnect instant. static let nostrRelayBackoffJitterRatio: Double = 0.2 - static let nostrRelayDefaultFetchLimit: Int = 100 + // Randomized envelope timestamps can put a recent DM behind older rumors. + // Match the existing location backfill allowance, while keeping requests bounded. + // Relays may impose a lower cap; this is not complete history pagination. + static let nostrGiftWrapFetchLimit: Int = 1000 // How many consecutive Tor-readiness waits (each bounded by TorManager's // bootstrap deadline) to attempt before unblocking pending EOSE callers. static let nostrTorReadyMaxWaitAttempts: Int = 3 diff --git a/bitchatTests/NostrProtocolTests.swift b/bitchatTests/NostrProtocolTests.swift index f63928c9..c86899ed 100644 --- a/bitchatTests/NostrProtocolTests.swift +++ b/bitchatTests/NostrProtocolTests.swift @@ -453,6 +453,27 @@ struct NostrProtocolTests { #expect(!signed.isValidSignature()) } + @Test func giftWrapFilter_requestsExpandedBoundedBackfill() throws { + let since = Date(timeIntervalSince1970: 1_699_739_900) + let filter = NostrFilter.giftWrapsFor(pubkey: "recipient", since: since) + let data = try JSONEncoder().encode(filter) + let object = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + let limit = try #require(object["limit"] as? Int) + + #expect(object["kinds"] as? [Int] == [1059]) + #expect(object["#p"] as? [String] == ["recipient"]) + #expect(object["since"] as? Int == 1_699_739_900) + #expect(limit == 1000) + + // Model a relay honoring the requested cap and sorting by outer created_at. + // A freshly sent rumor can have an older envelope than 100 retained wraps. + let recentRumorEnvelope = 1_699_920_800 + let retainedEnvelopes = (0..<100).map { 1_699_990_000 + $0 } + let newestFirst = (retainedEnvelopes + [recentRumorEnvelope]).sorted(by: >) + #expect(!newestFirst.prefix(100).contains(recentRumorEnvelope)) + #expect(newestFirst.prefix(limit).contains(recentRumorEnvelope)) + } + @Test func geohashNotesSingleFilter_encodesExpectedTagShape() throws { let since = Date(timeIntervalSince1970: 1_234_567) let filter = NostrFilter.geohashNotes("u4pruyd", since: since, limit: 42)