Default Tor ON everywhere, harden Stealth Mode, and update panic-wipe copy (#1964)

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
This commit is contained in:
jackandjack authored and GitHub committed 2026-11-28 16:32:46 -10:00
1 parent d783e8cc24
commit 8997484d34
13 files changed
+1490 -203

No files matched your search

+17 -1
View File
@@ -101,7 +101,10 @@ enum PTTSettings {
}
static func publicAutoPlayEnabled(in defaults: UserDefaults) -> Bool {
defaults.object(forKey: publicAutoPlayEnabledKey) as? Bool ?? false
if PrivacyModeSettings.currentMode(in: defaults) == .stealth {
return false
}
return defaults.object(forKey: publicAutoPlayEnabledKey) as? Bool ?? false
}
static func setPublicAutoPlayEnabled(_ enabled: Bool, in defaults: UserDefaults) {
@@ -222,6 +225,7 @@ final class PTTPreferences: ObservableObject {
@Published private(set) var policyRevision: UInt64 = 0
private var observer: NSObjectProtocol?
private var privacyModeObserver: NSObjectProtocol?
private init() {
self.liveVoiceEnabled = PTTSettings.liveVoiceEnabled
@@ -237,12 +241,24 @@ final class PTTPreferences: ObservableObject {
self?.syncFromSettings()
}
}
privacyModeObserver = NotificationCenter.default.addObserver(
forName: PrivacyModeSettings.didChangeNotification,
object: nil,
queue: .main
) { [weak self] _ in
Task { @MainActor [weak self] in
self?.syncFromSettings()
}
}
}
deinit {
if let observer {
NotificationCenter.default.removeObserver(observer)
}
if let privacyModeObserver {
NotificationCenter.default.removeObserver(privacyModeObserver)
}
}
func setLiveVoiceEnabled(_ enabled: Bool) {
File diff suppressed because it is too large. Load diff
+38 -3
View File
@@ -234,21 +234,30 @@ final class BridgeService: ObservableObject {
private let defaults: UserDefaults
private let now: () -> Date
private let verifyEventSignature: (NostrEvent) -> Bool
private var privacyModeCancellable: AnyCancellable?
private static let enabledKey = "bridge.userEnabled"
var queuedUplinks: [CarrierRelayEngine.QueuedUplink] {
relayEngine.queuedUplinks
}
private static func effectiveEnabled(in defaults: UserDefaults) -> Bool {
if PrivacyModeSettings.currentMode(in: defaults) == .stealth {
return false
}
return defaults.bool(forKey: enabledKey)
}
init(
defaults: UserDefaults = .standard,
now: @escaping () -> Date = Date.init,
verifyEventSignature: @escaping (NostrEvent) -> Bool = { $0.isValidSignature() }
verifyEventSignature: @escaping (NostrEvent) -> Bool = { $0.isValidSignature() },
notificationCenter: NotificationCenter = .default
) {
self.defaults = defaults
self.now = now
self.verifyEventSignature = verifyEventSignature
self.isEnabled = defaults.bool(forKey: Self.enabledKey)
self.isEnabled = Self.effectiveEnabled(in: defaults)
self.relayEngine = CarrierRelayEngine(
config: .init(
maxQueuedUplinks: Limits.maxQueuedUplinks,
@@ -264,14 +273,40 @@ final class BridgeService: ObservableObject {
self.injectedMessageIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
self.receivedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
self.observedRadioMessageIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs)
self.privacyModeCancellable = notificationCenter
.publisher(for: PrivacyModeSettings.didChangeNotification)
.sink { [weak self] _ in
if Thread.isMainThread {
MainActor.assumeIsolated {
self?.syncWithPrivacyMode()
}
} else {
Task { @MainActor [weak self] in
self?.syncWithPrivacyMode()
}
}
}
}
// MARK: - Toggle & lifecycle
func setEnabled(_ enabled: Bool) {
// Stealth Mode disables Mesh Bridge so the device does not advertise
// rendezvous geohash cells or carry internet traffic for nearby peers.
if enabled && PrivacyModeSettings.currentMode(in: defaults) == .stealth {
return
}
defaults.set(enabled, forKey: Self.enabledKey)
applyEnabledState(enabled)
}
private func syncWithPrivacyMode() {
applyEnabledState(Self.effectiveEnabled(in: defaults))
}
private func applyEnabledState(_ enabled: Bool) {
guard enabled != isEnabled else { return }
isEnabled = enabled
defaults.set(enabled, forKey: Self.enabledKey)
if !enabled {
relayEngine.clearQueuesOnDisable()
inboundEventTimes.removeAll()
@@ -49,7 +49,7 @@ final class NetworkActivationService: ObservableObject {
static let shared = NetworkActivationService()
@Published private(set) var activationAllowed: Bool = false
@Published private(set) var userTorEnabled: Bool = false
@Published private(set) var userTorEnabled: Bool = true
/// Coarse, debounced network reachability. `false` only when the OS reports
/// no usable interface at all. Surfaced for UI ("offline" vs "connecting").
@Published private(set) var isNetworkReachable: Bool = true
@@ -135,12 +135,16 @@ final class NetworkActivationService: ObservableObject {
nonisolated static func persistedTorPreference(
in defaults: UserDefaults = .standard
) -> Bool {
// Stealth Mode always enforces Tor routing fail-closed.
if PrivacyModeSettings.currentMode(in: defaults) == .stealth {
return true
}
if let stored = defaults.object(forKey: torPreferenceKey) as? Bool {
return stored
}
// Everyday Mode defaults to direct connections for instant startup;
// Stealth Mode enables Tor routing.
return PrivacyModeSettings.currentMode(in: defaults) == .stealth
// Tor defaults ON everywhere so Nostr relays cannot correlate IPs to
// rough locations; disabling Tor requires an explicit opt-out.
return true
}
func start() {
@@ -238,21 +242,23 @@ final class NetworkActivationService: ObservableObject {
}
func setUserTorEnabled(_ enabled: Bool) {
let changed = enabled != userTorEnabled
// Stealth Mode enforces Tor fail-closed; turning Tor off requires Everyday Mode.
let effectiveEnabled = PrivacyModeSettings.currentMode(in: storage) == .stealth ? true : enabled
let changed = effectiveEnabled != userTorEnabled
let hasStoredPreference = storage.object(forKey: Self.torPreferenceKey) != nil
guard changed || !hasStoredPreference else { return }
userTorEnabled = enabled
storage.set(enabled, forKey: Self.torPreferenceKey)
userTorEnabled = effectiveEnabled
storage.set(effectiveEnabled, forKey: Self.torPreferenceKey)
guard changed else { return }
notificationCenter.post(
name: .TorUserPreferenceChanged,
object: nil,
userInfo: ["enabled": enabled]
userInfo: ["enabled": effectiveEnabled]
)
if started {
reevaluate(proxyPreferenceChanged: true)
} else {
proxyController.setProxyMode(useTor: enabled)
proxyController.setProxyMode(useTor: effectiveEnabled)
}
}
+18 -23
View File
@@ -3,11 +3,12 @@
// bitchat
//
// Coordinates the high-level Everyday vs Stealth privacy posture.
// Everyday Mode prioritizes instant startup and daily usability (fast direct
// Nostr relays, encrypted local DM/group history, standard Settings access).
// Stealth Mode activates activist/high-risk defenses (Tor routing, RAM-only
// ephemeral timelines, redacted lock-screen notifications, logo triple-tap
// panic wipe).
// Tor defaults ON everywhere (disabling it is an explicit opt-out in
// Connectivity settings). Everyday Mode keeps encrypted local DM/group
// history and standard Settings flexibility. Stealth Mode activates
// activist/high-risk defenses (enforced Tor, RAM-only ephemeral timelines,
// read receipts off, mesh bridge off, public live-voice auto-play off,
// redacted lock-screen notifications, top-bar triple-tap panic wipe).
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
@@ -168,7 +169,7 @@ enum PrivacyModeSettings {
notificationCenter.post(name: didChangeNotification, object: nil)
}
/// Whether the hidden triple-tap panic wipe gesture on the header logo is armed.
/// Whether the hidden triple-tap panic wipe gesture on the top bar is armed.
/// Armed in Stealth Mode; in Everyday Mode panic wipe remains available in Settings.
static func isTripleTapPanicEnabled(in defaults: UserDefaults = .standard) -> Bool {
currentMode(in: defaults) == .stealth
@@ -199,16 +200,12 @@ enum PrivacyModeSettings {
onClearPersistedHistory: (() -> Void)? = nil
) {
let activation = networkActivation ?? .shared
let previousMode = currentMode(in: defaults)
let hasExplicitTorPreference = defaults.object(forKey: NetworkActivationService.torPreferenceKey) != nil
setMode(newMode, in: defaults)
switch newMode {
case .everyday:
// Turn Tor off when switching away from Stealth or on initial setup,
// but preserve an explicit user Tor toggle if already in Everyday Mode.
if previousMode == .stealth || !hasExplicitTorPreference {
activation.setUserTorEnabled(false)
}
// Tor defaults ON everywhere and disabling it is an explicit choice
// in Connectivity settings; leaving Stealth never silently turns Tor off.
break
case .stealth:
activation.setUserTorEnabled(true)
NotificationPrivacySettings.setHideMessagePreviews(true, in: defaults)
@@ -226,24 +223,22 @@ enum PrivacyModeSettings {
notificationCenter.post(name: didChangeNotification, object: nil)
}
/// Panic-wipe reset: clears persisted history preferences while preserving
/// Stealth/Tor posture for users who triggered panic wipe from Stealth Mode
/// (so wiping never unexpectedly turns disk persistence on or disarms
/// triple-tap wipe) and keeping the v2 migration marker set so relaunch
/// does not misclassify the wiped container.
/// Panic-wipe reset: clears persisted preferences (restoring default-ON Tor)
/// while preserving Stealth posture for users who triggered panic wipe from
/// Stealth Mode (so wiping never unexpectedly turns disk persistence on or
/// disarms triple-tap wipe) and keeping the v2 migration marker set so
/// relaunch does not misclassify the wiped container.
static func resetForPanic(
in defaults: UserDefaults = .standard,
wasTorEnabled: Bool? = nil,
notificationCenter: NotificationCenter = .default
) {
let wasStealthOrTor = currentMode(in: defaults) == .stealth
|| (wasTorEnabled ?? NetworkActivationService.persistedTorPreference(in: defaults))
let wasStealth = currentMode(in: defaults) == .stealth
defaults.removeObject(forKey: modeKey)
defaults.removeObject(forKey: persistHistoryKey)
defaults.removeObject(forKey: sendReadReceiptsKey)
defaults.removeObject(forKey: NetworkActivationService.torPreferenceKey)
defaults.set(true, forKey: migrationCompletedKey)
if wasStealthOrTor {
defaults.set(true, forKey: NetworkActivationService.torPreferenceKey)
if wasStealth {
defaults.set(PrivacyMode.stealth.rawValue, forKey: modeKey)
defaults.set(false, forKey: persistHistoryKey)
}
+1 -3
View File
@@ -1989,8 +1989,6 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
isPanicResetting = true
defer { isPanicResetting = false }
let wasTorEnabledBeforePanic = NetworkActivationService.persistedTorPreference(in: userDefaults)
// Stop internet and location-presence work before clearing identity or
// state. These services cancel their subscriptions and delayed tasks,
// so old callbacks cannot reconnect during the transaction.
@@ -2087,7 +2085,7 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
expirationSweepTask?.cancel()
expirationSweepTask = nil
encryptedHistoryStore.wipe()
PrivacyModeSettings.resetForPanic(in: userDefaults, wasTorEnabled: wasTorEnabledBeforePanic)
PrivacyModeSettings.resetForPanic(in: userDefaults)
CourierStore.shared.wipe()
BridgeCourierService.shared.wipe()
BridgeService.shared.resetForPanic()
+58 -16
View File
@@ -45,6 +45,7 @@ struct AppInfoView: View {
/// introduction), and afterwards the sheet reopens wherever it was left.
@AppStorage(AppInfoView.selectedPaneStorageKey) private var selectedPane: Pane = .info
@State private var showPanicConfirmation = false
@State private var showDisableTorConfirmation = false
@AppStorage(AppLanguageSettings.overrideKey) private var languageOverride = ""
/// The override changed this session; localization resolves at process
/// start, so surface the restart hint.
@@ -129,6 +130,12 @@ struct AppInfoView: View {
// 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 Places and private messages delivered over the internet.", 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: relays 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 torDisableConfirmTitle = String(localized: "app_info.settings.tor.disable_confirm_title", defaultValue: "Disable Tor Routing?", comment: "Confirmation dialog title when explicitly turning Tor off in settings")
static let torDisableConfirmMessage = String(localized: "app_info.settings.tor.disable_confirm_message", defaultValue: "Without Tor, Nostr relays you connect to can see your IP address and approximate location, including relays carrying your private messages and Places.", comment: "Confirmation dialog message explaining the privacy cost of disabling Tor")
static let torDisableConfirmAction = String(localized: "app_info.settings.tor.disable_confirm_action", defaultValue: "Disable Tor", comment: "Destructive button confirming the user wants to disable Tor routing")
static let torDisableConfirmCancel = String(localized: "app_info.settings.tor.disable_confirm_cancel", defaultValue: "Keep Tor On", comment: "Cancel button keeping Tor routing enabled")
static let stealthAlwaysOnNote = String(localized: "app_info.settings.stealth.always_on", defaultValue: "Always on in Stealth Mode.", comment: "Caption shown under settings forced ON while Stealth Mode is active")
static let stealthAutomaticallyOffNote = String(localized: "app_info.settings.stealth.auto_off", defaultValue: "Automatically off in Stealth Mode.", comment: "Caption shown under settings forced OFF while Stealth Mode is active")
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. Built-in relays are well-known addresses that a network filter can block, so you can add your own.", comment: "Subtitle explaining what the relay list is for and why someone would add a relay")
@@ -477,15 +484,15 @@ struct AppInfoView: View {
)
) {
Text(String(localized: "app_info.settings.privacy_mode.everyday", defaultValue: "Everyday", comment: "Everyday mode option")).tag(PrivacyMode.everyday)
Text(String(localized: "app_info.settings.privacy_mode.stealth", defaultValue: "Stealth (Tor)", comment: "Stealth mode option")).tag(PrivacyMode.stealth)
Text(String(localized: "app_info.settings.privacy_mode.stealth", defaultValue: "Stealth", comment: "Stealth mode option")).tag(PrivacyMode.stealth)
}
.pickerStyle(.segmented)
.labelsHidden()
Text(
privacyMode == .everyday
? String(localized: "app_info.settings.privacy_mode.everyday_desc", defaultValue: "Instant internet relay connections and encrypted local history for DMs and groups. End-to-end encryption is always on.", comment: "Description of Everyday mode")
: String(localized: "app_info.settings.privacy_mode.stealth_desc", defaultValue: "Routes internet traffic through Tor, keeps chats in RAM only, hides lock-screen previews, and arms triple-tap panic wipe on the logo.", comment: "Description of Stealth mode")
? String(localized: "app_info.settings.privacy_mode.everyday_desc", defaultValue: "Encrypted local history for DMs and groups, with full control over connectivity and privacy toggles. Tor routing and end-to-end encryption are on by default.", comment: "Description of Everyday mode")
: String(localized: "app_info.settings.privacy_mode.stealth_desc", defaultValue: "Keeps chats in RAM only, enforces Tor, disables read receipts, Mesh Bridge, and Nearby auto-play, hides lock-screen previews, and arms triple-tap panic wipe on the top bar.", comment: "Description of Stealth mode")
)
.bitchatFont(size: 11)
.foregroundColor(secondaryTextColor)
@@ -581,12 +588,13 @@ struct AppInfoView: View {
settingToggle(
title: Text(String(localized: "app_info.voice.public_autoplay.title", defaultValue: "Auto-play in Nearby (#mesh)", comment: "Settings toggle title for automatic speaker playback in public Nearby mesh")),
subtitle: Text(String(localized: "app_info.voice.public_autoplay.description", defaultValue: "Off by default. Play incoming live voices aloud in public Nearby; trusted DMs and groups always auto-play unless muted.", comment: "Settings toggle description for public Nearby live voice auto-play")),
subtitle: Text(String(localized: "app_info.voice.public_autoplay.description", defaultValue: "Off by default. Play incoming live voices aloud in public Nearby; trusted DMs and groups always auto-play unless muted. Automatically off in Stealth Mode.", comment: "Settings toggle description for public Nearby live voice auto-play")),
isOn: Binding(
get: { pttPreferences.publicAutoPlayEnabled },
get: { pttPreferences.publicAutoPlayEnabled && privacyMode == .everyday },
set: { pttPreferences.setPublicAutoPlayEnabled($0) }
)
)
.disabled(privacyMode == .stealth)
Divider().opacity(0.35)
@@ -611,10 +619,15 @@ struct AppInfoView: View {
subtitle: Text(Strings.Settings.bridgeSubtitle),
isOn: bridgeToggleBinding
)
// Where the bridge meets: the geohash rendezvous cell, or
// a hint about why there isn't one yet (no location and no
// bridge peer advertising a cell).
if bridgeService.isEnabled {
.disabled(privacyMode == .stealth)
if privacyMode == .stealth {
Text(verbatim: Strings.Settings.stealthAutomaticallyOffNote)
.bitchatFont(size: 11)
.foregroundColor(secondaryTextColor)
} else if bridgeService.isEnabled {
// Where the bridge meets: the geohash rendezvous cell, or
// a hint about why there isn't one yet (no location and no
// bridge peer advertising a cell).
Text(bridgeCaption)
.bitchatFont(size: 11)
.foregroundColor(secondaryTextColor)
@@ -627,10 +640,27 @@ struct AppInfoView: View {
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 {
.disabled(privacyMode == .stealth)
.confirmationDialog(
Strings.Settings.torDisableConfirmTitle,
isPresented: $showDisableTorConfirmation,
titleVisibility: .visible
) {
Button(Strings.Settings.torDisableConfirmAction, role: .destructive) {
locationChannelsModel.setUserTorEnabled(false)
}
Button(Strings.Settings.torDisableConfirmCancel, role: .cancel) {}
} message: {
Text(verbatim: Strings.Settings.torDisableConfirmMessage)
}
if privacyMode == .stealth {
Text(verbatim: Strings.Settings.stealthAlwaysOnNote)
.bitchatFont(size: 11)
.foregroundColor(secondaryTextColor)
} else if !locationChannelsModel.userTorEnabled {
// 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.
Text(verbatim: Strings.Settings.torOffWarning)
.bitchatFont(size: 11)
.foregroundColor(palette.alertRed)
@@ -745,13 +775,19 @@ struct AppInfoView: View {
title: Text(verbatim: Strings.Settings.hidePreviewsTitle),
subtitle: Text(verbatim: Strings.Settings.hidePreviewsSubtitle),
isOn: Binding(
get: { hideMessagePreviews },
get: { hideMessagePreviews || privacyMode == .stealth },
set: { newValue in
hideMessagePreviews = newValue
NotificationPrivacySettings.hideMessagePreviews = newValue
}
)
)
.disabled(privacyMode == .stealth)
if privacyMode == .stealth {
Text(verbatim: Strings.Settings.stealthAlwaysOnNote)
.bitchatFont(size: 11)
.foregroundColor(secondaryTextColor)
}
}
}
@@ -937,8 +973,14 @@ struct AppInfoView: View {
private var torToggleBinding: Binding<Bool> {
Binding(
get: { locationChannelsModel.userTorEnabled },
set: { locationChannelsModel.setUserTorEnabled($0) }
get: { locationChannelsModel.userTorEnabled || privacyMode == .stealth },
set: { newValue in
if newValue {
locationChannelsModel.setUserTorEnabled(true)
} else if privacyMode != .stealth {
showDisableTorConfirmation = true
}
}
)
}
+2 -2
View File
@@ -186,7 +186,7 @@ struct OnboardingSheetView: View {
icon: "bolt.shield.fill",
tint: palette.accent,
title: String(localized: "settings.privacy_mode.everyday", defaultValue: "Everyday", comment: "Everyday privacy mode label"),
detail: String(localized: "onboarding.mode.everyday.detail", defaultValue: "Fast direct Nostr relays and encrypted local chat history on this device.", comment: "Description of Everyday mode during onboarding")
detail: String(localized: "onboarding.mode.everyday.detail", defaultValue: "Encrypted local chat history on this device, with Tor routing and end-to-end encryption on by default.", comment: "Description of Everyday mode during onboarding")
)
modeOptionRow(
@@ -194,7 +194,7 @@ struct OnboardingSheetView: View {
icon: "eye.slash.fill",
tint: .orange,
title: String(localized: "settings.privacy_mode.stealth", defaultValue: "Stealth", comment: "Stealth privacy mode label"),
detail: String(localized: "onboarding.mode.stealth.detail", defaultValue: "Tor routing, RAM-only chats that clear on close, and hidden lock-screen previews.", comment: "Description of Stealth mode during onboarding")
detail: String(localized: "onboarding.mode.stealth.detail", defaultValue: "RAM-only chats that clear on close, enforced Tor, hidden lock-screen previews, and top-bar triple-tap panic wipe.", comment: "Description of Stealth mode during onboarding")
)
}
}
@@ -22,16 +22,16 @@ final class NetworkActivationServiceTests: XCTestCase {
XCTAssertEqual(context.relayController.disconnectCallCount, 1)
}
func test_start_defaultsToEverydayDirectModeWhenUnset() {
func test_start_defaultsToTorOnInEverydayModeWhenUnset() {
let context = makeService(permission: .authorized, favorites: [], torEnabled: nil)
context.service.start()
XCTAssertTrue(context.service.activationAllowed)
XCTAssertFalse(context.service.userTorEnabled)
XCTAssertEqual(context.torController.autoStartAllowedValues, [false])
XCTAssertEqual(context.proxyController.proxyModes, [false])
XCTAssertEqual(context.torController.startIfNeededCallCount, 0)
XCTAssertTrue(context.service.userTorEnabled)
XCTAssertEqual(context.torController.autoStartAllowedValues, [true])
XCTAssertEqual(context.proxyController.proxyModes, [true])
XCTAssertEqual(context.torController.startIfNeededCallCount, 1)
XCTAssertEqual(context.relayController.connectCallCount, 1)
}
@@ -265,19 +265,24 @@ final class NetworkActivationServiceTests: XCTestCase {
XCTAssertEqual(context.proxyController.proxyModes.last, true)
}
func test_applyModeEveryday_preservesExplicitTorOnWhileSwitchingFromStealthDisablesTor() {
let context = makeService(permission: .authorized, favorites: [], torEnabled: true)
func test_applyModeEveryday_preservesTorOnWhenSwitchingFromStealth() {
let context = makeService(permission: .authorized, favorites: [], torEnabled: nil)
context.service.start()
PrivacyModeSettings.setMode(.everyday, in: context.storage)
// Already in Everyday Mode with explicit user Tor ON -> re-applying Everyday preserves Tor ON.
// Tor defaults ON in Everyday Mode; re-applying Everyday preserves Tor ON.
PrivacyModeSettings.applyMode(.everyday, in: context.storage, networkActivation: context.service)
XCTAssertTrue(context.service.userTorEnabled)
// Switching to Stealth forces Tor ON; switching FROM Stealth -> Everyday turns Tor OFF.
// Switching to Stealth enforces Tor ON; switching FROM Stealth -> Everyday keeps Tor ON
// so disabling Tor is always an explicit choice in Connectivity settings.
PrivacyModeSettings.applyMode(.stealth, in: context.storage, networkActivation: context.service)
XCTAssertTrue(context.service.userTorEnabled)
PrivacyModeSettings.applyMode(.everyday, in: context.storage, networkActivation: context.service)
XCTAssertTrue(context.service.userTorEnabled)
// Explicitly disabling Tor in Everyday Mode works as expected.
context.service.setUserTorEnabled(false)
XCTAssertFalse(context.service.userTorEnabled)
}
@@ -204,16 +204,43 @@ final class NetworkReachabilityGateTests: XCTestCase {
XCTAssertTrue(recovered)
}
func test_torDefaultsOnAndDisablingRequiresEverydayMode() {
let ctx = makeService(permission: .authorized, reachable: true, seedTorPreference: nil)
ctx.service.start()
// Fresh install in Everyday Mode defaults Tor ON.
XCTAssertTrue(ctx.service.userTorEnabled)
XCTAssertEqual(ctx.torController.startIfNeededCallCount, 1)
// Explicitly disabling Tor in Everyday Mode shuts Tor down.
ctx.service.setUserTorEnabled(false)
XCTAssertFalse(ctx.service.userTorEnabled)
XCTAssertEqual(ctx.torController.shutdownCompletelyCallCount, 1)
// Switching to Stealth Mode re-enforces Tor ON and blocks disabling it.
PrivacyModeSettings.applyMode(.stealth, in: ctx.storage, networkActivation: ctx.service)
XCTAssertTrue(ctx.service.userTorEnabled)
ctx.service.setUserTorEnabled(false)
XCTAssertTrue(ctx.service.userTorEnabled)
// Switching back to Everyday Mode never silently turns Tor off.
PrivacyModeSettings.applyMode(.everyday, in: ctx.storage, networkActivation: ctx.service)
XCTAssertTrue(ctx.service.userTorEnabled)
}
// MARK: - Harness
private func makeService(
permission: LocationChannelManager.PermissionState,
reachable: Bool
reachable: Bool,
seedTorPreference: Bool? = true
) -> Context {
let suiteName = "NetworkReachabilityGateTests-\(UUID().uuidString)"
let storage = UserDefaults(suiteName: suiteName)!
storage.removePersistentDomain(forName: suiteName)
storage.set(true, forKey: NetworkActivationService.torPreferenceKey)
if let seedTorPreference {
storage.set(seedTorPreference, forKey: NetworkActivationService.torPreferenceKey)
}
let permissionSubject = CurrentValueSubject<LocationChannelManager.PermissionState, Never>(permission)
let favoritesSubject = CurrentValueSubject<Set<Data>, Never>([])
@@ -235,6 +262,7 @@ final class NetworkReachabilityGateTests: XCTestCase {
)
return Context(
service: service,
storage: storage,
reachability: reachability,
torController: torController,
relayController: relayController
@@ -257,6 +285,7 @@ final class NetworkReachabilityGateTests: XCTestCase {
@MainActor
private struct Context {
let service: NetworkActivationService
let storage: UserDefaults
let reachability: ControllableReachabilityMonitor
let torController: GateMockTorController
let relayController: GateMockRelayController
@@ -247,15 +247,17 @@ final class PanicWipeCoverageTests: XCTestCase {
PrivacyModeSettings.setSendReadReceipts(false, in: defaults)
XCTAssertFalse(PrivacyModeSettings.shouldSendReadReceipts(in: defaults))
PrivacyModeSettings.resetForPanic(in: defaults, wasTorEnabled: false)
PrivacyModeSettings.resetForPanic(in: defaults)
XCTAssertNil(defaults.object(forKey: PrivacyModeSettings.sendReadReceiptsKey))
XCTAssertTrue(PrivacyModeSettings.shouldSendReadReceipts(in: defaults))
XCTAssertTrue(NetworkActivationService.persistedTorPreference(in: defaults))
// Stealth mode preserves read-receipts-off posture across panic wipe.
PrivacyModeSettings.setMode(.stealth, in: defaults)
XCTAssertFalse(PrivacyModeSettings.shouldSendReadReceipts(in: defaults))
PrivacyModeSettings.resetForPanic(in: defaults, wasTorEnabled: true)
PrivacyModeSettings.resetForPanic(in: defaults)
XCTAssertFalse(PrivacyModeSettings.shouldSendReadReceipts(in: defaults))
XCTAssertTrue(NetworkActivationService.persistedTorPreference(in: defaults))
}
func test_encryptedHistoryStore_wipe_clearsSealedReadReceipts() {
@@ -87,21 +87,21 @@ final class PrivacyModeSettingsTests: XCTestCase {
XCTAssertFalse(PrivacyModeSettings.shouldPersistPrivateHistory(in: defaults))
}
func test_migrateLegacyInstall_leavesFresh20InstallInEverydayMode() {
func test_migrateLegacyInstall_leavesFresh20InstallInEverydayModeWithTorOn() {
let defaults = makeDefaults()
let migrated = PrivacyModeSettings.migrateLegacyInstallIfNeeded(in: defaults)
XCTAssertFalse(migrated)
XCTAssertEqual(PrivacyModeSettings.currentMode(in: defaults), .everyday)
XCTAssertFalse(NetworkActivationService.persistedTorPreference(in: defaults))
XCTAssertTrue(NetworkActivationService.persistedTorPreference(in: defaults))
XCTAssertTrue(PrivacyModeSettings.shouldPersistPrivateHistory(in: defaults))
XCTAssertFalse(PrivacyModeSettings.isTripleTapPanicEnabled(in: defaults))
// Writing 2.0 keys afterwards never retro-triggers 1.x migration.
defaults.set("charlie", forKey: "bitchat.nickname")
XCTAssertFalse(PrivacyModeSettings.migrateLegacyInstallIfNeeded(in: defaults))
XCTAssertFalse(NetworkActivationService.persistedTorPreference(in: defaults))
XCTAssertTrue(NetworkActivationService.persistedTorPreference(in: defaults))
}
func test_resetForPanic_preservesStealthTorPostureAndTripleTap() {
@@ -116,6 +116,48 @@ final class PrivacyModeSettingsTests: XCTestCase {
XCTAssertFalse(PrivacyModeSettings.shouldPersistPrivateHistory(in: defaults))
XCTAssertTrue(PrivacyModeSettings.isTripleTapPanicEnabled(in: defaults))
}
func test_resetForPanic_everydayRestoresDefaultTorOnWithoutForcingStealth() {
let defaults = makeDefaults()
PrivacyModeSettings.setMode(.everyday, in: defaults)
defaults.set(false, forKey: NetworkActivationService.torPreferenceKey)
XCTAssertFalse(NetworkActivationService.persistedTorPreference(in: defaults))
PrivacyModeSettings.resetForPanic(in: defaults)
XCTAssertEqual(PrivacyModeSettings.currentMode(in: defaults), .everyday)
XCTAssertTrue(NetworkActivationService.persistedTorPreference(in: defaults))
XCTAssertTrue(PrivacyModeSettings.shouldPersistPrivateHistory(in: defaults))
XCTAssertFalse(PrivacyModeSettings.isTripleTapPanicEnabled(in: defaults))
}
@MainActor
func test_stealthMode_enforcesBridgeOffAndPublicAutoPlayOff() {
let defaults = makeDefaults()
let center = NotificationCenter()
let bridge = BridgeService(defaults: defaults, notificationCenter: center)
bridge.setEnabled(true)
PTTSettings.setPublicAutoPlayEnabled(true, in: defaults)
XCTAssertTrue(bridge.isEnabled)
XCTAssertTrue(PTTSettings.publicAutoPlayEnabled(in: defaults))
PrivacyModeSettings.setMode(.stealth, in: defaults, notificationCenter: center)
XCTAssertFalse(bridge.isEnabled)
XCTAssertFalse(PTTSettings.publicAutoPlayEnabled(in: defaults))
XCTAssertTrue(NotificationPrivacySettings.hideMessagePreviews(in: defaults))
// Enabling Bridge while in Stealth Mode must be rejected.
bridge.setEnabled(true)
XCTAssertFalse(bridge.isEnabled)
// Switching back to Everyday restores the user's Everyday settings.
PrivacyModeSettings.setMode(.everyday, in: defaults, notificationCenter: center)
XCTAssertTrue(bridge.isEnabled)
XCTAssertTrue(PTTSettings.publicAutoPlayEnabled(in: defaults))
}
}
@MainActor
@@ -3,24 +3,25 @@ import Testing
@testable import bitchat
/// Verifies off-main Tor preference reads used by background tasks like geo-relay
/// directory refresh. Everyday Mode defaults to direct (Tor off) for instant
/// cold start; Stealth Mode and explicit `true` enable Tor.
/// directory refresh. Tor defaults ON everywhere; only an explicit `false` in
/// Everyday Mode disables it, and Stealth Mode always enforces Tor fail-closed.
struct TorPreferenceReadTests {
private func makeDefaults() -> UserDefaults {
UserDefaults(suiteName: "bitchat.tests.tor.\(UUID().uuidString)")!
}
@Test func defaultsToOffInEverydayModeWhenNothingHasBeenStored() {
#expect(!NetworkActivationService.persistedTorPreference(in: makeDefaults()))
@Test func defaultsToOnInEverydayModeWhenNothingHasBeenStored() {
#expect(NetworkActivationService.persistedTorPreference(in: makeDefaults()))
}
@Test func defaultsToOnInStealthModeWhenExplicitTorPreferenceIsUnset() {
@Test func defaultsToOnInStealthModeEvenWhenExplicitFalseStored() {
let defaults = makeDefaults()
defaults.set(false, forKey: NetworkActivationService.torPreferenceKey)
defaults.set(PrivacyMode.stealth.rawValue, forKey: PrivacyModeSettings.modeKey)
#expect(NetworkActivationService.persistedTorPreference(in: defaults))
}
@Test func reflectsTheStoredPreference() {
@Test func reflectsTheStoredPreferenceInEverydayMode() {
let defaults = makeDefaults()
defaults.set(false, forKey: NetworkActivationService.torPreferenceKey)
@@ -30,10 +31,10 @@ struct TorPreferenceReadTests {
#expect(NetworkActivationService.persistedTorPreference(in: defaults))
}
@Test func nonBooleanStoredValueFallsBackToPrivacyModeDefault() {
@Test func nonBooleanStoredValueFallsBackFailClosedToTrue() {
let defaults = makeDefaults()
defaults.set("nonsense", forKey: NetworkActivationService.torPreferenceKey)
#expect(!NetworkActivationService.persistedTorPreference(in: defaults))
#expect(NetworkActivationService.persistedTorPreference(in: defaults))
defaults.set(PrivacyMode.stealth.rawValue, forKey: PrivacyModeSettings.modeKey)
#expect(NetworkActivationService.persistedTorPreference(in: defaults))