mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-27 16:05:18 +00:00
Keep working when the network is hostile, and make the app verifiable (#1486)
Tier 3 of a protest-hardening review. The BLE mesh is already properly fenced off from network reachability and needs nothing here; every gap is on the internet side, or in how someone gets a build they can trust. Say when Tor is blocked. The bootstrap poll loop simply ended at its 75-second deadline, leaving isStarting true with no further state, so a network that blocks Tor was indistinguishable from a slow one and the UI said "starting tor…" indefinitely. TorManager now exposes bootstrapDidStall and posts .TorBootstrapDidStall, and the app reports that mesh messaging still works while internet delivery is paused. It is cleared on each new start or restart, so a later attempt can report again. Let relays be added by hand. The four built-in relays are well-known clearnet hostnames, which is four names for a censor to block and no recourse short of a new build. NostrRelaySettings persists up to eight additional relays, normalized, .onion accepted, with a settings editor. They join the same target set as the built-ins and are subject to the same activation policy. Removal reconciles against the previous set: the teardown path iterates the current targets, so without that a removed relay's socket and queued sends would linger — covered by a test that fails without it. The merged list is cached rather than recomputed, because allowedRelayList consults it once per candidate URL and would otherwise read UserDefaults inside that loop. Stop stranding people who denied location. The activation gate required location permission or a mutual favorite, but teleporting into a geohash requires neither, so someone with no permission and no favorites could sit in a channel that never connected while Tor and the relays stayed suppressed and nothing said why. Being in a location channel is now a third arm of the gate, in both the activation service and the relay manager's copy of the policy, and leaving the channel closes it again. Stop burning the Tor timeout when Tor is off. GeoRelayDirectory awaited Tor readiness unconditionally, but with the preference off TorManager has been shut down, so every refresh spent the full bootstrap deadline and the directory froze on its cached copy. It now keys on the preference, not on live readiness: Tor wanted but unavailable must still skip the fetch rather than fall back to clearnet. Say what turning Tor off costs. The toggle's copy described it as hiding your IP "for location channels", understating both scope and consequence. It now names private messages too, and while the toggle is off the settings screen states that every relay can see the device IP. Make builds verifiable. There was no release verification of any kind: no signatures, no checksums, no documented procedure. Post-takedown that is the acute gap, because mirrors appear and people install whatever they can find during a shutdown. source-manifest.yml publishes a per-tag SHA-256 manifest with a provenance attestation, self-checking before it publishes, and docs/VERIFYING-A-BUILD.md explains how to verify source and states plainly that compiled builds from anywhere but the App Store cannot be verified. It also records the gaps honestly: no published signing key, no reproducible build, no non-GitHub mirror. docs/TOR-INTEGRATION.md was substantially stale — it documented a torrc, SOCKSPort and ControlPort that the in-process Arti client does not use, and claimed there are no user-visible settings — so it is rewritten, including the deferred gap below. Deferred: no Tor bridges or pluggable transports. arti-client is built without pt-client or bridge-client and bootstraps from stock config, so in a country that blocks Tor outright there is still no circumvention path — only a clear report that there isn't. Closing it needs the Rust features, bridge config through the FFI, and an xcframework rebuild under the pinned toolchain with a provenance update, which is its own change. Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
jack
Claude Opus 5
parent
c079d2ab5d
commit
c1ce9029d8
@@ -13,6 +13,8 @@ enum TorLifecycleEvent: String, Sendable, Equatable {
|
||||
case willRestart
|
||||
case didBecomeReady
|
||||
case preferenceChanged
|
||||
/// Bootstrap ran out its deadline without completing.
|
||||
case bootstrapDidStall
|
||||
}
|
||||
|
||||
enum AppEvent: Sendable, Equatable {
|
||||
|
||||
@@ -329,6 +329,16 @@ private extension AppRuntime {
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
NotificationCenter.default.publisher(for: .TorBootstrapDidStall)
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] _ in
|
||||
guard self?.chatViewModel.networkActivationAllowed == true
|
||||
else { return }
|
||||
self?.record(.torLifecycleChanged(.bootstrapDidStall))
|
||||
self?.chatViewModel.handleTorBootstrapDidStall()
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
NotificationCenter.default.publisher(for: .TorUserPreferenceChanged)
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] notification in
|
||||
|
||||
+2232
-185
File diff suppressed because it is too large
Load Diff
@@ -75,7 +75,19 @@ private extension GeoRelayDirectoryDependencies {
|
||||
refreshCheckInterval: TransportConfig.geoRelayRefreshCheckIntervalSeconds,
|
||||
retryInitialSeconds: TransportConfig.geoRelayRetryInitialSeconds,
|
||||
retryMaxSeconds: TransportConfig.geoRelayRetryMaxSeconds,
|
||||
awaitTorReady: { await TorManager.shared.awaitReady() },
|
||||
// Only wait for Tor when Tor is switched on. With it off, the fetch
|
||||
// is meant to go direct through the same unproxied session the relay
|
||||
// sockets already use — and `TorManager` has been shut down, so
|
||||
// awaiting readiness would spend the whole bootstrap timeout on
|
||||
// every refresh and freeze the directory on its cached copy.
|
||||
//
|
||||
// Deliberately keyed on the preference rather than live readiness:
|
||||
// if Tor is wanted but not ready, this must keep returning false so
|
||||
// the fetch is skipped instead of silently leaking the IP.
|
||||
awaitTorReady: {
|
||||
guard NetworkActivationService.persistedTorPreference() else { return true }
|
||||
return await TorManager.shared.awaitReady()
|
||||
},
|
||||
makeFetchData: {
|
||||
let session = TorURLSession.shared.session
|
||||
return { request in
|
||||
|
||||
@@ -76,6 +76,18 @@ struct NostrRelayManagerDependencies {
|
||||
/// Uniform random value in [0, 1) used to jitter reconnect backoff.
|
||||
/// Injectable so tests can pin or sweep the jitter deterministically.
|
||||
var jitterUnit: () -> Double
|
||||
/// Where relay-settings changes are observed. Injectable so a test can use
|
||||
/// its own center instead of racing the process-wide one.
|
||||
var notificationCenter: NotificationCenter = .default
|
||||
/// Relays added by hand, merged with the built-in set. Injectable so tests
|
||||
/// do not have to write to shared preferences.
|
||||
var customRelays: () -> [String] = { NostrRelaySettings.customRelays() }
|
||||
/// Whether a location channel is currently open. Mirrors the third arm of
|
||||
/// `NetworkActivationService`'s gate: teleporting into a geohash needs no
|
||||
/// location permission, and without this the relays would stay filtered out
|
||||
/// for someone who denied location and has no mutual favorites.
|
||||
var isInLocationChannel: () -> Bool = { false }
|
||||
var selectedChannelPublisher: AnyPublisher<ChannelID, Never> = Empty().eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
private extension NostrRelayManagerDependencies {
|
||||
@@ -104,7 +116,12 @@ private extension NostrRelayManagerDependencies {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: action)
|
||||
},
|
||||
now: Date.init,
|
||||
jitterUnit: { Double.random(in: 0..<1) }
|
||||
jitterUnit: { Double.random(in: 0..<1) },
|
||||
isInLocationChannel: {
|
||||
if case .location = LocationChannelManager.shared.selectedChannel { return true }
|
||||
return false
|
||||
},
|
||||
selectedChannelPublisher: LocationChannelManager.shared.$selectedChannel.eraseToAnyPublisher()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -134,15 +151,40 @@ final class NostrRelayManager: ObservableObject {
|
||||
var nextReconnectTime: Date?
|
||||
}
|
||||
|
||||
// Default relays carry NIP-17 gift wraps, so avoid relays known to reject kind 1059.
|
||||
private static let defaultRelays = [
|
||||
// Built-in relays carry private-message envelopes, so avoid relays known to
|
||||
// reject the kinds they use.
|
||||
private static let builtInRelays = [
|
||||
"wss://relay.damus.io",
|
||||
"wss://nos.lol",
|
||||
"wss://relay.primal.net",
|
||||
"wss://offchain.pub"
|
||||
// For local testing, you can add: "ws://localhost:8080"
|
||||
]
|
||||
private static let defaultRelaySet = Set(defaultRelays.compactMap { NostrRelayURL.normalized($0) })
|
||||
private static let builtInRelaySet = Set(builtInRelays.compactMap { NostrRelayURL.normalized($0) })
|
||||
|
||||
/// The relays private messages target: the built-in set plus any added by
|
||||
/// hand. Four hardcoded hostnames are four names for a censor to block, so
|
||||
/// the added ones are what keeps this reachable without a new build.
|
||||
///
|
||||
/// Cached rather than computed per access: `allowedRelayList` consults the
|
||||
/// set once per candidate URL, and recomputing would mean a `UserDefaults`
|
||||
/// read and a fresh normalize-and-dedupe pass inside that loop. Refreshed
|
||||
/// from `reloadDefaultRelays()` on construction and whenever the relay
|
||||
/// settings change.
|
||||
private var defaultRelays: [String] = []
|
||||
private var defaultRelaySet: Set<String> = []
|
||||
|
||||
private func reloadDefaultRelays() {
|
||||
var seen = Set<String>()
|
||||
defaultRelays = (Self.builtInRelays + dependencies.customRelays())
|
||||
.compactMap { NostrRelayURL.normalized($0) }
|
||||
.filter { seen.insert($0).inserted }
|
||||
defaultRelaySet = Set(defaultRelays)
|
||||
}
|
||||
|
||||
/// Exposed so the relay settings UI can reject re-adding a built-in.
|
||||
/// `nonisolated` because it is an immutable constant with no actor state.
|
||||
nonisolated static var builtInRelayURLs: Set<String> { builtInRelaySet }
|
||||
|
||||
@Published private(set) var relays: [Relay] = []
|
||||
@Published private(set) var isConnected = false
|
||||
@@ -276,37 +318,15 @@ final class NostrRelayManager: ObservableObject {
|
||||
// off-main; the yield stays cheap.
|
||||
private let inboundRouter = InboundFrameRouter()
|
||||
|
||||
init() {
|
||||
self.dependencies = .live()
|
||||
hasMutualFavorites = dependencies.hasMutualFavorites()
|
||||
hasLocationPermission = dependencies.hasLocationPermission()
|
||||
applyDefaultRelayPolicy(force: true)
|
||||
// Deterministic JSON shape for outbound requests
|
||||
self.encoder.outputFormatting = .sortedKeys
|
||||
dependencies.mutualFavoritesPublisher
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] favorites in
|
||||
guard let self = self else { return }
|
||||
self.hasMutualFavorites = !favorites.isEmpty
|
||||
self.applyDefaultRelayPolicy()
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
dependencies.locationPermissionPublisher
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] state in
|
||||
guard let self = self else { return }
|
||||
let authorized = (state == .authorized)
|
||||
if authorized == self.hasLocationPermission { return }
|
||||
self.hasLocationPermission = authorized
|
||||
self.applyDefaultRelayPolicy()
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
convenience init() {
|
||||
self.init(dependencies: .live())
|
||||
}
|
||||
|
||||
internal init(dependencies: NostrRelayManagerDependencies) {
|
||||
self.dependencies = dependencies
|
||||
hasMutualFavorites = dependencies.hasMutualFavorites()
|
||||
hasLocationPermission = dependencies.hasLocationPermission()
|
||||
reloadDefaultRelays()
|
||||
applyDefaultRelayPolicy(force: true)
|
||||
// Deterministic JSON shape for outbound requests
|
||||
self.encoder.outputFormatting = .sortedKeys
|
||||
@@ -328,6 +348,28 @@ final class NostrRelayManager: ObservableObject {
|
||||
self.applyDefaultRelayPolicy()
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
dependencies.selectedChannelPublisher
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] _ in
|
||||
self?.applyDefaultRelayPolicy()
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
// Adding or removing a relay by hand changes the target set, so
|
||||
// reconcile connections now rather than at the next send.
|
||||
dependencies.notificationCenter
|
||||
.publisher(for: NostrRelaySettings.didChangeNotification)
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] _ in
|
||||
guard let self else { return }
|
||||
// Reconcile against the previous set: a removed relay is no
|
||||
// longer in `defaultRelays`, so nothing downstream would ever
|
||||
// close its socket or drop its queued sends.
|
||||
let previous = self.defaultRelaySet
|
||||
self.reloadDefaultRelays()
|
||||
self.dropRelays(previous.subtracting(self.defaultRelaySet))
|
||||
self.applyDefaultRelayPolicy(force: true)
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -509,13 +551,13 @@ final class NostrRelayManager: ObservableObject {
|
||||
// event locally so it survives a slow bootstrap (queued sends flush
|
||||
// when relays connect), then kick off connection setup, which itself
|
||||
// waits for Tor readiness.
|
||||
let targetRelays = allowedRelayList(from: relayUrls ?? Self.defaultRelays)
|
||||
let targetRelays = allowedRelayList(from: relayUrls ?? defaultRelays)
|
||||
guard !targetRelays.isEmpty else { return }
|
||||
enqueuePendingSend(event, pendingRelays: Set(targetRelays))
|
||||
ensureConnections(to: targetRelays)
|
||||
return
|
||||
}
|
||||
let requestedRelays = relayUrls ?? Self.defaultRelays
|
||||
let requestedRelays = relayUrls ?? defaultRelays
|
||||
let targetRelays = allowedRelayList(from: requestedRelays)
|
||||
guard !targetRelays.isEmpty else { return }
|
||||
ensureConnections(to: targetRelays)
|
||||
@@ -554,7 +596,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
return
|
||||
}
|
||||
|
||||
let requestedRelays = relayUrls ?? Self.defaultRelays
|
||||
let requestedRelays = relayUrls ?? defaultRelays
|
||||
let targetRelays = allowedRelayList(from: requestedRelays)
|
||||
let connectedTargets = targetRelays.compactMap { relayUrl -> (String, NostrRelayConnectionProtocol)? in
|
||||
guard let connection = connectedConnection(for: relayUrl) else { return nil }
|
||||
@@ -723,7 +765,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
// SecureLogger.debug("📋 Subscription filter JSON: \(messageString.prefix(200))...", category: .session)
|
||||
|
||||
// Target specific relays if provided; else default. Filter permanently failed relays.
|
||||
let baseUrls = relayUrls ?? Self.defaultRelays
|
||||
let baseUrls = relayUrls ?? defaultRelays
|
||||
let urls = allowedRelayList(from: baseUrls).filter { !isPermanentlyFailed($0) }
|
||||
let requestState = SubscriptionRequestState(messageString: messageString, relayURLs: Set(urls))
|
||||
if subscriptionRequestState[id] == requestState, subscriptionStateExists(id: id, requestState: requestState) {
|
||||
@@ -765,50 +807,57 @@ final class NostrRelayManager: ObservableObject {
|
||||
}
|
||||
|
||||
private func applyDefaultRelayPolicy(force: Bool = false) {
|
||||
let shouldAllow = hasMutualFavorites || hasLocationPermission
|
||||
let shouldAllow = hasMutualFavorites || hasLocationPermission || dependencies.isInLocationChannel()
|
||||
if !force && shouldAllow == allowDefaultRelays { return }
|
||||
allowDefaultRelays = shouldAllow
|
||||
if shouldAllow {
|
||||
var existing = Set(relays.map { $0.url })
|
||||
for url in Self.defaultRelays where !existing.contains(url) {
|
||||
for url in defaultRelays where !existing.contains(url) {
|
||||
relays.append(Relay(url: url))
|
||||
existing.insert(url)
|
||||
}
|
||||
if dependencies.activationAllowed() {
|
||||
ensureConnections(to: Self.defaultRelays)
|
||||
ensureConnections(to: defaultRelays)
|
||||
}
|
||||
} else {
|
||||
for url in Self.defaultRelays {
|
||||
if let connection = connections[url] {
|
||||
connection.cancel(with: .goingAway, reason: nil)
|
||||
}
|
||||
connections.removeValue(forKey: url)
|
||||
teardownRelayInboundPipeline(for: url)
|
||||
subscriptions.removeValue(forKey: url)
|
||||
pendingSubscriptions.removeValue(forKey: url)
|
||||
}
|
||||
messageQueueLock.lock()
|
||||
for index in (0..<messageQueue.count).reversed() {
|
||||
var item = messageQueue[index]
|
||||
item.pendingRelays.subtract(Self.defaultRelaySet)
|
||||
if item.pendingRelays.isEmpty {
|
||||
messageQueue.remove(at: index)
|
||||
} else {
|
||||
messageQueue[index] = item
|
||||
}
|
||||
}
|
||||
messageQueueLock.unlock()
|
||||
relays.removeAll { Self.defaultRelaySet.contains($0.url) }
|
||||
updateConnectionStatus()
|
||||
dropRelays(defaultRelaySet)
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes and forgets a set of relays: connection, inbound pipeline,
|
||||
/// subscriptions, queued sends addressed only to them, and the published row.
|
||||
private func dropRelays(_ urls: Set<String>) {
|
||||
guard !urls.isEmpty else { return }
|
||||
for url in urls {
|
||||
if let connection = connections[url] {
|
||||
connection.cancel(with: .goingAway, reason: nil)
|
||||
}
|
||||
connections.removeValue(forKey: url)
|
||||
teardownRelayInboundPipeline(for: url)
|
||||
subscriptions.removeValue(forKey: url)
|
||||
pendingSubscriptions.removeValue(forKey: url)
|
||||
}
|
||||
messageQueueLock.lock()
|
||||
for index in (0..<messageQueue.count).reversed() {
|
||||
var item = messageQueue[index]
|
||||
item.pendingRelays.subtract(urls)
|
||||
if item.pendingRelays.isEmpty {
|
||||
messageQueue.remove(at: index)
|
||||
} else {
|
||||
messageQueue[index] = item
|
||||
}
|
||||
}
|
||||
messageQueueLock.unlock()
|
||||
relays.removeAll { urls.contains($0.url) }
|
||||
updateConnectionStatus()
|
||||
}
|
||||
|
||||
private func allowedRelayList(from urls: [String]) -> [String] {
|
||||
var seen = Set<String>()
|
||||
var result: [String] = []
|
||||
for rawURL in urls {
|
||||
guard let url = NostrRelayURL.normalized(rawURL) else { continue }
|
||||
if !allowDefaultRelays && Self.defaultRelaySet.contains(url) { continue }
|
||||
if !allowDefaultRelays && defaultRelaySet.contains(url) { continue }
|
||||
if seen.insert(url).inserted {
|
||||
result.append(url)
|
||||
}
|
||||
@@ -1366,7 +1415,7 @@ final class NostrRelayManager: ObservableObject {
|
||||
isConnected = relays.contains { $0.isConnected }
|
||||
// Relay URLs are normalized before entries are created, so direct
|
||||
// set membership is sound.
|
||||
isDMRelayConnected = relays.contains { $0.isConnected && Self.defaultRelaySet.contains($0.url) }
|
||||
isDMRelayConnected = relays.contains { $0.isConnected && defaultRelaySet.contains($0.url) }
|
||||
}
|
||||
|
||||
/// A relay that drops before sending EOSE must not stall initial-load
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
//
|
||||
// NostrRelaySettings.swift
|
||||
// bitchat
|
||||
//
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
// For more information, see <https://unlicense.org>
|
||||
//
|
||||
|
||||
import BitLogger
|
||||
import Foundation
|
||||
|
||||
/// Relays someone has added by hand, alongside the built-in set.
|
||||
///
|
||||
/// The built-in relays are four well-known clearnet hostnames, so a censor
|
||||
/// blocking four names ends internet-delivered private messages for everyone.
|
||||
/// Adding relays — including `.onion` addresses, or a relay run by whoever
|
||||
/// needs it — is the escape hatch that does not require shipping a new build.
|
||||
///
|
||||
/// Stored normalized so comparisons against connection keys and the built-in
|
||||
/// set are exact, and bounded so a long list cannot turn every send into a
|
||||
/// fan-out across dozens of sockets.
|
||||
enum NostrRelaySettings {
|
||||
/// Enough to add a personal relay, an onion address, and a couple of
|
||||
/// regional fallbacks without letting the connection fan-out grow unbounded.
|
||||
static let maxCustomRelays = 8
|
||||
|
||||
private static let storageKey = "nostr.customRelays"
|
||||
|
||||
static let didChangeNotification = Notification.Name("bitchat.nostrRelaySettingsDidChange")
|
||||
|
||||
enum AddFailure: Error, Equatable {
|
||||
case malformed
|
||||
case alreadyPresent
|
||||
case limitReached
|
||||
}
|
||||
|
||||
/// Normalized relay URLs, in the order they were added.
|
||||
static func customRelays(in defaults: UserDefaults = .standard) -> [String] {
|
||||
let stored = defaults.stringArray(forKey: storageKey) ?? []
|
||||
// Re-normalize on read: a value written by an older build, or edited
|
||||
// outside the app, must not reach the connection layer unchecked.
|
||||
var seen = Set<String>()
|
||||
return stored.compactMap { NostrRelayURL.normalized($0) }
|
||||
.filter { seen.insert($0).inserted }
|
||||
}
|
||||
|
||||
/// Adds a relay, returning the normalized URL or why it was rejected.
|
||||
@discardableResult
|
||||
static func add(
|
||||
_ rawValue: String,
|
||||
builtIn: Set<String>,
|
||||
in defaults: UserDefaults = .standard
|
||||
) -> Result<String, AddFailure> {
|
||||
// Bare hostnames are the common way people quote a relay, and wss is
|
||||
// the only sensible assumption for one.
|
||||
guard let normalized = NostrRelayURL.normalized(rawValue, defaultScheme: "wss") else {
|
||||
return .failure(.malformed)
|
||||
}
|
||||
|
||||
var current = customRelays(in: defaults)
|
||||
guard !current.contains(normalized), !builtIn.contains(normalized) else {
|
||||
return .failure(.alreadyPresent)
|
||||
}
|
||||
guard current.count < maxCustomRelays else {
|
||||
return .failure(.limitReached)
|
||||
}
|
||||
|
||||
current.append(normalized)
|
||||
write(current, in: defaults)
|
||||
return .success(normalized)
|
||||
}
|
||||
|
||||
static func remove(_ url: String, in defaults: UserDefaults = .standard) {
|
||||
// Same default scheme as `add`, so a relay entered as a bare hostname
|
||||
// can be removed the way it was typed.
|
||||
guard let normalized = NostrRelayURL.normalized(url, defaultScheme: "wss") else { return }
|
||||
let remaining = customRelays(in: defaults).filter { $0 != normalized }
|
||||
write(remaining, in: defaults)
|
||||
}
|
||||
|
||||
/// Panic-wipe hook: an added relay names somewhere someone chose to route
|
||||
/// through, which is exactly the kind of trace a wipe should not leave.
|
||||
static func reset(in defaults: UserDefaults = .standard) {
|
||||
defaults.removeObject(forKey: storageKey)
|
||||
NotificationCenter.default.post(name: didChangeNotification, object: nil)
|
||||
}
|
||||
|
||||
private static func write(_ relays: [String], in defaults: UserDefaults) {
|
||||
defaults.set(relays, forKey: storageKey)
|
||||
NotificationCenter.default.post(name: didChangeNotification, object: nil)
|
||||
}
|
||||
}
|
||||
@@ -42,13 +42,18 @@ final class NetworkActivationService: ObservableObject {
|
||||
|
||||
private var cancellables = Set<AnyCancellable>()
|
||||
private var started = false
|
||||
private let torPreferenceKey = "networkActivationService.userTorEnabled"
|
||||
/// Storage key for the Tor preference. Exposed as a `nonisolated` constant
|
||||
/// so off-main callers can read the preference without hopping to the main
|
||||
/// actor; see `persistedTorPreference(in:)`.
|
||||
nonisolated static let torPreferenceKey = "networkActivationService.userTorEnabled"
|
||||
private var torAutoStartDesired: Bool = false
|
||||
private let storage: UserDefaults
|
||||
private let locationPermissionPublisher: AnyPublisher<LocationChannelManager.PermissionState, Never>
|
||||
private let mutualFavoritesPublisher: AnyPublisher<Set<Data>, Never>
|
||||
private let selectedChannelPublisher: AnyPublisher<ChannelID, Never>
|
||||
private let permissionProvider: () -> LocationChannelManager.PermissionState
|
||||
private let mutualFavoritesProvider: () -> Set<Data>
|
||||
private let locationChannelSelectedProvider: () -> Bool
|
||||
private let reachabilityMonitor: NetworkReachabilityMonitoring
|
||||
private let torController: NetworkActivationTorControlling
|
||||
// Resolved lazily: NostrRelayManager.init() reads NetworkActivationService.shared
|
||||
@@ -63,8 +68,13 @@ final class NetworkActivationService: ObservableObject {
|
||||
storage = .standard
|
||||
locationPermissionPublisher = LocationChannelManager.shared.$permissionState.eraseToAnyPublisher()
|
||||
mutualFavoritesPublisher = FavoritesPersistenceService.shared.$mutualFavorites.eraseToAnyPublisher()
|
||||
selectedChannelPublisher = LocationChannelManager.shared.$selectedChannel.eraseToAnyPublisher()
|
||||
permissionProvider = { LocationChannelManager.shared.permissionState }
|
||||
mutualFavoritesProvider = { FavoritesPersistenceService.shared.mutualFavorites }
|
||||
locationChannelSelectedProvider = {
|
||||
if case .location = LocationChannelManager.shared.selectedChannel { return true }
|
||||
return false
|
||||
}
|
||||
reachabilityMonitor = NWPathReachabilityMonitor()
|
||||
torController = TorManager.shared
|
||||
relayControllerProvider = { NostrRelayManager.shared }
|
||||
@@ -78,6 +88,8 @@ final class NetworkActivationService: ObservableObject {
|
||||
mutualFavoritesPublisher: AnyPublisher<Set<Data>, Never>,
|
||||
permissionProvider: @escaping () -> LocationChannelManager.PermissionState,
|
||||
mutualFavoritesProvider: @escaping () -> Set<Data>,
|
||||
selectedChannelPublisher: AnyPublisher<ChannelID, Never> = Empty().eraseToAnyPublisher(),
|
||||
locationChannelSelectedProvider: @escaping () -> Bool = { false },
|
||||
reachabilityMonitor: NetworkReachabilityMonitoring,
|
||||
torController: NetworkActivationTorControlling,
|
||||
relayController: NetworkActivationRelayControlling,
|
||||
@@ -89,6 +101,8 @@ final class NetworkActivationService: ObservableObject {
|
||||
self.mutualFavoritesPublisher = mutualFavoritesPublisher
|
||||
self.permissionProvider = permissionProvider
|
||||
self.mutualFavoritesProvider = mutualFavoritesProvider
|
||||
self.selectedChannelPublisher = selectedChannelPublisher
|
||||
self.locationChannelSelectedProvider = locationChannelSelectedProvider
|
||||
self.reachabilityMonitor = reachabilityMonitor
|
||||
self.torController = torController
|
||||
self.relayControllerProvider = { relayController }
|
||||
@@ -96,11 +110,25 @@ final class NetworkActivationService: ObservableObject {
|
||||
self.notificationCenter = notificationCenter
|
||||
}
|
||||
|
||||
/// Whether Tor routing is switched on, read without main-actor isolation.
|
||||
///
|
||||
/// This is the *preference*, not live Tor readiness. Background work that
|
||||
/// must decide whether waiting for Tor is even meaningful needs the
|
||||
/// preference: when someone has deliberately turned Tor off, requests are
|
||||
/// intended to go direct, so waiting on a client that has been shut down
|
||||
/// would only burn the bootstrap timeout. When the preference is on, callers
|
||||
/// must still wait for readiness rather than falling back to clearnet.
|
||||
nonisolated static func persistedTorPreference(
|
||||
in defaults: UserDefaults = .standard
|
||||
) -> Bool {
|
||||
defaults.object(forKey: torPreferenceKey) as? Bool ?? true
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard !started else { return }
|
||||
started = true
|
||||
|
||||
if let stored = storage.object(forKey: torPreferenceKey) as? Bool {
|
||||
if let stored = storage.object(forKey: Self.torPreferenceKey) as? Bool {
|
||||
userTorEnabled = stored
|
||||
} else {
|
||||
userTorEnabled = true
|
||||
@@ -138,6 +166,16 @@ final class NetworkActivationService: ObservableObject {
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
// React to entering or leaving a location channel, which can flip the
|
||||
// gate on its own for someone with no location permission and no
|
||||
// mutual favorites.
|
||||
selectedChannelPublisher
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] _ in
|
||||
self?.reevaluate()
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
// React to network reachability changes (debounced, unsatisfied-only).
|
||||
reachabilityMonitor.reachabilityPublisher
|
||||
.receive(on: DispatchQueue.main)
|
||||
@@ -170,7 +208,7 @@ final class NetworkActivationService: ObservableObject {
|
||||
func setUserTorEnabled(_ enabled: Bool) {
|
||||
guard enabled != userTorEnabled else { return }
|
||||
userTorEnabled = enabled
|
||||
storage.set(enabled, forKey: torPreferenceKey)
|
||||
storage.set(enabled, forKey: Self.torPreferenceKey)
|
||||
notificationCenter.post(
|
||||
name: .TorUserPreferenceChanged,
|
||||
object: nil,
|
||||
@@ -211,7 +249,14 @@ final class NetworkActivationService: ObservableObject {
|
||||
private func basePolicyAllowed() -> Bool {
|
||||
let permOK = permissionProvider() == .authorized
|
||||
let hasMutual = !mutualFavoritesProvider().isEmpty
|
||||
return permOK || hasMutual
|
||||
// Being in a location channel counts too. Teleporting into a geohash
|
||||
// needs no location permission, so someone who denied location and has
|
||||
// no mutual favorites could sit in a channel that never connects: the
|
||||
// gate suppressed Tor and the relays, and nothing said why. The channel
|
||||
// is itself an internet feature in active use, which is exactly what
|
||||
// this gate is meant to detect.
|
||||
let inLocationChannel = locationChannelSelectedProvider()
|
||||
return permOK || hasMutual || inLocationChannel
|
||||
}
|
||||
|
||||
/// Effective gate: base policy AND a usable network path. When there is
|
||||
|
||||
@@ -363,6 +363,8 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
// Track whether a Tor restart is pending so we only announce
|
||||
// "tor restarted" after an actual restart, not the first launch.
|
||||
var torRestartPending: Bool = false
|
||||
// Announce a stalled bootstrap once per attempt, not once per poll.
|
||||
var torStallAnnounced: Bool = false
|
||||
// Ensure we set up DM subscription only once per app session
|
||||
var nostrHandlersSetup: Bool = false
|
||||
var geoChannelCoordinator: GeoChannelCoordinator?
|
||||
@@ -1633,6 +1635,9 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
MeshSightingsTracker.shared.clear()
|
||||
MeshEchoSettings.reset()
|
||||
NotificationPrivacySettings.reset()
|
||||
// A hand-added relay names an operator someone chose to route through,
|
||||
// which is the kind of trace a wipe should not leave behind.
|
||||
NostrRelaySettings.reset()
|
||||
|
||||
// Drop private group keys and rosters (keychain + disk)
|
||||
groupStore.wipe()
|
||||
|
||||
@@ -15,6 +15,8 @@ extension ChatViewModel {
|
||||
|
||||
@objc func handleTorWillStart() {
|
||||
Task { @MainActor in
|
||||
// A fresh attempt can stall again, so let it be reported again.
|
||||
self.torStallAnnounced = false
|
||||
if !self.torStatusAnnounced && TorManager.shared.torEnforced {
|
||||
self.torStatusAnnounced = true
|
||||
// Post only in geohash channels (queue if not active)
|
||||
@@ -37,6 +39,7 @@ extension ChatViewModel {
|
||||
|
||||
@objc func handleTorDidBecomeReady() {
|
||||
Task { @MainActor in
|
||||
self.torStallAnnounced = false
|
||||
// Only announce "restarted" if we actually restarted this session
|
||||
if self.torRestartPending {
|
||||
// Post only in geohash channels (queue if not active)
|
||||
@@ -54,11 +57,31 @@ extension ChatViewModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bootstrap spent its whole deadline without connecting. Say so rather
|
||||
/// than leaving "starting tor…" on screen indefinitely: on a network that
|
||||
/// blocks Tor this is the terminal state, and someone needs to know that
|
||||
/// internet features are stalled while the mesh still works.
|
||||
@objc func handleTorBootstrapDidStall() {
|
||||
Task { @MainActor in
|
||||
guard TorManager.shared.torEnforced else { return }
|
||||
guard !self.torStallAnnounced else { return }
|
||||
self.torStallAnnounced = true
|
||||
self.addGeohashOnlySystemMessage(
|
||||
String(
|
||||
localized: "system.tor.blocked",
|
||||
defaultValue: "tor could not connect — this network may be blocking it. mesh messaging still works; location channels and internet delivery are paused until tor gets through.",
|
||||
comment: "System message shown when Tor bootstrap runs out its deadline without connecting, which is what a network that blocks Tor looks like"
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@objc func handleTorPreferenceChanged(_: Notification) {
|
||||
Task { @MainActor in
|
||||
self.torStatusAnnounced = false
|
||||
self.torInitialReadyAnnounced = false
|
||||
self.torRestartPending = false
|
||||
self.torStallAnnounced = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,9 @@ struct AppInfoView: View {
|
||||
@State private var liveVoiceEnabled = PTTSettings.liveVoiceEnabled
|
||||
@State private var locationNotesEnabled = LocationNotesSettings.enabled
|
||||
@State private var hideMessagePreviews = NotificationPrivacySettings.hideMessagePreviews
|
||||
@State private var customRelays = NostrRelaySettings.customRelays()
|
||||
@State private var relayInput = ""
|
||||
@State private var relayError: String?
|
||||
@ObservedObject private var locationManager = LocationChannelManager.shared
|
||||
/// Sticky across opens: first-ever open lands on Info (the gentler
|
||||
/// introduction), and afterwards the sheet reopens wherever it was left.
|
||||
@@ -80,7 +83,34 @@ struct AppInfoView: View {
|
||||
// internet-gateway toggle is gone: the bridge switch drives all
|
||||
// internet sharing, including geohash-channel gatewaying.)
|
||||
static let torTitle: LocalizedStringKey = "location_channels.tor.title"
|
||||
static let torSubtitle: LocalizedStringKey = "location_channels.tor.subtitle"
|
||||
// Replaces `location_channels.tor.subtitle`, which described the
|
||||
// setting as location-channels-only. It covers private messages and
|
||||
// relay-directory refreshes too, and said nothing about the cost of
|
||||
// switching it off.
|
||||
static let torSubtitle = String(localized: "app_info.settings.tor.subtitle", defaultValue: "sends internet traffic through tor, so relay operators see tor's address instead of yours. covers location channels and private messages delivered over the internet. recommended: on.", comment: "Subtitle for the tor routing toggle in settings, explaining what it covers")
|
||||
static let torOffWarning = String(localized: "app_info.settings.tor.off_warning", defaultValue: "tor is off: every relay you connect to can see your IP address, including relays carrying your private messages.", comment: "Warning shown under the tor toggle while tor is switched off, stating that relay operators can see the device IP address")
|
||||
|
||||
static let relaysTitle = String(localized: "app_info.settings.relays.title", defaultValue: "private message relays", comment: "Title of the relay list editor in settings")
|
||||
static let relaysSubtitle = String(localized: "app_info.settings.relays.subtitle", defaultValue: "when the mesh can't reach someone, private messages travel through these relays. the built-in ones are well-known addresses that a network filter can block, so you can add your own — including .onion addresses.", comment: "Subtitle explaining what the relay list is for and why someone would add a relay")
|
||||
static let relayBuiltIn = String(localized: "app_info.settings.relays.built_in", defaultValue: "built in", comment: "Label marking a relay as one of the built-in relays, which cannot be removed")
|
||||
static let relayPlaceholder = String(localized: "app_info.settings.relays.placeholder", defaultValue: "wss://relay.example.com", comment: "Placeholder text in the field for adding a relay address")
|
||||
static let relayAdd = String(localized: "app_info.settings.relays.add", defaultValue: "add", comment: "Button that adds the typed relay address to the list")
|
||||
static let relayRemove = String(localized: "app_info.settings.relays.remove", defaultValue: "remove relay", comment: "Accessibility label for the button that removes an added relay")
|
||||
|
||||
static func relayError(_ failure: NostrRelaySettings.AddFailure) -> String {
|
||||
switch failure {
|
||||
case .malformed:
|
||||
return String(localized: "app_info.settings.relays.error.malformed", defaultValue: "that doesn't look like a relay address. try wss://host.", comment: "Error shown when a typed relay address cannot be parsed")
|
||||
case .alreadyPresent:
|
||||
return String(localized: "app_info.settings.relays.error.duplicate", defaultValue: "that relay is already in the list.", comment: "Error shown when the typed relay address is already in the list")
|
||||
case .limitReached:
|
||||
return String(
|
||||
format: String(localized: "app_info.settings.relays.error.limit", defaultValue: "you can add up to %d relays.", comment: "Error shown when the relay list is already at its maximum size; %d is that maximum"),
|
||||
locale: .current,
|
||||
NostrRelaySettings.maxCustomRelays
|
||||
)
|
||||
}
|
||||
}
|
||||
static let toggleOn: LocalizedStringKey = "common.toggle.on"
|
||||
static let toggleOff: LocalizedStringKey = "common.toggle.off"
|
||||
|
||||
@@ -415,11 +445,22 @@ struct AppInfoView: View {
|
||||
settingsCard {
|
||||
settingToggle(
|
||||
title: Text(Strings.Settings.torTitle),
|
||||
subtitle: Text(Strings.Settings.torSubtitle),
|
||||
subtitle: Text(verbatim: Strings.Settings.torSubtitle),
|
||||
isOn: torToggleBinding
|
||||
)
|
||||
// Turning tor off is not a location-channels-only choice, so
|
||||
// say what it costs while it is off rather than in the
|
||||
// subtitle everyone skims.
|
||||
if !locationChannelsModel.userTorEnabled {
|
||||
Text(verbatim: Strings.Settings.torOffWarning)
|
||||
.bitchatFont(size: 11)
|
||||
.foregroundColor(palette.alertRed)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
|
||||
relaySettingsCard
|
||||
|
||||
// Location notes / dead drops (merged from main's flat
|
||||
// layout into the shared card + pill style). Turning it on
|
||||
// may need the location prompt; the permission control below
|
||||
@@ -563,6 +604,108 @@ struct AppInfoView: View {
|
||||
)
|
||||
}
|
||||
|
||||
/// Relay list editor. The built-in relays are four well-known hostnames, so
|
||||
/// a filter blocking four names ends internet-delivered private messages;
|
||||
/// adding one here is the only fix that does not need a new build.
|
||||
@ViewBuilder
|
||||
private var relaySettingsCard: some View {
|
||||
settingsCard {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(verbatim: Strings.Settings.relaysTitle)
|
||||
.bitchatFont(size: 12, weight: .semibold)
|
||||
.foregroundColor(textColor)
|
||||
Text(verbatim: Strings.Settings.relaysSubtitle)
|
||||
.bitchatFont(size: 11)
|
||||
.foregroundColor(secondaryTextColor)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
|
||||
ForEach(NostrRelayManager.builtInRelayURLs.sorted(), id: \.self) { relay in
|
||||
HStack(spacing: 6) {
|
||||
Text(verbatim: relay)
|
||||
.bitchatFont(size: 11)
|
||||
.foregroundColor(secondaryTextColor)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
Spacer(minLength: 4)
|
||||
Text(verbatim: Strings.Settings.relayBuiltIn)
|
||||
.bitchatFont(size: 10)
|
||||
.foregroundColor(secondaryTextColor)
|
||||
}
|
||||
}
|
||||
|
||||
ForEach(customRelays, id: \.self) { relay in
|
||||
HStack(spacing: 6) {
|
||||
Text(verbatim: relay)
|
||||
.bitchatFont(size: 11)
|
||||
.foregroundColor(textColor)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
Spacer(minLength: 4)
|
||||
Button {
|
||||
NostrRelaySettings.remove(relay)
|
||||
reloadCustomRelays()
|
||||
} label: {
|
||||
Image(systemName: "minus.circle")
|
||||
.foregroundColor(palette.alertRed)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityLabel(Strings.Settings.relayRemove)
|
||||
}
|
||||
}
|
||||
|
||||
if customRelays.count < NostrRelaySettings.maxCustomRelays {
|
||||
HStack(spacing: 6) {
|
||||
TextField(Strings.Settings.relayPlaceholder, text: $relayInput)
|
||||
.textFieldStyle(.plain)
|
||||
.bitchatFont(size: 11)
|
||||
.foregroundColor(textColor)
|
||||
.autocorrectionDisabled(true)
|
||||
#if os(iOS)
|
||||
.textInputAutocapitalization(.never)
|
||||
.keyboardType(.URL)
|
||||
#endif
|
||||
.onSubmit(addRelay)
|
||||
Button(action: addRelay) {
|
||||
Text(verbatim: Strings.Settings.relayAdd)
|
||||
.bitchatFont(size: 11, weight: .semibold)
|
||||
.foregroundColor(palette.accent)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.disabled(relayInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
if let relayError {
|
||||
Text(verbatim: relayError)
|
||||
.bitchatFont(size: 11)
|
||||
.foregroundColor(palette.alertRed)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
// The store can change from outside this view — a panic wipe clears it —
|
||||
// so follow it rather than trusting the value read at creation.
|
||||
.onReceive(NotificationCenter.default.publisher(for: NostrRelaySettings.didChangeNotification)) { _ in
|
||||
reloadCustomRelays()
|
||||
}
|
||||
}
|
||||
|
||||
private func addRelay() {
|
||||
let candidate = relayInput
|
||||
switch NostrRelaySettings.add(candidate, builtIn: NostrRelayManager.builtInRelayURLs) {
|
||||
case .success:
|
||||
relayInput = ""
|
||||
relayError = nil
|
||||
reloadCustomRelays()
|
||||
case .failure(let failure):
|
||||
relayError = Strings.Settings.relayError(failure)
|
||||
}
|
||||
}
|
||||
|
||||
private func reloadCustomRelays() {
|
||||
customRelays = NostrRelaySettings.customRelays()
|
||||
}
|
||||
|
||||
private var torToggleBinding: Binding<Bool> {
|
||||
Binding(
|
||||
get: { locationChannelsModel.userTorEnabled },
|
||||
|
||||
Reference in New Issue
Block a user