mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-26 18:25:21 +00:00
Keep working when the network is hostile, and make the app verifiable
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: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
name: Source manifest
|
||||
|
||||
# Publishes a hash manifest for every tagged release so a copy of the source
|
||||
# obtained from somewhere other than this repository can be checked against it.
|
||||
#
|
||||
# This exists because the repository has been the target of takedown demands.
|
||||
# When that succeeds, mirrors appear, and without a manifest there is no way to
|
||||
# tell a faithful mirror from a modified one. The manifest is attested to this
|
||||
# workflow run, so its own provenance is verifiable with `gh attestation verify`.
|
||||
#
|
||||
# Scope, stated plainly: this verifies SOURCE. It does not verify any compiled
|
||||
# app. See docs/VERIFYING-A-BUILD.md.
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ref:
|
||||
description: 'Tag or commit to produce a manifest for'
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
manifest:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # attach the manifest to the release
|
||||
id-token: write # provenance attestation
|
||||
attestations: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.inputs.ref || github.ref }}
|
||||
# Full history so the commit the tag names can be recorded exactly.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Build manifest
|
||||
id: build
|
||||
run: |
|
||||
set -euo pipefail
|
||||
ref_name="${{ github.event.inputs.ref || github.ref_name }}"
|
||||
commit="$(git rev-parse HEAD)"
|
||||
tree="$(git rev-parse HEAD^{tree})"
|
||||
|
||||
# Hash every tracked file, in a stable order, with NUL separation so
|
||||
# paths containing spaces or newlines cannot shift the columns.
|
||||
git ls-files -z \
|
||||
| sort -z \
|
||||
| xargs -0 sha256sum \
|
||||
> files.sha256
|
||||
|
||||
{
|
||||
echo "# bitchat source manifest"
|
||||
echo "#"
|
||||
echo "# ref: ${ref_name}"
|
||||
echo "# commit: ${commit}"
|
||||
echo "# tree: ${tree}"
|
||||
echo "# files: $(wc -l < files.sha256 | tr -d ' ')"
|
||||
echo "#"
|
||||
echo "# Verify a checkout of this ref with:"
|
||||
echo "# shasum -a 256 -c files.sha256"
|
||||
echo "# The git tree hash above is the single value that covers all of it:"
|
||||
echo "# git rev-parse HEAD^{tree}"
|
||||
echo "#"
|
||||
} > SOURCE-MANIFEST.txt
|
||||
cat files.sha256 >> SOURCE-MANIFEST.txt
|
||||
|
||||
echo "commit=${commit}" >> "$GITHUB_OUTPUT"
|
||||
echo "tree=${tree}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Self-check the manifest
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# A manifest that does not validate against the tree it was made from
|
||||
# is worse than none, so fail loudly rather than publishing it.
|
||||
grep -v '^#' SOURCE-MANIFEST.txt > check.sha256
|
||||
sha256sum -c check.sha256 > /dev/null
|
||||
echo "manifest validates against this checkout"
|
||||
|
||||
- name: Attest the manifest
|
||||
uses: actions/attest-build-provenance@v1
|
||||
with:
|
||||
subject-path: SOURCE-MANIFEST.txt
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: source-manifest
|
||||
path: SOURCE-MANIFEST.txt
|
||||
|
||||
- name: Attach to release
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# A tag may be pushed before its release exists; only attach when
|
||||
# there is a release to attach to, and never fail the run over it.
|
||||
if gh release view "${{ github.ref_name }}" >/dev/null 2>&1; then
|
||||
gh release upload "${{ github.ref_name }}" SOURCE-MANIFEST.txt --clobber
|
||||
else
|
||||
echo "no release for ${{ github.ref_name }} yet; manifest is available as a workflow artifact"
|
||||
fi
|
||||
@@ -81,6 +81,8 @@ Internet-backed features are optional. When enabled or used:
|
||||
|
||||
Nostr relays are operated by third parties. Their retention, logging, availability, and privacy practices are outside the project's control. Public events and encrypted events may remain on relays according to each relay's policy.
|
||||
|
||||
You can add relays yourself in settings, including `.onion` addresses. Added relays are stored locally, are limited in number, and are erased by panic wipe. Tor routing is on by default; while it is off, every relay you connect to can see your IP address, including relays carrying your private messages.
|
||||
|
||||
## Location and Apple Services
|
||||
|
||||
Location permission is optional and requested as when-in-use access. It is used to compute geohash channels, bridge rendezvous cells, and nearby place labels.
|
||||
|
||||
@@ -8,6 +8,12 @@ A decentralized peer-to-peer messaging app with dual transport architecture: loc
|
||||
|
||||
📲 [App Store](https://apps.apple.com/us/app/bitchat-mesh/id6748219622)
|
||||
|
||||
### Getting a copy you can trust
|
||||
|
||||
Install from the App Store, or build from source you have verified. A compiled build from anywhere else cannot be verified — see [Verifying bitchat](docs/VERIFYING-A-BUILD.md) for how to check source against the per-release hash manifest, and for what to do if that is the only build you can get.
|
||||
|
||||
This matters more than it usually would: this repository has been the target of takedown demands, and when a repository or releases page disappears, mirrors appear that nobody can check.
|
||||
|
||||
## License
|
||||
|
||||
This project is released into the public domain. See the [LICENSE](LICENSE) file for details.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -319,6 +319,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?
|
||||
@@ -1628,6 +1630,9 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
GeohashChatActivityTracker.shared.clear()
|
||||
MeshSightingsTracker.shared.clear()
|
||||
MeshEchoSettings.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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,9 @@ struct AppInfoView: View {
|
||||
@State private var showTopology = false
|
||||
@State private var liveVoiceEnabled = PTTSettings.liveVoiceEnabled
|
||||
@State private var locationNotesEnabled = LocationNotesSettings.enabled
|
||||
@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.
|
||||
@@ -79,7 +82,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"
|
||||
|
||||
@@ -410,11 +440,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
|
||||
@@ -538,6 +579,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 },
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import bitchat
|
||||
|
||||
/// The built-in relay set is four well-known hostnames, so a filter blocking
|
||||
/// four names ends internet-delivered private messages. These cover the
|
||||
/// hand-added relays that make that recoverable without shipping a build.
|
||||
struct NostrRelaySettingsTests {
|
||||
/// Each case gets its own suite so nothing touches the real preferences or
|
||||
/// races another case.
|
||||
private func makeDefaults() -> UserDefaults {
|
||||
let suite = "bitchat.tests.relays.\(UUID().uuidString)"
|
||||
return UserDefaults(suiteName: suite)!
|
||||
}
|
||||
|
||||
private let builtIn: Set<String> = [
|
||||
"wss://relay.damus.io",
|
||||
"wss://nos.lol"
|
||||
]
|
||||
|
||||
@Test func addNormalizesABareHostname() {
|
||||
let defaults = makeDefaults()
|
||||
|
||||
// A bare hostname is how relays are usually quoted; wss is the only
|
||||
// sensible assumption.
|
||||
let result = NostrRelaySettings.add("relay.example.com", builtIn: builtIn, in: defaults)
|
||||
|
||||
#expect(result == .success("wss://relay.example.com"))
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults) == ["wss://relay.example.com"])
|
||||
}
|
||||
|
||||
@Test func addAcceptsAnOnionAddress() {
|
||||
let defaults = makeDefaults()
|
||||
|
||||
// The reason this feature exists: an onion relay is not blockable by
|
||||
// hostname or SNI filtering.
|
||||
let result = NostrRelaySettings.add(
|
||||
"wss://exampleonionaddressxyz234567.onion",
|
||||
builtIn: builtIn,
|
||||
in: defaults
|
||||
)
|
||||
|
||||
#expect(result == .success("wss://exampleonionaddressxyz234567.onion"))
|
||||
}
|
||||
|
||||
@Test func addRejectsMalformedInput() {
|
||||
let defaults = makeDefaults()
|
||||
|
||||
#expect(NostrRelaySettings.add("", builtIn: builtIn, in: defaults) == .failure(.malformed))
|
||||
#expect(NostrRelaySettings.add(" ", builtIn: builtIn, in: defaults) == .failure(.malformed))
|
||||
// A scheme the relay layer cannot dial must not be stored.
|
||||
#expect(NostrRelaySettings.add("ftp://relay.example.com", builtIn: builtIn, in: defaults) == .failure(.malformed))
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults).isEmpty)
|
||||
}
|
||||
|
||||
@Test func addRejectsDuplicatesAndBuiltIns() {
|
||||
let defaults = makeDefaults()
|
||||
#expect(NostrRelaySettings.add("wss://relay.example.com", builtIn: builtIn, in: defaults) == .success("wss://relay.example.com"))
|
||||
|
||||
// Same relay written differently still normalizes to the same URL.
|
||||
#expect(NostrRelaySettings.add("relay.example.com", builtIn: builtIn, in: defaults) == .failure(.alreadyPresent))
|
||||
#expect(NostrRelaySettings.add("WSS://Relay.Example.com", builtIn: builtIn, in: defaults) == .failure(.alreadyPresent))
|
||||
// Re-adding a built-in would double-count it in the target list.
|
||||
#expect(NostrRelaySettings.add("wss://nos.lol", builtIn: builtIn, in: defaults) == .failure(.alreadyPresent))
|
||||
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults) == ["wss://relay.example.com"])
|
||||
}
|
||||
|
||||
@Test func addStopsAtTheLimit() {
|
||||
let defaults = makeDefaults()
|
||||
for index in 0..<NostrRelaySettings.maxCustomRelays {
|
||||
#expect(NostrRelaySettings.add("relay\(index).example.com", builtIn: builtIn, in: defaults) == .success("wss://relay\(index).example.com"))
|
||||
}
|
||||
|
||||
// Unbounded growth would fan every send out across dozens of sockets.
|
||||
#expect(NostrRelaySettings.add("one.too.many.example.com", builtIn: builtIn, in: defaults) == .failure(.limitReached))
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults).count == NostrRelaySettings.maxCustomRelays)
|
||||
}
|
||||
|
||||
@Test func addPreservesInsertionOrder() {
|
||||
let defaults = makeDefaults()
|
||||
NostrRelaySettings.add("b.example.com", builtIn: builtIn, in: defaults)
|
||||
NostrRelaySettings.add("a.example.com", builtIn: builtIn, in: defaults)
|
||||
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults) == ["wss://b.example.com", "wss://a.example.com"])
|
||||
}
|
||||
|
||||
@Test func removeTakesAnyEquivalentSpelling() {
|
||||
let defaults = makeDefaults()
|
||||
NostrRelaySettings.add("wss://relay.example.com", builtIn: builtIn, in: defaults)
|
||||
NostrRelaySettings.add("wss://other.example.com", builtIn: builtIn, in: defaults)
|
||||
|
||||
NostrRelaySettings.remove("Relay.Example.com", in: defaults)
|
||||
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults) == ["wss://other.example.com"])
|
||||
}
|
||||
|
||||
@Test func resetClearsEverything() {
|
||||
let defaults = makeDefaults()
|
||||
NostrRelaySettings.add("relay.example.com", builtIn: builtIn, in: defaults)
|
||||
|
||||
// Panic wipe: an added relay names an operator someone chose to route
|
||||
// through, which is exactly the trace a wipe must not leave.
|
||||
NostrRelaySettings.reset(in: defaults)
|
||||
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults).isEmpty)
|
||||
}
|
||||
|
||||
@Test func readsSkipUnusableStoredValues() {
|
||||
let defaults = makeDefaults()
|
||||
// Written by an older build, or edited outside the app: it must not
|
||||
// reach the connection layer unchecked.
|
||||
defaults.set(
|
||||
["wss://good.example.com", "ftp://bad.example.com", "", "wss://good.example.com"],
|
||||
forKey: "nostr.customRelays"
|
||||
)
|
||||
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults) == ["wss://good.example.com"])
|
||||
}
|
||||
|
||||
@Test func builtInRelaysAreExposedNormalizedForDeduplication() {
|
||||
// The UI rejects re-adding a built-in by comparing against this set, so
|
||||
// it has to hold normalized URLs.
|
||||
let builtIn = NostrRelayManager.builtInRelayURLs
|
||||
#expect(!builtIn.isEmpty)
|
||||
for url in builtIn {
|
||||
#expect(NostrRelayURL.normalized(url) == url)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -138,9 +138,67 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
XCTAssertEqual(context.relayController.connectCallCount, 2)
|
||||
}
|
||||
|
||||
/// Teleporting into a geohash needs no location permission, so someone who
|
||||
/// denied location and has no mutual favorites could previously sit in a
|
||||
/// channel that never connected: the gate suppressed Tor and the relays,
|
||||
/// and nothing explained why.
|
||||
func test_start_enablesNetworkForALocationChannelWithoutPermissionOrFavorites() {
|
||||
let context = makeService(
|
||||
permission: .denied,
|
||||
favorites: [],
|
||||
selectedChannel: .location(GeohashChannel(level: .city, geohash: "u4pruy"))
|
||||
)
|
||||
|
||||
context.service.start()
|
||||
|
||||
XCTAssertTrue(context.service.activationAllowed)
|
||||
XCTAssertEqual(context.torController.startIfNeededCallCount, 1)
|
||||
XCTAssertEqual(context.relayController.connectCallCount, 1)
|
||||
}
|
||||
|
||||
func test_selectedChannelPublisher_activatesOnEnteringALocationChannel() async {
|
||||
let channelSubject = CurrentValueSubject<ChannelID, Never>(.mesh)
|
||||
let context = makeService(
|
||||
permission: .denied,
|
||||
favorites: [],
|
||||
selectedChannelSubject: channelSubject
|
||||
)
|
||||
|
||||
context.service.start()
|
||||
XCTAssertFalse(context.service.activationAllowed)
|
||||
|
||||
channelSubject.send(.location(GeohashChannel(level: .city, geohash: "u4pruy")))
|
||||
|
||||
let activated = await waitUntil { context.service.activationAllowed }
|
||||
XCTAssertTrue(activated)
|
||||
}
|
||||
|
||||
/// Leaving the channel must close the gate again, or the exception would
|
||||
/// quietly become permanent for the rest of the session.
|
||||
func test_selectedChannelPublisher_deactivatesOnReturningToMesh() async {
|
||||
let channelSubject = CurrentValueSubject<ChannelID, Never>(
|
||||
.location(GeohashChannel(level: .city, geohash: "u4pruy"))
|
||||
)
|
||||
let context = makeService(
|
||||
permission: .denied,
|
||||
favorites: [],
|
||||
selectedChannelSubject: channelSubject
|
||||
)
|
||||
|
||||
context.service.start()
|
||||
XCTAssertTrue(context.service.activationAllowed)
|
||||
|
||||
channelSubject.send(.mesh)
|
||||
|
||||
let deactivated = await waitUntil { !context.service.activationAllowed }
|
||||
XCTAssertTrue(deactivated)
|
||||
}
|
||||
|
||||
private func makeService(
|
||||
permission: LocationChannelManager.PermissionState,
|
||||
favorites: Set<Data>
|
||||
favorites: Set<Data>,
|
||||
selectedChannel: ChannelID = .mesh,
|
||||
selectedChannelSubject: CurrentValueSubject<ChannelID, Never>? = nil
|
||||
) -> NetworkActivationTestContext {
|
||||
let suiteName = "NetworkActivationServiceTests-\(UUID().uuidString)"
|
||||
let storage = UserDefaults(suiteName: suiteName)!
|
||||
@@ -148,6 +206,8 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
|
||||
let permissionSubject = CurrentValueSubject<LocationChannelManager.PermissionState, Never>(permission)
|
||||
let favoritesSubject = CurrentValueSubject<Set<Data>, Never>(favorites)
|
||||
let channelSubject = selectedChannelSubject
|
||||
?? CurrentValueSubject<ChannelID, Never>(selectedChannel)
|
||||
let torController = MockNetworkActivationTorController()
|
||||
let relayController = MockNetworkActivationRelayController()
|
||||
let proxyController = MockNetworkActivationProxyController()
|
||||
@@ -159,6 +219,11 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
mutualFavoritesPublisher: favoritesSubject.eraseToAnyPublisher(),
|
||||
permissionProvider: { permissionSubject.value },
|
||||
mutualFavoritesProvider: { favoritesSubject.value },
|
||||
selectedChannelPublisher: channelSubject.eraseToAnyPublisher(),
|
||||
locationChannelSelectedProvider: {
|
||||
if case .location = channelSubject.value { return true }
|
||||
return false
|
||||
},
|
||||
reachabilityMonitor: reachability,
|
||||
torController: torController,
|
||||
relayController: relayController,
|
||||
|
||||
@@ -1735,6 +1735,58 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
XCTAssertGreaterThan(Set(factors).count, 1)
|
||||
}
|
||||
|
||||
// MARK: - Hand-added relays
|
||||
|
||||
/// Adding a relay has to take effect without a restart: the whole point is
|
||||
/// recovering reachability when the built-in hostnames are blocked.
|
||||
@MainActor
|
||||
func testAddedRelayJoinsTheTargetSetOnSettingsChange() async {
|
||||
let center = NotificationCenter()
|
||||
let custom = MutableRelayList(urls: [])
|
||||
let context = makeContext(
|
||||
permission: .authorized,
|
||||
notificationCenter: center,
|
||||
customRelays: custom
|
||||
)
|
||||
|
||||
XCTAssertFalse(context.manager.relays.contains { $0.url == "wss://added.example.com" })
|
||||
|
||||
custom.urls = ["wss://added.example.com"]
|
||||
center.post(name: NostrRelaySettings.didChangeNotification, object: nil)
|
||||
|
||||
let joined = await waitUntil {
|
||||
context.manager.relays.contains { $0.url == "wss://added.example.com" }
|
||||
}
|
||||
XCTAssertTrue(joined)
|
||||
}
|
||||
|
||||
/// Removing a relay must actually close it. The teardown path iterates the
|
||||
/// current target list, and a removed relay is no longer in it, so without
|
||||
/// an explicit reconcile against the previous set its socket and queued
|
||||
/// sends would linger.
|
||||
@MainActor
|
||||
func testRemovedRelayLeavesTheTargetSet() async {
|
||||
let center = NotificationCenter()
|
||||
let custom = MutableRelayList(urls: ["wss://added.example.com"])
|
||||
let context = makeContext(
|
||||
permission: .authorized,
|
||||
notificationCenter: center,
|
||||
customRelays: custom
|
||||
)
|
||||
|
||||
XCTAssertTrue(context.manager.relays.contains { $0.url == "wss://added.example.com" })
|
||||
|
||||
custom.urls = []
|
||||
center.post(name: NostrRelaySettings.didChangeNotification, object: nil)
|
||||
|
||||
let dropped = await waitUntil {
|
||||
!context.manager.relays.contains { $0.url == "wss://added.example.com" }
|
||||
}
|
||||
XCTAssertTrue(dropped)
|
||||
// The built-in relays are untouched by a custom-relay removal.
|
||||
XCTAssertTrue(context.manager.relays.contains { $0.url == "wss://nos.lol" })
|
||||
}
|
||||
|
||||
private func makeContext(
|
||||
permission: LocationChannelManager.PermissionState,
|
||||
favorites: Set<Data> = [],
|
||||
@@ -1743,6 +1795,8 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
torEnforced: Bool = false,
|
||||
torIsReady: Bool = true,
|
||||
torIsForeground: Bool = true,
|
||||
notificationCenter: NotificationCenter = NotificationCenter(),
|
||||
customRelays: MutableRelayList = MutableRelayList(urls: []),
|
||||
jitterUnit: @escaping () -> Double = { 0.5 } // 0.5 -> jitter factor 1.0 (no jitter)
|
||||
) -> RelayManagerTestContext {
|
||||
let permissionSubject = CurrentValueSubject<LocationChannelManager.PermissionState, Never>(permission)
|
||||
@@ -1770,7 +1824,9 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
scheduler.schedule(delay: delay, action: action)
|
||||
},
|
||||
now: { clock.now },
|
||||
jitterUnit: jitterUnit
|
||||
jitterUnit: jitterUnit,
|
||||
notificationCenter: notificationCenter,
|
||||
customRelays: { customRelays.urls }
|
||||
)
|
||||
)
|
||||
return RelayManagerTestContext(
|
||||
@@ -1845,6 +1901,16 @@ private final class MutableClock {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stand-in for the persisted hand-added relay list, so tests can change it
|
||||
/// without writing to shared preferences.
|
||||
private final class MutableRelayList {
|
||||
var urls: [String]
|
||||
|
||||
init(urls: [String]) {
|
||||
self.urls = urls
|
||||
}
|
||||
}
|
||||
|
||||
/// Deterministic jitter source: returns the queued values in order, then a
|
||||
/// neutral 0.5 (jitter factor 1.0) once exhausted.
|
||||
private final class JitterSequence {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import bitchat
|
||||
|
||||
/// The geo-relay directory refresh runs off the main actor and has to decide
|
||||
/// whether waiting for Tor is meaningful. It previously waited unconditionally,
|
||||
/// so with Tor switched off — and `TorManager` therefore shut down — every
|
||||
/// refresh spent the full bootstrap timeout and the directory froze on its
|
||||
/// cached copy.
|
||||
struct TorPreferenceReadTests {
|
||||
private func makeDefaults() -> UserDefaults {
|
||||
UserDefaults(suiteName: "bitchat.tests.tor.\(UUID().uuidString)")!
|
||||
}
|
||||
|
||||
@Test func defaultsToOnWhenNothingHasBeenStored() {
|
||||
// Fail safe: an unwritten preference must not read as "Tor off", which
|
||||
// would let a fetch go direct.
|
||||
#expect(NetworkActivationService.persistedTorPreference(in: makeDefaults()))
|
||||
}
|
||||
|
||||
@Test func reflectsTheStoredPreference() {
|
||||
let defaults = makeDefaults()
|
||||
|
||||
defaults.set(false, forKey: NetworkActivationService.torPreferenceKey)
|
||||
#expect(!NetworkActivationService.persistedTorPreference(in: defaults))
|
||||
|
||||
defaults.set(true, forKey: NetworkActivationService.torPreferenceKey)
|
||||
#expect(NetworkActivationService.persistedTorPreference(in: defaults))
|
||||
}
|
||||
|
||||
@Test func nonBooleanStoredValueReadsAsOn() {
|
||||
let defaults = makeDefaults()
|
||||
defaults.set("nonsense", forKey: NetworkActivationService.torPreferenceKey)
|
||||
|
||||
// Same fail-safe direction: anything unrecognized means keep using Tor.
|
||||
#expect(NetworkActivationService.persistedTorPreference(in: defaults))
|
||||
}
|
||||
}
|
||||
+43
-37
@@ -1,47 +1,53 @@
|
||||
Tor-by-default integration (scaffold)
|
||||
# Tor integration
|
||||
|
||||
Overview
|
||||
- All network traffic is routed via a local Tor SOCKS5 proxy by default, with fail-closed behavior when Tor isn’t ready. There are no user-visible settings.
|
||||
- This repo vendors an Arti-backed Swift package under `localPackages/Arti`, including a Rust static-library xcframework linked by SwiftPM.
|
||||
## Overview
|
||||
|
||||
Key pieces
|
||||
- TorManager
|
||||
- Boots Tor, manages a DataDirectory under Application Support, exposes SOCKS at 127.0.0.1:39050, and provides awaitReady().
|
||||
- Fails closed by default until Tor is bootstrapped. For local development only, define BITCHAT_DEV_ALLOW_CLEARNET to bypass Tor.
|
||||
- TorURLSession
|
||||
- Provides a shared URLSession configured with a SOCKS5 proxy when Tor is enforced/ready.
|
||||
- NostrRelayManager and GeoRelayDirectory now use this session and await Tor readiness before starting network activity.
|
||||
Internet traffic — Nostr relay sockets and the geo-relay directory fetch — is routed through Tor by default, fail-closed: when Tor is wanted but not ready, requests queue rather than falling back to clearnet.
|
||||
|
||||
Artifact maintenance
|
||||
- Binary provenance, rebuild steps, and current hashes are documented in `docs/ARTI-BINARY-PROVENANCE.md`.
|
||||
Tor is provided by **Arti, in-process**, vendored as a Swift package under `localPackages/Arti` wrapping a Rust static-library xcframework. There is no `tor` binary, no `torrc`, and no control port. A SOCKS5 listener on `127.0.0.1:39050` is the only interface.
|
||||
|
||||
## Key pieces
|
||||
|
||||
- **`TorManager`** — owns the Arti client and its data directory under Application Support, exposes the SOCKS port, and provides `awaitReady()`.
|
||||
- `torEnforced` is compile-time: true unless `BITCHAT_DEV_ALLOW_CLEARNET` is defined. It is not set anywhere in `Configs/` or the project file, so release builds enforce.
|
||||
- `isStarting`, `bootstrapProgress`, and `bootstrapSummary` describe an attempt in flight.
|
||||
- `bootstrapDidStall` becomes true when an attempt spends its whole 75-second deadline without completing, and posts `.TorBootstrapDidStall`. This is the state a network that blocks Tor produces, and it is deliberately distinct from `isStarting`: without it the UI says "starting tor…" indefinitely. It is cleared on each new start or restart.
|
||||
- **`TorURLSession`** — a shared `URLSession` with the SOCKS proxy configured when proxying is on, and an unproxied session when it is off. `setProxyMode(useTor:)` is the switch, driven by `NetworkActivationService`.
|
||||
- **`NetworkActivationService`** — decides whether Tor may run at all. Tor starts when the activation policy permits it *and* the Tor preference is on. `persistedTorPreference(in:)` is a `nonisolated` read of that preference for callers off the main actor.
|
||||
|
||||
Both network call sites go through `TorURLSession`: `NostrRelayManager` (relay websockets) and `GeoRelayDirectory` (directory CSV refresh). There is no other outbound network in the app or the share extension.
|
||||
|
||||
## The Tor preference is user-visible
|
||||
|
||||
The earlier version of this document said there are no user-visible settings. There is one: a **tor routing** toggle in settings, persisted under `networkActivationService.userTorEnabled`, defaulting to on.
|
||||
|
||||
Turning it off is a real change in exposure, not a performance tweak. Every fail-closed guard is conditioned on the preference, so with it off:
|
||||
|
||||
- relay websockets connect directly, and every relay operator sees the device IP — including relays carrying private messages;
|
||||
- the geo-relay directory fetch also goes direct.
|
||||
|
||||
The settings UI states this while the toggle is off.
|
||||
|
||||
`GeoRelayDirectory` keys its Tor wait on the *preference*, not on live readiness, and this distinction is load-bearing. With Tor off, waiting for a client that has been shut down would spend the full bootstrap timeout on every refresh and freeze the directory on its cached copy. With Tor on but not ready, the wait must still fail so the fetch is skipped rather than silently leaking the IP.
|
||||
|
||||
## Relays
|
||||
|
||||
Private messages target the built-in relay set plus any relays added by hand (`NostrRelaySettings`, capped at 8, `.onion` addresses accepted). The built-in set is four well-known clearnet hostnames, so a filter blocking four names would otherwise end internet-delivered private messages until a new build shipped.
|
||||
|
||||
## Artifact maintenance
|
||||
|
||||
- Binary provenance, rebuild steps, and current hashes: `docs/ARTI-BINARY-PROVENANCE.md`, enforced by `.github/workflows/arti-provenance.yml`.
|
||||
- The xcframework must include iOS device, iOS simulator, and macOS arm64 slices.
|
||||
- Any refresh should review the Rust source, `Cargo.lock`, generated header, build script, and new hashes together.
|
||||
- Any refresh reviews the Rust source, `Cargo.lock`, generated header, build script, and new hashes together. A binary-only update is not acceptable.
|
||||
|
||||
Verification
|
||||
- On app launch, TorManager.startIfNeeded() is called implicitly by awaitReady().
|
||||
- NostrRelayManager.connect() awaits readiness, then creates WebSocket tasks via TorURLSession.shared.
|
||||
- GeoRelayDirectory.fetchRemote() awaits readiness, then fetches via TorURLSession.shared.
|
||||
## Known gap: no bridges or pluggable transports
|
||||
|
||||
Optional macOS optimization
|
||||
- Detect a system Tor binary (e.g., /opt/homebrew/bin/tor) and run it as a subprocess to avoid bundling. Keep the embedded fallback for portability.
|
||||
`arti-client` is built with `default-features = false` and features `["tokio", "rustls"]` only — no `pt-client`, no `bridge-client` — and `arti-bitchat/src/lib.rs` bootstraps from stock configuration with no bridge lines and no configurable directory authorities.
|
||||
|
||||
torrc template
|
||||
The generated torrc (under Application Support/bitchat/tor/torrc) is:
|
||||
So in a country that blocks Tor by blocking the public relays and directory authorities, bootstrap never completes. The app reports that clearly now instead of appearing to start forever, and the BLE mesh is unaffected, but there is no circumvention path: obfs4, snowflake, and meek are all unavailable.
|
||||
|
||||
DataDirectory <AppSupport>/bitchat/tor
|
||||
ClientOnly 1
|
||||
SOCKSPort 127.0.0.1:39050
|
||||
ControlPort 127.0.0.1:39051
|
||||
CookieAuthentication 1
|
||||
AvoidDiskWrites 1
|
||||
MaxClientCircuitsPending 8
|
||||
Closing this means enabling the pluggable-transport features, plumbing bridge configuration through the FFI and a settings surface, and rebuilding the xcframework under the pinned toolchain with a provenance-manifest update. That is the single largest remaining gap in censorship resilience for the internet transport.
|
||||
|
||||
Dev bypass (local only)
|
||||
- To temporarily allow direct network without Tor for local development:
|
||||
- Add Swift compiler flag: BITCHAT_DEV_ALLOW_CLEARNET
|
||||
- This enables a clearnet session in TorURLSession when Tor isn’t present.
|
||||
- Never enable this in release builds.
|
||||
## Dev bypass (local only)
|
||||
|
||||
Notes
|
||||
- We intentionally do not change any app-level APIs: consumers simply use TorURLSession via existing code paths.
|
||||
- When Tor is missing in release builds, the app will not connect (fail-closed), logging a clear reason.
|
||||
Define the Swift compiler flag `BITCHAT_DEV_ALLOW_CLEARNET` to allow direct network access without Tor while developing. Never enable it in release builds.
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
# Verifying bitchat
|
||||
|
||||
This document is about a specific risk: getting a copy of bitchat that someone has modified.
|
||||
|
||||
It matters because the repository has been the target of takedown demands. When a repository or a releases page becomes unavailable, mirrors appear, and people who need the app during a shutdown install whatever they can find. That is exactly the moment a trojaned build reaches the people with the most to lose. A modified bitchat can log plaintext, ship keys off the device, or weaken the mesh, and it will look and behave normally while doing it.
|
||||
|
||||
The honest summary is short. **Source can be verified. Compiled apps cannot, unless they come from the App Store.** Everything below elaborates on that.
|
||||
|
||||
## Getting the app
|
||||
|
||||
In order of how much verification is possible:
|
||||
|
||||
1. **The App Store.** Apple verifies the developer signature, and the binary cannot be altered without breaking it. This is the only channel where a compiled build is verifiable end to end, and it is the right recommendation for almost everyone.
|
||||
2. **Build it yourself from verified source.** See below. Requires a Mac and Xcode, and gives you the strongest guarantee if you can do it.
|
||||
3. **A compiled build from anywhere else.** Not verifiable. See "Builds from other sources".
|
||||
|
||||
## Verifying source
|
||||
|
||||
Every tagged release has a `SOURCE-MANIFEST.txt` produced by `.github/workflows/source-manifest.yml`. It records the tag, the commit, the git tree hash, and a SHA-256 for every tracked file.
|
||||
|
||||
Check a copy of the source against it:
|
||||
|
||||
```sh
|
||||
# From the root of the source you obtained
|
||||
grep -v '^#' SOURCE-MANIFEST.txt > /tmp/files.sha256
|
||||
shasum -a 256 -c /tmp/files.sha256
|
||||
```
|
||||
|
||||
Any `FAILED` line means that file differs from the released source. Investigate before building.
|
||||
|
||||
The single value that covers the whole tree is the git tree hash in the manifest header:
|
||||
|
||||
```sh
|
||||
git rev-parse HEAD^{tree} # must equal the "tree:" line in the manifest
|
||||
```
|
||||
|
||||
The manifest itself carries a provenance attestation tying it to the workflow run that produced it, so a manifest handed to you along with a mirror is checkable too:
|
||||
|
||||
```sh
|
||||
gh attestation verify SOURCE-MANIFEST.txt --repo permissionlesstech/bitchat
|
||||
```
|
||||
|
||||
That last step is what makes this resistant to a hostile mirror. Without it, whoever gives you the source can give you a matching manifest.
|
||||
|
||||
### If the manifest is unavailable
|
||||
|
||||
Compare against a commit instead. Git object hashes cover content and history, so if you can obtain the expected commit hash through any channel you trust — a second mirror, a maintainer's post elsewhere, someone who cloned earlier — then:
|
||||
|
||||
```sh
|
||||
git fetch <mirror> --tags
|
||||
git rev-parse v1.2.3 # compare against the hash you trust
|
||||
git verify-tag v1.2.3 # if the tag is signed
|
||||
```
|
||||
|
||||
A mirror whose history matches a commit hash you trust from elsewhere is a faithful mirror.
|
||||
|
||||
## Builds from other sources
|
||||
|
||||
If you have an `.ipa`, an `.apk`, or a Mac app from a forum, a chat group, a file locker, or any mirror, you cannot verify it, and this project cannot help you verify it. There is no published signing key for compiled builds and no reproducible-build pipeline, so there is nothing to compare a binary against.
|
||||
|
||||
What to do instead, in order of preference: install from the App Store; build from verified source; or, if neither is possible, treat that build as untrusted — assume anything you type into it may be disclosed, do not use it for anything sensitive, and do not carry it somewhere it being on your phone is itself a risk.
|
||||
|
||||
Do not rely on the app looking right. A modified build has no reason to look different.
|
||||
|
||||
## For maintainers
|
||||
|
||||
Cutting a release:
|
||||
|
||||
- Push the tag. `source-manifest.yml` runs and attaches `SOURCE-MANIFEST.txt` to the release; if the release does not exist yet, collect the manifest from the workflow artifact and attach it when you publish.
|
||||
- Sign the tag (`git tag -s`). A signed tag lets anyone verify the release came from a key you control, independent of GitHub. This needs a published key fingerprint to be useful — see the gap below.
|
||||
- Note the commit hash somewhere outside this repository. If the repository is taken down, a hash recorded elsewhere is what lets people verify a mirror.
|
||||
|
||||
Known gaps, so nobody assumes more protection than exists:
|
||||
|
||||
- **No published signing key.** Tags are not currently verifiable against a known key. Publishing a fingerprint through channels independent of GitHub, and signing tags with it from then on, is the missing piece.
|
||||
- **No verifiable compiled builds outside the App Store.** Closing this needs either a signed-and-notarized release pipeline or a reproducible build, and until one exists the guidance above stands.
|
||||
- **No non-GitHub source mirror.** Every remote for this project is on the platform the takedown demands were served to. A mirror on independent infrastructure, published before it is needed, would mean a takedown does not remove the ability to verify.
|
||||
@@ -60,6 +60,9 @@ Public archives contain content already intended for public mesh/board distribut
|
||||
- When mesh bridge is enabled, public mesh messages not marked “nearby only” are signed under a per-cell Nostr identity and published to a neighborhood rendezvous geohash. Presence and public bridge traffic therefore expose a coarse area to relays and participants.
|
||||
- A bridge gateway can carry signed bridge/location events and opaque courier drops for nearby mesh-only peers. It cannot validly publish a neighbor's radio-only message because the author must first sign the bridge event.
|
||||
|
||||
- Relays added by hand persist in local preferences (`nostr.customRelays`, at most 8, normalized on read) and are wiped on panic. An added relay names an operator someone chose to route through, so it is treated as sensitive local state rather than inert configuration. `.onion` addresses are accepted, which is the point: the four built-in relays are well-known clearnet hostnames and a filter blocking four names would otherwise end internet-delivered private messages until a new build shipped.
|
||||
- Turning the Tor preference off routes relay sockets and the relay-directory fetch directly, disclosing the device IP to every relay operator including those carrying private messages. The settings UI states this while the preference is off.
|
||||
|
||||
Residual risk: Nostr relay retention and logging are outside project control. Public events may be copied indefinitely. Timing, coarse location, and participation can be correlated even when content is encrypted or per-cell identities are used.
|
||||
|
||||
## Location
|
||||
@@ -88,7 +91,7 @@ Residual risk: Nostr relay retention and logging are outside project control. Pu
|
||||
|
||||
## Panic Wipe Coverage
|
||||
|
||||
The panic action clears identity/session state, preferences, location state, groups, prekeys, outbox mail, courier mail, bridge dedup state, gossip archive, board data, managed media, and active subscriptions/transports. Managed media deletion completes synchronously, after active media work has been invalidated. Keychain secrets use device-only accessibility, and an install marker detects and clears app keys that survive uninstall before a later reinstall can use them. New persistent stores must add an explicit wipe hook and a regression test.
|
||||
The panic action clears identity/session state, preferences, location state, groups, prekeys, outbox mail, courier mail, bridge dedup state, gossip archive, board data, managed media, hand-added relays, and active subscriptions/transports. Managed media deletion completes synchronously, after active media work has been invalidated. Keychain secrets use device-only accessibility, and an install marker detects and clears app keys that survive uninstall before a later reinstall can use them. New persistent stores must add an explicit wipe hook and a regression test.
|
||||
|
||||
## Release Review Checklist
|
||||
|
||||
|
||||
@@ -48,6 +48,15 @@ public final class TorManager: ObservableObject {
|
||||
@Published private(set) var lastError: Error?
|
||||
@Published private(set) var bootstrapProgress: Int = 0
|
||||
@Published private(set) var bootstrapSummary: String = ""
|
||||
/// True once a bootstrap attempt has spent its whole deadline without
|
||||
/// completing.
|
||||
///
|
||||
/// This separates "still starting" from "not getting through", which are
|
||||
/// indistinguishable from `isStarting` alone. The second is what a network
|
||||
/// that blocks Tor looks like from inside the app, and without it the UI
|
||||
/// says "starting tor…" indefinitely while nothing is happening. Cleared on
|
||||
/// each new start attempt.
|
||||
@Published private(set) public var bootstrapDidStall: Bool = false
|
||||
|
||||
// Internal readiness trackers
|
||||
private var socksReady: Bool = false { didSet { recomputeReady() } }
|
||||
@@ -96,6 +105,7 @@ public final class TorManager: ObservableObject {
|
||||
guard !didStart else { return }
|
||||
didStart = true
|
||||
isStarting = true
|
||||
bootstrapDidStall = false
|
||||
startedAt = Date() // Track startup time for grace period
|
||||
SecureLogger.debug("TorManager: startIfNeeded() - startedAt set", category: .session)
|
||||
lastError = nil
|
||||
@@ -265,6 +275,7 @@ public final class TorManager: ObservableObject {
|
||||
|
||||
private func bootstrapPollLoop() async {
|
||||
let deadline = Date().addingTimeInterval(75)
|
||||
var didComplete = false
|
||||
while Date() < deadline {
|
||||
let progress = Int(arti_bootstrap_progress())
|
||||
let summary = getBootstrapSummary()
|
||||
@@ -276,9 +287,27 @@ public final class TorManager: ObservableObject {
|
||||
self.recomputeReady()
|
||||
}
|
||||
|
||||
if progress >= 100 { break }
|
||||
if progress >= 100 {
|
||||
didComplete = true
|
||||
break
|
||||
}
|
||||
try? await Task.sleep(nanoseconds: 1_000_000_000)
|
||||
}
|
||||
|
||||
// Running out the deadline is a reportable outcome, not silence. The
|
||||
// loop previously just ended, leaving `isStarting` true forever, so a
|
||||
// blocked network was indistinguishable from a slow one.
|
||||
if !didComplete {
|
||||
await MainActor.run {
|
||||
self.isStarting = false
|
||||
self.bootstrapDidStall = true
|
||||
SecureLogger.warning(
|
||||
"TorManager: bootstrap did not complete within its deadline (progress=\(self.bootstrapProgress)); network may be blocking Tor",
|
||||
category: .session
|
||||
)
|
||||
NotificationCenter.default.post(name: .TorBootstrapDidStall, object: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func getBootstrapSummary() -> String {
|
||||
@@ -374,6 +403,7 @@ public final class TorManager: ObservableObject {
|
||||
self.bootstrapProgress = 0
|
||||
self.bootstrapSummary = ""
|
||||
self.isStarting = true
|
||||
self.bootstrapDidStall = false
|
||||
self.lastRestartAt = Date()
|
||||
}
|
||||
|
||||
|
||||
@@ -5,4 +5,7 @@ public extension Notification.Name {
|
||||
static let TorWillRestart = Notification.Name("TorWillRestart")
|
||||
static let TorWillStart = Notification.Name("TorWillStart")
|
||||
static let TorUserPreferenceChanged = Notification.Name("TorUserPreferenceChanged")
|
||||
/// A bootstrap attempt ran out its deadline without completing — the
|
||||
/// signature of a network that blocks Tor.
|
||||
static let TorBootstrapDidStall = Notification.Name("TorBootstrapDidStall")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user